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