我正在使用 BLE 设备,但无法onCharacteristicChanged
被调用。我有 8BluetoothGattCharacteristic
个需要订阅。
找到设备后,onServicesDiscovered
我开始订阅每个特征的过程。
private fun requestCharacteristics(gatt: BluetoothGatt, char: BluetoothGattCharacteristic){
subscribeToCharacteristic(gatt, char, true)
(charList).getOrNull(0)?.let {
charList.removeAt(0)
}
}
然后在subscribeToCharacteristic
我做所有检查描述符。
private val CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
private fun subscribeToCharacteristic(gatt: BluetoothGatt, char: BluetoothGattCharacteristic, enable: Boolean) {
if (gatt.setCharacteristicNotification(char, enable)){
val descriptor = char.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID)
if (descriptor != null){
if (BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 && char.properties != 0) {
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
} else if (BluetoothGattCharacteristic.PROPERTY_INDICATE != 0 && char.properties != 0) {
descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
} else {
println("The characteristic does not have NOTIFY or INDICATE property set")
}
if (gatt.writeDescriptor(descriptor)){
println("this worked")
} else {
println("This did not work")
}
} else {
println("Failed to set client characteristic notification")
}
} else {
println("Failed to register notification")
}
}
然后我接到每个特征的电话,onDescriptorWrite
并检查我是否需要订阅另一个特征。
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor?, status: Int) {
super.onDescriptorWrite(gatt, descriptor, status)
if (signalsChars.isNotEmpty()) {
requestCharacteristics(gatt, signalsChars.first())
}
}
所有这些工作,但我从来没有接到任何电话onCharacteristicChanged
。另外,如果我 gatt.readCharacteristic(char)
在订阅之前调用,onDescriptorWrite
将不会被调用。我再次需要订阅 8 个特征。请帮忙!