Cross-platform Bluetooth Low Energy GATT client library for asynchronous BLE communication
npx @tessl/cli install tessl/pypi-bleak@1.1.0Bleak 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.
pip install bleakimport bleakCommon for BLE operations:
from bleak import BleakScanner, BleakClientFor device discovery:
from bleak import BLEDevice, AdvertisementDataFor GATT operations:
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.descriptor import BleakGATTDescriptor
from bleak.backends.service import BleakGATTService, BleakGATTServiceCollectionimport 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())Bleak's architecture centers around two main components designed for cross-platform BLE operations:
This design provides a unified async/await API across all platforms while leveraging native Bluetooth stacks for optimal performance and compatibility.
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]: ...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: ...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, ...]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: ...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: ...# 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