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