]> git.basschouten.com Git - openhab-addons.git/blob
10491b01a7b4b24d7a785b21a92c81637ce349d4
[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.handler;
14
15 import java.util.List;
16 import java.util.Optional;
17 import java.util.concurrent.CopyOnWriteArrayList;
18 import java.util.concurrent.atomic.AtomicReference;
19 import java.util.stream.Collectors;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.modbus.internal.AtomicStampedValue;
24 import org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal;
25 import org.openhab.binding.modbus.internal.config.ModbusPollerConfiguration;
26 import org.openhab.binding.modbus.internal.handler.ModbusDataThingHandler;
27 import org.openhab.core.io.transport.modbus.AsyncModbusFailure;
28 import org.openhab.core.io.transport.modbus.AsyncModbusReadResult;
29 import org.openhab.core.io.transport.modbus.ModbusCommunicationInterface;
30 import org.openhab.core.io.transport.modbus.ModbusConstants;
31 import org.openhab.core.io.transport.modbus.ModbusFailureCallback;
32 import org.openhab.core.io.transport.modbus.ModbusReadCallback;
33 import org.openhab.core.io.transport.modbus.ModbusReadFunctionCode;
34 import org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint;
35 import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
36 import org.openhab.core.io.transport.modbus.PollTask;
37 import org.openhab.core.thing.Bridge;
38 import org.openhab.core.thing.ChannelUID;
39 import org.openhab.core.thing.Thing;
40 import org.openhab.core.thing.ThingStatus;
41 import org.openhab.core.thing.ThingStatusDetail;
42 import org.openhab.core.thing.ThingStatusInfo;
43 import org.openhab.core.thing.binding.BaseBridgeHandler;
44 import org.openhab.core.thing.binding.ThingHandler;
45 import org.openhab.core.types.Command;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * The {@link ModbusPollerThingHandler} is responsible for polling Modbus slaves. Errors and data is delegated to
51  * child thing handlers inheriting from {@link ModbusReadCallback} -- in practice: {@link ModbusDataThingHandler}.
52  *
53  * @author Sami Salonen - Initial contribution
54  */
55 @NonNullByDefault
56 public class ModbusPollerThingHandler extends BaseBridgeHandler {
57
58     /**
59      * {@link ModbusReadCallback} that delegates all tasks forward.
60      *
61      * All instances of {@linkplain ReadCallbackDelegator} are considered equal, if they are connected to the same
62      * bridge. This makes sense, as the callback delegates
63      * to all child things of this bridge.
64      *
65      * @author Sami Salonen - Initial contribution
66      *
67      */
68     private class ReadCallbackDelegator
69             implements ModbusReadCallback, ModbusFailureCallback<ModbusReadRequestBlueprint> {
70
71         private volatile @Nullable AtomicStampedValue<PollResult> lastResult;
72
73         public synchronized void handleResult(PollResult result) {
74             // Ignore all incoming data and errors if configuration is not correct
75             if (hasConfigurationError() || disposed) {
76                 return;
77             }
78             if (config.getCacheMillis() >= 0) {
79                 AtomicStampedValue<PollResult> localLastResult = this.lastResult;
80                 if (localLastResult == null) {
81                     this.lastResult = new AtomicStampedValue<>(System.currentTimeMillis(), result);
82                 } else {
83                     localLastResult.update(System.currentTimeMillis(), result);
84                     this.lastResult = localLastResult;
85                 }
86             }
87             logger.debug("Thing {} received response {}", thing.getUID(), result);
88             notifyChildren(result);
89             if (result.failure != null) {
90                 Exception error = result.failure.getCause();
91                 assert error != null;
92                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
93                         String.format("Error with read: %s: %s", error.getClass().getName(), error.getMessage()));
94             } else {
95                 resetCommunicationError();
96             }
97         }
98
99         @Override
100         public synchronized void handle(AsyncModbusReadResult result) {
101             // Casting to allow registers.orElse(null) below..
102             Optional<@Nullable ModbusRegisterArray> registers = (Optional<@Nullable ModbusRegisterArray>) result
103                     .getRegisters();
104             lastPolledDataCache.set(registers.orElse(null));
105             handleResult(new PollResult(result));
106         }
107
108         @Override
109         public synchronized void handle(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
110             handleResult(new PollResult(failure));
111         }
112
113         private void resetCommunicationError() {
114             ThingStatusInfo statusInfo = thing.getStatusInfo();
115             if (ThingStatus.OFFLINE.equals(statusInfo.getStatus())
116                     && ThingStatusDetail.COMMUNICATION_ERROR.equals(statusInfo.getStatusDetail())) {
117                 updateStatus(ThingStatus.ONLINE);
118             }
119         }
120
121         /**
122          * Update children data if data is fresh enough
123          *
124          * @param oldestStamp oldest data that is still passed to children
125          * @return whether data was updated. Data is not updated when it's too old or there's no data at all.
126          */
127         @SuppressWarnings("null")
128         public boolean updateChildrenWithOldData(long oldestStamp) {
129             return Optional.ofNullable(this.lastResult).map(result -> result.copyIfStampAfter(oldestStamp))
130                     .map(result -> {
131                         logger.debug("Thing {} reusing cached data: {}", thing.getUID(), result.getValue());
132                         notifyChildren(result.getValue());
133                         return true;
134                     }).orElse(false);
135         }
136
137         private void notifyChildren(PollResult pollResult) {
138             @Nullable
139             AsyncModbusReadResult result = pollResult.result;
140             @Nullable
141             AsyncModbusFailure<ModbusReadRequestBlueprint> failure = pollResult.failure;
142             childCallbacks.forEach(handler -> {
143                 if (result != null) {
144                     handler.onReadResult(result);
145                 } else if (failure != null) {
146                     handler.handleReadError(failure);
147                 }
148             });
149         }
150
151         /**
152          * Rest data caches
153          */
154         public void resetCache() {
155             lastResult = null;
156         }
157     }
158
159     /**
160      * Immutable data object to cache the results of a poll request
161      */
162     private class PollResult {
163
164         public final @Nullable AsyncModbusReadResult result;
165         public final @Nullable AsyncModbusFailure<ModbusReadRequestBlueprint> failure;
166
167         PollResult(AsyncModbusReadResult result) {
168             this.result = result;
169             this.failure = null;
170         }
171
172         PollResult(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
173             this.result = null;
174             this.failure = failure;
175         }
176
177         @Override
178         public String toString() {
179             return failure == null ? String.format("PollResult(result=%s)", result)
180                     : String.format("PollResult(failure=%s)", failure);
181         }
182     }
183
184     private final Logger logger = LoggerFactory.getLogger(ModbusPollerThingHandler.class);
185
186     private static final List<String> SORTED_READ_FUNCTION_CODES = ModbusBindingConstantsInternal.READ_FUNCTION_CODES
187             .keySet().stream().sorted().collect(Collectors.toUnmodifiableList());
188
189     private @NonNullByDefault({}) ModbusPollerConfiguration config;
190     private long cacheMillis;
191     private volatile @Nullable PollTask pollTask;
192     private volatile @Nullable ModbusReadRequestBlueprint request;
193     private volatile boolean disposed;
194     private volatile List<ModbusDataThingHandler> childCallbacks = new CopyOnWriteArrayList<>();
195     private volatile AtomicReference<@Nullable ModbusRegisterArray> lastPolledDataCache = new AtomicReference<>();
196     private @NonNullByDefault({}) ModbusCommunicationInterface comms;
197
198     private ReadCallbackDelegator callbackDelegator = new ReadCallbackDelegator();
199
200     private @Nullable ModbusReadFunctionCode functionCode;
201
202     public ModbusPollerThingHandler(Bridge bridge) {
203         super(bridge);
204     }
205
206     @Override
207     public void handleCommand(ChannelUID channelUID, Command command) {
208         // No channels, no commands
209     }
210
211     private @Nullable ModbusEndpointThingHandler getEndpointThingHandler() {
212         Bridge bridge = getBridge();
213         if (bridge == null) {
214             logger.debug("Bridge is null");
215             return null;
216         }
217         if (bridge.getStatus() != ThingStatus.ONLINE) {
218             logger.debug("Bridge is not online");
219             return null;
220         }
221
222         ThingHandler handler = bridge.getHandler();
223         if (handler == null) {
224             logger.debug("Bridge handler is null");
225             return null;
226         }
227
228         if (handler instanceof ModbusEndpointThingHandler thingHandler) {
229             return thingHandler;
230         } else {
231             logger.debug("Unexpected bridge handler: {}", handler);
232             return null;
233         }
234     }
235
236     @Override
237     public synchronized void initialize() {
238         if (this.getThing().getStatus().equals(ThingStatus.ONLINE)) {
239             // If the bridge was online then first change it to offline.
240             // this ensures that children will be notified about the change
241             updateStatus(ThingStatus.OFFLINE);
242         }
243         this.callbackDelegator.resetCache();
244         comms = null;
245         request = null;
246         disposed = false;
247         logger.trace("Initializing {} from status {}", this.getThing().getUID(), this.getThing().getStatus());
248         try {
249             config = getConfigAs(ModbusPollerConfiguration.class);
250             String type = config.getType();
251             if (!ModbusBindingConstantsInternal.READ_FUNCTION_CODES.containsKey(type)) {
252                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
253                         String.format("No function code found for type='%s'. Was expecting one of: %s", type,
254                                 String.join(", ", SORTED_READ_FUNCTION_CODES)));
255                 return;
256             }
257             functionCode = ModbusBindingConstantsInternal.READ_FUNCTION_CODES.get(type);
258             switch (functionCode) {
259                 case READ_INPUT_REGISTERS:
260                 case READ_MULTIPLE_REGISTERS:
261                     if (config.getLength() > ModbusConstants.MAX_REGISTERS_READ_COUNT) {
262                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
263                                 "Maximum of %d registers can be polled at once due to protocol limitations. Length %d is out of bounds.",
264                                 ModbusConstants.MAX_REGISTERS_READ_COUNT, config.getLength()));
265                         return;
266                     }
267                     break;
268                 case READ_COILS:
269                 case READ_INPUT_DISCRETES:
270                     if (config.getLength() > ModbusConstants.MAX_BITS_READ_COUNT) {
271                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format(
272                                 "Maximum of %d coils/discrete inputs can be polled at once due to protocol limitations. Length %d is out of bounds.",
273                                 ModbusConstants.MAX_BITS_READ_COUNT, config.getLength()));
274                         return;
275                     }
276                     break;
277             }
278             cacheMillis = this.config.getCacheMillis();
279             registerPollTask();
280         } catch (EndpointNotInitializedException e) {
281             logger.debug("Exception during initialization", e);
282             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String
283                     .format("Exception during initialization: %s (%s)", e.getMessage(), e.getClass().getSimpleName()));
284         } finally {
285             logger.trace("initialize() of thing {} '{}' finished", thing.getUID(), thing.getLabel());
286         }
287     }
288
289     @Override
290     public synchronized void dispose() {
291         logger.debug("dispose()");
292         // Mark handler as disposed as soon as possible to halt processing of callbacks
293         disposed = true;
294         unregisterPollTask();
295         this.callbackDelegator.resetCache();
296         comms = null;
297         lastPolledDataCache.set(null);
298     }
299
300     /**
301      * Unregister poll task.
302      *
303      * No-op in case no poll task is registered, or if the initialization is incomplete.
304      */
305     public synchronized void unregisterPollTask() {
306         logger.trace("unregisterPollTask()");
307         if (config == null) {
308             return;
309         }
310         PollTask localPollTask = this.pollTask;
311         if (localPollTask != null) {
312             logger.debug("Unregistering polling from ModbusManager");
313             comms.unregisterRegularPoll(localPollTask);
314         }
315         this.pollTask = null;
316         request = null;
317         comms = null;
318         updateStatus(ThingStatus.OFFLINE);
319     }
320
321     /**
322      * Register poll task
323      *
324      * @throws EndpointNotInitializedException in case the bridge initialization is not complete. This should only
325      *             happen in transient conditions, for example, when bridge is initializing.
326      */
327     @SuppressWarnings("null")
328     private synchronized void registerPollTask() throws EndpointNotInitializedException {
329         logger.trace("registerPollTask()");
330         if (pollTask != null) {
331             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
332             logger.debug("pollTask should be unregistered before registering a new one!");
333             return;
334         }
335
336         ModbusEndpointThingHandler slaveEndpointThingHandler = getEndpointThingHandler();
337         if (slaveEndpointThingHandler == null) {
338             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, String.format("Bridge '%s' is offline",
339                     Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>")));
340             logger.debug("No bridge handler available -- aborting init for {}", this);
341             return;
342         }
343         ModbusCommunicationInterface localComms = slaveEndpointThingHandler.getCommunicationInterface();
344         if (localComms == null) {
345             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, String.format(
346                     "Bridge '%s' not completely initialized", Optional.ofNullable(getBridge()).map(b -> b.getLabel())));
347             logger.debug("Bridge not initialized fully (no communication interface) -- aborting init for {}", this);
348             return;
349         }
350         this.comms = localComms;
351         ModbusReadFunctionCode localFunctionCode = functionCode;
352         if (localFunctionCode == null) {
353             return;
354         }
355
356         ModbusReadRequestBlueprint localRequest = new ModbusReadRequestBlueprint(slaveEndpointThingHandler.getSlaveId(),
357                 localFunctionCode, config.getStart(), config.getLength(), config.getMaxTries());
358         this.request = localRequest;
359
360         if (config.getRefresh() <= 0L) {
361             logger.debug("Not registering polling with ModbusManager since refresh disabled");
362             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, "Not polling");
363         } else {
364             logger.debug("Registering polling with ModbusManager");
365             pollTask = localComms.registerRegularPoll(localRequest, config.getRefresh(), 0, callbackDelegator,
366                     callbackDelegator);
367             assert pollTask != null;
368             updateStatus(ThingStatus.ONLINE);
369         }
370     }
371
372     private boolean hasConfigurationError() {
373         ThingStatusInfo statusInfo = getThing().getStatusInfo();
374         return statusInfo.getStatus() == ThingStatus.OFFLINE
375                 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
376     }
377
378     @Override
379     public synchronized void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
380         logger.debug("bridgeStatusChanged for {}. Reseting handler", this.getThing().getUID());
381         this.dispose();
382         this.initialize();
383     }
384
385     @Override
386     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
387         if (childHandler instanceof ModbusDataThingHandler modbusDataThingHandler) {
388             this.childCallbacks.add(modbusDataThingHandler);
389         }
390     }
391
392     @SuppressWarnings("unlikely-arg-type")
393     @Override
394     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
395         if (childHandler instanceof ModbusDataThingHandler) {
396             this.childCallbacks.remove(childHandler);
397         }
398     }
399
400     /**
401      * Return {@link ModbusReadRequestBlueprint} represented by this thing.
402      *
403      * Note that request might be <code>null</code> in case initialization is not complete.
404      *
405      * @return modbus request represented by this poller
406      */
407     public @Nullable ModbusReadRequestBlueprint getRequest() {
408         return request;
409     }
410
411     /**
412      * Get communication interface associated with this poller
413      *
414      * @return
415      */
416     public ModbusCommunicationInterface getCommunicationInterface() {
417         return comms;
418     }
419
420     /**
421      * Refresh the data
422      *
423      * If data or error was just recently received (i.e. cache is fresh), return the cached response.
424      */
425     public void refresh() {
426         ModbusReadRequestBlueprint localRequest = this.request;
427         if (localRequest == null) {
428             return;
429         }
430         ModbusRegisterArray possiblyMutatedCache = lastPolledDataCache.get();
431         AtomicStampedValue<PollResult> lastPollResult = callbackDelegator.lastResult;
432         if (lastPollResult != null && possiblyMutatedCache != null) {
433             AsyncModbusReadResult lastSuccessfulPollResult = lastPollResult.getValue().result;
434             if (lastSuccessfulPollResult != null) {
435                 ModbusRegisterArray lastRegisters = ((Optional<@Nullable ModbusRegisterArray>) lastSuccessfulPollResult
436                         .getRegisters()).orElse(null);
437                 if (lastRegisters != null && !possiblyMutatedCache.equals(lastRegisters)) {
438                     // Register has been mutated in between by a data thing that writes "individual bits"
439                     // Invalidate cache for a fresh poll
440                     callbackDelegator.resetCache();
441                 }
442             }
443         }
444
445         long oldDataThreshold = System.currentTimeMillis() - cacheMillis;
446         boolean cacheWasRecentEnoughForUpdate = cacheMillis > 0
447                 && this.callbackDelegator.updateChildrenWithOldData(oldDataThreshold);
448         if (cacheWasRecentEnoughForUpdate) {
449             logger.debug(
450                     "Poller {} received refresh() and cache was recent enough (age at most {} ms). Reusing old response",
451                     getThing().getUID(), cacheMillis);
452         } else {
453             // cache expired, poll new data
454             logger.debug("Poller {} received refresh() but the cache is not applicable. Polling new data",
455                     getThing().getUID());
456             ModbusCommunicationInterface localComms = comms;
457             if (localComms != null) {
458                 localComms.submitOneTimePoll(localRequest, callbackDelegator, callbackDelegator);
459             }
460         }
461     }
462
463     public AtomicReference<@Nullable ModbusRegisterArray> getLastPolledDataCache() {
464         return lastPolledDataCache;
465     }
466 }