2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.bluetooth;
15 import java.nio.charset.StandardCharsets;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.UUID;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * The {@link BluetoothCharacteristic} class defines the Bluetooth characteristic.
28 * Characteristics are defined attribute types that contain a single logical value.
30 * https://www.bluetooth.com/specifications/gatt/characteristics
32 * @author Chris Jackson - Initial contribution
33 * @author Kai Kreuzer - Cleaned up code
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;
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;
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;
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;
67 private final Logger logger = LoggerFactory.getLogger(BluetoothCharacteristic.class);
70 * The {@link UUID} for this characteristic
75 * The handle for this characteristic
80 * A map of {@link BluetoothDescriptor}s applicable to this characteristic
82 protected Map<UUID, BluetoothDescriptor> gattDescriptors = new HashMap<>();
83 protected int instance;
84 protected int properties;
85 protected int permissions;
86 protected int writeType;
89 * The raw data value for this characteristic
91 protected int[] value = new int[0];
94 * The {@link BluetoothService} to which this characteristic belongs
96 protected BluetoothService service;
99 * Create a new BluetoothCharacteristic.
101 * @param uuid the {@link UUID} of the new characteristic
104 public BluetoothCharacteristic(UUID uuid, int handle) {
106 this.handle = handle;
110 * Adds a descriptor to this characteristic.
112 * @param descriptor {@link BluetoothDescriptor} to be added to this characteristic.
113 * @return true, if the descriptor was added to the characteristic
115 public boolean addDescriptor(BluetoothDescriptor descriptor) {
116 if (gattDescriptors.get(descriptor.getUuid()) != null) {
120 gattDescriptors.put(descriptor.getUuid(), descriptor);
125 * Returns the {@link UUID} of this characteristic
127 * @return UUID of this characteristic
129 public UUID getUuid() {
134 * Returns the instance ID for this characteristic.
136 * If a remote device offers multiple characteristics with the same UUID, the instance ID is used to distinguish
137 * between characteristics.
139 * @return Instance ID of this characteristic
141 public int getInstanceId() {
146 * Returns the properties of this characteristic.
148 * The properties contain a bit mask of property flags indicating the features of this characteristic.
151 public int getProperties() {
156 * Returns the permissions for this characteristic.
158 public int getPermissions() {
163 * Gets the write type for this characteristic.
166 public int getWriteType() {
171 * Set the write type for this characteristic
175 public void setWriteType(int writeType) {
176 this.writeType = writeType;
180 * Get the service to which this characteristic belongs
182 * @return the {@link BluetoothService}
184 public BluetoothService getService() {
189 * Returns the handle for this characteristic
191 * @return the handle for the characteristic
193 public int getHandle() {
198 * Get the service to which this characteristic belongs
200 * @return the {@link BluetoothService}
202 public void setService(BluetoothService service) {
203 this.service = service;
207 * Returns a list of descriptors for this characteristic.
210 public List<BluetoothDescriptor> getDescriptors() {
211 return new ArrayList<>(gattDescriptors.values());
215 * Returns a descriptor with a given UUID out of the list of
216 * descriptors for this characteristic.
218 * @return the {@link BluetoothDescriptor}
220 public BluetoothDescriptor getDescriptor(UUID uuid) {
221 return gattDescriptors.get(uuid);
225 * Get the stored value for this characteristic.
228 public int[] getValue() {
233 * Get the stored value for this characteristic.
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);
245 * Return the stored value of this characteristic.
248 public Integer getIntValue(int formatType, int offset) {
249 if ((offset + getTypeLen(formatType)) > value.length) {
253 switch (formatType) {
255 return unsignedByteToInt(value[offset]);
258 return unsignedBytesToInt(value[offset], value[offset + 1]);
261 return unsignedBytesToInt(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]);
264 return unsignedToSigned(unsignedByteToInt(value[offset]), 8);
267 return unsignedToSigned(unsignedBytesToInt(value[offset], value[offset + 1]), 16);
270 return unsignedToSigned(
271 unsignedBytesToInt(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]), 32);
273 logger.error("Unknown format type {} - no int value can be provided for it.", formatType);
280 * Return the stored value of this characteristic. This doesn't read the remote data.
283 public Float getFloatValue(int formatType, int offset) {
284 if ((offset + getTypeLen(formatType)) > value.length) {
288 switch (formatType) {
290 return bytesToFloat(value[offset], value[offset + 1]);
292 return bytesToFloat(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]);
294 logger.error("Unknown format type {} - no float value can be provided for it.", formatType);
301 * Return the stored value of this characteristic. This doesn't read the remote data.
304 public String getStringValue(int offset) {
305 if (value == null || offset > value.length) {
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];
312 return new String(strBytes, StandardCharsets.UTF_8);
316 * Updates the locally stored value of this characteristic.
318 * @param value the value to set
319 * @return true, if it has been set successfully
321 public boolean setValue(int[] value) {
327 * Set the local value of this characteristic.
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
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];
339 if (len > this.value.length) {
343 switch (formatType) {
345 val = intToSignedBits(value, 8);
346 // Fall-through intended
348 this.value[offset] = (byte) (val & 0xFF);
352 val = intToSignedBits(value, 16);
353 // Fall-through intended
355 this.value[offset] = (byte) (val & 0xFF);
356 this.value[offset + 1] = (byte) ((val >> 8) & 0xFF);
360 val = intToSignedBits(value, 32);
361 // Fall-through intended
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);
376 * Set the local value of this characteristic.
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
385 public boolean setValue(int mantissa, int exponent, int formatType, int offset) {
386 int len = offset + getTypeLen(formatType);
388 value = new int[len];
390 if (len > value.length) {
394 switch (formatType) {
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);
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);
420 * Set the local value of this characteristic.
422 * @param value the value to set
423 * @return true, if it has been set successfully
425 public boolean setValue(byte[] value) {
426 this.value = new int[value.length];
428 for (byte val : value) {
429 this.value[cnt++] = val;
435 * Set the local value of this characteristic.
437 * @param value the value to set
438 * @return true, if it has been set successfully
440 public boolean setValue(String value) {
441 this.value = new int[value.getBytes().length];
443 for (byte val : value.getBytes()) {
444 this.value[cnt++] = val;
450 * Returns the size of the requested value type.
452 private int getTypeLen(int formatType) {
453 return formatType & 0xF;
457 * Convert a signed byte to an unsigned int.
459 private int unsignedByteToInt(int value) {
464 * Convert signed bytes to a 16-bit unsigned int.
466 private int unsignedBytesToInt(int value1, int value2) {
467 return value1 + (value2 << 8);
471 * Convert signed bytes to a 32-bit unsigned int.
473 private int unsignedBytesToInt(int value1, int value2, int value3, int value4) {
474 return value1 + (value2 << 8) + (value3 << 16) + (value4 << 24);
478 * Convert signed bytes to a 16-bit short float value.
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));
487 * Convert signed bytes to a 32-bit short float value.
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));
496 * Convert an unsigned integer to a two's-complement signed value.
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)));
507 * Convert an integer into the signed bits of the specified length.
509 private int intToSignedBits(int i, int size) {
511 return (1 << size - 1) + (i & ((1 << size - 1) - 1));
517 public GattCharacteristic getGattCharacteristic() {
518 return GattCharacteristic.getCharacteristic(uuid);
521 public enum GattCharacteristic {
523 ALERT_CATEGORY_ID(0x2A43),
524 ALERT_CATEGORY_ID_BIT_MASK(0x2A42),
526 ALERT_NOTIFICATION_CONTROL_POINT(0x2A44),
527 ALERT_STATUS(0x2A3F),
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),
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),
544 DAY_DATE_TIME(0x2A0A),
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),
563 LOCAL_TIME_INFORMATION(0x2A0F),
564 LOCATION_AND_SPEED(0x2A67),
565 MANUFACTURER_NAME_STRING(0x2A29),
566 MEASUREMENT_INTERVAL(0x2A21),
567 MODEL_NUMBER_STRING(0x2A24),
570 PERIPERAL_PREFFERED_CONNECTION_PARAMETERS(0x2A04),
571 PERIPHERAL_PRIVACY_FLAG(0x2A02),
573 POSITION_QUALITY(0x2A69),
574 PROTOCOL_MODE(0x2A4E),
575 RECONNECTION_ADDRESS(0x2A03),
576 RECORD_ACCESS_CONTROL_POINT(0x2A52),
577 REFERENCE_TIME_INFORMATION(0x2A14),
580 RINGER_CONTROL_POINT(0x2A40),
581 RINGER_SETTING(0x2A41),
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),
594 TEMPERATURE_MEASUREMENT(0x2A1C),
595 TEMPERATURE_TYPE(0x2A1D),
596 TIME_ACCURACY(0x2A12),
598 TIME_UPDATE_CONTROL_POINT(0x2A16),
599 TIME_UPDATE_STATE(0x2A17),
600 TIME_WITH_DST(0x2A11),
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),
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),
626 SERVICE_REQUIRED(0x2A3B);
628 private static Map<UUID, GattCharacteristic> uuidToServiceMapping;
632 private GattCharacteristic(long key) {
633 this.uuid = new UUID((key << 32) | 0x1000, BluetoothBindingConstants.BLUETOOTH_BASE_UUID);
636 private static void initMapping() {
637 uuidToServiceMapping = new HashMap<>();
638 for (GattCharacteristic s : values()) {
639 uuidToServiceMapping.put(s.uuid, s);
643 public static GattCharacteristic getCharacteristic(UUID uuid) {
644 if (uuidToServiceMapping == null) {
647 return uuidToServiceMapping.get(uuid);
653 public UUID getUUID() {