| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import logging |
| 6 |
import time |
| 7 |
from collections.abc import Callable, Generator |
| 8 |
from dataclasses import dataclass |
| 9 |
from enum import Enum |
| 10 |
from functools import partial |
| 11 |
from typing import Any |
| 12 |
|
| 13 |
from bleak import BleakGATTServiceCollection |
| 14 |
from bleak.backends.device import BLEDevice |
| 15 |
from bleak.exc import BleakError |
| 16 |
|
| 17 |
from .bleak_manager import ( |
| 18 |
get_global_bluez_manager_sync, |
| 19 |
get_global_bluez_manager_with_timeout, |
| 20 |
) |
| 21 |
from .const import ( |
| 22 |
DISCONNECT_TIMEOUT, |
| 23 |
IS_LINUX, |
| 24 |
NO_RSSI_VALUE, |
| 25 |
REAPPEAR_WAIT_INTERVAL, |
| 26 |
RSSI_SWITCH_THRESHOLD, |
| 27 |
) |
| 28 |
from .util import asyncio_timeout |
| 29 |
|
| 30 |
if IS_LINUX: |
| 31 |
from dbus_fast.message import Message |
| 32 |
|
| 33 |
_LOGGER = logging.getLogger(__name__) |
| 34 |
|
| 35 |
|
| 36 |
if IS_LINUX: |
| 37 |
with contextlib.suppress(ImportError): # pragma: no cover |
| 38 |
from bleak.backends.bluezdbus import defs # pragma: no cover |
| 39 |
from bleak.backends.bluezdbus.manager import ( # pragma: no cover |
| 40 |
BlueZManager, |
| 41 |
DeviceWatcher, |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
class AllocationChange(Enum): |
| 46 |
"""Allocation change.""" |
| 47 |
|
| 48 |
ALLOCATED = 1 |
| 49 |
RELEASED = 2 |
| 50 |
|
| 51 |
|
| 52 |
@dataclass(slots=True) |
| 53 |
class AllocationChangeEvent: |
| 54 |
change: AllocationChange |
| 55 |
path: str | None # D-Bus object path of the device |
| 56 |
adapter: str # Adapter/Controller (hciX) |
| 57 |
address: str # Address of the remote BLE device |
| 58 |
|
| 59 |
|
| 60 |
@dataclass(slots=True) |
| 61 |
class Allocations: |
| 62 |
adapter: str # Adapter/Controller (hciX) |
| 63 |
slots: int # Number of slots |
| 64 |
free: int # Number of free slots |
| 65 |
allocated: list[str] # Addresses of connected devices |
| 66 |
|
| 67 |
|
| 68 |
def device_source(device: BLEDevice) -> str | None: |
| 69 |
"""Return the device source.""" |
| 70 |
return _device_details_value_or_none(device, "source") |
| 71 |
|
| 72 |
|
| 73 |
def _device_details_value_or_none(device: BLEDevice, key: str) -> Any | None: |
| 74 |
"""Return a value from device details or None.""" |
| 75 |
details = device.details |
| 76 |
if not isinstance(details, dict) or key not in details: |
| 77 |
return None |
| 78 |
key_value: str = device.details[key] |
| 79 |
return key_value |
| 80 |
|
| 81 |
|
| 82 |
def adapter_from_path(path: str) -> str: |
| 83 |
"""Get the adapter from a ble device path.""" |
| 84 |
return path.split("/")[3] |
| 85 |
|
| 86 |
|
| 87 |
def address_from_path(path: str) -> str: |
| 88 |
"""Get the address from a ble device path.""" |
| 89 |
return path.split("/")[-1].removeprefix("dev_").replace("_", ":").upper() |
| 90 |
|
| 91 |
|
| 92 |
def path_from_ble_device(device: BLEDevice) -> str | None: |
| 93 |
"""Get the adapter from a ble device.""" |
| 94 |
return _device_details_value_or_none(device, "path") |
| 95 |
|
| 96 |
|
| 97 |
def _on_characteristic_value_changed(*args: Any, **kwargs: Any) -> None: |
| 98 |
"""Dummy callback for registering characteristic value changed.""" |
| 99 |
|
| 100 |
|
| 101 |
class BleakSlotManager: |
| 102 |
"""A class to manage the connection slots.""" |
| 103 |
|
| 104 |
def __init__(self) -> None: |
| 105 |
"""Initialize the class.""" |
| 106 |
self._adapter_slots: dict[str, int] = {} |
| 107 |
self._allocations_by_adapter: dict[str, dict[str, DeviceWatcher]] = {} |
| 108 |
self._manager: BlueZManager | None = None |
| 109 |
self._callbacks: set[Callable[[AllocationChangeEvent], None]] = set() |
| 110 |
|
| 111 |
async def async_setup(self) -> None: |
| 112 |
"""Set up the class.""" |
| 113 |
self._manager = await get_global_bluez_manager_with_timeout() |
| 114 |
|
| 115 |
def diagnostics(self) -> dict[str, Any]: |
| 116 |
"""Return diagnostics.""" |
| 117 |
return { |
| 118 |
"manager": self._manager is not None, |
| 119 |
"adapter_slots": self._adapter_slots, |
| 120 |
"allocations_by_adapter": { |
| 121 |
adapter: self._get_allocations(adapter) |
| 122 |
for adapter in self._adapter_slots |
| 123 |
}, |
| 124 |
} |
| 125 |
|
| 126 |
def get_allocations(self, adapter: str) -> Allocations: |
| 127 |
"""Get the allocations.""" |
| 128 |
slots = self._adapter_slots.get(adapter, 0) |
| 129 |
allocated: list[str] = [] |
| 130 |
if adapter in self._allocations_by_adapter: |
| 131 |
allocated = [ |
| 132 |
address_from_path(path) |
| 133 |
for path in self._allocations_by_adapter[adapter] |
| 134 |
] |
| 135 |
free = slots - len(allocated) |
| 136 |
return Allocations(adapter, slots, free, allocated) |
| 137 |
|
| 138 |
def _get_allocations(self, adapter: str) -> list[str]: |
| 139 |
"""Get connected path allocations.""" |
| 140 |
if self._manager is None or adapter not in self._allocations_by_adapter: |
| 141 |
return [] |
| 142 |
return list(self._allocations_by_adapter[adapter]) |
| 143 |
|
| 144 |
def remove_adapter(self, adapter: str) -> None: |
| 145 |
"""Remove an adapter.""" |
| 146 |
del self._adapter_slots[adapter] |
| 147 |
watchers = self._allocations_by_adapter[adapter] |
| 148 |
if self._manager is None: |
| 149 |
return |
| 150 |
for watcher in watchers.values(): |
| 151 |
self._manager.remove_device_watcher(watcher) |
| 152 |
del self._allocations_by_adapter[adapter] |
| 153 |
|
| 154 |
def register_allocation_callback( |
| 155 |
self, callback: Callable[[AllocationChangeEvent], None] |
| 156 |
) -> Callable[[], None]: |
| 157 |
"""Register a callback for when allocations change.""" |
| 158 |
self._callbacks.add(callback) |
| 159 |
return partial(self.unregister_allocation_callback, callback) |
| 160 |
|
| 161 |
def unregister_allocation_callback( |
| 162 |
self, callback: Callable[[AllocationChangeEvent], None] |
| 163 |
) -> None: |
| 164 |
"""Unregister a callback.""" |
| 165 |
self._callbacks.discard(callback) |
| 166 |
|
| 167 |
def register_adapter(self, adapter: str, slots: int) -> None: |
| 168 |
"""Register an adapter.""" |
| 169 |
self._allocations_by_adapter[adapter] = {} |
| 170 |
self._adapter_slots[adapter] = slots |
| 171 |
if self._manager is None: |
| 172 |
return |
| 173 |
for path, device in self._manager._properties.items(): |
| 174 |
if ( |
| 175 |
defs.DEVICE_INTERFACE in device |
| 176 |
and device[defs.DEVICE_INTERFACE].get("Connected") |
| 177 |
and adapter_from_path(path) == adapter |
| 178 |
): |
| 179 |
self._allocate_and_watch_slot(path) |
| 180 |
|
| 181 |
def _allocate_and_watch_slot(self, path: str) -> None: |
| 182 |
"""Setup a device watcher.""" |
| 183 |
assert self._manager is not None # nosec |
| 184 |
adapter = adapter_from_path(path) |
| 185 |
allocations = self._allocations_by_adapter[adapter] |
| 186 |
|
| 187 |
def _on_device_connected_changed(connected: bool) -> None: |
| 188 |
if not connected: |
| 189 |
self._release_slot(path) |
| 190 |
|
| 191 |
allocations[path] = self._manager.add_device_watcher( |
| 192 |
path, |
| 193 |
on_connected_changed=_on_device_connected_changed, |
| 194 |
on_characteristic_value_changed=_on_characteristic_value_changed, |
| 195 |
) |
| 196 |
self._call_callbacks(AllocationChange.ALLOCATED, path) |
| 197 |
|
| 198 |
def release_slot(self, device: BLEDevice) -> None: |
| 199 |
"""Release a slot.""" |
| 200 |
if ( |
| 201 |
self._manager is None |
| 202 |
or not (path := path_from_ble_device(device)) |
| 203 |
or self._manager.is_connected(path) |
| 204 |
): |
| 205 |
return |
| 206 |
self._release_slot(path) |
| 207 |
|
| 208 |
def _release_slot(self, path: str) -> None: |
| 209 |
"""Unconditional release of the slot.""" |
| 210 |
assert self._manager is not None # nosec |
| 211 |
adapter = adapter_from_path(path) |
| 212 |
if adapter not in self._allocations_by_adapter: |
| 213 |
# Adapter was already removed (e.g., unplugged) |
| 214 |
_LOGGER.debug( |
| 215 |
"Cannot release slot for %s: adapter %s not found", path, adapter |
| 216 |
) |
| 217 |
return |
| 218 |
allocations = self._allocations_by_adapter[adapter] |
| 219 |
if watcher := allocations.pop(path, None): |
| 220 |
self._manager.remove_device_watcher(watcher) |
| 221 |
self._call_callbacks(AllocationChange.RELEASED, path) |
| 222 |
|
| 223 |
def _call_callbacks(self, change: AllocationChange, path: str) -> None: |
| 224 |
"""Call the callbacks.""" |
| 225 |
for callback_ in self._callbacks: |
| 226 |
try: |
| 227 |
callback_( |
| 228 |
AllocationChangeEvent( |
| 229 |
change, path, adapter_from_path(path), address_from_path(path) |
| 230 |
) |
| 231 |
) |
| 232 |
except Exception: # pylint |
| 233 |
_LOGGER.exception("Error in callback") |
| 234 |
|
| 235 |
def allocate_slot(self, device: BLEDevice) -> bool: |
| 236 |
"""Allocate a slot.""" |
| 237 |
if ( |
| 238 |
self._manager is None |
| 239 |
or not (path := path_from_ble_device(device)) |
| 240 |
or not (adapter := adapter_from_path(path)) |
| 241 |
or adapter not in self._allocations_by_adapter |
| 242 |
): |
| 243 |
return True |
| 244 |
allocations = self._allocations_by_adapter[adapter] |
| 245 |
if path in allocations: |
| 246 |
# Already connected |
| 247 |
return True |
| 248 |
if len(allocations) >= self._adapter_slots[adapter]: |
| 249 |
_LOGGER.debug( |
| 250 |
"No slots available for %s (used by: %s)", |
| 251 |
path, |
| 252 |
self._get_allocations(adapter), |
| 253 |
) |
| 254 |
return False |
| 255 |
self._allocate_and_watch_slot(path) |
| 256 |
return True |
| 257 |
|
| 258 |
|
| 259 |
async def _get_properties() -> dict[str, dict[str, dict[str, Any]]] | None: |
| 260 |
"""Get the properties.""" |
| 261 |
if bluez_manager := await get_global_bluez_manager_with_timeout(): |
| 262 |
return bluez_manager._properties # pylint: disable=protected-access |
| 263 |
return None |
| 264 |
|
| 265 |
|
| 266 |
def _get_properties_sync() -> dict[str, dict[str, dict[str, Any]]] | None: |
| 267 |
"""Get the properties from an already running BlueZ manager, or None.""" |
| 268 |
if bluez_manager := get_global_bluez_manager_sync(): |
| 269 |
return bluez_manager._properties # pylint: disable=protected-access |
| 270 |
return None |
| 271 |
|
| 272 |
|
| 273 |
async def _get_services_cache() -> dict[str, BleakGATTServiceCollection] | None: |
| 274 |
"""Get the services cache.""" |
| 275 |
if bluez_manager := await get_global_bluez_manager_with_timeout(): |
| 276 |
return bluez_manager._services_cache # pylint: disable=protected-access |
| 277 |
return None |
| 278 |
|
| 279 |
|
| 280 |
async def clear_cache(address: str) -> bool: |
| 281 |
"""Clear the cache for a device.""" |
| 282 |
if not IS_LINUX: |
| 283 |
return False |
| 284 |
caches_cleared: list[str] = [] |
| 285 |
with contextlib.suppress(Exception): |
| 286 |
if not await get_device(address): |
| 287 |
return False |
| 288 |
if (services_cache := await _get_services_cache()) is None: |
| 289 |
_LOGGER.warning( |
| 290 |
"Failed to clear cache for %s because no services cache", address |
| 291 |
) |
| 292 |
return False |
| 293 |
if not (manager := await get_global_bluez_manager_with_timeout()): |
| 294 |
_LOGGER.warning("Failed to clear cache for %s because no manager", address) |
| 295 |
return False |
| 296 |
bluez_path = address_to_bluez_path(address) |
| 297 |
for path in _get_possible_paths(bluez_path): |
| 298 |
if services_cache.pop(path, None): |
| 299 |
caches_cleared.append(path) |
| 300 |
_LOGGER.debug("Cleared cache for %s: %s", address, caches_cleared) |
| 301 |
async with asyncio_timeout(DISCONNECT_TIMEOUT): |
| 302 |
for device_path in caches_cleared: |
| 303 |
# Send since we are going to ignore errors |
| 304 |
# in case the device is already gone |
| 305 |
await manager._bus.send( |
| 306 |
Message( |
| 307 |
destination=defs.BLUEZ_SERVICE, |
| 308 |
path=adapter_path_from_device_path(device_path), |
| 309 |
interface=defs.ADAPTER_INTERFACE, |
| 310 |
member="RemoveDevice", |
| 311 |
signature="o", |
| 312 |
body=[device_path], |
| 313 |
) |
| 314 |
) |
| 315 |
return bool(caches_cleared) |
| 316 |
|
| 317 |
|
| 318 |
async def stop_discovery(adapter_name: str) -> None: |
| 319 |
"""Stop discovery on an adapter. |
| 320 |
|
| 321 |
:param adapter_name: The adapter name (hciX). |
| 322 |
""" |
| 323 |
if manager := await get_global_bluez_manager_with_timeout(): |
| 324 |
adapter_path = f"/org/bluez/{adapter_name}" |
| 325 |
await manager._bus.send( |
| 326 |
Message( |
| 327 |
destination=defs.BLUEZ_SERVICE, |
| 328 |
path=adapter_path, |
| 329 |
interface=defs.ADAPTER_INTERFACE, |
| 330 |
member="StopDiscovery", |
| 331 |
) |
| 332 |
) |
| 333 |
else: |
| 334 |
_LOGGER.error( |
| 335 |
"Failed to stop discovery for %s because no manager", adapter_name |
| 336 |
) |
| 337 |
|
| 338 |
|
| 339 |
def adapter_path_from_device_path(device_path: str) -> str: |
| 340 |
""" |
| 341 |
Scrape the adapter path from a D-Bus device path. |
| 342 |
|
| 343 |
Args: |
| 344 |
device_path: The D-Bus object path of the device. |
| 345 |
|
| 346 |
Returns: |
| 347 |
A D-Bus object path of the adapter. |
| 348 |
""" |
| 349 |
# /org/bluez/hci1/dev_FA_23_9D_AA_45_46 |
| 350 |
return device_path[:15] |
| 351 |
|
| 352 |
|
| 353 |
async def wait_for_device_to_reappear(device: BLEDevice, wait_timeout: float) -> bool: |
| 354 |
"""Wait for a device to reappear on the bus.""" |
| 355 |
await asyncio.sleep(0) |
| 356 |
if ( |
| 357 |
not IS_LINUX |
| 358 |
or not isinstance(device.details, dict) |
| 359 |
or "path" not in device.details |
| 360 |
or not (properties := await _get_properties()) |
| 361 |
): |
| 362 |
await asyncio.sleep(wait_timeout) |
| 363 |
return False |
| 364 |
|
| 365 |
debug = _LOGGER.isEnabledFor(logging.DEBUG) |
| 366 |
device_path = address_to_bluez_path(device.address) |
| 367 |
for i in range(int(wait_timeout / REAPPEAR_WAIT_INTERVAL)): |
| 368 |
for path in _get_possible_paths(device_path): |
| 369 |
if path in properties and properties[path].get(defs.DEVICE_INTERFACE): |
| 370 |
if debug: |
| 371 |
_LOGGER.debug( |
| 372 |
"%s - %s: Device re-appeared on bus after %s seconds as %s", |
| 373 |
device.name, |
| 374 |
device.address, |
| 375 |
i * REAPPEAR_WAIT_INTERVAL, |
| 376 |
path, |
| 377 |
) |
| 378 |
return True |
| 379 |
if debug: |
| 380 |
_LOGGER.debug( |
| 381 |
"%s - %s: Waiting %s/%s for device to re-appear on bus", |
| 382 |
device.name, |
| 383 |
device.address, |
| 384 |
(i + 1) * REAPPEAR_WAIT_INTERVAL, |
| 385 |
wait_timeout, |
| 386 |
) |
| 387 |
await asyncio.sleep(REAPPEAR_WAIT_INTERVAL) |
| 388 |
if debug: |
| 389 |
_LOGGER.debug( |
| 390 |
"%s - %s: Device did not re-appear on bus after %s seconds", |
| 391 |
device.name, |
| 392 |
device.address, |
| 393 |
wait_timeout, |
| 394 |
) |
| 395 |
return False |
| 396 |
|
| 397 |
|
| 398 |
async def wait_for_disconnect(device: BLEDevice, min_wait_time: float) -> None: |
| 399 |
"""Wait for the device to disconnect. |
| 400 |
|
| 401 |
After a connection failure, the device may not have |
| 402 |
had time to disconnect so we wait for it to do so. |
| 403 |
|
| 404 |
If we do not wait, we may end up connecting to the |
| 405 |
same device again before it has had time to disconnect. |
| 406 |
""" |
| 407 |
if ( |
| 408 |
not IS_LINUX |
| 409 |
or not isinstance(device.details, dict) |
| 410 |
or "path" not in device.details |
| 411 |
): |
| 412 |
await asyncio.sleep(min_wait_time) |
| 413 |
return |
| 414 |
device_path = device.details["path"] |
| 415 |
start = time.monotonic() if min_wait_time else 0 |
| 416 |
try: |
| 417 |
if not (manager := await get_global_bluez_manager_with_timeout()): |
| 418 |
_LOGGER.debug( |
| 419 |
"%s - %s: Failed to wait for disconnect because no manager", |
| 420 |
device.name, |
| 421 |
device.address, |
| 422 |
) |
| 423 |
return |
| 424 |
async with asyncio_timeout(DISCONNECT_TIMEOUT): |
| 425 |
await manager._wait_condition(device_path, "Connected", False) |
| 426 |
end = time.monotonic() if min_wait_time else 0 |
| 427 |
waited = end - start |
| 428 |
_LOGGER.debug( |
| 429 |
"%s - %s: Waited %s seconds to disconnect", |
| 430 |
device.name, |
| 431 |
device.address, |
| 432 |
waited, |
| 433 |
) |
| 434 |
if min_wait_time and waited < min_wait_time: |
| 435 |
await asyncio.sleep(min_wait_time - waited) |
| 436 |
except (BleakError, KeyError) as ex: |
| 437 |
# Device was removed from bus |
| 438 |
# |
| 439 |
# In testing it was found that most of the CSR adapters |
| 440 |
# only support 5 slots and the broadcom only support 7 slots. |
| 441 |
# |
| 442 |
# When they run out of slots the device they are trying to |
| 443 |
# connect to disappears from the bus so we must backoff |
| 444 |
_LOGGER.debug( |
| 445 |
"%s - %s: Device was removed from bus at %s, waiting %s for it to re-appear: (%s) %s", |
| 446 |
device.name, |
| 447 |
device.address, |
| 448 |
device_path, |
| 449 |
min_wait_time, |
| 450 |
type(ex), |
| 451 |
ex, |
| 452 |
) |
| 453 |
await wait_for_device_to_reappear(device, min_wait_time) |
| 454 |
except Exception: # pylint: disable=broad-except |
| 455 |
_LOGGER.debug( |
| 456 |
"%s - %s: Failed waiting for disconnect at %s", |
| 457 |
device.name, |
| 458 |
device.address, |
| 459 |
device_path, |
| 460 |
exc_info=True, |
| 461 |
) |
| 462 |
|
| 463 |
|
| 464 |
async def get_device_by_adapter(address: str, adapter: str) -> BLEDevice | None: |
| 465 |
"""Get the device by adapter and address.""" |
| 466 |
if not IS_LINUX: |
| 467 |
return None |
| 468 |
if not (properties := await _get_properties()): |
| 469 |
return None |
| 470 |
device_path = address_to_bluez_path(address, adapter) |
| 471 |
if device_path in properties and ( |
| 472 |
device_props := properties[device_path].get(defs.DEVICE_INTERFACE) |
| 473 |
): |
| 474 |
return ble_device_from_properties(device_path, device_props) |
| 475 |
return None |
| 476 |
|
| 477 |
|
| 478 |
async def get_bluez_device( |
| 479 |
name: str, path: str, rssi: int | None = None, _log_disappearance: bool = True |
| 480 |
) -> BLEDevice | None: |
| 481 |
"""Get a BLEDevice object for a BlueZ DBus path.""" |
| 482 |
|
| 483 |
best_path = device_path = path |
| 484 |
rssi_to_beat: int = rssi or NO_RSSI_VALUE |
| 485 |
|
| 486 |
if not (properties := await _get_properties()): |
| 487 |
return None |
| 488 |
|
| 489 |
if ( |
| 490 |
device_path not in properties |
| 491 |
or defs.DEVICE_INTERFACE not in properties[device_path] |
| 492 |
): |
| 493 |
# device has disappeared so take |
| 494 |
# anything over the current path |
| 495 |
if _log_disappearance: |
| 496 |
_LOGGER.debug("%s - %s: Device has disappeared", name, device_path) |
| 497 |
rssi_to_beat = NO_RSSI_VALUE |
| 498 |
|
| 499 |
for path in _get_possible_paths(device_path): |
| 500 |
if path not in properties or not ( |
| 501 |
device_props := properties[path].get(defs.DEVICE_INTERFACE) |
| 502 |
): |
| 503 |
continue |
| 504 |
|
| 505 |
if device_props.get("Connected"): |
| 506 |
# device is connected so take it |
| 507 |
_LOGGER.debug("%s - %s: Device is already connected", name, path) |
| 508 |
if path == device_path: |
| 509 |
# device is connected to the path we were given |
| 510 |
# so we can just return None so it will be used |
| 511 |
return None |
| 512 |
return ble_device_from_properties(path, device_props) |
| 513 |
|
| 514 |
if path == device_path: |
| 515 |
# Device is not connected and is the original path |
| 516 |
# so no need to check it since returning None will |
| 517 |
# cause the device to be used anyways. |
| 518 |
continue |
| 519 |
|
| 520 |
alternate_device_rssi: int = device_props.get("RSSI") or NO_RSSI_VALUE |
| 521 |
if ( |
| 522 |
rssi_to_beat != NO_RSSI_VALUE |
| 523 |
and alternate_device_rssi - RSSI_SWITCH_THRESHOLD < rssi_to_beat |
| 524 |
): |
| 525 |
continue |
| 526 |
best_path = path |
| 527 |
_LOGGER.debug( |
| 528 |
"%s - %s: Found path %s with better RSSI %s > %s", |
| 529 |
name, |
| 530 |
device_path, |
| 531 |
path, |
| 532 |
alternate_device_rssi, |
| 533 |
rssi_to_beat, |
| 534 |
) |
| 535 |
rssi_to_beat = alternate_device_rssi |
| 536 |
|
| 537 |
if best_path == device_path: |
| 538 |
return None |
| 539 |
|
| 540 |
return ble_device_from_properties( |
| 541 |
best_path, properties[best_path][defs.DEVICE_INTERFACE] |
| 542 |
) |
| 543 |
|
| 544 |
|
| 545 |
async def get_connected_devices(device: BLEDevice) -> list[BLEDevice]: |
| 546 |
"""Check if the device is connected.""" |
| 547 |
connected: list[BLEDevice] = [] |
| 548 |
|
| 549 |
if not isinstance(device.details, dict) or "path" not in device.details: |
| 550 |
return connected |
| 551 |
if not (properties := await _get_properties()): |
| 552 |
return connected |
| 553 |
device_path = device.details["path"] |
| 554 |
for path in _get_possible_paths(device_path): |
| 555 |
if path not in properties or defs.DEVICE_INTERFACE not in properties[path]: |
| 556 |
continue |
| 557 |
props = properties[path][defs.DEVICE_INTERFACE] |
| 558 |
if props.get("Connected"): |
| 559 |
connected.append(ble_device_from_properties(path, props)) |
| 560 |
return connected |
| 561 |
|
| 562 |
|
| 563 |
async def get_device(address: str) -> BLEDevice | None: |
| 564 |
"""Get the device.""" |
| 565 |
if not IS_LINUX: |
| 566 |
return None |
| 567 |
return await get_bluez_device( |
| 568 |
address, address_to_bluez_path(address), _log_disappearance=False |
| 569 |
) |
| 570 |
|
| 571 |
|
| 572 |
def address_to_bluez_path(address: str, adapter: str | None = None) -> str: |
| 573 |
"""Convert an address to a BlueZ path.""" |
| 574 |
return f"/org/bluez/{adapter or 'hciX'}/dev_{address.upper().replace(':', '_')}" |
| 575 |
|
| 576 |
|
| 577 |
def _get_possible_paths(path: str) -> Generator[str]: |
| 578 |
"""Get the possible paths.""" |
| 579 |
# The path is deterministic so we splice up the string |
| 580 |
# /org/bluez/hci2/dev_FA_23_9D_AA_45_46 |
| 581 |
for i in range(0, 9): |
| 582 |
yield f"{path[0:14]}{i}{path[15:]}" |
| 583 |
|
| 584 |
|
| 585 |
def ble_device_from_properties(path: str, props: dict[str, Any]) -> BLEDevice: |
| 586 |
"""Get a BLEDevice from a dict of properties.""" |
| 587 |
return BLEDevice( |
| 588 |
props["Address"], |
| 589 |
props["Alias"], |
| 590 |
{"path": path, "props": props}, |
| 591 |
) |