Debian Codegraph @

src/bleak_retry_connector/dbus.py

raw
1 from __future__ import annotations
2
3 import contextlib
4
5 from bleak.backends.bluezdbus import defs
6 from bleak.backends.device import BLEDevice
7 from dbus_fast.message import Message
8
9 from .bleak_manager import get_global_bluez_manager_with_timeout
10 from .const import DISCONNECT_TIMEOUT
11 from .util import asyncio_timeout
12
13
14 async def disconnect_devices(devices: list[BLEDevice]) -> None:
15 """Disconnect a list of devices."""
16 valid_devices = [
17 device
18 for device in devices
19 if isinstance(device.details, dict) and "path" in device.details
20 ]
21 if not valid_devices:
22 return
23 if not (bluez_manager := await get_global_bluez_manager_with_timeout()):
24 return
25 bus = bluez_manager._bus
26 for device in valid_devices:
27 # https://bleak.readthedocs.io/en/latest/troubleshooting.html#id4
28 # Force-disconnect the device via BlueZ. Removing the device to
29 # clear its disk cache is handled separately by clear_cache().
30 with contextlib.suppress(Exception):
31 async with asyncio_timeout(DISCONNECT_TIMEOUT):
32 await bus.call(
33 Message(
34 destination=defs.BLUEZ_SERVICE,
35 path=device.details["path"],
36 interface=defs.DEVICE_INTERFACE,
37 member="Disconnect",
38 )
39 )