BleakDBusError 'Operation already in progress' - is it possible to stop the BleakScanner after a timeout #1629
-
DescriptionI have a gateway continually connecting to 4 of the same type of device in a round-robin fashion. I have a BleakScanner with a timeout. The timeout still occured after returning from the
My question is - is it possible to cancel the scanning without having to restart the entire process? What I DidI ran the following code and get the log from the async def scan(
device_id, timeout=SCAN_TIMEOUT_S
) -> Optional[Tuple[BLEDevice, Set[str]]]:
try:
filter = get_device_filter(device_id)
return await asyncio.wait_for(_scan_with_timeout(filter, device_id), timeout)
except asyncio.TimeoutError:
logger.info(
f"Timeout reached. Device {device_id} not found after {timeout} seconds"
)
return None
async def _scan_with_timeout(filter, device_id):
seen = set()
async with BleakScanner() as scanner:
async for device, advertisement in scanner.advertisement_data():
found_device_id = get_device_id(device)
if found_device_id and found_device_id.startswith(filter):
logger.info(f"Found {device!r}")
logger.debug(f"{advertisement!r}")
logger.debug(f"platform_data: {advertisement.platform_data}")
logger.debug(f"service_data: {advertisement.service_data}")
seen.add(found_device_id)
if found_device_id == device_id:
logger.info(f"Connecting")
return (device, seen) LogsThese are the logs I have, I don't have any further in depth logs yet.
These two lines are the ones that are the problem:
The "Connecting" log occurs just before the return of the function. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
This sounds relevant: #691 (comment) |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
asyncio.wait_for()
does not wait for canceled tasks to complete. You may have better luck withasyncio.timeout()
. Otherwise you will need to protect the scanner with anasyncio.Lock()
to prevent concurrent scanning.