bleak: Bluez backend: Can't connect to device returned from detection callback

  • bleak version: 0.10.0
  • Python version: 3.7.3
  • Operating System: raspbian buster
  • BlueZ version (bluetoothctl -v) in case of Linux: 5.50

Description

“path” isn’t set in the device in the detection callback and crashes if you try and use the code in the following way:

import asyncio
from bleak import BleakScanner, BleakClient
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData
import logging

logging.basicConfig()

search_name = "Mo03F4000B"

class Test:
    def __init__(self):
        self.bt_client = None
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.run())
        
    def simple_callback(self, device: BLEDevice, advertisement_data: AdvertisementData):
        if search_name in device.name:
            print(f"Found {device}")
            self.bt_client = device
        
    async def run(self):
        scanner = BleakScanner()
        scanner.register_detection_callback(self.simple_callback)

        while self.bt_client is None:
            print(self.bt_client)
            await scanner.start()
            await asyncio.sleep(1.0)
            await scanner.stop()
        print(f"Connecting to {self.bt_client}")
        async with BleakClient(self.bt_client) as client:
            svcs = await client.get_services()
            print(f"{svcs}")

t = Test()

Output:

Found D5:D5:27:2F:0A:B2: Mo03F4000B000000000
Connecting to D5:D5:27:2F:0A:B2: Mo03F4000B000000000
Traceback (most recent call last):
  File "detection_callback.py", line 46, in <module>
    t = Test()
  File "detection_callback.py", line 25, in __init__
    loop.run_until_complete(self.run())
  File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "detection_callback.py", line 42, in run
    async with BleakClient(self.bt_client) as client:
  File "/home/pi/.local/lib/python3.7/site-packages/bleak/backends/bluezdbus/client.py", line 58, in __init__
    self._device_path = address_or_ble_device.details["path"]
KeyError: 'path'

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 20 (9 by maintainers)

Commits related to this issue

Most upvoted comments

I think I see what is going on now. I think the scanner is stopping and restarting while a device is connected. This can trigger a race condition where a “PropertiesChanged” signal is received before “GetManagedObjects” returns in the scanner start method. I’ve added a fix for this in the dbus-next-2 branch.