2 * Copyright (c) 2010-2023 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.internal.handler;
15 import static org.eclipse.jdt.annotation.Checks.requireNonNull;
16 import static org.hamcrest.CoreMatchers.is;
17 import static org.hamcrest.MatcherAssert.assertThat;
18 import static org.junit.jupiter.api.Assertions.*;
19 import static org.mockito.ArgumentMatchers.*;
20 import static org.mockito.Mockito.*;
21 import static org.openhab.binding.mqtt.homie.internal.handler.ThingChannelConstants.TEST_HOMIE_THING;
23 import java.lang.reflect.Field;
24 import java.util.ArrayList;
25 import java.util.List;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.junit.jupiter.api.BeforeEach;
36 import org.junit.jupiter.api.Test;
37 import org.junit.jupiter.api.extension.ExtendWith;
38 import org.mockito.Mock;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.junit.jupiter.MockitoExtension;
41 import org.mockito.junit.jupiter.MockitoSettings;
42 import org.mockito.quality.Strictness;
43 import org.openhab.binding.mqtt.generic.ChannelState;
44 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
45 import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass;
46 import org.openhab.binding.mqtt.generic.mapping.SubscribeFieldToMQTTtopic;
47 import org.openhab.binding.mqtt.generic.tools.ChildMap;
48 import org.openhab.binding.mqtt.generic.tools.DelayedBatchProcessing;
49 import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
50 import org.openhab.binding.mqtt.homie.ChannelStateHelper;
51 import org.openhab.binding.mqtt.homie.ThingHandlerHelper;
52 import org.openhab.binding.mqtt.homie.generic.internal.MqttBindingConstants;
53 import org.openhab.binding.mqtt.homie.internal.homie300.Device;
54 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes;
55 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes.ReadyState;
56 import org.openhab.binding.mqtt.homie.internal.homie300.Node;
57 import org.openhab.binding.mqtt.homie.internal.homie300.NodeAttributes;
58 import org.openhab.binding.mqtt.homie.internal.homie300.Property;
59 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes;
60 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes.DataTypeEnum;
61 import org.openhab.core.config.core.Configuration;
62 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
63 import org.openhab.core.library.types.StringType;
64 import org.openhab.core.thing.Channel;
65 import org.openhab.core.thing.Thing;
66 import org.openhab.core.thing.ThingStatus;
67 import org.openhab.core.thing.ThingStatusDetail;
68 import org.openhab.core.thing.ThingStatusInfo;
69 import org.openhab.core.thing.binding.ThingHandlerCallback;
70 import org.openhab.core.thing.binding.builder.ThingBuilder;
71 import org.openhab.core.thing.type.ChannelKind;
72 import org.openhab.core.thing.type.ThingTypeRegistry;
73 import org.openhab.core.types.RefreshType;
76 * Tests cases for {@link HomieThingHandler}.
78 * @author David Graeff - Initial contribution
80 @ExtendWith(MockitoExtension.class)
81 @MockitoSettings(strictness = Strictness.LENIENT)
83 public class HomieThingHandlerTests {
85 private @Mock @NonNullByDefault({}) AbstractBrokerHandler bridgeHandlerMock;
86 private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
87 private @Mock @NonNullByDefault({}) MqttBrokerConnection connectionMock;
88 private @Mock @NonNullByDefault({}) ScheduledExecutorService schedulerMock;
89 private @Mock @NonNullByDefault({}) ScheduledFuture<?> scheduledFutureMock;
90 private @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistryMock;
92 private @NonNullByDefault({}) Thing thing;
93 private @NonNullByDefault({}) HomieThingHandler thingHandler;
95 private final MqttChannelTypeProvider channelTypeProvider = new MqttChannelTypeProvider(thingTypeRegistryMock);
97 private final String deviceID = ThingChannelConstants.TEST_HOMIE_THING.getId();
98 private final String deviceTopic = "homie/" + deviceID;
100 // A completed future is returned for a subscribe call to the attributes
101 private CompletableFuture<@Nullable Void> future = CompletableFuture.completedFuture(null);
104 public void setUp() {
105 final ThingStatusInfo thingStatus = new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
107 final Configuration config = new Configuration();
108 config.put("basetopic", "homie");
109 config.put("deviceid", deviceID);
111 thing = ThingBuilder.create(MqttBindingConstants.HOMIE300_MQTT_THING, TEST_HOMIE_THING.getId())
112 .withConfiguration(config).build();
113 thing.setStatusInfo(thingStatus);
115 // Return the mocked connection object if the bridge handler is asked for it
116 when(bridgeHandlerMock.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connectionMock));
118 doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).subscribe(any(), any());
119 doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribe(any(), any());
120 doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).unsubscribeAll();
121 doReturn(CompletableFuture.completedFuture(true)).when(connectionMock).publish(any(), any(), anyInt(),
124 doReturn(false).when(scheduledFutureMock).isDone();
125 doReturn(scheduledFutureMock).when(schedulerMock).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
127 final HomieThingHandler handler = new HomieThingHandler(thing, channelTypeProvider, 1000, 30, 5);
128 thingHandler = spy(handler);
129 thingHandler.setCallback(callbackMock);
130 final Device device = new Device(thing.getUID(), thingHandler, spy(new DeviceAttributes()),
131 spy(new ChildMap<>()));
132 thingHandler.setInternalObjects(spy(device),
133 spy(new DelayedBatchProcessing<>(500, thingHandler, schedulerMock)));
135 // Return the bridge handler if the thing handler asks for it
136 doReturn(bridgeHandlerMock).when(thingHandler).getBridgeHandler();
138 // We are by default online
139 doReturn(thingStatus).when(thingHandler).getBridgeStatus();
143 public void initialize() {
144 assertThat(thingHandler.device.isInitialized(), is(false));
145 // // A completed future is returned for a subscribe call to the attributes
146 doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
148 doReturn(future).when(thingHandler.device.attributes).unsubscribe();
149 // Prevent a call to accept, that would update our thing.
150 doNothing().when(thingHandler).accept(any());
151 // Pretend that a device state change arrived.
152 thingHandler.device.attributes.state = ReadyState.ready;
154 verify(callbackMock, times(0)).statusUpdated(eq(thing), any());
156 thingHandler.initialize();
158 // Expect a call to the bridge status changed, the start, the propertiesChanged method
159 verify(thingHandler).bridgeStatusChanged(any());
160 verify(thingHandler).start(any());
161 verify(thingHandler).readyStateChanged(any());
162 verify(thingHandler.device.attributes).subscribeAndReceive(any(), any(),
163 argThat(arg -> deviceTopic.equals(arg)), any(), anyInt());
165 assertThat(thingHandler.device.isInitialized(), is(true));
167 verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.ONLINE.equals(arg.getStatus())
168 && ThingStatusDetail.NONE.equals(arg.getStatusDetail())));
172 public void initializeGeneralTimeout() throws InterruptedException {
173 // A non completed future is returned for a subscribe call to the attributes
174 doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
176 doReturn(future).when(thingHandler.device.attributes).unsubscribe();
178 // Prevent a call to accept, that would update our thing.
179 doNothing().when(thingHandler).accept(any());
181 thingHandler.initialize();
183 verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.OFFLINE.equals(arg.getStatus())
184 && ThingStatusDetail.COMMUNICATION_ERROR.equals(arg.getStatusDetail())));
188 public void initializeNoStateReceived() throws InterruptedException {
189 // A completed future is returned for a subscribe call to the attributes
190 doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
192 doReturn(future).when(thingHandler.device.attributes).unsubscribe();
194 // Prevent a call to accept, that would update our thing.
195 doNothing().when(thingHandler).accept(any());
197 thingHandler.initialize();
198 assertThat(thingHandler.device.isInitialized(), is(true));
200 verify(callbackMock).statusUpdated(eq(thing), argThat(arg -> ThingStatus.OFFLINE.equals(arg.getStatus())
201 && ThingStatusDetail.GONE.equals(arg.getStatusDetail())));
204 @SuppressWarnings("null")
206 public void handleCommandRefresh() {
207 // Create mocked homie device tree with one node and one read-only property
208 Node node = thingHandler.device.createNode("node", spy(new NodeAttributes()));
209 doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
210 doReturn(future).when(node.attributes).unsubscribe();
211 node.attributes.name = "testnode";
213 Property property = node.createProperty("property", spy(new PropertyAttributes()));
214 doReturn(future).when(property.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
215 doReturn(future).when(property.attributes).unsubscribe();
216 property.attributes.name = "testprop";
217 property.attributes.datatype = DataTypeEnum.string_;
218 property.attributes.settable = false;
219 property.attributesReceived();
220 node.properties.put(property.propertyID, property);
221 thingHandler.device.nodes.put(node.nodeID, node);
223 ThingHandlerHelper.setConnection(thingHandler, connectionMock);
224 // we need to set a channel value first, undefined values ignored on REFRESH
225 property.getChannelState().getCache().update(new StringType("testString"));
227 thingHandler.handleCommand(property.channelUID, RefreshType.REFRESH);
228 verify(callbackMock).stateUpdated(argThat(arg -> property.channelUID.equals(arg)),
229 argThat(arg -> property.getChannelState().getCache().getChannelState().equals(arg)));
232 @SuppressWarnings("null")
234 public void handleCommandUpdate() {
235 // Create mocked homie device tree with one node and one writable property
236 Node node = thingHandler.device.createNode("node", spy(new NodeAttributes()));
237 doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
238 doReturn(future).when(node.attributes).unsubscribe();
239 node.attributes.name = "testnode";
241 Property property = node.createProperty("property", spy(new PropertyAttributes()));
242 doReturn(future).when(property.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
243 doReturn(future).when(property.attributes).unsubscribe();
244 property.attributes.name = "testprop";
245 property.attributes.datatype = DataTypeEnum.string_;
246 property.attributes.settable = true;
247 property.attributesReceived();
248 node.properties.put(property.propertyID, property);
249 thingHandler.device.nodes.put(node.nodeID, node);
251 ChannelState channelState = requireNonNull(property.getChannelState());
252 assertNotNull(channelState);
253 ChannelStateHelper.setConnection(channelState, connectionMock);// Pretend we called start()
254 ThingHandlerHelper.setConnection(thingHandler, connectionMock);
256 StringType updateValue = new StringType("UPDATE");
257 thingHandler.handleCommand(property.channelUID, updateValue);
258 verify(connectionMock, times(1)).publish(any(), any(), anyInt(), anyBoolean());
260 // Check non writable property
261 property.attributes.settable = false;
262 property.attributesReceived();
264 property.getChannelState().getCache().update(new StringType("OLDVALUE"));
265 // Try to update with new value
266 updateValue = new StringType("SOMETHINGNEW");
267 thingHandler.handleCommand(property.channelUID, updateValue);
268 // Expect old value and no MQTT publish
269 assertThat(property.getChannelState().getCache().getChannelState().toString(), is("OLDVALUE"));
270 verify(connectionMock, times(1)).publish(any(), any(), anyInt(), anyBoolean());
273 public Object createSubscriberAnswer(InvocationOnMock invocation) {
274 final AbstractMqttAttributeClass attributes = (AbstractMqttAttributeClass) invocation.getMock();
275 final ScheduledExecutorService scheduler = (ScheduledExecutorService) invocation.getArguments()[0];
276 final Field field = (Field) invocation.getArguments()[1];
277 final String topic = (String) invocation.getArguments()[2];
278 final boolean mandatory = (boolean) invocation.getArguments()[3];
279 final SubscribeFieldToMQTTtopic s = spy(
280 new SubscribeFieldToMQTTtopic(scheduler, field, attributes, topic, mandatory));
281 doReturn(CompletableFuture.completedFuture(true)).when(s).subscribeAndReceive(any(), anyInt());
285 public Property createSpyProperty(String propertyID, Node node) {
286 // Create a property with the same ID and insert it instead
287 Property property = spy(node.createProperty(propertyID, spy(new PropertyAttributes())));
288 doAnswer(this::createSubscriberAnswer).when(property.attributes).createSubscriber(any(), any(), any(),
290 property.attributes.name = "testprop";
291 property.attributes.datatype = DataTypeEnum.string_;
296 public Node createSpyNode(String propertyID, Device device) {
298 Node node = spy(device.createNode("node", spy(new NodeAttributes())));
299 doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
300 doReturn(future).when(node.attributes).unsubscribe();
301 node.attributes.name = "testnode";
302 node.attributes.properties = new String[] { "property" };
303 doAnswer(this::createSubscriberAnswer).when(node.attributes).createSubscriber(any(), any(), any(),
306 // Intercept creating a property in the next call and inject a spy'ed property.
307 doAnswer(i -> createSpyProperty("property", node)).when(node).createProperty(any());
313 public void propertiesChanged() throws InterruptedException, ExecutionException {
314 thingHandler.device.initialize("homie", "device", new ArrayList<>());
315 ThingHandlerHelper.setConnection(thingHandler, connectionMock);
317 // Create mocked homie device tree with one node and one property
318 doAnswer(this::createSubscriberAnswer).when(thingHandler.device.attributes).createSubscriber(any(), any(),
319 any(), anyBoolean());
321 thingHandler.device.attributes.state = ReadyState.ready;
322 thingHandler.device.attributes.name = "device";
323 thingHandler.device.attributes.homie = "3.0";
324 thingHandler.device.attributes.nodes = new String[] { "node" };
326 // Intercept creating a node in initialize()->start() and inject a spy'ed node.
327 doAnswer(i -> createSpyNode("node", thingHandler.device)).when(thingHandler.device).createNode(any());
329 verify(thingHandler, times(0)).nodeAddedOrChanged(any());
330 verify(thingHandler, times(0)).propertyAddedOrChanged(any());
332 thingHandler.initialize();
334 assertThat(thingHandler.device.isInitialized(), is(true));
336 verify(thingHandler).propertyAddedOrChanged(any());
337 verify(thingHandler).nodeAddedOrChanged(any());
339 verify(thingHandler.device).subscribe(any(), any(), anyInt());
340 verify(thingHandler.device).attributesReceived(any(), any(), anyInt());
342 assertNotNull(thingHandler.device.nodes.get("node").properties.get("property"));
344 assertTrue(thingHandler.delayedProcessing.isArmed());
346 // Simulate waiting for the delayed processor
347 thingHandler.delayedProcessing.forceProcessNow();
349 // Called for the updated property + for the new channels
350 verify(callbackMock, atLeast(2)).thingUpdated(any());
352 final List<Channel> channels = thingHandler.getThing().getChannels();
353 assertThat(channels.size(), is(1));
354 assertThat(channels.get(0).getLabel(), is("testprop"));
355 assertThat(channels.get(0).getKind(), is(ChannelKind.STATE));
357 final Map<String, String> properties = thingHandler.getThing().getProperties();
358 assertThat(properties.get(MqttBindingConstants.HOMIE_PROPERTY_VERSION), is("3.0"));
359 assertThat(properties.size(), is(1));