]> git.basschouten.com Git - openhab-addons.git/blob
4c02a4bb4f0ce9880c6c4ad0b8a59d4dbc5cedce
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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 java.math.BigDecimal;
16 import java.math.RoundingMode;
17 import java.text.DecimalFormat;
18 import java.text.NumberFormat;
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.Arrays;
22 import java.util.Calendar;
23 import java.util.Date;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.Map;
28
29 import org.openhab.binding.knx.internal.KNXTypeMapper;
30 import org.openhab.core.library.types.DateTimeType;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.HSBType;
33 import org.openhab.core.library.types.IncreaseDecreaseType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.OpenClosedType;
36 import org.openhab.core.library.types.PercentType;
37 import org.openhab.core.library.types.QuantityType;
38 import org.openhab.core.library.types.StopMoveType;
39 import org.openhab.core.library.types.StringType;
40 import org.openhab.core.library.types.UpDownType;
41 import org.openhab.core.types.Type;
42 import org.openhab.core.types.UnDefType;
43 import org.osgi.service.component.annotations.Component;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import tuwien.auto.calimero.KNXException;
48 import tuwien.auto.calimero.KNXFormatException;
49 import tuwien.auto.calimero.KNXIllegalArgumentException;
50 import tuwien.auto.calimero.datapoint.Datapoint;
51 import tuwien.auto.calimero.dptxlator.DPT;
52 import tuwien.auto.calimero.dptxlator.DPTXlator;
53 import tuwien.auto.calimero.dptxlator.DPTXlator1BitControlled;
54 import tuwien.auto.calimero.dptxlator.DPTXlator2ByteFloat;
55 import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned;
56 import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
57 import tuwien.auto.calimero.dptxlator.DPTXlator4ByteFloat;
58 import tuwien.auto.calimero.dptxlator.DPTXlator4ByteSigned;
59 import tuwien.auto.calimero.dptxlator.DPTXlator4ByteUnsigned;
60 import tuwien.auto.calimero.dptxlator.DPTXlator64BitSigned;
61 import tuwien.auto.calimero.dptxlator.DPTXlator8BitSigned;
62 import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned;
63 import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;
64 import tuwien.auto.calimero.dptxlator.DPTXlatorDate;
65 import tuwien.auto.calimero.dptxlator.DPTXlatorDateTime;
66 import tuwien.auto.calimero.dptxlator.DPTXlatorRGB;
67 import tuwien.auto.calimero.dptxlator.DPTXlatorSceneControl;
68 import tuwien.auto.calimero.dptxlator.DPTXlatorSceneNumber;
69 import tuwien.auto.calimero.dptxlator.DPTXlatorString;
70 import tuwien.auto.calimero.dptxlator.DPTXlatorTime;
71 import tuwien.auto.calimero.dptxlator.DPTXlatorUtf8;
72 import tuwien.auto.calimero.dptxlator.TranslatorTypes;
73
74 /**
75  * This class provides type mapping between all openHAB core types and KNX data point types.
76  *
77  * Each 'MainType' delivered from calimero, has a default mapping
78  * for all it's children to a openHAB Typeclass.
79  * All these 'MainType' mapping's are put into 'dptMainTypeMap'.
80  *
81  * Default 'MainType' mapping's we can override by a specific mapping.
82  * All specific mapping's are put into 'dptTypeMap'.
83  *
84  * If for a 'MainType' there is currently no specific mapping registered,
85  * you can find a commented example line, with it's correct 'DPTXlator' class.
86  *
87  * @author Kai Kreuzer
88  * @author Volker Daube
89  * @author Jan N. Klug
90  * @author Helmut Lehmeyer - Java8, generic DPT Mapper
91  */
92 @Component
93 public class KNXCoreTypeMapper implements KNXTypeMapper {
94
95     private final Logger logger = LoggerFactory.getLogger(KNXCoreTypeMapper.class);
96
97     private static final String TIME_DAY_FORMAT = new String("EEE, HH:mm:ss");
98     private static final String DATE_FORMAT = new String("yyyy-MM-dd");
99
100     /**
101      * stores the openHAB type class for (supported) KNX datapoint types in a generic way.
102      * dptTypeMap stores more specific type class and exceptions.
103      */
104     private final Map<Integer, Class<? extends Type>> dptMainTypeMap;
105
106     /** stores the openHAB type class for all (supported) KNX datapoint types */
107     private final Map<String, Class<? extends Type>> dptTypeMap;
108
109     /** stores the default KNX DPT to use for each openHAB type */
110     private final Map<Class<? extends Type>, String> defaultDptMap;
111
112     public KNXCoreTypeMapper() {
113         @SuppressWarnings("unused")
114         final List<Class<?>> xlators = Arrays.<Class<?>> asList(DPTXlator1BitControlled.class,
115                 DPTXlator2ByteFloat.class, DPTXlator2ByteUnsigned.class, DPTXlator3BitControlled.class,
116                 DPTXlator4ByteFloat.class, DPTXlator4ByteSigned.class, DPTXlator4ByteUnsigned.class,
117                 DPTXlator64BitSigned.class, DPTXlator8BitSigned.class, DPTXlator8BitUnsigned.class,
118                 DPTXlatorBoolean.class, DPTXlatorDate.class, DPTXlatorDateTime.class, DPTXlatorRGB.class,
119                 DPTXlatorSceneControl.class, DPTXlatorSceneNumber.class, DPTXlatorString.class, DPTXlatorTime.class,
120                 DPTXlatorUtf8.class);
121
122         dptTypeMap = new HashMap<>();
123         dptMainTypeMap = new HashMap<>();
124
125         /**
126          * MainType: 1
127          * 1.000: General bool
128          * 1.001: DPT_Switch values: 0 = off 1 = on
129          * 1.002: DPT_Bool values: 0 = false 1 = true
130          * 1.003: DPT_Enable values: 0 = disable 1 = enable
131          * 1.004: DPT_Ramp values: 0 = no ramp 1 = ramp
132          * 1.005: DPT_Alarm values: 0 = no alarm 1 = alarm
133          * 1.006: DPT_BinaryValue values: 0 = low 1 = high
134          * 1.007: DPT_Step values: 0 = decrease 1 = increase
135          * 1.008: DPT_UpDown values: 0 = up 1 = down
136          * 1.009: DPT_OpenClose values: 0 = open 1 = close
137          * 1.010: DPT_Start values: 0 = stop 1 = start
138          * 1.011: DPT_State values: 0 = inactive 1 = active
139          * 1.012: DPT_Invert values: 0 = not inverted 1 = inverted
140          * 1.013: DPT_DimSendStyle values: 0 = start/stop 1 = cyclic
141          * 1.014: DPT_InputSource values: 0 = fixed 1 = calculated
142          * 1.015: DPT_Reset values: 0 = no action 1 = reset
143          * 1.016: DPT_Ack values: 0 = no action 1 = acknowledge
144          * 1.017: DPT_Trigger values: 0 = trigger 1 = trigger
145          * 1.018: DPT_Occupancy values: 0 = not occupied 1 = occupied
146          * 1.019: DPT_Window_Door values: 0 = closed 1 = open
147          * 1.021: DPT_LogicalFunction values: 0 = OR 1 = AND
148          * 1.022: DPT_Scene_AB values: 0 = scene A 1 = scene B
149          * 1.023: DPT_ShutterBlinds_Mode values: 0 = only move up/down 1 = move up/down + step-stop
150          * 1.100: DPT_Heat/Cool values: 0 = cooling 1 = heating
151          */
152         dptMainTypeMap.put(1, OnOffType.class);
153         /** Exceptions Datapoint Types "B1", Main number 1 */
154         dptTypeMap.put(DPTXlatorBoolean.DPT_UPDOWN.getID(), UpDownType.class);
155         dptTypeMap.put(DPTXlatorBoolean.DPT_OPENCLOSE.getID(), OpenClosedType.class);
156         dptTypeMap.put(DPTXlatorBoolean.DPT_START.getID(), StopMoveType.class);
157         dptTypeMap.put(DPTXlatorBoolean.DPT_WINDOW_DOOR.getID(), OpenClosedType.class);
158         dptTypeMap.put(DPTXlatorBoolean.DPT_SCENE_AB.getID(), DecimalType.class);
159
160         /**
161          * MainType: 2
162          * 2.001: DPT_Switch_Control values: 0 = off 1 = on
163          * 2.002: DPT_Bool_Control values: 0 = false 1 = true
164          * 2.003: DPT_Enable_Control values: 0 = disable 1 = enable
165          * 2.004: DPT_Ramp_Control values: 0 = no ramp 1 = ramp
166          * 2.005: DPT_Alarm_Control values: 0 = no alarm 1 = alarm
167          * 2.006: DPT_BinaryValue_Control values: 0 = low 1 = high
168          * 2.007: DPT_Step_Control values: 0 = decrease 1 = increase
169          * 2.008: DPT_Direction1_Control values: 0 = up 1 = down
170          * 2.009: DPT_Direction2_Control values: 0 = open 1 = close
171          * 2.010: DPT_Start_Control values: 0 = stop 1 = start
172          * 2.011: DPT_State_Control values: 0 = inactive 1 = active
173          * 2.012: DPT_Invert_Control values: 0 = not inverted 1 = inverted
174          */
175         dptMainTypeMap.put(2, DecimalType.class);
176         /** Exceptions Datapoint Types "B2", Main number 2 */
177         // Example: dptTypeMap.put(DPTXlator1BitControlled.DPT_SWITCH_CONTROL.getID(), DecimalType.class);
178
179         /**
180          * MainType: 3
181          * 3.007: DPT_Control_Dimming values: 0 = decrease 1 = increase
182          * 3.008: DPT_Control_Blinds values: 0 = up 1 = down
183          */
184         dptMainTypeMap.put(3, IncreaseDecreaseType.class);
185         /** Exceptions Datapoint Types "B1U3", Main number 3 */
186         dptTypeMap.put(DPTXlator3BitControlled.DPT_CONTROL_BLINDS.getID(), UpDownType.class);
187
188         /**
189          * MainType: 4
190          * 4.001: DPT_Char_ASCII
191          * 4.002: DPT_Char_8859_1
192          */
193         dptMainTypeMap.put(4, StringType.class);
194
195         /**
196          * MainType: 5
197          * 5.000: General byte
198          * 5.001: DPT_Scaling values: 0...100 %
199          * 5.003: DPT_Angle values: 0...360 °
200          * 5.004: DPT_Percent_U8 (8 Bit) values: 0...255 %
201          * 5.005: DPT_DecimalFactor values: 0...255 ratio
202          * 5.006: DPT_Tariff values: 0...254
203          * 5.010: DPT_Value_1_Ucount Unsigned count values: 0...255 counter pulses
204          */
205         dptMainTypeMap.put(5, DecimalType.class);
206         /** Exceptions Types "8-Bit Unsigned Value", Main number 5 */
207         dptTypeMap.put(DPTXlator8BitUnsigned.DPT_SCALING.getID(), PercentType.class);
208         dptTypeMap.put(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID(), PercentType.class);
209
210         /**
211          * MainType: 6
212          * 6.001: DPT_Percent_V8 (8 Bit) values: -128...127 %
213          * 6.010: DPT_Value_1_Count values: signed -128...127 counter pulses
214          * 6.020: DPT_Status_Mode3 with mode values: 0/0/0/0/0 0...1/1/1/1/1 2
215          */
216         dptMainTypeMap.put(6, DecimalType.class);
217         /** Exceptions Datapoint Types "8-Bit Signed Value", Main number 6 */
218         dptTypeMap.put(DPTXlator8BitSigned.DPT_PERCENT_V8.getID(), PercentType.class);
219         dptTypeMap.put(DPTXlator8BitSigned.DPT_STATUS_MODE3.getID(), StringType.class);
220
221         /**
222          * MainType: 7
223          * 7.000: General unsigned integer
224          * 7.001: DPT_Value_2_Ucount values: 0...65535 pulses
225          * 7.002: DPT_TimePeriodMsec values: 0...65535 res 1 ms
226          * 7.003: DPT_TimePeriod10MSec values: 0...655350 res 10 ms
227          * 7.004: DPT_TimePeriod100MSec values: 0...6553500 res 100 ms
228          * 7.005: DPT_TimePeriodSec values: 0...65535 s
229          * 7.006: DPT_TimePeriodMin values: 0...65535 min
230          * 7.007: DPT_TimePeriodHrs values: 0...65535 h
231          * 7.010: DPT_PropDataType values: 0...65535
232          * 7.011: DPT_Length_mm values: 0...65535 mm
233          * 7.012: DPT_UElCurrentmA values: 0...65535 mA
234          * 7.013: DPT_Brightness values: 0...65535 lx
235          * 7.600: DPT_Colour_Temperature values: 0...65535 K, 2000K 3000K 5000K 8000K
236          */
237         dptMainTypeMap.put(7, DecimalType.class);
238         /** Exceptions Datapoint Types "2-Octet Unsigned Value", Main number 7 */
239         dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
240
241         /**
242          * MainType: 8
243          * 8.000: General integer
244          * 8.001: DPT_Value_2_Count
245          * 8.002: DPT_DeltaTimeMsec
246          * 8.003: DPT_DeltaTime10MSec
247          * 8.004: DPT_DeltaTime100MSec
248          * 8.005: DPT_DeltaTimeSec
249          * 8.006: DPT_DeltaTimeMin
250          * 8.007: DPT_DeltaTimeHrs
251          * 8.010: DPT_Percent_V16
252          * 8.011: DPT_Rotation_Angle
253          * 8.012: DPT_Length_m
254          */
255         dptMainTypeMap.put(8, DecimalType.class);
256
257         /**
258          * MainType: 9
259          * 9.000: General float
260          * 9.001: DPT_Value_Temp values: -273...+670760 °C
261          * 9.002: DPT_Value_Tempd values: -670760...+670760 K
262          * 9.003: DPT_Value_Tempa values: -670760...+670760 K/h
263          * 9.004: DPT_Value_Lux values: 0...+670760 lx
264          * 9.005: DPT_Value_Wsp values: 0...+670760 m/s
265          * 9.006: DPT_Value_Pres values: 0...+670760 Pa
266          * 9.007: DPT_Value_Humidity values: 0...+670760 %
267          * 9.008: DPT_Value_AirQuality values: 0...+670760 ppm
268          * 9.010: DPT_Value_Time1 values: -670760...+670760 s
269          * 9.011: DPT_Value_Time2 values: -670760...+670760 ms
270          * 9.020: DPT_Value_Volt values: -670760...+670760 mV
271          * 9.021: DPT_Value_Curr values: -670760...+670760 mA
272          * 9.022: DPT_PowerDensity values: -670760...+670760 W/m²
273          * 9.023: DPT_KelvinPerPercent values: -670760...+670760 K/%
274          * 9.024: DPT_Power values: -670760...+670760 kW
275          * 9.025: DPT_Value_Volume_Flow values: -670760...+670760 l/h
276          * 9.026: DPT_Rain_Amount values: -671088.64...670760.96 l/m²
277          * 9.027: DPT_Value_Temp_F values: -459.6...670760.96 °F
278          * 9.028: DPT_Value_Wsp_kmh values: 0...670760.96 km/h
279          * 9.029: DPT_Value_Absolute_Humidity: 0...670760 g/m³
280          * 9.030: DPT_Concentration_μgm3: 0...670760 µg/m³
281          */
282         dptMainTypeMap.put(9, DecimalType.class);
283         /** Exceptions Datapoint Types "2-Octet Float Value", Main number 9 */
284         dptTypeMap.put(DPTXlator2ByteFloat.DPT_HUMIDITY.getID(), PercentType.class);
285
286         /**
287          * MainType: 10
288          * 10.001: DPT_TimeOfDay values: 1 = Monday...7 = Sunday, 0 = no-day, 00:00:00 Sun, 23:59:59 dow, hh:mm:ss
289          */
290         dptMainTypeMap.put(10, DateTimeType.class);
291         /** Exceptions Datapoint Types "Time", Main number 10 */
292         // Example: dptTypeMap.put(DPTXlatorTime.DPT_TIMEOFDAY.getID(), DateTimeType.class);
293
294         /**
295          * MainType: 11
296          * 11.001: DPT_Date values: 1990-01-01...2089-12-31, yyyy-mm-dd
297          */
298         dptMainTypeMap.put(11, DateTimeType.class);
299         /** Exceptions Datapoint Types “Date”", Main number 11 */
300         // Example: dptTypeMap.put(DPTXlatorDate.DPT_DATE.getID(), DateTimeType.class);
301
302         /**
303          * MainType: 12
304          * 12.000: General unsigned long
305          * 12.001: DPT_Value_4_Ucount values: 0...4294967295 counter pulses
306          * 12.100: DPT_LongTimePeriod_Sec values: 0...4294967295 s
307          * 12.101: DPT_LongTimePeriod_Min values: 0...4294967295 min
308          * 12.102: DPT_LongTimePeriod_Hrs values: 0...4294967295 h
309          * 12.1200: DPT_VolumeLiquid_Litre values: 0..4294967295 l
310          * 12.1201: DPT_Volume_m3 values: 0..4294967295 m3
311          */
312         dptMainTypeMap.put(12, DecimalType.class);
313         /** Exceptions Datapoint Types "4-Octet Unsigned Value", Main number 12 */
314         // Example: dptTypeMap.put(DPTXlator4ByteUnsigned.DPT_VALUE_4_UCOUNT.getID(), DecimalType.class);
315
316         /**
317          * MainType: 13
318          * 13.000: General long
319          * 13.001: DPT_Value_4_Count values: -2147483648...2147483647 counter pulses
320          * 13.002: DPT_FlowRate_m3h values: -2147483648...2147483647 m3/h
321          * 13.010: DPT_ActiveEnergy values: -2147483648...2147483647 Wh
322          * 13.011: DPT_ApparantEnergy values: -2147483648...2147483647 VAh
323          * 13.012: DPT_ReactiveEnergy values: -2147483648...2147483647 VARh
324          * 13.013: DPT_ActiveEnergy_kWh values: -2147483648...2147483647 kWh
325          * 13.014: DPT_ApparantEnergy_kVAh values: -2147483648...2147483647 kVAh
326          * 13.015: DPT_ReactiveEnergy_kVARh values: -2147483648...2147483647 kVAR
327          * 13.016: DPT_ActiveEnergy_MWh4 values: -2147483648...2147483647 MWh
328          * 13.100: DPT_LongDeltaTimeSec values: -2147483648...2147483647 s
329          * 13.1200: DPT_DeltaVolumeLiquid_Litre values: -2147483648...2147483647 l
330          * 13.1201: DPT_DeltaVolume_m3 values: -2147483648...2147483647 m³
331          */
332         dptMainTypeMap.put(13, DecimalType.class);
333         /** Exceptions Datapoint Types "4-Octet Signed Value", Main number 13 */
334         // Example: dptTypeMap.put(DPTXlator4ByteSigned.DPT_COUNT.getID(), DecimalType.class);
335
336         /**
337          * MainType: 14, Range: [-3.40282347e+38f...3.40282347e+38f]
338          * 14.000: Acceleration, values: ms⁻²
339          * 14.001: Acceleration, angular, values: rad s⁻²
340          * 14.002: Activation energy, values: J/mol
341          * 14.003: Activity, values: s⁻¹
342          * 14.004: Mol, values: mol
343          * 14.005: Amplitude, values:
344          * 14.006: Angle, values: rad
345          * 14.007: Angle, values: °
346          * 14.008: Momentum, values: Js
347          * 14.009: Angular velocity, values: rad/s
348          * 14.010: Area, values: m²
349          * 14.011: Capacitance, values: F
350          * 14.012: Charge density (surface), values: C m⁻²
351          * 14.013: Charge density (volume), values: C m⁻³
352          * 14.014: Compressibility, values: m²/N
353          * 14.015: Conductance, values: Ω⁻¹
354          * 14.016: Conductivity, electrical, values: Ω⁻¹m⁻¹
355          * 14.017: Density, values: kg m⁻³
356          * 14.018: Electric charge, values: C
357          * 14.019: Electric current, values: A
358          * 14.020: Electric current density, values: A m⁻²
359          * 14.021: Electric dipole moment, values: Cm
360          * 14.022: Electric displacement, values: C m⁻²
361          * 14.023: Electric field strength, values: V/m
362          * 14.024: Electric flux, values: Vm
363          * 14.025: Electric flux density, values: C m⁻²
364          * 14.026: Electric polarization, values: C m⁻²
365          * 14.027: Electric potential, values: V
366          * 14.028: Electric potential difference, values: V
367          * 14.029: Electromagnetic moment, values: A m²
368          * 14.030: Electromotive force, values: V
369          * 14.031: Energy, values: J
370          * 14.032: Force, values: N
371          * 14.033: Frequency, values: Hz
372          * 14.034: Frequency, angular, values: rad/s
373          * 14.035: Heat capacity, values: J/K
374          * 14.036: Heat flow rate, values: W
375          * 14.037: Heat quantity, values: J
376          * 14.038: Impedance, values: Ω
377          * 14.039: Length, values: m
378          * 14.040: Quantity of Light, values: J
379          * 14.041: Luminance, values: cd m⁻²
380          * 14.042: Luminous flux, values: lm
381          * 14.043: Luminous intensity, values: cd
382          * 14.044: Magnetic field strength, values: A/m
383          * 14.045: Magnetic flux, values: Wb
384          * 14.046: Magnetic flux density, values: T
385          * 14.047: Magnetic moment, values: A m²
386          * 14.048: Magnetic polarization, values: T
387          * 14.049: Magnetization, values: A/m
388          * 14.050: Magneto motive force, values: A
389          * 14.051: Mass, values: kg
390          * 14.052: Mass flux, values: kg/s
391          * 14.053: Momentum, values: N/s
392          * 14.054: Phase angle, radiant, values: rad
393          * 14.055: Phase angle, degree, values: °
394          * 14.056: Power, values: W
395          * 14.057: Power factor, values:
396          * 14.058: Pressure, values: Pa
397          * 14.059: Reactance, values: Ω
398          * 14.060: Resistance, values: Ω
399          * 14.061: Resistivity, values: Ωm
400          * 14.062: Self inductance, values: H
401          * 14.063: Solid angle, values: sr
402          * 14.064: Sound intensity, values: W m⁻²
403          * 14.065: Speed, values: m/s
404          * 14.066: Stress, values: Pa
405          * 14.067: Surface tension, values: N/m
406          * 14.068: Temperature in Celsius Degree, values: °C
407          * 14.069: Temperature, absolute, values: K
408          * 14.070: Temperature difference, values: K
409          * 14.071: Thermal capacity, values: J/K
410          * 14.072: Thermal conductivity, values: W/m K⁻¹
411          * 14.073: Thermoelectric power, values: V/K
412          * 14.074: Time, values: s
413          * 14.075: Torque, values: Nm
414          * 14.076: Volume, values: m³
415          * 14.077: Volume flux, values: m³/s
416          * 14.078: Weight, values: N
417          * 14.079: Work, values: J
418          * 14.080: apparent power: VA
419          */
420         dptMainTypeMap.put(14, DecimalType.class);
421         /** Exceptions Datapoint Types "4-Octet Float Value", Main number 14 */
422         // Example: dptTypeMap.put(DPTXlator4ByteFloat.DPT_ACCELERATION_ANGULAR.getID(), DecimalType.class);
423
424         /**
425          * MainType: 16
426          * 16.000: ASCII string
427          * 16.001: ISO-8859-1 string (Latin 1)
428          */
429         dptMainTypeMap.put(16, StringType.class);
430         /** Exceptions Datapoint Types "String", Main number 16 */
431         dptTypeMap.put(DPTXlatorString.DPT_STRING_8859_1.getID(), StringType.class);
432         dptTypeMap.put(DPTXlatorString.DPT_STRING_ASCII.getID(), StringType.class);
433
434         /**
435          * MainType: 17
436          * 17.001: Scene Number, values: 0...63
437          */
438         dptMainTypeMap.put(17, DecimalType.class);
439         /** Exceptions Datapoint Types "Scene Number", Main number 17 */
440         // Example: dptTypeMap.put(DPTXlatorSceneNumber.DPT_SCENE_NUMBER.getID(), DecimalType.class);
441
442         /**
443          * MainType: 18
444          * 18.001: Scene Control, values: 0...63, 0 = activate, 1 = learn
445          */
446         dptMainTypeMap.put(18, DecimalType.class);
447         /** Exceptions Datapoint Types "Scene Control", Main number 18 */
448         // Example: dptTypeMap.put(DPTXlatorSceneControl.DPT_SCENE_CONTROL.getID(), DecimalType.class);
449
450         /**
451          * MainType: 19
452          * 19.001: Date with time, values: 0 = 1900, 255 = 2155, 01/01 00:00:00, 12/31 24:00:00 yr/mth/day hr:min:sec
453          */
454         dptMainTypeMap.put(19, DateTimeType.class);
455         /** Exceptions Datapoint Types "DateTime", Main number 19 */
456         // Example: dptTypeMap.put(DPTXlatorDateTime.DPT_DATE_TIME.getID(), DateTimeType.class);
457
458         /**
459          * MainType: 20
460          * 20.001: System Clock Mode, enumeration [0..2]
461          * 20.002: Building Mode, enumeration [0..2]
462          * 20.003: Occupancy Mode, enumeration [0..2]
463          * 20.004: Priority, enumeration [0..3]
464          * 20.005: Light Application Mode, enumeration [0..2]
465          * 20.006: Application Area, enumeration [0..14]
466          * 20.007: Alarm Class Type, enumeration [0..3]
467          * 20.008: PSU Mode, enumeration [0..2]
468          * 20.011: Error Class System, enumeration [0..18]
469          * 20.012: Error Class HVAC, enumeration [0..4]
470          * 20.013: Time Delay, enumeration [0..25]
471          * 20.014: Beaufort Wind Force Scale, enumeration [0..12]
472          * 20.017: Sensor Select, enumeration [0..4]
473          * 20.020: Actuator Connect Type, enumeration [1..2]
474          * 20.100: Fuel Type, enumeration [0..3]
475          * 20.101: Burner Type, enumeration [0..3]
476          * 20.102: HVAC Mode, enumeration [0..4]
477          * 20.103: DHW Mode, enumeration [0..4]
478          * 20.104: Load Priority, enumeration [0..2]
479          * 20.105: HVAC Control Mode, enumeration [0..20]
480          * 20.106: HVAC Emergency Mode, enumeration [0..5]
481          * 20.107: Changeover Mode, enumeration [0..2]
482          * 20.108: Valve Mode, enumeration [1..5]
483          * 20.109: Damper Mode, enumeration [1..4]
484          * 20.110: Heater Mode, enumeration [1..3]
485          * 20.111: Fan Mode, enumeration [0..2]
486          * 20.112: Master/Slave Mode, enumeration [0..2]
487          * 20.113: Status Room Setpoint, enumeration [0..2]
488          * 20.114: Metering Device Type, enumeration [0..41/255]
489          * 20.120: Air Damper Actuator Type, enumeration [1..2]
490          * 20.121: Backup Mode, enumeration [0..1]
491          * 20.122: Start Synchronization, enumeration [0..2]
492          * 20.600: Behavior Lock/Unlock, enumeration [0..6]
493          * 20.601: Behavior Bus Power Up/Down, enumeration [0..4]
494          * 20.602: DALI Fade Time, enumeration [0..15]
495          * 20.603: Blinking Mode, enumeration [0..2]
496          * 20.604: Light Control Mode, enumeration [0..1]
497          * 20.605: Switch PB Model, enumeration [1..2]
498          * 20.606: PB Action, enumeration [0..3]
499          * 20.607: Dimm PB Model, enumeration [1..4]
500          * 20.608: Switch On Mode, enumeration [0..2]
501          * 20.609: Load Type Set, enumeration [0..2]
502          * 20.610: Load Type Detected, enumeration [0..3]
503          * 20.801: SAB Except Behavior, enumeration [0..4]
504          * 20.802: SAB Behavior Lock/Unlock, enumeration [0..6]
505          * 20.803: SSSB Mode, enumeration [1..4]
506          * 20.804: Blinds Control Mode, enumeration [0..1]
507          * 20.1000: Comm Mode, enumeration [0..255]
508          * 20.1001: Additional Info Type, enumeration [0..7]
509          * 20.1002: RF Mode Select, enumeration [0..2]
510          * 20.1003: RF Filter Select, enumeration [0..3]
511          * 20.1200: M-Bus Breaker/Valve State, enumeration [0..255]
512          * 20.1202: Gas Measurement Condition, enumeration [0..3]
513          *
514          */
515         dptMainTypeMap.put(20, StringType.class);
516         /** Exceptions Datapoint Types, Main number 20 */
517         // Example since calimero 2.4: dptTypeMap.put(DPTXlator8BitEnum.DptSystemClockMode.getID(), StringType.class);
518
519         /**
520          * MainType: 21
521          * 21.001: General Status, values: 0...31
522          * 21.002: Device Control, values: 0...7
523          * 21.100: Forcing Signal, values: 0...255
524          * 21.101: Forcing Signal Cool, values: 0...1
525          * 21.102: Room Heating Controller Status, values: 0...255
526          * 21.103: Solar Dhw Controller Status, values: 0...7
527          * 21.104: Fuel Type Set, values: 0...7
528          * 21.105: Room Cooling Controller Status, values: 0...1
529          * 21.106: Ventilation Controller Status, values: 0...15
530          * 21.601: Light Actuator Error Info, values: 0...127
531          * 21.1000: R F Comm Mode Info, values: 0...7
532          * 21.1001: R F Filter Modes, values: 0...7
533          * 21.1010: Channel Activation State, values: 0...255
534          */
535         dptMainTypeMap.put(21, StringType.class);
536         /** Exceptions Datapoint Types, Main number 21 */
537         // Example since calimero 2.4: dptTypeMap.put(DptXlator8BitSet.DptGeneralStatus.getID(), StringType.class);
538
539         /**
540          * MainType: 28
541          * 28.001: UTF-8
542          */
543         dptMainTypeMap.put(28, StringType.class);
544         /** Exceptions Datapoint Types "String" UTF-8, Main number 28 */
545         // Example: dptTypeMap.put(DPTXlatorUtf8.DPT_UTF8.getID(), StringType.class);
546
547         /**
548          * MainType: 29
549          * 29.010: Active Energy, values: -9223372036854775808...9223372036854775807 Wh
550          * 29.011: Apparent energy, values: -9223372036854775808...9223372036854775807 VAh
551          * 29.012: Reactive energy, values: -9223372036854775808...9223372036854775807 VARh
552          */
553         dptMainTypeMap.put(29, DecimalType.class);
554         /** Exceptions Datapoint Types "64-Bit Signed Value", Main number 29 */
555         // Example: dptTypeMap.put(DPTXlator64BitSigned.DPT_ACTIVE_ENERGY.getID(), DecimalType.class);
556
557         /**
558          * MainType: 229
559          * 229.001: Metering Value, values: -2147483648...2147483647
560          */
561         dptMainTypeMap.put(229, DecimalType.class);
562         /** Exceptions Datapoint Types "4-Octet Signed Value", Main number 229 */
563         // Example: dptTypeMap.put(DptXlatorMeteringValue.DptMeteringValue.getID(), DecimalType.class);
564
565         /**
566          * MainType: 232, 3 bytes
567          * 232.600: DPT_Colour_RGB, values: 0 0 0...255 255 255, r g b
568          */
569         dptMainTypeMap.put(232, HSBType.class);
570         /** Exceptions Datapoint Types "RGB Color", Main number 232 */
571         // Example: dptTypeMap.put(DPTXlatorRGB.DPT_RGB.getID(), HSBType.class);
572
573         defaultDptMap = new HashMap<>();
574         defaultDptMap.put(OnOffType.class, DPTXlatorBoolean.DPT_SWITCH.getID());
575         defaultDptMap.put(UpDownType.class, DPTXlatorBoolean.DPT_UPDOWN.getID());
576         defaultDptMap.put(StopMoveType.class, DPTXlatorBoolean.DPT_START.getID());
577         defaultDptMap.put(OpenClosedType.class, DPTXlatorBoolean.DPT_WINDOW_DOOR.getID());
578         defaultDptMap.put(IncreaseDecreaseType.class, DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID());
579         defaultDptMap.put(PercentType.class, DPTXlator8BitUnsigned.DPT_SCALING.getID());
580         defaultDptMap.put(DecimalType.class, DPTXlator2ByteFloat.DPT_TEMPERATURE.getID());
581         defaultDptMap.put(DateTimeType.class, DPTXlatorTime.DPT_TIMEOFDAY.getID());
582         defaultDptMap.put(StringType.class, DPTXlatorString.DPT_STRING_8859_1.getID());
583         defaultDptMap.put(HSBType.class, DPTXlatorRGB.DPT_RGB.getID());
584     }
585
586     /*
587      * This function computes the target unit for type conversion from OH quantity type to DPT types.
588      * Calimero library provides units which can be used for most of the DPTs. There are some deviations
589      * from the OH unit scheme which are handled.
590      */
591     private String quantityTypeToDPTValue(QuantityType<?> qt, int mainNumber, int subNumber, String dpUnit)
592             throws KNXException {
593         String targetOhUnit = dpUnit;
594         double scaleFactor = 1.0;
595         switch (mainNumber) {
596             case 7:
597                 switch (subNumber) {
598                     case 3:
599                     case 4:
600                         targetOhUnit = "ms";
601                         break;
602                 }
603                 break;
604             case 9:
605                 switch (subNumber) {
606                     // special case: temperature deltas specified in different units
607                     // ignore the offset, but run a conversion to handle prefixes like mK
608                     // scaleFactor is needed to properly handle °F
609                     case 2: {
610                         final String unit = qt.getUnit().toString();
611                         // find out if the unit is based on °C or K, getSystemUnit() does not help here as it always
612                         // gives "K"
613                         if (unit.contains("°C")) {
614                             targetOhUnit = "°C";
615                         } else if (unit.contains("°F")) {
616                             targetOhUnit = "°F";
617                             scaleFactor = 5.0 / 9.0;
618                         } else if (unit.contains("K")) {
619                             targetOhUnit = "K";
620                         } else {
621                             targetOhUnit = "";
622                         }
623                         break;
624                     }
625                     case 3: {
626                         final String unit = qt.getUnit().toString();
627                         if (unit.contains("°C")) {
628                             targetOhUnit = "°C/h";
629                         } else if (unit.contains("°F")) {
630                             targetOhUnit = "°F/h";
631                             scaleFactor = 5.0 / 9.0;
632                         } else if (unit.contains("K")) {
633                             targetOhUnit = "K/h";
634                         } else {
635                             targetOhUnit = "";
636                         }
637                         break;
638                     }
639                     case 23: {
640                         final String unit = qt.getUnit().toString();
641                         if (unit.contains("°C")) {
642                             targetOhUnit = "°C/%";
643                         } else if (unit.contains("°F")) {
644                             targetOhUnit = "°F/%";
645                             scaleFactor = 5.0 / 9.0;
646                         } else if (unit.contains("K")) {
647                             targetOhUnit = "K/%";
648                         } else {
649                             targetOhUnit = "";
650                         }
651                         break;
652                     }
653                 }
654                 break;
655             case 12:
656                 switch (subNumber) {
657                     case 1200:
658                         // Calimero uses "litre"
659                         targetOhUnit = "l";
660                         break;
661                 }
662                 break;
663             case 13:
664                 switch (subNumber) {
665                     case 12:
666                     case 15:
667                         // Calimero uses VARh, OH uses varh
668                         targetOhUnit = targetOhUnit.replace("VARh", "varh");
669                         break;
670                     case 14:
671                         // OH does not accept kVAh, only VAh
672                         targetOhUnit = targetOhUnit.replace("kVAh", "VAh");
673                         scaleFactor = 1.0 / 1000.0;
674                         break;
675                 }
676                 break;
677
678             case 14:
679                 targetOhUnit = targetOhUnit.replace("Ω\u207B¹", "S");
680                 // Calimero uses a special unicode character to specify units like m*s^-2
681                 // this needs to be rewritten to m/s²
682                 final int posMinus = targetOhUnit.indexOf("\u207B");
683                 if (posMinus > 0) {
684                     targetOhUnit = targetOhUnit.substring(0, posMinus - 1) + "/" + targetOhUnit.charAt(posMinus - 1)
685                             + targetOhUnit.substring(posMinus + 1);
686                 }
687                 switch (subNumber) {
688                     case 8:
689                         // OH does not support unut Js, need to expand
690                         targetOhUnit = "J*s";
691                         break;
692                     case 21:
693                         targetOhUnit = "C*m";
694                         break;
695                     case 24:
696                         targetOhUnit = "C";
697                         break;
698                     case 29:
699                     case 47:
700                         targetOhUnit = "A*m²";
701                         break;
702                     case 40:
703                         if (qt.getUnit().toString().contains("J")) {
704                             targetOhUnit = "J";
705                         } else {
706                             targetOhUnit = "lm*s";
707                         }
708                         break;
709                     case 61:
710                         targetOhUnit = "Ohm*m";
711                         break;
712                     case 75:
713                         targetOhUnit = "N*m";
714                         break;
715                 }
716                 break;
717             case 29:
718                 switch (subNumber) {
719                     case 12:
720                         // Calimero uses VARh, OH uses varh
721                         targetOhUnit = targetOhUnit.replace("VARh", "varh");
722                         break;
723                 }
724                 break;
725         }
726         // replace e.g. m3 by m³
727         targetOhUnit = targetOhUnit.replace("3", "³").replace("2", "²");
728
729         final QuantityType<?> result = qt.toUnit(targetOhUnit);
730         if (result == null) {
731             throw new KNXException("incompatible types: " + qt.getUnit().toString() + ", " + targetOhUnit);
732         }
733         return String.valueOf(result.doubleValue() * scaleFactor);
734     }
735
736     @Override
737     public String toDPTValue(Type type, String dptID) {
738         DPT dpt;
739         int mainNumber = getMainNumber(dptID);
740         if (mainNumber == -1) {
741             logger.error("toDPTValue couldn't identify mainnumber in dptID: {}", dptID);
742             return null;
743         }
744         int subNumber = getSubNumber(dptID);
745         if (subNumber == -1) {
746             logger.debug("toType: couldn't identify sub number in dptID: {}.", dptID);
747             return null;
748         }
749
750         try {
751             DPTXlator translator = TranslatorTypes.createTranslator(mainNumber, dptID);
752             dpt = translator.getType();
753         } catch (KNXException e) {
754             return null;
755         }
756
757         try {
758             // check for HSBType first, because it extends PercentType as well
759             if (type instanceof HSBType) {
760                 switch (mainNumber) {
761                     case 5:
762                         switch (subNumber) {
763                             case 3: // * 5.003: Angle, values: 0...360 °
764                                 return ((HSBType) type).getHue().toString();
765                             case 1: // * 5.001: Scaling, values: 0...100 %
766                             default:
767                                 return ((HSBType) type).getBrightness().toString();
768                         }
769                     case 232:
770                         switch (subNumber) {
771                             case 600: // 232.600
772                                 HSBType hc = ((HSBType) type);
773                                 return "r:" + convertPercentToByte(hc.getRed()) + " g:"
774                                         + convertPercentToByte(hc.getGreen()) + " b:"
775                                         + convertPercentToByte(hc.getBlue());
776                         }
777                     default:
778                         HSBType hc = ((HSBType) type);
779                         return "r:" + hc.getRed().intValue() + " g:" + hc.getGreen().intValue() + " b:"
780                                 + hc.getBlue().intValue();
781                 }
782             } else if (type instanceof OnOffType) {
783                 return type.equals(OnOffType.OFF) ? dpt.getLowerValue() : dpt.getUpperValue();
784             } else if (type instanceof UpDownType) {
785                 return type.equals(UpDownType.UP) ? dpt.getLowerValue() : dpt.getUpperValue();
786             } else if (type instanceof IncreaseDecreaseType) {
787                 DPT valueDPT = ((DPTXlator3BitControlled.DPT3BitControlled) dpt).getControlDPT();
788                 return type.equals(IncreaseDecreaseType.DECREASE) ? valueDPT.getLowerValue() + " 5"
789                         : valueDPT.getUpperValue() + " 5";
790             } else if (type instanceof OpenClosedType) {
791                 return type.equals(OpenClosedType.CLOSED) ? dpt.getLowerValue() : dpt.getUpperValue();
792             } else if (type instanceof StopMoveType) {
793                 return type.equals(StopMoveType.STOP) ? dpt.getLowerValue() : dpt.getUpperValue();
794             } else if (type instanceof PercentType) {
795                 return String.valueOf(((DecimalType) type).intValue());
796             } else if (type instanceof DecimalType) {
797                 switch (mainNumber) {
798                     case 2:
799                         DPT valueDPT = ((DPTXlator1BitControlled.DPT1BitControlled) dpt).getValueDPT();
800                         switch (((DecimalType) type).intValue()) {
801                             case 0:
802                                 return "0 " + valueDPT.getLowerValue();
803                             case 1:
804                                 return "0 " + valueDPT.getUpperValue();
805                             case 2:
806                                 return "1 " + valueDPT.getLowerValue();
807                             default:
808                                 return "1 " + valueDPT.getUpperValue();
809                         }
810                     case 18:
811                         int intVal = ((DecimalType) type).intValue();
812                         if (intVal > 63) {
813                             return "learn " + (intVal - 0x80);
814                         } else {
815                             return "activate " + intVal;
816                         }
817                     default:
818                         return ((DecimalType) type).toBigDecimal().stripTrailingZeros().toPlainString();
819                 }
820             } else if (type instanceof StringType) {
821                 return type.toString();
822             } else if (type instanceof DateTimeType) {
823                 return formatDateTime((DateTimeType) type, dptID);
824             } else if (type instanceof QuantityType) {
825                 final QuantityType<?> qt = (QuantityType<?>) type;
826                 return quantityTypeToDPTValue(qt, mainNumber, subNumber, dpt.getUnit());
827             }
828         } catch (Exception e) {
829             logger.warn("An exception occurred converting type {} to dpt id {}: error message={}", type, dptID,
830                     e.getMessage());
831             return null;
832         }
833
834         logger.debug("toDPTValue: Couldn't convert type {} to dpt id {} (no mapping).", type, dptID);
835
836         return null;
837     }
838
839     @Override
840     public Type toType(Datapoint datapoint, byte[] data) {
841         try {
842             DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
843             translator.setData(data);
844             String value = translator.getValue();
845
846             String id = translator.getType().getID();
847             logger.trace("toType datapoint DPT = {}", datapoint.getDPT());
848
849             int mainNumber = getMainNumber(id);
850             if (mainNumber == -1) {
851                 logger.debug("toType: couldn't identify mainnumber in dptID: {}.", id);
852                 return null;
853             }
854             int subNumber = getSubNumber(id);
855             if (subNumber == -1) {
856                 logger.debug("toType: couldn't identify sub number in dptID: {}.", id);
857                 return null;
858             }
859             /*
860              * Following code section deals with specific mapping of values from KNX to openHAB types were the String
861              * received from the DPTXlator is not sufficient to set the openHAB type or has bugs
862              */
863             switch (mainNumber) {
864                 case 1:
865                     DPTXlatorBoolean translatorBoolean = (DPTXlatorBoolean) translator;
866                     switch (subNumber) {
867                         case 8:
868                             return translatorBoolean.getValueBoolean() ? UpDownType.DOWN : UpDownType.UP;
869                         case 9:
870                             return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
871                         case 10:
872                             return translatorBoolean.getValueBoolean() ? StopMoveType.MOVE : StopMoveType.STOP;
873                         case 19:
874                             return translatorBoolean.getValueBoolean() ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
875                         case 22:
876                             return DecimalType.valueOf(translatorBoolean.getValueBoolean() ? "1" : "0");
877                         default:
878                             return translatorBoolean.getValueBoolean() ? OnOffType.ON : OnOffType.OFF;
879                     }
880                 case 2:
881                     DPTXlator1BitControlled translator1BitControlled = (DPTXlator1BitControlled) translator;
882                     int decValue = (translator1BitControlled.getControlBit() ? 2 : 0)
883                             + (translator1BitControlled.getValueBit() ? 1 : 0);
884                     return new DecimalType(decValue);
885                 case 3:
886                     DPTXlator3BitControlled translator3BitControlled = (DPTXlator3BitControlled) translator;
887                     if (translator3BitControlled.getStepCode() == 0) {
888                         logger.debug("toType: KNX DPT_Control_Dimming: break received.");
889                         return UnDefType.UNDEF;
890                     }
891                     switch (subNumber) {
892                         case 7:
893                             return translator3BitControlled.getControlBit() ? IncreaseDecreaseType.INCREASE
894                                     : IncreaseDecreaseType.DECREASE;
895                         case 8:
896                             return translator3BitControlled.getControlBit() ? UpDownType.DOWN : UpDownType.UP;
897                     }
898                 case 14:
899                     /*
900                      * FIXME: Workaround for a bug in Calimero / Openhab DPTXlator4ByteFloat.makeString(): is using a
901                      * locale when
902                      * translating a Float to String. It could happen the a ',' is used as separator, such as
903                      * 3,14159E20.
904                      * Openhab's DecimalType expects this to be in US format and expects '.': 3.14159E20.
905                      * There is no issue with DPTXlator2ByteFloat since calimero is using a non-localized translation
906                      * there.
907                      */
908                     DPTXlator4ByteFloat translator4ByteFloat = (DPTXlator4ByteFloat) translator;
909                     Float f = translator4ByteFloat.getValueFloat();
910                     if (Math.abs(f) < 100000) {
911                         value = String.valueOf(f);
912                     } else {
913                         NumberFormat dcf = NumberFormat.getInstance(Locale.US);
914                         if (dcf instanceof DecimalFormat) {
915                             ((DecimalFormat) dcf).applyPattern("0.#####E0");
916                         }
917                         value = dcf.format(f);
918                     }
919                     break;
920                 case 18:
921                     DPTXlatorSceneControl translatorSceneControl = (DPTXlatorSceneControl) translator;
922                     int decimalValue = translatorSceneControl.getSceneNumber();
923                     if (value.startsWith("learn")) {
924                         decimalValue += 0x80;
925                     }
926                     value = String.valueOf(decimalValue);
927
928                     break;
929                 case 19:
930                     DPTXlatorDateTime translatorDateTime = (DPTXlatorDateTime) translator;
931                     if (translatorDateTime.isFaultyClock()) {
932                         // Not supported: faulty clock
933                         logger.debug("toType: KNX clock msg ignored: clock faulty bit set, which is not supported");
934                         return null;
935                     } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
936                             && translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
937                         // Not supported: "/1/1" (month and day without year)
938                         logger.debug(
939                                 "toType: KNX clock msg ignored: no year, but day and month, which is not supported");
940                         return null;
941                     } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
942                             && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)) {
943                         // Not supported: "1900" (year without month and day)
944                         logger.debug(
945                                 "toType: KNX clock msg ignored: no day and month, but year, which is not supported");
946                         return null;
947                     } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
948                             && !translatorDateTime.isValidField(DPTXlatorDateTime.DATE)
949                             && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
950                         // Not supported: No year, no date and no time
951                         logger.debug("toType: KNX clock msg ignored: no day and month or year, which is not supported");
952                         return null;
953                     }
954
955                     Calendar cal = Calendar.getInstance();
956                     if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
957                             && !translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
958                         // Pure date format, no time information
959                         cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
960                         value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
961                         return DateTimeType.valueOf(value);
962                     } else if (!translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
963                             && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
964                         // Pure time format, no date information
965                         cal.clear();
966                         cal.set(Calendar.HOUR_OF_DAY, translatorDateTime.getHour());
967                         cal.set(Calendar.MINUTE, translatorDateTime.getMinute());
968                         cal.set(Calendar.SECOND, translatorDateTime.getSecond());
969                         value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
970                         return DateTimeType.valueOf(value);
971                     } else if (translatorDateTime.isValidField(DPTXlatorDateTime.YEAR)
972                             && translatorDateTime.isValidField(DPTXlatorDateTime.TIME)) {
973                         // Date format and time information
974                         cal.setTimeInMillis(translatorDateTime.getValueMilliseconds());
975                         value = new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(cal.getTime());
976                         return DateTimeType.valueOf(value);
977                     }
978                     break;
979             }
980
981             Class<? extends Type> typeClass = toTypeClass(id);
982             if (typeClass == null) {
983                 return null;
984             }
985
986             if (typeClass.equals(PercentType.class)) {
987                 return new PercentType(BigDecimal.valueOf(Math.round(translator.getNumericValue())));
988             }
989             if (typeClass.equals(DecimalType.class)) {
990                 return new DecimalType(translator.getNumericValue());
991             }
992             if (typeClass.equals(StringType.class)) {
993                 return StringType.valueOf(value);
994             }
995
996             if (typeClass.equals(DateTimeType.class)) {
997                 String date = formatDateTime(value, datapoint.getDPT());
998                 if ((date == null) || (date.isEmpty())) {
999                     logger.debug("toType: KNX clock msg ignored: date object null or empty {}.", date);
1000                     return null;
1001                 } else {
1002                     return DateTimeType.valueOf(date);
1003                 }
1004             }
1005
1006             if (typeClass.equals(HSBType.class)) {
1007                 // value has format of "r:<red value> g:<green value> b:<blue value>"
1008                 int r = Integer.parseInt(value.split(" ")[0].split(":")[1]);
1009                 int g = Integer.parseInt(value.split(" ")[1].split(":")[1]);
1010                 int b = Integer.parseInt(value.split(" ")[2].split(":")[1]);
1011
1012                 return HSBType.fromRGB(r, g, b);
1013             }
1014
1015         } catch (KNXFormatException kfe) {
1016             logger.info("Translator couldn't parse data for datapoint type '{}' (KNXFormatException).",
1017                     datapoint.getDPT());
1018         } catch (KNXIllegalArgumentException kiae) {
1019             logger.info("Translator couldn't parse data for datapoint type '{}' (KNXIllegalArgumentException).",
1020                     datapoint.getDPT());
1021         } catch (KNXException e) {
1022             logger.warn("Failed creating a translator for datapoint type '{}'.", datapoint.getDPT(), e);
1023         }
1024
1025         return null;
1026     }
1027
1028     /**
1029      * Converts a datapoint type id into an openHAB type class
1030      *
1031      * @param dptId the datapoint type id
1032      * @return the openHAB type (command or state) class or {@code null} if the datapoint type id is not supported.
1033      */
1034     @Override
1035     public Class<? extends Type> toTypeClass(String dptId) {
1036         Class<? extends Type> ohClass = dptTypeMap.get(dptId);
1037         if (ohClass == null) {
1038             int mainNumber = getMainNumber(dptId);
1039             if (mainNumber == -1) {
1040                 logger.debug("Couldn't convert KNX datapoint type id into openHAB type class for dptId: {}.", dptId);
1041                 return null;
1042             }
1043             ohClass = dptMainTypeMap.get(mainNumber);
1044         }
1045         return ohClass;
1046     }
1047
1048     /**
1049      * Converts an openHAB type class into a datapoint type id.
1050      *
1051      * @param typeClass the openHAB type class
1052      * @return the datapoint type id
1053      */
1054     public String toDPTid(Class<? extends Type> typeClass) {
1055         return defaultDptMap.get(typeClass);
1056     }
1057
1058     /**
1059      * Formats the given <code>value</code> according to the datapoint type
1060      * <code>dpt</code> to a String which can be processed by {@link DateTimeType}.
1061      *
1062      * @param value
1063      * @param dpt
1064      *
1065      * @return a formatted String like </code>yyyy-MM-dd'T'HH:mm:ss</code> which
1066      *         is target format of the {@link DateTimeType}
1067      */
1068     private String formatDateTime(String value, String dpt) {
1069         Date date = null;
1070
1071         try {
1072             if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
1073                 date = new SimpleDateFormat(DATE_FORMAT).parse(value);
1074             } else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
1075                 if (value.contains("no-day")) {
1076                     /*
1077                      * KNX "no-day" needs special treatment since openHAB's DateTimeType doesn't support "no-day".
1078                      * Workaround: remove the "no-day" String, parse the remaining time string, which will result in a
1079                      * date of "1970-01-01".
1080                      * Replace "no-day" with the current day name
1081                      */
1082                     StringBuffer stb = new StringBuffer(value);
1083                     int start = stb.indexOf("no-day");
1084                     int end = start + "no-day".length();
1085                     stb.replace(start, end, String.format(Locale.US, "%1$ta", Calendar.getInstance()));
1086                     value = stb.toString();
1087                 }
1088                 date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
1089             }
1090         } catch (ParseException pe) {
1091             // do nothing but logging
1092             logger.warn("Could not parse '{}' to a valid date", value);
1093         }
1094
1095         return date != null ? new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date) : "";
1096     }
1097
1098     /**
1099      * Formats the given internal <code>dateType</code> to a knx readable String
1100      * according to the target datapoint type <code>dpt</code>.
1101      *
1102      * @param dateType
1103      * @param dpt the target datapoint type
1104      *
1105      * @return a String which contains either an ISO8601 formatted date (yyyy-mm-dd),
1106      *         a formatted 24-hour clock with the day of week prepended (Mon, 12:00:00) or
1107      *         a formatted 24-hour clock (12:00:00)
1108      *
1109      * @throws IllegalArgumentException if none of the datapoint types DPT_DATE or
1110      *             DPT_TIMEOFDAY has been used.
1111      */
1112     private static String formatDateTime(DateTimeType dateType, String dpt) {
1113         if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
1114             return dateType.format("%tF");
1115         } else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
1116             return dateType.format(Locale.US, "%1$ta, %1$tT");
1117         } else if (DPTXlatorDateTime.DPT_DATE_TIME.getID().equals(dpt)) {
1118             return dateType.format(Locale.US, "%tF %1$tT");
1119         } else {
1120             throw new IllegalArgumentException("Could not format date to datapoint type '" + dpt + "'");
1121         }
1122     }
1123
1124     /**
1125      * Retrieves sub number from a DTP ID such as "14.001"
1126      *
1127      * @param dptID String with DPT ID
1128      * @return sub number or -1
1129      */
1130     private int getSubNumber(String dptID) {
1131         int result = -1;
1132         if (dptID == null) {
1133             throw new IllegalArgumentException("Parameter dptID cannot be null");
1134         }
1135
1136         int dptSepratorPosition = dptID.indexOf('.');
1137         if (dptSepratorPosition > 0) {
1138             try {
1139                 result = Integer.parseInt(dptID.substring(dptSepratorPosition + 1, dptID.length()));
1140             } catch (NumberFormatException nfe) {
1141                 logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
1142                         dptID);
1143             } catch (IndexOutOfBoundsException ioobe) {
1144                 logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
1145                         dptID);
1146             }
1147         }
1148         return result;
1149     }
1150
1151     /**
1152      * Retrieves main number from a DTP ID such as "14.001"
1153      *
1154      * @param dptID String with DPT ID
1155      * @return main number or -1
1156      */
1157     private int getMainNumber(String dptID) {
1158         int result = -1;
1159         if (dptID == null) {
1160             throw new IllegalArgumentException("Parameter dptID cannot be null");
1161         }
1162
1163         int dptSepratorPosition = dptID.indexOf('.');
1164         if (dptSepratorPosition > 0) {
1165             try {
1166                 result = Integer.parseInt(dptID.substring(0, dptSepratorPosition));
1167             } catch (NumberFormatException nfe) {
1168                 logger.error("toType couldn't identify main and/or sub number in dptID (NumberFormatException): {}",
1169                         dptID);
1170             } catch (IndexOutOfBoundsException ioobe) {
1171                 logger.error("toType couldn't identify main and/or sub number in dptID (IndexOutOfBoundsException): {}",
1172                         dptID);
1173             }
1174         }
1175         return result;
1176     }
1177
1178     /**
1179      * convert 0...100% to 1 byte 0..255
1180      *
1181      * @param percent
1182      * @return int 0..255
1183      */
1184     private int convertPercentToByte(PercentType percent) {
1185         return percent.toBigDecimal().multiply(BigDecimal.valueOf(255))
1186                 .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).intValue();
1187     }
1188 }