我有一个程序可以同时从多个蓝牙设备读取数据。我需要等待来自每个传感器的 200 个数据包。我最初只使用一个设备进行测试,在此期间我使用 asyncio.event 等待 200 个数据包然后继续。
async with BleakClient(sensor_address, loop = loop, timeout = timeout) as bluetooth:
x = await bluetooth.is_connected()
logging.info(f'connected: {x}')
await bluetooth.start_notify(self.SENSOR_CHARACTERISTIC_UUID, self._notification_handler)
await event.wait()
await bluetooth.stop_notify(self.SENSOR_CHARACTERISTIC_UUID)
在我的 _notification_handler 函数中:
def _notification_handler(self, event, sender, data: bin):
if self.packets_received < self.num_packets:
self.packets_received += 1
self.decode_data(data)
else:
event.set()
但是,由于我现在使用多个传感器,我不能等待设置事件,因为如果第一个传感器完成,无论其他传感器的状态如何,这都会触发所有传感器停止收集。
我曾考虑在 start_notify 下设置一个循环来等待所有数据包,然后在再次检查之前休眠几秒钟,但这对我来说似乎很笨拙。
await client.start_notify(SENSOR_CHARACTERISTIC_UUID, notification_handler)
while packets_received < self.num_packets:
await asyncio.sleep(10.0)
await client.stop_notify(SENSOR_CHARACTERISTIC_UUID)
有没有更好的方法来解决这个问题?(notification_handler 函数已被修改以适应上述更改)。