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