2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mqtt;
15 import static org.hamcrest.CoreMatchers.is;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.junit.jupiter.api.Assertions.*;
18 import static org.mockito.ArgumentMatchers.any;
19 import static org.mockito.Mockito.*;
20 import static org.mockito.MockitoAnnotations.openMocks;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.ScheduledThreadPoolExecutor;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.TimeoutException;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.junit.jupiter.api.AfterEach;
38 import org.junit.jupiter.api.BeforeEach;
39 import org.junit.jupiter.api.Test;
40 import org.mockito.Mock;
41 import org.openhab.binding.mqtt.generic.AvailabilityTracker;
42 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
43 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
44 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
45 import org.openhab.binding.mqtt.homeassistant.internal.AbstractComponent;
46 import org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory;
47 import org.openhab.binding.mqtt.homeassistant.internal.ComponentSwitch;
48 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents;
49 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents.ComponentDiscovered;
50 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
51 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
52 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
53 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
54 import org.openhab.core.io.transport.mqtt.MqttService;
55 import org.openhab.core.library.types.OnOffType;
56 import org.openhab.core.test.java.JavaOSGiTest;
57 import org.openhab.core.types.State;
58 import org.openhab.core.types.UnDefType;
59 import org.openhab.core.util.UIDUtils;
61 import com.google.gson.Gson;
62 import com.google.gson.GsonBuilder;
65 * A full implementation test, that starts the embedded MQTT broker and publishes a homeassistant MQTT discovery device
68 * @author David Graeff - Initial contribution
71 public class HomeAssistantMQTTImplementationTest extends JavaOSGiTest {
72 private @NonNullByDefault({}) MqttService mqttService;
73 private @NonNullByDefault({}) MqttBrokerConnection embeddedConnection;
74 private @NonNullByDefault({}) MqttBrokerConnection connection;
75 private int registeredTopics = 100;
76 private @Nullable Throwable failure;
78 private @NonNullByDefault({}) AutoCloseable mocksCloseable;
80 private @Mock @NonNullByDefault({}) ChannelStateUpdateListener channelStateUpdateListener;
81 private @Mock @NonNullByDefault({}) AvailabilityTracker availabilityTracker;
82 private @Mock @NonNullByDefault({}) TransformationServiceProvider transformationServiceProvider;
85 * Create an observer that fails the test as soon as the broker client connection changes its connection state
86 * to something else then CONNECTED.
88 private final MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
89 is(MqttConnectionState.CONNECTED));
90 private final String testObjectTopic = "homeassistant/switch/node/"
91 + ThingChannelConstants.testHomeAssistantThing.getId();
94 public void beforeEach() throws Exception {
95 registerVolatileStorageService();
96 mocksCloseable = openMocks(this);
97 mqttService = getService(MqttService.class);
99 // Wait for the EmbeddedBrokerService internal connection to be connected
100 embeddedConnection = new EmbeddedBrokerTools().waitForConnection(mqttService);
102 connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(),
103 embeddedConnection.isSecure(), "ha_mqtt");
104 connection.start().get(1000, TimeUnit.MILLISECONDS);
105 assertThat(connection.connectionState(), is(MqttConnectionState.CONNECTED));
107 // If the connection state changes in between -> fail
108 connection.addConnectionObserver(failIfChange);
110 // Create topic string and config for one example HA component (a Switch)
111 final String config = "{'name':'testname','state_topic':'" + testObjectTopic + "/state','command_topic':'"
112 + testObjectTopic + "/set'}";
114 // Publish component configurations and component states to MQTT
115 List<CompletableFuture<Boolean>> futures = new ArrayList<>();
116 futures.add(embeddedConnection.publish(testObjectTopic + "/config", config.getBytes(), 0, true));
117 futures.add(embeddedConnection.publish(testObjectTopic + "/state", "ON".getBytes(), 0, true));
119 registeredTopics = futures.size();
120 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(1000, TimeUnit.MILLISECONDS);
124 doReturn(null).when(transformationServiceProvider).getTransformationService(any());
128 public void afterEach() throws Exception {
129 if (connection != null) {
130 connection.removeConnectionObserver(failIfChange);
131 connection.stop().get(1000, TimeUnit.MILLISECONDS);
134 mocksCloseable.close();
138 public void reconnectTest() throws InterruptedException, ExecutionException, TimeoutException {
139 connection.removeConnectionObserver(failIfChange);
140 connection.stop().get(2000, TimeUnit.MILLISECONDS);
141 connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(),
142 embeddedConnection.isSecure(), "ha_mqtt");
143 connection.start().get(2000, TimeUnit.MILLISECONDS);
147 public void retrieveAllTopics() throws InterruptedException, ExecutionException, TimeoutException {
148 CountDownLatch c = new CountDownLatch(registeredTopics);
149 connection.subscribe("homeassistant/+/+/" + ThingChannelConstants.testHomeAssistantThing.getId() + "/#",
150 (topic, payload) -> c.countDown()).get(1000, TimeUnit.MILLISECONDS);
151 assertTrue(c.await(1000, TimeUnit.MILLISECONDS),
152 "Connection " + connection.getClientId() + " not retrieving all topics");
156 public void parseHATree() throws InterruptedException, ExecutionException, TimeoutException {
157 MqttChannelTypeProvider channelTypeProvider = mock(MqttChannelTypeProvider.class);
159 final Map<String, AbstractComponent<?>> haComponents = new HashMap<>();
160 Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory()).create();
162 ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
163 DiscoverComponents discover = spy(new DiscoverComponents(ThingChannelConstants.testHomeAssistantThing,
164 scheduler, channelStateUpdateListener, availabilityTracker, gson, transformationServiceProvider));
166 // The DiscoverComponents object calls ComponentDiscovered callbacks.
167 // In the following implementation we add the found component to the `haComponents` map
168 // and add the types to the channelTypeProvider, like in the real Thing handler.
169 final CountDownLatch latch = new CountDownLatch(1);
170 ComponentDiscovered cd = (haID, c) -> {
171 haComponents.put(c.uid().getId(), c);
172 c.addChannelTypes(channelTypeProvider);
173 channelTypeProvider.setChannelGroupType(c.groupTypeUID(), c.type());
177 // Start the discovery for 2000ms. Forced timeout after 4000ms.
178 HaID haID = new HaID(testObjectTopic + "/config");
179 CompletableFuture<Void> future = discover.startDiscovery(connection, 2000, Collections.singleton(haID), cd)
181 }).exceptionally(e -> {
186 assertTrue(latch.await(4000, TimeUnit.MILLISECONDS));
187 future.get(2000, TimeUnit.MILLISECONDS);
189 // No failure expected and one discovered result
191 assertThat(haComponents.size(), is(1));
193 // For the switch component we should have one channel group type and one channel type
194 // setChannelGroupType is called once above
195 verify(channelTypeProvider, times(2)).setChannelGroupType(any(), any());
196 verify(channelTypeProvider, times(1)).setChannelType(any(), any());
198 String channelGroupId = UIDUtils
199 .encode("node_" + ThingChannelConstants.testHomeAssistantThing.getId() + "_switch");
201 State value = haComponents.get(channelGroupId).channelTypes().get(ComponentSwitch.switchChannelID).getState()
202 .getCache().getChannelState();
203 assertThat(value, is(UnDefType.UNDEF));
205 haComponents.values().stream().map(e -> e.start(connection, scheduler, 100))
206 .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v)).exceptionally(e -> {
211 // We should have received the retained value, while subscribing to the channels MQTT state topic.
212 verify(channelStateUpdateListener, timeout(4000).times(1)).updateChannelState(any(), any());
214 // Value should be ON now.
215 value = haComponents.get(channelGroupId).channelTypes().get(ComponentSwitch.switchChannelID).getState()
216 .getCache().getChannelState();
217 assertThat(value, is(OnOffType.ON));