]> git.basschouten.com Git - openhab-addons.git/blob
3a0d97412f2c1e49f86afbd46694eca9247c5bdb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.studer.internal;
14
15 import static org.openhab.binding.modbus.studer.internal.StuderBindingConstants.*;
16
17 import java.util.ArrayList;
18 import java.util.Optional;
19 import java.util.Set;
20
21 import javax.measure.Unit;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
26 import org.openhab.binding.modbus.studer.internal.StuderParser.ModeXtender;
27 import org.openhab.binding.modbus.studer.internal.StuderParser.VSMode;
28 import org.openhab.binding.modbus.studer.internal.StuderParser.VTMode;
29 import org.openhab.binding.modbus.studer.internal.StuderParser.VTType;
30 import org.openhab.core.library.types.OnOffType;
31 import org.openhab.core.library.types.QuantityType;
32 import org.openhab.core.library.types.StringType;
33 import org.openhab.core.thing.Bridge;
34 import org.openhab.core.thing.ChannelUID;
35 import org.openhab.core.thing.Thing;
36 import org.openhab.core.thing.ThingStatus;
37 import org.openhab.core.thing.ThingStatusDetail;
38 import org.openhab.core.thing.ThingStatusInfo;
39 import org.openhab.core.thing.ThingTypeUID;
40 import org.openhab.core.thing.binding.BaseThingHandler;
41 import org.openhab.core.thing.binding.ThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.State;
44 import org.openhab.core.types.UnDefType;
45 import org.openhab.io.transport.modbus.AsyncModbusFailure;
46 import org.openhab.io.transport.modbus.ModbusCommunicationInterface;
47 import org.openhab.io.transport.modbus.ModbusReadFunctionCode;
48 import org.openhab.io.transport.modbus.ModbusReadRequestBlueprint;
49 import org.openhab.io.transport.modbus.ModbusRegisterArray;
50 import org.openhab.io.transport.modbus.PollTask;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * The {@link StuderHandler} is responsible for handling commands, which are
56  * sent to one of the channels.
57  *
58  * @author Giovanni Mirulla - Initial contribution
59  */
60 @NonNullByDefault
61 public class StuderHandler extends BaseThingHandler {
62
63     private final Logger logger = LoggerFactory.getLogger(StuderHandler.class);
64
65     private @Nullable StuderConfiguration config;
66
67     /**
68      * Array of tasks used to poll the device
69      */
70     private ArrayList<PollTask> pollTasks = new ArrayList<PollTask>();
71
72     /**
73      * Communication interface to the slave endpoint we're connecting to
74      */
75     protected volatile @Nullable ModbusCommunicationInterface comms = null;
76
77     /**
78      * Importing parser methods and enums
79      */
80     final StuderParser parser = new StuderParser();
81     /**
82      * Support variable for type of thing
83      */
84     protected ThingTypeUID type;
85
86     /**
87      * Array of registers of Studer slave to read, we store this once initialization is complete
88      */
89     private Integer[] registers = new Integer[0];
90
91     /**
92      * Instances of this handler
93      *
94      * @param thing the thing to handle
95      * @param type the type of thing to handle
96      * @param slaveAddress the address of thing
97      * @param refreshSec the address of thing
98      */
99     public StuderHandler(Thing thing) {
100         super(thing);
101         this.type = thing.getThingTypeUID();
102     }
103
104     @Override
105     public void handleCommand(ChannelUID channelUID, Command command) {
106
107         // Currently we do not support any commands
108     }
109
110     /**
111      * Initialization:
112      * Load the config object
113      * Connect to the slave bridge
114      * Get registers to poll
115      * Start the periodic polling
116      */
117     @Override
118     public void initialize() {
119         config = getConfigAs(StuderConfiguration.class);
120         logger.debug("Initializing thing with configuration: {}", thing.getConfiguration());
121
122         startUp();
123     }
124
125     /*
126      * This method starts the operation of this handler
127      * Connect to the slave bridge
128      * Get registers to poll
129      * Start the periodic polling
130      */
131     private void startUp() {
132
133         connectEndpoint();
134
135         if (comms == null || config == null) {
136             logger.debug("Invalid endpoint/config/manager ref for studer handler");
137             return;
138         }
139
140         if (!pollTasks.isEmpty()) {
141             return;
142         }
143
144         if (type.equals(THING_TYPE_BSP)) {
145             Set<Integer> keys = CHANNELS_BSP.keySet();
146             registers = keys.toArray(new Integer[keys.size()]);
147         } else if (type.equals(THING_TYPE_XTENDER)) {
148             Set<Integer> keys = CHANNELS_XTENDER.keySet();
149             registers = keys.toArray(new Integer[keys.size()]);
150         } else if (type.equals(THING_TYPE_VARIOTRACK)) {
151             Set<Integer> keys = CHANNELS_VARIOTRACK.keySet();
152             registers = keys.toArray(new Integer[keys.size()]);
153         } else if (type.equals(THING_TYPE_VARIOSTRING)) {
154             Set<Integer> keys = CHANNELS_VARIOSTRING.keySet();
155             registers = keys.toArray(new Integer[keys.size()]);
156         }
157
158         for (int r : registers) {
159             registerPollTask(r);
160
161         }
162     }
163
164     /**
165      * Dispose the binding correctly
166      */
167     @Override
168     public void dispose() {
169         tearDown();
170     }
171
172     /**
173      * Unregister the poll tasks and release the endpoint reference
174      */
175     private void tearDown() {
176         unregisterPollTasks();
177         unregisterEndpoint();
178     }
179
180     /**
181      * Get the endpoint handler from the bridge this handler is connected to
182      * Checks that we're connected to the right type of bridge
183      *
184      * @return the endpoint handler or null if the bridge does not exist
185      */
186     private @Nullable ModbusEndpointThingHandler getEndpointThingHandler() {
187         Bridge bridge = getBridge();
188         if (bridge == null) {
189             logger.debug("Bridge is null");
190             return null;
191         }
192         if (bridge.getStatus() != ThingStatus.ONLINE) {
193             logger.debug("Bridge is not online");
194             return null;
195         }
196
197         ThingHandler handler = bridge.getHandler();
198         if (handler == null) {
199             logger.debug("Bridge handler is null");
200             return null;
201         }
202
203         if (handler instanceof ModbusEndpointThingHandler) {
204             ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
205             return slaveEndpoint;
206         } else {
207             logger.debug("Unexpected bridge handler: {}", handler);
208             return null;
209         }
210     }
211
212     /**
213      * Get a reference to the modbus endpoint
214      */
215     private void connectEndpoint() {
216         if (comms != null) {
217             return;
218         }
219
220         ModbusEndpointThingHandler slaveEndpointThingHandler = getEndpointThingHandler();
221         if (slaveEndpointThingHandler == null) {
222             @SuppressWarnings("null")
223             String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
224             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
225                     String.format("Bridge '%s' is offline", label));
226             logger.debug("No bridge handler available -- aborting init for {}", label);
227             return;
228         }
229         comms = slaveEndpointThingHandler.getCommunicationInterface();
230         if (comms == null) {
231             @SuppressWarnings("null")
232             String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
233             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
234                     String.format("Bridge '%s' not completely initialized", label));
235             logger.debug("Bridge not initialized fully (no endpoint) -- aborting init for {}", this);
236             return;
237         }
238     }
239
240     /**
241      * Remove the endpoint if exists
242      */
243     private void unregisterEndpoint() {
244         // Comms will be close()'d by endpoint thing handler
245         comms = null;
246     }
247
248     private synchronized void unregisterPollTasks() {
249         if (pollTasks.isEmpty()) {
250             return;
251         }
252         logger.debug("Unregistering polling from ModbusManager");
253         ModbusCommunicationInterface mycomms = comms;
254         if (mycomms != null) {
255             for (PollTask t : pollTasks) {
256                 mycomms.unregisterRegularPoll(t);
257             }
258             pollTasks.clear();
259         }
260     }
261
262     /**
263      * Register poll task
264      * This is where we set up our regular poller
265      */
266     private synchronized void registerPollTask(int registerNumber) {
267         if (pollTasks.size() >= registers.length) {
268             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR);
269             throw new IllegalStateException("New pollTask invalid");
270         }
271         ModbusCommunicationInterface mycomms = comms;
272         StuderConfiguration studerConfig = config;
273         if (studerConfig == null || mycomms == null) {
274             throw new IllegalStateException("registerPollTask called without proper configuration");
275         }
276
277         logger.debug("Setting up regular polling");
278
279         ModbusReadRequestBlueprint request = new ModbusReadRequestBlueprint(studerConfig.slaveAddress,
280                 ModbusReadFunctionCode.READ_INPUT_REGISTERS, registerNumber, 2, studerConfig.maxTries);
281         long refreshMillis = studerConfig.refresh * 1000;
282         PollTask pollTask = mycomms.registerRegularPoll(request, refreshMillis, 1000, result -> {
283             if (result.getRegisters().isPresent()) {
284                 ModbusRegisterArray reg = result.getRegisters().get();
285                 handlePolledData(registerNumber, reg);
286             } else {
287                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
288                 return;
289             }
290             if (getThing().getStatus() != ThingStatus.ONLINE) {
291                 updateStatus(ThingStatus.ONLINE);
292             }
293         }, this::handleError);
294         pollTasks.add(pollTask);
295     }
296
297     /**
298      * This method is called each time new data has been polled from the modbus slave
299      * The register array is first parsed, then each of the channels are updated
300      * to the new values
301      *
302      * @param n register readed
303      * @param registers byte array read from the modbus slave
304      */
305     protected void handlePolledData(int registerNumber, ModbusRegisterArray registers) {
306         String hexString = registers.toHexString().toString();
307         Float quantity = parser.hexToFloat(hexString);
308         if (quantity != null) {
309             if (type.equals(THING_TYPE_BSP)) {
310                 Unit<?> unit = UNIT_CHANNELS_BSP.get(registerNumber);
311                 if (unit != null) {
312                     internalUpdateState(CHANNELS_BSP.get(registerNumber), new QuantityType<>(quantity, unit));
313                 }
314             } else if (type.equals(THING_TYPE_XTENDER)) {
315                 handlePolledDataXtender(registerNumber, quantity);
316             } else if (type.equals(THING_TYPE_VARIOTRACK)) {
317                 handlePolledDataVarioTrack(registerNumber, quantity);
318             } else if (type.equals(THING_TYPE_VARIOSTRING)) {
319                 handlePolledDataVarioString(registerNumber, quantity);
320             }
321         }
322         resetCommunicationError();
323     }
324
325     /**
326      * This method is called each time new data has been polled from the VarioString slave
327      * The register array is first parsed, then each of the channels are updated
328      * to the new values
329      */
330     protected void handlePolledDataVarioString(int registerNumber, Float quantity) {
331         switch (CHANNELS_VARIOSTRING.get(registerNumber)) {
332             case CHANNEL_PV_OPERATING_MODE:
333             case CHANNEL_PV1_OPERATING_MODE:
334             case CHANNEL_PV2_OPERATING_MODE:
335                 VSMode vsmode = StuderParser.getVSModeByCode(quantity.intValue());
336                 if (vsmode == VSMode.UNKNOWN) {
337                     internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), UnDefType.UNDEF);
338                 } else {
339                     internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
340                 }
341                 break;
342             case CHANNEL_STATE_VARIOSTRING:
343                 OnOffType vsstate = StuderParser.getStateByCode(quantity.intValue());
344                 internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
345                 break;
346             default:
347                 Unit<?> unit = UNIT_CHANNELS_VARIOSTRING.get(registerNumber);
348                 if (unit != null) {
349                     internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new QuantityType<>(quantity, unit));
350                 }
351         }
352     }
353
354     /**
355      * This method is called each time new data has been polled from the VarioTrack slave
356      * The register array is first parsed, then each of the channels are updated
357      * to the new values
358      */
359     protected void handlePolledDataVarioTrack(int registerNumber, Float quantity) {
360         switch (CHANNELS_VARIOTRACK.get(registerNumber)) {
361             case CHANNEL_MODEL_VARIOTRACK:
362                 VTType type = StuderParser.getVTTypeByCode(quantity.intValue());
363                 if (type == VTType.UNKNOWN) {
364                     internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
365                 } else {
366                     internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
367                 }
368                 break;
369
370             case CHANNEL_OPERATING_MODE:
371                 VTMode vtmode = StuderParser.getVTModeByCode(quantity.intValue());
372                 if (vtmode == VTMode.UNKNOWN) {
373                     internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), UnDefType.UNDEF);
374                 } else {
375                     internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
376                 }
377                 break;
378
379             case CHANNEL_STATE_VARIOTRACK:
380                 OnOffType vtstate = StuderParser.getStateByCode(quantity.intValue());
381                 internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
382                 break;
383             default:
384                 Unit<?> unit = UNIT_CHANNELS_VARIOTRACK.get(registerNumber);
385                 if (unit != null) {
386                     internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new QuantityType<>(quantity, unit));
387                 }
388         }
389     }
390
391     /**
392      * This method is called each time new data has been polled from the Xtender slave
393      * The register array is first parsed, then each of the channels are updated
394      * to the new values
395      */
396     protected void handlePolledDataXtender(int registerNumber, Float quantity) {
397         switch (CHANNELS_XTENDER.get(registerNumber)) {
398             case CHANNEL_OPERATING_STATE:
399                 ModeXtender mode = StuderParser.getModeXtenderByCode(quantity.intValue());
400                 if (mode == ModeXtender.UNKNOWN) {
401                     internalUpdateState(CHANNELS_XTENDER.get(registerNumber), UnDefType.UNDEF);
402                 } else {
403                     internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
404                 }
405                 break;
406             case CHANNEL_STATE_INVERTER:
407                 OnOffType xtstate = StuderParser.getStateByCode(quantity.intValue());
408                 internalUpdateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
409                 break;
410             default:
411                 Unit<?> unit = UNIT_CHANNELS_XTENDER.get(registerNumber);
412                 if (unit != null) {
413                     internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new QuantityType<>(quantity, unit));
414                 }
415         }
416     }
417
418     /**
419      * Handle errors received during communication
420      */
421     protected void handleError(AsyncModbusFailure<ModbusReadRequestBlueprint> failure) {
422         // Ignore all incoming data and errors if configuration is not correct
423         if (hasConfigurationError() || getThing().getStatus() == ThingStatus.OFFLINE) {
424             return;
425         }
426         String msg = failure.getCause().getMessage();
427         String cls = failure.getCause().getClass().getName();
428         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
429                 String.format("Error with read: %s: %s", cls, msg));
430     }
431
432     /**
433      * Returns true, if we're in a CONFIGURATION_ERROR state
434      *
435      * @return
436      */
437     protected boolean hasConfigurationError() {
438         ThingStatusInfo statusInfo = getThing().getStatusInfo();
439         return statusInfo.getStatus() == ThingStatus.OFFLINE
440                 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
441     }
442
443     /**
444      * Reset communication status to ONLINE if we're in an OFFLINE state
445      */
446     protected void resetCommunicationError() {
447         ThingStatusInfo statusInfo = thing.getStatusInfo();
448         if (ThingStatus.OFFLINE.equals(statusInfo.getStatus())
449                 && ThingStatusDetail.COMMUNICATION_ERROR.equals(statusInfo.getStatusDetail())) {
450             updateStatus(ThingStatus.ONLINE);
451         }
452     }
453
454     protected void internalUpdateState(@Nullable String channelUID, @Nullable State state) {
455         if (channelUID != null && state != null) {
456             super.updateState(channelUID, state);
457         }
458     }
459 }