2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mqtt.homie;
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.*;
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;
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;
63 * A full implementation test, that starts the embedded MQTT broker and publishes a homie device tree.
65 * @author David Graeff - Initial contribution
67 @ExtendWith(MockitoExtension.class)
68 @MockitoSettings(strictness = Strictness.LENIENT)
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;
75 private @NonNullByDefault({}) MqttBrokerConnection homieConnection;
76 private int registeredTopics = 100;
78 // The handler is not tested here, so just mock the callback
79 private @Mock @NonNullByDefault({}) DeviceCallback callback;
81 // A handler mock is required to verify that channel value changes have been received
82 private @Mock @NonNullByDefault({}) HomieThingHandler handler;
84 private @NonNullByDefault({}) ScheduledExecutorService scheduler;
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.
90 private MqttConnectionObserver failIfChange = (state, error) -> assertThat(state,
91 is(MqttConnectionState.CONNECTED));
93 private String propertyTestTopic = "";
97 public void beforeEach() throws Exception {
100 homieConnection = createBrokerConnection("homie");
102 // If the connection state changes in between -> fail
103 homieConnection.addConnectionObserver(failIfChange);
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"));
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"));
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"));
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"));
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"));
138 registeredTopics = futures.size();
139 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(5, TimeUnit.SECONDS);
141 scheduler = new ScheduledThreadPoolExecutor(6);
146 public void afterEach() throws Exception {
147 if (homieConnection != null) {
148 homieConnection.removeConnectionObserver(failIfChange);
149 homieConnection.stop().get(5, TimeUnit.SECONDS);
151 if (scheduler != null) {
152 scheduler.shutdownNow();
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,
163 assertTrue(c.await(5, TimeUnit.SECONDS),
164 "Connection " + homieConnection.getClientId() + " not retrieving all topics ");
168 public void retrieveOneAttribute() throws Exception {
169 WaitForTopicValue watcher = new WaitForTopicValue(homieConnection, DEVICE_TOPIC + "/$homie");
170 assertThat(watcher.waitForTopicValue(1000), is("3.0"));
173 @SuppressWarnings("null")
175 public void retrieveAttributes() throws Exception {
176 assertThat(homieConnection.hasSubscribers(), is(false));
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()));
183 // Create a scheduler
184 ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(4);
186 property.subscribe(homieConnection, scheduler, 500).get();
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();
196 // Receive property value
197 ChannelState channelState = spy(property.getChannelState());
198 PropertyHelper.setChannelState(property, channelState);
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());
205 assertThat(property.getChannelState().getCache().getChannelState(),
206 is(new QuantityType<>(10, SIUnits.CELSIUS)));
208 property.stop().get();
209 assertThat(homieConnection.hasSubscribers(), is(false));
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())));
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];
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());
230 @SuppressWarnings("null")
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<>();
237 new Device(ThingChannelConstants.TEST_HOME_THING, callback, new DeviceAttributes(), nodeMap));
239 // Intercept creating a node in initialize()->start() and inject a spy'ed node.
240 doAnswer(this::createSpyNode).when(device).createNode(any());
242 // initialize the device, subscribe and wait.
243 device.initialize(BASE_TOPIC, DEVICE_ID, Collections.emptyList());
244 device.subscribe(homieConnection, scheduler, 1500).get();
246 assertThat(device.isInitialized(), is(true));
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());
258 assertThat(device.nodes.size(), is(1));
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"));
269 assertThat(node.properties.size(), is(3));
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));
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_));
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)));
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"));
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));