]> git.basschouten.com Git - openhab-addons.git/blob
e3bbf466351d685cf34024007eb641b833e72951
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.bluetooth;
14
15 import java.nio.charset.StandardCharsets;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.UUID;
21
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * The {@link BluetoothCharacteristic} class defines the Bluetooth characteristic.
27  * <p>
28  * Characteristics are defined attribute types that contain a single logical value.
29  * <p>
30  * https://www.bluetooth.com/specifications/gatt/characteristics
31  *
32  * @author Chris Jackson - Initial contribution
33  * @author Kai Kreuzer - Cleaned up code
34  */
35 public class BluetoothCharacteristic {
36     public static final int FORMAT_UINT8 = 0x11;
37     public static final int FORMAT_UINT16 = 0x12;
38     public static final int FORMAT_UINT32 = 0x14;
39     public static final int FORMAT_SINT8 = 0x21;
40     public static final int FORMAT_SINT16 = 0x22;
41     public static final int FORMAT_SINT32 = 0x24;
42     public static final int FORMAT_SFLOAT = 0x32;
43     public static final int FORMAT_FLOAT = 0x34;
44
45     public static final int PROPERTY_BROADCAST = 0x01;
46     public static final int PROPERTY_READ = 0x02;
47     public static final int PROPERTY_WRITE_NO_RESPONSE = 0x04;
48     public static final int PROPERTY_WRITE = 0x08;
49     public static final int PROPERTY_NOTIFY = 0x10;
50     public static final int PROPERTY_INDICATE = 0x20;
51     public static final int PROPERTY_SIGNED_WRITE = 0x40;
52     public static final int PROPERTY_EXTENDED_PROPS = 0x80;
53
54     public static final int PERMISSION_READ = 0x01;
55     public static final int PERMISSION_READ_ENCRYPTED = 0x02;
56     public static final int PERMISSION_READ_ENCRYPTED_MITM = 0x04;
57     public static final int PERMISSION_WRITE = 0x10;
58     public static final int PERMISSION_WRITE_ENCRYPTED = 0x20;
59     public static final int PERMISSION_WRITE_ENCRYPTED_MITM = 0x40;
60     public static final int PERMISSION_WRITE_SIGNED = 0x80;
61     public static final int PERMISSION_WRITE_SIGNED_MITM = 0x100;
62
63     public static final int WRITE_TYPE_DEFAULT = 0x02;
64     public static final int WRITE_TYPE_NO_RESPONSE = 0x01;
65     public static final int WRITE_TYPE_SIGNED = 0x04;
66
67     private final Logger logger = LoggerFactory.getLogger(BluetoothCharacteristic.class);
68
69     /**
70      * The {@link UUID} for this characteristic
71      */
72     protected UUID uuid;
73
74     /**
75      * The handle for this characteristic
76      */
77     protected int handle;
78
79     /**
80      * A map of {@link BluetoothDescriptor}s applicable to this characteristic
81      */
82     protected Map<UUID, BluetoothDescriptor> gattDescriptors = new HashMap<>();
83     protected int instance;
84     protected int properties;
85     protected int permissions;
86     protected int writeType;
87
88     /**
89      * The raw data value for this characteristic
90      */
91     protected int[] value = new int[0];
92
93     /**
94      * The {@link BluetoothService} to which this characteristic belongs
95      */
96     protected BluetoothService service;
97
98     /**
99      * Create a new BluetoothCharacteristic.
100      *
101      * @param uuid the {@link UUID} of the new characteristic
102      * @param handle
103      */
104     public BluetoothCharacteristic(UUID uuid, int handle) {
105         this.uuid = uuid;
106         this.handle = handle;
107     }
108
109     /**
110      * Adds a descriptor to this characteristic.
111      *
112      * @param descriptor {@link BluetoothDescriptor} to be added to this characteristic.
113      * @return true, if the descriptor was added to the characteristic
114      */
115     public boolean addDescriptor(BluetoothDescriptor descriptor) {
116         if (gattDescriptors.get(descriptor.getUuid()) != null) {
117             return false;
118         }
119
120         gattDescriptors.put(descriptor.getUuid(), descriptor);
121         return true;
122     }
123
124     /**
125      * Returns the {@link UUID} of this characteristic
126      *
127      * @return UUID of this characteristic
128      */
129     public UUID getUuid() {
130         return uuid;
131     }
132
133     /**
134      * Returns the instance ID for this characteristic.
135      *
136      * If a remote device offers multiple characteristics with the same UUID, the instance ID is used to distinguish
137      * between characteristics.
138      *
139      * @return Instance ID of this characteristic
140      */
141     public int getInstanceId() {
142         return instance;
143     }
144
145     /**
146      * Returns the properties of this characteristic.
147      *
148      * The properties contain a bit mask of property flags indicating the features of this characteristic.
149      *
150      */
151     public int getProperties() {
152         return properties;
153     }
154
155     /**
156      * Returns the permissions for this characteristic.
157      */
158     public int getPermissions() {
159         return permissions;
160     }
161
162     /**
163      * Gets the write type for this characteristic.
164      *
165      */
166     public int getWriteType() {
167         return writeType;
168     }
169
170     /**
171      * Set the write type for this characteristic
172      *
173      * @param writeType
174      */
175     public void setWriteType(int writeType) {
176         this.writeType = writeType;
177     }
178
179     /**
180      * Get the service to which this characteristic belongs
181      *
182      * @return the {@link BluetoothService}
183      */
184     public BluetoothService getService() {
185         return service;
186     }
187
188     /**
189      * Returns the handle for this characteristic
190      *
191      * @return the handle for the characteristic
192      */
193     public int getHandle() {
194         return handle;
195     }
196
197     /**
198      * Get the service to which this characteristic belongs
199      *
200      * @return the {@link BluetoothService}
201      */
202     public void setService(BluetoothService service) {
203         this.service = service;
204     }
205
206     /**
207      * Returns a list of descriptors for this characteristic.
208      *
209      */
210     public List<BluetoothDescriptor> getDescriptors() {
211         return new ArrayList<>(gattDescriptors.values());
212     }
213
214     /**
215      * Returns a descriptor with a given UUID out of the list of
216      * descriptors for this characteristic.
217      *
218      * @return the {@link BluetoothDescriptor}
219      */
220     public BluetoothDescriptor getDescriptor(UUID uuid) {
221         return gattDescriptors.get(uuid);
222     }
223
224     /**
225      * Get the stored value for this characteristic.
226      *
227      */
228     public int[] getValue() {
229         return value;
230     }
231
232     /**
233      * Get the stored value for this characteristic.
234      *
235      */
236     public byte[] getByteValue() {
237         byte[] byteValue = new byte[value.length];
238         for (int cnt = 0; cnt < value.length; cnt++) {
239             byteValue[cnt] = (byte) (value[cnt] & 0xFF);
240         }
241         return byteValue;
242     }
243
244     /**
245      * Return the stored value of this characteristic.
246      *
247      */
248     public Integer getIntValue(int formatType, int offset) {
249         if ((offset + getTypeLen(formatType)) > value.length) {
250             return null;
251         }
252
253         switch (formatType) {
254             case FORMAT_UINT8:
255                 return unsignedByteToInt(value[offset]);
256
257             case FORMAT_UINT16:
258                 return unsignedBytesToInt(value[offset], value[offset + 1]);
259
260             case FORMAT_UINT32:
261                 return unsignedBytesToInt(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]);
262
263             case FORMAT_SINT8:
264                 return unsignedToSigned(unsignedByteToInt(value[offset]), 8);
265
266             case FORMAT_SINT16:
267                 return unsignedToSigned(unsignedBytesToInt(value[offset], value[offset + 1]), 16);
268
269             case FORMAT_SINT32:
270                 return unsignedToSigned(
271                         unsignedBytesToInt(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]), 32);
272             default:
273                 logger.error("Unknown format type {} - no int value can be provided for it.", formatType);
274         }
275
276         return null;
277     }
278
279     /**
280      * Return the stored value of this characteristic. This doesn't read the remote data.
281      *
282      */
283     public Float getFloatValue(int formatType, int offset) {
284         if ((offset + getTypeLen(formatType)) > value.length) {
285             return null;
286         }
287
288         switch (formatType) {
289             case FORMAT_SFLOAT:
290                 return bytesToFloat(value[offset], value[offset + 1]);
291             case FORMAT_FLOAT:
292                 return bytesToFloat(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]);
293             default:
294                 logger.error("Unknown format type {} - no float value can be provided for it.", formatType);
295         }
296
297         return null;
298     }
299
300     /**
301      * Return the stored value of this characteristic. This doesn't read the remote data.
302      *
303      */
304     public String getStringValue(int offset) {
305         if (value == null || offset > value.length) {
306             return null;
307         }
308         byte[] strBytes = new byte[value.length - offset];
309         for (int i = 0; i < (value.length - offset); ++i) {
310             strBytes[i] = (byte) value[offset + i];
311         }
312         return new String(strBytes, StandardCharsets.UTF_8);
313     }
314
315     /**
316      * Updates the locally stored value of this characteristic.
317      *
318      * @param value the value to set
319      * @return true, if it has been set successfully
320      */
321     public boolean setValue(int[] value) {
322         this.value = value;
323         return true;
324     }
325
326     /**
327      * Set the local value of this characteristic.
328      *
329      * @param value the value to set
330      * @param formatType the format of the value (as one of the FORMAT_* constants in this class)
331      * @param offset the offset to use when interpreting the value
332      * @return true, if it has been set successfully
333      */
334     public boolean setValue(int value, int formatType, int offset) {
335         int len = offset + getTypeLen(formatType);
336         if (this.value == null) {
337             this.value = new int[len];
338         }
339         if (len > this.value.length) {
340             return false;
341         }
342         int val = value;
343         switch (formatType) {
344             case FORMAT_SINT8:
345                 val = intToSignedBits(value, 8);
346                 // Fall-through intended
347             case FORMAT_UINT8:
348                 this.value[offset] = (byte) (val & 0xFF);
349                 break;
350
351             case FORMAT_SINT16:
352                 val = intToSignedBits(value, 16);
353                 // Fall-through intended
354             case FORMAT_UINT16:
355                 this.value[offset] = (byte) (val & 0xFF);
356                 this.value[offset + 1] = (byte) ((val >> 8) & 0xFF);
357                 break;
358
359             case FORMAT_SINT32:
360                 val = intToSignedBits(value, 32);
361                 // Fall-through intended
362             case FORMAT_UINT32:
363                 this.value[offset] = (byte) (val & 0xFF);
364                 this.value[offset + 1] = (byte) ((val >> 8) & 0xFF);
365                 this.value[offset + 2] = (byte) ((val >> 16) & 0xFF);
366                 this.value[offset + 2] = (byte) ((val >> 24) & 0xFF);
367                 break;
368
369             default:
370                 return false;
371         }
372         return true;
373     }
374
375     /**
376      * Set the local value of this characteristic.
377      *
378      * @param mantissa the mantissa of the value
379      * @param exponent the exponent of the value
380      * @param formatType the format of the value (as one of the FORMAT_* constants in this class)
381      * @param offset the offset to use when interpreting the value
382      * @return true, if it has been set successfully
383      *
384      */
385     public boolean setValue(int mantissa, int exponent, int formatType, int offset) {
386         int len = offset + getTypeLen(formatType);
387         if (value == null) {
388             value = new int[len];
389         }
390         if (len > value.length) {
391             return false;
392         }
393
394         switch (formatType) {
395             case FORMAT_SFLOAT:
396                 int m = intToSignedBits(mantissa, 12);
397                 int exp = intToSignedBits(exponent, 4);
398                 value[offset] = (byte) (m & 0xFF);
399                 value[offset + 1] = (byte) ((m >> 8) & 0x0F);
400                 value[offset + 1] += (byte) ((exp & 0x0F) << 4);
401                 break;
402
403             case FORMAT_FLOAT:
404                 m = intToSignedBits(mantissa, 24);
405                 exp = intToSignedBits(exponent, 8);
406                 value[offset] = (byte) (m & 0xFF);
407                 value[offset + 1] = (byte) ((m >> 8) & 0xFF);
408                 value[offset + 2] = (byte) ((m >> 16) & 0xFF);
409                 value[offset + 2] += (byte) (exp & 0xFF);
410                 break;
411
412             default:
413                 return false;
414         }
415
416         return true;
417     }
418
419     /**
420      * Set the local value of this characteristic.
421      *
422      * @param value the value to set
423      * @return true, if it has been set successfully
424      */
425     public boolean setValue(byte[] value) {
426         this.value = new int[value.length];
427         int cnt = 0;
428         for (byte val : value) {
429             this.value[cnt++] = val;
430         }
431         return true;
432     }
433
434     /**
435      * Set the local value of this characteristic.
436      *
437      * @param value the value to set
438      * @return true, if it has been set successfully
439      */
440     public boolean setValue(String value) {
441         this.value = new int[value.getBytes().length];
442         int cnt = 0;
443         for (byte val : value.getBytes()) {
444             this.value[cnt++] = val;
445         }
446         return true;
447     }
448
449     /**
450      * Returns the size of the requested value type.
451      */
452     private int getTypeLen(int formatType) {
453         return formatType & 0xF;
454     }
455
456     /**
457      * Convert a signed byte to an unsigned int.
458      */
459     private int unsignedByteToInt(int value) {
460         return value & 0xFF;
461     }
462
463     /**
464      * Convert signed bytes to a 16-bit unsigned int.
465      */
466     private int unsignedBytesToInt(int value1, int value2) {
467         return value1 + (value2 << 8);
468     }
469
470     /**
471      * Convert signed bytes to a 32-bit unsigned int.
472      */
473     private int unsignedBytesToInt(int value1, int value2, int value3, int value4) {
474         return value1 + (value2 << 8) + (value3 << 16) + (value4 << 24);
475     }
476
477     /**
478      * Convert signed bytes to a 16-bit short float value.
479      */
480     private float bytesToFloat(int value1, int value2) {
481         int mantissa = unsignedToSigned(unsignedByteToInt(value1) + ((unsignedByteToInt(value2) & 0x0F) << 8), 12);
482         int exponent = unsignedToSigned(unsignedByteToInt(value2) >> 4, 4);
483         return (float) (mantissa * Math.pow(10, exponent));
484     }
485
486     /**
487      * Convert signed bytes to a 32-bit short float value.
488      */
489     private float bytesToFloat(int value1, int value2, int value3, int value4) {
490         int mantissa = unsignedToSigned(
491                 unsignedByteToInt(value1) + (unsignedByteToInt(value2) << 8) + (unsignedByteToInt(value3) << 16), 24);
492         return (float) (mantissa * Math.pow(10, value4));
493     }
494
495     /**
496      * Convert an unsigned integer to a two's-complement signed value.
497      */
498     private int unsignedToSigned(int unsigned, int size) {
499         if ((unsigned & (1 << size - 1)) != 0) {
500             return -1 * ((1 << size - 1) - (unsigned & ((1 << size - 1) - 1)));
501         } else {
502             return unsigned;
503         }
504     }
505
506     /**
507      * Convert an integer into the signed bits of the specified length.
508      */
509     private int intToSignedBits(int i, int size) {
510         if (i < 0) {
511             return (1 << size - 1) + (i & ((1 << size - 1) - 1));
512         } else {
513             return i;
514         }
515     }
516
517     public GattCharacteristic getGattCharacteristic() {
518         return GattCharacteristic.getCharacteristic(uuid);
519     }
520
521     public enum GattCharacteristic {
522         // Characteristic
523         ALERT_CATEGORY_ID(0x2A43),
524         ALERT_CATEGORY_ID_BIT_MASK(0x2A42),
525         ALERT_LEVEL(0x2A06),
526         ALERT_NOTIFICATION_CONTROL_POINT(0x2A44),
527         ALERT_STATUS(0x2A3F),
528         APPEARANCE(0x2A01),
529         BATTERY_LEVEL(0x2A19),
530         BLOOD_PRESSURE_FEATURE(0x2A49),
531         BLOOD_PRESSURE_MEASUREMENT(0x2A35),
532         BODY_SENSOR_LOCATION(0x2A38),
533         BOOT_KEYOBARD_INPUT_REPORT(0x2A22),
534         BOOT_KEYOBARD_OUTPUT_REPORT(0x2A32),
535         BOOT_MOUSE_INPUT_REPORT(0x2A33),
536         CSC_FEATURE(0x2A5C),
537         CSC_MEASUREMENT(0x2A5B),
538         CURRENT_TIME(0x2A2B),
539         CYCLING_POWER_CONTROL_POINT(0x2A66),
540         CYCLING_POWER_FEATURE(0x2A65),
541         CYCLING_POWER_MEASUREMENT(0x2A63),
542         CYCLING_POWER_VECTOR(0x2A64),
543         DATE_TIME(0x2A08),
544         DAY_DATE_TIME(0x2A0A),
545         DAY_OF_WEEK(0x2A09),
546         DEVICE_NAME(0x2A00),
547         DST_OFFSET(0x2A0D),
548         EXACT_TIME_256(0x2A0C),
549         FIRMWARE_REVISION_STRING(0x2A26),
550         GLUCOSE_FEATURE(0x2A51),
551         GLUCOSE_MEASUREMENT(0x2A18),
552         GLUCOSE_MEASUREMENT_CONTROL(0x2A34),
553         HARDWARE_REVISION_STRING(0x2A27),
554         HEART_RATE_CONTROL_POINT(0x2A39),
555         HEART_RATE_MEASUREMENT(0x2A37),
556         HID_CONTROL_POINT(0x2A4C),
557         HID_INFORMATION(0x2A4A),
558         IEEE11073_20601_REGULATORY_CERTIFICATION_DATA_LIST(0x2A2A),
559         INTERMEDIATE_CUFF_PRESSURE(0x2A36),
560         INTERMEDIATE_TEMPERATURE(0x2A1E),
561         LN_CONTROL_POINT(0x2A6B),
562         LN_FEATURE(0x2A6A),
563         LOCAL_TIME_INFORMATION(0x2A0F),
564         LOCATION_AND_SPEED(0x2A67),
565         MANUFACTURER_NAME_STRING(0x2A29),
566         MEASUREMENT_INTERVAL(0x2A21),
567         MODEL_NUMBER_STRING(0x2A24),
568         NAVIGATION(0x2A68),
569         NEW_ALERT(0x2A46),
570         PERIPERAL_PREFFERED_CONNECTION_PARAMETERS(0x2A04),
571         PERIPHERAL_PRIVACY_FLAG(0x2A02),
572         PN_PID(0x2A50),
573         POSITION_QUALITY(0x2A69),
574         PROTOCOL_MODE(0x2A4E),
575         RECONNECTION_ADDRESS(0x2A03),
576         RECORD_ACCESS_CONTROL_POINT(0x2A52),
577         REFERENCE_TIME_INFORMATION(0x2A14),
578         REPORT(0x2A4D),
579         REPORT_MAP(0x2A4B),
580         RINGER_CONTROL_POINT(0x2A40),
581         RINGER_SETTING(0x2A41),
582         RSC_FEATURE(0x2A54),
583         RSC_MEASUREMENT(0x2A53),
584         SC_CONTROL_POINT(0x2A55),
585         SCAN_INTERVAL_WINDOW(0x2A4F),
586         SCAN_REFRESH(0x2A31),
587         SENSOR_LOCATION(0x2A5D),
588         SERIAL_NUMBER_STRING(0x2A25),
589         SERVICE_CHANGED(0x2A05),
590         SOFTWARE_REVISION_STRING(0x2A28),
591         SUPPORTED_NEW_ALERT_CATEGORY(0x2A47),
592         SUPPORTED_UNREAD_ALERT_CATEGORY(0x2A48),
593         SYSTEM_ID(0x2A23),
594         TEMPERATURE_MEASUREMENT(0x2A1C),
595         TEMPERATURE_TYPE(0x2A1D),
596         TIME_ACCURACY(0x2A12),
597         TIME_SOURCE(0x2A13),
598         TIME_UPDATE_CONTROL_POINT(0x2A16),
599         TIME_UPDATE_STATE(0x2A17),
600         TIME_WITH_DST(0x2A11),
601         TIME_ZONE(0x2A0E),
602         TX_POWER_LEVEL(0x2A07),
603         UNREAD_ALERT_STATUS(0x2A45),
604         AGGREGATE_INPUT(0x2A5A),
605         ANALOG_INPUT(0x2A58),
606         ANALOG_OUTPUT(0x2A59),
607         DIGITAL_INPUT(0x2A56),
608         DIGITAL_OUTPUT(0x2A57),
609         EXACT_TIME_100(0x2A0B),
610         NETWORK_AVAILABILITY(0x2A3E),
611         SCIENTIFIC_TEMPERATURE_IN_CELSIUS(0x2A3C),
612         SECONDARY_TIME_ZONE(0x2A10),
613         STRING(0x2A3D),
614         TEMPERATURE_IN_CELSIUS(0x2A1F),
615         TEMPERATURE_IN_FAHRENHEIT(0x2A20),
616         TIME_BROADCAST(0x2A15),
617         BATTERY_LEVEL_STATE(0x2A1B),
618         BATTERY_POWER_STATE(0x2A1A),
619         PULSE_OXIMETRY_CONTINUOUS_MEASUREMENT(0x2A5F),
620         PULSE_OXIMETRY_CONTROL_POINT(0x2A62),
621         PULSE_OXIMETRY_FEATURES(0x2A61),
622         PULSE_OXIMETRY_PULSATILE_EVENT(0x2A60),
623         PULSE_OXIMETRY_SPOT_CHECK_MEASUREMENT(0x2A5E),
624         RECORD_ACCESS_CONTROL_POINT_TESTVERSION(0x2A52),
625         REMOVABLE(0x2A3A),
626         SERVICE_REQUIRED(0x2A3B);
627
628         private static Map<UUID, GattCharacteristic> uuidToServiceMapping;
629
630         private UUID uuid;
631
632         private GattCharacteristic(long key) {
633             this.uuid = new UUID((key << 32) | 0x1000, BluetoothBindingConstants.BLUETOOTH_BASE_UUID);
634         }
635
636         private static void initMapping() {
637             uuidToServiceMapping = new HashMap<>();
638             for (GattCharacteristic s : values()) {
639                 uuidToServiceMapping.put(s.uuid, s);
640             }
641         }
642
643         public static GattCharacteristic getCharacteristic(UUID uuid) {
644             if (uuidToServiceMapping == null) {
645                 initMapping();
646             }
647             return uuidToServiceMapping.get(uuid);
648         }
649
650         /**
651          * @return the key
652          */
653         public UUID getUUID() {
654             return uuid;
655         }
656     }
657 }