]> git.basschouten.com Git - openhab-addons.git/blob
6364aeba3e396e0eaa35f9625f29b959e87b6fb3
[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 or point as decimal point), 0-100 for Y, invalid values
77     // omitted
78     public static final Pattern XYY_PATTERN = Pattern
79             .compile("(?:\\((?<x>\\d+(?:[,.]\\d+)?) (?<y>\\d+(?:[,.]\\d+)?)\\))?\\s*(?:(?<Y>\\d+(?:[,.]\\d+)?)\\s%)?");
80
81     /**
82      * convert the raw value received to the corresponding openHAB value
83      *
84      * @param dptId the DPT of the given data
85      * @param data a byte array containing the value
86      * @param preferredType the preferred datatype for this conversion
87      * @return the data converted to an openHAB Type (or null if conversion failed)
88      */
89     public static @Nullable Type decode(String dptId, byte[] data, Class<? extends Type> preferredType) {
90         try {
91             DPTXlator translator = TranslatorTypes.createTranslator(0,
92                     DPTUtil.NORMALIZED_DPT.getOrDefault(dptId, dptId));
93             translator.setData(data);
94             String value = translator.getValue();
95
96             String id = dptId; // prefer using the user-supplied DPT
97
98             Matcher m = DPTUtil.DPT_PATTERN.matcher(id);
99             if (!m.matches() || m.groupCount() != 2) {
100                 LOGGER.trace("User-Supplied DPT '{}' did not match for sub-type, using DPT returned from Translator",
101                         id);
102                 id = translator.getType().getID();
103                 m = DPTUtil.DPT_PATTERN.matcher(id);
104                 if (!m.matches() || m.groupCount() != 2) {
105                     LOGGER.warn("Couldn't identify main/sub number in dptID '{}'", id);
106                     return null;
107                 }
108             }
109             LOGGER.trace("Finally using datapoint DPT = {}", id);
110
111             String mainType = m.group("main");
112             String subType = m.group("sub");
113
114             switch (mainType) {
115                 case "1":
116                     return handleDpt1(subType, translator);
117                 case "2":
118                     DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
119                     int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
120                             + (translator1BitControlled.getValueBit() ? 1 : 0);
121                     return new DecimalType(decValue);
122                 case "3":
123                     return handleDpt3(subType, translator);
124                 case "10":
125                     return handleDpt10(value);
126                 case "11":
127                     return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN)
128                             .format(new SimpleDateFormat(DATE_FORMAT).parse(value)));
129                 case "18":
130                     DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
131                     int decimalValue = translatorSceneControl.getSceneNumber();
132                     if (value.startsWith("learn")) {
133                         decimalValue += 0x80;
134                     }
135                     return new DecimalType(decimalValue);
136                 case "19":
137                     return handleDpt19(translator);
138                 case "16":
139                 case "20":
140                 case "21":
141                 case "22":
142                 case "28":
143                     return StringType.valueOf(value);
144                 case "232":
145                     return handleDpt232(value, subType);
146                 case "242":
147                     return handleDpt242(value);
148                 case "251":
149                     return handleDpt251(value, preferredType);
150                 default:
151                     return handleNumericDpt(id, translator, preferredType);
152             }
153         } catch (NumberFormatException | KNXFormatException | KNXIllegalArgumentException | ParseException e) {
154             LOGGER.info("Translator couldn't parse data '{}' for datapoint type '{}' ({}).", data, dptId, e.getClass());
155         } catch (KNXException e) {
156             LOGGER.warn("Failed creating a translator for datapoint type '{}'.", dptId, e);
157         }
158
159         return null;
160     }
161
162     private static Type handleDpt1(String subType, DPTXlator translator) {
163         DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
164         switch (subType) {
165             case "008":
166                 return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
167             case "009":
168             case "019":
169                 // This is wrong for DPT 1.009. It should be true -> CLOSE, false -> OPEN, but unfortunately
170                 // can't be fixed without breaking a lot of working installations.
171                 // The documentation has been updated to reflect that. / @J-N-K
172                 return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
173             case "010":
174                 return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
175             case "022":
176                 return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
177             default:
178                 return OnOffType.from(translatorBoolean.getValueBoolean());
179         }
180     }
181
182     private static @Nullable Type handleDpt3(String subType, DPTXlator translator) {
183         DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
184         if (translator3BitControlled.getStepCode() == 0) {
185             LOGGER.debug("convertRawDataToType: KNX DPT_Control_Dimming: break received.");
186             return UnDefType.NULL;
187         }
188         switch (subType) {
189             case "007":
190                 return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
191                         : IncreaseDecreaseType.DECREASE;
192             case "008":
193                 return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
194             default:
195                 LOGGER.warn("DPT3, subtype '{}' is unknown.", subType);
196                 return null;
197         }
198     }
199
200     private static Type handleDpt10(String value) throws ParseException {
201         if (value.contains("no-day")) {
202             /*
203              * KNX "no-day" needs special treatment since openHAB's DateTimeType doesn't support "no-day".
204              * Workaround: remove the "no-day" String, parse the remaining time string, which will result in a
205              * date of "1970-01-01".
206              * Replace "no-day" with the current day name
207              */
208             StringBuilder stb = new StringBuilder(value);
209             int start = stb.indexOf("no-day");
210             int end = start + "no-day".length();
211             stb.replace(start, end, String.format(Locale.US, "%1$ta", Calendar.getInstance()));
212             value = stb.toString();
213         }
214         Date date = null;
215         try {
216             date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
217         } catch (ParseException pe) {
218             try {
219                 date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
220             } catch (ParseException pe2) {
221                 throw pe2;
222             }
223         }
224         return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
225     }
226
227     private static @Nullable Type handleDpt19(DPTXlator translator) 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             cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
271             String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
272             return DateTimeType.valueOf(value);
273         } else {
274             LOGGER.warn("Failed to convert '{}'", translator.getValue());
275             return null;
276         }
277     }
278
279     private static @Nullable Type handleDpt232(String value, String subType) {
280         Matcher rgb = RGB_PATTERN.matcher(value);
281         if (rgb.matches()) {
282             int r = Integer.parseInt(rgb.group("r"));
283             int g = Integer.parseInt(rgb.group("g"));
284             int b = Integer.parseInt(rgb.group("b"));
285
286             switch (subType) {
287                 case "600":
288                     return HSBType.fromRGB(r, g, b);
289                 case "60000":
290                     // MDT specific: mis-use 232.600 for hsv instead of rgb
291                     DecimalType hue = new DecimalType(coerceToRange(r * 360.0 / 255.0, 0.0, 359.9999));
292                     PercentType sat = new PercentType(BigDecimal.valueOf(coerceToRange(g / 2.55, 0.0, 100.0)));
293                     PercentType bright = new PercentType(BigDecimal.valueOf(coerceToRange(b / 2.55, 0.0, 100.0)));
294                     return new HSBType(hue, sat, bright);
295                 default:
296                     LOGGER.warn("Unknown subtype '232.{}', no conversion possible.", subType);
297                     return null;
298             }
299         }
300         LOGGER.warn("Failed to convert '{}' (DPT 232): Pattern does not match", value);
301         return null;
302     }
303
304     private static @Nullable Type handleDpt242(String value) {
305         Matcher xyY = XYY_PATTERN.matcher(value);
306         if (xyY.matches()) {
307             String stringx = xyY.group("x");
308             String stringy = xyY.group("y");
309             String stringY = xyY.group("Y");
310
311             if (stringx != null && stringy != null) {
312                 double x = Double.parseDouble(stringx.replace(",", "."));
313                 double y = Double.parseDouble(stringy.replace(",", "."));
314                 if (stringY == null) {
315                     return ColorUtil.xyToHsb(new double[] { x, y });
316                 } else {
317                     double pY = Double.parseDouble(stringY.replace(",", "."));
318                     return ColorUtil.xyToHsb(new double[] { x, y, pY / 100.0 });
319                 }
320             }
321         }
322         LOGGER.warn("Failed to convert '{}' (DPT 242): Pattern does not match", value);
323         return null;
324     }
325
326     private static @Nullable Type handleDpt251(String value, Class<? extends Type> preferredType) {
327         Matcher rgbw = RGBW_PATTERN.matcher(value);
328         if (rgbw.matches()) {
329             String rString = rgbw.group("r");
330             String gString = rgbw.group("g");
331             String bString = rgbw.group("b");
332             String wString = rgbw.group("w");
333
334             if (rString != null && gString != null && bString != null && HSBType.class.equals(preferredType)) {
335                 // does not support PercentType and r,g,b valid -> HSBType
336                 int r = coerceToRange((int) (Double.parseDouble(rString.replace(",", ".")) * 2.55), 0, 255);
337                 int g = coerceToRange((int) (Double.parseDouble(gString.replace(",", ".")) * 2.55), 0, 255);
338                 int b = coerceToRange((int) (Double.parseDouble(bString.replace(",", ".")) * 2.55), 0, 255);
339
340                 return HSBType.fromRGB(r, g, b);
341             } else if (wString != null && PercentType.class.equals(preferredType)) {
342                 // does support PercentType and w valid -> PercentType
343                 BigDecimal w = new BigDecimal(wString.replace(",", "."));
344
345                 return new PercentType(w);
346             }
347         }
348         LOGGER.warn("Failed to convert '{}' (DPT 251): Pattern does not match or invalid content", value);
349         return null;
350     }
351
352     private static @Nullable Type handleNumericDpt(String id, DPTXlator translator, Class<? extends Type> preferredType)
353             throws KNXFormatException {
354         Set<Class<? extends Type>> allowedTypes = DPTUtil.getAllowedTypes(id);
355
356         double value = translator.getNumericValue();
357         if (allowedTypes.contains(PercentType.class)
358                 && (HSBType.class.equals(preferredType) || PercentType.class.equals(preferredType))) {
359             return new PercentType(BigDecimal.valueOf(Math.round(value)));
360         }
361
362         if (allowedTypes.contains(QuantityType.class) && !disableUoM) {
363             String unit = DPTUnits.getUnitForDpt(id);
364             if (unit != null) {
365                 return new QuantityType<>(value + " " + unit);
366             } else {
367                 LOGGER.trace("Could not determine unit for DPT '{}', fallback to plain decimal", id);
368             }
369         }
370
371         if (allowedTypes.contains(DecimalType.class)) {
372             return new DecimalType(value);
373         }
374
375         LOGGER.warn("Failed to convert '{}' (DPT '{}'): no matching type found", value, id);
376         return null;
377     }
378
379     private static double coerceToRange(double value, double min, double max) {
380         return Math.min(Math.max(value, min), max);
381     }
382
383     private static int coerceToRange(int value, int min, int max) {
384         return Math.min(Math.max(value, min), max);
385     }
386 }