-
The example provided for connecting to two devices does not work on my device. import asyncio
from bleak import BleakClient
notify_uuid = "00002A37-0000-1000-8000-00805F9B34FB"
def callback(characteristic, data):
print(characteristic, data)
async def connect_to_device(address):
print("starting", address, "loop")
async with BleakClient(address, timeout=5.0) as client:
print("connect to", address)
try:
await client.start_notify(notify_uuid, callback)
await asyncio.sleep(10.0)
await client.stop_notify(notify_uuid)
except Exception as e:
print(e)
print("disconnect from", address)
def main(addresses):
return asyncio.gather(*(connect_to_device(address) for address in addresses))
if __name__ == "__main__":
asyncio.run(main(["A0:9E:1A:B5:E1:03", "A0:9E:1A:B5:EE:10" ])) This code throws an error: If I change the code a bit to make sure the ascyn functions are happy, I get another error as follows: import asyncio
from bleak import BleakClient
notify_uuid = "00002A37-0000-1000-8000-00805F9B34FB"
def callback(characteristic, data):
print(characteristic, data)
async def connect_to_device(address):
print("starting", address, "loop")
async with BleakClient(address, timeout=5.0) as client:
print("connect to", address)
try:
await client.start_notify(notify_uuid, callback)
await asyncio.sleep(10.0)
await client.stop_notify(notify_uuid)
except Exception as e:
print(e)
print("disconnect from", address)
async def main(addresses):
return await asyncio.gather(*(connect_to_device(address) for address in addresses))
if __name__ == "__main__":
asyncio.run(main(["A0:9E:1A:B5:E1:03", "A0:9E:1A:B5:EE:10" ])) error: Is there a better example for connecting to multiple devices? Where does the operation already in progress error originates from and how can I avoid it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yeah, trying to connect to two devices at the same time is usually asking for trouble. Maybe something like this would be better? async def connect_to_device(address, lock):
print("starting", address, "loop")
try:
with lock:
client = BleakClient(address, timeout=5.0)
await client.connect()
try:
print("connected to", address)
await client.start_notify(notify_uuid, callback)
await asyncio.sleep(10.0)
finally:
await client.disconnect()
print("disconnect from", address)
except Exception as e:
print(e)
async def main(addresses):
lock = asyncio.Lock()
return await asyncio.gather(
*(connect_to_device(address, lock) for address in addresses)
) |
Beta Was this translation helpful? Give feedback.
Yeah, trying to connect to two devices at the same time is usually asking for trouble. Maybe something like this would be better?