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

ERROR:root:A message handler raised an exception: 'org.bluez.Device1'. #1404

Closed
DictXiong opened this issue Aug 28, 2023 · 3 comments
Closed
Labels
Backend: BlueZ Issues and PRs relating to the BlueZ backend bug Something isn't working

Comments

@DictXiong
Copy link

DictXiong commented Aug 28, 2023

  • bleak version: 0.20.2
  • Python version: 3.10.12
  • Operating System: Ubuntu 22.04.2 LTS
  • BlueZ version (bluetoothctl -v) in case of Linux: 5.64

Description

I'm trying to connect to multiple BLE peripherals in one program, which needs to repeatedly read a characteristic from peripherals. I wrote my program referring to https://github.com/hbldh/bleak/blob/develop/examples/two_devices.py. When the first attempt to connect fails and the second attempt is made, the program will report errors.

What I Did

Minimal reproducible example:

import sys
import asyncio
import contextlib
from bleak import BleakScanner, BleakClient, exc

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

gatt_report = "00002a00-0000-1000-8000-00805f9b34fb"


async def ble_access(name, address, lock):
    def named_print(*args, **kwargs):
        eprint(f"[{name}]", *args, **kwargs)
    named_print(f"Job started for {address}")
    while True:
        await asyncio.sleep(3)
        try:
            async with contextlib.AsyncExitStack() as stack:
                async with lock:
                    named_print(f"Scanning...")
                    device = await BleakScanner.find_device_by_address(address, timeout=10)
                    if device is None:
                        raise exc.BleakDeviceNotFoundError(f"Device {address} not found")
                    named_print(f"Found {device.name}, connecting...")
                    client = BleakClient(device, timeout=32)
                    await stack.enter_async_context(client)
                    named_print(f"Connected")
                while True:
                    if not client.is_connected:
                        named_print(f"Disconnected")
                        break
                    await asyncio.sleep(3)
                    try:
                        async with lock:
                            raw_data = await client.read_gatt_char(gatt_report)
                    except Exception as e:
                        named_print(f"Failed reading data. Error {type(e)}: {str(e)}")
                        continue
                    print(raw_data)
                    await asyncio.sleep(60)
        except Exception as e:
            named_print(f"Failed connecting. Error {type(e)}: {str(e)}")
            continue


if __name__ == "__main__":
    tasks = []
    lock = asyncio.Lock()
    for sensor in ['test0,8C:F6:81:59:EB:C8', 'test1,8C:F6:81:58:E1:CD', 'test2,B4:35:22:B8:88:C5']:
        name, address = sensor.split(",")
        tasks.append(ble_access(name, address, lock))
    if tasks:
        asyncio.run(asyncio.wait(tasks))

Logs

Outputs:

[test0] Job started for 8C:F6:81:59:EB:C8
[test2] Job started for B4:35:22:B8:88:C5
[test1] Job started for 8C:F6:81:58:E1:CD
[test0] Scanning...
[test0] Found Blitz_LEE-59EBC8, connecting...
[test0] Failed connecting. Error <class 'asyncio.exceptions.TimeoutError'>:
[test2] Scanning...
[test2] Found BlitzLEE-88C5, connecting...
[test2] Failed connecting. Error <class 'bleak.exc.BleakError'>: failed to discover services, device disconnected
[test1] Scanning...
[test1] Found Blitz_LEE-58E1CD, connecting...
[test1] Failed connecting. Error <class 'asyncio.exceptions.TimeoutError'>:
[test0] Scanning...
ERROR:root:A message handler raised an exception: 'org.bluez.Device1'.
Traceback (most recent call last):
  File "src/dbus_fast/message_bus.py", line 811, in dbus_fast.message_bus.BaseMessageBus._process_message
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 854, in _parse_msg
    condition_callback()
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 709, in callback
    self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
KeyError: 'org.bluez.Device1'

ERROR:root:A message handler raised an exception: 'org.bluez.Device1'.
Traceback (most recent call last):
  File "src/dbus_fast/message_bus.py", line 811, in dbus_fast.message_bus.BaseMessageBus._process_message
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 854, in _parse_msg
    condition_callback()
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 709, in callback
    self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
KeyError: 'org.bluez.Device1'

ERROR:root:A message handler raised an exception: 'org.bluez.Device1'.
Traceback (most recent call last):
  File "src/dbus_fast/message_bus.py", line 811, in dbus_fast.message_bus.BaseMessageBus._process_message
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 854, in _parse_msg
    condition_callback()
  File "/usr/local/lib/python3.10/dist-packages/bleak/backends/bluezdbus/manager.py", line 709, in callback
    self._properties[device_path][defs.DEVICE_INTERFACE][property_name]
KeyError: 'org.bluez.Device1'

The error message repeats many times, but the program is still running.

Thanks if anyone can help me.

@DictXiong
Copy link
Author

In addition: is this the right way to keep multiple active connections?

@dlech dlech added bug Something isn't working Backend: BlueZ Issues and PRs relating to the BlueZ backend labels Aug 28, 2023
@dlech
Copy link
Collaborator

dlech commented Aug 28, 2023

Thanks for the report. I think this should be fixed by #1399.

It looks like a reasonable way to maintain connections... although for this kind of polling, it could be better for battery life to disconnect and reconnect every time you want to read.

@DictXiong
Copy link
Author

DictXiong commented Aug 30, 2023

I tried the develop branch and didn't see that error again. Seems it has been successfully fixed. Thank you!

Those peripherals are made by myself. They consume less power in connections than in advertisements (thanks to the feature of BLE connection latency). That's why I'd like to maintain connections. Thanks for your suggestions!

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 bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants