]> git.basschouten.com Git - openhab-addons.git/blob
7aa716130c16d0b79db4f21a627af0c2353bf240
[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.knx.internal.dpt;
14
15 import static org.openhab.binding.knx.internal.KNXBindingConstants.disableUoM;
16
17 import java.math.BigDecimal;
18 import java.text.ParseException;
19 import java.text.SimpleDateFormat;
20 import java.util.Calendar;
21 import java.util.Date;
22 import java.util.Locale;
23 import java.util.Set;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.core.library.types.DateTimeType;
30 import org.openhab.core.library.types.DecimalType;
31 import org.openhab.core.library.types.HSBType;
32 import org.openhab.core.library.types.IncreaseDecreaseType;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.library.types.OpenClosedType;
35 import org.openhab.core.library.types.PercentType;
36 import org.openhab.core.library.types.QuantityType;
37 import org.openhab.core.library.types.StopMoveType;
38 import org.openhab.core.library.types.StringType;
39 import org.openhab.core.library.types.UpDownType;
40 import org.openhab.core.types.Type;
41 import org.openhab.core.types.UnDefType;
42 import org.openhab.core.util.ColorUtil;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import tuwien.auto.calimero.KNXException;
47 import tuwien.auto.calimero.KNXFormatException;
48 import tuwien.auto.calimero.KNXIllegalArgumentException;
49 import tuwien.auto.calimero.dptxlator.DPTXlator;
50 import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;
51 import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
52 import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;
53 import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;
54 import tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl;
55 import tuwien.auto.calimero.dptxlator.TranslatorTypes;
56
57 /**
58  * This class decodes raw data received from the KNX bus to an openHAB datatype
59  *
60  * Parts of this code are based on the openHAB KNXCoreTypeMapper by Kai Kreuzer et al.
61  *
62  * @author Jan N. Klug - Initial contribution
63  */
64 @NonNullByDefault
65 public class ValueDecoder {
66     private static final Logger LOGGER = LoggerFactory.getLogger(ValueDecoder.class);
67
68     private static final String TIME_DAY_FORMAT = "EEE, HH:mm:ss";
69     private static final String TIME_FORMAT = "HH:mm:ss";
70     private static final String DATE_FORMAT = "yyyy-MM-dd";
71     // RGB: "r:123 g:123 b:123" value-range: 0-255
72     private static final Pattern RGB_PATTERN = Pattern.compile("r:(?<r>\\d+) g:(?<g>\\d+) b:(?<b>\\d+)");
73     // RGBW: "100 27 25 12 %", value range: 0-100, invalid values: "-"
74     private static final Pattern RGBW_PATTERN = Pattern
75             .compile("(?:(?<r>[\\d,.]+)|-)\\s(?:(?<g>[\\d,.]+)|-)\\s(?:(?<b>[\\d,.]+)|-)\\s(?:(?<w>[\\d,.]+)|-)\\s%");
76     // xyY: "(0,123 0,123) 56 %", value range 0-1 for xy (comma as decimal point), 0-100 for Y, invalid values omitted
77     private static final Pattern XYY_PATTERN = Pattern
78             .compile("(?:\\((?<x>\\d+(?:,\\d+)?) (?<y>\\d+(?:,\\d+)?)\\))?\\s*(?:(?<Y>\\d+(?:,\\d+)?)\\s%)?");
79
80     /**
81      * convert the raw value received to the corresponding openHAB value
82      *
83      * @param dptId the DPT of the given data
84      * @param data a byte array containing the value
85      * @param preferredType the preferred datatype for this conversion
86      * @return the data converted to an openHAB Type (or null if conversion failed)
87      */
88     public static @Nullable Type decode(String dptId, byte[] data, Class<? extends Type> preferredType) {
89         try {
90             DPTXlator translator = TranslatorTypes.createTranslator(0,
91                     DPTUtil.NORMALIZED_DPT.getOrDefault(dptId, dptId));
92             translator.setData(data);
93             String value = translator.getValue();
94
95             String id = dptId; // prefer using the user-supplied DPT
96
97             Matcher m = DPTUtil.DPT_PATTERN.matcher(id);
98             if (!m.matches() || m.groupCount() != 2) {
99                 LOGGER.trace("User-Supplied DPT '{}' did not match for sub-type, using DPT returned from Translator",
100                         id);
101                 id = translator.getType().getID();
102                 m = DPTUtil.DPT_PATTERN.matcher(id);
103                 if (!m.matches() || m.groupCount() != 2) {
104                     LOGGER.warn("Couldn't identify main/sub number in dptID '{}'", id);
105                     return null;
106                 }
107             }
108             LOGGER.trace("Finally using datapoint DPT = {}", id);
109
110             String mainType = m.group("main");
111             String subType = m.group("sub");
112
113             switch (mainType) {
114                 case "1":
115                     return handleDpt1(subType, translator);
116                 case "2":
117                     DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
118                     int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
119                             + (translator1BitControlled.getValueBit() ? 1 : 0);
120                     return new DecimalType(decValue);
121                 case "3":
122                     return handleDpt3(subType, translator);
123                 case "10":
124                     return handleDpt10(value);
125                 case "11":
126                     return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN)
127                             .format(new SimpleDateFormat(DATE_FORMAT).parse(value)));
128                 case "18":
129                     DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
130                     int decimalValue = translatorSceneControl.getSceneNumber();
131                     if (value.startsWith("learn")) {
132                         decimalValue += 0x80;
133                     }
134                     return new DecimalType(decimalValue);
135                 case "19":
136                     return handleDpt19(translator);
137                 case "16":
138                 case "20":
139                 case "21":
140                 case "22":
141                 case "28":
142                     return StringType.valueOf(value);
143                 case "232":
144                     return handleDpt232(value, subType);
145                 case "242":
146                     return handleDpt242(value);
147                 case "251":
148                     return handleDpt251(value, preferredType);
149                 default:
150                     return handleNumericDpt(id, translator, preferredType);
151             }
152         } catch (NumberFormatException | KNXFormatException | KNXIllegalArgumentException | ParseException e) {
153             LOGGER.info("Translator couldn't parse data '{}' for datapoint type '{}' ({}).", data, dptId, e.getClass());
154         } catch (KNXException e) {
155             LOGGER.warn("Failed creating a translator for datapoint type '{}'.", dptId, e);
156         }
157
158         return null;
159     }
160
161     private static Type handleDpt1(String subType, DPTXlator translator) {
162         DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
163         switch (subType) {
164             case "008":
165                 return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
166             case "009":
167             case "019":
168                 // This is wrong for DPT 1.009. It should be true -> CLOSE, false -> OPEN, but unfortunately
169                 // can't be fixed without breaking a lot of working installations.
170                 // The documentation has been updated to reflect that. / @J-N-K
171                 return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
172             case "010":
173                 return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
174             case "022":
175                 return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
176             default:
177                 return OnOffType.from(translatorBoolean.getValueBoolean());
178         }
179     }
180
181     private static @Nullable Type handleDpt3(String subType, DPTXlator translator) {
182         DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
183         if (translator3BitControlled.getStepCode() == 0) {
184             LOGGER.debug("convertRawDataToType: KNX DPT_Control_Dimming: break received.");
185             return UnDefType.NULL;
186         }
187         switch (subType) {
188             case "007":
189                 return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
190                         : IncreaseDecreaseType.DECREASE;
191             case "008":
192                 return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
193             default:
194                 LOGGER.warn("DPT3, subtype '{}' is unknown.", subType);
195                 return null;
196         }
197     }
198
199     private static Type handleDpt10(String value) throws ParseException {
200         if (value.contains("no-day")) {
201             /*
202              * KNX "no-day" needs special treatment since openHAB's DateTimeType doesn't support "no-day".
203              * Workaround: remove the "no-day" String, parse the remaining time string, which will result in a
204              * date of "1970-01-01".
205              * Replace "no-day" with the current day name
206              */
207             StringBuilder stb = new StringBuilder(value);
208             int start = stb.indexOf("no-day");
209             int end = start + "no-day".length();
210             stb.replace(start, end, String.format(Locale.US, "%1$ta", Calendar.getInstance()));
211             value = stb.toString();
212         }
213         Date date = null;
214         try {
215             date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
216         } catch (ParseException pe) {
217             date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
218             throw pe;
219         }
220         return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
221     }
222
223     private static @Nullable Type handleDpt19(DPTXlator translator) throws KNXFormatException {
224         DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
225         if (translatorDateTime.isFaultyClock()) {
226             // Not supported: faulty clock
227             LOGGER.debug("KNX clock msg ignored: clock faulty bit set, which is not supported");
228             return null;
229         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
230                 && translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
231             // Not supported: "/1/1" (month and day without year)
232             LOGGER.debug("KNX clock msg ignored: no year, but day and month, which is not supported");
233             return null;
234         } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
235                 && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
236             // Not supported: "1900" (year without month and day)
237             LOGGER.debug("KNX clock msg ignored: no day and month, but year, which is not supported");
238             return null;
239         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
240                 && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)
241                 && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
242             // Not supported: No year, no date and no time
243             LOGGER.debug("KNX clock msg ignored: no day and month or year, which is not supported");
244             return null;
245         }
246
247         Calendar cal = Calendar.getInstance();
248         if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
249                 && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
250             // Pure date format, no time information
251             cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
252             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
253             return DateTimeType.valueOf(value);
254         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
255                 && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
256             // Pure time format, no date information
257             cal.clear();
258             cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
259             cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
260             cal.set(Calendar.SECOND, translatorDateTime.getSecond());
261             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
262             return DateTimeType.valueOf(value);
263         } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
264                 && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
265             // Date format and time information
266             cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
267             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
268             return DateTimeType.valueOf(value);
269         } else {
270             LOGGER.warn("Failed to convert '{}'", translator.getValue());
271             return null;
272         }
273     }
274
275     private static @Nullable Type handleDpt232(String value, String subType) {
276         Matcher rgb = RGB_PATTERN.matcher(value);
277         if (rgb.matches()) {
278             int r = Integer.parseInt(rgb.group("r"));
279             int g = Integer.parseInt(rgb.group("g"));
280             int b = Integer.parseInt(rgb.group("b"));
281
282             switch (subType) {
283                 case "600":
284                     return HSBType.fromRGB(r, g, b);
285                 case "60000":
286                     // MDT specific: mis-use 232.600 for hsv instead of rgb
287                     DecimalType hue = new DecimalType(coerceToRange(r * 360.0 / 255.0, 0.0, 359.9999));
288                     PercentType sat = new PercentType(BigDecimal.valueOf(coerceToRange(g / 2.55, 0.0, 100.0)));
289                     PercentType bright = new PercentType(BigDecimal.valueOf(coerceToRange(b / 2.55, 0.0, 100.0)));
290                     return new HSBType(hue, sat, bright);
291                 default:
292                     LOGGER.warn("Unknown subtype '232.{}', no conversion possible.", subType);
293                     return null;
294             }
295         }
296         LOGGER.warn("Failed to convert '{}' (DPT 232): Pattern does not match", value);
297         return null;
298     }
299
300     private static @Nullable Type handleDpt242(String value) {
301         Matcher xyY = XYY_PATTERN.matcher(value);
302         if (xyY.matches()) {
303             String stringx = xyY.group("x");
304             String stringy = xyY.group("y");
305             String stringY = xyY.group("Y");
306
307             if (stringx != null && stringy != null) {
308                 double x = Double.parseDouble(stringx.replace(",", "."));
309                 double y = Double.parseDouble(stringy.replace(",", "."));
310                 if (stringY == null) {
311                     return ColorUtil.xyToHsb(new double[] { x, y });
312                 } else {
313                     double Y = Double.parseDouble(stringY.replace(",", "."));
314                     return ColorUtil.xyToHsb(new double[] { x, y, Y });
315                 }
316             }
317         }
318         LOGGER.warn("Failed to convert '{}' (DPT 242): Pattern does not match", value);
319         return null;
320     }
321
322     private static @Nullable Type handleDpt251(String value, Class<? extends Type> preferredType) {
323         Matcher rgbw = RGBW_PATTERN.matcher(value);
324         if (rgbw.matches()) {
325             String rString = rgbw.group("r");
326             String gString = rgbw.group("g");
327             String bString = rgbw.group("b");
328             String wString = rgbw.group("w");
329
330             if (rString != null && gString != null && bString != null && HSBType.class.equals(preferredType)) {
331                 // does not support PercentType and r,g,b valid -> HSBType
332                 int r = coerceToRange((int) (Double.parseDouble(rString.replace(",", ".")) * 2.55), 0, 255);
333                 int g = coerceToRange((int) (Double.parseDouble(gString.replace(",", ".")) * 2.55), 0, 255);
334                 int b = coerceToRange((int) (Double.parseDouble(bString.replace(",", ".")) * 2.55), 0, 255);
335
336                 return HSBType.fromRGB(r, g, b);
337             } else if (wString != null && PercentType.class.equals(preferredType)) {
338                 // does support PercentType and w valid -> PercentType
339                 BigDecimal w = new BigDecimal(wString.replace(",", "."));
340
341                 return new PercentType(w);
342             }
343         }
344         LOGGER.warn("Failed to convert '{}' (DPT 251): Pattern does not match or invalid content", value);
345         return null;
346     }
347
348     private static @Nullable Type handleNumericDpt(String id, DPTXlator translator, Class<? extends Type> preferredType)
349             throws KNXFormatException {
350         Set<Class<? extends Type>> allowedTypes = DPTUtil.getAllowedTypes(id);
351
352         double value = translator.getNumericValue();
353         if (allowedTypes.contains(PercentType.class)
354                 && (HSBType.class.equals(preferredType) || PercentType.class.equals(preferredType))) {
355             return new PercentType(BigDecimal.valueOf(Math.round(value)));
356         }
357
358         if (allowedTypes.contains(QuantityType.class) && !disableUoM) {
359             String unit = DPTUnits.getUnitForDpt(id);
360             if (unit != null) {
361                 return new QuantityType<>(value + " " + unit);
362             } else {
363                 LOGGER.trace("Could not determine unit for DPT '{}', fallback to plain decimal", id);
364             }
365         }
366
367         if (allowedTypes.contains(DecimalType.class)) {
368             return new DecimalType(value);
369         }
370
371         LOGGER.warn("Failed to convert '{}' (DPT '{}'): no matching type found", value, id);
372         return null;
373     }
374
375     private static double coerceToRange(double value, double min, double max) {
376         return Math.min(Math.max(value, min), max);
377     }
378
379     private static int coerceToRange(int value, int min, int max) {
380         return Math.min(Math.max(value, min), max);
381     }
382 }