Reputation: 388
Problem: Connecting to a BTLE device succeeds about 1 out of 10 times. How can I improve this and reliably connect to the device?
I have a Sensirion SHT41x that I want to access via Bluetooth from my Windows laptop. This does work (see script below), but only about 1 out of 10 times. When It does not work, it returns
raise BleakDeviceNotFoundError(
bleak.exc.BleakDeviceNotFoundError: Device with address ... was not found.
The device is about half a meter from my laptop. What can I do to fix this?
So far tried:
Here the simple script:
import asyncio
from bleak import BleakClient
address = "..."
async def connect_device():
async with BleakClient(address) as client:
connected = await client.is_connected()
print(f"Connected: {connected}")
disconnected = await client.disconnect()
print(f"Disonnected: {disconnected}")
asyncio.run(connect_device())
EDIT:
I added re-tries and exception handling according to Klaus D.'s suggestion:
import time
import asyncio
from bleak import BleakClient
from loguru import logger
async def just_connect(mac):
async with BleakClient(mac) as client:
pass
await asyncio.sleep(2)
mac = "C5:5A:42:A4:3C:80"
tries = 10
results = {}
start = time.time()
timeout = 12
for try_ in range(tries):
try:
await asyncio.wait_for(just_connect(mac), timeout)
logger.info(f"try {try_} succeeded")
except Exception as e:
logger.info(f"try {try_} failed due to {type(e).__name__}: {e}")
the result does not completely fail always as shown in the logs below, but often enough to defeat the whole purpose of IoT BLE.
2024-06-02 15:25:25.346 | INFO | __main__:<module>:24 - try 0 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
2024-06-02 15:25:35.366 | INFO | __main__:<module>:24 - try 1 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
2024-06-02 15:25:45.377 | INFO | __main__:<module>:24 - try 2 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
2024-06-02 15:25:55.907 | INFO | __main__:<module>:24 - try 3 failed due to TimeoutError:
2024-06-02 15:26:05.941 | INFO | __main__:<module>:24 - try 4 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
2024-06-02 15:26:17.953 | INFO | __main__:<module>:24 - try 5 failed due to TimeoutError:
2024-06-02 15:26:27.951 | INFO | __main__:<module>:24 - try 6 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
2024-06-02 15:26:39.963 | INFO | __main__:<module>:24 - try 7 failed due to TimeoutError:
2024-06-02 15:26:51.971 | INFO | __main__:<module>:24 - try 8 failed due to TimeoutError:
2024-06-02 15:27:01.978 | INFO | __main__:<module>:24 - try 9 failed due to BleakDeviceNotFoundError: Device with address C5:5A:42:A4:3C:80 was not found.
Upvotes: 0
Views: 113