]> git.basschouten.com Git - openhab-addons.git/blob
04a732c9296f2860aa5f69991da70feb25a9f2bd
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.mqtt.homeassistant;
14
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
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
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;
31
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.homeassistant.internal.DiscoverComponents;
46 import org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents.ComponentDiscovered;
47 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
48 import org.openhab.binding.mqtt.homeassistant.internal.component.AbstractComponent;
49 import org.openhab.binding.mqtt.homeassistant.internal.component.Switch;
50 import org.openhab.binding.mqtt.homeassistant.internal.config.ChannelConfigurationTypeAdapterFactory;
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.library.types.OnOffType;
55 import org.openhab.core.types.State;
56 import org.openhab.core.types.UnDefType;
57
58 import com.google.gson.Gson;
59 import com.google.gson.GsonBuilder;
60
61 /**
62  * A full implementation test, that starts the embedded MQTT broker and publishes a homeassistant MQTT discovery device
63  * tree.
64  *
65  * @author David Graeff - Initial contribution
66  */
67 @ExtendWith(MockitoExtension.class)
68 @MockitoSettings(strictness = Strictness.LENIENT)
69 @NonNullByDefault
70 public class HomeAssistantMQTTImplementationTest extends MqttOSGiTest {
71
72     private @NonNullByDefault({}) MqttBrokerConnection haConnection;
73     private int registeredTopics = 100;
74     private @Nullable Throwable failure;
75
76     private @Mock @NonNullByDefault({}) ChannelStateUpdateListener channelStateUpdateListener;
77     private @Mock @NonNullByDefault({}) AvailabilityTracker availabilityTracker;
78
79     /**
80      * Create an observer that fails the test as soon as the broker client connection changes its connection state
81      * to something else then CONNECTED.
82      */
83     private final MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
84             is(MqttConnectionState.CONNECTED));
85     private final String testObjectTopic = "homeassistant/switch/node/"
86             + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId();
87
88     @Override
89     @BeforeEach
90     public void beforeEach() throws Exception {
91         super.beforeEach();
92
93         haConnection = createBrokerConnection("ha_mqtt");
94
95         // If the connection state changes in between -> fail
96         haConnection.addConnectionObserver(failIfChange);
97
98         // Create topic string and config for one example HA component (a Switch)
99         final String config = "{'name':'testname','state_topic':'" + testObjectTopic + "/state','command_topic':'"
100                 + testObjectTopic + "/set'}";
101
102         // Publish component configurations and component states to MQTT
103         List<CompletableFuture<Boolean>> futures = new ArrayList<>();
104         futures.add(publish(testObjectTopic + "/config", config));
105         futures.add(publish(testObjectTopic + "/state", "ON"));
106
107         registeredTopics = futures.size();
108         CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(2, TimeUnit.SECONDS);
109
110         failure = null;
111     }
112
113     @Override
114     @AfterEach
115     public void afterEach() throws Exception {
116         if (haConnection != null) {
117             haConnection.removeConnectionObserver(failIfChange);
118             haConnection.stop().get(5, TimeUnit.SECONDS);
119         }
120
121         super.afterEach();
122     }
123
124     @Test
125     public void reconnectTest() throws Exception {
126         haConnection.removeConnectionObserver(failIfChange);
127         haConnection.stop().get(5, TimeUnit.SECONDS);
128         haConnection = createBrokerConnection("ha_mqtt");
129     }
130
131     @Test
132     public void retrieveAllTopics() throws Exception {
133         CountDownLatch c = new CountDownLatch(registeredTopics);
134         haConnection.subscribe("homeassistant/+/+/" + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId() + "/#",
135                 (topic, payload) -> c.countDown()).get(5, TimeUnit.SECONDS);
136         assertTrue(c.await(2, TimeUnit.SECONDS),
137                 "Connection " + haConnection.getClientId() + " not retrieving all topics");
138     }
139
140     @Test
141     public void parseHATree() throws Exception {
142         MqttChannelTypeProvider channelTypeProvider = mock(MqttChannelTypeProvider.class);
143
144         final Map<String, AbstractComponent<?>> haComponents = new HashMap<>();
145         Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ChannelConfigurationTypeAdapterFactory()).create();
146
147         ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
148         DiscoverComponents discover = spy(new DiscoverComponents(ThingChannelConstants.TEST_HOME_ASSISTANT_THING,
149                 scheduler, channelStateUpdateListener, availabilityTracker, gson, true));
150
151         // The DiscoverComponents object calls ComponentDiscovered callbacks.
152         // In the following implementation we add the found component to the `haComponents` map
153         // and add the types to the channelTypeProvider, like in the real Thing handler.
154         final CountDownLatch latch = new CountDownLatch(1);
155         ComponentDiscovered cd = (haID, c) -> {
156             haComponents.put(c.getGroupId(), c);
157             latch.countDown();
158         };
159
160         // Start the discovery for 2000ms. Forced timeout after 4000ms.
161         HaID haID = new HaID(testObjectTopic + "/config");
162         CompletableFuture<Void> future = discover.startDiscovery(haConnection, 2000, Set.of(haID), cd).thenRun(() -> {
163         }).exceptionally(e -> {
164             failure = e;
165             return null;
166         });
167
168         assertTrue(latch.await(4, TimeUnit.SECONDS));
169         future.get(5, TimeUnit.SECONDS);
170
171         // No failure expected and one discovered result
172         assertNull(failure);
173         assertThat(haComponents.size(), is(1));
174
175         String channelGroupId = "switch_" + ThingChannelConstants.TEST_HOME_ASSISTANT_THING.getId();
176         String channelId = Switch.SWITCH_CHANNEL_ID;
177
178         State value = haComponents.get(channelGroupId).getChannel(channelGroupId).getState().getCache()
179                 .getChannelState();
180         assertThat(value, is(UnDefType.UNDEF));
181
182         haComponents.values().stream().map(e -> e.start(haConnection, scheduler, 100))
183                 .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v)).exceptionally(e -> {
184                     failure = e;
185                     return null;
186                 }).get();
187
188         // We should have received the retained value, while subscribing to the channels MQTT state topic.
189         verify(channelStateUpdateListener, timeout(4000).times(1)).updateChannelState(any(), any());
190
191         // Value should be ON now.
192         value = haComponents.get(channelGroupId).getChannel(channelGroupId).getState().getCache().getChannelState();
193         assertThat(value, is(OnOffType.ON));
194     }
195 }