or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-structures.mddevice-discovery.mdexception-handling.mdgatt-client.mdindex.mduuid-utilities.md
tile.json

tessl/pypi-bleak

Cross-platform Bluetooth Low Energy GATT client library for asynchronous BLE communication

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/bleak@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-bleak@1.1.0

index.mddocs/

Bleak

Bleak is a comprehensive cross-platform Python library that provides an asynchronous GATT client implementation for Bluetooth Low Energy (BLE) communication. The library enables developers to discover, connect to, and interact with BLE devices acting as GATT servers across multiple operating systems including Windows 10+, Linux with BlueZ, macOS/OS X, and Android.

Package Information

  • Package Name: bleak
  • Language: Python
  • Installation: pip install bleak
  • Supported Platforms: Windows 10+, Linux (BlueZ), macOS/OS X, Android

Core Imports

import bleak

Common for BLE operations:

from bleak import BleakScanner, BleakClient

For device discovery:

from bleak import BLEDevice, AdvertisementData

For GATT operations:

from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.descriptor import BleakGATTDescriptor
from bleak.backends.service import BleakGATTService, BleakGATTServiceCollection

Basic Usage

import asyncio
from bleak import BleakScanner, BleakClient

async def scan_and_connect():
    # Discover devices
    devices = await BleakScanner.discover(timeout=5.0)
    for device in devices:
        print(f"Found device: {device.name} ({device.address})")
    
    # Connect to first device
    if devices:
        device = devices[0]
        async with BleakClient(device) as client:
            print(f"Connected to {client.name}")
            
            # Read device name characteristic
            device_name = await client.read_gatt_char("00002a00-0000-1000-8000-00805f9b34fb")
            print(f"Device name: {device_name.decode()}")
            
            # List all services
            for service in client.services:
                print(f"Service: {service.uuid} - {service.description}")
                for char in service.characteristics:
                    print(f"  Characteristic: {char.uuid} - {char.description}")

# Run the async function
asyncio.run(scan_and_connect())

Architecture

Bleak's architecture centers around two main components designed for cross-platform BLE operations:

  • Scanner: Discovers BLE devices and collects advertisement data using platform-specific backends
  • Client: Establishes GATT connections and performs characteristic/descriptor operations
  • Platform Backends: Native implementations for Windows (WinRT), macOS (CoreBluetooth), Linux (BlueZ), and Android (P4Android)
  • Data Models: Structured representations of BLE devices, services, characteristics, and descriptors

This design provides a unified async/await API across all platforms while leveraging native Bluetooth stacks for optimal performance and compatibility.

Capabilities

Device Discovery and Scanning

Comprehensive BLE device discovery with filtering, callback support, and advertisement data collection. Supports both active and passive scanning modes with platform-specific optimizations.

class BleakScanner:
    def __init__(
        self,
        detection_callback: Optional[AdvertisementDataCallback] = None,
        service_uuids: Optional[list[str]] = None,
        scanning_mode: Literal["active", "passive"] = "active",
        *,
        bluez: BlueZScannerArgs = {},
        cb: CBScannerArgs = {},
        backend: Optional[type[BaseBleakScanner]] = None,
        **kwargs: Any,
    ) -> None: ...
    
    async def start(self) -> None: ...
    async def stop(self) -> None: ...
    
    @classmethod
    async def discover(
        cls,
        timeout: float = 5.0,
        *,
        return_adv: bool = False,
        **kwargs: Unpack[ExtraArgs],
    ): ...
    
    @classmethod
    async def find_device_by_address(
        cls, device_identifier: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]
    ) -> Optional[BLEDevice]: ...

Device Discovery and Scanning

GATT Client Operations

Complete GATT client functionality for connecting to BLE devices and performing read, write, and notification operations on services, characteristics, and descriptors.

class BleakClient:
    def __init__(
        self,
        address_or_ble_device: Union[BLEDevice, str],
        disconnected_callback: Optional[Callable[[BleakClient], None]] = None,
        services: Optional[Iterable[str]] = None,
        *,
        timeout: float = 10.0,
        pair: bool = False,
        winrt: WinRTClientArgs = {},
        backend: Optional[type[BaseBleakClient]] = None,
        **kwargs: Any,
    ) -> None: ...
    
    async def connect(self, **kwargs: Any) -> None: ...
    async def disconnect(self) -> None: ...
    
    async def read_gatt_char(
        self,
        char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
        **kwargs: Any,
    ) -> bytearray: ...
    
    async def write_gatt_char(
        self,
        char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
        data: Buffer,
        response: Optional[bool] = None,
    ) -> None: ...

GATT Client Operations

Data Structures and Models

Core data structures representing BLE devices, advertisement data, and GATT hierarchy components including services, characteristics, and descriptors.

class BLEDevice:
    def __init__(self, address: str, name: Optional[str], details: Any, **kwargs: Any): ...
    
    address: str
    name: Optional[str]
    details: Any

class AdvertisementData(NamedTuple):
    local_name: Optional[str]
    manufacturer_data: dict[int, bytes]
    service_data: dict[str, bytes]
    service_uuids: list[str]
    tx_power: Optional[int]
    rssi: int
    platform_data: tuple[Any, ...]

Data Structures and Models

Exception Handling and Error Management

Comprehensive exception hierarchy for handling BLE operation errors, device connectivity issues, and platform-specific error conditions.

class BleakError(Exception): ...

class BleakCharacteristicNotFoundError(BleakError):
    char_specifier: Union[int, str, uuid.UUID]
    def __init__(self, char_specifier: Union[int, str, uuid.UUID]) -> None: ...

class BleakDeviceNotFoundError(BleakError):
    identifier: str
    def __init__(self, identifier: str, *args: object) -> None: ...

Exception Handling

UUID Utilities and Constants

Utilities for UUID normalization, conversion, and lookup of Bluetooth assigned numbers including service and characteristic UUIDs.

from bleak.uuids import normalize_uuid_str, normalize_uuid_16, normalize_uuid_32, uuidstr_to_str, register_uuids

def normalize_uuid_str(uuid: str) -> str: ...
def normalize_uuid_16(uuid: int) -> str: ...
def normalize_uuid_32(uuid: int) -> str: ...
def uuidstr_to_str(uuid_: str) -> str: ...
def register_uuids(uuids_to_descriptions: dict[str, str]) -> None: ...

UUID Utilities

Types

# Type aliases for callbacks and filters
AdvertisementDataCallback = Callable[
    [BLEDevice, AdvertisementData],
    Optional[Coroutine[Any, Any, None]],
]

AdvertisementDataFilter = Callable[
    [BLEDevice, AdvertisementData],
    bool,
]

# Platform-specific argument types
class BlueZScannerArgs(TypedDict, total=False):
    filters: BlueZDiscoveryFilters
    or_patterns: list[OrPatternLike]

class BlueZDiscoveryFilters(TypedDict, total=False):
    UUIDs: list[str]
    RSSI: int
    Pathloss: int
    Transport: str
    DuplicateData: bool
    Discoverable: bool
    Pattern: str

class CBScannerArgs(TypedDict, total=False):
    use_bdaddr: bool

class WinRTClientArgs(TypedDict, total=False):
    address_type: Literal["public", "random"]
    use_cached_services: bool

class CBStartNotifyArgs(TypedDict, total=False):
    use_bdaddr: bool

# Buffer protocol type for data writing
if sys.version_info < (3, 12):
    from typing_extensions import Buffer
else:
    from collections.abc import Buffer

# Additional platform type aliases
OrPatternLike = Any  # Platform-specific BlueZ pattern type