0
# Backend Management
1
2
Core backend lifecycle and configuration operations for initializing and managing BLE adapters. The BLEBackend class provides the abstract interface that both BGAPI and GATTTool backends implement.
3
4
## Capabilities
5
6
### Backend Lifecycle
7
8
Initialize and manage backend resources including USB connections, CLI processes, and cleanup operations.
9
10
```python { .api }
11
def start(self):
12
"""
13
Initialize and start the backend resources.
14
15
For BGAPI: Opens serial connection to USB adapter
16
For GATTTool: Starts gatttool subprocess and initializes CLI
17
18
Raises:
19
BGAPIError: BGAPI backend initialization failed
20
BLEError: General backend startup failure
21
"""
22
23
def stop(self):
24
"""
25
Stop and free all backend resources.
26
27
Disconnects all active connections and cleans up background processes.
28
Must be called to prevent resource leaks.
29
"""
30
31
def supports_unbonded(self) -> bool:
32
"""
33
Check if backend supports unbonded (unauthenticated) communication.
34
35
Returns:
36
bool: True if unbonded communication supported
37
"""
38
```
39
40
### Device Connection
41
42
Connect to BLE devices using MAC addresses with configurable connection parameters and address types.
43
44
```python { .api }
45
def connect(self, address: str, timeout: float = 5.0, **kwargs) -> BLEDevice:
46
"""
47
Connect to a BLE device by MAC address.
48
49
Args:
50
address: BLE MAC address (e.g., '01:23:45:67:89:ab')
51
timeout: Connection timeout in seconds (default: 5.0)
52
address_type: BLEAddressType.public or BLEAddressType.random
53
**kwargs: Backend-specific connection parameters
54
55
Returns:
56
BLEDevice: Connected device instance
57
58
Raises:
59
NotConnectedError: Connection failed
60
BLEError: General connection error
61
"""
62
```
63
64
**Usage Example:**
65
66
```python
67
import pygatt
68
69
adapter = pygatt.BGAPIBackend()
70
adapter.start()
71
72
# Connect with random address type
73
device = adapter.connect('01:23:45:67:89:ab',
74
address_type=pygatt.BLEAddressType.random,
75
timeout=10.0)
76
77
# BGAPI-specific connection parameters
78
device = adapter.connect('01:23:45:67:89:ab',
79
interval_min=60,
80
interval_max=76,
81
supervision_timeout=100,
82
latency=0)
83
```
84
85
### Device Scanning
86
87
Discover nearby BLE devices with configurable scan parameters and filtering options.
88
89
```python { .api }
90
def scan(self, *args, **kwargs) -> list:
91
"""
92
Perform BLE device scan to discover nearby devices.
93
94
Args:
95
timeout: Scan duration in seconds
96
**kwargs: Backend-specific scan parameters
97
98
Returns:
99
list: List of discovered device dictionaries containing:
100
- 'address': Device MAC address
101
- 'name': Device name (may be None)
102
- 'rssi': Signal strength
103
104
Raises:
105
BLEError: Scan operation failed
106
"""
107
108
def filtered_scan(self, name_filter: str = "", *args, **kwargs) -> list:
109
"""
110
Scan for BLE devices and filter by device name.
111
112
Args:
113
name_filter: String that must be contained in device name
114
**kwargs: Same as scan() method
115
116
Returns:
117
list: Filtered list of devices matching name filter
118
"""
119
```
120
121
**Usage Example:**
122
123
```python
124
import pygatt
125
126
adapter = pygatt.GATTToolBackend()
127
adapter.start()
128
129
# Basic scan
130
devices = adapter.scan(timeout=10)
131
for device in devices:
132
print(f"Found: {device['address']} - {device['name']} (RSSI: {device['rssi']})")
133
134
# Filtered scan for specific device types
135
fitness_trackers = adapter.filtered_scan("Fitbit", timeout=10)
136
```
137
138
### Bond Management
139
140
Manage stored device bonds and pairing information for encrypted connections.
141
142
```python { .api }
143
def clear_bond(self, address: str = None):
144
"""
145
Clear stored bonding information for a device or all devices.
146
147
Args:
148
address: Specific device MAC address to unbond, or None for all devices
149
150
Note:
151
BGAPI: Clears bonds from adapter's internal storage
152
GATTTool: Uses bluetoothctl to remove system-level bonds
153
"""
154
```
155
156
**Usage Example:**
157
158
```python
159
# Clear bond for specific device
160
adapter.clear_bond('01:23:45:67:89:ab')
161
162
# Clear all bonds
163
adapter.clear_bond()
164
```
165
166
## Backend Selection
167
168
### BGAPI Backend
169
170
Best for cross-platform development and applications requiring:
171
- Windows/macOS/Linux compatibility
172
- USB dongle deployment
173
- Stable, predictable behavior
174
- Advanced BGAPI protocol features
175
176
```python
177
adapter = pygatt.BGAPIBackend()
178
```
179
180
### GATTTool Backend
181
182
Best for Linux-based applications requiring:
183
- Native BlueZ integration
184
- System-level Bluetooth management
185
- Development/debugging capabilities
186
- No additional hardware requirements
187
188
```python
189
adapter = pygatt.GATTToolBackend()
190
```
191
192
## Error Handling
193
194
Common backend management errors and their typical causes:
195
196
- **BGAPIError**: USB device not found, driver issues, permissions
197
- **BLEError**: Bluetooth adapter not available, system configuration
198
- **NotConnectedError**: Device out of range, address type mismatch, device busy