]> git.basschouten.com Git - openhab-addons.git/blob
c2519d3bf719ffd3343a49ea1acf13bc712995cc
[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.dpt.DPTUtil.NORMALIZED_DPT;
16
17 import java.math.BigDecimal;
18 import java.math.RoundingMode;
19 import java.util.Locale;
20 import java.util.regex.Matcher;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.core.library.types.DateTimeType;
25 import org.openhab.core.library.types.DecimalType;
26 import org.openhab.core.library.types.HSBType;
27 import org.openhab.core.library.types.IncreaseDecreaseType;
28 import org.openhab.core.library.types.OnOffType;
29 import org.openhab.core.library.types.OpenClosedType;
30 import org.openhab.core.library.types.PercentType;
31 import org.openhab.core.library.types.QuantityType;
32 import org.openhab.core.library.types.StopMoveType;
33 import org.openhab.core.library.types.StringType;
34 import org.openhab.core.library.types.UpDownType;
35 import org.openhab.core.library.unit.SIUnits;
36 import org.openhab.core.library.unit.Units;
37 import org.openhab.core.types.Type;
38 import org.openhab.core.util.ColorUtil;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import tuwien.auto.calimero.KNXException;
43 import tuwien.auto.calimero.dptxlator.DPT;
44 import tuwien.auto.calimero.dptxlator.DPTXlator;
45 import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;
46 import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat;
47 import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
48 import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat;
49 import tuwien.auto.calimero.dptxlator.DPTXlatorDate;
50 import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;
51 import tuwien.auto.calimero.dptxlator.DPTXlatorTime;
52 import tuwien.auto.calimero.dptxlator.TranslatorTypes;
53
54 /**
55  * This class encodes openHAB data types to strings for sending via Calimero
56  *
57  * Parts of this code are based on the openHAB KNXCoreTypeMapper by Kai Kreuzer et al.
58  *
59  * @author Jan N. Klug - Initial contribution
60  */
61 @NonNullByDefault
62 public class ValueEncoder {
63     private static final Logger LOGGER = LoggerFactory.getLogger(ValueEncoder.class);
64
65     private ValueEncoder() {
66         // prevent instantiation
67     }
68
69     /**
70      * Formats the given value as String for outputting via Calimero.
71      *
72      * @param value the value
73      * @param dptId the DPT id to use for formatting the string (e.g. 9.001)
74      * @return the value formatted as String
75      */
76     public static @Nullable String encode(Type value, String dptId) {
77         Matcher m = DPTUtil.DPT_PATTERN.matcher(dptId);
78         if (!m.matches() || m.groupCount() != 2) {
79             LOGGER.warn("Couldn't identify main/sub number in dptId '{}'", dptId);
80             return null;
81         }
82
83         String mainNumber = m.group("main");
84
85         try {
86             DPTXlator translator = TranslatorTypes.createTranslator(Integer.parseInt(mainNumber),
87                     NORMALIZED_DPT.getOrDefault(dptId, dptId));
88             DPT dpt = translator.getType();
89
90             // check for HSBType first, because it extends PercentType as well
91             if (value instanceof HSBType type) {
92                 return handleHSBType(dptId, type);
93             } else if (value instanceof OnOffType) {
94                 return OnOffType.OFF == value ? dpt.getLowerValue() : dpt.getUpperValue();
95             } else if (value instanceof UpDownType) {
96                 return UpDownType.UP == value ? dpt.getLowerValue() : dpt.getUpperValue();
97             } else if (value instanceof IncreaseDecreaseType) {
98                 DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();
99                 return IncreaseDecreaseType.DECREASE == value ? valueDPT.getLowerValue() + " 5"
100                         : valueDPT.getUpperValue() + " 5";
101             } else if (value instanceof OpenClosedType) {
102                 return OpenClosedType.CLOSED == value ? dpt.getLowerValue() : dpt.getUpperValue();
103             } else if (value instanceof StopMoveType) {
104                 return StopMoveType.STOP == value ? dpt.getLowerValue() : dpt.getUpperValue();
105             } else if (value instanceof PercentType type) {
106                 int intValue = type.intValue();
107                 return "251.600".equals(dptId) ? String.format("- - - %d %%", intValue) : String.valueOf(intValue);
108             } else if (value instanceof DecimalType || value instanceof QuantityType<?>) {
109                 return handleNumericTypes(dptId, mainNumber, dpt, value);
110             } else if (value instanceof StringType) {
111                 return value.toString();
112             } else if (value instanceof DateTimeType type) {
113                 return handleDateTimeType(dptId, type);
114             }
115         } catch (KNXException e) {
116             return null;
117         } catch (Exception e) {
118             LOGGER.warn("An exception occurred converting value {} to dpt id {}: error message={}", value, dptId,
119                     e.getMessage());
120             return null;
121         }
122
123         LOGGER.debug("formatAsDPTString: Couldn't convert value {} to dpt id {} (no mapping).", value, dptId);
124         return null;
125     }
126
127     /**
128      * Formats the given internal <code>dateType</code> to a knx readable String
129      * according to the target datapoint type <code>dpt</code>.
130      *
131      * @param value the input value
132      * @param dptId the target datapoint type
133      *
134      * @return a String which contains either an ISO8601 formatted date (yyyy-mm-dd),
135      *         a formatted 24-hour clock with the day of week prepended (Mon, 12:00:00) or
136      *         a formatted 24-hour clock (12:00:00)
137      */
138     private static @Nullable String handleDateTimeType(String dptId, DateTimeType value) {
139         if (DPTXlatorDate.DPT_DATE.getID().equals(dptId)) {
140             return value.format("%tF");
141         } else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dptId)) {
142             return value.format(Locale.US, "%1$ta, %1$tT");
143         } else if (DPTXlatorDateTime.DPT_DATE_TIME.getID().equals(dptId)) {
144             return value.format(Locale.US, "%tF %1$tT");
145         }
146         LOGGER.warn("Could not format DateTimeType for datapoint type '{}'", dptId);
147         return null;
148     }
149
150     private static String handleHSBType(String dptId, HSBType hsb) {
151         switch (dptId) {
152             case "232.600":
153                 int[] rgb = ColorUtil.hsbToRgb(hsb);
154                 return String.format("r:%d g:%d b:%d", rgb[0], rgb[1], rgb[2]);
155             case "232.60000":
156                 // MDT specific: mis-use 232.600 for hsv instead of rgb
157                 int hue = hsb.getHue().toBigDecimal().multiply(BigDecimal.valueOf(255))
158                         .divide(BigDecimal.valueOf(360), 0, RoundingMode.HALF_UP).intValue();
159                 return "r:" + hue + " g:" + convertPercentToByte(hsb.getSaturation()) + " b:"
160                         + convertPercentToByte(hsb.getBrightness());
161             case "242.600":
162                 double[] xyY = ColorUtil.hsbToXY(hsb);
163                 return String.format("(%,.4f %,.4f) %,.1f %%", xyY[0], xyY[1], xyY[2] * 100.0);
164             case "251.600":
165                 PercentType[] rgbw = ColorUtil.hsbToRgbPercent(hsb);
166                 return String.format("%,.1f %,.1f %,.1f - %%", rgbw[0].doubleValue(), rgbw[1].doubleValue(),
167                         rgbw[2].doubleValue());
168             case "5.003":
169                 return hsb.getHue().toString();
170             default:
171                 return hsb.getBrightness().toString();
172         }
173     }
174
175     private static String handleNumericTypes(String dptId, String mainNumber, DPT dpt, Type value) {
176         BigDecimal bigDecimal;
177         if (value instanceof DecimalType decimalType) {
178             bigDecimal = decimalType.toBigDecimal();
179         } else {
180             String unit = DPTUnits.getUnitForDpt(dptId);
181
182             // exception for DPT using temperature differences
183             // - conversion °C or °F to K is wrong for differences,
184             // - stick to the unit given, fix the scaling for °F
185             // 9.002 DPT_Value_Tempd
186             // 9.003 DPT_Value_Tempa
187             // 9.023 DPT_KelvinPerPercent
188             if (DPTXlator2ByteFloat.DPT_TEMPERATURE_DIFFERENCE.getID().equals(dptId)
189                     || DPTXlator2ByteFloat.DPT_TEMPERATURE_GRADIENT.getID().equals(dptId)
190                     || DPTXlator2ByteFloat.DPT_KELVIN_PER_PERCENT.getID().equals(dptId)) {
191                 // match unicode character or °C
192                 if (value.toString().contains(SIUnits.CELSIUS.getSymbol()) || value.toString().contains("°C")) {
193                     if (unit != null) {
194                         unit = unit.replace("K", "°C");
195                     }
196                 } else if (value.toString().contains("°F")) {
197                     // an new approach to handle temperature differences was introduced to core
198                     // after 4.0, stripping the unit and and creating a new QuantityType works
199                     // both with core release 4.0 and current snapshot
200                     boolean perPercent = value.toString().contains("/%");
201                     value = new QuantityType<>(((QuantityType<?>) value).doubleValue() * 5.0 / 9.0, Units.KELVIN);
202                     // PercentType needs to be adapted
203                     if (perPercent) {
204                         value = ((QuantityType<?>) value).multiply(BigDecimal.valueOf(100));
205                     }
206                 }
207             } else if (DPTXlator4ByteFloat.DPT_LIGHT_QUANTITY.getID().equals(dptId)) {
208                 if (!value.toString().contains("J")) {
209                     if (unit != null) {
210                         unit = unit.replace("J", "lm*s");
211                     }
212                 }
213             } else if (DPTXlator4ByteFloat.DPT_ELECTRIC_FLUX.getID().equals(dptId)) {
214                 // use alternate definition of flux
215                 if (value.toString().contains("C")) {
216                     unit = "C";
217                 }
218             }
219
220             if (unit != null) {
221                 QuantityType<?> converted = ((QuantityType<?>) value).toUnit(unit);
222                 if (converted == null) {
223                     LOGGER.warn("Could not convert {} to unit {}, stripping unit only. Check your configuration.",
224                             value, unit);
225                     bigDecimal = ((QuantityType<?>) value).toBigDecimal();
226                 } else {
227                     bigDecimal = converted.toBigDecimal();
228                 }
229             } else {
230                 bigDecimal = ((QuantityType<?>) value).toBigDecimal();
231             }
232         }
233         switch (mainNumber) {
234             case "2":
235                 DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();
236                 switch (bigDecimal.intValue()) {
237                     case 0:
238                         return "0 " + valueDPT.getLowerValue();
239                     case 1:
240                         return "0 " + valueDPT.getUpperValue();
241                     case 2:
242                         return "1 " + valueDPT.getLowerValue();
243                     default:
244                         return "1 " + valueDPT.getUpperValue();
245                 }
246             case "18":
247                 int intVal = bigDecimal.intValue();
248                 if (intVal > 63) {
249                     return "learn " + (intVal - 0x80);
250                 } else {
251                     return "activate " + intVal;
252                 }
253             default:
254                 return bigDecimal.stripTrailingZeros().toPlainString();
255         }
256     }
257
258     /**
259      * convert 0...100% to 1 byte 0..255
260      *
261      * @param percent
262      * @return int 0..255
263      */
264     private static int convertPercentToByte(PercentType percent) {
265         return percent.toBigDecimal().multiply(BigDecimal.valueOf(255))
266                 .divide(BigDecimal.valueOf(100), 0, RoundingMode.HALF_UP).intValue();
267     }
268 }