android - 无法使用蓝牙 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;
}
所以特性不是可读的,而是如何使它可读。我是蓝牙新手,所有这些东西都让我感到困惑。
解决方案
试试这个 根据文档,血压需要加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);
这对我有用,我从设备中获取血压数据。我不是以英语为母语的人,对不起我的英语不好
推荐阅读
- javascript - 为什么我不能在 if 语句中保存 Flask 中的会话变量?
- prolog - 序言中的深度限制α-β
- reactjs - 类型检查动作创建者参数的动态值
- node.js - 如何将正文传递给表达路由器以进行 PUT 请求?
- ansible - 错误:无法使用脚本插件解析 /get_branches.py:库存脚本 (/get_branches.py) 出现执行错误:
- javascript - 如何使用JavaScript调用数据文件然后以表格形式显示
- javascript - 将多个 Typescript 文件合并为一个 JS 文件,包括摇树
- unity3d - 如何调整着色器区域的大小?
- javascript - 使用 javascript 保存许多持久化配置值
- python - 计算年复利python