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.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;
58 * This class decodes raw data received from the KNX bus to an openHAB datatype
60 * Parts of this code are based on the openHAB KNXCoreTypeMapper by Kai Kreuzer et al.
62 * @author Jan N. Klug - Initial contribution
65 public class ValueDecoder {
66 private static final Logger LOGGER = LoggerFactory.getLogger(ValueDecoder.class);
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
78 public static final Pattern XYY_PATTERN = Pattern
79 .compile("(?:\\((?<x>\\d+(?:[,.]\\d+)?) (?<y>\\d+(?:[,.]\\d+)?)\\))?\\s*(?:(?<Y>\\d+(?:[,.]\\d+)?)\\s%)?");
82 * convert the raw value received to the corresponding openHAB value
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)
89 public static @Nullable Type decode(String dptId, byte[] data, Class<? extends Type> preferredType) {
91 DPTXlator translator = TranslatorTypes.createTranslator(0,
92 DPTUtil.NORMALIZED_DPT.getOrDefault(dptId, dptId));
93 translator.setData(data);
94 String value = translator.getValue();
96 String id = dptId; // prefer using the user-supplied DPT
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",
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);
109 LOGGER.trace("Finally using datapoint DPT = {}", id);
111 String mainType = m.group("main");
112 String subType = m.group("sub");
116 return handleDpt1(subType, translator);
118 DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
119 int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
120 + (translator1BitControlled.getValueBit() ? 1 : 0);
121 return new DecimalType(decValue);
123 return handleDpt3(subType, translator);
125 return handleDpt10(value);
127 return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN)
128 .format(new SimpleDateFormat(DATE_FORMAT).parse(value)));
130 DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
131 int decimalValue = translatorSceneControl.getSceneNumber();
132 if (value.startsWith("learn")) {
133 decimalValue += 0x80;
135 return new DecimalType(decimalValue);
137 return handleDpt19(translator);
143 return StringType.valueOf(value);
145 return handleDpt232(value, subType);
147 return handleDpt242(value);
149 return handleDpt251(value, preferredType);
151 return handleNumericDpt(id, translator, preferredType);
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);
162 private static Type handleDpt1(String subType, DPTXlator translator) {
163 DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
166 return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
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;
174 return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
176 return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
178 return OnOffType.from(translatorBoolean.getValueBoolean());
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;
190 return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
191 : IncreaseDecreaseType.DECREASE;
193 return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
195 LOGGER.warn("DPT3, subtype '{}' is unknown.", subType);
200 private static Type handleDpt10(String value) throws ParseException {
201 if (value.contains("no-day")) {
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
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();
216 date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
217 } catch (ParseException pe) {
218 date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
220 return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
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");
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");
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");
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");
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
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);
270 LOGGER.warn("Failed to convert '{}'", translator.getValue());
275 private static @Nullable Type handleDpt232(String value, String subType) {
276 Matcher rgb = RGB_PATTERN.matcher(value);
278 int r = Integer.parseInt(rgb.group("r"));
279 int g = Integer.parseInt(rgb.group("g"));
280 int b = Integer.parseInt(rgb.group("b"));
284 return HSBType.fromRGB(r, g, b);
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);
292 LOGGER.warn("Unknown subtype '232.{}', no conversion possible.", subType);
296 LOGGER.warn("Failed to convert '{}' (DPT 232): Pattern does not match", value);
300 private static @Nullable Type handleDpt242(String value) {
301 Matcher xyY = XYY_PATTERN.matcher(value);
303 String stringx = xyY.group("x");
304 String stringy = xyY.group("y");
305 String stringY = xyY.group("Y");
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 });
313 double pY = Double.parseDouble(stringY.replace(",", "."));
314 return ColorUtil.xyToHsb(new double[] { x, y, pY / 100.0 });
318 LOGGER.warn("Failed to convert '{}' (DPT 242): Pattern does not match", value);
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");
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);
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(",", "."));
341 return new PercentType(w);
344 LOGGER.warn("Failed to convert '{}' (DPT 251): Pattern does not match or invalid content", value);
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);
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)));
358 if (allowedTypes.contains(QuantityType.class) && !disableUoM) {
359 String unit = DPTUnits.getUnitForDpt(id);
361 return new QuantityType<>(value + " " + unit);
363 LOGGER.trace("Could not determine unit for DPT '{}', fallback to plain decimal", id);
367 if (allowedTypes.contains(DecimalType.class)) {
368 return new DecimalType(value);
371 LOGGER.warn("Failed to convert '{}' (DPT '{}'): no matching type found", value, id);
375 private static double coerceToRange(double value, double min, double max) {
376 return Math.min(Math.max(value, min), max);
379 private static int coerceToRange(int value, int min, int max) {
380 return Math.min(Math.max(value, min), max);