or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backend-management.mdbgapi-backend.mddevice-operations.mderror-handling.mdgatttool-backend.mdindex.mdutilities.md

bgapi-backend.mddocs/

0

# BGAPI Backend

1

2

BGAPI-specific backend implementation for USB dongles with advanced configuration options and low-level protocol access. The BGAPIBackend provides cross-platform BLE connectivity using Bluegiga/Silicon Labs USB adapters like the BLED112.

3

4

## Capabilities

5

6

### Initialization and Configuration

7

8

Initialize BGAPI backend with USB serial port configuration and communication parameters.

9

10

```python { .api }

11

def __init__(self, serial_port: str = None, receive_queue_timeout: float = 0.1):

12

"""

13

Initialize BGAPI backend.

14

15

Args:

16

serial_port: Specific COM port (Windows) or device path (Linux/macOS)

17

None for auto-discovery

18

receive_queue_timeout: Internal queue timeout in seconds

19

"""

20

21

def start(self, reset: bool = True, delay_after_reset_s: float = 1):

22

"""

23

Start BGAPI backend with optional device reset.

24

25

Args:

26

reset: Reset USB adapter on startup (recommended)

27

delay_after_reset_s: Wait time after reset before operations

28

29

Raises:

30

BGAPIError: USB device not found or initialization failed

31

"""

32

```

33

34

**Usage Example:**

35

36

```python

37

import pygatt

38

39

# Auto-discover USB adapter

40

adapter = pygatt.BGAPIBackend()

41

42

# Specify COM port (Windows)

43

adapter = pygatt.BGAPIBackend(serial_port='COM9')

44

45

# Specify device path (Linux)

46

adapter = pygatt.BGAPIBackend(serial_port='/dev/ttyACM0')

47

48

# Start with custom reset timing

49

adapter.start(reset=True, delay_after_reset_s=2.0)

50

```

51

52

### Device Information

53

54

Retrieve adapter hardware information and configuration status.

55

56

```python { .api }

57

def get_mac(self) -> str:

58

"""

59

Get the MAC address of the BGAPI adapter.

60

61

Returns:

62

str: Adapter MAC address in format 'XX:XX:XX:XX:XX:XX'

63

64

Raises:

65

BGAPIError: Failed to retrieve MAC address

66

"""

67

```

68

69

**Usage Example:**

70

71

```python

72

adapter = pygatt.BGAPIBackend()

73

adapter.start()

74

75

mac = adapter.get_mac()

76

print(f"Adapter MAC: {mac}")

77

```

78

79

### Advanced Scanning

80

81

Configure detailed scan parameters for optimized device discovery with active/passive scanning modes.

82

83

```python { .api }

84

def scan(self, timeout: int = 10, scan_interval: int = 75, scan_window: int = 50,

85

active: bool = True, discover_mode=None, scan_cb=None, **kwargs) -> list:

86

"""

87

Perform BLE scan with advanced BGAPI parameters.

88

89

Args:

90

timeout: Scan duration in seconds

91

scan_interval: Time between scan starts (0.625ms units, range: 4-16384)

92

scan_window: Scan duration per interval (0.625ms units, ≤ scan_interval)

93

active: Active scanning (requests scan response) vs passive

94

discover_mode: GAP discovery mode (limited, general, observation)

95

scan_cb: Optional callback for real-time scan results

96

callback(address, name, rssi, advertisement_data)

97

98

Returns:

99

list: Discovered devices with extended advertisement data

100

101

Raises:

102

BGAPIError: Scan configuration or execution failed

103

"""

104

```

105

106

**Usage Example:**

107

108

```python

109

import pygatt

110

111

adapter = pygatt.BGAPIBackend()

112

adapter.start()

113

114

# High-frequency active scan

115

devices = adapter.scan(timeout=15,

116

scan_interval=50, # 31.25ms

117

scan_window=25, # 15.625ms

118

active=True)

119

120

# Real-time scan callback

121

def scan_callback(address, name, rssi, ad_data):

122

print(f"Found: {address} ({name}) RSSI: {rssi}")

123

124

adapter.scan(timeout=10, scan_cb=scan_callback)

125

```

126

127

### Advanced Connection

128

129

Establish connections with precise connection interval and timing parameters.

130

131

```python { .api }

132

def connect(self, address: str, timeout: int = 5, address_type=BLEAddressType.public,

133

interval_min: int = 60, interval_max: int = 76,

134

supervision_timeout: int = 100, latency: int = 0) -> BGAPIBLEDevice:

135

"""

136

Connect to device with advanced BGAPI connection parameters.

137

138

Args:

139

address: Device MAC address

140

timeout: Connection timeout in seconds

141

address_type: BLEAddressType.public or BLEAddressType.random

142

interval_min: Minimum connection interval (1.25ms units, range: 6-3200)

143

interval_max: Maximum connection interval (1.25ms units, range: 6-3200)

144

supervision_timeout: Connection supervision timeout (10ms units, range: 10-3200)

145

latency: Slave latency (number of intervals, range: 0-500)

146

147

Returns:

148

BGAPIBLEDevice: Connected device with BGAPI-specific features

149

150

Raises:

151

BGAPIError: Connection failed

152

NotConnectedError: Device unreachable

153

"""

154

```

155

156

**Usage Example:**

157

158

```python

159

# Low-latency connection for real-time applications

160

device = adapter.connect('01:23:45:67:89:ab',

161

interval_min=6, # 7.5ms

162

interval_max=12, # 15ms

163

supervision_timeout=100, # 1s

164

latency=0)

165

166

# Power-optimized connection

167

device = adapter.connect('01:23:45:67:89:ab',

168

interval_min=80, # 100ms

169

interval_max=120, # 150ms

170

supervision_timeout=400, # 4s

171

latency=4)

172

```

173

174

### Characteristic Discovery

175

176

Perform comprehensive GATT service and characteristic discovery with detailed attribute information.

177

178

```python { .api }

179

def discover_characteristics(self, connection_handle: int, timeout: int = 30) -> dict:

180

"""

181

Discover all GATT characteristics on connected device.

182

183

Args:

184

connection_handle: BGAPI connection handle (internal)

185

timeout: Discovery timeout in seconds

186

187

Returns:

188

dict: Complete characteristic mapping with descriptors

189

{UUID: Characteristic(uuid, handle, descriptors)}

190

191

Raises:

192

BGAPIError: Discovery failed or timed out

193

"""

194

```

195

196

### Bonding Configuration

197

198

Configure device bonding behavior and security settings.

199

200

```python { .api }

201

def set_bondable(self, bondable: bool):

202

"""

203

Enable or disable bonding mode on the adapter.

204

205

Args:

206

bondable: True to allow bonding, False to disable

207

208

Note:

209

Must be called before connecting to devices that require bonding

210

"""

211

212

def clear_bond(self, address: str = None):

213

"""

214

Clear stored bonding information from adapter.

215

216

Args:

217

address: Specific device address, or None for all bonds

218

219

Note:

220

BGAPI stores bonds in adapter's internal flash memory

221

"""

222

```

223

224

**Usage Example:**

225

226

```python

227

# Enable bonding for secure connections

228

adapter.set_bondable(True)

229

230

# Connect and bond with device

231

device = adapter.connect('01:23:45:67:89:ab')

232

device.bond(permanent=True)

233

234

# Later, clear specific bond

235

adapter.clear_bond('01:23:45:67:89:ab')

236

```

237

238

### Low-Level Protocol Access

239

240

Direct access to BGAPI protocol commands for advanced applications and debugging.

241

242

```python { .api }

243

def send_command(self, *args, **kwargs):

244

"""

245

Send raw BGAPI command to adapter.

246

247

Args:

248

*args, **kwargs: Command-specific parameters

249

250

Returns:

251

Response packet data

252

253

Raises:

254

BGAPIError: Command failed or invalid

255

"""

256

257

def expect(self, expected, *args, **kwargs):

258

"""

259

Send command and wait for specific response type.

260

261

Args:

262

expected: Expected response packet type

263

*args, **kwargs: Command parameters

264

265

Returns:

266

Response packet matching expected type

267

268

Raises:

269

ExpectedResponseTimeout: Response not received within timeout

270

"""

271

272

def expect_any(self, expected_packet_choices, timeout: float = None,

273

assert_return_success: bool = True):

274

"""

275

Wait for any of multiple expected response types.

276

277

Args:

278

expected_packet_choices: List of acceptable response types

279

timeout: Wait timeout in seconds

280

assert_return_success: Verify response indicates success

281

282

Returns:

283

First matching response packet

284

285

Raises:

286

ExpectedResponseTimeout: No expected response received

287

BGAPIError: Response indicates error

288

"""

289

```

290

291

### Advertising Control

292

293

Control adapter advertising behavior for peripheral mode applications.

294

295

```python { .api }

296

def disable_advertising(self):

297

"""

298

Disable BLE advertising on the adapter.

299

300

Used when adapter should only operate in central mode.

301

"""

302

```

303

304

## BGAPI Device Features

305

306

The BGAPIBLEDevice class extends BLEDevice with BGAPI-specific enhancements:

307

308

### Enhanced Signal Monitoring

309

310

```python { .api }

311

def get_rssi(self) -> int:

312

"""

313

Get RSSI with BGAPI-specific retry logic.

314

315

Handles BGAPI quirks for more reliable signal strength readings.

316

317

Returns:

318

int: RSSI in dBm, or None if unavailable

319

"""

320

```

321

322

### Robust Bonding

323

324

```python { .api }

325

def bond(self, permanent: bool = False):

326

"""

327

Create bonded connection with BGAPI security features.

328

329

Args:

330

permanent: Store bond in adapter's flash memory

331

332

Provides more reliable bonding than GATTTool backend.

333

"""

334

```

335

336

## Hardware Compatibility

337

338

### Supported Adapters

339

340

- **BLED112**: Silicon Labs/Bluegiga USB BLE adapter

341

- **BLED113**: Similar to BLED112 with different form factor

342

- **BGM11x Series**: Silicon Labs Gecko modules with BGAPI firmware

343

- **Custom BGAPI devices**: Any device implementing BGAPI protocol

344

345

### USB Device Discovery

346

347

```python { .api }

348

# Auto-discovery attempts to find BGAPI devices by VID/PID

349

BLED112_VENDOR_ID = 0x2458

350

BLED112_PRODUCT_ID = 0x0001

351

```

352

353

**Manual Port Selection:**

354

355

```python

356

# Windows

357

adapter = pygatt.BGAPIBackend(serial_port='COM9')

358

359

# Linux

360

adapter = pygatt.BGAPIBackend(serial_port='/dev/ttyACM0')

361

362

# macOS

363

adapter = pygatt.BGAPIBackend(serial_port='/dev/cu.usbmodem1411')

364

```

365

366

## Error Handling

367

368

BGAPI-specific exceptions and common error scenarios:

369

370

### BGAPIError

371

372

Protocol-level errors from BGAPI commands:

373

374

```python

375

try:

376

adapter.start()

377

except pygatt.BGAPIError as e:

378

print(f"BGAPI error: {e}")

379

# Common causes: USB device not found, driver issues, permissions

380

```

381

382

### ExpectedResponseTimeout

383

384

Command response timeouts:

385

386

```python

387

try:

388

device = adapter.connect('01:23:45:67:89:ab', timeout=5)

389

except pygatt.ExpectedResponseTimeout:

390

print("Connection timeout - device may be out of range")

391

```

392

393

### Common Issues

394

395

- **USB permissions**: Linux may require udev rules or sudo

396

- **Driver conflicts**: Ensure no other BGAPI applications are running

397

- **Port selection**: Windows COM port numbers >10 may cause issues

398

- **Reset timing**: Some adapters need longer reset delays