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