]> git.basschouten.com Git - openhab-addons.git/blob
d5f20a3a8a423819d316e67330c43b887070305d
[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.homematic.internal.communicator.parser;
14
15 import java.io.IOException;
16 import java.util.Objects;
17
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.openhab.binding.homematic.internal.misc.HomematicConstants;
20 import org.openhab.binding.homematic.internal.misc.MiscUtils;
21 import org.openhab.binding.homematic.internal.model.HmDatapoint;
22 import org.openhab.binding.homematic.internal.model.HmParamsetType;
23 import org.openhab.binding.homematic.internal.model.HmValueType;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Abstract base class for all parsers with common methods.
29  *
30  * @author Gerhard Riegler - Initial contribution
31  */
32 public abstract class CommonRpcParser<M, R> implements RpcParser<M, R> {
33
34     private final Logger logger = LoggerFactory.getLogger(CommonRpcParser.class);
35
36     /**
37      * Converts the object to a string.
38      */
39     protected String toString(Object object) {
40         String value = Objects.toString(object, "").trim();
41         return value.isEmpty() ? null : value;
42     }
43
44     /**
45      * Converts the object to an integer.
46      */
47     protected Integer toInteger(Object object) {
48         if (object == null || object instanceof Integer) {
49             return (Integer) object;
50         }
51         try {
52             return Double.valueOf(object.toString()).intValue();
53         } catch (NumberFormatException ex) {
54             logger.debug("Failed converting {} to a Double", object, ex);
55             return null;
56         }
57     }
58
59     /**
60      * Converts the object to a double.
61      */
62     protected Double toDouble(Object object) {
63         if (object == null || object instanceof Double) {
64             return (Double) object;
65         }
66         try {
67             return Double.valueOf(object.toString());
68         } catch (NumberFormatException ex) {
69             logger.debug("Failed converting {} to a Double", object, ex);
70             return null;
71         }
72     }
73
74     /**
75      * Converts the object to a number.
76      */
77     protected Number toNumber(Object object) {
78         if (object == null || object instanceof Number) {
79             return (Number) object;
80         }
81         try {
82             String value = object.toString();
83             if (value.contains(".")) {
84                 return Float.parseFloat(value);
85             } else {
86                 return Integer.parseInt(value);
87             }
88         } catch (NumberFormatException ex) {
89             logger.debug("Failed converting {} to a Number", object, ex);
90             return null;
91         }
92     }
93
94     /**
95      * Converts the object to a boolean.
96      */
97     protected Boolean toBoolean(Object object) {
98         if (object == null || object instanceof Boolean) {
99             return (Boolean) object;
100         }
101         return "true".equals(object.toString().toLowerCase());
102     }
103
104     /**
105      * Converts the object to a string array.
106      */
107     protected String[] toOptionList(Object optionList) {
108         if (optionList != null && optionList instanceof Object[] vl) {
109             String[] stringArray = new String[vl.length];
110             for (int i = 0; i < vl.length; i++) {
111                 stringArray[i] = vl[i].toString();
112             }
113             return stringArray;
114         }
115         return null;
116     }
117
118     /**
119      * Returns the address of a device, replacing group address identifier and illegal characters.
120      */
121     @NonNull
122     protected String getSanitizedAddress(Object object) {
123         String address = Objects.toString(object, "").trim().replaceFirst("\\*", "T-");
124         return MiscUtils.validateCharacters(address.isEmpty() ? null : address, "Address", "_");
125     }
126
127     /**
128      * Adjust uninitialized rssi values to zero.
129      */
130     protected void adjustRssiValue(HmDatapoint dp) {
131         if (dp.getValue() != null && dp.getName().startsWith("RSSI_") && dp.isIntegerType()) {
132             int rssiValue = ((Number) dp.getValue()).intValue();
133             dp.setValue(getAdjustedRssiValue(rssiValue));
134         }
135     }
136
137     /**
138      * Adjust a rssi value if it is out of range.
139      */
140     protected Integer getAdjustedRssiValue(Integer rssiValue) {
141         if (rssiValue == null || rssiValue >= 255 || rssiValue <= -255) {
142             return 0;
143         }
144         return rssiValue;
145     }
146
147     /**
148      * Converts the value to the correct type if necessary.
149      */
150     protected Object convertToType(HmDatapoint dp, Object value) {
151         if (value == null) {
152             return null;
153         } else if (dp.isBooleanType()) {
154             return toBoolean(value);
155         } else if (dp.isIntegerType()) {
156             return toInteger(value);
157         } else if (dp.isFloatType()) {
158             return toNumber(value);
159         } else if (dp.isStringType()) {
160             return toString(value);
161         } else {
162             return value;
163         }
164     }
165
166     /**
167      * Assembles a datapoint with the given parameters.
168      */
169     protected HmDatapoint assembleDatapoint(String name, String unit, String type, String[] options, Object min,
170             Object max, Integer operations, Object defaultValue, HmParamsetType paramsetType, boolean isHmIpDevice)
171             throws IOException {
172         HmDatapoint dp = new HmDatapoint();
173         dp.setName(name);
174         dp.setDescription(name);
175         if (unit != null) {
176             unit = unit.trim().replace("\ufffd", "°");
177         }
178         dp.setUnit(unit == null || unit.isEmpty() ? null : unit);
179
180         // Bypass: For several devices the CCU does not send a unit together with the value in the data point definition
181         if (dp.getUnit() == null && dp.getName() != null) {
182             if (dp.getName().startsWith("RSSI_")) {
183                 dp.setUnit("dBm");
184             } else if (dp.getName().startsWith(HomematicConstants.DATAPOINT_NAME_OPERATING_VOLTAGE)) {
185                 dp.setUnit("V");
186             } else if (HomematicConstants.DATAPOINT_NAME_HUMIDITY.equals(dp.getName())) {
187                 dp.setUnit("%");
188             } else if (HomematicConstants.DATAPOINT_NAME_LEVEL.equals(dp.getName())) {
189                 dp.setUnit("100%");
190             }
191         }
192
193         HmValueType valueType = HmValueType.parse(type);
194         if (valueType == null || valueType == HmValueType.UNKNOWN) {
195             throw new IOException("Unknown datapoint type: " + type);
196         } else if (valueType == HmValueType.FLOAT && dp.getUnit() == null
197                 && dp.getName().matches("\\w*_TEMPERATURE(_\\w.*|$)")) {
198             logger.debug("No unit information found for temperature datapoint {}, assuming Number:Temperature",
199                     dp.getName());
200             dp.setUnit("°C"); // Bypass for a problem with HMIP devices where unit of temperature channels is sometimes
201                               // empty
202         }
203         dp.setType(valueType);
204
205         dp.setOptions(options);
206         if (dp.isNumberType() || dp.isEnumType()) {
207             if (isHmIpDevice && dp.isEnumType()) {
208                 dp.setMinValue(dp.getOptionIndex(toString(min)));
209                 dp.setMaxValue(dp.getOptionIndex(toString(max)));
210             } else {
211                 dp.setMinValue(toNumber(min));
212                 dp.setMaxValue(toNumber(max));
213             }
214         }
215         dp.setReadOnly((operations & 2) != 2);
216         dp.setReadable((operations & 1) == 1);
217         dp.setParamsetType(paramsetType);
218         if (isHmIpDevice && dp.isEnumType()) {
219             dp.setDefaultValue(dp.getOptionIndex(toString(defaultValue)));
220         } else {
221             dp.setDefaultValue(convertToType(dp, defaultValue));
222         }
223         dp.setValue(dp.getDefaultValue());
224         return dp;
225     }
226
227     /**
228      * Converts a string value to the type.
229      */
230     protected Object convertToType(String value) {
231         if (value == null || value.isBlank()) {
232             return null;
233         }
234         if ("true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) {
235             return (Boolean.TRUE);
236         } else if ("false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) {
237             return (Boolean.FALSE);
238         } else if (value.matches("(-|\\+)?[0-9]+")) {
239             return (Integer.valueOf(value));
240         } else if (value.matches("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")) {
241             return (Double.valueOf(value));
242         } else {
243             return value;
244         }
245     }
246 }