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