gatt.writeDescriptor() 一直返回 false:

gatt.writeDescriptor() returning false all the time:

抱歉,如果之前有人问过我要问的问题,但是尽管进行了大量搜索,我仍无法找到对我遇到的问题的任何可能解释。

我正在开发一个 Android 应用程序,它与 BLE 设备 (CC2541) 通信。我能够毫无问题地将数据从 Android 写入 BLE 设备。然而,当尝试从 Android.

中的 BLE 设备读取数据时,问题就开始了

我正在使用 Kotlin,我正在尝试为我想要读取的特定 GATT 特性“启用”通知,我通过将描述符设置为以下 UUID

00002902-0000-1000-8000-00805f9b34fb

为此,我有以下代码:

private suspend fun setNotification(
    char: BluetoothGattCharacteristic,
    descValue: ByteArray,
    enable: Boolean
) {
    val desc = char.getDescriptor(UUID_CLIENT_CHAR_CONFIG)
        ?: throw IOException("missing config descriptor on $char")
    val key = Pair(char.uuid, desc.uuid)
    if (descWriteCont.containsKey(key))
        throw IllegalStateException("last not finished yet")

    if (!gatt.setCharacteristicNotification(char, enable))
        throw IOException("fail to set notification on $char")

    return suspendCoroutine { cont ->
        descWriteCont[key] = cont
        desc.value = descValue
        if (!gatt.writeDescriptor(desc))
            cont.resumeWithException(IOException("fail to config descriptor $this"))
    }
}

然而,碰巧以下方法 returns 一直都是错误的:

gatt.writeDescriptor(desc)

有谁知道可能导致此问题的原因是什么?如果这是一个我忽略了答案的愚蠢问题,请提前致歉。我是 Kotlin 和协程的新手,事实上我怀疑这个问题与我使用挂起函数的方式有关。

我已经解决了这个问题。

经过多次调试,我发现由于一些奇怪的原因(我对 Kotlin 或 Android 不是很有经验,所以我不知道这个原因),方法 gatt.writeDescriptor() returns 3 次,(至少就我而言)。只有最后一次 return truedescriptor 才真正被写入。

所以因为我的代码只检查了它是 returned true 还是 false 第一次,它显然失败了。

我现在已经修改了我的代码,让它等到它 returns true 这总是发生在第三次它 returns.

private suspend fun setNotification(
    char: BluetoothGattCharacteristic,
    descValue: ByteArray,
    enable: Boolean
) {
    val desc = char.getDescriptor(UUID_CLIENT_CHAR_CONFIG)
        ?: throw IOException("missing config descriptor on $char")
    val key = Pair(char.uuid, desc.uuid)
    if (descWriteCont.containsKey(key))
        throw IllegalStateException("last setNotification() not finish")

    if (!gatt.setCharacteristicNotification(char, enable))
        throw IOException("fail to set notification on $char")

    return suspendCoroutine { cont ->
        descWriteCont[key] = cont
        desc.value = descValue
        while (!gatt.writeDescriptor(desc)) {

        }

    }
}

现在我已成功订阅通知,并且可以毫无问题地从 BLE 设备读取数据。

感谢所有提供帮助的人,我希望这能帮助将来遇到同样情况的人。