| 1 |
# Usage Guide |
| 2 |
|
| 3 |
## Why Use bleak-retry-connector? |
| 4 |
|
| 5 |
This package provides robust retry logic and intelligent backoff strategies for establishing BLE connections. Key benefits include: |
| 6 |
|
| 7 |
- **Automatic retry with backoff** - Handles transient connection failures with intelligent retry timing |
| 8 |
- **Connection slot management** - Critical for ESPHome Bluetooth proxies that have limited connection slots |
| 9 |
- **Service caching** - Speeds up reconnections by caching GATT services |
| 10 |
- **Platform-specific optimizations** - Special handling for Linux/BlueZ, macOS, and ESP32 devices |
| 11 |
- **Error categorization** - Distinguishes between transient errors, missing devices, and out-of-slots conditions |
| 12 |
|
| 13 |
### Essential for ESPHome Bluetooth Proxies |
| 14 |
|
| 15 |
If you're using ESPHome Bluetooth proxies, this package is **critical** because: |
| 16 |
|
| 17 |
1. **Proper slot management** - ESP32 devices have limited connection slots that must be carefully managed |
| 18 |
2. **Handles ESP-specific errors** - Recognizes ESP32 error codes like `ESP_GATT_CONN_CONN_CANCEL` (connection cancelled by the ESP32 Bluetooth stack) |
| 19 |
3. **Appropriate backoff timing** - Uses longer backoff (4 seconds) when slots are exhausted or the controller cancels a connection to allow proper cleanup |
| 20 |
4. **Prevents slot exhaustion** - Manages connection attempts to avoid overwhelming the proxy |
| 21 |
|
| 22 |
## BleakClientWithServiceCache |
| 23 |
|
| 24 |
`BleakClientWithServiceCache` is a subclass of `BleakClient` that provides service caching capabilities for faster reconnections. |
| 25 |
|
| 26 |
### Basic Usage |
| 27 |
|
| 28 |
```python |
| 29 |
from bleak_retry_connector import BleakClientWithServiceCache |
| 30 |
from bleak.backends.device import BLEDevice |
| 31 |
|
| 32 |
|
| 33 |
async def connect_with_cache(device: BLEDevice): |
| 34 |
client = BleakClientWithServiceCache(device) |
| 35 |
await client.connect() |
| 36 |
|
| 37 |
# Use the client normally |
| 38 |
services = client.services |
| 39 |
|
| 40 |
# Clear cache if needed (e.g., after service changes) |
| 41 |
await client.clear_cache() |
| 42 |
|
| 43 |
await client.disconnect() |
| 44 |
``` |
| 45 |
|
| 46 |
### Key Features |
| 47 |
|
| 48 |
- **Automatic service caching**: Services are cached between connections for faster reconnections |
| 49 |
- **Cache clearing**: Call `clear_cache()` to force a fresh service discovery |
| 50 |
- **Connection parameter tuning**: Call `set_connection_params()` to adjust BLE connection intervals |
| 51 |
- **Drop-in replacement**: Can be used anywhere `BleakClient` is used |
| 52 |
|
| 53 |
### Extension Methods |
| 54 |
|
| 55 |
`BleakClientWithServiceCache` provides extension methods that are forwarded to the underlying backend (e.g., habluetooth). These methods allow integrations to control BLE behavior beyond what standard bleak provides. |
| 56 |
|
| 57 |
#### clear_cache |
| 58 |
|
| 59 |
```python |
| 60 |
async def clear_cache(self) -> bool |
| 61 |
``` |
| 62 |
|
| 63 |
Clears the cached GATT services, forcing a fresh service discovery on the next access. Useful when a device's firmware has been updated or services have changed. |
| 64 |
|
| 65 |
Returns `True` if the cache was successfully cleared, `False` otherwise. |
| 66 |
|
| 67 |
```python |
| 68 |
client = await establish_connection( |
| 69 |
BleakClientWithServiceCache, device, name="MyDevice" |
| 70 |
) |
| 71 |
|
| 72 |
# If characteristics are missing, clear cache and reconnect |
| 73 |
await client.clear_cache() |
| 74 |
await client.disconnect() |
| 75 |
``` |
| 76 |
|
| 77 |
#### set_connection_params |
| 78 |
|
| 79 |
```python |
| 80 |
async def set_connection_params( |
| 81 |
self, |
| 82 |
min_interval: int, |
| 83 |
max_interval: int, |
| 84 |
latency: int, |
| 85 |
timeout: int, |
| 86 |
) -> None |
| 87 |
``` |
| 88 |
|
| 89 |
Sets BLE connection parameters on a connected device. This is useful for "Always Connected" devices where battery conservation is important — switching from fast intervals (~7.5ms) to slow intervals (e.g., 1000ms) after the initial data sync can significantly reduce power consumption. |
| 90 |
|
| 91 |
Parameters are in BLE units: |
| 92 |
|
| 93 |
- **min_interval** / **max_interval**: Connection interval in units of 1.25ms (e.g., 800 = 1000ms) |
| 94 |
- **latency**: Number of connection events the peripheral can skip (typically 0) |
| 95 |
- **timeout**: Supervision timeout in units of 10ms (e.g., 600 = 6000ms) |
| 96 |
|
| 97 |
```python |
| 98 |
client = await establish_connection( |
| 99 |
BleakClientWithServiceCache, device, name="MyDevice" |
| 100 |
) |
| 101 |
|
| 102 |
# After initial sync, switch to slow intervals to save battery |
| 103 |
await client.set_connection_params( |
| 104 |
min_interval=800, # 1000ms |
| 105 |
max_interval=800, # 1000ms |
| 106 |
latency=0, |
| 107 |
timeout=600, # 6000ms |
| 108 |
) |
| 109 |
``` |
| 110 |
|
| 111 |
The method delegates to the backend (habluetooth), which routes to either: |
| 112 |
|
| 113 |
- **ESPHome proxy**: Sends a protobuf message to the ESP32 to call `esp_ble_gap_update_conn_params()` |
| 114 |
- **Local BlueZ adapter**: Uses the MGMT API (`MGMT_OP_LOAD_CONN_PARAM`) |
| 115 |
|
| 116 |
## establish_connection |
| 117 |
|
| 118 |
`establish_connection` is the main function for establishing robust BLE connections with automatic retry logic. |
| 119 |
|
| 120 |
### Function Signature |
| 121 |
|
| 122 |
```python |
| 123 |
async def establish_connection( |
| 124 |
client_class: type[BleakClient], |
| 125 |
device: BLEDevice, |
| 126 |
name: str, |
| 127 |
disconnected_callback: Callable[[BleakClient], None] | None = None, |
| 128 |
max_attempts: int = 4, |
| 129 |
cached_services: BleakGATTServiceCollection | None = None, |
| 130 |
ble_device_callback: Callable[[], BLEDevice] | None = None, |
| 131 |
use_services_cache: bool = True, |
| 132 |
pair: bool = False, |
| 133 |
**kwargs: Any |
| 134 |
) -> BleakClient |
| 135 |
``` |
| 136 |
|
| 137 |
### Parameters |
| 138 |
|
| 139 |
- **client_class**: The BleakClient class to use (typically `BleakClientWithServiceCache`) |
| 140 |
- **device**: The BLE device to connect to |
| 141 |
- **name**: A descriptive name for the device (used in logging) |
| 142 |
- **disconnected_callback**: Optional callback when device disconnects unexpectedly |
| 143 |
- **max_attempts**: Maximum connection attempts before giving up (default: 4) |
| 144 |
- **cached_services**: Deprecated; the collection itself is no longer threaded into the |
| 145 |
client. Only the parameter's truthiness still has any effect — passing any non-`None` |
| 146 |
value forces `dangerous_use_bleak_cache=True` for that connect call, identical to |
| 147 |
setting `use_services_cache=True`. Bleak 0.17+ ships built-in service caching, which |
| 148 |
this library calls into directly. Prefer `use_services_cache=True` and stop constructing |
| 149 |
a stand-in `BleakGATTServiceCollection` for this parameter. |
| 150 |
- **ble_device_callback**: Deprecated and unused; retained for API compatibility. The |
| 151 |
callback is never invoked. Pass the freshest `BLEDevice` to `device` instead — Home |
| 152 |
Assistant and other discovery layers already supply an up-to-date path on each retry. |
| 153 |
- **use_services_cache**: Whether to use service caching (default: True) |
| 154 |
- **pair**: Whether to pair with the device on connect (default: False) |
| 155 |
- **kwargs**: Additional arguments passed to the client class constructor |
| 156 |
|
| 157 |
### Return Value |
| 158 |
|
| 159 |
Returns the connected client instance of the specified `client_class`. |
| 160 |
|
| 161 |
### Exceptions |
| 162 |
|
| 163 |
`establish_connection` can raise the following exceptions after exhausting retry attempts: |
| 164 |
|
| 165 |
- **BleakNotFoundError**: Device was not found or disappeared |
| 166 |
|
| 167 |
- Raised when the device cannot be found |
| 168 |
- Raised on `asyncio.TimeoutError` after all retries, unless the timeout says no connection slot became available |
| 169 |
- Raised when `BleakDeviceNotFoundError` occurs |
| 170 |
- Raised when device is missing from the adapter |
| 171 |
|
| 172 |
- **BleakOutOfConnectionSlotsError**: Adapter/proxy has no available connection slots |
| 173 |
|
| 174 |
- Raised when local Bluetooth adapters or ESP32 proxies are out of connection slots |
| 175 |
- Common with errors containing "connection slot" or "available connection" |
| 176 |
- Also raised when bleak-esphome times out with "No free BLE connection slot became available" |
| 177 |
- For local adapters: disconnect unused devices or use a different adapter |
| 178 |
- For ESP32 proxies: add more proxies or disconnect other devices |
| 179 |
|
| 180 |
- **BleakAbortedError**: Connection was aborted due to interference, range, or proxy controller issues |
| 181 |
|
| 182 |
- Raised for transient connection failures that suggest environmental issues |
| 183 |
- Common with errors like "le-connection-abort-by-local", "br-connection-canceled" |
| 184 |
- Indicates interference, range problems, or USB 3.0 port interference |
| 185 |
- Also raised for "ESP_GATT_CONN_CONN_CANCEL", which the ESP32 Bluetooth stack reports when a connection is cancelled before it is established; if the attempt failed immediately the controller rejected it, which points to a proxy firmware or controller problem, otherwise the stack gave up because the device did not respond |
| 186 |
|
| 187 |
- **BleakConnectionError**: General connection failure after all retries |
| 188 |
- Raised for any other connection errors that don't fit the above categories |
| 189 |
- The fallback exception when connection cannot be established |
| 190 |
|
| 191 |
### Basic Example |
| 192 |
|
| 193 |
```python |
| 194 |
from bleak_retry_connector import establish_connection, BleakClientWithServiceCache |
| 195 |
from bleak.backends.device import BLEDevice |
| 196 |
|
| 197 |
|
| 198 |
async def connect_to_device(device: BLEDevice): |
| 199 |
# Simple connection with retry |
| 200 |
client = await establish_connection( |
| 201 |
BleakClientWithServiceCache, device, name=device.name or device.address |
| 202 |
) |
| 203 |
|
| 204 |
# Use the client |
| 205 |
services = client.services |
| 206 |
|
| 207 |
# Disconnect when done |
| 208 |
await client.disconnect() |
| 209 |
|
| 210 |
return client |
| 211 |
``` |
| 212 |
|
| 213 |
### Example with Disconnection Callback |
| 214 |
|
| 215 |
```python |
| 216 |
async def connect_with_callback(device: BLEDevice): |
| 217 |
def on_disconnect(client): |
| 218 |
print(f"Device {device.address} disconnected unexpectedly") |
| 219 |
|
| 220 |
client = await establish_connection( |
| 221 |
BleakClientWithServiceCache, |
| 222 |
device, |
| 223 |
name=device.name or device.address, |
| 224 |
disconnected_callback=on_disconnect, |
| 225 |
max_attempts=5, # Try up to 5 times |
| 226 |
) |
| 227 |
|
| 228 |
return client |
| 229 |
``` |
| 230 |
|
| 231 |
### Example with Custom Client Class |
| 232 |
|
| 233 |
```python |
| 234 |
from bleak import BleakClient |
| 235 |
|
| 236 |
|
| 237 |
class CustomClient(BleakClient): |
| 238 |
async def custom_method(self): |
| 239 |
# Custom functionality |
| 240 |
pass |
| 241 |
|
| 242 |
|
| 243 |
async def connect_with_custom_client(device: BLEDevice): |
| 244 |
client = await establish_connection( |
| 245 |
CustomClient, device, name=device.name, max_attempts=3 |
| 246 |
) |
| 247 |
|
| 248 |
# Use custom methods |
| 249 |
await client.custom_method() |
| 250 |
|
| 251 |
return client |
| 252 |
``` |
| 253 |
|
| 254 |
### Error Handling Example |
| 255 |
|
| 256 |
```python |
| 257 |
from bleak_retry_connector import ( |
| 258 |
establish_connection, |
| 259 |
BleakClientWithServiceCache, |
| 260 |
BleakNotFoundError, |
| 261 |
BleakOutOfConnectionSlotsError, |
| 262 |
BleakAbortedError, |
| 263 |
BleakConnectionError, |
| 264 |
) |
| 265 |
|
| 266 |
|
| 267 |
async def connect_with_error_handling(device: BLEDevice): |
| 268 |
try: |
| 269 |
client = await establish_connection( |
| 270 |
BleakClientWithServiceCache, device, name=device.name |
| 271 |
) |
| 272 |
return client |
| 273 |
|
| 274 |
except BleakNotFoundError: |
| 275 |
print("Device not found - it may have moved out of range") |
| 276 |
return None |
| 277 |
|
| 278 |
except BleakOutOfConnectionSlotsError: |
| 279 |
print("No connection slots available - try disconnecting other devices") |
| 280 |
return None |
| 281 |
|
| 282 |
except BleakAbortedError: |
| 283 |
print("Connection aborted - check for interference or move closer") |
| 284 |
return None |
| 285 |
|
| 286 |
except BleakConnectionError as e: |
| 287 |
print(f"Connection failed: {e}") |
| 288 |
return None |
| 289 |
``` |
| 290 |
|
| 291 |
### Example with Cache Clearing on Missing Characteristic |
| 292 |
|
| 293 |
When a device's firmware changes or services are updated, you might encounter missing characteristics. Here's how to handle this scenario by clearing the cache and retrying: |
| 294 |
|
| 295 |
```python |
| 296 |
from bleak_retry_connector import establish_connection, BleakClientWithServiceCache |
| 297 |
from bleak.exc import BleakError |
| 298 |
|
| 299 |
|
| 300 |
class CharacteristicMissingError(Exception): |
| 301 |
"""Raised when a required characteristic is missing.""" |
| 302 |
|
| 303 |
pass |
| 304 |
|
| 305 |
|
| 306 |
async def connect_and_validate_services(device: BLEDevice): |
| 307 |
"""Connect and validate required characteristics exist.""" |
| 308 |
|
| 309 |
client = await establish_connection( |
| 310 |
BleakClientWithServiceCache, |
| 311 |
device, |
| 312 |
name=device.name or device.address, |
| 313 |
use_services_cache=True, |
| 314 |
) |
| 315 |
|
| 316 |
try: |
| 317 |
# Check for required characteristics |
| 318 |
required_service_uuid = "cba20d00-224d-11e6-9fb8-0002a5d5c51b" |
| 319 |
required_char_uuid = "cba20002-224d-11e6-9fb8-0002a5d5c51b" |
| 320 |
|
| 321 |
service = client.services.get_service(required_service_uuid) |
| 322 |
if not service: |
| 323 |
raise CharacteristicMissingError( |
| 324 |
f"Service {required_service_uuid} not found" |
| 325 |
) |
| 326 |
|
| 327 |
char = service.get_characteristic(required_char_uuid) |
| 328 |
if not char: |
| 329 |
raise CharacteristicMissingError( |
| 330 |
f"Characteristic {required_char_uuid} not found" |
| 331 |
) |
| 332 |
|
| 333 |
except (CharacteristicMissingError, KeyError) as ex: |
| 334 |
# Services might have changed, clear cache and reconnect |
| 335 |
print(f"Characteristic missing, clearing cache: {ex}") |
| 336 |
await client.clear_cache() |
| 337 |
await client.disconnect() |
| 338 |
|
| 339 |
# Reconnect without cache |
| 340 |
client = await establish_connection( |
| 341 |
BleakClientWithServiceCache, |
| 342 |
device, |
| 343 |
name=device.name or device.address, |
| 344 |
use_services_cache=False, # Force fresh service discovery |
| 345 |
) |
| 346 |
|
| 347 |
# Validate again |
| 348 |
service = client.services.get_service(required_service_uuid) |
| 349 |
if not service: |
| 350 |
await client.disconnect() |
| 351 |
raise CharacteristicMissingError( |
| 352 |
f"Service {required_service_uuid} still not found after cache clear" |
| 353 |
) |
| 354 |
|
| 355 |
char = service.get_characteristic(required_char_uuid) |
| 356 |
if not char: |
| 357 |
await client.disconnect() |
| 358 |
raise CharacteristicMissingError( |
| 359 |
f"Characteristic {required_char_uuid} still not found after cache clear" |
| 360 |
) |
| 361 |
|
| 362 |
return client |
| 363 |
``` |
| 364 |
|
| 365 |
### Advanced Configuration |
| 366 |
|
| 367 |
```python |
| 368 |
async def connect_with_full_options(device: BLEDevice): |
| 369 |
client = await establish_connection( |
| 370 |
BleakClientWithServiceCache, |
| 371 |
device, |
| 372 |
name="MyDevice", |
| 373 |
disconnected_callback=lambda c: print("Disconnected"), |
| 374 |
max_attempts=6, # More attempts for difficult devices |
| 375 |
use_services_cache=True, # Use caching for faster reconnects |
| 376 |
timeout=30.0, # Pass additional kwargs to BleakClient |
| 377 |
) |
| 378 |
|
| 379 |
return client |
| 380 |
``` |
| 381 |
|
| 382 |
## Complete Working Example |
| 383 |
|
| 384 |
```python |
| 385 |
import asyncio |
| 386 |
from bleak import BleakScanner |
| 387 |
from bleak_retry_connector import ( |
| 388 |
establish_connection, |
| 389 |
BleakClientWithServiceCache, |
| 390 |
BleakNotFoundError, |
| 391 |
BleakOutOfConnectionSlotsError, |
| 392 |
BleakAbortedError, |
| 393 |
BleakConnectionError, |
| 394 |
) |
| 395 |
|
| 396 |
|
| 397 |
async def main(): |
| 398 |
# Scan for devices |
| 399 |
print("Scanning for devices...") |
| 400 |
devices = await BleakScanner.discover() |
| 401 |
|
| 402 |
if not devices: |
| 403 |
print("No devices found") |
| 404 |
return |
| 405 |
|
| 406 |
# Connect to the first device found |
| 407 |
device = devices[0] |
| 408 |
print(f"Connecting to {device.name or device.address}...") |
| 409 |
|
| 410 |
try: |
| 411 |
# Establish connection with retry |
| 412 |
client = await establish_connection( |
| 413 |
BleakClientWithServiceCache, |
| 414 |
device, |
| 415 |
name=device.name or device.address, |
| 416 |
max_attempts=4, |
| 417 |
) |
| 418 |
|
| 419 |
print("Connected successfully!") |
| 420 |
|
| 421 |
# List services |
| 422 |
for service in client.services: |
| 423 |
print(f" Service: {service.uuid}") |
| 424 |
for char in service.characteristics: |
| 425 |
print(f" Characteristic: {char.uuid}") |
| 426 |
|
| 427 |
# Disconnect |
| 428 |
await client.disconnect() |
| 429 |
print("Disconnected") |
| 430 |
|
| 431 |
except ( |
| 432 |
BleakNotFoundError, |
| 433 |
BleakOutOfConnectionSlotsError, |
| 434 |
BleakAbortedError, |
| 435 |
BleakConnectionError, |
| 436 |
) as e: |
| 437 |
print(f"Failed to connect: {e}") |
| 438 |
|
| 439 |
|
| 440 |
if __name__ == "__main__": |
| 441 |
asyncio.run(main()) |
| 442 |
``` |
| 443 |
|
| 444 |
## retry_bluetooth_connection_error |
| 445 |
|
| 446 |
A decorator that wraps an async function and retries it on transient Bleak |
| 447 |
errors. Useful for short GATT operations (reads, writes, notifications) that |
| 448 |
can be disconnected mid-flight by the device. |
| 449 |
|
| 450 |
### Function Signature |
| 451 |
|
| 452 |
```python |
| 453 |
def retry_bluetooth_connection_error( |
| 454 |
attempts: int = 2, |
| 455 |
) -> Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]] |
| 456 |
``` |
| 457 |
|
| 458 |
### Parameters |
| 459 |
|
| 460 |
- **attempts**: Number of times to attempt the wrapped call before re-raising |
| 461 |
the underlying error (default: 2). |
| 462 |
|
| 463 |
The decorator catches the same `BLEAK_EXCEPTIONS` group used internally by |
| 464 |
`establish_connection` and backs off with `calculate_backoff_time()` between |
| 465 |
attempts. After the final attempt fails, the original exception propagates. |
| 466 |
|
| 467 |
### Example |
| 468 |
|
| 469 |
```python |
| 470 |
from bleak_retry_connector import ( |
| 471 |
establish_connection, |
| 472 |
BleakClientWithServiceCache, |
| 473 |
retry_bluetooth_connection_error, |
| 474 |
) |
| 475 |
|
| 476 |
|
| 477 |
@retry_bluetooth_connection_error(attempts=3) |
| 478 |
async def read_battery(client: BleakClientWithServiceCache) -> int: |
| 479 |
data = await client.read_gatt_char("00002a19-0000-1000-8000-00805f9b34fb") |
| 480 |
return data[0] |
| 481 |
|
| 482 |
|
| 483 |
async def main(device): |
| 484 |
client = await establish_connection( |
| 485 |
BleakClientWithServiceCache, device, name=device.name |
| 486 |
) |
| 487 |
try: |
| 488 |
level = await read_battery(client) |
| 489 |
print(f"Battery: {level}%") |
| 490 |
finally: |
| 491 |
await client.disconnect() |
| 492 |
``` |
| 493 |
|
| 494 |
## close_stale_connections |
| 495 |
|
| 496 |
On Linux/BlueZ, BlueZ may report a device as connected even when another |
| 497 |
adapter or a crashed process owns the connection. `close_stale_connections` |
| 498 |
disconnects those existing connections so a fresh `establish_connection` |
| 499 |
attempt can proceed. |
| 500 |
|
| 501 |
Two variants are exported: |
| 502 |
|
| 503 |
```python |
| 504 |
async def close_stale_connections( |
| 505 |
device: BLEDevice, only_other_adapters: bool = False |
| 506 |
) -> None |
| 507 |
|
| 508 |
async def close_stale_connections_by_address( |
| 509 |
address: str, only_other_adapters: bool = False |
| 510 |
) -> None |
| 511 |
``` |
| 512 |
|
| 513 |
- **device** / **address**: The target device or its MAC address. |
| 514 |
- **only_other_adapters**: If `True`, only disconnect instances on adapters |
| 515 |
different from the one the supplied `device` is on. Useful when you want |
| 516 |
to keep your own active connection alive while clearing duplicates that |
| 517 |
appeared on another adapter. |
| 518 |
|
| 519 |
Both functions are no-ops on non-Linux platforms. |
| 520 |
|
| 521 |
### Example |
| 522 |
|
| 523 |
```python |
| 524 |
from bleak_retry_connector import ( |
| 525 |
close_stale_connections_by_address, |
| 526 |
establish_connection, |
| 527 |
BleakClientWithServiceCache, |
| 528 |
) |
| 529 |
|
| 530 |
# Before reconnecting after a service restart, clear stale BlueZ state: |
| 531 |
await close_stale_connections_by_address("AA:BB:CC:DD:EE:FF") |
| 532 |
|
| 533 |
client = await establish_connection( |
| 534 |
BleakClientWithServiceCache, device, name=device.name |
| 535 |
) |
| 536 |
``` |
| 537 |
|
| 538 |
## clear_cache |
| 539 |
|
| 540 |
Removes a device from BlueZ via the `RemoveDevice` D-Bus method. This clears |
| 541 |
cached GATT services and any stale `Connected=True` state BlueZ may be |
| 542 |
holding for the address. |
| 543 |
|
| 544 |
```python |
| 545 |
async def clear_cache(address: str) -> bool |
| 546 |
``` |
| 547 |
|
| 548 |
- **address**: The MAC address of the device to remove. |
| 549 |
- **Returns**: `True` if the device was removed, `False` otherwise (including |
| 550 |
on non-Linux platforms). |
| 551 |
|
| 552 |
`clear_cache()` is safe to call unconditionally — it suppresses all errors |
| 553 |
internally and returns `False` rather than raising. There is also an instance |
| 554 |
method `BleakClientWithServiceCache.clear_cache()` (documented above) which |
| 555 |
clears only the bleak-level service cache for an already-connected client; |
| 556 |
the module-level `clear_cache(address)` operates on BlueZ directly and does |
| 557 |
not require a client. |
| 558 |
|
| 559 |
### Example |
| 560 |
|
| 561 |
```python |
| 562 |
from bleak_retry_connector import clear_cache |
| 563 |
|
| 564 |
# After a firmware update, force BlueZ to forget cached services: |
| 565 |
await clear_cache("AA:BB:CC:DD:EE:FF") |
| 566 |
``` |
| 567 |
|
| 568 |
## restore_discoveries |
| 569 |
|
| 570 |
On Linux/BlueZ, advertisement data tracked by BlueZ can be lost when a |
| 571 |
scanner is recreated. `restore_discoveries` re-seeds a freshly created |
| 572 |
`BleakScanner` with the devices BlueZ already knows about, so callers don't |
| 573 |
have to wait for the next advertisement to see existing devices. |
| 574 |
|
| 575 |
```python |
| 576 |
async def restore_discoveries(scanner: BleakScanner, adapter: str) -> None |
| 577 |
``` |
| 578 |
|
| 579 |
- **scanner**: The newly created `BleakScanner` instance. |
| 580 |
- **adapter**: The HCI adapter name (e.g. `"hci0"`). |
| 581 |
|
| 582 |
No-op on non-Linux platforms. |
| 583 |
|
| 584 |
```python |
| 585 |
def restore_discoveries_sync(scanner: BleakScanner, adapter: str) -> None |
| 586 |
``` |
| 587 |
|
| 588 |
Same seeding without awaiting, for callers that restart a scanner in place |
| 589 |
(bleak clears `seen_devices` on every `start()`). It reads the BlueZ manager |
| 590 |
bleak already built for the running event loop, so call it from the loop |
| 591 |
after the scanner has started; no-op when there is no such manager, off the |
| 592 |
loop, or on non-Linux platforms. |
| 593 |
|
| 594 |
## get_device / get_device_by_adapter |
| 595 |
|
| 596 |
Look up a `BLEDevice` by MAC address against BlueZ's current view of the bus. |
| 597 |
Useful when a caller has lost its `BLEDevice` handle (e.g. after a scanner |
| 598 |
restart) but still knows the address. |
| 599 |
|
| 600 |
```python |
| 601 |
async def get_device(address: str) -> BLEDevice | None |
| 602 |
async def get_device_by_adapter(address: str, adapter: str) -> BLEDevice | None |
| 603 |
``` |
| 604 |
|
| 605 |
- **address**: The MAC address of the device. |
| 606 |
- **adapter** (`get_device_by_adapter` only): The HCI adapter name (e.g. |
| 607 |
`"hci0"`) to restrict the lookup to a single controller. |
| 608 |
|
| 609 |
`get_device` searches every adapter and returns the device with the strongest |
| 610 |
RSSI; `get_device_by_adapter` only inspects the BlueZ object at |
| 611 |
`/org/bluez/<adapter>/dev_<ADDR>` and returns `None` if no device exists on |
| 612 |
that adapter. |
| 613 |
|
| 614 |
Both return `None` on non-Linux platforms and when BlueZ has no matching |
| 615 |
object. |
| 616 |
|
| 617 |
```python |
| 618 |
from bleak_retry_connector import ( |
| 619 |
get_device, |
| 620 |
establish_connection, |
| 621 |
BleakClientWithServiceCache, |
| 622 |
) |
| 623 |
|
| 624 |
device = await get_device("AA:BB:CC:DD:EE:FF") |
| 625 |
if device is None: |
| 626 |
raise RuntimeError("device not currently known to BlueZ") |
| 627 |
|
| 628 |
client = await establish_connection( |
| 629 |
BleakClientWithServiceCache, device, name=device.name |
| 630 |
) |
| 631 |
``` |
| 632 |
|
| 633 |
## device_source |
| 634 |
|
| 635 |
Return the `source` tag from a `BLEDevice`'s `details` mapping, or `None` if |
| 636 |
the tag is absent. The source is set by the scanner that produced the |
| 637 |
advertisement — for example, ESPHome Bluetooth proxies tag their devices with |
| 638 |
the proxy name. Native BlueZ devices typically have no source. |
| 639 |
|
| 640 |
```python |
| 641 |
def device_source(device: BLEDevice) -> str | None |
| 642 |
``` |
| 643 |
|
| 644 |
```python |
| 645 |
from bleak_retry_connector import device_source |
| 646 |
|
| 647 |
if device_source(device) is None: |
| 648 |
# Local adapter device — slot management applies. |
| 649 |
... |
| 650 |
else: |
| 651 |
# Came from an ESPHome proxy — handle ESP-specific errors. |
| 652 |
... |
| 653 |
``` |
| 654 |
|
| 655 |
## ble_device_description |
| 656 |
|
| 657 |
Format a `BLEDevice` into a short, log-friendly string of the form |
| 658 |
`<address> - <name> -> <path-or-source>`. Used by `establish_connection` |
| 659 |
internally for log lines; exported so callers can produce the same format in |
| 660 |
their own diagnostics. |
| 661 |
|
| 662 |
```python |
| 663 |
def ble_device_description(device: BLEDevice) -> str |
| 664 |
``` |
| 665 |
|
| 666 |
The trailing `-> ...` is only appended when the device's `details` carry a |
| 667 |
BlueZ `path` (truncated to 15 characters) or a `source` tag. Devices with |
| 668 |
neither are described as `<address> - <name>` (or just `<address>` when the |
| 669 |
name equals the address). |
| 670 |
|
| 671 |
## BleakSlotManager |
| 672 |
|
| 673 |
`BleakSlotManager` tracks how many BLE connection slots each local BlueZ |
| 674 |
adapter has free and which addresses currently hold a slot. It is intended |
| 675 |
for callers that orchestrate multiple connections across multiple adapters |
| 676 |
(e.g. Home Assistant) and need to make scheduling decisions before calling |
| 677 |
`establish_connection`. |
| 678 |
|
| 679 |
```python |
| 680 |
from bleak_retry_connector import BleakSlotManager |
| 681 |
|
| 682 |
manager = BleakSlotManager() |
| 683 |
await manager.async_setup() |
| 684 |
|
| 685 |
# Tell the manager about each adapter and its slot capacity: |
| 686 |
manager.register_adapter("hci0", slots=5) |
| 687 |
manager.register_adapter("hci1", slots=5) |
| 688 |
|
| 689 |
allocations = manager.get_allocations("hci0") |
| 690 |
print(allocations.free, allocations.allocated) |
| 691 |
``` |
| 692 |
|
| 693 |
Key methods: |
| 694 |
|
| 695 |
- **`async_setup()`** — Attach to the global BlueZ manager. Must be awaited |
| 696 |
before any other call. |
| 697 |
- **`register_adapter(adapter, slots)`** / **`remove_adapter(adapter)`** — |
| 698 |
Declare or forget an adapter and its slot capacity. On registration, |
| 699 |
devices that BlueZ already reports as connected on the adapter are |
| 700 |
pre-allocated. |
| 701 |
- **`get_allocations(adapter)`** — Return an `Allocations` dataclass |
| 702 |
describing the adapter (`slots`, `free`, list of allocated addresses). |
| 703 |
- **`release_slot(device)`** — Manually release a slot held by `device`. |
| 704 |
Normally unnecessary: the manager watches BlueZ's `Connected` property and |
| 705 |
releases automatically on disconnect. |
| 706 |
- **`register_allocation_callback(callback)`** — Subscribe to |
| 707 |
`AllocationChangeEvent`s (allocated / released). Returns an unsubscribe |
| 708 |
callable. |
| 709 |
- **`diagnostics()`** — Return a JSON-friendly snapshot for logging. |
| 710 |
|
| 711 |
`BleakSlotManager` only sees BlueZ adapters; ESPHome proxy slots are tracked |
| 712 |
by the proxy itself and reported through habluetooth. On non-Linux platforms |
| 713 |
the manager can be constructed but `async_setup()` will not find a BlueZ |
| 714 |
manager to attach to. |
| 715 |
|
| 716 |
## Constants |
| 717 |
|
| 718 |
- **`BLEAK_RETRY_EXCEPTIONS`**: A tuple of exception classes that |
| 719 |
`establish_connection` treats as transient and retryable: |
| 720 |
`AttributeError`, `BleakError`, `EOFError`, `BrokenPipeError`, and |
| 721 |
`asyncio.TimeoutError`. Re-exported so callers layering their own retry |
| 722 |
logic on top can match the same set. `retry_bluetooth_connection_error` |
| 723 |
retries the same set except `asyncio.TimeoutError`, which is deliberately |
| 724 |
excluded so timeouts set by the caller are not multiplied by the retry |
| 725 |
attempts. |
| 726 |
|
| 727 |
- **`NO_RSSI_VALUE`** (`-127`): Sentinel value used internally when an |
| 728 |
advertisement carries no RSSI. Exported so callers ranking devices by |
| 729 |
signal strength can use the same floor. |
| 730 |
|
| 731 |
- **`RSSI_SWITCH_THRESHOLD`** (`5`): Minimum RSSI delta in dBm that |
| 732 |
`establish_connection` requires before switching to a stronger advertised |
| 733 |
path mid-retry. Exposed for callers that want to apply the same hysteresis |
| 734 |
to their own adapter-selection logic. |
| 735 |
|
| 736 |
- **`DISCONNECT_TIMEOUT`** (`5`): Maximum time in seconds that |
| 737 |
bleak-retry-connector will wait for a D-Bus disconnect operation — |
| 738 |
including `clear_cache`'s `RemoveDevice` calls and the post-failure |
| 739 |
disconnect wait in `establish_connection` — to complete before giving up. |
| 740 |
Exposed so callers wrapping the same D-Bus operations can apply a matching |
| 741 |
ceiling. |