首页 > 解决方案 > 无法使用蓝牙 LE 读取特征,readCharacteristic 在 Android 上返回 false

问题描述

我想通过我的 Android 设备上的蓝牙从 Medisana 设备读取血压。

这是我的代码

override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
                        super.onServicesDiscovered(gatt, status)
                        if (status != BluetoothGatt.GATT_SUCCESS) {
                            Log.e(TAG, "onServicesDiscovered failed")
                            return
                        }

                        val characteristic = gatt?.getService(BLOOD_PRESSURE_SERVICE_UUID)?.
                            getCharacteristic(BLOOD_PRESSURE_CHARACTERISTICS_UUID)
                        if (characteristic == null) {
                            Log.e(TAG, "blood pressure measurement characteristics is not supported by the device")
                        } else {
                            gatt.setCharacteristicNotification(characteristic, true)
                            val descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID)
                            descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
                            gatt.writeDescriptor(descriptor)
                            if (!gatt.readCharacteristic(characteristic)) {
                                Log.e(TAG, "Unable to read characteristic")
                            }
                        }
                    }

这是我从蓝牙官方网站复制的常量

private val BLOOD_PRESSURE_SERVICE_UUID = UUIDUtils.convertFromInteger(0x1810)
private val BLOOD_PRESSURE_CHARACTERISTICS_UUID = UUIDUtils.convertFromInteger(0x2A35)

object UUIDUtils {
    fun convertFromInteger(i: Int): UUID {
        val MSB = 0x0000000000001000L
        val LSB = -0x7fffff7fa064cb05L
        val value = (i and -0x1).toLong()
        return UUID(MSB or (value shl 32), LSB)
    }
}

执行代码时,我在日志中看到“无法读取特征”。当我调试readCharacteristic它返回在行

public boolean readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
            return false;
        }

所以特性不是可读的,而是如何使它可读。我是蓝牙新手,所有这些东西都让我感到困惑。

标签: androidbluetooth

解决方案


试试这个 根据文档,血压需要加indication enable才能获取数据。所以您需要:首先,将“ENABLE_INDICATION_VALUE”添加到 CLIENT_CHARACTERISTIC_CONFIG 描述符中。

这个描述符来自:

descriptor = characteristic.getDescriptor(
                    UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); //CLIENT_CHARACTERISTIC_CONFIG equal to 00002902-0000-1000-8000-00805f9b34fb

然后:

descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); 

最后一步,像这样将描述符写入远程设备(压力主机)

mBluetoothGatt.writeDescriptor(descriptor); 

这对我有用,我从设备中获取血压数据。我不是以英语为母语的人,对不起我的英语不好


推荐阅读