2 * Copyright (c) 2010-2023 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.homeassistant;
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.HashMap;
23 import java.util.List;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.ScheduledThreadPoolExecutor;
30 import java.util.concurrent.TimeUnit;
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.junit.jupiter.api.AfterEach;
35 import org.junit.jupiter.api.BeforeEach;
36 import org.junit.jupiter.api.Test;
37 import org.junit.jupiter.api.extension.ExtendWith;
38 import org.mockito.Mock;
39 import org.mockito.junit.jupiter.MockitoExtension;
40 import org.mockito.junit.jupiter.MockitoSettings;
41 import org.mockito.quality.Strictness;
42 import org.openhab.binding.mqtt.generic.AvailabilityTracker;
43 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
44 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
45 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
46 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents;
47 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents.ComponentDiscovered;
48 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
49 import org.openhab.binding.mqtt.homeassistant.internal.component.AbstractComponent;
50 import org.openhab.binding.mqtt.homeassistant.internal.component.Switch;
51 import org.openhab.binding.mqtt.homeassistant.internal.config.ChannelConfigurationTypeAdapterFactory;
52 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
53 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
54 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
55 import org.openhab.core.library.types.OnOffType;
56 import org.openhab.core.types.State;
57 import org.openhab.core.types.UnDefType;
58 import org.openhab.core.util.UIDUtils;
60 import com.google.gson.Gson;
61 import com.google.gson.GsonBuilder;
64 * A full implementation test, that starts the embedded MQTT broker and publishes a homeassistant MQTT discovery device
67 * @author David Graeff - Initial contribution
69 @ExtendWith(MockitoExtension.class)
70 @MockitoSettings(strictness = Strictness.LENIENT)
72 public class HomeAssistantMQTTImplementationTest extends MqttOSGiTest {
74 private @NonNullByDefault({}) MqttBrokerConnection haConnection;
75 private int registeredTopics = 100;
76 private @Nullable Throwable failure;
78 private @Mock @NonNullByDefault({}) ChannelStateUpdateListener channelStateUpdateListener;
79 private @Mock @NonNullByDefault({}) AvailabilityTracker availabilityTracker;
80 private @Mock @NonNullByDefault({}) TransformationServiceProvider transformationServiceProvider;
83 * Create an observer that fails the test as soon as the broker client connection changes its connection state
84 * to something else then CONNECTED.
86 private final MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
87 is(MqttConnectionState.CONNECTED));
88 private final String testObjectTopic = "homeassistant/switch/node/"
89 + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId();
93 public void beforeEach() throws Exception {
96 haConnection = createBrokerConnection("ha_mqtt");
98 // If the connection state changes in between -> fail
99 haConnection.addConnectionObserver(failIfChange);
101 // Create topic string and config for one example HA component (a Switch)
102 final String config = "{'name':'testname','state_topic':'" + testObjectTopic + "/state','command_topic':'"
103 + testObjectTopic + "/set'}";
105 // Publish component configurations and component states to MQTT
106 List<CompletableFuture<Boolean>> futures = new ArrayList<>();
107 futures.add(publish(testObjectTopic + "/config", config));
108 futures.add(publish(testObjectTopic + "/state", "ON"));
110 registeredTopics = futures.size();
111 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(2, TimeUnit.SECONDS);
115 doReturn(null).when(transformationServiceProvider).getTransformationService(any());
120 public void afterEach() throws Exception {
121 if (haConnection != null) {
122 haConnection.removeConnectionObserver(failIfChange);
123 haConnection.stop().get(5, TimeUnit.SECONDS);
130 public void reconnectTest() throws Exception {
131 haConnection.removeConnectionObserver(failIfChange);
132 haConnection.stop().get(5, TimeUnit.SECONDS);
133 haConnection = createBrokerConnection("ha_mqtt");
137 public void retrieveAllTopics() throws Exception {
138 CountDownLatch c = new CountDownLatch(registeredTopics);
139 haConnection.subscribe("homeassistant/+/+/" + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId() + "/#",
140 (topic, payload) -> c.countDown()).get(5, TimeUnit.SECONDS);
141 assertTrue(c.await(2, TimeUnit.SECONDS),
142 "Connection " + haConnection.getClientId() + " not retrieving all topics");
146 public void parseHATree() throws Exception {
147 MqttChannelTypeProvider channelTypeProvider = mock(MqttChannelTypeProvider.class);
149 final Map<String, AbstractComponent<?>> haComponents = new HashMap<>();
150 Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory()).create();
152 ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
153 DiscoverComponents discover = spy(new DiscoverComponents(ThingChannelConstants.TEST_HOME_ASSISTANT_THING,
154 scheduler, channelStateUpdateListener, availabilityTracker, gson, transformationServiceProvider));
156 // The DiscoverComponents object calls ComponentDiscovered callbacks.
157 // In the following implementation we add the found component to the `haComponents` map
158 // and add the types to the channelTypeProvider, like in the real Thing handler.
159 final CountDownLatch latch = new CountDownLatch(1);
160 ComponentDiscovered cd = (haID, c) -> {
161 haComponents.put(c.getGroupUID().getId(), c);
162 c.addChannelTypes(channelTypeProvider);
163 channelTypeProvider.setChannelGroupType(c.getGroupTypeUID(), c.getType());
167 // Start the discovery for 2000ms. Forced timeout after 4000ms.
168 HaID haID = new HaID(testObjectTopic + "/config");
169 CompletableFuture<Void> future = discover.startDiscovery(haConnection, 2000, Set.of(haID), cd).thenRun(() -> {
170 }).exceptionally(e -> {
175 assertTrue(latch.await(4, TimeUnit.SECONDS));
176 future.get(5, TimeUnit.SECONDS);
178 // No failure expected and one discovered result
180 assertThat(haComponents.size(), is(1));
182 // For the switch component we should have one channel group type and one channel type
183 // setChannelGroupType is called once above
184 verify(channelTypeProvider, times(2)).setChannelGroupType(any(), any());
185 verify(channelTypeProvider, times(1)).setChannelType(any(), any());
187 String channelGroupId = UIDUtils
188 .encode("node_" + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId() + "_switch");
190 State value = haComponents.get(channelGroupId).getChannel(Switch.SWITCH_CHANNEL_ID).getState().getCache()
192 assertThat(value, is(UnDefType.UNDEF));
194 haComponents.values().stream().map(e -> e.start(haConnection, scheduler, 100))
195 .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v)).exceptionally(e -> {
200 // We should have received the retained value, while subscribing to the channels MQTT state topic.
201 verify(channelStateUpdateListener, timeout(4000).times(1)).updateChannelState(any(), any());
203 // Value should be ON now.
204 value = haComponents.get(channelGroupId).getChannel(Switch.SWITCH_CHANNEL_ID).getState().getCache()
206 assertThat(value, is(OnOffType.ON));