]> git.basschouten.com Git - openhab-addons.git/blob
8eb720b40cf74414bc127ea318013ae3bea7f222
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.modbus.internal.handler;
14
15 import static org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal.*;
16
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;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.atomic.AtomicReference;
29
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;
87
88 /**
89  * The {@link ModbusDataThingHandler} is responsible for interpreting polled modbus data, as well as handling openHAB
90  * commands
91  *
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
94  * synchronized
95  * to avoid data race conditions.
96  *
97  * @author Sami Salonen - Initial contribution
98  */
99 @NonNullByDefault
100 public class ModbusDataThingHandler extends BaseThingHandler {
101
102     private final Logger logger = LoggerFactory.getLogger(ModbusDataThingHandler.class);
103
104     private final BundleContext bundleContext;
105
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<>();
108
109     static {
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());
124     }
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;
127
128     //
129     // If you change the below default/initial values, please update the corresponding values in dispose()
130     //
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);
154
155     private volatile LocalDateTime lastStatusInfoUpdate = LocalDateTime.MIN;
156     private volatile ThingStatusInfo statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE,
157             null);
158
159     public ModbusDataThingHandler(Thing thing) {
160         super(thing);
161         this.bundleContext = FrameworkUtil.getBundle(ModbusDataThingHandler.class).getBundleContext();
162     }
163
164     @Override
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) {
170             return;
171         }
172
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
178                 return;
179             }
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
182             // onRegisters.
183             scheduler.schedule(() -> poller.refresh(), 0, TimeUnit.SECONDS);
184             return;
185         } else if (hasConfigurationError()) {
186             logger.debug(
187                     "Thing {} '{}' command '{}' to channel '{}': Thing has configuration error so ignoring the command",
188                     getThing().getUID(), getThing().getLabel(), command, channelUID);
189             return;
190         } else if (!isWriteEnabled) {
191             logger.debug(
192                     "Thing {} '{}' command '{}' to channel '{}': no writing configured -> aborting processing command",
193                     getThing().getUID(), getThing().getLabel(), command, channelUID);
194             return;
195         }
196
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
201             return;
202         }
203
204         // We did not have JSON output from the transformation, so writeStart is absolute required. Abort if it is
205         // missing
206         Optional<Integer> writeStart = this.writeStart;
207         if (writeStart.isEmpty()) {
208             logger.debug(
209                     "Thing {} '{}': not processing command {} since writeStart is missing and transformation output is not a JSON",
210                     getThing().getUID(), getThing().getLabel(), command);
211             return;
212         }
213
214         if (transformedCommand.isEmpty()) {
215             // transformation failed, return
216             logger.warn("Cannot process command {} (of type {}) with channel {} since transformation was unsuccessful",
217                     command, command.getClass().getSimpleName(), channelUID);
218             return;
219         }
220
221         ModbusWriteRequestBlueprint request = requestFromCommand(channelUID, command, config, transformedCommand.get(),
222                 writeStart.get());
223         if (request == null) {
224             return;
225         }
226
227         logger.trace("Submitting write task {} to endpoint {}", request, comms.getEndpoint());
228         comms.submitOneTimeWrite(request, this::onWriteResponse, this::handleWriteError);
229     }
230
231     /**
232      * Transform received command using the transformation.
233      *
234      * In case of JSON as transformation output, the output processed using {@link processJsonTransform}.
235      *
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
239      *
240      * @see processJsonTransform
241      */
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);
248         } else {
249             transformOutput = writeTransformation.transform(bundleContext, command.toString());
250             if (transformOutput.contains("[")) {
251                 processJsonTransform(command, transformOutput);
252                 return null;
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));
257                 return null;
258             } else {
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>"));
263             }
264         }
265         return transformedCommand;
266     }
267
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) {
275             // disposed thing
276             return null;
277         }
278         if (writeType.equals(WRITE_TYPE_COIL)) {
279             Optional<Boolean> commandAsBoolean = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
280             if (commandAsBoolean.isEmpty()) {
281                 logger.warn(
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);
284                 return null;
285             }
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");
295                 return null;
296             }
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");
302                     return null;
303                 }
304                 Optional<Boolean> commandBool = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
305                 if (commandBool.isEmpty()) {
306                     logger.warn(
307                             "Data thing is configured to write individual bit but we received command that is not convertible to 0/1 bit. Ignoring.");
308                     return null;
309                 } else if (pollerHandler == null) {
310                     logger.warn("Bug: sub index present but not child of poller. Should be in configuration erro");
311                     return null;
312                 }
313
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(),
320                                         commandBool.get()));
321                 if (mutatedRegisters == null) {
322                     logger.warn(
323                             "Received command to thing with writeValueType=bit (pointing to individual bit of a holding register) but internal cache not yet populated. Ignoring command");
324                     return null;
325                 }
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]);
331
332             } else {
333                 data = ModbusBitUtilities.commandToRegisters(transformedCommand, writeValueType);
334             }
335             writeMultiple = writeMultiple || data.size() > 1;
336             request = new ModbusWriteRegisterRequestBlueprint(slaveId, writeStart, data, writeMultiple,
337                     config.getWriteMaxTries());
338         } else {
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));
345         }
346         return request;
347     }
348
349     /**
350      * Combine boolean-like command with registers. Updated registers are returned
351      *
352      * @return
353      */
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);
362         if (b) {
363             allBytes[byteIndex] |= 1 << indexWithinByte;
364         } else {
365             allBytes[byteIndex] &= ~(1 << indexWithinByte);
366         }
367         if (logger.isTraceEnabled()) {
368             logger.trace(
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));
372         }
373         return new ModbusRegisterArray(allBytes);
374     }
375
376     private void processJsonTransform(Command command, String transformOutput) {
377         ModbusCommunicationInterface localComms = this.comms;
378         if (localComms == null) {
379             return;
380         }
381         Collection<ModbusWriteRequestBlueprint> requests;
382         try {
383             requests = WriteRequestJsonUtilities.fromJson(slaveId, transformOutput);
384         } catch (IllegalArgumentException | IllegalStateException e) {
385             logger.warn(
386                     "Thing {} '{}' could handle transformation result '{}'. Original command {}. Error details follow",
387                     getThing().getUID(), getThing().getLabel(), transformOutput, command, e);
388             return;
389         }
390
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);
395         });
396     }
397
398     @Override
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.
402         try {
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");
411                 return;
412             }
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(),
417                         bridge.getLabel());
418                 throw new ModbusConfigurationException(errmsg);
419             }
420             if (bridgeHandler instanceof ModbusEndpointThingHandler endpointHandler) {
421                 slaveId = endpointHandler.getSlaveId();
422                 comms = endpointHandler.getCommunicationInterface();
423                 childOfEndpoint = true;
424                 functionCode = null;
425                 readRequest = null;
426             } else {
427                 ModbusPollerThingHandler localPollerHandler = (ModbusPollerThingHandler) bridgeHandler;
428                 pollerHandler = localPollerHandler;
429                 ModbusReadRequestBlueprint localReadRequest = localPollerHandler.getRequest();
430                 if (localReadRequest == null) {
431                     logger.debug(
432                             "Poller {} '{}' has no read request -- configuration is changing or bridge having invalid configuration?",
433                             bridge.getUID(), bridge.getLabel());
434                     updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
435                             String.format("Poller %s '%s' has no poll task", bridge.getUID(), bridge.getLabel()));
436                     return;
437                 }
438                 readRequest = localReadRequest;
439                 slaveId = localReadRequest.getUnitID();
440                 functionCode = localReadRequest.getFunctionCode();
441                 comms = localPollerHandler.getCommunicationInterface();
442                 pollStart = localReadRequest.getReference();
443                 childOfEndpoint = false;
444             }
445             validateAndParseReadParameters(localConfig);
446             validateAndParseWriteParameters(localConfig);
447             validateMustReadOrWrite();
448
449             updateStatusIfChanged(ThingStatus.ONLINE);
450         } catch (ModbusConfigurationException | EndpointNotInitializedException e) {
451             logger.debug("Thing {} '{}' initialization error: {}", getThing().getUID(), getThing().getLabel(),
452                     e.getMessage());
453             updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
454         } finally {
455             logger.trace("initialize() of thing {} '{}' finished", thing.getUID(), thing.getLabel());
456         }
457     }
458
459     @Override
460     public synchronized void dispose() {
461         config = null;
462         readValueType = null;
463         writeValueType = null;
464         readTransformation = null;
465         writeTransformation = null;
466         readIndex = Optional.empty();
467         readSubIndex = Optional.empty();
468         writeStart = Optional.empty();
469         writeSubIndex = Optional.empty();
470         pollStart = 0;
471         slaveId = 0;
472         comms = null;
473         functionCode = null;
474         readRequest = null;
475         isWriteEnabled = false;
476         isReadEnabled = false;
477         writeParametersHavingTransformationOnly = false;
478         childOfEndpoint = false;
479         pollerHandler = null;
480         channelCache = new HashMap<>();
481         lastStatusInfoUpdate = LocalDateTime.MIN;
482         statusInfo = new ThingStatusInfo(ThingStatus.UNKNOWN, ThingStatusDetail.NONE, null);
483         channelLastUpdated = new HashMap<>(NUMER_OF_CHANNELS_HINT);
484         channelLastState = new HashMap<>(NUMER_OF_CHANNELS_HINT);
485     }
486
487     @Override
488     public synchronized void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
489         logger.debug("bridgeStatusChanged for {}. Reseting handler", this.getThing().getUID());
490         this.dispose();
491         this.initialize();
492     }
493
494     private boolean hasConfigurationError() {
495         ThingStatusInfo statusInfo = getThing().getStatusInfo();
496         return statusInfo.getStatus() == ThingStatus.OFFLINE
497                 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
498     }
499
500     private void validateMustReadOrWrite() throws ModbusConfigurationException {
501         if (!isReadEnabled && !isWriteEnabled) {
502             throw new ModbusConfigurationException("Should try to read or write data!");
503         }
504     }
505
506     private void validateAndParseReadParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
507         ModbusReadFunctionCode functionCode = this.functionCode;
508         boolean readingDiscreteOrCoil = functionCode == ModbusReadFunctionCode.READ_COILS
509                 || functionCode == ModbusReadFunctionCode.READ_INPUT_DISCRETES;
510         boolean readStartMissing = config.getReadStart() == null || config.getReadStart().isBlank();
511         boolean readValueTypeMissing = config.getReadValueType() == null || config.getReadValueType().isBlank();
512
513         if (childOfEndpoint && readRequest == null) {
514             if (!readStartMissing || !readValueTypeMissing) {
515                 String errmsg = String.format(
516                         "Thing %s readStart=%s, and readValueType=%s were specified even though the data thing is child of endpoint (that is, write-only)!",
517                         getThing().getUID(), config.getReadStart(), config.getReadValueType());
518                 throw new ModbusConfigurationException(errmsg);
519             }
520         }
521
522         // we assume readValueType=bit by default if it is missing
523         boolean allMissingOrAllPresent = (readStartMissing && readValueTypeMissing)
524                 || (!readStartMissing && (!readValueTypeMissing || readingDiscreteOrCoil));
525         if (!allMissingOrAllPresent) {
526             String errmsg = String.format(
527                     "Thing %s readStart=%s, and readValueType=%s should be all present or all missing!",
528                     getThing().getUID(), config.getReadStart(), config.getReadValueType());
529             throw new ModbusConfigurationException(errmsg);
530         } else if (!readStartMissing) {
531             // all read values are present
532             isReadEnabled = true;
533             if (readingDiscreteOrCoil && readValueTypeMissing) {
534                 readValueType = ModbusConstants.ValueType.BIT;
535             } else {
536                 try {
537                     readValueType = ValueType.fromConfigValue(config.getReadValueType());
538                 } catch (IllegalArgumentException e) {
539                     String errmsg = String.format("Thing %s readValueType=%s is invalid!", getThing().getUID(),
540                             config.getReadValueType());
541                     throw new ModbusConfigurationException(errmsg);
542                 }
543             }
544
545             if (readingDiscreteOrCoil && !ModbusConstants.ValueType.BIT.equals(readValueType)) {
546                 String errmsg = String.format(
547                         "Thing %s invalid readValueType: Only readValueType='%s' (or undefined) supported with coils or discrete inputs. Value type was: %s",
548                         getThing().getUID(), ModbusConstants.ValueType.BIT, config.getReadValueType());
549                 throw new ModbusConfigurationException(errmsg);
550             }
551         } else {
552             isReadEnabled = false;
553         }
554
555         if (isReadEnabled) {
556             String readStart = config.getReadStart();
557             if (readStart == null) {
558                 throw new ModbusConfigurationException(
559                         String.format("Thing %s invalid readStart: %s", getThing().getUID(), config.getReadStart()));
560             }
561             String[] readParts = readStart.split("\\.", 2);
562             try {
563                 readIndex = Optional.of(Integer.parseInt(readParts[0]));
564                 if (readParts.length == 2) {
565                     readSubIndex = Optional.of(Integer.parseInt(readParts[1]));
566                 } else {
567                     readSubIndex = Optional.empty();
568                 }
569             } catch (IllegalArgumentException e) {
570                 String errmsg = String.format("Thing %s invalid readStart: %s", getThing().getUID(),
571                         config.getReadStart());
572                 throw new ModbusConfigurationException(errmsg);
573             }
574         }
575         readTransformation = new CascadedValueTransformationImpl(config.getReadTransform());
576         validateReadIndex();
577     }
578
579     private void validateAndParseWriteParameters(ModbusDataConfiguration config) throws ModbusConfigurationException {
580         boolean writeTypeMissing = config.getWriteType() == null || config.getWriteType().isBlank();
581         boolean writeStartMissing = config.getWriteStart() == null || config.getWriteStart().isBlank();
582         boolean writeValueTypeMissing = config.getWriteValueType() == null || config.getWriteValueType().isBlank();
583         boolean writeTransformationMissing = config.getWriteTransform() == null || config.getWriteTransform().isBlank();
584         writeTransformation = new CascadedValueTransformationImpl(config.getWriteTransform());
585         boolean writingCoil = WRITE_TYPE_COIL.equals(config.getWriteType());
586         writeParametersHavingTransformationOnly = (writeTypeMissing && writeStartMissing && writeValueTypeMissing
587                 && !writeTransformationMissing);
588         boolean allMissingOrAllPresentOrOnlyNonDefaultTransform = //
589                 // read-only thing, no write specified
590                 (writeTypeMissing && writeStartMissing && writeValueTypeMissing)
591                         // mandatory write parameters provided. With coils one can drop value type
592                         || (!writeTypeMissing && !writeStartMissing && (!writeValueTypeMissing || writingCoil))
593                         // only transformation provided
594                         || writeParametersHavingTransformationOnly;
595         if (!allMissingOrAllPresentOrOnlyNonDefaultTransform) {
596             String errmsg = String.format(
597                     "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.",
598                     config.getWriteType(), config.getWriteStart(), config.getWriteValueType());
599             throw new ModbusConfigurationException(errmsg);
600         } else if (!writeTypeMissing || writeParametersHavingTransformationOnly) {
601             isWriteEnabled = true;
602             // all write values are present
603             if (!writeParametersHavingTransformationOnly && !WRITE_TYPE_HOLDING.equals(config.getWriteType())
604                     && !WRITE_TYPE_COIL.equals(config.getWriteType())) {
605                 String errmsg = String.format("Invalid writeType=%s. Expecting %s or %s!", config.getWriteType(),
606                         WRITE_TYPE_HOLDING, WRITE_TYPE_COIL);
607                 throw new ModbusConfigurationException(errmsg);
608             }
609             final ValueType localWriteValueType;
610             if (writeParametersHavingTransformationOnly) {
611                 // Placeholder for further checks
612                 localWriteValueType = writeValueType = ModbusConstants.ValueType.INT16;
613             } else if (writingCoil && writeValueTypeMissing) {
614                 localWriteValueType = writeValueType = ModbusConstants.ValueType.BIT;
615             } else {
616                 try {
617                     localWriteValueType = writeValueType = ValueType.fromConfigValue(config.getWriteValueType());
618                 } catch (IllegalArgumentException e) {
619                     String errmsg = String.format("Invalid writeValueType=%s!", config.getWriteValueType());
620                     throw new ModbusConfigurationException(errmsg);
621                 }
622             }
623
624             try {
625                 if (!writeParametersHavingTransformationOnly) {
626                     String localWriteStart = config.getWriteStart();
627                     if (localWriteStart == null) {
628                         String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
629                                 config.getWriteStart());
630                         throw new ModbusConfigurationException(errmsg);
631                     }
632                     String[] writeParts = localWriteStart.split("\\.", 2);
633                     try {
634                         writeStart = Optional.of(Integer.parseInt(writeParts[0]));
635                         if (writeParts.length == 2) {
636                             writeSubIndex = Optional.of(Integer.parseInt(writeParts[1]));
637                         } else {
638                             writeSubIndex = Optional.empty();
639                         }
640                     } catch (IllegalArgumentException e) {
641                         String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
642                                 config.getReadStart());
643                         throw new ModbusConfigurationException(errmsg);
644                     }
645                 }
646             } catch (IllegalArgumentException e) {
647                 String errmsg = String.format("Thing %s invalid writeStart: %s", getThing().getUID(),
648                         config.getWriteStart());
649                 throw new ModbusConfigurationException(errmsg);
650             }
651
652             if (writingCoil && !ModbusConstants.ValueType.BIT.equals(localWriteValueType)) {
653                 String errmsg = String.format(
654                         "Invalid writeValueType: Only writeValueType='%s' (or undefined) supported with coils. Value type was: %s",
655                         ModbusConstants.ValueType.BIT, config.getWriteValueType());
656                 throw new ModbusConfigurationException(errmsg);
657             } else if (writeSubIndex.isEmpty() && !writingCoil && localWriteValueType.getBits() < 16) {
658                 // trying to write holding registers with < 16 bit value types. Not supported
659                 String errmsg = String.format(
660                         "Invalid writeValueType: Only writeValueType with larger or equal to 16 bits are supported holding registers. Value type was: %s",
661                         config.getWriteValueType());
662                 throw new ModbusConfigurationException(errmsg);
663             }
664
665             if (writeSubIndex.isPresent()) {
666                 if (writeValueTypeMissing || writeTypeMissing || !WRITE_TYPE_HOLDING.equals(config.getWriteType())
667                         || !ModbusConstants.ValueType.BIT.equals(localWriteValueType) || childOfEndpoint) {
668                     String errmsg = String.format(
669                             "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",
670                             getThing().getUID(), config.getWriteStart());
671                     throw new ModbusConfigurationException(errmsg);
672                 }
673                 ModbusReadRequestBlueprint readRequest = this.readRequest;
674                 if (readRequest == null
675                         || readRequest.getFunctionCode() != ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS) {
676                     String errmsg = String.format(
677                             "Thing %s invalid. Since writeStart=X.Y, expecting poller reading holding registers.",
678                             getThing().getUID());
679                     throw new ModbusConfigurationException(errmsg);
680                 }
681             }
682             validateWriteIndex();
683         } else {
684             isWriteEnabled = false;
685         }
686     }
687
688     private void validateReadIndex() throws ModbusConfigurationException {
689         @Nullable
690         ModbusReadRequestBlueprint readRequest = this.readRequest;
691         ValueType readValueType = this.readValueType;
692         if (readIndex.isEmpty() || readRequest == null) {
693             return;
694         }
695         assert readValueType != null;
696         // bits represented by the value type, e.g. int32 -> 32
697         int valueTypeBitCount = readValueType.getBits();
698         int dataElementBits;
699         switch (readRequest.getFunctionCode()) {
700             case READ_INPUT_REGISTERS:
701             case READ_MULTIPLE_REGISTERS:
702                 dataElementBits = 16;
703                 break;
704             case READ_COILS:
705             case READ_INPUT_DISCRETES:
706                 dataElementBits = 1;
707                 break;
708             default:
709                 throw new IllegalStateException(readRequest.getFunctionCode().toString());
710         }
711
712         boolean bitQuery = dataElementBits == 1;
713         if (bitQuery && readSubIndex.isPresent()) {
714             String errmsg = String.format("readStart=X.Y is not allowed to be used with coils or discrete inputs!");
715             throw new ModbusConfigurationException(errmsg);
716         }
717
718         if (valueTypeBitCount >= 16 && readSubIndex.isPresent()) {
719             String errmsg = String.format(
720                     "readStart=X.Y notation is not allowed to be used with value types larger than 16bit! Use readStart=X instead.");
721             throw new ModbusConfigurationException(errmsg);
722         } else if (!bitQuery && valueTypeBitCount < 16 && readSubIndex.isEmpty()) {
723             // User has specified value type which is less than register width (16 bits).
724             // readStart=X.Y notation must be used to define which data to extract from the 16 bit register.
725             String errmsg = String
726                     .format("readStart=X.Y must be used with value types (readValueType) less than 16bit!");
727             throw new ModbusConfigurationException(errmsg);
728         } else if (readSubIndex.isPresent() && (readSubIndex.get() + 1) * valueTypeBitCount > 16) {
729             // the sub index Y (in X.Y) is above the register limits
730             String errmsg = String.format("readStart=X.Y, the value Y is too large");
731             throw new ModbusConfigurationException(errmsg);
732         }
733
734         // Determine bit positions polled, both start and end inclusive
735         int pollStartBitIndex = readRequest.getReference() * dataElementBits;
736         int pollEndBitIndex = pollStartBitIndex + readRequest.getDataLength() * dataElementBits - 1;
737
738         // Determine bit positions read, both start and end inclusive
739         int readStartBitIndex = readIndex.get() * dataElementBits + readSubIndex.orElse(0) * valueTypeBitCount;
740         int readEndBitIndex = readStartBitIndex + valueTypeBitCount - 1;
741
742         if (readStartBitIndex < pollStartBitIndex || readEndBitIndex > pollEndBitIndex) {
743             String errmsg = String.format(
744                     "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.",
745                     pollStartBitIndex / dataElementBits, pollEndBitIndex / dataElementBits, readValueType,
746                     readIndex.get());
747             throw new ModbusConfigurationException(errmsg);
748         }
749     }
750
751     private void validateWriteIndex() throws ModbusConfigurationException {
752         @Nullable
753         ModbusReadRequestBlueprint readRequest = this.readRequest;
754         if (writeStart.isEmpty() || writeSubIndex.isEmpty()) {
755             //
756             // this validation is really about writeStart=X.Y validation
757             //
758             return;
759         } else if (readRequest == null) {
760             // should not happen, already validated
761             throw new ModbusConfigurationException("Must poll data with writeStart=X.Y");
762         }
763
764         if (writeSubIndex.isPresent() && (writeSubIndex.get() + 1) > 16) {
765             // the sub index Y (in X.Y) is above the register limits
766             String errmsg = String.format("readStart=X.Y, the value Y is too large");
767             throw new ModbusConfigurationException(errmsg);
768         }
769
770         // Determine bit positions polled, both start and end inclusive
771         int pollStartBitIndex = readRequest.getReference() * 16;
772         int pollEndBitIndex = pollStartBitIndex + readRequest.getDataLength() * 16 - 1;
773
774         // Determine bit positions read, both start and end inclusive
775         int writeStartBitIndex = writeStart.get() * 16 + readSubIndex.orElse(0);
776         int writeEndBitIndex = writeStartBitIndex - 1;
777
778         if (writeStartBitIndex < pollStartBitIndex || writeEndBitIndex > pollEndBitIndex) {
779             String errmsg = String.format(
780                     "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",
781                     pollStartBitIndex / 16, pollEndBitIndex / 16, writeStart.get());
782             throw new ModbusConfigurationException(errmsg);
783         }
784     }
785
786     private boolean containsOnOff(List<Class<? extends State>> channelAcceptedDataTypes) {
787         return channelAcceptedDataTypes.stream().anyMatch(clz -> clz.equals(OnOffType.class));
788     }
789
790     private boolean containsOpenClosed(List<Class<? extends State>> acceptedDataTypes) {
791         return acceptedDataTypes.stream().anyMatch(clz -> clz.equals(OpenClosedType.class));
792     }
793
794     public synchronized void onReadResult(AsyncModbusReadResult result) {
795         result.getRegisters().ifPresent(registers -> onRegisters(result.getRequest(), registers));
796         result.getBits().ifPresent(bits -> onBits(result.getRequest(), bits));
797     }
798
799     public synchronized void handleReadError(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
800         onError(failure.getRequest(), failure.getCause());
801     }
802
803     public synchronized void handleWriteError(AsyncModbusFailure<ModbusWriteRequestBlueprint> failure) {
804         onError(failure.getRequest(), failure.getCause());
805     }
806
807     private synchronized void onRegisters(ModbusReadRequestBlueprint request, ModbusRegisterArray registers) {
808         if (hasConfigurationError()) {
809             return;
810         } else if (!isReadEnabled) {
811             return;
812         }
813         ValueType readValueType = this.readValueType;
814         if (readValueType == null) {
815             return;
816         }
817         State numericState;
818
819         // extractIndex:
820         // e.g. with bit, extractIndex=4 means 5th bit (from right) ("10.4" -> 5th bit of register 10, "10.4" -> 5th bit
821         // of register 10)
822         // bit of second register)
823         // e.g. with 8bit integer, extractIndex=3 means high byte of second register
824         //
825         // with <16 bit types, this is the index of the N'th 1-bit/8-bit item. Each register has 16/2 items,
826         // respectively.
827         // with >=16 bit types, this is index of first register
828         int extractIndex;
829         if (readValueType.getBits() >= 16) {
830             // Invariant, checked in initialize
831             assert readSubIndex.orElse(0) == 0;
832             extractIndex = readIndex.get() - pollStart;
833         } else {
834             int subIndex = readSubIndex.orElse(0);
835             int itemsPerRegister = 16 / readValueType.getBits();
836             extractIndex = (readIndex.get() - pollStart) * itemsPerRegister + subIndex;
837         }
838         numericState = ModbusBitUtilities.extractStateFromRegisters(registers, extractIndex, readValueType)
839                 .map(state -> (State) state).orElse(UnDefType.UNDEF);
840         boolean boolValue = !numericState.equals(DecimalType.ZERO);
841         Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
842         logger.debug(
843                 "Thing {} channels updated: {}. readValueType={}, readIndex={}, readSubIndex(or 0)={}, extractIndex={} -> numeric value {} and boolValue={}. Registers {} for request {}",
844                 thing.getUID(), values, readValueType, readIndex, readSubIndex.orElse(0), extractIndex, numericState,
845                 boolValue, registers, request);
846     }
847
848     private synchronized void onBits(ModbusReadRequestBlueprint request, BitArray bits) {
849         if (hasConfigurationError()) {
850             return;
851         } else if (!isReadEnabled) {
852             return;
853         }
854         boolean boolValue = bits.getBit(readIndex.get() - pollStart);
855         DecimalType numericState = boolValue ? new DecimalType(BigDecimal.ONE) : DecimalType.ZERO;
856         Map<ChannelUID, State> values = processUpdatedValue(numericState, boolValue);
857         logger.debug(
858                 "Thing {} channels updated: {}. readValueType={}, readIndex={} -> numeric value {} and boolValue={}. Bits {} for request {}",
859                 thing.getUID(), values, readValueType, readIndex, numericState, boolValue, bits, request);
860     }
861
862     private synchronized void onError(ModbusReadRequestBlueprint request, Exception error) {
863         if (hasConfigurationError()) {
864             return;
865         } else if (!isReadEnabled) {
866             return;
867         }
868         if (error instanceof ModbusConnectionException) {
869             logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
870                     error.getClass().getSimpleName(), error.toString());
871         } else if (error instanceof ModbusTransportException) {
872             logger.trace("Thing {} '{}' had {} error on read: {}", getThing().getUID(), getThing().getLabel(),
873                     error.getClass().getSimpleName(), error.toString());
874         } else {
875             logger.error(
876                     "Thing {} '{}' had {} error on read: {} (message: {}). Stack trace follows since this is unexpected error.",
877                     getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
878                     error.getMessage(), error);
879         }
880         Map<ChannelUID, State> states = new HashMap<>();
881         ChannelUID lastReadErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_ERROR);
882         if (isLinked(lastReadErrorUID)) {
883             states.put(lastReadErrorUID, new DateTimeType());
884         }
885
886         synchronized (this) {
887             // Update channels
888             states.forEach((uid, state) -> {
889                 tryUpdateState(uid, state);
890             });
891
892             updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
893                     String.format("Error (%s) with read. Request: %s. Description: %s. Message: %s",
894                             error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
895         }
896     }
897
898     private synchronized void onError(ModbusWriteRequestBlueprint request, Exception error) {
899         if (hasConfigurationError()) {
900             return;
901         } else if (!isWriteEnabled) {
902             return;
903         }
904         if (error instanceof ModbusConnectionException) {
905             logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
906                     error.getClass().getSimpleName(), error.toString());
907         } else if (error instanceof ModbusTransportException) {
908             logger.debug("Thing {} '{}' had {} error on write: {}", getThing().getUID(), getThing().getLabel(),
909                     error.getClass().getSimpleName(), error.toString());
910         } else {
911             logger.error(
912                     "Thing {} '{}' had {} error on write: {} (message: {}). Stack trace follows since this is unexpected error.",
913                     getThing().getUID(), getThing().getLabel(), error.getClass().getName(), error.toString(),
914                     error.getMessage(), error);
915         }
916         Map<ChannelUID, State> states = new HashMap<>();
917         ChannelUID lastWriteErrorUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_ERROR);
918         if (isLinked(lastWriteErrorUID)) {
919             states.put(lastWriteErrorUID, new DateTimeType());
920         }
921
922         synchronized (this) {
923             // Update channels
924             states.forEach((uid, state) -> {
925                 tryUpdateState(uid, state);
926             });
927
928             updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
929                     String.format("Error (%s) with write. Request: %s. Description: %s. Message: %s",
930                             error.getClass().getSimpleName(), request, error.toString(), error.getMessage()));
931         }
932     }
933
934     public synchronized void onWriteResponse(AsyncModbusWriteResult result) {
935         if (hasConfigurationError()) {
936             return;
937         } else if (!isWriteEnabled) {
938             return;
939         }
940         logger.debug("Successful write, matching request {}", result.getRequest());
941         updateStatusIfChanged(ThingStatus.ONLINE);
942         ChannelUID lastWriteSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_WRITE_SUCCESS);
943         if (isLinked(lastWriteSuccessUID)) {
944             updateState(lastWriteSuccessUID, new DateTimeType());
945         }
946     }
947
948     /**
949      * Update linked channels
950      *
951      * @param numericState numeric state corresponding to polled data (or UNDEF with floating point NaN or infinity)
952      * @param boolValue boolean value corresponding to polled data
953      * @return updated channel data
954      */
955     private Map<ChannelUID, State> processUpdatedValue(State numericState, boolean boolValue) {
956         ValueTransformation localReadTransformation = readTransformation;
957         if (localReadTransformation == null) {
958             // We should always have transformation available if thing is initalized properly
959             logger.trace("No transformation available, aborting processUpdatedValue");
960             return Collections.emptyMap();
961         }
962         Map<ChannelUID, State> states = new HashMap<>();
963         CHANNEL_ID_TO_ACCEPTED_TYPES.keySet().stream().forEach(channelId -> {
964             ChannelUID channelUID = getChannelUID(channelId);
965             if (!isLinked(channelUID)) {
966                 return;
967             }
968             List<Class<? extends State>> acceptedDataTypes = CHANNEL_ID_TO_ACCEPTED_TYPES.get(channelId);
969             if (acceptedDataTypes.isEmpty()) {
970                 return;
971             }
972
973             State boolLikeState;
974             if (containsOnOff(acceptedDataTypes)) {
975                 boolLikeState = boolValue ? OnOffType.ON : OnOffType.OFF;
976             } else if (containsOpenClosed(acceptedDataTypes)) {
977                 boolLikeState = boolValue ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
978             } else {
979                 boolLikeState = null;
980             }
981
982             State transformedState;
983             if (localReadTransformation.isIdentityTransform()) {
984                 if (boolLikeState != null) {
985                     // A bit of smartness for ON/OFF and OPEN/CLOSED with boolean like items
986                     transformedState = boolLikeState;
987                 } else {
988                     // Numeric states always go through transformation. This allows value of 17.5 to be
989                     // converted to
990                     // 17.5% with percent types (instead of raising error)
991                     transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
992                             numericState);
993                 }
994             } else {
995                 transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes,
996                         numericState);
997             }
998
999             if (transformedState != null) {
1000                 logger.trace(
1001                         "Channel {} will be updated to '{}' (type {}). Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}",
1002                         channelId, transformedState, transformedState.getClass().getSimpleName(), numericState,
1003                         readValueType, boolValue,
1004                         localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
1005                 states.put(channelUID, transformedState);
1006             } else {
1007                 String types = String.join(", ",
1008                         acceptedDataTypes.stream().map(cls -> cls.getSimpleName()).toArray(String[]::new));
1009                 logger.warn(
1010                         "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: {}",
1011                         channelId, types, numericState, readValueType, boolValue,
1012                         localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
1013             }
1014         });
1015
1016         ChannelUID lastReadSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_SUCCESS);
1017         if (isLinked(lastReadSuccessUID)) {
1018             states.put(lastReadSuccessUID, new DateTimeType());
1019         }
1020         updateExpiredChannels(states);
1021         return states;
1022     }
1023
1024     private void updateExpiredChannels(Map<ChannelUID, State> states) {
1025         synchronized (this) {
1026             updateStatusIfChanged(ThingStatus.ONLINE);
1027             long now = System.currentTimeMillis();
1028             // Update channels that have not been updated in a while, or when their values has changed
1029             states.forEach((uid, state) -> updateExpiredChannel(now, uid, state));
1030             channelLastState = states;
1031         }
1032     }
1033
1034     // since lastState can be null, and "lastState == null" in conditional is not useless
1035     @SuppressWarnings("null")
1036     private void updateExpiredChannel(long now, ChannelUID uid, State state) {
1037         @Nullable
1038         State lastState = channelLastState.get(uid);
1039         long lastUpdatedMillis = channelLastUpdated.getOrDefault(uid, 0L);
1040         long millisSinceLastUpdate = now - lastUpdatedMillis;
1041         if (lastUpdatedMillis <= 0L || lastState == null || updateUnchangedValuesEveryMillis <= 0L
1042                 || millisSinceLastUpdate > updateUnchangedValuesEveryMillis || !lastState.equals(state)) {
1043             tryUpdateState(uid, state);
1044             channelLastUpdated.put(uid, now);
1045         }
1046     }
1047
1048     private void tryUpdateState(ChannelUID uid, State state) {
1049         try {
1050             updateState(uid, state);
1051         } catch (IllegalArgumentException e) {
1052             logger.warn("Error updating state '{}' (type {}) to channel {}: {} {}", state,
1053                     Optional.ofNullable(state).map(s -> s.getClass().getName()).orElse("null"), uid,
1054                     e.getClass().getName(), e.getMessage());
1055         }
1056     }
1057
1058     private ChannelUID getChannelUID(String channelID) {
1059         return Objects
1060                 .requireNonNull(channelCache.computeIfAbsent(channelID, id -> new ChannelUID(getThing().getUID(), id)));
1061     }
1062
1063     private void updateStatusIfChanged(ThingStatus status) {
1064         updateStatusIfChanged(status, ThingStatusDetail.NONE, null);
1065     }
1066
1067     private void updateStatusIfChanged(ThingStatus status, ThingStatusDetail statusDetail,
1068             @Nullable String description) {
1069         ThingStatusInfo newStatusInfo = new ThingStatusInfo(status, statusDetail, description);
1070         Duration durationSinceLastUpdate = Duration.between(lastStatusInfoUpdate, LocalDateTime.now());
1071         boolean intervalElapsed = MIN_STATUS_INFO_UPDATE_INTERVAL.minus(durationSinceLastUpdate).isNegative();
1072         if (statusInfo.getStatus() == ThingStatus.UNKNOWN || !statusInfo.equals(newStatusInfo) || intervalElapsed) {
1073             statusInfo = newStatusInfo;
1074             lastStatusInfoUpdate = LocalDateTime.now();
1075             updateStatus(newStatusInfo);
1076         }
1077     }
1078
1079     /**
1080      * Update status using pre-constructed ThingStatusInfo
1081      *
1082      * Implementation adapted from BaseThingHandler updateStatus implementations
1083      *
1084      * @param statusInfo new status info
1085      */
1086     protected void updateStatus(ThingStatusInfo statusInfo) {
1087         synchronized (this) {
1088             ThingHandlerCallback callback = getCallback();
1089             if (callback != null) {
1090                 callback.statusUpdated(this.thing, statusInfo);
1091             } else {
1092                 logger.warn("Handler {} tried updating the thing status although the handler was already disposed.",
1093                         this.getClass().getSimpleName());
1094             }
1095         }
1096     }
1097 }