如何解决gatt.writeDescriptor() 一直返回 false:
如果之前有人问过我要问的问题,我深表歉意,但是尽管进行了多次搜索,我还是找不到对我遇到的问题的任何可能的解释。
我正在开发与 BLE 设备 (CC2541) 通信的 Android 应用程序。我能够毫无问题地将数据从 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"))
}
}
然而,碰巧以下方法总是返回false:
gatt.writeDescriptor(desc)
有谁知道是什么导致了这个问题?如果这是一个愚蠢的问题,我忽略了其答案,请提前道歉。我是 Kotlin 和协程的新手,实际上我怀疑这个问题与我如何使用挂起函数有关。
解决方法
我已经解决了这个问题。
经过多次调试,我发现由于某种奇怪的原因(我对 Kotlin 或 Android 不是很熟悉,所以我不知道这个原因),方法 gatt.writeDescriptor()
返回了 3 次,(在我的情况,至少)。并且只有最后一次返回 true
并且 descriptor
实际被写入。
所以因为我的代码第一次只检查了它返回的是 true
还是 false
,所以它显然失败了。
我现在修改了我的代码,让它一直等到它返回 true
,这总是在它第三次返回时发生。
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 设备读取数据。
感谢所有提供帮助的人,我希望这能帮助将来面临同样情况的人。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。