2 * Copyright (c) 2010-2021 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.*;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledThreadPoolExecutor;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.TimeoutException;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.junit.jupiter.api.AfterEach;
37 import org.junit.jupiter.api.BeforeEach;
38 import org.junit.jupiter.api.Test;
39 import org.junit.jupiter.api.extension.ExtendWith;
40 import org.mockito.Mock;
41 import org.mockito.junit.jupiter.MockitoExtension;
42 import org.mockito.junit.jupiter.MockitoSettings;
43 import org.mockito.quality.Strictness;
44 import org.openhab.binding.mqtt.generic.AvailabilityTracker;
45 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
46 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
47 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
48 import org.openhab.binding.mqtt.homeassistant.internal.AbstractComponent;
49 import org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory;
50 import org.openhab.binding.mqtt.homeassistant.internal.ComponentSwitch;
51 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents;
52 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents.ComponentDiscovered;
53 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
54 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
55 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
56 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
57 import org.openhab.core.io.transport.mqtt.MqttService;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.test.java.JavaOSGiTest;
60 import org.openhab.core.types.State;
61 import org.openhab.core.types.UnDefType;
62 import org.openhab.core.util.UIDUtils;
63 import org.osgi.service.cm.ConfigurationAdmin;
65 import com.google.gson.Gson;
66 import com.google.gson.GsonBuilder;
69 * A full implementation test, that starts the embedded MQTT broker and publishes a homeassistant MQTT discovery device
72 * @author David Graeff - Initial contribution
74 @ExtendWith(MockitoExtension.class)
75 @MockitoSettings(strictness = Strictness.WARN)
77 public class HomeAssistantMQTTImplementationTest extends JavaOSGiTest {
78 private @NonNullByDefault({}) ConfigurationAdmin configurationAdmin;
79 private @NonNullByDefault({}) MqttService mqttService;
80 private @NonNullByDefault({}) MqttBrokerConnection embeddedConnection;
81 private @NonNullByDefault({}) MqttBrokerConnection connection;
82 private int registeredTopics = 100;
83 private @Nullable Throwable failure;
85 private @Mock @NonNullByDefault({}) ChannelStateUpdateListener channelStateUpdateListener;
86 private @Mock @NonNullByDefault({}) AvailabilityTracker availabilityTracker;
87 private @Mock @NonNullByDefault({}) TransformationServiceProvider transformationServiceProvider;
90 * Create an observer that fails the test as soon as the broker client connection changes its connection state
91 * to something else then CONNECTED.
93 private final MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
94 is(MqttConnectionState.CONNECTED));
95 private final String testObjectTopic = "homeassistant/switch/node/"
96 + ThingChannelConstants.testHomeAssistantThing.getId();
99 public void beforeEach() throws Exception {
100 registerVolatileStorageService();
101 configurationAdmin = getService(ConfigurationAdmin.class);
102 mqttService = getService(MqttService.class);
104 // Wait for the EmbeddedBrokerService internal connection to be connected
105 embeddedConnection = new EmbeddedBrokerTools(configurationAdmin, mqttService).waitForConnection();
107 connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(),
108 embeddedConnection.isSecure(), "ha_mqtt");
109 connection.start().get(2, TimeUnit.SECONDS);
110 assertThat(connection.connectionState(), is(MqttConnectionState.CONNECTED));
112 // If the connection state changes in between -> fail
113 connection.addConnectionObserver(failIfChange);
115 // Create topic string and config for one example HA component (a Switch)
116 final String config = "{'name':'testname','state_topic':'" + testObjectTopic + "/state','command_topic':'"
117 + testObjectTopic + "/set'}";
119 // Publish component configurations and component states to MQTT
120 List<CompletableFuture<Boolean>> futures = new ArrayList<>();
121 futures.add(embeddedConnection.publish(testObjectTopic + "/config", config.getBytes(), 0, true));
122 futures.add(embeddedConnection.publish(testObjectTopic + "/state", "ON".getBytes(), 0, true));
124 registeredTopics = futures.size();
125 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(2, TimeUnit.SECONDS);
129 doReturn(null).when(transformationServiceProvider).getTransformationService(any());
133 public void afterEach() throws Exception {
134 if (connection != null) {
135 connection.removeConnectionObserver(failIfChange);
136 connection.stop().get(2, TimeUnit.SECONDS);
141 public void reconnectTest() throws InterruptedException, ExecutionException, TimeoutException {
142 connection.removeConnectionObserver(failIfChange);
143 connection.stop().get(2, TimeUnit.SECONDS);
144 connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(),
145 embeddedConnection.isSecure(), "ha_mqtt");
146 connection.start().get(2, TimeUnit.SECONDS);
150 public void retrieveAllTopics() throws InterruptedException, ExecutionException, TimeoutException {
151 CountDownLatch c = new CountDownLatch(registeredTopics);
152 connection.subscribe("homeassistant/+/+/" + ThingChannelConstants.testHomeAssistantThing.getId() + "/#",
153 (topic, payload) -> c.countDown()).get(2, TimeUnit.SECONDS);
154 assertTrue(c.await(2, TimeUnit.SECONDS),
155 "Connection " + connection.getClientId() + " not retrieving all topics");
159 public void parseHATree() throws InterruptedException, ExecutionException, TimeoutException {
160 MqttChannelTypeProvider channelTypeProvider = mock(MqttChannelTypeProvider.class);
162 final Map<String, AbstractComponent<?>> haComponents = new HashMap<>();
163 Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory()).create();
165 ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
166 DiscoverComponents discover = spy(new DiscoverComponents(ThingChannelConstants.testHomeAssistantThing,
167 scheduler, channelStateUpdateListener, availabilityTracker, gson, transformationServiceProvider));
169 // The DiscoverComponents object calls ComponentDiscovered callbacks.
170 // In the following implementation we add the found component to the `haComponents` map
171 // and add the types to the channelTypeProvider, like in the real Thing handler.
172 final CountDownLatch latch = new CountDownLatch(1);
173 ComponentDiscovered cd = (haID, c) -> {
174 haComponents.put(c.uid().getId(), c);
175 c.addChannelTypes(channelTypeProvider);
176 channelTypeProvider.setChannelGroupType(c.groupTypeUID(), c.type());
180 // Start the discovery for 2000ms. Forced timeout after 4000ms.
181 HaID haID = new HaID(testObjectTopic + "/config");
182 CompletableFuture<Void> future = discover.startDiscovery(connection, 2000, Collections.singleton(haID), cd)
184 }).exceptionally(e -> {
189 assertTrue(latch.await(4, TimeUnit.SECONDS));
190 future.get(2, TimeUnit.SECONDS);
192 // No failure expected and one discovered result
194 assertThat(haComponents.size(), is(1));
196 // For the switch component we should have one channel group type and one channel type
197 // setChannelGroupType is called once above
198 verify(channelTypeProvider, times(2)).setChannelGroupType(any(), any());
199 verify(channelTypeProvider, times(1)).setChannelType(any(), any());
201 String channelGroupId = UIDUtils
202 .encode("node_" + ThingChannelConstants.testHomeAssistantThing.getId() + "_switch");
204 State value = haComponents.get(channelGroupId).channelTypes().get(ComponentSwitch.switchChannelID).getState()
205 .getCache().getChannelState();
206 assertThat(value, is(UnDefType.UNDEF));
208 haComponents.values().stream().map(e -> e.start(connection, scheduler, 100))
209 .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v)).exceptionally(e -> {
214 // We should have received the retained value, while subscribing to the channels MQTT state topic.
215 verify(channelStateUpdateListener, timeout(4000).times(1)).updateChannelState(any(), any());
217 // Value should be ON now.
218 value = haComponents.get(channelGroupId).channelTypes().get(ComponentSwitch.switchChannelID).getState()
219 .getCache().getChannelState();
220 assertThat(value, is(OnOffType.ON));