or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# Bleak

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: bleak

7

- **Language**: Python

8

- **Installation**: `pip install bleak`

9

- **Supported Platforms**: Windows 10+, Linux (BlueZ), macOS/OS X, Android

10

11

## Core Imports

12

13

```python

14

import bleak

15

```

16

17

Common for BLE operations:

18

19

```python

20

from bleak import BleakScanner, BleakClient

21

```

22

23

For device discovery:

24

25

```python

26

from bleak import BLEDevice, AdvertisementData

27

```

28

29

For GATT operations:

30

31

```python

32

from bleak.backends.characteristic import BleakGATTCharacteristic

33

from bleak.backends.descriptor import BleakGATTDescriptor

34

from bleak.backends.service import BleakGATTService, BleakGATTServiceCollection

35

```

36

37

## Basic Usage

38

39

```python

40

import asyncio

41

from bleak import BleakScanner, BleakClient

42

43

async def scan_and_connect():

44

# Discover devices

45

devices = await BleakScanner.discover(timeout=5.0)

46

for device in devices:

47

print(f"Found device: {device.name} ({device.address})")

48

49

# Connect to first device

50

if devices:

51

device = devices[0]

52

async with BleakClient(device) as client:

53

print(f"Connected to {client.name}")

54

55

# Read device name characteristic

56

device_name = await client.read_gatt_char("00002a00-0000-1000-8000-00805f9b34fb")

57

print(f"Device name: {device_name.decode()}")

58

59

# List all services

60

for service in client.services:

61

print(f"Service: {service.uuid} - {service.description}")

62

for char in service.characteristics:

63

print(f" Characteristic: {char.uuid} - {char.description}")

64

65

# Run the async function

66

asyncio.run(scan_and_connect())

67

```

68

69

## Architecture

70

71

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

72

73

- **Scanner**: Discovers BLE devices and collects advertisement data using platform-specific backends

74

- **Client**: Establishes GATT connections and performs characteristic/descriptor operations

75

- **Platform Backends**: Native implementations for Windows (WinRT), macOS (CoreBluetooth), Linux (BlueZ), and Android (P4Android)

76

- **Data Models**: Structured representations of BLE devices, services, characteristics, and descriptors

77

78

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

79

80

## Capabilities

81

82

### Device Discovery and Scanning

83

84

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

85

86

```python { .api }

87

class BleakScanner:

88

def __init__(

89

self,

90

detection_callback: Optional[AdvertisementDataCallback] = None,

91

service_uuids: Optional[list[str]] = None,

92

scanning_mode: Literal["active", "passive"] = "active",

93

*,

94

bluez: BlueZScannerArgs = {},

95

cb: CBScannerArgs = {},

96

backend: Optional[type[BaseBleakScanner]] = None,

97

**kwargs: Any,

98

) -> None: ...

99

100

async def start(self) -> None: ...

101

async def stop(self) -> None: ...

102

103

@classmethod

104

async def discover(

105

cls,

106

timeout: float = 5.0,

107

*,

108

return_adv: bool = False,

109

**kwargs: Unpack[ExtraArgs],

110

): ...

111

112

@classmethod

113

async def find_device_by_address(

114

cls, device_identifier: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]

115

) -> Optional[BLEDevice]: ...

116

```

117

118

[Device Discovery and Scanning](./device-discovery.md)

119

120

### GATT Client Operations

121

122

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

123

124

```python { .api }

125

class BleakClient:

126

def __init__(

127

self,

128

address_or_ble_device: Union[BLEDevice, str],

129

disconnected_callback: Optional[Callable[[BleakClient], None]] = None,

130

services: Optional[Iterable[str]] = None,

131

*,

132

timeout: float = 10.0,

133

pair: bool = False,

134

winrt: WinRTClientArgs = {},

135

backend: Optional[type[BaseBleakClient]] = None,

136

**kwargs: Any,

137

) -> None: ...

138

139

async def connect(self, **kwargs: Any) -> None: ...

140

async def disconnect(self) -> None: ...

141

142

async def read_gatt_char(

143

self,

144

char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],

145

**kwargs: Any,

146

) -> bytearray: ...

147

148

async def write_gatt_char(

149

self,

150

char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],

151

data: Buffer,

152

response: Optional[bool] = None,

153

) -> None: ...

154

```

155

156

[GATT Client Operations](./gatt-client.md)

157

158

### Data Structures and Models

159

160

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

161

162

```python { .api }

163

class BLEDevice:

164

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

165

166

address: str

167

name: Optional[str]

168

details: Any

169

170

class AdvertisementData(NamedTuple):

171

local_name: Optional[str]

172

manufacturer_data: dict[int, bytes]

173

service_data: dict[str, bytes]

174

service_uuids: list[str]

175

tx_power: Optional[int]

176

rssi: int

177

platform_data: tuple[Any, ...]

178

```

179

180

[Data Structures and Models](./data-structures.md)

181

182

### Exception Handling and Error Management

183

184

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

185

186

```python { .api }

187

class BleakError(Exception): ...

188

189

class BleakCharacteristicNotFoundError(BleakError):

190

char_specifier: Union[int, str, uuid.UUID]

191

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

192

193

class BleakDeviceNotFoundError(BleakError):

194

identifier: str

195

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

196

```

197

198

[Exception Handling](./exception-handling.md)

199

200

### UUID Utilities and Constants

201

202

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

203

204

```python { .api }

205

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

206

207

def normalize_uuid_str(uuid: str) -> str: ...

208

def normalize_uuid_16(uuid: int) -> str: ...

209

def normalize_uuid_32(uuid: int) -> str: ...

210

def uuidstr_to_str(uuid_: str) -> str: ...

211

def register_uuids(uuids_to_descriptions: dict[str, str]) -> None: ...

212

```

213

214

[UUID Utilities](./uuid-utilities.md)

215

216

## Types

217

218

```python { .api }

219

# Type aliases for callbacks and filters

220

AdvertisementDataCallback = Callable[

221

[BLEDevice, AdvertisementData],

222

Optional[Coroutine[Any, Any, None]],

223

]

224

225

AdvertisementDataFilter = Callable[

226

[BLEDevice, AdvertisementData],

227

bool,

228

]

229

230

# Platform-specific argument types

231

class BlueZScannerArgs(TypedDict, total=False):

232

filters: BlueZDiscoveryFilters

233

or_patterns: list[OrPatternLike]

234

235

class BlueZDiscoveryFilters(TypedDict, total=False):

236

UUIDs: list[str]

237

RSSI: int

238

Pathloss: int

239

Transport: str

240

DuplicateData: bool

241

Discoverable: bool

242

Pattern: str

243

244

class CBScannerArgs(TypedDict, total=False):

245

use_bdaddr: bool

246

247

class WinRTClientArgs(TypedDict, total=False):

248

address_type: Literal["public", "random"]

249

use_cached_services: bool

250

251

class CBStartNotifyArgs(TypedDict, total=False):

252

use_bdaddr: bool

253

254

# Buffer protocol type for data writing

255

if sys.version_info < (3, 12):

256

from typing_extensions import Buffer

257

else:

258

from collections.abc import Buffer

259

260

# Additional platform type aliases

261

OrPatternLike = Any # Platform-specific BlueZ pattern type

262

```