2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.knx.internal.dpt;
15 import static org.openhab.binding.knx.internal.KNXBindingConstants.disableUoM;
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;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
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;
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;
61 * This class decodes raw data received from the KNX bus to an openHAB datatype
63 * Parts of this code are based on the openHAB KNXCoreTypeMapper by Kai Kreuzer et al.
65 * @author Jan N. Klug - Initial contribution
68 public class ValueDecoder {
69 private static final Logger LOGGER = LoggerFactory.getLogger(ValueDecoder.class);
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
81 public static final Pattern XYY_PATTERN = Pattern
82 .compile("(?:\\((?<x>\\d+(?:[,.]\\d+)?) (?<y>\\d+(?:[,.]\\d+)?)\\))?\\s*(?:(?<Y>\\d+(?:[,.]\\d+)?)\\s%)?");
85 * convert the raw value received to the corresponding openHAB value
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)
92 public static @Nullable Type decode(String dptId, byte[] data, Class<? extends Type> preferredType) {
94 DPTXlator translator = TranslatorTypes.createTranslator(0,
95 DPTUtil.NORMALIZED_DPT.getOrDefault(dptId, dptId));
96 translator.setData(data);
97 String value = translator.getValue();
99 String id = dptId; // prefer using the user-supplied DPT
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",
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);
112 LOGGER.trace("Finally using datapoint DPT = {}", id);
114 String mainType = m.group("main");
115 String subType = m.group("sub");
119 return handleDpt1(subType, translator);
121 DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
122 int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
123 + (translator1BitControlled.getValueBit() ? 1 : 0);
124 return new DecimalType(decValue);
126 return handleDpt3(subType, translator);
128 return handleDpt10(value);
130 return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN)
131 .format(new SimpleDateFormat(DATE_FORMAT).parse(value)));
133 DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
134 int decimalValue = translatorSceneControl.getSceneNumber();
135 if (value.startsWith("learn")) {
136 decimalValue += 0x80;
138 return new DecimalType(decimalValue);
140 return handleDpt19(translator, data);
143 return handleStringOrDecimal(data, value, preferredType, 8);
145 return handleStringOrDecimal(data, value, preferredType, 16);
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(". ", ", "));
157 return handleDpt232(value, subType);
159 return handleDpt242(value);
161 return handleDpt251(value, preferredType);
163 return handleNumericDpt(id, translator, preferredType);
164 // TODO 6.001 is mapped to PercentType, which can only cover 0-100%, not -128..127%
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);
175 private static Type handleDpt1(String subType, DPTXlator translator) {
176 DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
179 return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
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;
187 return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
189 return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
191 return OnOffType.from(translatorBoolean.getValueBoolean());
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;
203 return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
204 : IncreaseDecreaseType.DECREASE;
206 return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
208 LOGGER.warn("DPT3, subtype '{}' is unknown.", subType);
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
217 // Calimero will provide either TIME_DAY_FORMAT or TIME_FORMAT, no-day is not printed
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);
224 return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
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");
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");
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");
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");
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
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
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) {
278 data[6] = (byte) (data[6] ^ 0x01);
279 translator.setData(data, 0);
280 cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
282 String value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
283 return DateTimeType.valueOf(value);
285 LOGGER.warn("Failed to convert '{}'", translator.getValue());
290 private static @Nullable Type handleStringOrDecimal(byte[] data, String value, Class<? extends Type> preferredType,
292 if (DecimalType.class.equals(preferredType)) {
294 // need a new translator for 8 bit unsigned, as Calimero handles only the string type
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());
306 } catch (KNXFormatException e) {
310 return StringType.valueOf(value);
314 private static @Nullable Type handleDpt232(String value, String subType) {
315 Matcher rgb = RGB_PATTERN.matcher(value);
317 int r = Integer.parseInt(rgb.group("r"));
318 int g = Integer.parseInt(rgb.group("g"));
319 int b = Integer.parseInt(rgb.group("b"));
323 return HSBType.fromRGB(r, g, b);
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);
331 LOGGER.warn("Unknown subtype '232.{}', no conversion possible.", subType);
335 LOGGER.warn("Failed to convert '{}' (DPT 232): Pattern does not match", value);
339 private static @Nullable Type handleDpt242(String value) {
340 Matcher xyY = XYY_PATTERN.matcher(value);
342 String stringx = xyY.group("x");
343 String stringy = xyY.group("y");
344 String stringY = xyY.group("Y");
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 });
352 double pY = Double.parseDouble(stringY.replace(",", "."));
353 return ColorUtil.xyToHsb(new double[] { x, y, pY / 100.0 });
357 LOGGER.warn("Failed to convert '{}' (DPT 242): Pattern does not match", value);
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");
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);
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(",", "."));
380 return new PercentType(w);
383 LOGGER.warn("Failed to convert '{}' (DPT 251): Pattern does not match or invalid content", value);
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);
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)));
397 if (allowedTypes.contains(QuantityType.class) && !disableUoM) {
398 String unit = DPTUnits.getUnitForDpt(id);
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);
404 return new QuantityType<>(value + " " + unit);
406 LOGGER.trace("Could not determine unit for DPT '{}', fallback to plain decimal", id);
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());
415 return new DecimalType(value);
418 LOGGER.warn("Failed to convert '{}' (DPT '{}'): no matching type found", value, id);
422 private static double coerceToRange(double value, double min, double max) {
423 return Math.min(Math.max(value, min), max);
426 private static int coerceToRange(int value, int min, int max) {
427 return Math.min(Math.max(value, min), max);