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.internal.handler;
15 import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal.*;
17 import java.math.BigDecimal;
18 import java.time.Duration;
19 import java.time.LocalDateTime;
21 import java.util.concurrent.TimeUnit;
23 import org.apache.commons.lang.NotImplementedException;
24 import org.apache.commons.lang.StringUtils;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.modbus.handler.EndpointNotInitializedException;
28 import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
29 import org.openhab.binding.modbus.handler.ModbusPollerThingHandler;
30 import org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal;
31 import org.openhab.binding.modbus.internal.ModbusConfigurationException;
32 import org.openhab.binding.modbus.internal.Transformation;
33 import org.openhab.binding.modbus.internal.config.ModbusDataConfiguration;
34 import org.openhab.core.library.items.ContactItem;
35 import org.openhab.core.library.items.DateTimeItem;
36 import org.openhab.core.library.items.DimmerItem;
37 import org.openhab.core.library.items.NumberItem;
38 import org.openhab.core.library.items.RollershutterItem;
39 import org.openhab.core.library.items.StringItem;
40 import org.openhab.core.library.items.SwitchItem;
41 import org.openhab.core.library.types.DateTimeType;
42 import org.openhab.core.library.types.DecimalType;
43 import org.openhab.core.library.types.OnOffType;
44 import org.openhab.core.library.types.OpenClosedType;
45 import org.openhab.core.thing.Bridge;
46 import org.openhab.core.thing.ChannelUID;
47 import org.openhab.core.thing.Thing;
48 import org.openhab.core.thing.ThingStatus;
49 import org.openhab.core.thing.ThingStatusDetail;
50 import org.openhab.core.thing.ThingStatusInfo;
51 import org.openhab.core.thing.binding.BaseThingHandler;
52 import org.openhab.core.thing.binding.BridgeHandler;
53 import org.openhab.core.thing.binding.ThingHandlerCallback;
54 import org.openhab.core.types.Command;
55 import org.openhab.core.types.RefreshType;
56 import org.openhab.core.types.State;
57 import org.openhab.core.types.UnDefType;
58 import org.openhab.io.transport.modbus.AsyncModbusFailure;
59 import org.openhab.io.transport.modbus.AsyncModbusReadResult;
60 import org.openhab.io.transport.modbus.AsyncModbusWriteResult;
61 import org.openhab.io.transport.modbus.BitArray;
62 import org.openhab.io.transport.modbus.ModbusBitUtilities;
63 import org.openhab.io.transport.modbus.ModbusCommunicationInterface;
64 import org.openhab.io.transport.modbus.ModbusConstants;
65 import org.openhab.io.transport.modbus.ModbusConstants.ValueType;
66 import org.openhab.io.transport.modbus.ModbusReadFunctionCode;
67 import org.openhab.io.transport.modbus.ModbusReadRequestBlueprint;
68 import org.openhab.io.transport.modbus.ModbusRegisterArray;
69 import org.openhab.io.transport.modbus.ModbusWriteCoilRequestBlueprint;
70 import org.openhab.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
71 import org.openhab.io.transport.modbus.ModbusWriteRequestBlueprint;
72 import org.openhab.io.transport.modbus.exception.ModbusConnectionException;
73 import org.openhab.io.transport.modbus.exception.ModbusTransportException;
74 import org.openhab.io.transport.modbus.json.WriteRequestJsonUtilities;
75 import org.osgi.framework.BundleContext;
76 import org.osgi.framework.FrameworkUtil;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * The {@link ModbusDataThingHandler} is responsible for interpreting polled modbus data, as well as handling openHAB
84 * Thing can be re-initialized by the bridge in case of configuration changes (bridgeStatusChanged).
85 * Because of this, initialize, dispose and all callback methods (onRegisters, onBits, onError, onWriteResponse) are
87 * to avoid data race conditions.
89 * @author Sami Salonen - Initial contribution
92 public class ModbusDataThingHandler extends BaseThingHandler {
94 private final Logger logger = LoggerFactory.getLogger(ModbusDataThingHandler.class);
96 private final BundleContext bundleContext;
98 private static final Duration MIN_STATUS_INFO_UPDATE_INTERVAL = Duration.ofSeconds(1);
99 private static final Map<String, List<Class<? extends State>>> CHANNEL_ID_TO_ACCEPTED_TYPES = new HashMap<>();
102 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_SWITCH,
103 new SwitchItem("").getAcceptedDataTypes());
104 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_CONTACT,
105 new ContactItem("").getAcceptedDataTypes());
106 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_DATETIME,
107 new DateTimeItem("").getAcceptedDataTypes());
108 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_DIMMER,
109 new DimmerItem("").getAcceptedDataTypes());
110 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_NUMBER,
111 new NumberItem("").getAcceptedDataTypes());
112 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_STRING,
113 new StringItem("").getAcceptedDataTypes());
114 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_ROLLERSHUTTER,
115 new RollershutterItem("").getAcceptedDataTypes());
117 // data channels + 4 for read/write last error/success
118 private static final int NUMER_OF_CHANNELS_HINT = CHANNEL_ID_TO_ACCEPTED_TYPES.size() + 4;
121 // If you change the below default/initial values, please update the corresponding values in dispose()
123 private volatile @Nullable ModbusDataConfiguration config;
124 private volatile @Nullable ValueType readValueType;
125 private volatile @Nullable ValueType writeValueType;
126 private volatile @Nullable Transformation readTransformation;
127 private volatile @Nullable Transformation writeTransformation;
128 private volatile Optional<Integer> readIndex = Optional.empty();
129 private volatile Optional<Integer> readSubIndex = Optional.empty();
130 private volatile @Nullable Integer writeStart;
131 private volatile int pollStart;
132 private volatile int slaveId;
133 private volatile @Nullable ModbusReadFunctionCode functionCode;
134 private volatile @Nullable ModbusReadRequestBlueprint readRequest;
135 private volatile long updateUnchangedValuesEveryMillis;
136 private volatile @NonNullByDefault({}) ModbusCommunicationInterface comms;
137 private volatile boolean isWriteEnabled;
138 private volatile boolean isReadEnabled;
139 private volatile boolean writeParametersHavingTransformationOnly;
140 private volatile boolean childOfEndpoint;
141 private volatile @Nullable ModbusPollerThingHandler pollerHandler;
142 private volatile Map<String, ChannelUID> channelCache = new HashMap<>();
143 private volatile Map<ChannelUID, Long> channelLastUpdated = new HashMap<>(NUMER_OF_CHANNELS_HINT);
144 private volatile Map<ChannelUID, State> channelLastState = new HashMap<>(NUMER_OF_CHANNELS_HINT);
146 private volatile LocalDateTime lastStatusInfoUpdate = LocalDateTime.MIN;
147 private volatile ThingStatusInfo statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE,
150 public ModbusDataThingHandler(Thing thing) {
152 this.bundleContext = FrameworkUtil.getBundle(ModbusDataThingHandler.class).getBundleContext();
156 public synchronized void handleCommand(ChannelUID channelUID, Command command) {
157 logger.trace("Thing {} '{}' received command '{}' to channel '{}'", getThing().getUID(), getThing().getLabel(),
158 command, channelUID);
159 ModbusDataConfiguration config = this.config;
160 if (config == null) {
164 if (RefreshType.REFRESH == command) {
165 ModbusPollerThingHandler poller = pollerHandler;
166 if (poller == null) {
167 // Data thing must be child of endpoint, and thus write-only.
168 // There is no data to update
171 // We *schedule* the REFRESH to avoid dead-lock situation where poller is trying update this
172 // data thing with cached data (resulting in deadlock in two synchronized methods: this (handleCommand) and
174 scheduler.schedule(() -> poller.refresh(), 0, TimeUnit.SECONDS);
176 } else if (hasConfigurationError()) {
178 "Thing {} '{}' command '{}' to channel '{}': Thing has configuration error so ignoring the command",
179 getThing().getUID(), getThing().getLabel(), command, channelUID);
181 } else if (!isWriteEnabled) {
183 "Thing {} '{}' command '{}' to channel '{}': no writing configured -> aborting processing command",
184 getThing().getUID(), getThing().getLabel(), command, channelUID);
188 Optional<Command> transformedCommand = transformCommandAndProcessJSON(channelUID, command);
189 if (transformedCommand == null) {
190 // We have, JSON as transform output (which has been processed) or some error. See
191 // transformCommandAndProcessJSON javadoc
195 // We did not have JSON output from the transformation, so writeStart is absolute required. Abort if it is
197 Integer writeStart = this.writeStart;
198 if (writeStart == null) {
200 "Thing {} '{}': not processing command {} since writeStart is missing and transformation output is not a JSON",
201 getThing().getUID(), getThing().getLabel(), command);
205 if (!transformedCommand.isPresent()) {
206 // transformation failed, return
207 logger.warn("Cannot process command {} (of type {}) with channel {} since transformation was unsuccessful",
208 command, command.getClass().getSimpleName(), channelUID);
212 ModbusWriteRequestBlueprint request = requestFromCommand(channelUID, command, config, transformedCommand.get(),
214 if (request == null) {
218 logger.trace("Submitting write task {} to endpoint {}", request, comms.getEndpoint());
219 comms.submitOneTimeWrite(request, this::onWriteResponse, this::handleWriteError);
223 * Transform received command using the transformation.
225 * In case of JSON as transformation output, the output processed using {@link processJsonTransform}.
227 * @param channelUID channel UID corresponding to received command
228 * @param command command to be transformed
229 * @return transformed command. Null is returned with JSON transformation outputs and configuration errors
231 * @see processJsonTransform
233 private @Nullable Optional<Command> transformCommandAndProcessJSON(ChannelUID channelUID, Command command) {
234 String transformOutput;
235 Optional<Command> transformedCommand;
236 Transformation writeTransformation = this.writeTransformation;
237 if (writeTransformation == null || writeTransformation.isIdentityTransform()) {
238 transformedCommand = Optional.of(command);
240 transformOutput = writeTransformation.transform(bundleContext, command.toString());
241 if (transformOutput.contains("[")) {
242 processJsonTransform(command, transformOutput);
244 } else if (writeParametersHavingTransformationOnly) {
245 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
246 "Seems to have writeTransformation but no other write parameters. Since the transformation did not return a JSON for command '%s' (channel %s), this is a configuration error",
247 command, channelUID));
250 transformedCommand = Transformation.tryConvertToCommand(transformOutput);
251 logger.trace("Converted transform output '{}' to command '{}' (type {})", transformOutput,
252 transformedCommand.map(c -> c.toString()).orElse("<conversion failed>"),
253 transformedCommand.map(c -> c.getClass().getName()).orElse("<conversion failed>"));
256 return transformedCommand;
259 private @Nullable ModbusWriteRequestBlueprint requestFromCommand(ChannelUID channelUID, Command origCommand,
260 ModbusDataConfiguration config, Command transformedCommand, Integer writeStart) {
261 ModbusWriteRequestBlueprint request;
262 boolean writeMultiple = config.isWriteMultipleEvenWithSingleRegisterOrCoil();
263 String writeType = config.getWriteType();
264 if (writeType == null) {
267 if (writeType.equals(WRITE_TYPE_COIL)) {
268 Optional<Boolean> commandAsBoolean = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
269 if (!commandAsBoolean.isPresent()) {
271 "Cannot process command {} with channel {} since command is not OnOffType, OpenClosedType or Decimal trying to write to coil. Do not know how to convert to 0/1. Transformed command was '{}'",
272 origCommand, channelUID, transformedCommand);
275 boolean data = commandAsBoolean.get();
276 request = new ModbusWriteCoilRequestBlueprint(slaveId, writeStart, data, writeMultiple,
277 config.getWriteMaxTries());
278 } else if (writeType.equals(WRITE_TYPE_HOLDING)) {
279 ValueType writeValueType = this.writeValueType;
280 if (writeValueType == null) {
281 // Should not happen in practice, since we are not in configuration error (checked above)
282 // This will make compiler happy anyways with the null checks
283 logger.warn("Received command but write value type not set! Ignoring command");
286 ModbusRegisterArray data = ModbusBitUtilities.commandToRegisters(transformedCommand, writeValueType);
287 writeMultiple = writeMultiple || data.size() > 1;
288 request = new ModbusWriteRegisterRequestBlueprint(slaveId, writeStart, data, writeMultiple,
289 config.getWriteMaxTries());
291 // Should not happen! This method is not called in case configuration errors and writeType is validated
292 // already in initialization (validateAndParseWriteParameters).
293 // We keep this here for future-proofing the code (new writeType values)
294 throw new NotImplementedException(String.format(
295 "writeType does not equal %s or %s and thus configuration is invalid. Should not end up this far with configuration error.",
296 WRITE_TYPE_COIL, WRITE_TYPE_HOLDING));
301 private void processJsonTransform(Command command, String transformOutput) {
302 ModbusCommunicationInterface localComms = this.comms;
303 if (localComms == null) {
306 Collection<ModbusWriteRequestBlueprint> requests;
308 requests = WriteRequestJsonUtilities.fromJson(slaveId, transformOutput);
309 } catch (IllegalArgumentException | IllegalStateException e) {
311 "Thing {} '{}' could handle transformation result '{}'. Original command {}. Error details follow",
312 getThing().getUID(), getThing().getLabel(), transformOutput, command, e);
316 requests.stream().forEach(request -> {
317 logger.trace("Submitting write request: {} to endpoint {} (based from transformation {})", request,
318 localComms.getEndpoint(), transformOutput);
319 localComms.submitOneTimeWrite(request, this::onWriteResponse, this::handleWriteError);
324 public synchronized void initialize() {
325 // Initialize the thing. If done set status to ONLINE to indicate proper working.
326 // Long running initialization should be done asynchronously in background.
328 logger.trace("initialize() of thing {} '{}' starting", thing.getUID(), thing.getLabel());
329 ModbusDataConfiguration localConfig = config = getConfigAs(ModbusDataConfiguration.class);
330 updateUnchangedValuesEveryMillis = localConfig.getUpdateUnchangedValuesEveryMillis();
331 Bridge bridge = getBridge();
332 if (bridge == null || !bridge.getStatus().equals(ThingStatus.ONLINE)) {
333 logger.debug("Thing {} '{}' has no bridge or it is not online", getThing().getUID(),
334 getThing().getLabel());
335 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, "No online bridge");
338 BridgeHandler bridgeHandler = bridge.getHandler();
339 if (bridgeHandler == null) {
340 logger.warn("Bridge {} '{}' has no handler.", bridge.getUID(), bridge.getLabel());
341 String errmsg = String.format("Bridge %s '%s' configuration incomplete or with errors", bridge.getUID(),
343 throw new ModbusConfigurationException(errmsg);
345 if (bridgeHandler instanceof ModbusEndpointThingHandler) {
346 // Write-only thing, parent is endpoint
347 ModbusEndpointThingHandler endpointHandler = (ModbusEndpointThingHandler) bridgeHandler;
348 slaveId = endpointHandler.getSlaveId();
349 comms = endpointHandler.getCommunicationInterface();
350 childOfEndpoint = true;
354 ModbusPollerThingHandler localPollerHandler = (ModbusPollerThingHandler) bridgeHandler;
355 pollerHandler = localPollerHandler;
356 ModbusReadRequestBlueprint localReadRequest = localPollerHandler.getRequest();
357 if (localReadRequest == null) {
359 "Poller {} '{}' has no read request -- configuration is changing or bridge having invalid configuration?",
360 bridge.getUID(), bridge.getLabel());
361 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
362 String.format("Poller %s '%s' has no poll task", bridge.getUID(), bridge.getLabel()));
365 readRequest = localReadRequest;
366 slaveId = localReadRequest.getUnitID();
367 functionCode = localReadRequest.getFunctionCode();
368 comms = localPollerHandler.getCommunicationInterface();
369 pollStart = localReadRequest.getReference();
370 childOfEndpoint = false;
372 validateAndParseReadParameters(localConfig);
373 validateAndParseWriteParameters(localConfig);
374 validateMustReadOrWrite();
376 updateStatusIfChanged(ThingStatus.ONLINE);
377 } catch (ModbusConfigurationException | EndpointNotInitializedException e) {
378 logger.debug("Thing {} '{}' initialization error: {}", getThing().getUID(), getThing().getLabel(),
380 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
382 logger.trace("initialize() of thing {} '{}' finished", thing.getUID(), thing.getLabel());
387 public synchronized void dispose() {
389 readValueType = null;
390 writeValueType = null;
391 readTransformation = null;
392 writeTransformation = null;
393 readIndex = Optional.empty();
394 readSubIndex = Optional.empty();
401 isWriteEnabled = false;
402 isReadEnabled = false;
403 writeParametersHavingTransformationOnly = false;
404 childOfEndpoint = false;
405 pollerHandler = null;
406 channelCache = new HashMap<>();
407 lastStatusInfoUpdate = LocalDateTime.MIN;
408 statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE, null);
409 channelLastUpdated = new HashMap<>(NUMER_OF_CHANNELS_HINT);
410 channelLastState = new HashMap<>(NUMER_OF_CHANNELS_HINT);
414 public synchronized void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
415 logger.debug("bridgeStatusChanged for {}. Reseting handler", this.getThing().getUID());
420 private boolean hasConfigurationError() {
421 ThingStatusInfo statusInfo = getThing().getStatusInfo();
422 return statusInfo.getStatus() == ThingStatus.OFFLINE
423 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
426 private void validateMustReadOrWrite() throws ModbusConfigurationException {
427 if (!isReadEnabled && !isWriteEnabled) {
428 throw new ModbusConfigurationException("Should try to read or write data!");
432 private void validateAndParseReadParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
433 ModbusReadFunctionCode functionCode = this.functionCode;
434 boolean readingDiscreteOrCoil = functionCode == ModbusReadFunctionCode.READ_COILS
435 || functionCode == ModbusReadFunctionCode.READ_INPUT_DISCRETES;
436 boolean readStartMissing = StringUtils.isBlank(config.getReadStart());
437 boolean readValueTypeMissing = StringUtils.isBlank(config.getReadValueType());
439 if (childOfEndpoint && readRequest == null) {
440 if (!readStartMissing || !readValueTypeMissing) {
441 String errmsg = String.format(
442 "Thing %s readStart=%s, and readValueType=%s were specified even though the data thing is child of endpoint (that is, write-only)!",
443 getThing().getUID(), config.getReadStart(), config.getReadValueType());
444 throw new ModbusConfigurationException(errmsg);
448 // we assume readValueType=bit by default if it is missing
449 boolean allMissingOrAllPresent = (readStartMissing && readValueTypeMissing)
450 || (!readStartMissing && (!readValueTypeMissing || readingDiscreteOrCoil));
451 if (!allMissingOrAllPresent) {
452 String errmsg = String.format(
453 "Thing %s readStart=%s, and readValueType=%s should be all present or all missing!",
454 getThing().getUID(), config.getReadStart(), config.getReadValueType());
455 throw new ModbusConfigurationException(errmsg);
456 } else if (!readStartMissing) {
457 // all read values are present
458 isReadEnabled = true;
459 if (readingDiscreteOrCoil && readValueTypeMissing) {
460 readValueType = ModbusConstants.ValueType.BIT;
463 readValueType = ValueType.fromConfigValue(config.getReadValueType());
464 } catch (IllegalArgumentException e) {
465 String errmsg = String.format("Thing %s readValueType=%s is invalid!", getThing().getUID(),
466 config.getReadValueType());
467 throw new ModbusConfigurationException(errmsg);
471 if (readingDiscreteOrCoil && !ModbusConstants.ValueType.BIT.equals(readValueType)) {
472 String errmsg = String.format(
473 "Thing %s invalid readValueType: Only readValueType='%s' (or undefined) supported with coils or discrete inputs. Value type was: %s",
474 getThing().getUID(), ModbusConstants.ValueType.BIT, config.getReadValueType());
475 throw new ModbusConfigurationException(errmsg);
478 isReadEnabled = false;
482 String readStart = config.getReadStart();
483 if (readStart == null) {
484 throw new ModbusConfigurationException(
485 String.format("Thing %s invalid readStart: %s", getThing().getUID(), config.getReadStart()));
487 String[] readParts = readStart.split("\\.", 2);
489 readIndex = Optional.of(Integer.parseInt(readParts[0]));
490 if (readParts.length == 2) {
491 readSubIndex = Optional.of(Integer.parseInt(readParts[1]));
493 readSubIndex = Optional.empty();
495 } catch (IllegalArgumentException e) {
496 String errmsg = String.format("Thing %s invalid readStart: %s", getThing().getUID(),
497 config.getReadStart());
498 throw new ModbusConfigurationException(errmsg);
501 readTransformation = new Transformation(config.getReadTransform());
505 private void validateAndParseWriteParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
506 boolean writeTypeMissing = StringUtils.isBlank(config.getWriteType());
507 boolean writeStartMissing = StringUtils.isBlank(config.getWriteStart());
508 boolean writeValueTypeMissing = StringUtils.isBlank(config.getWriteValueType());
509 boolean writeTransformationMissing = StringUtils.isBlank(config.getWriteTransform());
510 writeTransformation = new Transformation(config.getWriteTransform());
511 boolean writingCoil = WRITE_TYPE_COIL.equals(config.getWriteType());
512 writeParametersHavingTransformationOnly = (writeTypeMissing && writeStartMissing && writeValueTypeMissing
513 && !writeTransformationMissing);
514 boolean allMissingOrAllPresentOrOnlyNonDefaultTransform = //
515 // read-only thing, no write specified
516 (writeTypeMissing && writeStartMissing && writeValueTypeMissing)
517 // mandatory write parameters provided. With coils one can drop value type
518 || (!writeTypeMissing && !writeStartMissing && (!writeValueTypeMissing || writingCoil))
519 // only transformation provided
520 || writeParametersHavingTransformationOnly;
521 if (!allMissingOrAllPresentOrOnlyNonDefaultTransform) {
522 String errmsg = String.format(
523 "writeType=%s, writeStart=%s, and writeValueType=%s should be all present, or all missing! Alternatively, you can provide just writeTransformation, and use transformation returning JSON.",
524 config.getWriteType(), config.getWriteStart(), config.getWriteValueType());
525 throw new ModbusConfigurationException(errmsg);
526 } else if (!writeTypeMissing || writeParametersHavingTransformationOnly) {
527 isWriteEnabled = true;
528 // all write values are present
529 if (!writeParametersHavingTransformationOnly && !WRITE_TYPE_HOLDING.equals(config.getWriteType())
530 && !WRITE_TYPE_COIL.equals(config.getWriteType())) {
531 String errmsg = String.format("Invalid writeType=%s. Expecting %s or %s!", config.getWriteType(),
532 WRITE_TYPE_HOLDING, WRITE_TYPE_COIL);
533 throw new ModbusConfigurationException(errmsg);
535 final ValueType localWriteValueType;
536 if (writeParametersHavingTransformationOnly) {
537 // Placeholder for further checks
538 localWriteValueType = writeValueType = ModbusConstants.ValueType.INT16;
539 } else if (writingCoil && writeValueTypeMissing) {
540 localWriteValueType = writeValueType = ModbusConstants.ValueType.BIT;
543 localWriteValueType = writeValueType = ValueType.fromConfigValue(config.getWriteValueType());
544 } catch (IllegalArgumentException e) {
545 String errmsg = String.format("Invalid writeValueType=%s!", config.getWriteValueType());
546 throw new ModbusConfigurationException(errmsg);
550 if (writingCoil && !ModbusConstants.ValueType.BIT.equals(localWriteValueType)) {
551 String errmsg = String.format(
552 "Invalid writeValueType: Only writeValueType='%s' (or undefined) supported with coils. Value type was: %s",
553 ModbusConstants.ValueType.BIT, config.getWriteValueType());
554 throw new ModbusConfigurationException(errmsg);
555 } else if (!writingCoil && localWriteValueType.getBits() < 16) {
556 // trying to write holding registers with < 16 bit value types. Not supported
557 String errmsg = String.format(
558 "Invalid writeValueType: Only writeValueType with larger or equal to 16 bits are supported holding registers. Value type was: %s",
559 config.getWriteValueType());
560 throw new ModbusConfigurationException(errmsg);
564 if (!writeParametersHavingTransformationOnly) {
565 String localWriteStart = config.getWriteStart();
566 if (localWriteStart == null) {
567 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
568 config.getWriteStart());
569 throw new ModbusConfigurationException(errmsg);
571 writeStart = Integer.parseInt(localWriteStart.trim());
573 } catch (IllegalArgumentException e) {
574 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
575 config.getWriteStart());
576 throw new ModbusConfigurationException(errmsg);
579 isWriteEnabled = false;
583 private void validateReadIndex() throws ModbusConfigurationException {
585 ModbusReadRequestBlueprint readRequest = this.readRequest;
586 ValueType readValueType = this.readValueType;
587 if (!readIndex.isPresent() || readRequest == null) {
590 assert readValueType != null;
591 // bits represented by the value type, e.g. int32 -> 32
592 int valueTypeBitCount = readValueType.getBits();
594 switch (readRequest.getFunctionCode()) {
595 case READ_INPUT_REGISTERS:
596 case READ_MULTIPLE_REGISTERS:
597 dataElementBits = 16;
600 case READ_INPUT_DISCRETES:
604 throw new IllegalStateException(readRequest.getFunctionCode().toString());
607 boolean bitQuery = dataElementBits == 1;
608 if (bitQuery && readSubIndex.isPresent()) {
609 String errmsg = String.format("readStart=X.Y is not allowed to be used with coils or discrete inputs!");
610 throw new ModbusConfigurationException(errmsg);
613 if (valueTypeBitCount >= 16 && readSubIndex.isPresent()) {
614 String errmsg = String
615 .format("readStart=X.Y is not allowed to be used with value types larger than 16bit!");
616 throw new ModbusConfigurationException(errmsg);
617 } else if (!bitQuery && valueTypeBitCount < 16 && !readSubIndex.isPresent()) {
618 String errmsg = String.format("readStart=X.Y must be used with value types less than 16bit!");
619 throw new ModbusConfigurationException(errmsg);
620 } else if (readSubIndex.isPresent() && (readSubIndex.get() + 1) * valueTypeBitCount > 16) {
621 // the sub index Y (in X.Y) is above the register limits
622 String errmsg = String.format("readStart=X.Y, the value Y is too large");
623 throw new ModbusConfigurationException(errmsg);
626 // Determine bit positions polled, both start and end inclusive
627 int pollStartBitIndex = readRequest.getReference() * dataElementBits;
628 int pollEndBitIndex = pollStartBitIndex + readRequest.getDataLength() * dataElementBits - 1;
630 // Determine bit positions read, both start and end inclusive
631 int readStartBitIndex = readIndex.get() * dataElementBits + readSubIndex.orElse(0) * valueTypeBitCount;
632 int readEndBitIndex = readStartBitIndex + valueTypeBitCount - 1;
634 if (readStartBitIndex < pollStartBitIndex || readEndBitIndex > pollEndBitIndex) {
635 String errmsg = String.format(
636 "Out-of-bounds: Poller is reading from index %d to %d (inclusive) but this thing configured to read '%s' starting from element %d. Exceeds polled data bounds.",
637 pollStartBitIndex / dataElementBits, pollEndBitIndex / dataElementBits, readValueType,
639 throw new ModbusConfigurationException(errmsg);
643 private boolean containsOnOff(List<Class<? extends State>> channelAcceptedDataTypes) {
644 return channelAcceptedDataTypes.stream().anyMatch(clz -> {
645 return clz.equals(OnOffType.class);
649 private boolean containsOpenClosed(List<Class<? extends State>> acceptedDataTypes) {
650 return acceptedDataTypes.stream().anyMatch(clz -> {
651 return clz.equals(OpenClosedType.class);
655 public synchronized void onReadResult(AsyncModbusReadResult result) {
656 result.getRegisters().ifPresent(registers -> onRegisters(result.getRequest(), registers));
657 result.getBits().ifPresent(bits -> onBits(result.getRequest(), bits));
660 public synchronized void handleReadError(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
661 onError(failure.getRequest(), failure.getCause());
664 public synchronized void handleWriteError(AsyncModbusFailure<ModbusWriteRequestBlueprint> failure) {
665 onError(failure.getRequest(), failure.getCause());
668 private synchronized void onRegisters(ModbusReadRequestBlueprint request, ModbusRegisterArray registers) {
669 if (hasConfigurationError()) {
671 } else if (!isReadEnabled) {
674 ValueType readValueType = this.readValueType;
675 if (readValueType == null) {
681 // e.g. with bit, extractIndex=4 means 5th bit (from right) ("10.4" -> 5th bit of register 10, "10.4" -> 5th bit
683 // bit of second register)
684 // e.g. with 8bit integer, extractIndex=3 means high byte of second register
686 // with <16 bit types, this is the index of the N'th 1-bit/8-bit item. Each register has 16/2 items,
688 // with >=16 bit types, this is index of first register
690 if (readValueType.getBits() >= 16) {
691 // Invariant, checked in initialize
692 assert readSubIndex.orElse(0) == 0;
693 extractIndex = readIndex.get() - pollStart;
695 int subIndex = readSubIndex.orElse(0);
696 int itemsPerRegister = 16 / readValueType.getBits();
697 extractIndex = (readIndex.get() - pollStart) * itemsPerRegister + subIndex;
699 numericState = ModbusBitUtilities.extractStateFromRegisters(registers, extractIndex, readValueType)
700 .map(state -> (State) state).orElse(UnDefType.UNDEF);
701 boolean boolValue = !numericState.equals(DecimalType.ZERO);
702 Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
704 "Thing {} channels updated: {}. readValueType={}, readIndex={}, readSubIndex(or 0)={}, extractIndex={} -> numeric value {} and boolValue={}. Registers {} for request {}",
705 thing.getUID(), values, readValueType, readIndex, readSubIndex.orElse(0), extractIndex, numericState,
706 boolValue, registers, request);
709 private synchronized void onBits(ModbusReadRequestBlueprint request, BitArray bits) {
710 if (hasConfigurationError()) {
712 } else if (!isReadEnabled) {
715 boolean boolValue = bits.getBit(readIndex.get() - pollStart);
716 DecimalType numericState = boolValue ? new DecimalType(BigDecimal.ONE) : DecimalType.ZERO;
717 Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
719 "Thing {} channels updated: {}. readValueType={}, readIndex={} -> numeric value {} and boolValue={}. Bits {} for request {}",
720 thing.getUID(), values, readValueType, readIndex, numericState, boolValue, bits, request);
723 private synchronized void onError(ModbusReadRequestBlueprint request, Exception error) {
724 if (hasConfigurationError()) {
726 } else if (!isReadEnabled) {
729 if (error instanceof ModbusConnectionException) {
730 logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
731 error.getClass().getSimpleName(), error.toString());
732 } else if (error instanceof ModbusTransportException) {
733 logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
734 error.getClass().getSimpleName(), error.toString());
737 "Thing {} '{}' had {} error on read: {} (message: {}). Stack trace follows since this is unexpected error.",
738 getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
739 error.getMessage(), error);
741 Map<ChannelUID, State> states = new HashMap<>();
742 ChannelUID lastReadErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_ERROR);
743 if (isLinked(lastReadErrorUID)) {
744 states.put(lastReadErrorUID, new DateTimeType());
747 synchronized (this) {
749 states.forEach((uid, state) -> {
750 tryUpdateState(uid, state);
753 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
754 String.format("Error (%s) with read. Request: %s. Description: %s. Message: %s",
755 error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
759 private synchronized void onError(ModbusWriteRequestBlueprint request, Exception error) {
760 if (hasConfigurationError()) {
762 } else if (!isWriteEnabled) {
765 if (error instanceof ModbusConnectionException) {
766 logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
767 error.getClass().getSimpleName(), error.toString());
768 } else if (error instanceof ModbusTransportException) {
769 logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
770 error.getClass().getSimpleName(), error.toString());
773 "Thing {} '{}' had {} error on write: {} (message: {}). Stack trace follows since this is unexpected error.",
774 getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
775 error.getMessage(), error);
777 Map<ChannelUID, State> states = new HashMap<>();
778 ChannelUID lastWriteErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_ERROR);
779 if (isLinked(lastWriteErrorUID)) {
780 states.put(lastWriteErrorUID, new DateTimeType());
783 synchronized (this) {
785 states.forEach((uid, state) -> {
786 tryUpdateState(uid, state);
789 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
790 String.format("Error (%s) with write. Request: %s. Description: %s. Message: %s",
791 error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
795 public synchronized void onWriteResponse(AsyncModbusWriteResult result) {
796 if (hasConfigurationError()) {
798 } else if (!isWriteEnabled) {
801 logger.debug("Successful write, matching request {}", result.getRequest());
802 updateStatusIfChanged(ThingStatus.ONLINE);
803 ChannelUID lastWriteSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_SUCCESS);
804 if (isLinked(lastWriteSuccessUID)) {
805 updateState(lastWriteSuccessUID, new DateTimeType());
810 * Update linked channels
812 * @param numericState numeric state corresponding to polled data (or UNDEF with floating point NaN or infinity)
813 * @param boolValue boolean value corresponding to polled data
814 * @return updated channel data
816 private Map<ChannelUID, State> processUpdatedValue(State numericState, boolean boolValue) {
817 Transformation localReadTransformation = readTransformation;
818 if (localReadTransformation == null) {
819 // We should always have transformation available if thing is initalized properly
820 logger.trace("No transformation available, aborting processUpdatedValue");
821 return Collections.emptyMap();
823 Map<ChannelUID, State> states = new HashMap<>();
824 CHANNEL_ID_TO_ACCEPTED_TYPES.keySet().stream().forEach(channelId -> {
825 ChannelUID channelUID = getChannelUID(channelId);
826 if (!isLinked(channelUID)) {
829 List<Class<? extends State>> acceptedDataTypes = CHANNEL_ID_TO_ACCEPTED_TYPES.get(channelId);
830 if (acceptedDataTypes.isEmpty()) {
835 if (containsOnOff(acceptedDataTypes)) {
836 boolLikeState = boolValue ? OnOffType.ON : OnOffType.OFF;
837 } else if (containsOpenClosed(acceptedDataTypes)) {
838 boolLikeState = boolValue ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
840 boolLikeState = null;
843 State transformedState;
844 if (localReadTransformation.isIdentityTransform()) {
845 if (boolLikeState != null) {
846 // A bit of smartness for ON/OFF and OPEN/CLOSED with boolean like items
847 transformedState = boolLikeState;
849 // Numeric states always go through transformation. This allows value of 17.5 to be
851 // 17.5% with percent types (instead of raising error)
852 transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
856 transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
860 if (transformedState != null) {
862 "Channel {} will be updated to '{}' (type {}). Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}",
863 channelId, transformedState, transformedState.getClass().getSimpleName(), numericState,
864 readValueType, boolValue,
865 localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
866 states.put(channelUID, transformedState);
868 String types = StringUtils.join(acceptedDataTypes.stream().map(cls -> cls.getSimpleName()).toArray(),
871 "Channel {} will not be updated since transformation was unsuccessful. Channel is expecting the following data types [{}]. Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}",
872 channelId, types, numericState, readValueType, boolValue,
873 localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
877 ChannelUID lastReadSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_SUCCESS);
878 if (isLinked(lastReadSuccessUID)) {
879 states.put(lastReadSuccessUID, new DateTimeType());
881 updateExpiredChannels(states);
885 private void updateExpiredChannels(Map<ChannelUID, State> states) {
886 synchronized (this) {
887 updateStatusIfChanged(ThingStatus.ONLINE);
888 long now = System.currentTimeMillis();
889 // Update channels that have not been updated in a while, or when their values has changed
890 states.forEach((uid, state) -> updateExpiredChannel(now, uid, state));
891 channelLastState = states;
895 // since lastState can be null, and "lastState == null" in conditional is not useless
896 @SuppressWarnings("null")
897 private void updateExpiredChannel(long now, ChannelUID uid, State state) {
899 State lastState = channelLastState.get(uid);
900 long lastUpdatedMillis = channelLastUpdated.getOrDefault(uid, 0L);
901 long millisSinceLastUpdate = now - lastUpdatedMillis;
902 if (lastUpdatedMillis <= 0L || lastState == null || updateUnchangedValuesEveryMillis <= 0L
903 || millisSinceLastUpdate > updateUnchangedValuesEveryMillis || !lastState.equals(state)) {
904 tryUpdateState(uid, state);
905 channelLastUpdated.put(uid, now);
909 private void tryUpdateState(ChannelUID uid, State state) {
911 updateState(uid, state);
912 } catch (IllegalArgumentException e) {
913 logger.warn("Error updating state '{}' (type {}) to channel {}: {} {}", state,
914 Optional.ofNullable(state).map(s -> s.getClass().getName()).orElse("null"), uid,
915 e.getClass().getName(), e.getMessage());
919 private ChannelUID getChannelUID(String channelID) {
921 .requireNonNull(channelCache.computeIfAbsent(channelID, id -> new ChannelUID(getThing().getUID(), id)));
924 private void updateStatusIfChanged(ThingStatus status) {
925 updateStatusIfChanged(status, ThingStatusDetail.NONE, null);
928 private void updateStatusIfChanged(ThingStatus status, ThingStatusDetail statusDetail,
929 @Nullable String description) {
930 ThingStatusInfo newStatusInfo = new ThingStatusInfo(status, statusDetail, description);
931 Duration durationSinceLastUpdate = Duration.between(lastStatusInfoUpdate, LocalDateTime.now());
932 boolean intervalElapsed = MIN_STATUS_INFO_UPDATE_INTERVAL.minus(durationSinceLastUpdate).isNegative();
933 if (statusInfo.getStatus() == ThingStatus.UNKNOWN || !statusInfo.equals(newStatusInfo) || intervalElapsed) {
934 statusInfo = newStatusInfo;
935 lastStatusInfoUpdate = LocalDateTime.now();
936 updateStatus(newStatusInfo);
941 * Update status using pre-constructed ThingStatusInfo
943 * Implementation adapted from BaseThingHandler updateStatus implementations
945 * @param statusInfo new status info
947 protected void updateStatus(ThingStatusInfo statusInfo) {
948 synchronized (this) {
949 ThingHandlerCallback callback = getCallback();
950 if (callback != null) {
951 callback.statusUpdated(this.thing, statusInfo);
953 logger.warn("Handler {} tried updating the thing status although the handler was already disposed.",
954 this.getClass().getSimpleName());