]> git.basschouten.com Git - openhab-addons.git/blob
8d6b33550cec47122fccfd25beb128d49ab80740
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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     private static boolean check235001(byte[] data) throws KNXException {
85         if (data.length != 6) {
86             throw new KNXFormatException("DPT235 broken frame");
87         }
88         if ((data[5] & 2) == 0) {
89             LOGGER.trace("DPT235.001 w/o ActiveEnergy ignored");
90             return false;
91         }
92         return true;
93     }
94
95     private static boolean check23561001(byte[] data) throws KNXException {
96         if (data.length != 6) {
97             throw new KNXFormatException("DPT235 broken frame");
98         }
99         if ((data[5] & 1) == 0) {
100             LOGGER.trace("DPT235.61001 w/o Tariff ignored");
101             return false;
102         }
103         return true;
104     }
105
106     /**
107      * convert the raw value received to the corresponding openHAB value
108      *
109      * @param dptId the DPT of the given data
110      * @param data a byte array containing the value
111      * @param preferredType the preferred datatype for this conversion
112      * @return the data converted to an openHAB Type (or null if conversion failed)
113      */
114     public static @Nullable Type decode(String dptId, byte[] data, Class<? extends Type> preferredType) {
115         try {
116             String value = "";
117             String translatorDptId = dptId;
118             DPTXlator translator;
119             try {
120                 translator = TranslatorTypes.createTranslator(0, DPTUtil.NORMALIZED_DPT.getOrDefault(dptId, dptId));
121                 translator.setData(data);
122                 value = translator.getValue();
123                 translatorDptId = translator.getType().getID();
124             } catch (KNXException e) {
125                 // special handling for decoding DPTs not yet supported by Calimero
126                 if ("235.001".equals(dptId)) {
127                     if (!check235001(data)) {
128                         return null;
129                     }
130                     translator = TranslatorTypes.createTranslator(0, "13.010");
131                     translator.setData(data);
132                     value = translator.getValue();
133                     dptId = "13.010";
134                     translatorDptId = dptId;
135                 } else if ("235.61001".equals(dptId)) {
136                     if (!check23561001(data)) {
137                         return null;
138                     }
139                     translator = TranslatorTypes.createTranslator(0, "5.006");
140                     translator.setData(new byte[] { data[4] });
141                     value = translator.getValue();
142                     dptId = "5.006";
143                     translatorDptId = dptId;
144                 } else {
145                     // no known special case, handle unknown translator outer try block
146                     throw e;
147                 }
148             }
149             String id = dptId; // prefer using the user-supplied DPT
150
151             Matcher m = DPTUtil.DPT_PATTERN.matcher(id);
152             if (!m.matches() || m.groupCount() != 2) {
153                 LOGGER.trace("User-Supplied DPT '{}' did not match for sub-type, using DPT returned from Translator",
154                         id);
155                 id = translatorDptId;
156                 m = DPTUtil.DPT_PATTERN.matcher(id);
157                 if (!m.matches() || m.groupCount() != 2) {
158                     LOGGER.warn("Couldn't identify main/sub number in dptID '{}'", id);
159                     return null;
160                 }
161             }
162             LOGGER.trace("Finally using datapoint DPT = {}", id);
163
164             String mainType = m.group("main");
165             String subType = m.group("sub");
166
167             switch (mainType) {
168                 case "1":
169                     return handleDpt1(subType, translator, preferredType);
170                 case "2":
171                     DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
172                     int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
173                             + (translator1BitControlled.getValueBit() ? 1 : 0);
174                     return new DecimalType(decValue);
175                 case "3":
176                     return handleDpt3(subType, translator);
177                 case "10":
178                     return handleDpt10(value);
179                 case "11":
180                     return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN)
181                             .format(new SimpleDateFormat(DATE_FORMAT).parse(value)));
182                 case "18":
183                     DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
184                     int decimalValue = translatorSceneControl.getSceneNumber();
185                     if (value.startsWith("learn")) {
186                         decimalValue += 0x80;
187                     }
188                     return new DecimalType(decimalValue);
189                 case "19":
190                     return handleDpt19(translator, data);
191                 case "20":
192                 case "21":
193                     return handleStringOrDecimal(data, value, preferredType, 8);
194                 case "22":
195                     return handleStringOrDecimal(data, value, preferredType, 16);
196                 case "16":
197                 case "28":
198                 case "250": // Map all combined color transitions to String,
199                 case "252": // as no native support is planned.
200                 case "253": // Currently only one subtype 2xx.600
201                 case "254": // is defined for those DPTs.
202                     return StringType.valueOf(value);
203                 case "243": // color translation, fix regional
204                 case "249": // settings
205                     return StringType.valueOf(value.replace(',', '.').replace(". ", ", "));
206                 case "232":
207                     return handleDpt232(value, subType);
208                 case "242":
209                     return handleDpt242(value);
210                 case "251":
211                     return handleDpt251(value, subType, preferredType);
212                 default:
213                     return handleNumericDpt(id, translator, preferredType);
214                 // TODO 6.001 is mapped to PercentType, which can only cover 0-100%, not -128..127%
215             }
216         } catch (NumberFormatException | KNXFormatException | KNXIllegalArgumentException | ParseException e) {
217             LOGGER.info("Translator couldn't parse data '{}' for datapoint type '{}' ({}).", data, dptId, e.getClass());
218         } catch (KNXException e) {
219             LOGGER.warn("Failed creating a translator for datapoint type '{}'.", dptId, e);
220         }
221
222         return null;
223     }
224
225     private static Type handleDpt1(String subType, DPTXlator translator, Class<? extends Type> preferredType) {
226         DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
227         switch (subType) {
228             case "008":
229                 return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
230             case "009":
231             case "019":
232                 // default is OpenClosedType (Contact), but it may be mapped to OnOffType as well
233                 if (OnOffType.class.equals(preferredType)) {
234                     return OnOffType.from(translatorBoolean.getValueBoolean());
235                 }
236
237                 // This is wrong for DPT 1.009. It should be true -> CLOSE, false -> OPEN, but unfortunately
238                 // can't be fixed without breaking a lot of working installations.
239                 // The documentation has been updated to reflect that. / @J-N-K
240                 return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
241             case "010":
242                 return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
243             case "022":
244                 return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
245             default:
246                 // default is OnOffType (Switch), but it may be mapped to OpenClosedType as well
247                 if (OpenClosedType.class.equals(preferredType)) {
248                     return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
249                 }
250
251                 return OnOffType.from(translatorBoolean.getValueBoolean());
252         }
253     }
254
255     private static @Nullable Type handleDpt3(String subType, DPTXlator translator) {
256         DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
257         if (translator3BitControlled.getStepCode() == 0) {
258             LOGGER.debug("convertRawDataToType: KNX DPT_Control_Dimming: break received.");
259             return UnDefType.NULL;
260         }
261         switch (subType) {
262             case "007":
263                 return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
264                         : IncreaseDecreaseType.DECREASE;
265             case "008":
266                 return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
267             default:
268                 LOGGER.warn("DPT3, subtype '{}' is unknown.", subType);
269                 return null;
270         }
271     }
272
273     private static Type handleDpt10(String value) throws ParseException {
274         // TODO check handling of DPT10: date is not set to current date, but 1970-01-01 + offset if day is given
275         // maybe we should change the semantics and use current date + offset if day is given
276
277         // Calimero will provide either TIME_DAY_FORMAT or TIME_FORMAT, no-day is not printed
278         Date date = null;
279         try {
280             date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
281         } catch (ParseException pe) {
282             date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
283         }
284         return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
285     }
286
287     private static @Nullable Type handleDpt19(DPTXlator translator, byte[] data) throws KNXFormatException {
288         DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
289         if (translatorDateTime.isFaultyClock()) {
290             // Not supported: faulty clock
291             LOGGER.debug("KNX clock msg ignored: clock faulty bit set, which is not supported");
292             return null;
293         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
294                 && translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
295             // Not supported: "/1/1" (month and day without year)
296             LOGGER.debug("KNX clock msg ignored: no year, but day and month, which is not supported");
297             return null;
298         } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
299                 && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
300             // Not supported: "1900" (year without month and day)
301             LOGGER.debug("KNX clock msg ignored: no day and month, but year, which is not supported");
302             return null;
303         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
304                 && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)
305                 && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
306             // Not supported: No year, no date and no time
307             LOGGER.debug("KNX clock msg ignored: no day and month or year, which is not supported");
308             return null;
309         }
310
311         Calendar cal = Calendar.getInstance();
312         if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
313                 && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
314             // Pure date format, no time information
315             cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
316             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
317             return DateTimeType.valueOf(value);
318         } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
319                 && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
320             // Pure time format, no date information
321             cal.clear();
322             cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
323             cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
324             cal.set(Calendar.SECOND, translatorDateTime.getSecond());
325             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
326             return DateTimeType.valueOf(value);
327         } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
328                 && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
329             // Date format and time information
330             try {
331                 cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
332             } catch (KNXFormatException ignore) {
333                 // throws KNXFormatException in case DST (SUTI) flag does not match calendar
334                 // As the spec regards the SUTI flag as purely informative, flip it and try again.
335                 if (data.length < 8) {
336                     return null;
337                 }
338                 data[6] = (byte) (data[6] ^ 0x01);
339                 translator.setData(data, 0);
340                 cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
341             }
342             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
343             return DateTimeType.valueOf(value);
344         } else {
345             LOGGER.warn("Failed to convert '{}'", translator.getValue());
346             return null;
347         }
348     }
349
350     private static @Nullable Type handleStringOrDecimal(byte[] data, String value, Class<? extends Type> preferredType,
351             int bits) {
352         if (DecimalType.class.equals(preferredType)) {
353             try {
354                 // need a new translator for 8 bit unsigned, as Calimero handles only the string type
355                 if (bits == 8) {
356                     DPTXlator8BitUnsigned translator = new DPTXlator8BitUnsigned("5.010");
357                     translator.setData(data);
358                     return new DecimalType(translator.getValueUnsigned());
359                 } else if (bits == 16) {
360                     DPTXlator2ByteUnsigned translator = new DPTXlator2ByteUnsigned("7.001");
361                     translator.setData(data);
362                     return new DecimalType(translator.getValueUnsigned());
363                 } else {
364                     return null;
365                 }
366             } catch (KNXFormatException e) {
367                 return null;
368             }
369         } else {
370             return StringType.valueOf(value);
371         }
372     }
373
374     private static @Nullable Type handleDpt232(String value, String subType) {
375         Matcher rgb = RGB_PATTERN.matcher(value);
376         if (rgb.matches()) {
377             int r = Integer.parseInt(rgb.group("r"));
378             int g = Integer.parseInt(rgb.group("g"));
379             int b = Integer.parseInt(rgb.group("b"));
380
381             switch (subType) {
382                 case "600":
383                     return HSBType.fromRGB(r, g, b);
384                 case "60000":
385                     // MDT specific: mis-use 232.600 for hsv instead of rgb
386                     DecimalType hue = new DecimalType(coerceToRange(r * 360.0 / 255.0, 0.0, 359.9999));
387                     PercentType sat = new PercentType(BigDecimal.valueOf(coerceToRange(g / 2.55, 0.0, 100.0)));
388                     PercentType bright = new PercentType(BigDecimal.valueOf(coerceToRange(b / 2.55, 0.0, 100.0)));
389                     return new HSBType(hue, sat, bright);
390                 default:
391                     LOGGER.warn("Unknown subtype '232.{}', no conversion possible.", subType);
392                     return null;
393             }
394         }
395         LOGGER.warn("Failed to convert '{}' (DPT 232): Pattern does not match", value);
396         return null;
397     }
398
399     private static @Nullable Type handleDpt242(String value) {
400         Matcher xyY = XYY_PATTERN.matcher(value);
401         if (xyY.matches()) {
402             String stringx = xyY.group("x");
403             String stringy = xyY.group("y");
404             String stringY = xyY.group("Y");
405
406             if (stringx != null && stringy != null) {
407                 double x = Double.parseDouble(stringx.replace(",", "."));
408                 double y = Double.parseDouble(stringy.replace(",", "."));
409                 if (stringY == null) {
410                     return ColorUtil.xyToHsb(new double[] { x, y });
411                 } else {
412                     double pY = Double.parseDouble(stringY.replace(",", "."));
413                     return ColorUtil.xyToHsb(new double[] { x, y, pY / 100.0 });
414                 }
415             }
416         }
417         LOGGER.warn("Failed to convert '{}' (DPT 242): Pattern does not match", value);
418         return null;
419     }
420
421     private static @Nullable Type handleDpt251(String value, String subType, Class<? extends Type> preferredType) {
422         Matcher rgbw = RGBW_PATTERN.matcher(value);
423         if (rgbw.matches()) {
424             String rString = rgbw.group("r");
425             String gString = rgbw.group("g");
426             String bString = rgbw.group("b");
427             String wString = rgbw.group("w");
428
429             switch (subType) {
430                 case "600":
431                     if (rString != null && gString != null && bString != null && HSBType.class.equals(preferredType)) {
432                         // does not support PercentType and r,g,b valid -> HSBType
433                         int r = coerceToRange((int) (Double.parseDouble(rString.replace(",", ".")) * 2.55), 0, 255);
434                         int g = coerceToRange((int) (Double.parseDouble(gString.replace(",", ".")) * 2.55), 0, 255);
435                         int b = coerceToRange((int) (Double.parseDouble(bString.replace(",", ".")) * 2.55), 0, 255);
436
437                         return HSBType.fromRGB(r, g, b);
438                     } else if (wString != null && PercentType.class.equals(preferredType)) {
439                         // does support PercentType and w valid -> PercentType
440                         BigDecimal w = new BigDecimal(wString.replace(",", "."));
441
442                         return new PercentType(w);
443                     }
444                 case "60600":
445                     // special type used by OH for .600 indicating that RGBW should be handled with a single HSBType,
446                     // typically we use HSBType for RGB and PercentType for W.
447                     if (rString != null && gString != null && bString != null && wString != null
448                             && HSBType.class.equals(preferredType)) {
449                         // does support PercentType and w valid -> PercentType
450                         int r = coerceToRange((int) (Double.parseDouble(rString.replace(",", ".")) * 2.55), 0, 255);
451                         int g = coerceToRange((int) (Double.parseDouble(gString.replace(",", ".")) * 2.55), 0, 255);
452                         int b = coerceToRange((int) (Double.parseDouble(bString.replace(",", ".")) * 2.55), 0, 255);
453                         int w = coerceToRange((int) (Double.parseDouble(wString.replace(",", ".")) * 2.55), 0, 255);
454
455                         return ColorUtil.rgbToHsb(new int[] { r, g, b, w });
456                     }
457                 default:
458                     LOGGER.warn("Unknown subtype '251.{}', no conversion possible.", subType);
459                     return null;
460             }
461
462         }
463         LOGGER.warn("Failed to convert '{}' (DPT 251): Pattern does not match or invalid content", value);
464         return null;
465     }
466
467     private static @Nullable Type handleNumericDpt(String id, DPTXlator translator, Class<? extends Type> preferredType)
468             throws KNXFormatException {
469         Set<Class<? extends Type>> allowedTypes = DPTUtil.getAllowedTypes(id);
470
471         double value = translator.getNumericValue();
472         if (allowedTypes.contains(PercentType.class)
473                 && (HSBType.class.equals(preferredType) || PercentType.class.equals(preferredType))) {
474             return new PercentType(BigDecimal.valueOf(Math.round(value)));
475         }
476
477         if (allowedTypes.contains(QuantityType.class) && !disableUoM) {
478             String unit = DPTUnits.getUnitForDpt(id);
479             if (unit != null) {
480                 if (translator instanceof DPTXlator64BitSigned translatorSigned) {
481                     // prevent loss of precision, do not represent 64bit decimal using double
482                     return new QuantityType<>(translatorSigned.getValueSigned() + " " + unit);
483                 }
484                 return new QuantityType<>(value + " " + unit);
485             } else {
486                 LOGGER.trace("Could not determine unit for DPT '{}', fallback to plain decimal", id);
487             }
488         }
489
490         if (allowedTypes.contains(DecimalType.class)) {
491             if (translator instanceof DPTXlator64BitSigned translatorSigned) {
492                 // prevent loss of precision, do not represent 64bit decimal using double
493                 return new DecimalType(translatorSigned.getValueSigned());
494             }
495             return new DecimalType(value);
496         }
497
498         LOGGER.warn("Failed to convert '{}' (DPT '{}'): no matching type found", value, id);
499         return null;
500     }
501
502     private static double coerceToRange(double value, double min, double max) {
503         return Math.min(Math.max(value, min), max);
504     }
505
506     private static int coerceToRange(int value, int min, int max) {
507         return Math.min(Math.max(value, min), max);
508     }
509 }