2 * Copyright (c) 2010-2023 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.helioseasycontrols.internal;
15 import java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.lang.reflect.Type;
19 import java.nio.charset.StandardCharsets;
20 import java.time.ZoneId;
21 import java.time.ZonedDateTime;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
26 import java.util.Optional;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.Semaphore;
31 import java.util.concurrent.TimeUnit;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
36 import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
37 import org.openhab.core.io.transport.modbus.ModbusCommunicationInterface;
38 import org.openhab.core.io.transport.modbus.ModbusReadFunctionCode;
39 import org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint;
40 import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
41 import org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
42 import org.openhab.core.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
43 import org.openhab.core.library.types.DateTimeType;
44 import org.openhab.core.library.types.DecimalType;
45 import org.openhab.core.library.types.OnOffType;
46 import org.openhab.core.library.types.QuantityType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.library.unit.SIUnits;
49 import org.openhab.core.library.unit.Units;
50 import org.openhab.core.thing.Bridge;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.binding.BaseThingHandler;
57 import org.openhab.core.thing.binding.ThingHandler;
58 import org.openhab.core.thing.binding.ThingHandlerService;
59 import org.openhab.core.types.Command;
60 import org.openhab.core.types.RefreshType;
61 import org.openhab.core.types.State;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 import com.google.gson.Gson;
66 import com.google.gson.reflect.TypeToken;
69 * The {@link HeliosEasyControlsHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Bernhard Bauer - Initial contribution
75 public class HeliosEasyControlsHandler extends BaseThingHandler {
77 private final Logger logger = LoggerFactory.getLogger(HeliosEasyControlsHandler.class);
79 private final HeliosEasyControlsTranslationProvider translationProvider;
81 private @Nullable HeliosEasyControlsConfiguration config;
83 private @Nullable ScheduledFuture<?> pollingJob;
85 private @Nullable Map<String, HeliosVariable> variableMap;
88 * This flag is used to ensure read requests (consisting of a write and subsequent read) are not influenced by
91 private final Map<ModbusSlaveEndpoint, Semaphore> transactionLocks = new ConcurrentHashMap<>();
93 private final Gson gson = new Gson();
95 private @Nullable ModbusCommunicationInterface comms;
97 private int dateFormat = -1;
98 private ZonedDateTime sysDate = ZonedDateTime.now(); // initialize with local system time as a best guess
99 // before reading from device
100 private long errors = 0;
101 private int warnings = 0;
102 private int infos = 0;
103 private String statusFlags = "";
105 private static class BypassDate {
106 private static final int[] MONTH_MAX_DAYS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
108 // initialization to avoid issues when updating before all variables were read
109 private int month = 1;
112 public BypassDate() {
115 public BypassDate(int day, int month) {
117 this.setMonth(month);
120 public void setMonth(int month) {
123 } else if (month > 12) {
130 public int getMonth() {
134 public void setDay(int day) {
138 this.day = Math.min(day, MONTH_MAX_DAYS[month - 1]);
142 public int getDay() {
146 public DateTimeType toDateTimeType() {
147 return new DateTimeType(ZonedDateTime.of(1900, this.month, this.day, 0, 0, 0, 0, ZoneId.of("UTC+00:00")));
151 private @Nullable BypassDate bypassFrom, bypassTo;
153 public HeliosEasyControlsHandler(Thing thing, HeliosEasyControlsTranslationProvider translationProvider) {
155 this.translationProvider = translationProvider;
159 * Reads variable definitions from JSON file and store them in variableMap
161 private void readVariableDefinition() {
162 Type vMapType = new TypeToken<Map<String, HeliosVariable>>() {
164 try (InputStreamReader jsonFile = new InputStreamReader(
165 getClass().getResourceAsStream(HeliosEasyControlsBindingConstants.VARIABLES_DEFINITION_FILE));
166 BufferedReader reader = new BufferedReader(jsonFile)) {
167 this.variableMap = gson.fromJson(reader, vMapType);
168 } catch (IOException e) {
169 this.handleError("Error reading variable definition file", ThingStatusDetail.CONFIGURATION_ERROR);
171 if (variableMap != null) {
172 // add the name to the variable itself
173 for (Map.Entry<String, HeliosVariable> entry : this.variableMap.entrySet()) {
174 entry.getValue().setName(entry.getKey()); // workaround to set the variable name inside the
175 // HeliosVariable object
176 if (!entry.getValue().isOk()) {
177 this.handleError("Variables definition file contains inconsistent data",
178 ThingStatusDetail.CONFIGURATION_ERROR);
182 this.handleError("Variables definition file not found or of illegal format",
183 ThingStatusDetail.CONFIGURATION_ERROR);
188 * Get the endpoint handler from the bridge this handler is connected to
189 * Checks that we're connected to the right type of bridge
191 * @return the endpoint handler or null if the bridge does not exist
193 private @Nullable ModbusEndpointThingHandler getEndpointThingHandler() {
194 Bridge bridge = getBridge();
195 if (bridge == null) {
196 logger.debug("Bridge is null");
199 if (bridge.getStatus() != ThingStatus.ONLINE) {
200 logger.debug("Bridge is not online");
204 ThingHandler handler = bridge.getHandler();
205 if (handler == null) {
206 logger.debug("Bridge handler is null");
210 if (handler instanceof ModbusEndpointThingHandler thingHandler) {
213 logger.debug("Unexpected bridge handler: {}", handler);
219 * Get a reference to the modbus endpoint
221 private void connectEndpoint() {
222 if (this.comms != null) {
226 ModbusEndpointThingHandler slaveEndpointThingHandler = getEndpointThingHandler();
227 if (slaveEndpointThingHandler == null) {
228 @SuppressWarnings("null")
229 String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
230 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
231 String.format("Bridge '%s' is offline", label));
232 logger.debug("No bridge handler available -- aborting init for {}", label);
236 comms = slaveEndpointThingHandler.getCommunicationInterface();
239 @SuppressWarnings("null")
240 String label = Optional.ofNullable(getBridge()).map(b -> b.getLabel()).orElse("<null>");
241 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
242 String.format("Bridge '%s' not completely initialized", label));
243 logger.debug("Bridge not initialized fully (no endpoint) -- aborting init for {}", this);
249 public void initialize() {
250 this.config = getConfigAs(HeliosEasyControlsConfiguration.class);
251 this.readVariableDefinition();
252 this.connectEndpoint();
253 if ((this.comms != null) && (this.variableMap != null) && (this.config != null)) {
254 this.transactionLocks.putIfAbsent(this.comms.getEndpoint(), new Semaphore(1, true));
255 updateStatus(ThingStatus.UNKNOWN);
257 // background initialization
258 scheduler.execute(() -> {
259 readValue(HeliosEasyControlsBindingConstants.DATE_FORMAT);
260 // status will be updated to ONLINE by the read callback function (via processResponse)
263 // poll for status updates regularly
264 HeliosEasyControlsConfiguration config = this.config;
265 if (config != null) {
266 this.pollingJob = scheduler.scheduleWithFixedDelay(() -> {
267 if (variableMap != null) {
268 for (Map.Entry<String, HeliosVariable> entry : variableMap.entrySet()) {
269 if (this.isProperty(entry.getKey()) || isLinked(entry.getValue().getGroupAndName())
270 || HeliosEasyControlsBindingConstants.ALWAYS_UPDATE_VARIABLES
271 .contains(entry.getKey())) {
272 readValue(entry.getKey());
276 handleError("Variable definition is null", ThingStatusDetail.CONFIGURATION_ERROR);
278 }, config.getRefreshInterval(), config.getRefreshInterval(), TimeUnit.MILLISECONDS);
280 } else { // at least one null assertion has failed, let's log the problem and update the thing status
281 if (this.comms == null) {
282 this.handleError("Modbus communication interface is unavailable",
283 ThingStatusDetail.COMMUNICATION_ERROR);
285 if (this.variableMap == null) {
286 this.handleError("Variable definition is unavailable", ThingStatusDetail.CONFIGURATION_ERROR);
288 if (this.config == null) {
289 this.handleError("Binding configuration is unavailable", ThingStatusDetail.CONFIGURATION_ERROR);
295 public void dispose() {
296 if (this.pollingJob != null) {
297 this.pollingJob.cancel(true);
303 public void handleCommand(ChannelUID channelUID, Command command) {
304 String channelId = channelUID.getIdWithoutGroup();
305 if (command instanceof RefreshType) {
306 if (channelId.equals(HeliosEasyControlsBindingConstants.SYS_DATE)) {
307 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.DATE));
308 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.TIME));
309 } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_FROM)) {
310 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.BYPASS_FROM_DAY));
311 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.BYPASS_FROM_MONTH));
312 } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_TO)) {
313 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.BYPASS_TO_DAY));
314 scheduler.submit(() -> readValue(HeliosEasyControlsBindingConstants.BYPASS_TO_MONTH));
316 scheduler.submit(() -> readValue(channelId));
318 } else { // write command
320 if (command instanceof OnOffType) {
321 value = command == OnOffType.ON ? "1" : "0";
322 } else if (command instanceof DateTimeType dateTimeCommand) {
324 ZonedDateTime d = dateTimeCommand.getZonedDateTime();
325 if (channelId.equals(HeliosEasyControlsBindingConstants.SYS_DATE)) {
327 } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_FROM)) {
328 this.setBypass(true, d.getDayOfMonth(), d.getMonthValue());
329 } else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_TO)) {
330 this.setBypass(false, d.getDayOfMonth(), d.getMonthValue());
332 value = formatDate(channelId, dateTimeCommand.getZonedDateTime());
334 } catch (InterruptedException e) {
336 "{} encountered Exception when trying to lock Semaphore for writing variable {} to the device: {}",
337 HeliosEasyControlsHandler.class.getSimpleName(), channelId, e.getMessage());
339 } else if ((command instanceof DecimalType) || (command instanceof StringType)) {
340 value = command.toString();
341 } else if (command instanceof QuantityType<?> val) {
342 // convert item's unit to the Helios device's unit
343 Map<String, HeliosVariable> variableMap = this.variableMap;
344 if (variableMap != null) {
345 HeliosVariable v = variableMap.get(channelId);
347 String unit = v.getUnit();
350 case HeliosVariable.UNIT_DAY:
351 val = val.toUnit(Units.DAY);
353 case HeliosVariable.UNIT_HOUR:
354 val = val.toUnit(Units.HOUR);
356 case HeliosVariable.UNIT_MIN:
357 val = val.toUnit(Units.MINUTE);
359 case HeliosVariable.UNIT_SEC:
360 val = val.toUnit(Units.SECOND);
362 case HeliosVariable.UNIT_VOLT:
363 val = val.toUnit(Units.VOLT);
365 case HeliosVariable.UNIT_PERCENT:
366 val = val.toUnit(Units.PERCENT);
368 case HeliosVariable.UNIT_PPM:
369 val = val.toUnit(Units.PARTS_PER_MILLION);
371 case HeliosVariable.UNIT_TEMP:
372 val = val.toUnit(SIUnits.CELSIUS);
375 value = val != null ? String.valueOf(val.doubleValue()) : null; // ignore the UoM
381 final String v = value;
382 scheduler.submit(() -> {
384 writeValue(channelId, v);
385 if (variableMap != null) {
386 HeliosVariable variable = variableMap.get(channelId);
387 if (variable != null) {
388 updateState(variable, v);
389 updateStatus(ThingStatus.ONLINE);
392 } catch (HeliosException e) {
393 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
394 "Writing value " + v + "to channel " + channelId + " failed: " + e.getMessage());
395 } catch (InterruptedException e) {
397 "{} encountered Exception when trying to lock Semaphore for writing variable {} to the device: {}",
398 HeliosEasyControlsHandler.class.getSimpleName(), channelId, e.getMessage());
407 public Collection<Class<? extends ThingHandlerService>> getServices() {
408 return Set.of(HeliosEasyControlsActions.class);
412 * Checks if the provided variable name is a property
414 * @param variableName The variable's name
415 * @return true if the variable is a property
417 private boolean isProperty(String variableName) {
418 return HeliosEasyControlsBindingConstants.PROPERTY_NAMES.contains(variableName);
422 * Writes a variable value to the Helios device
424 * @param variableName The variable name
425 * @param value The new value
426 * @throws HeliosException Thrown if the variable is read-only or the provided value is out of range
428 public void writeValue(String variableName, String value) throws HeliosException, InterruptedException {
429 if (this.variableMap == null) {
430 this.handleError("Variable definition is unavailable.", ThingStatusDetail.CONFIGURATION_ERROR);
433 Map<String, HeliosVariable> variableMap = this.variableMap;
434 if (variableMap != null) {
435 HeliosVariable v = variableMap.get(variableName);
438 if (!v.hasWriteAccess()) {
439 throw new HeliosException("Variable " + variableName + " is read-only");
440 } else if (!v.isInAllowedRange(value)) {
441 throw new HeliosException(
442 "Value " + value + " is outside of allowed range of variable " + variableName);
443 } else if (this.comms != null) {
445 String payload = v.getVariableString() + "=" + value;
446 ModbusCommunicationInterface comms = this.comms;
448 final Semaphore lock = transactionLocks.get(comms.getEndpoint());
451 comms.submitOneTimeWrite(new ModbusWriteRegisterRequestBlueprint(
452 HeliosEasyControlsBindingConstants.UNIT_ID,
453 HeliosEasyControlsBindingConstants.START_ADDRESS, preparePayload(payload), true,
454 HeliosEasyControlsBindingConstants.MAX_TRIES), result -> {
456 updateStatus(ThingStatus.ONLINE);
459 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
460 "Error writing to device: " + failureInfo.getCause().getMessage());
464 } else { // comms is null
465 this.handleError("Modbus communication interface is null",
466 ThingStatusDetail.COMMUNICATION_ERROR);
474 * Read a variable from the Helios device
476 * @param variableName The variable name
478 public void readValue(String variableName) {
479 Map<String, HeliosVariable> variableMap = this.variableMap;
480 ModbusCommunicationInterface comms = this.comms;
481 if ((comms != null) && (variableMap != null)) {
482 final Semaphore lock = transactionLocks.get(comms.getEndpoint());
483 HeliosVariable v = variableMap.get(variableName);
484 if ((v != null) && v.hasReadAccess() && (lock != null)) {
486 lock.acquire(); // will block until lock is available
487 } catch (InterruptedException e) {
488 logger.warn("{} encountered Exception when trying to read variable {} from the device: {}",
489 HeliosEasyControlsHandler.class.getSimpleName(), variableName, e.getMessage());
492 // write variable name to register
493 String payload = v.getVariableString();
494 comms.submitOneTimeWrite(new ModbusWriteRegisterRequestBlueprint(
495 HeliosEasyControlsBindingConstants.UNIT_ID, HeliosEasyControlsBindingConstants.START_ADDRESS,
496 preparePayload(payload), true, HeliosEasyControlsBindingConstants.MAX_TRIES), result -> {
497 comms.submitOneTimePoll(
498 new ModbusReadRequestBlueprint(HeliosEasyControlsBindingConstants.UNIT_ID,
499 ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS,
500 HeliosEasyControlsBindingConstants.START_ADDRESS, v.getCount(),
501 HeliosEasyControlsBindingConstants.MAX_TRIES),
504 Optional<ModbusRegisterArray> registers = pollResult.getRegisters();
505 if (registers.isPresent()) {
506 processResponse(v, registers.get());
510 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
511 "Error reading from device: " + failureInfo.getCause().getMessage());
515 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
516 "Error writing to device: " + failureInfo.getCause().getMessage());
522 if (this.comms == null) {
523 this.handleError("Modbus communication interface is unavailable",
524 ThingStatusDetail.COMMUNICATION_ERROR);
526 if (variableMap == null) {
527 this.handleError("Variable definition is unavailable", ThingStatusDetail.CONFIGURATION_ERROR);
532 private void updateSysDate(DateTimeType dateTime) {
533 this.updateSysDateTime(dateTime.getZonedDateTime(), true, sysDate.getOffset().getTotalSeconds() / 60 / 60);
536 private void updateSysTime(DateTimeType dateTime) {
537 this.updateSysDateTime(dateTime.getZonedDateTime(), false, sysDate.getOffset().getTotalSeconds() / 60 / 60);
540 private void updateUtcOffset(int utcOffset) {
541 this.updateSysDateTime(this.sysDate, true, sysDate.getOffset().getTotalSeconds() / 60 / 60);
544 private void updateSysDateTime(ZonedDateTime dateTime, boolean updateDate, int utcOffset) {
545 ZonedDateTime sysDate = this.sysDate;
546 sysDate = ZonedDateTime.of(updateDate ? dateTime.getYear() : sysDate.getYear(),
547 updateDate ? dateTime.getMonthValue() : sysDate.getMonthValue(),
548 updateDate ? dateTime.getDayOfMonth() : sysDate.getDayOfMonth(),
549 updateDate ? sysDate.getHour() : dateTime.getHour(),
550 updateDate ? sysDate.getMinute() : dateTime.getMinute(),
551 updateDate ? sysDate.getSecond() : dateTime.getSecond(), 0,
552 ZoneId.of("UTC" + (utcOffset >= 0 ? "+" : "") + String.format("%02d", utcOffset) + ":00"));
553 updateState("general#" + HeliosEasyControlsBindingConstants.SYS_DATE, new DateTimeType(sysDate));
554 this.sysDate = sysDate;
557 private void setSysDateTime(ZonedDateTime date) throws InterruptedException {
559 this.writeValue(HeliosEasyControlsBindingConstants.DATE,
560 this.formatDate(HeliosEasyControlsBindingConstants.DATE, date));
561 this.writeValue(HeliosEasyControlsBindingConstants.TIME,
562 date.getHour() + ":" + date.getMinute() + ":" + date.getSecond());
563 this.writeValue(HeliosEasyControlsBindingConstants.TIME_ZONE_DIFFERENCE_TO_GMT,
564 Integer.toString(date.getOffset().getTotalSeconds() / 60 / 60));
565 } catch (HeliosException e) {
566 logger.warn("{} encountered Exception when trying to set system date: {}",
567 HeliosEasyControlsHandler.class.getSimpleName(), e.getMessage());
571 protected void setSysDateTime() throws InterruptedException {
572 this.setSysDateTime(ZonedDateTime.now());
575 private void updateBypass(boolean from, boolean month, int val) {
576 BypassDate bypassDate = from ? this.bypassFrom : this.bypassTo;
577 if (bypassDate == null) {
578 bypassDate = new BypassDate();
581 bypassDate.setMonth(val);
584 bypassDate.setDay(val);
586 updateState("unitConfig#" + (from ? HeliosEasyControlsBindingConstants.BYPASS_FROM
587 : HeliosEasyControlsBindingConstants.BYPASS_TO), bypassDate.toDateTimeType());
589 this.bypassFrom = bypassDate;
592 this.bypassTo = bypassDate;
596 protected void setBypass(boolean from, int day, int month) throws InterruptedException {
597 BypassDate bypassDate = new BypassDate(day, month);
599 this.writeValue(from ? HeliosEasyControlsBindingConstants.BYPASS_FROM_DAY
600 : HeliosEasyControlsBindingConstants.BYPASS_TO_DAY, Integer.toString(bypassDate.getDay()));
602 from ? HeliosEasyControlsBindingConstants.BYPASS_FROM_MONTH
603 : HeliosEasyControlsBindingConstants.BYPASS_TO_MONTH,
604 Integer.toString(bypassDate.getMonth()));
605 } catch (HeliosException e) {
606 logger.warn("{} encountered Exception when trying to set bypass period: {}",
607 HeliosEasyControlsHandler.class.getSimpleName(), e.getMessage());
612 * Formats the provided date to a string in the device's configured date format
614 * @param variableName the variable name
615 * @param date the date to be formatted
616 * @return a string in the device's configured date format
618 public String formatDate(String variableName, ZonedDateTime date) {
619 String y = Integer.toString(date.getYear());
620 String m = Integer.toString(date.getMonthValue());
621 if (m.length() == 1) {
624 String d = Integer.toString(date.getDayOfMonth());
625 if (d.length() == 1) {
628 if (variableName.equals(HeliosEasyControlsBindingConstants.DATE)) { // fixed format for writing the system date
629 return d + "." + m + "." + y;
631 switch (this.dateFormat) {
632 case 0: // dd.mm.yyyy
633 return d + "." + m + "." + y;
634 case 1: // mm.dd.yyyy
635 return m + "." + d + "." + y;
636 case 2: // yyyy.mm.dd
637 return y + "." + m + "." + d;
639 return d + "." + m + "." + y;
644 private List<String> getMessages(long bitMask, int bits, String prefix) {
645 ArrayList<String> msg = new ArrayList<String>();
647 for (int i = 0; i < bits; i++) {
648 if ((bitMask & mask) != 0) {
649 msg.add(translationProvider.getText(prefix + i));
657 * Transforms the errors provided by the device into a human readable form (the basis for the
658 * corresponding action)
660 * @return an <code>List</code> of messages indicated by the error flags sent by the device
662 protected List<String> getErrorMessages() {
663 return this.getMessages(this.errors, HeliosEasyControlsBindingConstants.BITS_ERROR_MSG,
664 HeliosEasyControlsBindingConstants.PREFIX_ERROR_MSG);
668 * Transforms the warnings provided by the device into a human readable form (the basis for the
669 * corresponding action)
671 * @return an <code>List</code> of messages indicated by the warning flags sent by the device
673 protected List<String> getWarningMessages() {
674 return this.getMessages(this.warnings, HeliosEasyControlsBindingConstants.BITS_WARNING_MSG,
675 HeliosEasyControlsBindingConstants.PREFIX_WARNING_MSG);
679 * Transforms the infos provided by the device into a human readable form (the basis for the
680 * corresponding action)
682 * @return an <code>List</code> of messages indicated by the info flags sent by the device
684 protected List<String> getInfoMessages() {
685 return this.getMessages(this.infos, HeliosEasyControlsBindingConstants.BITS_INFO_MSG,
686 HeliosEasyControlsBindingConstants.PREFIX_INFO_MSG);
690 * Transforms the status flags provided by the device into a human readable form (the basis for the
691 * corresponding action)
693 * @return an <code>List</code> of messages indicated by the status flags sent by the device
695 protected List<String> getStatusMessages() {
696 ArrayList<String> msg = new ArrayList<String>();
697 if (this.statusFlags.length() == HeliosEasyControlsBindingConstants.BITS_STATUS_MSG) {
698 for (int i = 0; i < HeliosEasyControlsBindingConstants.BITS_STATUS_MSG; i++) {
699 String key = HeliosEasyControlsBindingConstants.PREFIX_STATUS_MSG + i + "."
700 + (this.statusFlags.substring(HeliosEasyControlsBindingConstants.BITS_STATUS_MSG - i - 1,
701 HeliosEasyControlsBindingConstants.BITS_STATUS_MSG - i));
702 String text = translationProvider.getText(key);
703 if (!text.equals(key)) { // there is a text in the properties file (no text => flag is irrelevant)
708 msg.add("Status messages have not yet been read from the device");
714 * Returns a DateTimeType object based on the provided String and the device's configured date format
716 * @param date The date string read from the device
717 * @return A DateTimeType object representing the date or time specified
719 private DateTimeType toDateTime(String date) {
720 String[] dateTimeParts = null;
721 String dateTime = date;
722 dateTimeParts = date.split("\\."); // try to split date components
723 if (dateTimeParts.length == 1) { // time
724 return DateTimeType.valueOf(date);
725 } else if (dateTimeParts.length == 3) { // date - we'll try the device's date format
726 switch (this.dateFormat) {
727 case 0: // dd.mm.yyyy
728 dateTime = dateTimeParts[2] + "-" + dateTimeParts[1] + "-" + dateTimeParts[0];
730 case 1: // mm.dd.yyyy
731 dateTime = dateTimeParts[2] + "-" + dateTimeParts[0] + "-" + dateTimeParts[1];
733 case 2: // yyyy.mm.dd
734 dateTime = dateTimeParts[0] + "-" + dateTimeParts[1] + "-" + dateTimeParts[2];
737 dateTime = dateTimeParts[2] + "-" + dateTimeParts[1] + "-" + dateTimeParts[0];
740 return DateTimeType.valueOf(dateTime);
742 // falling back to default date format (apparently using the configured format has failed)
743 dateTime = dateTimeParts[2] + "-" + dateTimeParts[1] + "-" + dateTimeParts[0];
744 return DateTimeType.valueOf(dateTime);
747 private @Nullable QuantityType<?> toQuantityType(String value, @Nullable String unit) {
750 } else if (unit.equals(HeliosVariable.UNIT_DAY)) {
751 return new QuantityType<>(Integer.parseInt(value), Units.DAY);
752 } else if (unit.equals(HeliosVariable.UNIT_HOUR)) {
753 return new QuantityType<>(Integer.parseInt(value), Units.HOUR);
754 } else if (unit.equals(HeliosVariable.UNIT_MIN)) {
755 return new QuantityType<>(Integer.parseInt(value), Units.MINUTE);
756 } else if (unit.equals(HeliosVariable.UNIT_SEC)) {
757 return new QuantityType<>(Integer.parseInt(value), Units.SECOND);
758 } else if (unit.equals(HeliosVariable.UNIT_VOLT)) {
759 return new QuantityType<>(Float.parseFloat(value), Units.VOLT);
760 } else if (unit.equals(HeliosVariable.UNIT_PERCENT)) {
761 return new QuantityType<>(Float.parseFloat(value), Units.PERCENT);
762 } else if (unit.equals(HeliosVariable.UNIT_PPM)) {
763 return new QuantityType<>(Float.parseFloat(value), Units.PARTS_PER_MILLION);
764 } else if (unit.equals(HeliosVariable.UNIT_TEMP)) {
765 return new QuantityType<>(Float.parseFloat(value), SIUnits.CELSIUS);
772 * Prepares the payload for the request
774 * @param payload The String representation of the payload
775 * @return The Register representation of the payload
777 private static ModbusRegisterArray preparePayload(String payload) {
778 // determine number of registers
779 byte[] asciiBytes = payload.getBytes(StandardCharsets.US_ASCII);
780 int bufferLength = asciiBytes.length // ascii characters
782 + ((asciiBytes.length % 2 == 0) ? 1 : 0); // to have even number of bytes
783 assert bufferLength % 2 == 0; // Invariant, ensured above
785 byte[] buffer = new byte[bufferLength];
786 System.arraycopy(asciiBytes, 0, buffer, 0, asciiBytes.length);
787 // Fill in rest of bytes with NUL bytes
788 for (int i = asciiBytes.length; i < buffer.length; i++) {
791 return new ModbusRegisterArray(buffer);
795 * Decodes the Helios device' response and updates the channel with the actual value of the variable
797 * @param response The registers received from the Helios device
798 * @return The value or <tt>null</tt> if an error occurred
800 private void processResponse(HeliosVariable v, ModbusRegisterArray registers) {
801 String r = ModbusBitUtilities.extractStringFromRegisters(registers, 0, registers.size() * 2,
802 StandardCharsets.US_ASCII);
803 String[] parts = r.split("=", 2); // remove the part "vXXXX=" from the string
804 // making sure we have a proper response and the response matches the requested variable
805 if ((parts.length == 2) && (v.getVariableString().equals(parts[0]))) {
806 if (this.isProperty(v.getName())) {
810 .getText(HeliosEasyControlsBindingConstants.PROPERTIES_PREFIX + v.getName()),
811 v.formatPropertyValue(parts[1], translationProvider));
812 } catch (HeliosException e) {
813 logger.warn("{} encountered Exception when trying to update property: {}",
814 HeliosEasyControlsHandler.class.getSimpleName(), e.getMessage());
817 this.updateState(v, parts[1]);
819 } else { // another variable was read
820 logger.warn("{} tried to read value from variable {} and the result provided by the device was {}",
821 HeliosEasyControlsHandler.class.getSimpleName(), v.getName(), r);
825 private void updateState(HeliosVariable v, String value) {
826 String variableType = v.getType();
827 // System date and time
828 if (v.getName().equals(HeliosEasyControlsBindingConstants.DATE)) {
829 this.updateSysDate(this.toDateTime(value));
830 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.TIME)) {
831 this.updateSysTime(this.toDateTime(value));
832 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.TIME_ZONE_DIFFERENCE_TO_GMT)) {
833 this.updateUtcOffset(Integer.parseInt(value));
835 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.BYPASS_FROM_DAY)) {
836 this.updateBypass(true, false, Integer.parseInt(value));
837 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.BYPASS_FROM_MONTH)) {
838 this.updateBypass(true, true, Integer.parseInt(value));
839 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.BYPASS_TO_DAY)) {
840 this.updateBypass(false, false, Integer.parseInt(value));
841 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.BYPASS_TO_MONTH)) {
842 this.updateBypass(false, true, Integer.parseInt(value));
844 Channel channel = getThing().getChannel(v.getGroupAndName());
846 if (channel != null) {
847 itemType = channel.getAcceptedItemType();
848 if (itemType != null) {
849 if (itemType.startsWith("Number:")) {
854 if (((HeliosVariable.TYPE_INTEGER.equals(variableType))
855 || (HeliosVariable.TYPE_FLOAT.equals(variableType))) && (!"-".equals(value))) {
857 if (v.getUnit() == null) {
858 state = DecimalType.valueOf(value);
859 } else { // QuantityType
860 state = this.toQuantityType(value, v.getUnit());
863 updateState(v.getGroupAndName(), state);
864 updateStatus(ThingStatus.ONLINE);
865 // update date format and messages upon read
866 if (v.getName().equals(HeliosEasyControlsBindingConstants.DATE_FORMAT)) {
867 this.dateFormat = Integer.parseInt(value);
868 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.ERRORS)) {
869 this.errors = Long.parseLong(value);
870 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.WARNINGS)) {
871 this.warnings = Integer.parseInt(value);
872 } else if (v.getName().equals(HeliosEasyControlsBindingConstants.INFOS)) {
873 this.infos = Integer.parseInt(value);
879 if (variableType.equals(HeliosVariable.TYPE_INTEGER)) {
880 updateState(v.getGroupAndName(), "1".equals(value) ? OnOffType.ON : OnOffType.OFF);
884 if (variableType.equals(HeliosVariable.TYPE_STRING)) {
885 updateState(v.getGroupAndName(), StringType.valueOf(value));
886 if (v.getName().equals(HeliosEasyControlsBindingConstants.STATUS_FLAGS)) {
887 this.statusFlags = value;
892 if (variableType.equals(HeliosVariable.TYPE_STRING)) {
893 updateState(v.getGroupAndName(), toDateTime(value));
897 } else { // itemType was null
898 logger.warn("{} couldn't determine item type of variable {}",
899 HeliosEasyControlsHandler.class.getSimpleName(), v.getName());
901 } else { // channel was null
902 logger.warn("{} couldn't find channel for variable {}", HeliosEasyControlsHandler.class.getSimpleName(),
909 * Logs an error (as a warning entry) and updates the thing status
911 * @param errorMsg The error message to be logged and provided with the Thing's status update
912 * @param status The Thing's new status
914 private void handleError(String errorMsg, ThingStatusDetail status) {
915 updateStatus(ThingStatus.OFFLINE, status, errorMsg);