多个BluetoothGattCharacteristic没有得到通知

tem*_*mp_ 5 android kotlin bluetooth-lowenergy bluetooth-gatt

我正在研究一个BLE设备,但我无法接听onCharacteristicChanged.我有8个BluetoothGattCharacteristic我需要订阅.

在找到设备后,onServicesDiscovered我开始一个订阅每个特征的过程.

private fun requestCharacteristics(gatt: BluetoothGatt, char: BluetoothGattCharacteristic){
        subscribeToCharacteristic(gatt, char, true)
        (charList).getOrNull(0)?.let {
            charList.removeAt(0)
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在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")
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后我接到每个特征的电话,onDescriptorWrite并检查我是否需要订阅另一个特征.

override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor?, status: Int) {
        super.onDescriptorWrite(gatt, descriptor, status)
        if (signalsChars.isNotEmpty()) {
            requestCharacteristics(gatt, signalsChars.first())
        } 
    }
Run Code Online (Sandbox Code Playgroud)

所有这些都有效但我从来没有接到任何电话onCharacteristicChanged.另外,如果我gatt.readCharacteristic(char)在订阅之前打电话 ,onDescriptorWrite将不会被呼叫.我再次拥有8个需要订阅的特性.请帮忙!

LaV*_*epe 0

我最近用 Kotlin 制作了一个简单的 BLE 客户端 Android 应用程序。您可以在此处找到其代码。也许它会对你有所帮助。

在我订阅后,gatt.setCharacteristicNotification每次特征发生变化时我都会收到通知,所以我认为你是对的。您确定 BLE 设备的特性发生变化吗?

另外,如果您遇到在订阅之前阅读特征的情况,您可以使用onCharacteristicRead方法。当读取特征时它会被调用,因此您可以获取描述符并在那里写入。