2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.modbus.studer.internal;
15 import static org.openhab.binding.modbus.studer.internal.StuderBindingConstants.*;
17 import java.util.ArrayList;
18 import java.util.Optional;
21 import javax.measure.Unit;
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;
55 * The {@link StuderHandler} is responsible for handling commands, which are
56 * sent to one of the channels.
58 * @author Giovanni Mirulla - Initial contribution
61 public class StuderHandler extends BaseThingHandler {
63 private final Logger logger = LoggerFactory.getLogger(StuderHandler.class);
65 private @Nullable StuderConfiguration config;
68 * Array of tasks used to poll the device
70 private ArrayList<PollTask> pollTasks = new ArrayList<PollTask>();
73 * Communication interface to the slave endpoint we're connecting to
75 protected volatile @Nullable ModbusCommunicationInterface comms = null;
78 * Importing parser methods and enums
80 final StuderParser parser = new StuderParser();
82 * Support variable for type of thing
84 protected ThingTypeUID type;
87 * Array of registers of Studer slave to read, we store this once initialization is complete
89 private Integer[] registers = new Integer[0];
92 * Instances of this handler
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
99 public StuderHandler(Thing thing) {
101 this.type = thing.getThingTypeUID();
105 public void handleCommand(ChannelUID channelUID, Command command) {
107 // Currently we do not support any commands
112 * Load the config object
113 * Connect to the slave bridge
114 * Get registers to poll
115 * Start the periodic polling
118 public void initialize() {
119 config = getConfigAs(StuderConfiguration.class);
120 logger.debug("Initializing thing with configuration: {}", thing.getConfiguration());
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
131 private void startUp() {
135 if (comms == null || config == null) {
136 logger.debug("Invalid endpoint/config/manager ref for studer handler");
140 if (!pollTasks.isEmpty()) {
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()]);
158 for (int r : registers) {
165 * Dispose the binding correctly
168 public void dispose() {
173 * Unregister the poll tasks and release the endpoint reference
175 private void tearDown() {
176 unregisterPollTasks();
177 unregisterEndpoint();
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
184 * @return the endpoint handler or null if the bridge does not exist
186 private @Nullable ModbusEndpointThingHandler getEndpointThingHandler() {
187 Bridge bridge = getBridge();
188 if (bridge == null) {
189 logger.debug("Bridge is null");
192 if (bridge.getStatus() != ThingStatus.ONLINE) {
193 logger.debug("Bridge is not online");
197 ThingHandler handler = bridge.getHandler();
198 if (handler == null) {
199 logger.debug("Bridge handler is null");
203 if (handler instanceof ModbusEndpointThingHandler) {
204 ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
205 return slaveEndpoint;
207 logger.debug("Unexpected bridge handler: {}", handler);
213 * Get a reference to the modbus endpoint
215 private void connectEndpoint() {
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);
229 comms = slaveEndpointThingHandler.getCommunicationInterface();
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);
241 * Remove the endpoint if exists
243 private void unregisterEndpoint() {
244 // Comms will be close()'d by endpoint thing handler
248 private synchronized void unregisterPollTasks() {
249 if (pollTasks.isEmpty()) {
252 logger.debug("Unregistering polling from ModbusManager");
253 ModbusCommunicationInterface mycomms = comms;
254 if (mycomms != null) {
255 for (PollTask t : pollTasks) {
256 mycomms.unregisterRegularPoll(t);
264 * This is where we set up our regular poller
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");
271 ModbusCommunicationInterface mycomms = comms;
272 StuderConfiguration studerConfig = config;
273 if (studerConfig == null || mycomms == null) {
274 throw new IllegalStateException("registerPollTask called without proper configuration");
277 logger.debug("Setting up regular polling");
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);
287 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
290 if (getThing().getStatus() != ThingStatus.ONLINE) {
291 updateStatus(ThingStatus.ONLINE);
293 }, this::handleError);
294 pollTasks.add(pollTask);
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
302 * @param n register readed
303 * @param registers byte array read from the modbus slave
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);
312 internalUpdateState(CHANNELS_BSP.get(registerNumber), new QuantityType<>(quantity, unit));
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);
322 resetCommunicationError();
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
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);
339 internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new StringType(vsmode.name()));
342 case CHANNEL_STATE_VARIOSTRING:
343 OnOffType vsstate = StuderParser.getStateByCode(quantity.intValue());
344 internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), vsstate);
347 Unit<?> unit = UNIT_CHANNELS_VARIOSTRING.get(registerNumber);
349 internalUpdateState(CHANNELS_VARIOSTRING.get(registerNumber), new QuantityType<>(quantity, unit));
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
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);
366 internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(type.name()));
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);
375 internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new StringType(vtmode.name()));
379 case CHANNEL_STATE_VARIOTRACK:
380 OnOffType vtstate = StuderParser.getStateByCode(quantity.intValue());
381 internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), vtstate);
384 Unit<?> unit = UNIT_CHANNELS_VARIOTRACK.get(registerNumber);
386 internalUpdateState(CHANNELS_VARIOTRACK.get(registerNumber), new QuantityType<>(quantity, unit));
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
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);
403 internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new StringType(mode.name()));
406 case CHANNEL_STATE_INVERTER:
407 OnOffType xtstate = StuderParser.getStateByCode(quantity.intValue());
408 internalUpdateState(CHANNELS_XTENDER.get(registerNumber), xtstate);
411 Unit<?> unit = UNIT_CHANNELS_XTENDER.get(registerNumber);
413 internalUpdateState(CHANNELS_XTENDER.get(registerNumber), new QuantityType<>(quantity, unit));
419 * Handle errors received during communication
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) {
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));
433 * Returns true, if we're in a CONFIGURATION_ERROR state
437 protected boolean hasConfigurationError() {
438 ThingStatusInfo statusInfo = getThing().getStatusInfo();
439 return statusInfo.getStatus() == ThingStatus.OFFLINE
440 && statusInfo.getStatusDetail() == ThingStatusDetail.CONFIGURATION_ERROR;
444 * Reset communication status to ONLINE if we're in an OFFLINE state
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);
454 protected void internalUpdateState(@Nullable String channelUID, @Nullable State state) {
455 if (channelUID != null && state != null) {
456 super.updateState(channelUID, state);