2 * Copyright (c) 2010-2020 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.modbus.tests;
15 import static org.hamcrest.CoreMatchers.*;
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.ArgumentMatchers.any;
20 import static org.mockito.Mockito.*;
21 import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal.*;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Objects;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.function.Consumer;
32 import java.util.function.Function;
34 import org.apache.commons.lang.StringUtils;
35 import org.hamcrest.Matcher;
36 import org.junit.jupiter.api.AfterEach;
37 import org.junit.jupiter.api.Test;
38 import org.mockito.Mockito;
39 import org.openhab.binding.modbus.handler.EndpointNotInitializedException;
40 import org.openhab.binding.modbus.handler.ModbusPollerThingHandler;
41 import org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler;
42 import org.openhab.binding.modbus.internal.handler.ModbusTcpThingHandler;
43 import org.openhab.core.config.core.Configuration;
44 import org.openhab.core.io.transport.modbus.AsyncModbusFailure;
45 import org.openhab.core.io.transport.modbus.AsyncModbusReadResult;
46 import org.openhab.core.io.transport.modbus.AsyncModbusWriteResult;
47 import org.openhab.core.io.transport.modbus.BitArray;
48 import org.openhab.core.io.transport.modbus.ModbusConstants;
49 import org.openhab.core.io.transport.modbus.ModbusConstants.ValueType;
50 import org.openhab.core.io.transport.modbus.ModbusReadFunctionCode;
51 import org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint;
52 import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
53 import org.openhab.core.io.transport.modbus.ModbusResponse;
54 import org.openhab.core.io.transport.modbus.ModbusWriteCoilRequestBlueprint;
55 import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
56 import org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
57 import org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint;
58 import org.openhab.core.io.transport.modbus.PollTask;
59 import org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
60 import org.openhab.core.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint;
61 import org.openhab.core.items.GenericItem;
62 import org.openhab.core.items.Item;
63 import org.openhab.core.library.items.DateTimeItem;
64 import org.openhab.core.library.types.DecimalType;
65 import org.openhab.core.library.types.OnOffType;
66 import org.openhab.core.library.types.OpenClosedType;
67 import org.openhab.core.library.types.StringType;
68 import org.openhab.core.thing.Bridge;
69 import org.openhab.core.thing.ChannelUID;
70 import org.openhab.core.thing.Thing;
71 import org.openhab.core.thing.ThingStatus;
72 import org.openhab.core.thing.ThingStatusDetail;
73 import org.openhab.core.thing.ThingStatusInfo;
74 import org.openhab.core.thing.ThingUID;
75 import org.openhab.core.thing.binding.ThingHandler;
76 import org.openhab.core.thing.binding.builder.BridgeBuilder;
77 import org.openhab.core.thing.binding.builder.ChannelBuilder;
78 import org.openhab.core.thing.binding.builder.ThingBuilder;
79 import org.openhab.core.transform.TransformationException;
80 import org.openhab.core.transform.TransformationService;
81 import org.openhab.core.types.Command;
82 import org.openhab.core.types.RefreshType;
83 import org.openhab.core.types.State;
84 import org.openhab.core.types.UnDefType;
85 import org.osgi.framework.BundleContext;
86 import org.osgi.framework.InvalidSyntaxException;
89 * @author Sami Salonen - Initial contribution
91 public class ModbusDataHandlerTest extends AbstractModbusOSGiTest {
93 private final class MultiplyTransformation implements TransformationService {
95 public String transform(String function, String source) throws TransformationException {
96 return String.valueOf(Integer.parseInt(function) * Integer.parseInt(source));
100 private static final Map<String, String> CHANNEL_TO_ACCEPTED_TYPE = new HashMap<>();
102 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_SWITCH, "Switch");
103 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_CONTACT, "Contact");
104 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_DATETIME, "DateTime");
105 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_DIMMER, "Dimmer");
106 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_NUMBER, "Number");
107 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_STRING, "String");
108 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_ROLLERSHUTTER, "Rollershutter");
109 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_LAST_READ_SUCCESS, "DateTime");
110 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_LAST_WRITE_SUCCESS, "DateTime");
111 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_LAST_WRITE_ERROR, "DateTime");
112 CHANNEL_TO_ACCEPTED_TYPE.put(CHANNEL_LAST_READ_ERROR, "DateTime");
114 private List<ModbusWriteRequestBlueprint> writeRequests = new ArrayList<>();
117 public void tearDown() {
118 writeRequests.clear();
121 private void captureModbusWrites() {
122 Mockito.when(comms.submitOneTimeWrite(any(), any(), any())).then(invocation -> {
123 ModbusWriteRequestBlueprint task = (ModbusWriteRequestBlueprint) invocation.getArgument(0);
124 writeRequests.add(task);
125 return Mockito.mock(ScheduledFuture.class);
129 private Bridge createPollerMock(String pollerId, PollTask task) {
131 ThingUID thingUID = new ThingUID(THING_TYPE_MODBUS_POLLER, pollerId);
132 BridgeBuilder builder = BridgeBuilder.create(THING_TYPE_MODBUS_POLLER, thingUID)
133 .withLabel("label for " + pollerId);
134 for (Entry<String, String> entry : CHANNEL_TO_ACCEPTED_TYPE.entrySet()) {
135 String channelId = entry.getKey();
136 String channelAcceptedType = entry.getValue();
137 builder = builder.withChannel(
138 ChannelBuilder.create(new ChannelUID(thingUID, channelId), channelAcceptedType).build());
140 poller = builder.build();
141 poller.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, ""));
143 ModbusPollerThingHandler mockHandler = Mockito.mock(ModbusPollerThingHandler.class);
144 doReturn(task.getRequest()).when(mockHandler).getRequest();
145 assert comms != null;
146 doReturn(comms).when(mockHandler).getCommunicationInterface();
147 doReturn(task.getEndpoint()).when(comms).getEndpoint();
148 poller.setHandler(mockHandler);
149 assertSame(poller.getHandler(), mockHandler);
150 assertSame(((ModbusPollerThingHandler) poller.getHandler()).getCommunicationInterface().getEndpoint(),
152 assertSame(((ModbusPollerThingHandler) poller.getHandler()).getRequest(), task.getRequest());
158 private Bridge createTcpMock() {
159 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
160 Bridge tcpBridge = ModbusPollerThingHandlerTest.createTcpThingBuilder("tcp1").build();
161 ModbusTcpThingHandler tcpThingHandler = Mockito.mock(ModbusTcpThingHandler.class);
162 tcpBridge.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, ""));
163 tcpBridge.setHandler(tcpThingHandler);
164 doReturn(comms).when(tcpThingHandler).getCommunicationInterface();
166 doReturn(0).when(tcpThingHandler).getSlaveId();
167 } catch (EndpointNotInitializedException e) {
168 // not raised -- we are mocking return value only, not actually calling the method
169 throw new IllegalStateException();
171 tcpThingHandler.initialize();
172 assertThat(tcpBridge.getStatus(), is(equalTo(ThingStatus.ONLINE)));
176 private ModbusDataThingHandler createDataHandler(String id, Bridge bridge,
177 Function<ThingBuilder, ThingBuilder> builderConfigurator) {
178 return createDataHandler(id, bridge, builderConfigurator, null);
181 private ModbusDataThingHandler createDataHandler(String id, Bridge bridge,
182 Function<ThingBuilder, ThingBuilder> builderConfigurator, BundleContext context) {
183 return createDataHandler(id, bridge, builderConfigurator, context, true);
186 private ModbusDataThingHandler createDataHandler(String id, Bridge bridge,
187 Function<ThingBuilder, ThingBuilder> builderConfigurator, BundleContext context,
188 boolean autoCreateItemsAndLinkToChannels) {
189 ThingUID thingUID = new ThingUID(THING_TYPE_MODBUS_DATA, id);
190 ThingBuilder builder = ThingBuilder.create(THING_TYPE_MODBUS_DATA, thingUID).withLabel("label for " + id);
191 Map<String, ChannelUID> toBeLinked = new HashMap<>();
192 for (Entry<String, String> entry : CHANNEL_TO_ACCEPTED_TYPE.entrySet()) {
193 String channelId = entry.getKey();
194 String channelAcceptedType = entry.getValue();
195 ChannelUID channelUID = new ChannelUID(thingUID, channelId);
196 builder = builder.withChannel(ChannelBuilder.create(channelUID, channelAcceptedType).build());
198 if (autoCreateItemsAndLinkToChannels) {
199 // Create item of correct type and link it to channel
200 String itemName = getItemName(channelUID);
201 final GenericItem item;
202 if (channelId.startsWith("last") || channelId.equals("datetime")) {
203 item = new DateTimeItem(itemName);
205 item = coreItemFactory.createItem(StringUtils.capitalize(channelId), itemName);
207 assertThat(String.format("Could not determine correct item type for %s", channelId), item,
210 Objects.requireNonNull(item);
212 toBeLinked.put(itemName, channelUID);
215 if (builderConfigurator != null) {
216 builder = builderConfigurator.apply(builder);
219 Thing dataThing = builder.withBridge(bridge.getUID()).build();
222 // Link after the things and items have been created
223 for (Entry<String, ChannelUID> entry : toBeLinked.entrySet()) {
224 linkItem(entry.getKey(), entry.getValue());
226 return (ModbusDataThingHandler) dataThing.getHandler();
229 private String getItemName(ChannelUID channelUID) {
230 return channelUID.toString().replace(':', '_') + "_item";
233 private void assertSingleStateUpdate(ModbusDataThingHandler handler, String channel, Matcher<State> matcher) {
234 waitForAssert(() -> {
235 ChannelUID channelUID = new ChannelUID(handler.getThing().getUID(), channel);
236 String itemName = getItemName(channelUID);
237 Item item = itemRegistry.get(itemName);
238 assertThat(String.format("Item %s is not available from item registry", itemName), item,
241 List<State> updates = getStateUpdates(itemName);
242 if (updates != null) {
244 String.format("Many updates found, expected one: %s", Arrays.deepToString(updates.toArray())),
245 updates.size(), is(equalTo(1)));
247 State state = updates == null ? null : updates.get(0);
248 assertThat(String.format("%s %s, state %s of type %s", item.getClass().getSimpleName(), itemName, state,
249 state == null ? null : state.getClass().getSimpleName()), state, is(matcher));
253 private void assertSingleStateUpdate(ModbusDataThingHandler handler, String channel, State state) {
254 assertSingleStateUpdate(handler, channel, is(equalTo(state)));
257 private void testOutOfBoundsGeneric(int pollStart, int pollLength, String start,
258 ModbusReadFunctionCode functionCode, ValueType valueType, ThingStatus expectedStatus) {
259 testOutOfBoundsGeneric(pollStart, pollLength, start, functionCode, valueType, expectedStatus, null);
262 private void testOutOfBoundsGeneric(int pollStart, int pollLength, String start,
263 ModbusReadFunctionCode functionCode, ValueType valueType, ThingStatus expectedStatus,
264 BundleContext context) {
265 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
267 // Minimally mocked request
268 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
269 doReturn(pollStart).when(request).getReference();
270 doReturn(pollLength).when(request).getDataLength();
271 doReturn(functionCode).when(request).getFunctionCode();
273 PollTask task = Mockito.mock(PollTask.class);
274 doReturn(endpoint).when(task).getEndpoint();
275 doReturn(request).when(task).getRequest();
277 Bridge pollerThing = createPollerMock("poller1", task);
279 Configuration dataConfig = new Configuration();
280 dataConfig.put("readStart", start);
281 dataConfig.put("readTransform", "default");
282 dataConfig.put("readValueType", valueType.getConfigValue());
283 ModbusDataThingHandler dataHandler = createDataHandler("data1", pollerThing,
284 builder -> builder.withConfiguration(dataConfig), context);
285 assertThat(dataHandler.getThing().getStatusInfo().getDescription(), dataHandler.getThing().getStatus(),
286 is(equalTo(expectedStatus)));
290 public void testInitCoilsOutOfIndex() {
291 testOutOfBoundsGeneric(4, 3, "8", ModbusReadFunctionCode.READ_COILS, ModbusConstants.ValueType.BIT,
292 ThingStatus.OFFLINE);
296 public void testInitCoilsOutOfIndex2() {
297 // Reading coils 4, 5, 6. Coil 7 is out of bounds
298 testOutOfBoundsGeneric(4, 3, "7", ModbusReadFunctionCode.READ_COILS, ModbusConstants.ValueType.BIT,
299 ThingStatus.OFFLINE);
303 public void testInitCoilsOK() {
304 // Reading coils 4, 5, 6. Coil 6 is OK
305 testOutOfBoundsGeneric(4, 3, "6", ModbusReadFunctionCode.READ_COILS, ModbusConstants.ValueType.BIT,
310 public void testInitRegistersWithBitOutOfIndex() {
311 testOutOfBoundsGeneric(4, 3, "8.0", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
312 ModbusConstants.ValueType.BIT, ThingStatus.OFFLINE);
316 public void testInitRegistersWithBitOutOfIndex2() {
317 testOutOfBoundsGeneric(4, 3, "7.16", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
318 ModbusConstants.ValueType.BIT, ThingStatus.OFFLINE);
322 public void testInitRegistersWithBitOK() {
323 testOutOfBoundsGeneric(4, 3, "6.0", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
324 ModbusConstants.ValueType.BIT, ThingStatus.ONLINE);
328 public void testInitRegistersWithBitOK2() {
329 testOutOfBoundsGeneric(4, 3, "6.15", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
330 ModbusConstants.ValueType.BIT, ThingStatus.ONLINE);
334 public void testInitRegistersWithInt8OutOfIndex() {
335 testOutOfBoundsGeneric(4, 3, "8.0", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
336 ModbusConstants.ValueType.INT8, ThingStatus.OFFLINE);
340 public void testInitRegistersWithInt8OutOfIndex2() {
341 testOutOfBoundsGeneric(4, 3, "7.2", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
342 ModbusConstants.ValueType.INT8, ThingStatus.OFFLINE);
346 public void testInitRegistersWithInt8OK() {
347 testOutOfBoundsGeneric(4, 3, "6.0", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
348 ModbusConstants.ValueType.INT8, ThingStatus.ONLINE);
352 public void testInitRegistersWithInt8OK2() {
353 testOutOfBoundsGeneric(4, 3, "6.1", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
354 ModbusConstants.ValueType.INT8, ThingStatus.ONLINE);
358 public void testInitRegistersWithInt16OK() {
359 // Poller reading registers 4, 5, 6. Register 6 is OK
360 testOutOfBoundsGeneric(4, 3, "6", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
361 ModbusConstants.ValueType.INT16, ThingStatus.ONLINE);
365 public void testInitRegistersWithInt16OutOfBounds() {
366 // Poller reading registers 4, 5, 6. Register 7 is out-of-bounds
367 testOutOfBoundsGeneric(4, 3, "7", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
368 ModbusConstants.ValueType.INT16, ThingStatus.OFFLINE);
372 public void testInitRegistersWithInt16OutOfBounds2() {
373 testOutOfBoundsGeneric(4, 3, "8", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
374 ModbusConstants.ValueType.INT16, ThingStatus.OFFLINE);
378 public void testInitRegistersWithInt16NoDecimalFormatAllowed() {
379 testOutOfBoundsGeneric(4, 3, "7.0", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
380 ModbusConstants.ValueType.INT16, ThingStatus.OFFLINE);
384 public void testInitRegistersWithInt32OK() {
385 testOutOfBoundsGeneric(4, 3, "5", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
386 ModbusConstants.ValueType.INT32, ThingStatus.ONLINE);
390 public void testInitRegistersWithInt32OutOfBounds() {
391 testOutOfBoundsGeneric(4, 3, "6", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
392 ModbusConstants.ValueType.INT32, ThingStatus.OFFLINE);
396 public void testInitRegistersWithInt32AtTheEdge() {
397 testOutOfBoundsGeneric(4, 3, "5", ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
398 ModbusConstants.ValueType.INT32, ThingStatus.ONLINE);
401 private ModbusDataThingHandler testReadHandlingGeneric(ModbusReadFunctionCode functionCode, String start,
402 String transform, ValueType valueType, BitArray bits, ModbusRegisterArray registers, Exception error) {
403 return testReadHandlingGeneric(functionCode, start, transform, valueType, bits, registers, error, null);
406 private ModbusDataThingHandler testReadHandlingGeneric(ModbusReadFunctionCode functionCode, String start,
407 String transform, ValueType valueType, BitArray bits, ModbusRegisterArray registers, Exception error,
408 BundleContext context) {
409 return testReadHandlingGeneric(functionCode, start, transform, valueType, bits, registers, error, context,
413 @SuppressWarnings({ "null" })
414 private ModbusDataThingHandler testReadHandlingGeneric(ModbusReadFunctionCode functionCode, String start,
415 String transform, ValueType valueType, BitArray bits, ModbusRegisterArray registers, Exception error,
416 BundleContext context, boolean autoCreateItemsAndLinkToChannels) {
417 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
421 // Minimally mocked request
422 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
423 doReturn(pollLength).when(request).getDataLength();
424 doReturn(functionCode).when(request).getFunctionCode();
426 PollTask task = Mockito.mock(PollTask.class);
427 doReturn(endpoint).when(task).getEndpoint();
428 doReturn(request).when(task).getRequest();
430 Bridge poller = createPollerMock("poller1", task);
432 Configuration dataConfig = new Configuration();
433 dataConfig.put("readStart", start);
434 dataConfig.put("readTransform", transform);
435 dataConfig.put("readValueType", valueType.getConfigValue());
437 String thingId = "read1";
438 ModbusDataThingHandler dataHandler = createDataHandler(thingId, poller,
439 builder -> builder.withConfiguration(dataConfig), context, autoCreateItemsAndLinkToChannels);
441 assertThat(dataHandler.getThing().getStatus(), is(equalTo(ThingStatus.ONLINE)));
445 assertNull(registers);
447 AsyncModbusReadResult result = new AsyncModbusReadResult(request, bits);
448 dataHandler.onReadResult(result);
449 } else if (registers != null) {
452 AsyncModbusReadResult result = new AsyncModbusReadResult(request, registers);
453 dataHandler.onReadResult(result);
456 assertNull(registers);
457 assertNotNull(error);
458 AsyncModbusFailure<ModbusReadRequestBlueprint> result = new AsyncModbusFailure<ModbusReadRequestBlueprint>(
460 dataHandler.handleReadError(result);
465 @SuppressWarnings({ "null" })
466 private ModbusDataThingHandler testWriteHandlingGeneric(String start, String transform, ValueType valueType,
467 String writeType, ModbusWriteFunctionCode successFC, String channel, Command command, Exception error,
468 BundleContext context) {
469 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
471 // Minimally mocked request
472 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
474 PollTask task = Mockito.mock(PollTask.class);
475 doReturn(endpoint).when(task).getEndpoint();
476 doReturn(request).when(task).getRequest();
478 Bridge poller = createPollerMock("poller1", task);
480 Configuration dataConfig = new Configuration();
481 dataConfig.put("readStart", "");
482 dataConfig.put("writeStart", start);
483 dataConfig.put("writeTransform", transform);
484 dataConfig.put("writeValueType", valueType.getConfigValue());
485 dataConfig.put("writeType", writeType);
487 String thingId = "write";
489 ModbusDataThingHandler dataHandler = createDataHandler(thingId, poller,
490 builder -> builder.withConfiguration(dataConfig), context);
492 assertThat(dataHandler.getThing().getStatus(), is(equalTo(ThingStatus.ONLINE)));
494 dataHandler.handleCommand(new ChannelUID(dataHandler.getThing().getUID(), channel), command);
497 dataHandler.handleReadError(new AsyncModbusFailure<ModbusReadRequestBlueprint>(request, error));
499 ModbusResponse resp = new ModbusResponse() {
502 public int getFunctionCode() {
503 return successFC.getFunctionCode();
507 .onWriteResponse(new AsyncModbusWriteResult(Mockito.mock(ModbusWriteRequestBlueprint.class), resp));
513 public void testOnError() {
514 ModbusDataThingHandler dataHandler = testReadHandlingGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
515 "0.0", "default", ModbusConstants.ValueType.BIT, null, null, new Exception("fooerror"));
517 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_ERROR, is(notNullValue(State.class)));
521 public void testOnRegistersInt16StaticTransformation() {
522 ModbusDataThingHandler dataHandler = testReadHandlingGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
523 "0", "-3", ModbusConstants.ValueType.INT16, null,
524 new ModbusRegisterArray(new byte[] { (byte) 0xff, (byte) 0xfd }), null);
526 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_SUCCESS, is(notNullValue(State.class)));
527 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_ERROR, is(nullValue(State.class)));
529 // -3 converts to "true"
530 assertSingleStateUpdate(dataHandler, CHANNEL_CONTACT, is(nullValue(State.class)));
531 assertSingleStateUpdate(dataHandler, CHANNEL_SWITCH, is(nullValue(State.class)));
532 assertSingleStateUpdate(dataHandler, CHANNEL_DIMMER, is(nullValue(State.class)));
533 assertSingleStateUpdate(dataHandler, CHANNEL_NUMBER, new DecimalType(-3));
534 // roller shutter fails since -3 is invalid value (not between 0...100)
535 // assertThatStateContains(state, CHANNEL_ROLLERSHUTTER, new PercentType(1));
536 assertSingleStateUpdate(dataHandler, CHANNEL_STRING, new StringType("-3"));
537 // no datetime, conversion not possible without transformation
541 public void testOnRegistersRealTransformation() {
542 mockTransformation("MULTIPLY", new MultiplyTransformation());
543 ModbusDataThingHandler dataHandler = testReadHandlingGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
544 "0", "MULTIPLY(10)", ModbusConstants.ValueType.INT16, null,
545 new ModbusRegisterArray(new byte[] { (byte) 0xff, (byte) 0xfd }), null, bundleContext);
547 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_SUCCESS, is(notNullValue(State.class)));
548 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_ERROR, is(nullValue(State.class)));
550 // transformation output (-30) is not valid for contact or switch
551 assertSingleStateUpdate(dataHandler, CHANNEL_CONTACT, is(nullValue(State.class)));
552 assertSingleStateUpdate(dataHandler, CHANNEL_SWITCH, is(nullValue(State.class)));
553 // -30 is not valid value for Dimmer (PercentType) (not between 0...100)
554 assertSingleStateUpdate(dataHandler, CHANNEL_DIMMER, is(nullValue(State.class)));
555 assertSingleStateUpdate(dataHandler, CHANNEL_NUMBER, new DecimalType(-30));
556 // roller shutter fails since -3 is invalid value (not between 0...100)
557 assertSingleStateUpdate(dataHandler, CHANNEL_ROLLERSHUTTER, is(nullValue(State.class)));
558 assertSingleStateUpdate(dataHandler, CHANNEL_STRING, new StringType("-30"));
559 // no datetime, conversion not possible without transformation
563 public void testOnRegistersNaNFloatInRegisters() throws InvalidSyntaxException {
564 ModbusDataThingHandler dataHandler = testReadHandlingGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
565 "0", "default", ModbusConstants.ValueType.FLOAT32, null, new ModbusRegisterArray(
566 // equivalent of floating point NaN
567 new byte[] { (byte) 0x7f, (byte) 0xc0, (byte) 0x00, (byte) 0x00 }),
568 null, bundleContext);
570 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_SUCCESS, is(notNullValue(State.class)));
571 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_ERROR, is(nullValue(State.class)));
573 // UNDEF is treated as "boolean true" (OPEN/ON) since it is != 0.
574 assertSingleStateUpdate(dataHandler, CHANNEL_CONTACT, OpenClosedType.OPEN);
575 assertSingleStateUpdate(dataHandler, CHANNEL_SWITCH, OnOffType.ON);
576 assertSingleStateUpdate(dataHandler, CHANNEL_DIMMER, OnOffType.ON);
577 assertSingleStateUpdate(dataHandler, CHANNEL_NUMBER, UnDefType.UNDEF);
578 assertSingleStateUpdate(dataHandler, CHANNEL_ROLLERSHUTTER, UnDefType.UNDEF);
579 assertSingleStateUpdate(dataHandler, CHANNEL_STRING, UnDefType.UNDEF);
583 public void testOnRegistersRealTransformation2() throws InvalidSyntaxException {
584 mockTransformation("ONOFF", new TransformationService() {
587 public String transform(String function, String source) throws TransformationException {
588 return Integer.parseInt(source) != 0 ? "ON" : "OFF";
591 ModbusDataThingHandler dataHandler = testReadHandlingGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
592 "0", "ONOFF(10)", ModbusConstants.ValueType.INT16, null,
593 new ModbusRegisterArray(new byte[] { (byte) 0xff, (byte) 0xfd }), null, bundleContext);
595 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_SUCCESS, is(notNullValue(State.class)));
596 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_READ_ERROR, is(nullValue(State.class)));
598 assertSingleStateUpdate(dataHandler, CHANNEL_CONTACT, is(nullValue(State.class)));
599 assertSingleStateUpdate(dataHandler, CHANNEL_SWITCH, is(equalTo(OnOffType.ON)));
600 assertSingleStateUpdate(dataHandler, CHANNEL_DIMMER, is(equalTo(OnOffType.ON)));
601 assertSingleStateUpdate(dataHandler, CHANNEL_NUMBER, is(nullValue(State.class)));
602 assertSingleStateUpdate(dataHandler, CHANNEL_ROLLERSHUTTER, is(nullValue(State.class)));
603 assertSingleStateUpdate(dataHandler, CHANNEL_STRING, is(equalTo(new StringType("ON"))));
607 public void testWriteRealTransformation() throws InvalidSyntaxException {
608 captureModbusWrites();
609 mockTransformation("MULTIPLY", new MultiplyTransformation());
610 ModbusDataThingHandler dataHandler = testWriteHandlingGeneric("50", "MULTIPLY(10)",
611 ModbusConstants.ValueType.BIT, "coil", ModbusWriteFunctionCode.WRITE_COIL, "number",
612 new DecimalType("2"), null, bundleContext);
614 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_SUCCESS, is(notNullValue(State.class)));
615 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_ERROR, is(nullValue(State.class)));
616 assertThat(writeRequests.size(), is(equalTo(1)));
617 ModbusWriteRequestBlueprint writeRequest = writeRequests.get(0);
618 assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_COIL)));
619 assertThat(writeRequest.getReference(), is(equalTo(50)));
620 assertThat(((ModbusWriteCoilRequestBlueprint) writeRequest).getCoils().size(), is(equalTo(1)));
621 // Since transform output is non-zero, it is mapped as "true"
622 assertThat(((ModbusWriteCoilRequestBlueprint) writeRequest).getCoils().getBit(0), is(equalTo(true)));
626 public void testWriteRealTransformation2() throws InvalidSyntaxException {
627 captureModbusWrites();
628 mockTransformation("ZERO", new TransformationService() {
631 public String transform(String function, String source) throws TransformationException {
635 ModbusDataThingHandler dataHandler = testWriteHandlingGeneric("50", "ZERO(foobar)",
636 ModbusConstants.ValueType.BIT, "coil", ModbusWriteFunctionCode.WRITE_COIL, "number",
637 new DecimalType("2"), null, bundleContext);
639 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_SUCCESS, is(notNullValue(State.class)));
640 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_ERROR, is(nullValue(State.class)));
641 assertThat(writeRequests.size(), is(equalTo(1)));
642 ModbusWriteRequestBlueprint writeRequest = writeRequests.get(0);
643 assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_COIL)));
644 assertThat(writeRequest.getReference(), is(equalTo(50)));
645 assertThat(((ModbusWriteCoilRequestBlueprint) writeRequest).getCoils().size(), is(equalTo(1)));
646 // Since transform output is zero, it is mapped as "false"
647 assertThat(((ModbusWriteCoilRequestBlueprint) writeRequest).getCoils().getBit(0), is(equalTo(false)));
651 public void testWriteRealTransformation3() throws InvalidSyntaxException {
652 captureModbusWrites();
653 mockTransformation("RANDOM", new TransformationService() {
656 public String transform(String function, String source) throws TransformationException {
660 ModbusDataThingHandler dataHandler = testWriteHandlingGeneric("50", "RANDOM(foobar)",
661 ModbusConstants.ValueType.INT16, "holding", ModbusWriteFunctionCode.WRITE_SINGLE_REGISTER, "number",
662 new DecimalType("2"), null, bundleContext);
664 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_SUCCESS, is(notNullValue(State.class)));
665 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_ERROR, is(nullValue(State.class)));
666 assertThat(writeRequests.size(), is(equalTo(1)));
667 ModbusWriteRequestBlueprint writeRequest = writeRequests.get(0);
668 assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_SINGLE_REGISTER)));
669 assertThat(writeRequest.getReference(), is(equalTo(50)));
670 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().size(), is(equalTo(1)));
671 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(0), is(equalTo(5)));
675 public void testWriteRealTransformation4() throws InvalidSyntaxException {
676 captureModbusWrites();
677 mockTransformation("JSON", new TransformationService() {
680 public String transform(String function, String source) throws TransformationException {
682 + "\"functionCode\": 16,"//
683 + "\"address\": 5412,"//
684 + "\"value\": [1, 0, 5]"//
687 + "\"functionCode\": 6,"//
688 + "\"address\": 555,"//
693 ModbusDataThingHandler dataHandler = testWriteHandlingGeneric("50", "JSON(foobar)",
694 ModbusConstants.ValueType.INT16, "holding", ModbusWriteFunctionCode.WRITE_MULTIPLE_REGISTERS, "number",
695 new DecimalType("2"), null, bundleContext);
697 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_SUCCESS, is(notNullValue(State.class)));
698 assertSingleStateUpdate(dataHandler, CHANNEL_LAST_WRITE_ERROR, is(nullValue(State.class)));
699 assertThat(writeRequests.size(), is(equalTo(2)));
701 ModbusWriteRequestBlueprint writeRequest = writeRequests.get(0);
702 assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_MULTIPLE_REGISTERS)));
703 assertThat(writeRequest.getReference(), is(equalTo(5412)));
704 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().size(), is(equalTo(3)));
705 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(0),
707 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(1),
709 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(2),
713 ModbusWriteRequestBlueprint writeRequest = writeRequests.get(1);
714 assertThat(writeRequest.getFunctionCode(), is(equalTo(ModbusWriteFunctionCode.WRITE_SINGLE_REGISTER)));
715 assertThat(writeRequest.getReference(), is(equalTo(555)));
716 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().size(), is(equalTo(1)));
717 assertThat(((ModbusWriteRegisterRequestBlueprint) writeRequest).getRegisters().getRegister(0),
722 private void testValueTypeGeneric(ModbusReadFunctionCode functionCode, ValueType valueType,
723 ThingStatus expectedStatus) {
724 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
726 // Minimally mocked request
727 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
728 doReturn(3).when(request).getDataLength();
729 doReturn(functionCode).when(request).getFunctionCode();
731 PollTask task = Mockito.mock(PollTask.class);
732 doReturn(endpoint).when(task).getEndpoint();
733 doReturn(request).when(task).getRequest();
735 Bridge poller = createPollerMock("poller1", task);
737 Configuration dataConfig = new Configuration();
738 dataConfig.put("readStart", "1");
739 dataConfig.put("readTransform", "default");
740 dataConfig.put("readValueType", valueType.getConfigValue());
741 ModbusDataThingHandler dataHandler = createDataHandler("data1", poller,
742 builder -> builder.withConfiguration(dataConfig));
743 assertThat(dataHandler.getThing().getStatus(), is(equalTo(expectedStatus)));
747 public void testCoilDoesNotAcceptFloat32ValueType() {
748 testValueTypeGeneric(ModbusReadFunctionCode.READ_COILS, ModbusConstants.ValueType.FLOAT32, ThingStatus.OFFLINE);
752 public void testCoilAcceptsBitValueType() {
753 testValueTypeGeneric(ModbusReadFunctionCode.READ_COILS, ModbusConstants.ValueType.BIT, ThingStatus.ONLINE);
757 public void testDiscreteInputDoesNotAcceptFloat32ValueType() {
758 testValueTypeGeneric(ModbusReadFunctionCode.READ_INPUT_DISCRETES, ModbusConstants.ValueType.FLOAT32,
759 ThingStatus.OFFLINE);
763 public void testDiscreteInputAcceptsBitValueType() {
764 testValueTypeGeneric(ModbusReadFunctionCode.READ_INPUT_DISCRETES, ModbusConstants.ValueType.BIT,
769 public void testRefreshOnData() throws InterruptedException {
770 ModbusReadFunctionCode functionCode = ModbusReadFunctionCode.READ_COILS;
772 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
776 // Minimally mocked request
777 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
778 doReturn(pollLength).when(request).getDataLength();
779 doReturn(functionCode).when(request).getFunctionCode();
781 PollTask task = Mockito.mock(PollTask.class);
782 doReturn(endpoint).when(task).getEndpoint();
783 doReturn(request).when(task).getRequest();
785 Bridge poller = createPollerMock("poller1", task);
787 Configuration dataConfig = new Configuration();
788 dataConfig.put("readStart", "0");
789 dataConfig.put("readTransform", "default");
790 dataConfig.put("readValueType", "bit");
792 String thingId = "read1";
794 ModbusDataThingHandler dataHandler = createDataHandler(thingId, poller,
795 builder -> builder.withConfiguration(dataConfig), bundleContext);
796 assertThat(dataHandler.getThing().getStatus(), is(equalTo(ThingStatus.ONLINE)));
798 verify(comms, never()).submitOneTimePoll(eq(request), notNull(), notNull());
799 // Reset initial REFRESH commands to data thing channels from the Core
800 reset(poller.getHandler());
801 dataHandler.handleCommand(Mockito.mock(ChannelUID.class), RefreshType.REFRESH);
803 // data handler asynchronously calls the poller.refresh() -- it might take some time
804 // We check that refresh is finally called
805 waitForAssert(() -> verify((ModbusPollerThingHandler) poller.getHandler()).refresh(), 2500, 50);
810 * @param pollerFunctionCode poller function code. Use null if you want to have data thing direct child of endpoint
812 * @param config thing config
813 * @param statusConsumer assertion method for data thingstatus
815 private void testInitGeneric(ModbusReadFunctionCode pollerFunctionCode, Configuration config,
816 Consumer<ThingStatusInfo> statusConsumer) {
820 if (pollerFunctionCode == null) {
821 parent = createTcpMock();
822 ThingHandler foo = parent.getHandler();
825 ModbusSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint("thisishost", 502, false);
827 // Minimally mocked request
828 ModbusReadRequestBlueprint request = Mockito.mock(ModbusReadRequestBlueprint.class);
829 doReturn(pollLength).when(request).getDataLength();
830 doReturn(pollerFunctionCode).when(request).getFunctionCode();
832 PollTask task = Mockito.mock(PollTask.class);
833 doReturn(endpoint).when(task).getEndpoint();
834 doReturn(request).when(task).getRequest();
836 parent = createPollerMock("poller1", task);
839 String thingId = "read1";
841 ModbusDataThingHandler dataHandler = createDataHandler(thingId, parent,
842 builder -> builder.withConfiguration(config), bundleContext);
844 statusConsumer.accept(dataHandler.getThing().getStatusInfo());
848 public void testReadOnlyData() {
849 Configuration dataConfig = new Configuration();
850 dataConfig.put("readStart", "0");
851 dataConfig.put("readValueType", "bit");
852 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig,
853 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
857 * readValueType=bit should be assumed with coils, so it's ok to skip it
860 public void testReadOnlyDataMissingValueTypeWithCoils() {
861 Configuration dataConfig = new Configuration();
862 dataConfig.put("readStart", "0");
863 // missing value type
864 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig,
865 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
869 public void testReadOnlyDataInvalidValueType() {
870 Configuration dataConfig = new Configuration();
871 dataConfig.put("readStart", "0");
872 dataConfig.put("readValueType", "foobar");
873 testInitGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, dataConfig, status -> {
874 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
875 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
880 * We do not assume value type with registers, not ok to skip it
883 public void testReadOnlyDataMissingValueTypeWithRegisters() {
884 Configuration dataConfig = new Configuration();
885 dataConfig.put("readStart", "0");
886 testInitGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, dataConfig, status -> {
887 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
888 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
893 public void testWriteOnlyData() {
894 Configuration dataConfig = new Configuration();
895 dataConfig.put("writeStart", "0");
896 dataConfig.put("writeValueType", "bit");
897 dataConfig.put("writeType", "coil");
898 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig,
899 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
903 public void testWriteHoldingInt16Data() {
904 Configuration dataConfig = new Configuration();
905 dataConfig.put("writeStart", "0");
906 dataConfig.put("writeValueType", "int16");
907 dataConfig.put("writeType", "holding");
908 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig,
909 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
913 public void testWriteHoldingInt8Data() {
914 Configuration dataConfig = new Configuration();
915 dataConfig.put("writeStart", "0");
916 dataConfig.put("writeValueType", "int8");
917 dataConfig.put("writeType", "holding");
918 testInitGeneric(null, dataConfig, status -> {
919 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
920 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
925 public void testWriteHoldingBitData() {
926 Configuration dataConfig = new Configuration();
927 dataConfig.put("writeStart", "0");
928 dataConfig.put("writeValueType", "bit");
929 dataConfig.put("writeType", "holding");
930 testInitGeneric(null, dataConfig, status -> {
931 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
932 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
937 public void testWriteOnlyDataChildOfEndpoint() {
938 Configuration dataConfig = new Configuration();
939 dataConfig.put("writeStart", "0");
940 dataConfig.put("writeValueType", "bit");
941 dataConfig.put("writeType", "coil");
942 testInitGeneric(null, dataConfig, status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
946 public void testWriteOnlyDataMissingOneParameter() {
947 Configuration dataConfig = new Configuration();
948 dataConfig.put("writeStart", "0");
949 dataConfig.put("writeValueType", "bit");
950 // missing writeType --> error
951 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
952 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
953 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
954 assertThat(status.getDescription(), is(not(equalTo(null))));
959 * OK to omit writeValueType with coils since bit is assumed
962 public void testWriteOnlyDataMissingValueTypeWithCoilParameter() {
963 Configuration dataConfig = new Configuration();
964 dataConfig.put("writeStart", "0");
965 dataConfig.put("writeType", "coil");
966 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig,
967 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
971 public void testWriteOnlyIllegalValueType() {
972 Configuration dataConfig = new Configuration();
973 dataConfig.put("writeStart", "0");
974 dataConfig.put("writeType", "coil");
975 dataConfig.put("writeValueType", "foobar");
976 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
977 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
978 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
983 public void testWriteInvalidType() {
984 Configuration dataConfig = new Configuration();
985 dataConfig.put("writeStart", "0");
986 dataConfig.put("writeType", "foobar");
987 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
988 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
989 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
994 public void testWriteCoilBadStart() {
995 Configuration dataConfig = new Configuration();
996 dataConfig.put("writeStart", "0.4");
997 dataConfig.put("writeType", "coil");
998 testInitGeneric(null, dataConfig, status -> {
999 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1000 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1005 public void testWriteHoldingBadStart() {
1006 Configuration dataConfig = new Configuration();
1007 dataConfig.put("writeStart", "0.4");
1008 dataConfig.put("writeType", "holding");
1009 testInitGeneric(null, dataConfig, status -> {
1010 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1011 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1016 public void testReadHoldingBadStart() {
1017 Configuration dataConfig = new Configuration();
1018 dataConfig.put("readStart", "0.0");
1019 dataConfig.put("readValueType", "int16");
1020 testInitGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, dataConfig, status -> {
1021 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1022 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1027 public void testReadHoldingBadStart2() {
1028 Configuration dataConfig = new Configuration();
1029 dataConfig.put("readStart", "0.0");
1030 dataConfig.put("readValueType", "bit");
1031 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
1032 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1033 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1038 public void testReadHoldingOKStart() {
1039 Configuration dataConfig = new Configuration();
1040 dataConfig.put("readStart", "0.0");
1041 dataConfig.put("readType", "holding");
1042 dataConfig.put("readValueType", "bit");
1043 testInitGeneric(ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, dataConfig,
1044 status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
1048 public void testReadValueTypeIllegal() {
1049 Configuration dataConfig = new Configuration();
1050 dataConfig.put("readStart", "0.0");
1051 dataConfig.put("readType", "holding");
1052 dataConfig.put("readValueType", "foobar");
1053 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
1054 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1055 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1060 public void testWriteOnlyTransform() {
1061 Configuration dataConfig = new Configuration();
1062 // no need to have start, JSON output of transformation defines everything
1063 dataConfig.put("writeTransform", "JS(myJsonTransform.js)");
1064 testInitGeneric(null, dataConfig, status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));
1068 public void testWriteTransformAndStart() {
1069 Configuration dataConfig = new Configuration();
1070 // It's illegal to have start and transform. Just have transform or have all
1071 dataConfig.put("writeStart", "3");
1072 dataConfig.put("writeTransform", "JS(myJsonTransform.js)");
1073 testInitGeneric(ModbusReadFunctionCode.READ_COILS, dataConfig, status -> {
1074 assertThat(status.getStatus(), is(equalTo(ThingStatus.OFFLINE)));
1075 assertThat(status.getStatusDetail(), is(equalTo(ThingStatusDetail.CONFIGURATION_ERROR)));
1080 public void testWriteTransformAndNecessary() {
1081 Configuration dataConfig = new Configuration();
1082 // It's illegal to have start and transform. Just have transform or have all
1083 dataConfig.put("writeStart", "3");
1084 dataConfig.put("writeType", "holding");
1085 dataConfig.put("writeValueType", "int16");
1086 dataConfig.put("writeTransform", "JS(myJsonTransform.js)");
1087 testInitGeneric(null, dataConfig, status -> assertThat(status.getStatus(), is(equalTo(ThingStatus.ONLINE))));