]> git.basschouten.com Git - openhab-addons.git/blob
776f8fb91f852a94ee4abd9e4ee394323228ad66
[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.*;
19 import static org.mockito.Mockito.*;
20 import static org.mockito.MockitoAnnotations.openMocks;
21
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledThreadPoolExecutor;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.TimeoutException;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.junit.jupiter.api.AfterEach;
36 import org.junit.jupiter.api.BeforeEach;
37 import org.junit.jupiter.api.Test;
38 import org.mockito.Mock;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.openhab.binding.mqtt.generic.ChannelState;
41 import org.openhab.binding.mqtt.generic.tools.ChildMap;
42 import org.openhab.binding.mqtt.generic.tools.WaitForTopicValue;
43 import org.openhab.binding.mqtt.homie.internal.handler.HomieThingHandler;
44 import org.openhab.binding.mqtt.homie.internal.homie300.Device;
45 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes;
46 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes.ReadyState;
47 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceCallback;
48 import org.openhab.binding.mqtt.homie.internal.homie300.Node;
49 import org.openhab.binding.mqtt.homie.internal.homie300.NodeAttributes;
50 import org.openhab.binding.mqtt.homie.internal.homie300.Property;
51 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes;
52 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes.DataTypeEnum;
53 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyHelper;
54 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
55 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
56 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
57 import org.openhab.core.io.transport.mqtt.MqttService;
58 import org.openhab.core.library.types.DecimalType;
59 import org.openhab.core.library.types.OnOffType;
60 import org.openhab.core.test.java.JavaOSGiTest;
61 import org.openhab.core.types.UnDefType;
62
63 /**
64  * A full implementation test, that starts the embedded MQTT broker and publishes a homie device tree.
65  *
66  * @author David Graeff - Initial contribution
67  */
68 @NonNullByDefault
69 public class HomieImplementationTest extends JavaOSGiTest {
70     private static final String BASE_TOPIC = "homie";
71     private static final String DEVICE_ID = ThingChannelConstants.testHomieThing.getId();
72     private static final String DEVICE_TOPIC = BASE_TOPIC + "/" + DEVICE_ID;
73
74     private @NonNullByDefault({}) MqttService mqttService;
75     private @NonNullByDefault({}) MqttBrokerConnection embeddedConnection;
76     private @NonNullByDefault({}) MqttBrokerConnection connection;
77     private int registeredTopics = 100;
78
79     private @NonNullByDefault({}) AutoCloseable mocksCloseable;
80
81     // The handler is not tested here, so just mock the callback
82     private @Mock @NonNullByDefault({}) DeviceCallback callback;
83
84     // A handler mock is required to verify that channel value changes have been received
85     private @Mock @NonNullByDefault({}) HomieThingHandler handler;
86
87     private @NonNullByDefault({}) ScheduledExecutorService scheduler;
88
89     /**
90      * Create an observer that fails the test as soon as the broker client connection changes its connection state
91      * to something else then CONNECTED.
92      */
93     private MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
94             is(MqttConnectionState.CONNECTED));
95
96     private String propertyTestTopic = "";
97
98     @BeforeEach
99     public void beforeEach() throws Exception {
100         registerVolatileStorageService();
101         mocksCloseable = openMocks(this);
102         mqttService = getService(MqttService.class);
103
104         embeddedConnection = new EmbeddedBrokerTools().waitForConnection(mqttService);
105         embeddedConnection.setQos(1);
106
107         connection = new MqttBrokerConnection(embeddedConnection.getHost(), embeddedConnection.getPort(),
108                 embeddedConnection.isSecure(), "homie");
109         connection.setQos(1);
110         connection.start().get(500, TimeUnit.MILLISECONDS);
111         assertThat(connection.connectionState(), is(MqttConnectionState.CONNECTED));
112         // If the connection state changes in between -> fail
113         connection.addConnectionObserver(failIfChange);
114
115         List<CompletableFuture<Boolean>> futures = new ArrayList<>();
116         futures.add(publish(DEVICE_TOPIC + "/$homie", "3.0"));
117         futures.add(publish(DEVICE_TOPIC + "/$name", "Name"));
118         futures.add(publish(DEVICE_TOPIC + "/$state", "ready"));
119         futures.add(publish(DEVICE_TOPIC + "/$nodes", "testnode"));
120
121         // Add homie node topics
122         final String testNode = DEVICE_TOPIC + "/testnode";
123         futures.add(publish(testNode + "/$name", "Testnode"));
124         futures.add(publish(testNode + "/$type", "Type"));
125         futures.add(publish(testNode + "/$properties", "temperature,doorbell,testRetain"));
126
127         // Add homie property topics
128         final String property = testNode + "/temperature";
129         futures.add(publish(property, "10"));
130         futures.add(publish(property + "/$name", "Testprop"));
131         futures.add(publish(property + "/$settable", "true"));
132         futures.add(publish(property + "/$unit", "°C"));
133         futures.add(publish(property + "/$datatype", "float"));
134         futures.add(publish(property + "/$format", "-100:100"));
135
136         final String propertyBellTopic = testNode + "/doorbell";
137         futures.add(publish(propertyBellTopic + "/$name", "Doorbell"));
138         futures.add(publish(propertyBellTopic + "/$settable", "false"));
139         futures.add(publish(propertyBellTopic + "/$retained", "false"));
140         futures.add(publish(propertyBellTopic + "/$datatype", "boolean"));
141
142         this.propertyTestTopic = testNode + "/testRetain";
143         futures.add(publish(propertyTestTopic + "/$name", "Test"));
144         futures.add(publish(propertyTestTopic + "/$settable", "true"));
145         futures.add(publish(propertyTestTopic + "/$retained", "false"));
146         futures.add(publish(propertyTestTopic + "/$datatype", "boolean"));
147
148         registeredTopics = futures.size();
149         CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(1000, TimeUnit.MILLISECONDS);
150
151         scheduler = new ScheduledThreadPoolExecutor(6);
152     }
153
154     private CompletableFuture<Boolean> publish(String topic, String message) {
155         return embeddedConnection.publish(topic, message.getBytes(StandardCharsets.UTF_8), 0, true);
156     }
157
158     @AfterEach
159     public void afterEach() throws Exception {
160         if (connection != null) {
161             connection.removeConnectionObserver(failIfChange);
162             connection.stop().get(500, TimeUnit.MILLISECONDS);
163         }
164         scheduler.shutdownNow();
165         mocksCloseable.close();
166     }
167
168     @Test
169     public void retrieveAllTopics() throws InterruptedException, ExecutionException, TimeoutException {
170         // four topics are not under /testnode !
171         CountDownLatch c = new CountDownLatch(registeredTopics - 4);
172         connection.subscribe(DEVICE_TOPIC + "/testnode/#", (topic, payload) -> c.countDown()).get(5000,
173                 TimeUnit.MILLISECONDS);
174         assertTrue(c.await(5000, TimeUnit.MILLISECONDS),
175                 "Connection " + connection.getClientId() + " not retrieving all topics ");
176     }
177
178     @Test
179     public void retrieveOneAttribute() throws InterruptedException, ExecutionException {
180         WaitForTopicValue watcher = new WaitForTopicValue(connection, DEVICE_TOPIC + "/$homie");
181         assertThat(watcher.waitForTopicValue(1000), is("3.0"));
182     }
183
184     @SuppressWarnings("null")
185     @Test
186     public void retrieveAttributes() throws InterruptedException, ExecutionException {
187         assertThat(connection.hasSubscribers(), is(false));
188
189         Node node = new Node(DEVICE_TOPIC, "testnode", ThingChannelConstants.testHomieThing, callback,
190                 new NodeAttributes());
191         Property property = spy(
192                 new Property(DEVICE_TOPIC + "/testnode", node, "temperature", callback, new PropertyAttributes()));
193
194         // Create a scheduler
195         ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
196
197         property.subscribe(connection, scheduler, 500).get();
198
199         assertThat(property.attributes.settable, is(true));
200         assertThat(property.attributes.retained, is(true));
201         assertThat(property.attributes.name, is("Testprop"));
202         assertThat(property.attributes.unit, is("°C"));
203         assertThat(property.attributes.datatype, is(DataTypeEnum.float_));
204         waitForAssert(() -> assertThat(property.attributes.format, is("-100:100")));
205         verify(property, timeout(500).atLeastOnce()).attributesReceived();
206
207         // Receive property value
208         ChannelState channelState = spy(property.getChannelState());
209         PropertyHelper.setChannelState(property, channelState);
210
211         property.startChannel(connection, scheduler, 500).get();
212         verify(channelState).start(any(), any(), anyInt());
213         verify(channelState, timeout(500)).processMessage(any(), any());
214         verify(callback).updateChannelState(any(), any());
215
216         assertThat(property.getChannelState().getCache().getChannelState(), is(new DecimalType(10)));
217
218         property.stop().get();
219         assertThat(connection.hasSubscribers(), is(false));
220     }
221
222     // Inject a spy'ed property
223     public Property createSpyProperty(InvocationOnMock invocation) {
224         final Node node = (Node) invocation.getMock();
225         final String id = (String) invocation.getArguments()[0];
226         return spy(node.createProperty(id, spy(new PropertyAttributes())));
227     }
228
229     // Inject a spy'ed node
230     public Node createSpyNode(InvocationOnMock invocation) {
231         final Device device = (Device) invocation.getMock();
232         final String id = (String) invocation.getArguments()[0];
233         // Create the node
234         Node node = spy(device.createNode(id, spy(new NodeAttributes())));
235         // Intercept creating a property in the next call and inject a spy'ed property.
236         doAnswer(this::createSpyProperty).when(node).createProperty(any());
237         return node;
238     }
239
240     @SuppressWarnings("null")
241     @Test
242     public void parseHomieTree() throws InterruptedException, ExecutionException, TimeoutException {
243         // Create a Homie Device object. Because spied Nodes are required for call verification,
244         // the full Device constructor need to be used and a ChildMap object need to be created manually.
245         ChildMap<Node> nodeMap = new ChildMap<>();
246         Device device = spy(
247                 new Device(ThingChannelConstants.testHomieThing, callback, new DeviceAttributes(), nodeMap));
248
249         // Intercept creating a node in initialize()->start() and inject a spy'ed node.
250         doAnswer(this::createSpyNode).when(device).createNode(any());
251
252         // initialize the device, subscribe and wait.
253         device.initialize(BASE_TOPIC, DEVICE_ID, Collections.emptyList());
254         device.subscribe(connection, scheduler, 1500).get();
255
256         assertThat(device.isInitialized(), is(true));
257
258         // Check device attributes
259         assertThat(device.attributes.homie, is("3.0"));
260         assertThat(device.attributes.name, is("Name"));
261         assertThat(device.attributes.state, is(ReadyState.ready));
262         assertThat(device.attributes.nodes.length, is(1));
263         verify(device, times(4)).attributeChanged(any(), any(), any(), any(), anyBoolean());
264         verify(callback).readyStateChanged(eq(ReadyState.ready));
265         verify(device).attributesReceived(any(), any(), anyInt());
266
267         // Expect 1 node
268         assertThat(device.nodes.size(), is(1));
269
270         // Check node and node attributes
271         Node node = device.nodes.get("testnode");
272         verify(node).subscribe(any(), any(), anyInt());
273         verify(node).attributesReceived(any(), any(), anyInt());
274         verify(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
275         assertThat(node.attributes.type, is("Type"));
276         assertThat(node.attributes.name, is("Testnode"));
277
278         // Expect 2 property
279         assertThat(node.properties.size(), is(3));
280
281         // Check property and property attributes
282         Property property = node.properties.get("temperature");
283         assertThat(property.attributes.settable, is(true));
284         assertThat(property.attributes.retained, is(true));
285         assertThat(property.attributes.name, is("Testprop"));
286         assertThat(property.attributes.unit, is("°C"));
287         assertThat(property.attributes.datatype, is(DataTypeEnum.float_));
288         assertThat(property.attributes.format, is("-100:100"));
289         verify(property).attributesReceived();
290         assertNotNull(property.getChannelState());
291         assertThat(property.getType().getState().getMinimum().intValue(), is(-100));
292         assertThat(property.getType().getState().getMaximum().intValue(), is(100));
293
294         // Check property and property attributes
295         Property propertyBell = node.properties.get("doorbell");
296         verify(propertyBell).attributesReceived();
297         assertThat(propertyBell.attributes.settable, is(false));
298         assertThat(propertyBell.attributes.retained, is(false));
299         assertThat(propertyBell.attributes.name, is("Doorbell"));
300         assertThat(propertyBell.attributes.datatype, is(DataTypeEnum.boolean_));
301
302         // The device->node->property tree is ready. Now subscribe to property values.
303         device.startChannels(connection, scheduler, 50, handler).get();
304         assertThat(propertyBell.getChannelState().isStateful(), is(false));
305         assertThat(propertyBell.getChannelState().getCache().getChannelState(), is(UnDefType.UNDEF));
306         assertThat(property.getChannelState().getCache().getChannelState(), is(new DecimalType(10)));
307
308         property = node.properties.get("testRetain");
309         WaitForTopicValue watcher = new WaitForTopicValue(embeddedConnection, propertyTestTopic + "/set");
310         // Watch the topic. Publish a retain=false value to MQTT
311         property.getChannelState().publishValue(OnOffType.OFF).get();
312         assertThat(watcher.waitForTopicValue(1000), is("false"));
313
314         // Publish a retain=false value to MQTT.
315         property.getChannelState().publishValue(OnOffType.ON).get();
316         // No value is expected to be retained on this MQTT topic
317         waitForAssert(() -> {
318             WaitForTopicValue w = new WaitForTopicValue(embeddedConnection, propertyTestTopic + "/set");
319             assertNull(w.waitForTopicValue(50));
320         }, 500, 100);
321     }
322 }