Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled success response from org.bluez.Adapter1.ConnectDevice #806

Closed
robbawebba opened this issue Apr 15, 2022 · 6 comments · Fixed by #902
Closed

Unhandled success response from org.bluez.Adapter1.ConnectDevice #806

robbawebba opened this issue Apr 15, 2022 · 6 comments · Fixed by #902
Labels
Backend: BlueZ Issues and PRs relating to the BlueZ backend

Comments

@robbawebba
Copy link

  • bleak version: 0.14.2
  • Python version: Python 3.10.4
  • Operating System: Fedora 35
  • BlueZ version (bluetoothctl -v) in case of Linux: bluetoothctl: 5.64

Description

While trying to connect to a BLE device using the BleakClient.connect, the bleak library always raises a BleakError exception saying "Connection was not successful!", but I am able to confirm the connection succeeded otherwise using bluetoothctl and the logs on my BLE device.

After logging the result of the org.bluez.Adapter1.ConnectDevice method, and reviewing the documentation, it seems that this method returns a successful response that is not handled in the BleakClient.connect method. Instead, the connect method waits for the Connected property to change to true.

The DBus client never receives a PropertyChanged notification for the Connected property. I'm not sure if this is normal behavior while using the ConnectDevice DBus method, or if this is an issue only I am facing. However, I have confirmed with the bluetoothctl info command that the device is connected.

What I Did

Here's a minimal example to reproduce the issue:

import asyncio
import logging
from bleak import BleakScanner, BleakClient

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
logging.getLogger("bleak.backends.bluezdbus.client").setLevel(logging.DEBUG)
logger = logging.getLogger()
async def main():
    devices = await BleakScanner.discover()
    for d in devices:
        if d.name == "DeviceName:
            connection = BleakClient(d)
            try:
                connected = await connection.connect()
                if connected:
                    logger.info("Connection Successful!")
                else:
                    logger.warning("Connection failed :(")
            except Exception as exc:
                logger.warning(f"Exception during connection: {exc}")

asyncio.run(main())

I also added two changes to help with logging while debugging this issue:

  • Logging the reply from ConnectDevice to see the details
  • asyncio.sleep for 15 seconds before checking self._is_connected in the hopes that the client just needs to wait a bit for the property to change.

Here are the logs from running this example:

2022-04-14 17:45:37,541 bleak.backends.bluezdbus.client DEBUG:Connecting to device @ 30:95:87:EC:2E:EA with hci0
2022-04-14 17:45:37,559 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.Properties.PropertiesChanged (/org/bluez/hci0/dev_30_95_87_EC_2E_EA): ['org.bluez.Device1', {}, ['RSSI']]
2022-04-14 17:45:37,561 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesRemoved (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006/char0007/desc0009', ['org.freedesktop.DBus.Properties', 'org.freedesktop.DBus.Introspectable', 'org.bluez.GattDescriptor1']]
2022-04-14 17:45:37,562 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesRemoved (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006/char0007', ['org.freedesktop.DBus.Properties', 'org.freedesktop.DBus.Introspectable', 'org.bluez.GattCharacteristic1']]
2022-04-14 17:45:37,564 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesRemoved (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006', ['org.freedesktop.DBus.Properties', 'org.freedesktop.DBus.Introspectable', 'org.bluez.GattService1']]
2022-04-14 17:45:37,678 bleak.backends.bluezdbus.client DEBUG:org.bluez.Device1 object not found, trying org.bluez.Adapter1.ConnectDevice (/org/bluez/hci0/dev_30_95_87_EC_2E_EA)
2022-04-14 17:45:40,958 bleak.backends.bluezdbus.client WARNING:REPLY::: message_type:MessageType.METHOD_RETURN error_name:None body:['/org/bluez/hci0/dev_30_95_87_EC_2E_EA']
2022-04-14 17:45:42,332 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattService1': {'UUID': <dbus_next.signature.Variant ('s', 00001801-0000-1000-8000-00805f9b34fb)>, 'Device': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA)>, 'Primary': <dbus_next.signature.Variant ('b', True)>, 'Includes': <dbus_next.signature.Variant ('ao', [])>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,334 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006/char0007', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 00002a05-0000-1000-8000-00805f9b34fb)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Notifying': <dbus_next.signature.Variant ('b', False)>, 'Flags': <dbus_next.signature.Variant ('as', ['indicate'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,336 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006/char0007/desc0009', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattDescriptor1': {'UUID': <dbus_next.signature.Variant ('s', 00002902-0000-1000-8000-00805f9b34fb)>, 'Characteristic': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006/char0007)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,337 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattService1': {'UUID': <dbus_next.signature.Variant ('s', 6e400001-b5a3-f393-e0a9-e50e24dcca9e)>, 'Device': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA)>, 'Primary': <dbus_next.signature.Variant ('b', True)>, 'Includes': <dbus_next.signature.Variant ('ao', [])>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,339 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b/char020c', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 6e400002-b5a3-f393-e0a9-e50e24dcca9e)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Flags': <dbus_next.signature.Variant ('as', ['write'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,340 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b/char020e', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 6e400003-b5a3-f393-e0a9-e50e24dcca9e)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Notifying': <dbus_next.signature.Variant ('b', False)>, 'Flags': <dbus_next.signature.Variant ('as', ['read', 'notify'])>, 'NotifyAcquired': <dbus_next.signature.Variant ('b', False)>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,341 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b/char020e/desc0210', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattDescriptor1': {'UUID': <dbus_next.signature.Variant ('s', 00002902-0000-1000-8000-00805f9b34fb)>, 'Characteristic': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service020b/char020e)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,342 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattService1': {'UUID': <dbus_next.signature.Variant ('s', 0000180a-0000-1000-8000-00805f9b34fb)>, 'Device': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA)>, 'Primary': <dbus_next.signature.Variant ('b', True)>, 'Includes': <dbus_next.signature.Variant ('ao', [])>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,343 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211/char0212', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 00002a26-0000-1000-8000-00805f9b34fb)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Flags': <dbus_next.signature.Variant ('as', ['read'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,343 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211/char0214', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 00002a27-0000-1000-8000-00805f9b34fb)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Flags': <dbus_next.signature.Variant ('as', ['read'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,344 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211/char0216', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 00002a29-0000-1000-8000-00805f9b34fb)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Flags': <dbus_next.signature.Variant ('as', ['read'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,345 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211/char0218', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', 00002a24-0000-1000-8000-00805f9b34fb)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0211)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Flags': <dbus_next.signature.Variant ('as', ['read'])>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,345 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service021a', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattService1': {'UUID': <dbus_next.signature.Variant ('s', d6166e60-12bd-43e7-a7fe-85836a3363cd)>, 'Device': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA)>, 'Primary': <dbus_next.signature.Variant ('b', True)>, 'Includes': <dbus_next.signature.Variant ('ao', [])>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,346 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service021a/char021b', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattCharacteristic1': {'UUID': <dbus_next.signature.Variant ('s', d6166e61-12bd-43e7-a7fe-85836a3363cd)>, 'Service': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service021a)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>, 'Notifying': <dbus_next.signature.Variant ('b', False)>, 'Flags': <dbus_next.signature.Variant ('as', ['notify'])>, 'NotifyAcquired': <dbus_next.signature.Variant ('b', False)>, 'MTU': <dbus_next.signature.Variant ('q', 517)>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,346 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service021a/char021b/desc021d', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattDescriptor1': {'UUID': <dbus_next.signature.Variant ('s', 00002902-0000-1000-8000-00805f9b34fb)>, 'Characteristic': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA/service021a/char021b)>, 'Value': <dbus_next.signature.Variant ('ay', b'')>}, 'org.freedesktop.DBus.Properties': {}}]
2022-04-14 17:45:42,347 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.Properties.PropertiesChanged (/org/bluez/hci0/dev_30_95_87_EC_2E_EA): ['org.bluez.Device1', {'UUIDs': <dbus_next.signature.Variant ('as', ['00001800-0000-1000-8000-00805f9b34fb', '00001801-0000-1000-8000-00805f9b34fb', '0000180a-0000-1000-8000-00805f9b34fb', '6e400001-b5a3-f393-e0a9-e50e24dcca9e', 'd6166e60-12bd-43e7-a7fe-85836a3363cd'])>, 'ServicesResolved': <dbus_next.signature.Variant ('b', True)>}, []]
2022-04-14 17:45:42,516 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.Properties.PropertiesChanged (/org/bluez/hci0/dev_30_95_87_EC_2E_EA): ['org.bluez.Device1', {'Name': <dbus_next.signature.Variant ('s', DeviceName)>, 'Alias': <dbus_next.signature.Variant ('s', DeviceName)>}, []]
2022-04-14 17:45:55,972 bleak.backends.bluezdbus.client DEBUG:_cleanup_all(/org/bluez/hci0/dev_30_95_87_EC_2E_EA)
Traceback (most recent call last):
  File "/home/rob/scripts/bleak_ble_scan.py", line 21, in <module>
    asyncio.run(main())
  File "/usr/lib64/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib64/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/home/rob/scripts/bleak_ble_scan.py", line 15, in main
    connected = await client.connect()
  File "/home/rob/virtualenvs/py3dev/lib/python3.10/site-packages/bleak/backends/bluezdbus/client.py", line 310, in connect
    raise BleakError(
bleak.exc.BleakError: Connection was not successful! (/org/bluez/hci0/dev_30_95_87_EC_2E_EA)

After this exception, bluetoothctl still confirms that the device is connected:

[DeviceName]# info
Device 30:95:87:EC:2E:EA (public)
	Name: DeviceName
	Alias: DeviceName
	Paired: no
	Trusted: no
	Blocked: no
	Connected: yes
	LegacyPairing: no
	UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
	UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
	UUID: Device Information        (0000180a-0000-1000-8000-00805f9b34fb)
	UUID: Nordic UART Service       (6e400001-b5a3-f393-e0a9-e50e24dcca9e)
	UUID: Vendor specific           (d6166e60-12bd-43e7-a7fe-85836a3363cd)

Another strange datapoint is the bluetoothctl logs also do not log when the Connected property changes. But when I reset my BLE peripheral, I see a log showing when the Connected property changes to false.

Let me know if you need any more information, I'm happy to help in any way.

@dlech
Copy link
Collaborator

dlech commented Apr 15, 2022

I'm not sure if this is normal behavior while using the ConnectDevice DBus method, or if this is an issue only I am facing.

Since this feature is behind the --experimental flag in BlueZ, I imagine this code path has been called quite rarely, if ever.

it seems that this method returns a successful response that is not handled in the BleakClient.connect method. Instead, the connect method waits for the Connected property to change to true.

I see what you mean. I suppose the first thing to do would be to read the return value from the ConnectDevice method and make sure it is the same object path as the one we already have for the device. If it isn't that would explain the bug in Bleak. If it is the same, then I think this could be a BlueZ bug that it is not sending the property change signal when the device connects.

@dlech dlech added the Backend: BlueZ Issues and PRs relating to the BlueZ backend label Apr 15, 2022
@robbawebba
Copy link
Author

Thanks for your input! I think your hunch is right - The path returned from ConnectDevice matches the object path to which I'm connecting, so this may be some strange and unexpected behavior from bluetoothd. Relevant logs:

2022-04-14 17:45:40,958 bleak.backends.bluezdbus.client WARNING:REPLY::: message_type:MessageType.METHOD_RETURN error_name:None body:['/org/bluez/hci0/dev_30_95_87_EC_2E_EA']
2022-04-14 17:45:42,332 bleak.backends.bluezdbus.client DEBUG:received D-Bus signal: org.freedesktop.DBus.ObjectManager.InterfacesAdded (/): ['/org/bluez/hci0/dev_30_95_87_EC_2E_EA/service0006', {'org.freedesktop.DBus.Introspectable': {}, 'org.bluez.GattService1': {'UUID': <dbus_next.signature.Variant ('s', 00001801-0000-1000-8000-00805f9b34fb)>, 'Device': <dbus_next.signature.Variant ('o', /org/bluez/hci0/dev_30_95_87_EC_2E_EA)>, 'Primary': <dbus_next.signature.Variant ('b', True)>, 'Includes': <dbus_next.signature.Variant ('ao', [])>}, 'org.freedesktop.DBus.Properties': {}}]

After a bit of searching in the linux-bluetooth mailing list, it seems like this lack of a connection signal may be intended. The developers seems to want to keep this object state internal to the bluetooth daemon. Here's the original patch, and there are a couple of revisions after this.

Do you know of a way I can "force" my application to use the other code path of connecting using the org.bluez.Device1.Connect method? It seems like this approach would be more reliable / is the non-experimental way of connecting. I'm kind of surprised that the desired object path does not exist in the ObjectManager despite having just scanned and found this device.

@dlech
Copy link
Collaborator

dlech commented Apr 15, 2022

Bleak should only be calling ConnectDevice if Connect fails. The reason ConnectDevice exists is that, like you have observed, that BlueZ can drop a device from its list of known devices in the time between scanning in connecting. I think this mostly happens with devices with random addresses that change their address.

#713 (comment) suggests that ConnectDevice is not meant to be used normally. So maybe the solution is to remove the use of ConnectDevice from Bleak. If connecting fails (i.e. because the device has been removed from BlueZ), then users will just have to scan again then try to connect again.

@robbawebba
Copy link
Author

I've been playing around with different scanning/connection approaches, and found that I can connect much more reliably when I scan using the BleakScanner.start() method as opposed to discover(). Judging by the logs, the BlueZ client backend connects using the Device1.Connect method when the device is found by scanning with start. I never call scanner.stop() in my example, not sure if that makes a difference for how the ObjectManager maintains its list of objects.

So for my immediate use case, I'll stick with this new approach. I agree that ConnectDevice may cause more problems than it solves.

import asyncio
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
logging.getLogger("bleak.backends.bluezdbus.client").setLevel(logging.INFO)
logger = logging.getLogger()

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

async def scan_result_cb(device: BLEDevice, advertisement_data: AdvertisementData):
    logger.info(f"[{device.name}] ADDR:{device.address} RSSI:{device.rssi}")
    if device.name == "DeviceName":
        client = BleakClient(device)
        try:
            connected = await client.connect()
            if not connected:
                logger.error("Not connected :(")
                return
        except Exception as e:
            logger.error(str(e))
            return
        
        logger.info("connected!! Available services:")
        services = await client.get_services()
        for s in services:
            logger.info(s)
        await client.disconnect()

async def scan_with_callback():
    scanner = BleakScanner()
    scanner.register_detection_callback(scan_result_cb)

    await scanner.start()
    while True:
        await asyncio.sleep(10.0)
        logger.debug("still scanning...")

asyncio.run(scan_with_callback())

@dlech
Copy link
Collaborator

dlech commented Apr 15, 2022

Generally, you want to stop scanning whenever possible so you don't drain the battery of any BLE devices in the vicinity. Since the delay in discover() is too long, you could try using find_device_by_filter() instead. It will return (and stop scanning) as soon as the device is discovered.

dlech added a commit that referenced this issue Jul 26, 2022
This fixes a number of bugs by moving the `BleakClient` state management
to the new global BlueZ manager object.

- Calling "GetManagedObjects" each time we connected caused performance
  issues. Fixes #500.
- Calling "ConnectDevice" didn't work as expected and has been removed/
  Fixes #806.
- BleakClient didn't handle "InterfacesRemoved" which resulted in an
  invalid service dictionary in some cases. Fixes #882.
@dlech
Copy link
Collaborator

dlech commented Jul 26, 2022

The fallback to "ConnectDevice" is removed in #902 (along with many other changes). Can you please test?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Backend: BlueZ Issues and PRs relating to the BlueZ backend
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants