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