bleak-retry-connector
bleak-retry-connector is a Python library that provides a robust wrapper around Bleak clients, adding automatic reconnection, service caching, and improved error handling for transient Bluetooth LE connection failures. It's built on top of the `bleak` library and is currently at version 4.6.0, with a fairly active release cadence, often updating dependencies and patching bugs.
Warnings
- gotcha This library requires Python 3.10 or newer. Using older Python versions will result in installation or runtime errors.
- gotcha The `device_address` parameter expects a valid Bluetooth MAC address (e.g., 'XX:XX:XX:XX:XX:XX') or a UUID. Providing an incorrect format or an address for a device that is not discoverable will lead to connection failures.
- gotcha As a wrapper around `bleak`, `bleak-retry-connector` inherits platform-specific quirks and requirements, such as D-Bus availability on Linux or specific macOS/Windows OS versions. Connection issues can often stem from underlying OS Bluetooth service problems.
- breaking Strict dependency ranges for `bleak` and `bluetooth-adapters` are enforced. If you have other packages that require different major versions of these dependencies, you might encounter version conflicts.
Install
-
pip install bleak-retry-connector
Imports
- BleakClientWithServiceCache
from bleak_retry_connector import BleakClientWithServiceCache
- BleakClientWithRetry
from bleak_retry_connector import BleakClientWithRetry
Quickstart
import asyncio
from bleak_retry_connector import BleakClientWithServiceCache
async def connect_and_read(device_address: str):
try:
# Ensure you replace 'DEVICE_MAC_ADDRESS_OR_UUID' with an actual device address
# For example: 'XX:XX:XX:XX:XX:XX' (MAC) or 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' (UUID)
# A real device with a known characteristic UUID is required to run this.
async with BleakClientWithServiceCache(device_address) as client:
if client.is_connected:
print(f"Connected to {device_address}")
# Example: List services
for service in client.services:
print(f" Service: {service.uuid}")
for char in service.characteristics:
print(f" Characteristic: {char.uuid}")
if "read" in char.properties:
try:
value = await client.read_gatt_char(char.uuid)
print(f" Value: {value.hex()}")
except Exception as e:
print(f" Could not read characteristic {char.uuid}: {e}")
else:
print(f"Failed to connect to {device_address} after retries.")
except Exception as e:
print(f"An error occurred: {e}")
# Replace with a real Bluetooth LE device address
# This example is illustrative and requires a discoverable device.
DEVICE_ADDRESS = "XX:XX:XX:XX:XX:XX" # Placeholder, replace with actual MAC or UUID
if __name__ == "__main__":
print("Attempting to connect to a BLE device. This requires an actual device and may take time.")
print("Please replace 'XX:XX:XX:XX:XX:XX' with your device's MAC address or UUID.")
asyncio.run(connect_and_read(DEVICE_ADDRESS))