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