bleak

repository·develop·Indexed 25 days ago

https://github.com/hbldh/bleak

An asynchronous, cross-platform Python library designed to act as a GATT client for Bluetooth Low Energy (BLE) devices. It provides tools for discovering devices via BleakScanner, communicating with GATT servers using BleakClient, and managing Bluetooth adapters through BleakAdapter. The library supports reading and writing GATT characteristics and descriptors, handling notifications, and includes support for Android builds via Buildozer.

Tokens
13.6K
Snippets
33
Records
85
Agent score
81%

What's inside bleak

  1. Overview of Bleak

    develop

    Bleak (Bluetooth Low Energy platform Agnostic Klient) is an asynchronous, cross-platform Python GATT client. It allows developers to connect to and communicate with Bluetooth Low Energy (BLE) devices acting as GATT servers (e.g., sensors).

    Core Features:

    • Scan for BLE advertising devices.
    • Retrieve device metadata (name, service UUIDs, service data, manufacturer-specific data, transmit power, and RSSI) from advertising packets.
    • Connect to BLE peripherals.
    • Read and write GATT characteristics and descriptors.
    • Subscribe to characteristic notifications and indications.
    • Initiate pairing/bonding (subject to platform support).
  2. Supported operating systems for Bleak

    develop

    Bleak provides Bluetooth support across several platforms, though implementation details and capabilities vary by OS:

    • Windows: Windows 11, version 22000 and greater.
    • Linux: Requires BlueZ >= 5.55.
    • macOS: Supported via Core Bluetooth API (version 10.15 or later).
    • Android: Partial support, primarily via Python-for-Android/Kivy.
    • iOS: Partial, optional support via the Pythonista iOS app.
  3. Explore the Bleak API reference

    develop

    The Bleak API is organized into several core modules that handle device discovery, client connections, and GATT operations. The primary entry points for interacting with Bluetooth Low Energy (BLE) devices are:

    • Scanner: Used for discovering nearby BLE devices.
    • Client: Used for connecting to a discovered device and interacting with its services and characteristics.
    • Adapter: Provides access to the local Bluetooth adapter.
    • Args: Contains argument parsing utilities.

    For specific device interactions, you will work with BLEDevice objects, GATT services, characteristics, and descriptors.

  4. Identify devices using UUIDs in Pythonista

    develop

    Unlike other Bleak backends that use Bluetooth MAC addresses, the Pythonista _cb (CoreBluetooth wrapper) backend utilizes UUIDs for device identification. These UUIDs are often unique to the specific scanning device and the device being scanned.

    When writing cross-platform code, you may need to handle both MAC addresses (for non-iOS platforms) and UUIDs (for iOS/Pythonista).

    mac_addr = (
        "24:71:89:cc:09:05"
        if sys.platform != "darwin"
        else "243E23AE-4A99-406C-B317-18F1BD7B4CBE"
    )
  5. Avoid `RuntimeError` when using multiple asyncio event loops

    develop
    Bleak objects are tied to the asyncio event loop in which they were created. While you can use Bleak with multiple event loops, do not share individual Bleak objects between different event loops. Doing so will trigger RuntimeError exceptions (e.g., [...] got Future <Future pending> attached to a different loop).
  6. Understand the Windows backend implementation

    develop

    The Windows backend is built using PyWinRT to provide bindings for the Windows Runtime (WinRT). It provides specialized implementations of core Bleak classes to work with Windows-specific Bluetooth APIs:

    • Client: Implemented as BleakClient in bleak.backends.winrt.client.
    • Scanner: Implemented via BleakScanner methods in bleak.backends.winrt.scanner.
    • GATT Entities: Backend-specific implementations exist for BleakGATTService, BleakGATTCharacteristic, and BleakGATTDescriptor.
  7. Use platform-specific arguments via bleak.args

    develop

    To access platform-specific features in Bleak, you must use argument objects located in the bleak.args sub-package. These arguments can be passed to various constructors and methods depending on the operating system you are running.

    Available platform-specific modules include:

    • bleak.args.bluez for Linux (BlueZ)
    • bleak.args.corebluetooth for macOS (CoreBluetooth)
    • bleak.args.winrt for Windows (WinRT)
  8. Retrieve discovered devices and advertisement data

    develop

    There are three primary patterns for accessing discovered devices and their advertisement data in BleakScanner:

    1. Event-driven (Callback): Provide a detection_callback to the BleakScanner constructor. This function is called every time a new advertisement is received.
    2. Asynchronous Iteration: Use the advertisement_data method, which returns an async iterator that yields tuples containing device and advertisement information as they arrive.
    3. Post-scan Properties: After the scanning process has stopped, you can access the collected data via properties:
      • discovered_devices: A collection of discovered devices.
      • discovered_devices_and_advertisement_data: A collection containing both devices and their advertisement data.
  9. Manage pairing and authentication on macOS

    develop

    The macOS backend does not currently implement explicit pairing functionality. Calling bleak.BleakClient.pair() will raise a NotImplementedError. Setting pair=True in the BleakClient constructor is silently ignored.

    Instead, macOS handles pairing via system prompts. When you attempt to access a characteristic that requires authorization or authentication, macOS will display a prompt to the user. This operation can block for a significant amount of time while waiting for user response, so ensure your timeouts are configured appropriately.

  10. Understand the Shared Backend API

    develop

    Bleak provides a shared backend API for Scanner and Client operations.

    Warning: The backend APIs are not considered part of the stable API and may change without notice. Use them with caution if you are building platform-specific extensions.

    The shared API is divided into two main functional areas:

    1. Scanner: Handles device discovery and scanning for Bluetooth devices.
    2. Client: Handles connections and communication with specific Bluetooth devices.
  11. Known limitations of the Android backend

    develop

    The bleak.backends.p4android backend currently has the following limitations:

    • Missing Features: Scanning filters and indications (notifications without replies) are not yet implemented.
    • Untested Functionality: Reading from a characteristic has not been tested on this backend.
    • Stability: The backend has not been fully tested across the breadth of Android devices.
  12. Operating System Support for Bleak

    develop

    Bleak uses platform-specific backends to provide cross-platform support. Support is categorized into tiers:

    Tier 1 (Maintained and Tested)

    • Linux: Distributions with BlueZ >= 5.55.
    • macOS: Via Core Bluetooth API, macOS 10.15 or later.
    • Windows: Windows 11, version 22000 (Fall Creators Update) or greater.

    Tier 2 (Community Supported)

    • Android: Via Python4Android.

    3rd Party Backends

    • Bumble: A full Bluetooth stack implemented in Python.
    • ESPHome Bluetooth Proxy: For use with ESPHome.
    • Pythonista: For iOS support.