bleak-retry-connector

4.6.0 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Bluetooth LE device using `BleakClientWithServiceCache`. It attempts to connect, and if successful, lists its services and tries to read from available characteristics. Remember to replace `DEVICE_ADDRESS` with an actual MAC address or UUID of a nearby BLE device. The retry mechanism is handled automatically by the client.

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))

view raw JSON →