我很高兴这可能已经得到解答,但我无法找到适合我的解决方案。
Tl;dr:如何制作功能块?
我有以下用 Kotlin 为 Android API 28 编写的 BLE 相关代码。
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
for (gattService: BluetoothGattService in gatt!!.services) {
for (gattChar: BluetoothGattCharacteristic in gattService.characteristics) {
if (gattChar.uuid.toString().contains(ADC_SAMPLESET_0) && !subscribed_0) {
subscribed_0 = true
gatt.setCharacteristicNotification(gattChar, true)
val descriptor = gattChar.getDescriptor(
UUID.fromString(BleNamesResolver.CLIENT_CHARACTERISTIC_CONFIG)
)
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
}
上面的 if 语句重复多次,以便于订阅多个 BLE 特性。不幸的是,gatt.writeDescriptor()
函数异步运行。我需要等它返回再打电话gatt.writeDescriptor()
对于下一个特征。我该如何实现这一目标?
我尝试过使用runBlocking
and GlobalScope.launch
in kotlinx.coroutines.experimental.*
但我并不完全确定它们是正确的。
谢谢,
亚当
The onDescriptorWrite()
方法可能会有所帮助。你应该已经覆盖它了。
请尝试以下操作:
private var canContinue = false;
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { //gatt shouldn't be null, so the null-safe ? isn't needed
loopAsync(gatt);
}
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
canContinue = true; //allow the loop to continue once a descriptor is written
}
private fun loopAsync(gatt: BluetoothGatt) {
async { //Run it async
gatt.services.forEach { gattService -> //Kotlin has a handy Collections.forEach() extension function
gattService.characteristics.forEach { gattChar -> //Same for this one
if (gattChar.uuid.toString().contains(ADC_SAMPLESET_0) && !subscribed_0) {
subscribed_0 = true
gatt.setCharacteristicNotification(gattChar, true)
val descriptor = gattChar.getDescriptor(
UUID.fromString(BleNamesResolver.CLIENT_CHARACTERISTIC_CONFIG)
}
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
while(!canContinue); //wait until canContinue becomes true and then continue
}
}
}
}
}
这有点hacky。可能有一种方法可以通过递归来做到这一点,但是嵌套的 for 循环使这变得很棘手。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)