【问题标题】:Multiple BluetoothGattCharacteristic not being notified未通知多个 BluetoothGattCharacteristic
【发布时间】:2018-08-24 21:19:20
【问题描述】:

我正在使用 BLE 设备,但无法调用 onCharacteristicChanged。我有 8 个BluetoothGattCharacteristic 需要订阅。

找到设备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 个特征。请帮忙!

【问题讨论】:

    标签: android kotlin bluetooth-lowenergy bluetooth-gatt


    【解决方案1】:

    我最近在 Kotlin 中制作了一个简单的 BLE Client Android 应用程序。你可以找到它的代码here。也许它会帮助你。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多