2 * Copyright (c) 2010-2021 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;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicReference;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.modbus.handler.EndpointNotInitializedException;
33 import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
34 import org.openhab.binding.modbus.handler.ModbusPollerThingHandler;
35 import org.openhab.binding.modbus.internal.CascadedValueTransformationImpl;
36 import org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal;
37 import org.openhab.binding.modbus.internal.ModbusConfigurationException;
38 import org.openhab.binding.modbus.internal.SingleValueTransformation;
39 import org.openhab.binding.modbus.internal.ValueTransformation;
40 import org.openhab.binding.modbus.internal.config.ModbusDataConfiguration;
41 import org.openhab.core.io.transport.modbus.AsyncModbusFailure;
42 import org.openhab.core.io.transport.modbus.AsyncModbusReadResult;
43 import org.openhab.core.io.transport.modbus.AsyncModbusWriteResult;
44 import org.openhab.core.io.transport.modbus.BitArray;
45 import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
46 import org.openhab.core.io.transport.modbus.ModbusCommunicationInterface;
47 import org.openhab.core.io.transport.modbus.ModbusConstants;
48 import org.openhab.core.io.transport.modbus.ModbusConstants.ValueType;
49 import org.openhab.core.io.transport.modbus.ModbusReadFunctionCode;
50 import org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint;
51 import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
52 import org.openhab.core.io.transport.modbus.ModbusWriteCoilRequestBlueprint;
53 import org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
54 import org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint;
55 import org.openhab.core.io.transport.modbus.exception.ModbusConnectionException;
56 import org.openhab.core.io.transport.modbus.exception.ModbusTransportException;
57 import org.openhab.core.io.transport.modbus.json.WriteRequestJsonUtilities;
58 import org.openhab.core.library.items.ContactItem;
59 import org.openhab.core.library.items.DateTimeItem;
60 import org.openhab.core.library.items.DimmerItem;
61 import org.openhab.core.library.items.NumberItem;
62 import org.openhab.core.library.items.RollershutterItem;
63 import org.openhab.core.library.items.StringItem;
64 import org.openhab.core.library.items.SwitchItem;
65 import org.openhab.core.library.types.DateTimeType;
66 import org.openhab.core.library.types.DecimalType;
67 import org.openhab.core.library.types.OnOffType;
68 import org.openhab.core.library.types.OpenClosedType;
69 import org.openhab.core.thing.Bridge;
70 import org.openhab.core.thing.ChannelUID;
71 import org.openhab.core.thing.Thing;
72 import org.openhab.core.thing.ThingStatus;
73 import org.openhab.core.thing.ThingStatusDetail;
74 import org.openhab.core.thing.ThingStatusInfo;
75 import org.openhab.core.thing.binding.BaseThingHandler;
76 import org.openhab.core.thing.binding.BridgeHandler;
77 import org.openhab.core.thing.binding.ThingHandlerCallback;
78 import org.openhab.core.types.Command;
79 import org.openhab.core.types.RefreshType;
80 import org.openhab.core.types.State;
81 import org.openhab.core.types.UnDefType;
82 import org.openhab.core.util.HexUtils;
83 import org.osgi.framework.BundleContext;
84 import org.osgi.framework.FrameworkUtil;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
89 * The {@link ModbusDataThingHandler} is responsible for interpreting polled modbus data, as well as handling openHAB
92 * Thing can be re-initialized by the bridge in case of configuration changes (bridgeStatusChanged).
93 * Because of this, initialize, dispose and all callback methods (onRegisters, onBits, onError, onWriteResponse) are
95 * to avoid data race conditions.
97 * @author Sami Salonen - Initial contribution
100 public class ModbusDataThingHandler extends BaseThingHandler {
102 private final Logger logger = LoggerFactory.getLogger(ModbusDataThingHandler.class);
104 private final BundleContext bundleContext;
106 private static final Duration MIN_STATUS_INFO_UPDATE_INTERVAL = Duration.ofSeconds(1);
107 private static final Map<String, List<Class<? extends State>>> CHANNEL_ID_TO_ACCEPTED_TYPES = new HashMap<>();
110 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_SWITCH,
111 new SwitchItem("").getAcceptedDataTypes());
112 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_CONTACT,
113 new ContactItem("").getAcceptedDataTypes());
114 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_DATETIME,
115 new DateTimeItem("").getAcceptedDataTypes());
116 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_DIMMER,
117 new DimmerItem("").getAcceptedDataTypes());
118 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_NUMBER,
119 new NumberItem("").getAcceptedDataTypes());
120 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_STRING,
121 new StringItem("").getAcceptedDataTypes());
122 CHANNEL_ID_TO_ACCEPTED_TYPES.put(ModbusBindingConstantsInternal.CHANNEL_ROLLERSHUTTER,
123 new RollershutterItem("").getAcceptedDataTypes());
125 // data channels + 4 for read/write last error/success
126 private static final int NUMER_OF_CHANNELS_HINT = CHANNEL_ID_TO_ACCEPTED_TYPES.size() + 4;
129 // If you change the below default/initial values, please update the corresponding values in dispose()
131 private volatile @Nullable ModbusDataConfiguration config;
132 private volatile @Nullable ValueType readValueType;
133 private volatile @Nullable ValueType writeValueType;
134 private volatile @Nullable CascadedValueTransformationImpl readTransformation;
135 private volatile @Nullable CascadedValueTransformationImpl writeTransformation;
136 private volatile Optional<Integer> readIndex = Optional.empty();
137 private volatile Optional<Integer> readSubIndex = Optional.empty();
138 private volatile Optional<Integer> writeStart = Optional.empty();
139 private volatile Optional<Integer> writeSubIndex = Optional.empty();
140 private volatile int pollStart;
141 private volatile int slaveId;
142 private volatile @Nullable ModbusReadFunctionCode functionCode;
143 private volatile @Nullable ModbusReadRequestBlueprint readRequest;
144 private volatile long updateUnchangedValuesEveryMillis;
145 private volatile @NonNullByDefault({}) ModbusCommunicationInterface comms;
146 private volatile boolean isWriteEnabled;
147 private volatile boolean isReadEnabled;
148 private volatile boolean writeParametersHavingTransformationOnly;
149 private volatile boolean childOfEndpoint;
150 private volatile @Nullable ModbusPollerThingHandler pollerHandler;
151 private volatile Map<String, ChannelUID> channelCache = new HashMap<>();
152 private volatile Map<ChannelUID, Long> channelLastUpdated = new HashMap<>(NUMER_OF_CHANNELS_HINT);
153 private volatile Map<ChannelUID, State> channelLastState = new HashMap<>(NUMER_OF_CHANNELS_HINT);
155 private volatile LocalDateTime lastStatusInfoUpdate = LocalDateTime.MIN;
156 private volatile ThingStatusInfo statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE,
159 public ModbusDataThingHandler(Thing thing) {
161 this.bundleContext = FrameworkUtil.getBundle(ModbusDataThingHandler.class).getBundleContext();
165 public synchronized void handleCommand(ChannelUID channelUID, Command command) {
166 logger.trace("Thing {} '{}' received command '{}' to channel '{}'", getThing().getUID(), getThing().getLabel(),
167 command, channelUID);
168 ModbusDataConfiguration config = this.config;
169 if (config == null) {
173 if (RefreshType.REFRESH == command) {
174 ModbusPollerThingHandler poller = pollerHandler;
175 if (poller == null) {
176 // Data thing must be child of endpoint, and thus write-only.
177 // There is no data to update
180 // We *schedule* the REFRESH to avoid dead-lock situation where poller is trying update this
181 // data thing with cached data (resulting in deadlock in two synchronized methods: this (handleCommand) and
183 scheduler.schedule(() -> poller.refresh(), 0, TimeUnit.SECONDS);
185 } else if (hasConfigurationError()) {
187 "Thing {} '{}' command '{}' to channel '{}': Thing has configuration error so ignoring the command",
188 getThing().getUID(), getThing().getLabel(), command, channelUID);
190 } else if (!isWriteEnabled) {
192 "Thing {} '{}' command '{}' to channel '{}': no writing configured -> aborting processing command",
193 getThing().getUID(), getThing().getLabel(), command, channelUID);
197 Optional<Command> transformedCommand = transformCommandAndProcessJSON(channelUID, command);
198 if (transformedCommand == null) {
199 // We have, JSON as transform output (which has been processed) or some error. See
200 // transformCommandAndProcessJSON javadoc
204 // We did not have JSON output from the transformation, so writeStart is absolute required. Abort if it is
206 Optional<Integer> writeStart = this.writeStart;
207 if (writeStart.isEmpty()) {
209 "Thing {} '{}': not processing command {} since writeStart is missing and transformation output is not a JSON",
210 getThing().getUID(), getThing().getLabel(), command);
214 if (!transformedCommand.isPresent()) {
215 // transformation failed, return
216 logger.warn("Cannot process command {} (of type {}) with channel {} since transformation was unsuccessful",
217 command, command.getClass().getSimpleName(), channelUID);
221 ModbusWriteRequestBlueprint request = requestFromCommand(channelUID, command, config, transformedCommand.get(),
223 if (request == null) {
227 logger.trace("Submitting write task {} to endpoint {}", request, comms.getEndpoint());
228 comms.submitOneTimeWrite(request, this::onWriteResponse, this::handleWriteError);
232 * Transform received command using the transformation.
234 * In case of JSON as transformation output, the output processed using {@link processJsonTransform}.
236 * @param channelUID channel UID corresponding to received command
237 * @param command command to be transformed
238 * @return transformed command. Null is returned with JSON transformation outputs and configuration errors
240 * @see processJsonTransform
242 private @Nullable Optional<Command> transformCommandAndProcessJSON(ChannelUID channelUID, Command command) {
243 String transformOutput;
244 Optional<Command> transformedCommand;
245 ValueTransformation writeTransformation = this.writeTransformation;
246 if (writeTransformation == null || writeTransformation.isIdentityTransform()) {
247 transformedCommand = Optional.of(command);
249 transformOutput = writeTransformation.transform(bundleContext, command.toString());
250 if (transformOutput.contains("[")) {
251 processJsonTransform(command, transformOutput);
253 } else if (writeParametersHavingTransformationOnly) {
254 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
255 "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",
256 command, channelUID));
259 transformedCommand = SingleValueTransformation.tryConvertToCommand(transformOutput);
260 logger.trace("Converted transform output '{}' to command '{}' (type {})", transformOutput,
261 transformedCommand.map(c -> c.toString()).orElse("<conversion failed>"),
262 transformedCommand.map(c -> c.getClass().getName()).orElse("<conversion failed>"));
265 return transformedCommand;
268 private @Nullable ModbusWriteRequestBlueprint requestFromCommand(ChannelUID channelUID, Command origCommand,
269 ModbusDataConfiguration config, Command transformedCommand, Integer writeStart) {
270 ModbusWriteRequestBlueprint request;
271 boolean writeMultiple = config.isWriteMultipleEvenWithSingleRegisterOrCoil();
272 String writeType = config.getWriteType();
273 ModbusPollerThingHandler pollerHandler = this.pollerHandler;
274 if (writeType == null) {
278 if (writeType.equals(WRITE_TYPE_COIL)) {
279 Optional<Boolean> commandAsBoolean = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
280 if (!commandAsBoolean.isPresent()) {
282 "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 '{}'",
283 origCommand, channelUID, transformedCommand);
286 boolean data = commandAsBoolean.get();
287 request = new ModbusWriteCoilRequestBlueprint(slaveId, writeStart, data, writeMultiple,
288 config.getWriteMaxTries());
289 } else if (writeType.equals(WRITE_TYPE_HOLDING)) {
290 ValueType writeValueType = this.writeValueType;
291 if (writeValueType == null) {
292 // Should not happen in practice, since we are not in configuration error (checked above)
293 // This will make compiler happy anyways with the null checks
294 logger.warn("Received command but write value type not set! Ignoring command");
297 final ModbusRegisterArray data;
298 if (writeValueType.equals(ValueType.BIT)) {
299 if (writeSubIndex.isEmpty()) {
300 // Should not happen! should be in configuration error
301 logger.error("Bug: sub index not present but writeValueType=BIT. Should be in configuration error");
304 Optional<Boolean> commandBool = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
305 if (commandBool.isEmpty()) {
307 "Data thing is configured to write individual bit but we received command that is not convertible to 0/1 bit. Ignoring.");
309 } else if (pollerHandler == null) {
310 logger.warn("Bug: sub index present but not child of poller. Should be in configuration erro");
314 // writing bit of an individual register. Using cache from poller
315 AtomicReference<@Nullable ModbusRegisterArray> cachedRegistersRef = pollerHandler
316 .getLastPolledDataCache();
317 ModbusRegisterArray mutatedRegisters = cachedRegistersRef
318 .updateAndGet(cachedRegisters -> cachedRegisters == null ? null
319 : combineCommandWithRegisters(cachedRegisters, writeStart, writeSubIndex.get(),
321 if (mutatedRegisters == null) {
323 "Received command to thing with writeValueType=bit (pointing to individual bit of a holding register) but internal cache not yet populated. Ignoring command");
326 // extract register (first byte index = register index * 2)
327 byte[] allMutatedBytes = mutatedRegisters.getBytes();
328 int writeStartRelative = writeStart - pollStart;
329 data = new ModbusRegisterArray(allMutatedBytes[writeStartRelative * 2],
330 allMutatedBytes[writeStartRelative * 2 + 1]);
333 data = ModbusBitUtilities.commandToRegisters(transformedCommand, writeValueType);
335 writeMultiple = writeMultiple || data.size() > 1;
336 request = new ModbusWriteRegisterRequestBlueprint(slaveId, writeStart, data, writeMultiple,
337 config.getWriteMaxTries());
339 // Should not happen! This method is not called in case configuration errors and writeType is validated
340 // already in initialization (validateAndParseWriteParameters).
341 // We keep this here for future-proofing the code (new writeType values)
342 throw new IllegalStateException(String.format(
343 "writeType does not equal %s or %s and thus configuration is invalid. Should not end up this far with configuration error.",
344 WRITE_TYPE_COIL, WRITE_TYPE_HOLDING));
350 * Combine boolean-like command with registers. Updated registers are returned
354 private ModbusRegisterArray combineCommandWithRegisters(ModbusRegisterArray registers, int registerIndex,
355 int bitIndex, boolean b) {
356 byte[] allBytes = registers.getBytes();
357 int bitIndexWithinRegister = bitIndex % 16;
358 boolean hiByte = bitIndexWithinRegister >= 8;
359 int indexWithinByte = bitIndexWithinRegister % 8;
360 int registerIndexRelative = registerIndex - pollStart;
361 int byteIndex = 2 * registerIndexRelative + (hiByte ? 0 : 1);
363 allBytes[byteIndex] |= 1 << indexWithinByte;
365 allBytes[byteIndex] &= ~(1 << indexWithinByte);
367 if (logger.isTraceEnabled()) {
369 "Boolean-like command {} from item, combining command with internal register ({}) with registerIndex={} (relative {}), bitIndex={}, resulting register {}",
370 b, HexUtils.bytesToHex(registers.getBytes()), registerIndex, registerIndexRelative, bitIndex,
371 HexUtils.bytesToHex(allBytes));
373 return new ModbusRegisterArray(allBytes);
376 private void processJsonTransform(Command command, String transformOutput) {
377 ModbusCommunicationInterface localComms = this.comms;
378 if (localComms == null) {
381 Collection<ModbusWriteRequestBlueprint> requests;
383 requests = WriteRequestJsonUtilities.fromJson(slaveId, transformOutput);
384 } catch (IllegalArgumentException | IllegalStateException e) {
386 "Thing {} '{}' could handle transformation result '{}'. Original command {}. Error details follow",
387 getThing().getUID(), getThing().getLabel(), transformOutput, command, e);
391 requests.stream().forEach(request -> {
392 logger.trace("Submitting write request: {} to endpoint {} (based from transformation {})", request,
393 localComms.getEndpoint(), transformOutput);
394 localComms.submitOneTimeWrite(request, this::onWriteResponse, this::handleWriteError);
399 public synchronized void initialize() {
400 // Initialize the thing. If done set status to ONLINE to indicate proper working.
401 // Long running initialization should be done asynchronously in background.
403 logger.trace("initialize() of thing {} '{}' starting", thing.getUID(), thing.getLabel());
404 ModbusDataConfiguration localConfig = config = getConfigAs(ModbusDataConfiguration.class);
405 updateUnchangedValuesEveryMillis = localConfig.getUpdateUnchangedValuesEveryMillis();
406 Bridge bridge = getBridge();
407 if (bridge == null || !bridge.getStatus().equals(ThingStatus.ONLINE)) {
408 logger.debug("Thing {} '{}' has no bridge or it is not online", getThing().getUID(),
409 getThing().getLabel());
410 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, "No online bridge");
413 BridgeHandler bridgeHandler = bridge.getHandler();
414 if (bridgeHandler == null) {
415 logger.warn("Bridge {} '{}' has no handler.", bridge.getUID(), bridge.getLabel());
416 String errmsg = String.format("Bridge %s '%s' configuration incomplete or with errors", bridge.getUID(),
418 throw new ModbusConfigurationException(errmsg);
420 if (bridgeHandler instanceof ModbusEndpointThingHandler) {
421 // Write-only thing, parent is endpoint
422 ModbusEndpointThingHandler endpointHandler = (ModbusEndpointThingHandler) bridgeHandler;
423 slaveId = endpointHandler.getSlaveId();
424 comms = endpointHandler.getCommunicationInterface();
425 childOfEndpoint = true;
429 ModbusPollerThingHandler localPollerHandler = (ModbusPollerThingHandler) bridgeHandler;
430 pollerHandler = localPollerHandler;
431 ModbusReadRequestBlueprint localReadRequest = localPollerHandler.getRequest();
432 if (localReadRequest == null) {
434 "Poller {} '{}' has no read request -- configuration is changing or bridge having invalid configuration?",
435 bridge.getUID(), bridge.getLabel());
436 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
437 String.format("Poller %s '%s' has no poll task", bridge.getUID(), bridge.getLabel()));
440 readRequest = localReadRequest;
441 slaveId = localReadRequest.getUnitID();
442 functionCode = localReadRequest.getFunctionCode();
443 comms = localPollerHandler.getCommunicationInterface();
444 pollStart = localReadRequest.getReference();
445 childOfEndpoint = false;
447 validateAndParseReadParameters(localConfig);
448 validateAndParseWriteParameters(localConfig);
449 validateMustReadOrWrite();
451 updateStatusIfChanged(ThingStatus.ONLINE);
452 } catch (ModbusConfigurationException | EndpointNotInitializedException e) {
453 logger.debug("Thing {} '{}' initialization error: {}", getThing().getUID(), getThing().getLabel(),
455 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
457 logger.trace("initialize() of thing {} '{}' finished", thing.getUID(), thing.getLabel());
462 public synchronized void dispose() {
464 readValueType = null;
465 writeValueType = null;
466 readTransformation = null;
467 writeTransformation = null;
468 readIndex = Optional.empty();
469 readSubIndex = Optional.empty();
470 writeStart = Optional.empty();
471 writeSubIndex = Optional.empty();
477 isWriteEnabled = false;
478 isReadEnabled = false;
479 writeParametersHavingTransformationOnly = false;
480 childOfEndpoint = false;
481 pollerHandler = null;
482 channelCache = new HashMap<>();
483 lastStatusInfoUpdate = LocalDateTime.MIN;
484 statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE, null);
485 channelLastUpdated = new HashMap<>(NUMER_OF_CHANNELS_HINT);
486 channelLastState = new HashMap<>(NUMER_OF_CHANNELS_HINT);
490 public synchronized void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
491 logger.debug("bridgeStatusChanged for {}. Reseting handler", this.getThing().getUID());
496 private boolean hasConfigurationError() {
497 ThingStatusInfo statusInfo = getThing().getStatusInfo();
498 return statusInfo.getStatus() == ThingStatus.OFFLINE
499 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
502 private void validateMustReadOrWrite() throws ModbusConfigurationException {
503 if (!isReadEnabled && !isWriteEnabled) {
504 throw new ModbusConfigurationException("Should try to read or write data!");
508 private void validateAndParseReadParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
509 ModbusReadFunctionCode functionCode = this.functionCode;
510 boolean readingDiscreteOrCoil = functionCode == ModbusReadFunctionCode.READ_COILS
511 || functionCode == ModbusReadFunctionCode.READ_INPUT_DISCRETES;
512 boolean readStartMissing = config.getReadStart() == null || config.getReadStart().isBlank();
513 boolean readValueTypeMissing = config.getReadValueType() == null || config.getReadValueType().isBlank();
515 if (childOfEndpoint && readRequest == null) {
516 if (!readStartMissing || !readValueTypeMissing) {
517 String errmsg = String.format(
518 "Thing %s readStart=%s, and readValueType=%s were specified even though the data thing is child of endpoint (that is, write-only)!",
519 getThing().getUID(), config.getReadStart(), config.getReadValueType());
520 throw new ModbusConfigurationException(errmsg);
524 // we assume readValueType=bit by default if it is missing
525 boolean allMissingOrAllPresent = (readStartMissing && readValueTypeMissing)
526 || (!readStartMissing && (!readValueTypeMissing || readingDiscreteOrCoil));
527 if (!allMissingOrAllPresent) {
528 String errmsg = String.format(
529 "Thing %s readStart=%s, and readValueType=%s should be all present or all missing!",
530 getThing().getUID(), config.getReadStart(), config.getReadValueType());
531 throw new ModbusConfigurationException(errmsg);
532 } else if (!readStartMissing) {
533 // all read values are present
534 isReadEnabled = true;
535 if (readingDiscreteOrCoil && readValueTypeMissing) {
536 readValueType = ModbusConstants.ValueType.BIT;
539 readValueType = ValueType.fromConfigValue(config.getReadValueType());
540 } catch (IllegalArgumentException e) {
541 String errmsg = String.format("Thing %s readValueType=%s is invalid!", getThing().getUID(),
542 config.getReadValueType());
543 throw new ModbusConfigurationException(errmsg);
547 if (readingDiscreteOrCoil && !ModbusConstants.ValueType.BIT.equals(readValueType)) {
548 String errmsg = String.format(
549 "Thing %s invalid readValueType: Only readValueType='%s' (or undefined) supported with coils or discrete inputs. Value type was: %s",
550 getThing().getUID(), ModbusConstants.ValueType.BIT, config.getReadValueType());
551 throw new ModbusConfigurationException(errmsg);
554 isReadEnabled = false;
558 String readStart = config.getReadStart();
559 if (readStart == null) {
560 throw new ModbusConfigurationException(
561 String.format("Thing %s invalid readStart: %s", getThing().getUID(), config.getReadStart()));
563 String[] readParts = readStart.split("\\.", 2);
565 readIndex = Optional.of(Integer.parseInt(readParts[0]));
566 if (readParts.length == 2) {
567 readSubIndex = Optional.of(Integer.parseInt(readParts[1]));
569 readSubIndex = Optional.empty();
571 } catch (IllegalArgumentException e) {
572 String errmsg = String.format("Thing %s invalid readStart: %s", getThing().getUID(),
573 config.getReadStart());
574 throw new ModbusConfigurationException(errmsg);
577 readTransformation = new CascadedValueTransformationImpl(config.getReadTransform());
581 private void validateAndParseWriteParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
582 boolean writeTypeMissing = config.getWriteType() == null || config.getWriteType().isBlank();
583 boolean writeStartMissing = config.getWriteStart() == null || config.getWriteStart().isBlank();
584 boolean writeValueTypeMissing = config.getWriteValueType() == null || config.getWriteValueType().isBlank();
585 boolean writeTransformationMissing = config.getWriteTransform() == null || config.getWriteTransform().isBlank();
586 writeTransformation = new CascadedValueTransformationImpl(config.getWriteTransform());
587 boolean writingCoil = WRITE_TYPE_COIL.equals(config.getWriteType());
588 writeParametersHavingTransformationOnly = (writeTypeMissing && writeStartMissing && writeValueTypeMissing
589 && !writeTransformationMissing);
590 boolean allMissingOrAllPresentOrOnlyNonDefaultTransform = //
591 // read-only thing, no write specified
592 (writeTypeMissing && writeStartMissing && writeValueTypeMissing)
593 // mandatory write parameters provided. With coils one can drop value type
594 || (!writeTypeMissing && !writeStartMissing && (!writeValueTypeMissing || writingCoil))
595 // only transformation provided
596 || writeParametersHavingTransformationOnly;
597 if (!allMissingOrAllPresentOrOnlyNonDefaultTransform) {
598 String errmsg = String.format(
599 "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.",
600 config.getWriteType(), config.getWriteStart(), config.getWriteValueType());
601 throw new ModbusConfigurationException(errmsg);
602 } else if (!writeTypeMissing || writeParametersHavingTransformationOnly) {
603 isWriteEnabled = true;
604 // all write values are present
605 if (!writeParametersHavingTransformationOnly && !WRITE_TYPE_HOLDING.equals(config.getWriteType())
606 && !WRITE_TYPE_COIL.equals(config.getWriteType())) {
607 String errmsg = String.format("Invalid writeType=%s. Expecting %s or %s!", config.getWriteType(),
608 WRITE_TYPE_HOLDING, WRITE_TYPE_COIL);
609 throw new ModbusConfigurationException(errmsg);
611 final ValueType localWriteValueType;
612 if (writeParametersHavingTransformationOnly) {
613 // Placeholder for further checks
614 localWriteValueType = writeValueType = ModbusConstants.ValueType.INT16;
615 } else if (writingCoil && writeValueTypeMissing) {
616 localWriteValueType = writeValueType = ModbusConstants.ValueType.BIT;
619 localWriteValueType = writeValueType = ValueType.fromConfigValue(config.getWriteValueType());
620 } catch (IllegalArgumentException e) {
621 String errmsg = String.format("Invalid writeValueType=%s!", config.getWriteValueType());
622 throw new ModbusConfigurationException(errmsg);
627 if (!writeParametersHavingTransformationOnly) {
628 String localWriteStart = config.getWriteStart();
629 if (localWriteStart == null) {
630 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
631 config.getWriteStart());
632 throw new ModbusConfigurationException(errmsg);
634 String[] writeParts = localWriteStart.split("\\.", 2);
636 writeStart = Optional.of(Integer.parseInt(writeParts[0]));
637 if (writeParts.length == 2) {
638 writeSubIndex = Optional.of(Integer.parseInt(writeParts[1]));
640 writeSubIndex = Optional.empty();
642 } catch (IllegalArgumentException e) {
643 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
644 config.getReadStart());
645 throw new ModbusConfigurationException(errmsg);
648 } catch (IllegalArgumentException e) {
649 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
650 config.getWriteStart());
651 throw new ModbusConfigurationException(errmsg);
654 if (writingCoil && !ModbusConstants.ValueType.BIT.equals(localWriteValueType)) {
655 String errmsg = String.format(
656 "Invalid writeValueType: Only writeValueType='%s' (or undefined) supported with coils. Value type was: %s",
657 ModbusConstants.ValueType.BIT, config.getWriteValueType());
658 throw new ModbusConfigurationException(errmsg);
659 } else if (writeSubIndex.isEmpty() && !writingCoil && localWriteValueType.getBits() < 16) {
660 // trying to write holding registers with < 16 bit value types. Not supported
661 String errmsg = String.format(
662 "Invalid writeValueType: Only writeValueType with larger or equal to 16 bits are supported holding registers. Value type was: %s",
663 config.getWriteValueType());
664 throw new ModbusConfigurationException(errmsg);
667 if (writeSubIndex.isPresent()) {
668 if (writeValueTypeMissing || writeTypeMissing || !WRITE_TYPE_HOLDING.equals(config.getWriteType())
669 || !ModbusConstants.ValueType.BIT.equals(localWriteValueType) || childOfEndpoint) {
670 String errmsg = String.format(
671 "Thing %s invalid writeType, writeValueType or parent. Since writeStart=X.Y, one should set writeType=holding, writeValueType=bit and have the thing as child of poller",
672 getThing().getUID(), config.getWriteStart());
673 throw new ModbusConfigurationException(errmsg);
675 ModbusReadRequestBlueprint readRequest = this.readRequest;
676 if (readRequest == null
677 || readRequest.getFunctionCode() != ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS) {
678 String errmsg = String.format(
679 "Thing %s invalid. Since writeStart=X.Y, expecting poller reading holding registers.",
680 getThing().getUID());
681 throw new ModbusConfigurationException(errmsg);
684 validateWriteIndex();
686 isWriteEnabled = false;
690 private void validateReadIndex() throws ModbusConfigurationException {
692 ModbusReadRequestBlueprint readRequest = this.readRequest;
693 ValueType readValueType = this.readValueType;
694 if (!readIndex.isPresent() || readRequest == null) {
697 assert readValueType != null;
698 // bits represented by the value type, e.g. int32 -> 32
699 int valueTypeBitCount = readValueType.getBits();
701 switch (readRequest.getFunctionCode()) {
702 case READ_INPUT_REGISTERS:
703 case READ_MULTIPLE_REGISTERS:
704 dataElementBits = 16;
707 case READ_INPUT_DISCRETES:
711 throw new IllegalStateException(readRequest.getFunctionCode().toString());
714 boolean bitQuery = dataElementBits == 1;
715 if (bitQuery && readSubIndex.isPresent()) {
716 String errmsg = String.format("readStart=X.Y is not allowed to be used with coils or discrete inputs!");
717 throw new ModbusConfigurationException(errmsg);
720 if (valueTypeBitCount >= 16 && readSubIndex.isPresent()) {
721 String errmsg = String
722 .format("readStart=X.Y is not allowed to be used with value types larger than 16bit!");
723 throw new ModbusConfigurationException(errmsg);
724 } else if (!bitQuery && valueTypeBitCount < 16 && !readSubIndex.isPresent()) {
725 String errmsg = String.format("readStart=X.Y must be used with value types less than 16bit!");
726 throw new ModbusConfigurationException(errmsg);
727 } else if (readSubIndex.isPresent() && (readSubIndex.get() + 1) * valueTypeBitCount > 16) {
728 // the sub index Y (in X.Y) is above the register limits
729 String errmsg = String.format("readStart=X.Y, the value Y is too large");
730 throw new ModbusConfigurationException(errmsg);
733 // Determine bit positions polled, both start and end inclusive
734 int pollStartBitIndex = readRequest.getReference() * dataElementBits;
735 int pollEndBitIndex = pollStartBitIndex + readRequest.getDataLength() * dataElementBits - 1;
737 // Determine bit positions read, both start and end inclusive
738 int readStartBitIndex = readIndex.get() * dataElementBits + readSubIndex.orElse(0) * valueTypeBitCount;
739 int readEndBitIndex = readStartBitIndex + valueTypeBitCount - 1;
741 if (readStartBitIndex < pollStartBitIndex || readEndBitIndex > pollEndBitIndex) {
742 String errmsg = String.format(
743 "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.",
744 pollStartBitIndex / dataElementBits, pollEndBitIndex / dataElementBits, readValueType,
746 throw new ModbusConfigurationException(errmsg);
750 private void validateWriteIndex() throws ModbusConfigurationException {
752 ModbusReadRequestBlueprint readRequest = this.readRequest;
753 if (!writeStart.isPresent() || !writeSubIndex.isPresent()) {
755 // this validation is really about writeStart=X.Y validation
758 } else if (readRequest == null) {
759 // should not happen, already validated
760 throw new ModbusConfigurationException("Must poll data with writeStart=X.Y");
763 if (writeSubIndex.isPresent() && (writeSubIndex.get() + 1) > 16) {
764 // the sub index Y (in X.Y) is above the register limits
765 String errmsg = String.format("readStart=X.Y, the value Y is too large");
766 throw new ModbusConfigurationException(errmsg);
769 // Determine bit positions polled, both start and end inclusive
770 int pollStartBitIndex = readRequest.getReference() * 16;
771 int pollEndBitIndex = pollStartBitIndex + readRequest.getDataLength() * 16 - 1;
773 // Determine bit positions read, both start and end inclusive
774 int writeStartBitIndex = writeStart.get() * 16 + readSubIndex.orElse(0);
775 int writeEndBitIndex = writeStartBitIndex - 1;
777 if (writeStartBitIndex < pollStartBitIndex || writeEndBitIndex > pollEndBitIndex) {
778 String errmsg = String.format(
779 "Out-of-bounds: Poller is reading from index %d to %d (inclusive) but this thing configured to write starting from element %d. Must write within polled limits",
780 pollStartBitIndex / 16, pollEndBitIndex / 16, writeStart.get());
781 throw new ModbusConfigurationException(errmsg);
785 private boolean containsOnOff(List<Class<? extends State>> channelAcceptedDataTypes) {
786 return channelAcceptedDataTypes.stream().anyMatch(clz -> {
787 return clz.equals(OnOffType.class);
791 private boolean containsOpenClosed(List<Class<? extends State>> acceptedDataTypes) {
792 return acceptedDataTypes.stream().anyMatch(clz -> {
793 return clz.equals(OpenClosedType.class);
797 public synchronized void onReadResult(AsyncModbusReadResult result) {
798 result.getRegisters().ifPresent(registers -> onRegisters(result.getRequest(), registers));
799 result.getBits().ifPresent(bits -> onBits(result.getRequest(), bits));
802 public synchronized void handleReadError(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
803 onError(failure.getRequest(), failure.getCause());
806 public synchronized void handleWriteError(AsyncModbusFailure<ModbusWriteRequestBlueprint> failure) {
807 onError(failure.getRequest(), failure.getCause());
810 private synchronized void onRegisters(ModbusReadRequestBlueprint request, ModbusRegisterArray registers) {
811 if (hasConfigurationError()) {
813 } else if (!isReadEnabled) {
816 ValueType readValueType = this.readValueType;
817 if (readValueType == null) {
823 // e.g. with bit, extractIndex=4 means 5th bit (from right) ("10.4" -> 5th bit of register 10, "10.4" -> 5th bit
825 // bit of second register)
826 // e.g. with 8bit integer, extractIndex=3 means high byte of second register
828 // with <16 bit types, this is the index of the N'th 1-bit/8-bit item. Each register has 16/2 items,
830 // with >=16 bit types, this is index of first register
832 if (readValueType.getBits() >= 16) {
833 // Invariant, checked in initialize
834 assert readSubIndex.orElse(0) == 0;
835 extractIndex = readIndex.get() - pollStart;
837 int subIndex = readSubIndex.orElse(0);
838 int itemsPerRegister = 16 / readValueType.getBits();
839 extractIndex = (readIndex.get() - pollStart) * itemsPerRegister + subIndex;
841 numericState = ModbusBitUtilities.extractStateFromRegisters(registers, extractIndex, readValueType)
842 .map(state -> (State) state).orElse(UnDefType.UNDEF);
843 boolean boolValue = !numericState.equals(DecimalType.ZERO);
844 Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
846 "Thing {} channels updated: {}. readValueType={}, readIndex={}, readSubIndex(or 0)={}, extractIndex={} -> numeric value {} and boolValue={}. Registers {} for request {}",
847 thing.getUID(), values, readValueType, readIndex, readSubIndex.orElse(0), extractIndex, numericState,
848 boolValue, registers, request);
851 private synchronized void onBits(ModbusReadRequestBlueprint request, BitArray bits) {
852 if (hasConfigurationError()) {
854 } else if (!isReadEnabled) {
857 boolean boolValue = bits.getBit(readIndex.get() - pollStart);
858 DecimalType numericState = boolValue ? new DecimalType(BigDecimal.ONE) : DecimalType.ZERO;
859 Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
861 "Thing {} channels updated: {}. readValueType={}, readIndex={} -> numeric value {} and boolValue={}. Bits {} for request {}",
862 thing.getUID(), values, readValueType, readIndex, numericState, boolValue, bits, request);
865 private synchronized void onError(ModbusReadRequestBlueprint request, Exception error) {
866 if (hasConfigurationError()) {
868 } else if (!isReadEnabled) {
871 if (error instanceof ModbusConnectionException) {
872 logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
873 error.getClass().getSimpleName(), error.toString());
874 } else if (error instanceof ModbusTransportException) {
875 logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
876 error.getClass().getSimpleName(), error.toString());
879 "Thing {} '{}' had {} error on read: {} (message: {}). Stack trace follows since this is unexpected error.",
880 getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
881 error.getMessage(), error);
883 Map<ChannelUID, State> states = new HashMap<>();
884 ChannelUID lastReadErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_ERROR);
885 if (isLinked(lastReadErrorUID)) {
886 states.put(lastReadErrorUID, new DateTimeType());
889 synchronized (this) {
891 states.forEach((uid, state) -> {
892 tryUpdateState(uid, state);
895 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
896 String.format("Error (%s) with read. Request: %s. Description: %s. Message: %s",
897 error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
901 private synchronized void onError(ModbusWriteRequestBlueprint request, Exception error) {
902 if (hasConfigurationError()) {
904 } else if (!isWriteEnabled) {
907 if (error instanceof ModbusConnectionException) {
908 logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
909 error.getClass().getSimpleName(), error.toString());
910 } else if (error instanceof ModbusTransportException) {
911 logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
912 error.getClass().getSimpleName(), error.toString());
915 "Thing {} '{}' had {} error on write: {} (message: {}). Stack trace follows since this is unexpected error.",
916 getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
917 error.getMessage(), error);
919 Map<ChannelUID, State> states = new HashMap<>();
920 ChannelUID lastWriteErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_ERROR);
921 if (isLinked(lastWriteErrorUID)) {
922 states.put(lastWriteErrorUID, new DateTimeType());
925 synchronized (this) {
927 states.forEach((uid, state) -> {
928 tryUpdateState(uid, state);
931 updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
932 String.format("Error (%s) with write. Request: %s. Description: %s. Message: %s",
933 error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
937 public synchronized void onWriteResponse(AsyncModbusWriteResult result) {
938 if (hasConfigurationError()) {
940 } else if (!isWriteEnabled) {
943 logger.debug("Successful write, matching request {}", result.getRequest());
944 updateStatusIfChanged(ThingStatus.ONLINE);
945 ChannelUID lastWriteSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_SUCCESS);
946 if (isLinked(lastWriteSuccessUID)) {
947 updateState(lastWriteSuccessUID, new DateTimeType());
952 * Update linked channels
954 * @param numericState numeric state corresponding to polled data (or UNDEF with floating point NaN or infinity)
955 * @param boolValue boolean value corresponding to polled data
956 * @return updated channel data
958 private Map<ChannelUID, State> processUpdatedValue(State numericState, boolean boolValue) {
959 ValueTransformation localReadTransformation = readTransformation;
960 if (localReadTransformation == null) {
961 // We should always have transformation available if thing is initalized properly
962 logger.trace("No transformation available, aborting processUpdatedValue");
963 return Collections.emptyMap();
965 Map<ChannelUID, State> states = new HashMap<>();
966 CHANNEL_ID_TO_ACCEPTED_TYPES.keySet().stream().forEach(channelId -> {
967 ChannelUID channelUID = getChannelUID(channelId);
968 if (!isLinked(channelUID)) {
971 List<Class<? extends State>> acceptedDataTypes = CHANNEL_ID_TO_ACCEPTED_TYPES.get(channelId);
972 if (acceptedDataTypes.isEmpty()) {
977 if (containsOnOff(acceptedDataTypes)) {
978 boolLikeState = boolValue ? OnOffType.ON : OnOffType.OFF;
979 } else if (containsOpenClosed(acceptedDataTypes)) {
980 boolLikeState = boolValue ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
982 boolLikeState = null;
985 State transformedState;
986 if (localReadTransformation.isIdentityTransform()) {
987 if (boolLikeState != null) {
988 // A bit of smartness for ON/OFF and OPEN/CLOSED with boolean like items
989 transformedState = boolLikeState;
991 // Numeric states always go through transformation. This allows value of 17.5 to be
993 // 17.5% with percent types (instead of raising error)
994 transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
998 transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
1002 if (transformedState != null) {
1004 "Channel {} will be updated to '{}' (type {}). Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}",
1005 channelId, transformedState, transformedState.getClass().getSimpleName(), numericState,
1006 readValueType, boolValue,
1007 localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
1008 states.put(channelUID, transformedState);
1010 String types = String.join(", ",
1011 acceptedDataTypes.stream().map(cls -> cls.getSimpleName()).toArray(String[]::new));
1013 "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: {}",
1014 channelId, types, numericState, readValueType, boolValue,
1015 localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
1019 ChannelUID lastReadSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_SUCCESS);
1020 if (isLinked(lastReadSuccessUID)) {
1021 states.put(lastReadSuccessUID, new DateTimeType());
1023 updateExpiredChannels(states);
1027 private void updateExpiredChannels(Map<ChannelUID, State> states) {
1028 synchronized (this) {
1029 updateStatusIfChanged(ThingStatus.ONLINE);
1030 long now = System.currentTimeMillis();
1031 // Update channels that have not been updated in a while, or when their values has changed
1032 states.forEach((uid, state) -> updateExpiredChannel(now, uid, state));
1033 channelLastState = states;
1037 // since lastState can be null, and "lastState == null" in conditional is not useless
1038 @SuppressWarnings("null")
1039 private void updateExpiredChannel(long now, ChannelUID uid, State state) {
1041 State lastState = channelLastState.get(uid);
1042 long lastUpdatedMillis = channelLastUpdated.getOrDefault(uid, 0L);
1043 long millisSinceLastUpdate = now - lastUpdatedMillis;
1044 if (lastUpdatedMillis <= 0L || lastState == null || updateUnchangedValuesEveryMillis <= 0L
1045 || millisSinceLastUpdate > updateUnchangedValuesEveryMillis || !lastState.equals(state)) {
1046 tryUpdateState(uid, state);
1047 channelLastUpdated.put(uid, now);
1051 private void tryUpdateState(ChannelUID uid, State state) {
1053 updateState(uid, state);
1054 } catch (IllegalArgumentException e) {
1055 logger.warn("Error updating state '{}' (type {}) to channel {}: {} {}", state,
1056 Optional.ofNullable(state).map(s -> s.getClass().getName()).orElse("null"), uid,
1057 e.getClass().getName(), e.getMessage());
1061 private ChannelUID getChannelUID(String channelID) {
1063 .requireNonNull(channelCache.computeIfAbsent(channelID, id -> new ChannelUID(getThing().getUID(), id)));
1066 private void updateStatusIfChanged(ThingStatus status) {
1067 updateStatusIfChanged(status, ThingStatusDetail.NONE, null);
1070 private void updateStatusIfChanged(ThingStatus status, ThingStatusDetail statusDetail,
1071 @Nullable String description) {
1072 ThingStatusInfo newStatusInfo = new ThingStatusInfo(status, statusDetail, description);
1073 Duration durationSinceLastUpdate = Duration.between(lastStatusInfoUpdate, LocalDateTime.now());
1074 boolean intervalElapsed = MIN_STATUS_INFO_UPDATE_INTERVAL.minus(durationSinceLastUpdate).isNegative();
1075 if (statusInfo.getStatus() == ThingStatus.UNKNOWN || !statusInfo.equals(newStatusInfo) || intervalElapsed) {
1076 statusInfo = newStatusInfo;
1077 lastStatusInfoUpdate = LocalDateTime.now();
1078 updateStatus(newStatusInfo);
1083 * Update status using pre-constructed ThingStatusInfo
1085 * Implementation adapted from BaseThingHandler updateStatus implementations
1087 * @param statusInfo new status info
1089 protected void updateStatus(ThingStatusInfo statusInfo) {
1090 synchronized (this) {
1091 ThingHandlerCallback callback = getCallback();
1092 if (callback != null) {
1093 callback.statusUpdated(this.thing, statusInfo);
1095 logger.warn("Handler {} tried updating the thing status although the handler was already disposed.",
1096 this.getClass().getSimpleName());