Debian Codegraph @

src/bleak_retry_connector/__init__.py

raw
1 from __future__ import annotations
2
3 __version__ = "4.7.1"
4
5
6 import asyncio
7 import logging
8 from collections.abc import Awaitable, Callable
9 from time import monotonic
10 from typing import Any, ParamSpec, TypeVar
11
12 from bleak import BleakClient, BleakScanner
13 from bleak.backends.device import BLEDevice
14 from bleak.backends.service import BleakGATTServiceCollection
15 from bleak.exc import BleakDBusError, BleakDeviceNotFoundError, BleakError
16
17 from .bluez import ( # noqa: F401
18 AllocationChange,
19 AllocationChangeEvent,
20 Allocations,
21 BleakSlotManager,
22 _get_properties,
23 _get_properties_sync,
24 _get_services_cache,
25 clear_cache,
26 device_source,
27 get_connected_devices,
28 get_device,
29 get_device_by_adapter,
30 path_from_ble_device,
31 wait_for_device_to_reappear,
32 wait_for_disconnect,
33 )
34 from .const import DISCONNECT_TIMEOUT, IS_LINUX, NO_RSSI_VALUE, RSSI_SWITCH_THRESHOLD
35 from .util import asyncio_timeout
36
37 DEFAULT_ATTEMPTS = 2
38
39 if IS_LINUX:
40 from bluetooth_adapters import load_history_from_managed_objects
41
42 from .dbus import disconnect_devices
43 else:
44 load_history_from_managed_objects = None
45 disconnect_devices = None # type: ignore[assignment]
46
47
48 # Make sure bleak and dbus-fast have time
49 # to run their cleanup callbacks or the
50 # retry call will just fail in the same way.
51 BLEAK_TRANSIENT_BACKOFF_TIME = 0.25
52 BLEAK_TRANSIENT_MEDIUM_BACKOFF_TIME = 0.50
53 BLEAK_TRANSIENT_LONG_BACKOFF_TIME = 1.0
54 BLEAK_DBUS_BACKOFF_TIME = 0.25
55 BLEAK_OUT_OF_SLOTS_BACKOFF_TIME = 4.00
56 BLEAK_BACKOFF_TIME = 0.1
57 # Expected disconnect or ran out of slots
58 # after checking, don't backoff since we
59 # want to retry immediately.
60 BLEAK_DISCONNECTED_BACKOFF_TIME = 0.0
61
62
63 __all__ = [
64 "BleakSlotManager", # Currently only possible for BlueZ, for MacOS we have no of knowing
65 "ble_device_description",
66 "establish_connection",
67 "close_stale_connections",
68 "close_stale_connections_by_address",
69 "clear_cache",
70 "get_device",
71 "get_device_by_adapter",
72 "device_source",
73 "restore_discoveries",
74 "restore_discoveries_sync",
75 "retry_bluetooth_connection_error",
76 "BleakClientWithServiceCache",
77 "BleakAbortedError",
78 "BleakConnectionError",
79 "BleakNotFoundError",
80 "BleakOutOfConnectionSlotsError",
81 "BLEAK_RETRY_EXCEPTIONS",
82 "DISCONNECT_TIMEOUT",
83 "RSSI_SWITCH_THRESHOLD",
84 "NO_RSSI_VALUE",
85 ]
86
87
88 BLEAK_EXCEPTIONS = (AttributeError, BleakError)
89 # EOFError and BrokenPipeError happen when the D-Bus socket dies out
90 # from under us; asyncio.TimeoutError is deliberately not retried so
91 # timeouts set by the caller are not multiplied by the retry attempts.
92 RETRYABLE_BLEAK_EXCEPTIONS = (*BLEAK_EXCEPTIONS, EOFError, BrokenPipeError)
93 BLEAK_RETRY_EXCEPTIONS = (*RETRYABLE_BLEAK_EXCEPTIONS, asyncio.TimeoutError)
94
95 _LOGGER = logging.getLogger(__name__)
96
97 MAX_TRANSIENT_ERRORS = 9
98
99 # Shorter time outs and more attempts
100 # seems to be better for dbus, and corebluetooth
101 # is happy either way. Ideally we want everything
102 # to finish in < 60s or declare we cannot connect
103
104 MAX_CONNECT_ATTEMPTS = 4
105 BLEAK_TIMEOUT = 20.0
106
107 # Bleak may not always timeout
108 # since the dbus connection can stall
109 # so we have an additional timeout to
110 # be sure we do not block forever
111 # This is likely fixed in https://github.com/hbldh/bleak/pull/1092
112 #
113 # This also accounts for the time it
114 # takes for the esp32s to disconnect
115 #
116 BLEAK_SAFETY_TIMEOUT = 60.0
117
118 TRANSIENT_ERRORS_LONG_BACKOFF = {
119 "ESP_GATT_ERROR",
120 }
121
122 TRANSIENT_ERRORS_MEDIUM_BACKOFF = {
123 "ESP_GATT_CONN_TIMEOUT",
124 "ESP_GATT_CONN_FAIL_ESTABLISH",
125 }
126
127 DEVICE_MISSING_ERRORS = {"org.freedesktop.DBus.Error.UnknownObject"}
128
129 OUT_OF_SLOTS_ERRORS = {
130 "available connection",
131 "connection slot",
132 }
133
134 # ESP_GATT_CONN_CONN_CANCEL (0x100) is set by the ESP32 Bluetooth stack itself,
135 # never by the device, when a connection is cancelled before it is established.
136 # It is not a reliable out of slots signal since the ESPHome proxy answers with a
137 # different error when it has no free slot and bleak-esphome waits for a free slot
138 # before connecting. It happens in two ways:
139 # 1. The controller rejects the create connection command right away, for example
140 # HCI 0x0d while it is still releasing the previous connection
141 # (https://github.com/espressif/esp-idf/issues/17452) or HCI 0x0c Command
142 # Disallowed when BLE 5.0 features are enabled
143 # (https://github.com/esphome/esphome/pull/18047).
144 # 2. The stack gives up after its connection establishment timeout
145 # (CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT, at least 10s in ESPHome) because the
146 # device never responded.
147 # The time the connect attempt took tells the two apart. A rejection can still
148 # take a few seconds since bleak-esphome waits up to 2s for a free slot before
149 # connecting and up to 2s for the slot to settle after a failure, so the cutoff
150 # sits between that and the 10s minimum establishment timeout.
151 # The 4-second backoff gives the controller time to finish cleaning up.
152 CONNECTION_CANCELLED_ERRORS = {"ESP_GATT_CONN_CONN_CANCEL"}
153 CONNECTION_CANCELLED_REJECTED_MAX_TIME = 8.0
154
155 TRANSIENT_ERRORS = (
156 {
157 "le-connection-abort-by-local",
158 "br-connection-canceled",
159 "ESP_GATT_CONN_FAIL_ESTABLISH",
160 "ESP_GATT_CONN_TERMINATE_PEER_USER",
161 "ESP_GATT_CONN_TERMINATE_LOCAL_HOST",
162 }
163 | OUT_OF_SLOTS_ERRORS
164 | CONNECTION_CANCELLED_ERRORS
165 )
166
167 # Currently the same as transient error
168 ABORT_ERRORS = (
169 TRANSIENT_ERRORS | TRANSIENT_ERRORS_MEDIUM_BACKOFF | TRANSIENT_ERRORS_LONG_BACKOFF
170 )
171
172
173 ABORT_ADVICE = (
174 "Interference/range; "
175 "External Bluetooth adapter w/extension may help; "
176 "Extension cables reduce USB 3 port interference"
177 )
178
179 DEVICE_MISSING_ADVICE = (
180 "The device disappeared; Try restarting the scanner or moving the device closer"
181 )
182
183 BLUETOOTH_PROXIES_URL = "https://esphome.io/projects/?type=bluetooth"
184
185 OUT_OF_SLOTS_ADVICE = (
186 "The proxy/adapter is out of connection slots or the device is no longer reachable; "
187 f"Add additional proxies ({BLUETOOTH_PROXIES_URL}) near this device"
188 )
189
190 CONNECTION_REJECTED_ADVICE = (
191 "The proxy/adapter controller rejected the connection immediately; "
192 "This usually points to a controller or firmware problem, not a lack of "
193 "connection slots; Check the proxy logs and update its firmware"
194 )
195
196 CONNECTION_CANCELLED_TIMEOUT_ADVICE = (
197 "The proxy/adapter gave up waiting for the device to respond; "
198 "The device may be out of range or not accepting connections; "
199 "Move the device closer or add additional proxies "
200 f"({BLUETOOTH_PROXIES_URL}) near this device"
201 )
202
203 NORMAL_DISCONNECT = "Disconnected"
204
205
206 class BleakNotFoundError(BleakError):
207 """The device was not found."""
208
209
210 class BleakConnectionError(BleakError):
211 """General connection failure after all retries."""
212
213
214 class BleakAbortedError(BleakError):
215 """The connection was aborted."""
216
217
218 class BleakOutOfConnectionSlotsError(BleakError):
219 """The proxy/adapter is out of connection slots."""
220
221
222 class BleakClientWithServiceCache(BleakClient):
223 """A BleakClient that implements service caching."""
224
225 def set_cached_services(self, services: BleakGATTServiceCollection | None) -> None:
226 """Set the cached services.
227
228 No longer used since bleak 0.17+ has service caching built-in.
229
230 This was only kept for backwards compatibility.
231 """
232
233 async def clear_cache(self) -> bool:
234 """Clear the cached services."""
235 if hasattr(super(), "clear_cache"):
236 return await super().clear_cache()
237 _LOGGER.warning("clear_cache not implemented in bleak version")
238 return False
239
240 async def set_connection_params(
241 self,
242 min_interval: int,
243 max_interval: int,
244 latency: int,
245 timeout: int,
246 ) -> None:
247 """Set BLE connection parameters."""
248 if hasattr(super(), "set_connection_params"):
249 await super().set_connection_params(
250 min_interval, max_interval, latency, timeout
251 )
252 return
253 _LOGGER.warning("set_connection_params not implemented in bleak version")
254
255
256 def ble_device_has_changed(original: BLEDevice, new: BLEDevice) -> bool:
257 """Check if the device has changed."""
258 return bool(
259 original.address != new.address
260 or (
261 isinstance(original.details, dict)
262 and isinstance(new.details, dict)
263 and "path" in original.details
264 and "path" in new.details
265 and original.details["path"] != new.details["path"]
266 )
267 )
268
269
270 def ble_device_description(device: BLEDevice) -> str:
271 """Get the device description."""
272 details = device.details
273 address = device.address
274 name = device.name
275 if name != address:
276 base_name = f"{address} - {name}"
277 else:
278 base_name = address
279 if isinstance(details, dict):
280 if path := details.get("path"):
281 # /org/bluez/hci2
282 return f"{base_name} -> {path[0:15]}"
283 if source := details.get("source"):
284 return f"{base_name} -> {source}"
285 return base_name
286
287
288 async def _has_valid_services_in_cache(device: BLEDevice) -> bool:
289 """Check if the device has valid services in cache.
290
291 For non-Linux platforms (macOS, ESPHome proxies), the cache is always valid
292 and we return True to allow using cached services.
293
294 For Linux/BlueZ, this function validates that cached services are still valid
295 by checking if they exist in the BlueZ manager's properties. Due to race
296 conditions, the properties and services cache can become out of sync. If
297 properties have disappeared but the services cache still contains them, the
298 cache is stale and should not be used.
299
300 Returns:
301 - True for non-Linux platforms (cache always valid)
302 - True for Linux if all cached services are still present in D-Bus properties
303 - False for Linux if cache is stale or unavailable
304 """
305 if not IS_LINUX:
306 # Cache is always valid on macOS and ESPHome proxies
307 return True
308
309 # Check if this is a BlueZ device
310 if not (device_path := path_from_ble_device(device)):
311 # Not a BlueZ device (might be ESPHome proxy), cache is valid
312 return True
313
314 # Get the services cache
315 if not (services_cache := await _get_services_cache()):
316 _LOGGER.debug(
317 "%s - %s: No services cache available, cannot validate",
318 device.name or "Unknown",
319 device.address,
320 )
321 return False
322
323 # Check if services are cached for this device
324 if not (cached_services := services_cache.get(device_path)):
325 _LOGGER.debug(
326 "%s - %s: No cached services found for device path %s",
327 device.name or "Unknown",
328 device.address,
329 device_path,
330 )
331 return False
332
333 # Get current properties to check if cached services are still present
334 if not (properties := await _get_properties()):
335 _LOGGER.debug(
336 "%s - %s: Could not get properties to validate cache",
337 device.name or "Unknown",
338 device.address,
339 )
340 return False
341
342 service_count = len(cached_services.services)
343 if not service_count:
344 _LOGGER.debug(
345 "%s - %s: No cached services found for device path %s",
346 device.name or "Unknown",
347 device.address,
348 device_path,
349 )
350 return False
351
352 # Check if all cached services are still present in properties
353 # The cached_services is a BleakGATTServiceCollection object
354 for service in cached_services:
355 if service.obj[0] not in properties:
356 # Service is in cache but not in properties (not on the bus)
357 _LOGGER.debug(
358 "%s - %s: Cached service %s not found in properties, cache invalid",
359 device.name or "Unknown",
360 device.address,
361 service,
362 )
363 return False
364
365 _LOGGER.debug(
366 "%s - %s: All %d cached services are valid and present in properties",
367 device.name or "Unknown",
368 device.address,
369 service_count,
370 )
371 return True
372
373
374 def calculate_backoff_time(exc: Exception) -> float:
375 """Calculate the backoff time based on the exception."""
376
377 # bleak-esphome raises a TimeoutError when no connection slot
378 # becomes available
379 if isinstance(exc, asyncio.TimeoutError) and any(
380 error in str(exc) for error in OUT_OF_SLOTS_ERRORS
381 ):
382 return BLEAK_OUT_OF_SLOTS_BACKOFF_TIME
383 if isinstance(
384 exc, (BleakDBusError, EOFError, asyncio.TimeoutError, BrokenPipeError)
385 ):
386 return BLEAK_DBUS_BACKOFF_TIME
387 # If the adapter runs out of slots can get a BleakDeviceNotFoundError
388 # since the device is no longer visible on the adapter. Almost none of
389 # the adapters document how many connection slots they have so we cannot
390 # know if we are out of slots or not. We can only guess based on the
391 # error message and backoff.
392 if isinstance(exc, (BleakDeviceNotFoundError, BleakNotFoundError)):
393 return BLEAK_OUT_OF_SLOTS_BACKOFF_TIME
394 if isinstance(exc, BleakError):
395 bleak_error = str(exc)
396 if any(
397 error in bleak_error
398 for error in OUT_OF_SLOTS_ERRORS | CONNECTION_CANCELLED_ERRORS
399 ):
400 return BLEAK_OUT_OF_SLOTS_BACKOFF_TIME
401 if any(error in bleak_error for error in TRANSIENT_ERRORS_MEDIUM_BACKOFF):
402 return BLEAK_TRANSIENT_MEDIUM_BACKOFF_TIME
403 if any(error in bleak_error for error in TRANSIENT_ERRORS_LONG_BACKOFF):
404 return BLEAK_TRANSIENT_LONG_BACKOFF_TIME
405 if any(error in bleak_error for error in TRANSIENT_ERRORS):
406 return BLEAK_TRANSIENT_BACKOFF_TIME
407 if NORMAL_DISCONNECT in bleak_error:
408 return BLEAK_DISCONNECTED_BACKOFF_TIME
409 return BLEAK_BACKOFF_TIME
410
411
412 async def close_stale_connections_by_address(
413 address: str, only_other_adapters: bool = False
414 ) -> None:
415 """Close stale connections by address."""
416 if not IS_LINUX or not (device := await get_device(address)):
417 return
418 await close_stale_connections(device, only_other_adapters)
419
420
421 async def close_stale_connections(
422 device: BLEDevice, only_other_adapters: bool = False
423 ) -> None:
424 """Close stale connections."""
425 if not IS_LINUX or not (devices := await get_connected_devices(device)):
426 return
427 to_disconnect: list[BLEDevice] = []
428 for connected_device in devices:
429 if only_other_adapters and not ble_device_has_changed(connected_device, device):
430 _LOGGER.debug(
431 "%s - %s: unexpectedly connected, not disconnecting since only_other_adapters is set",
432 connected_device.name,
433 connected_device.address,
434 )
435 else:
436 _LOGGER.debug(
437 "%s - %s: unexpectedly connected, disconnecting",
438 connected_device.name,
439 connected_device.address,
440 )
441 to_disconnect.append(connected_device)
442
443 if not to_disconnect:
444 return
445 await disconnect_devices(to_disconnect)
446
447
448 AnyBleakClient = TypeVar("AnyBleakClient", bound=BleakClient)
449
450
451 async def establish_connection(
452 client_class: type[AnyBleakClient],
453 device: BLEDevice,
454 name: str,
455 disconnected_callback: Callable[[AnyBleakClient], None] | None = None,
456 max_attempts: int = MAX_CONNECT_ATTEMPTS,
457 cached_services: BleakGATTServiceCollection | None = None,
458 ble_device_callback: Callable[[], BLEDevice] | None = None,
459 use_services_cache: bool = True,
460 pair: bool = False,
461 **kwargs: Any,
462 ) -> AnyBleakClient:
463 """Establish a connection to the device."""
464 timeouts = 0
465 connect_errors = 0
466 transient_errors = 0
467 attempt = 0
468 connect_elapsed = 0.0
469
470 def _raise_if_needed(name: str, description: str, exc: Exception) -> None:
471 """Raise if we reach the max attempts."""
472 if (
473 timeouts + connect_errors < max_attempts
474 and transient_errors < MAX_TRANSIENT_ERRORS
475 ):
476 return
477 msg = (
478 f"{name} - {description}: Failed to connect after "
479 f"{attempt} attempt(s): {str(exc) or type(exc).__name__}"
480 )
481 # Sure would be nice if bleak gave us typed exceptions
482 if isinstance(exc, asyncio.TimeoutError):
483 # bleak-esphome raises a TimeoutError when no connection slot
484 # becomes available
485 if any(error in str(exc) for error in OUT_OF_SLOTS_ERRORS):
486 raise BleakOutOfConnectionSlotsError(
487 f"{msg}: {OUT_OF_SLOTS_ADVICE}"
488 ) from exc
489 raise BleakNotFoundError(msg) from exc
490 if isinstance(exc, BleakDeviceNotFoundError) or "not found" in str(exc):
491 raise BleakNotFoundError(f"{msg}: {DEVICE_MISSING_ADVICE}") from exc
492 if isinstance(exc, BleakError):
493 if any(error in str(exc) for error in OUT_OF_SLOTS_ERRORS):
494 raise BleakOutOfConnectionSlotsError(
495 f"{msg}: {OUT_OF_SLOTS_ADVICE}"
496 ) from exc
497 if any(error in str(exc) for error in CONNECTION_CANCELLED_ERRORS):
498 if connect_elapsed < CONNECTION_CANCELLED_REJECTED_MAX_TIME:
499 raise BleakAbortedError(
500 f"{msg}: {CONNECTION_REJECTED_ADVICE}"
501 ) from exc
502 raise BleakAbortedError(
503 f"{msg}: {CONNECTION_CANCELLED_TIMEOUT_ADVICE}"
504 ) from exc
505 if any(error in str(exc) for error in ABORT_ERRORS):
506 raise BleakAbortedError(f"{msg}: {ABORT_ADVICE}") from exc
507 if any(error in str(exc) for error in DEVICE_MISSING_ERRORS):
508 raise BleakNotFoundError(f"{msg}: {DEVICE_MISSING_ADVICE}") from exc
509 raise BleakConnectionError(msg) from exc
510
511 debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
512 if IS_LINUX and (devices := await get_connected_devices(device)):
513 # Bleak 0.17 will handle already connected devices for us so
514 # if we are already connected we swap the device to the connected
515 # device.
516 device = devices[0]
517
518 client = client_class(
519 device,
520 disconnected_callback=disconnected_callback,
521 pair=pair,
522 _is_retry_client=True,
523 **kwargs,
524 )
525
526 while True:
527 attempt += 1
528 if debug_enabled:
529 _LOGGER.debug(
530 "%s - %s: Connection attempt: %s",
531 name,
532 device.address,
533 attempt,
534 )
535
536 connect_started = monotonic()
537 try:
538 async with asyncio_timeout(BLEAK_SAFETY_TIMEOUT):
539 # Only use cache if we have valid services in the cache
540 should_use_cache = use_services_cache or bool(cached_services)
541 if should_use_cache:
542 should_use_cache = await _has_valid_services_in_cache(device)
543
544 await client.connect(
545 timeout=BLEAK_TIMEOUT,
546 dangerous_use_bleak_cache=should_use_cache,
547 )
548 if debug_enabled:
549 _LOGGER.debug(
550 "%s - %s: Connected after %s attempts",
551 name,
552 device.address,
553 attempt,
554 )
555 except asyncio.TimeoutError as exc:
556 timeouts += 1
557 if debug_enabled:
558 _LOGGER.debug(
559 "%s - %s: Timed out trying to connect (attempt: %s)",
560 name,
561 device.address,
562 attempt,
563 )
564 backoff_time = calculate_backoff_time(exc)
565 await wait_for_disconnect(device, backoff_time)
566 _raise_if_needed(name, device.address, exc)
567 except KeyError as exc:
568 # Likely: KeyError: 'org.bluez.GattService1' from bleak
569 # ideally we would get a better error from bleak, but this is
570 # better than nothing.
571 # self._properties[service_path][defs.GATT_SERVICE_INTERFACE]
572 transient_errors += 1
573 if debug_enabled:
574 _LOGGER.debug(
575 "%s - %s: Failed to connect due to services changes: %s (attempt: %s)",
576 name,
577 device.address,
578 str(exc),
579 attempt,
580 )
581 if isinstance(client, BleakClientWithServiceCache):
582 await client.clear_cache()
583 await client.disconnect()
584 backoff_time = calculate_backoff_time(exc)
585 await wait_for_disconnect(device, backoff_time)
586 _raise_if_needed(name, device.address, exc)
587 except BrokenPipeError as exc:
588 # BrokenPipeError is raised by dbus-next when the device disconnects
589 #
590 # bleak.exc.BleakDBusError: [org.bluez.Error] le-connection-abort-by-local
591 # During handling of the above exception, another exception occurred:
592 # Traceback (most recent call last):
593 # File "bleak/backends/bluezdbus/client.py", line 177, in connect
594 # reply = await self._bus.call(
595 # File "dbus_next/aio/message_bus.py", line 63, in write_callback
596 # self.offset += self.sock.send(self.buf[self.offset:])
597 # BrokenPipeError: [Errno 32] Broken pipe
598 transient_errors += 1
599 if debug_enabled:
600 _LOGGER.debug(
601 "%s - %s: Failed to connect: %s (attempt: %s)",
602 name,
603 device.address,
604 str(exc),
605 attempt,
606 )
607 _raise_if_needed(name, device.address, exc)
608 except EOFError as exc:
609 transient_errors += 1
610 backoff_time = calculate_backoff_time(exc)
611 if debug_enabled:
612 _LOGGER.debug(
613 "%s - %s: Failed to connect: %s, backing off: %s (attempt: %s)",
614 name,
615 device.address,
616 str(exc),
617 backoff_time,
618 attempt,
619 )
620 await wait_for_disconnect(device, backoff_time)
621 _raise_if_needed(name, device.address, exc)
622 except BLEAK_EXCEPTIONS as exc:
623 connect_elapsed = monotonic() - connect_started
624 bleak_error = str(exc)
625 # BleakDeviceNotFoundError can mean that the adapter has run out of
626 # connection slots.
627 device_missing = isinstance(
628 exc, (BleakNotFoundError, BleakDeviceNotFoundError)
629 )
630 if device_missing or any(
631 error in bleak_error for error in TRANSIENT_ERRORS
632 ):
633 transient_errors += 1
634 else:
635 connect_errors += 1
636 backoff_time = calculate_backoff_time(exc)
637 if debug_enabled:
638 _LOGGER.debug(
639 "%s - %s: Failed to connect: %s, device_missing: %s, backing off: %s (attempt: %s)",
640 name,
641 device.address,
642 bleak_error,
643 device_missing,
644 backoff_time,
645 attempt,
646 )
647 await wait_for_disconnect(device, backoff_time)
648 _raise_if_needed(name, device.address, exc)
649 else:
650 return client
651 # Ensure the disconnect callback
652 # has a chance to run before we try to reconnect
653 await asyncio.sleep(0)
654
655 raise RuntimeError("This should never happen")
656
657
658 P = ParamSpec("P")
659 T = TypeVar("T")
660
661
662 def retry_bluetooth_connection_error(
663 attempts: int = DEFAULT_ATTEMPTS,
664 ) -> Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]:
665 """Define a wrapper to retry on bluetooth connection error."""
666
667 def _decorator_retry_bluetooth_connection_error(
668 func: Callable[P, Awaitable[T]],
669 ) -> Callable[P, Awaitable[T]]:
670 """Define a wrapper to retry on bleak error.
671
672 The accessory is allowed to disconnect us any time so
673 we need to retry the operation.
674 """
675
676 async def _async_wrap_bluetooth_connection_error_retry( # type: ignore[return]
677 *args: P.args, **kwargs: P.kwargs
678 ) -> T:
679 for attempt in range(attempts):
680 try:
681 return await func(*args, **kwargs)
682 except RETRYABLE_BLEAK_EXCEPTIONS as ex:
683 backoff_time = calculate_backoff_time(ex)
684 if attempt == attempts - 1:
685 raise
686 _LOGGER.debug(
687 "Bleak error calling %s, backing off: %s, retrying...",
688 func,
689 backoff_time,
690 exc_info=True,
691 )
692 await asyncio.sleep(backoff_time)
693
694 return _async_wrap_bluetooth_connection_error_retry
695
696 return _decorator_retry_bluetooth_connection_error
697
698
699 async def restore_discoveries(scanner: BleakScanner, adapter: str) -> None:
700 """Restore discoveries from the bus."""
701 if not IS_LINUX:
702 # This is only supported on Linux
703 return
704 if not (properties := await _get_properties()):
705 _LOGGER.debug("Failed to restore discoveries for %s", adapter)
706 return
707 _restore_discoveries(scanner, adapter, properties)
708
709
710 def restore_discoveries_sync(scanner: BleakScanner, adapter: str) -> None:
711 """Restore discoveries from a BlueZ manager that is already running.
712
713 Same as restore_discoveries but never awaits: it reads the manager
714 bleak created for the running loop, so call it from the loop after
715 the scanner has started. A no-op when there is no such manager.
716 """
717 if not IS_LINUX:
718 return
719 if not (properties := _get_properties_sync()):
720 _LOGGER.debug("No running BlueZ manager to restore discoveries for %s", adapter)
721 return
722 _restore_discoveries(scanner, adapter, properties)
723
724
725 def _restore_discoveries(
726 scanner: BleakScanner,
727 adapter: str,
728 properties: dict[str, dict[str, dict[str, Any]]],
729 ) -> None:
730 """Seed the scanner's seen devices from the managed objects."""
731 backend = scanner._backend
732 before = len(backend.seen_devices)
733 details: dict[str, Any]
734 backend.seen_devices.update(
735 {
736 path: (device, history.advertisement_data)
737 for history in load_history_from_managed_objects(
738 properties, adapter
739 ).values()
740 if (device := history.device)
741 and (details := device.details)
742 and (path := details.get("path"))
743 }
744 )
745 _LOGGER.debug(
746 "Restored %s discoveries for %s", len(backend.seen_devices) - before, adapter
747 )