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