-
Notifications
You must be signed in to change notification settings - Fork 186
/
device.py
383 lines (310 loc) · 13.2 KB
/
device.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
from __future__ import print_function
import threading
import logging
from collections import defaultdict
from binascii import hexlify
from uuid import UUID
from . import exceptions
try:
string_type = basestring
except NameError:
string_type = str
log = logging.getLogger(__name__)
class BLEDevice(object):
"""
An BLE device connection instance, returned by one of the BLEBackend
implementations. This class is not meant to be instantiated directly - use
BLEBackend.connect() to create one.
"""
def __init__(self, address):
"""
Initialize.
address -- the BLE address (aka MAC address) of the device as a string.
"""
self._address = address
self._characteristics = {}
self._callbacks = defaultdict(set)
self._subscribed_handlers = {}
self._subscribed_uuids = {}
self._lock = threading.Lock()
def bond(self, permanent=False):
"""
Create a new bond or use an existing bond with the device and make the
current connection bonded and encrypted.
"""
raise NotImplementedError()
def get_rssi(self):
"""
Get the receiver signal strength indicator (RSSI) value from the BLE
device.
Returns the RSSI value in dBm on success.
Returns None on failure.
"""
raise NotImplementedError()
def char_read(self, uuid):
"""
Reads a Characteristic by UUID.
uuid -- UUID of Characteristic to read as a string.
Returns a bytearray containing the characteristic value on success.
Example:
my_ble_device.char_read('a1e8f5b1-696b-4e4c-87c6-69dfe0b0093b')
"""
raise NotImplementedError()
def char_read_handle(self, uuid):
"""
Reads a Characteristic by handle.
handle -- handle of Characteristic to read.
Returns a bytearray containing the characteristic value on success.
Example:
my_ble_device.char_read_handle(5)
"""
raise NotImplementedError()
def char_read_long(self, uuid):
"""
Reads a Characteristic by UUID.
uuid -- UUID of Characteristic to read as a string.
Returns a bytearray containing the characteristic value on success.
Example:
my_ble_device.char_read('a1e8f5b1-696b-4e4c-87c6-69dfe0b0093b')
"""
raise NotImplementedError()
def char_read_long_handle(self, handle):
"""
Reads a Characteristic longer than one read by handle.
handle -- handle of Characteristic to read.
Returns a bytearray containing the characteristic value on success.
Example:
my_ble_device.char_read_long_handle(5)
"""
raise NotImplementedError()
def char_write(self, uuid, value, wait_for_response=True):
"""
Writes a value to a given characteristic UUID.
uuid -- the UUID of the characteristic to write to.
value -- a bytearray to write to the characteristic.
wait_for_response -- wait for response after writing. A GATT "command"
is used when not waiting for a response. The remote host will not
acknowledge the write.
Example:
my_ble_device.char_write('a1e8f5b1-696b-4e4c-87c6-69dfe0b0093b',
bytearray([0x00, 0xFF]))
"""
return self.char_write_handle(self.get_handle(uuid), value,
wait_for_response=wait_for_response)
def char_write_handle(self, handle, value, wait_for_response=True):
"""
Writes a value to a given characteristic handle. This can be used to
write to the characteristic config handle for a primary characteristic.
handle -- the handle to write to.
value -- a bytearray to write to the characteristic.
wait_for_response -- wait for response after writing.
Example:
my_ble_device.char_write_handle(42, bytearray([0x00, 0xFF]))
"""
raise NotImplementedError()
def char_write_long(self, uuid, value, wait_for_response=False):
"""
Writes a value to a given characteristic UUID.
uuid -- the UUID of the characteristic to write to.
value -- a bytearray to write to the characteristic.
wait_for_response -- wait for response after writing.
Example:
my_ble_device.char_write('a1e8f5b1-696b-4e4c-87c6-69dfe0b0093b',
bytearray([0x00, 0xFF]))
"""
return self.char_write_long_handle(self.get_handle(uuid), value,
wait_for_response=wait_for_response)
def char_write_long_handle(self, handle, value, wait_for_response=False):
"""
Writes a value to a given characteristic handle. This can be used to
write to the characteristic config handle for a primary characteristic.
handle -- the handle to write to.
value -- a bytearray to write to the characteristic.
wait_for_response -- wait for response after writing.
Example:
my_ble_device.char_write(42,
bytearray([0x00, 0xFF]))
"""
raise NotImplementedError()
def disconnect(self):
"""
Disconnect from the device. This instance of BLEDevice cannot be used
after calling this method, you must call BLEBackend.connect() again to
get a fresh connection.
"""
raise NotImplementedError()
def _notification_handles(self, uuid):
# Expect notifications on the value handle...
value_handle = self.get_handle(uuid)
# but write to the characteristic config to enable notifications
# TODO with the BGAPI backend we can be smarter and fetch the actual
# characteristic config handle - we can also do that with gattool if we
# use the 'desc' command, so we'll need to change the "get_handle" API
# to be able to get the value or characteristic config handle.
characteristic_config_handle = value_handle + 1
return value_handle, characteristic_config_handle
def subscribe(self, uuid, callback=None, indication=False,
wait_for_response=True):
"""
Enable notifications or indications for a characteristic and register a
callback function to be called whenever a new value arrives.
uuid -- UUID as a string of the characteristic to subscribe.
callback -- function to be called when a notification/indication is
received on this characteristic.
indication -- use indications (where each notificaiton is ACKd). This is
more reliable, but slower.
wait_for_response -- wait for response after subscription.
"""
value_handle, characteristic_config_handle = (
self._notification_handles(uuid)
)
properties = bytearray([
0x2 if indication else 0x1,
0x0
])
with self._lock:
if callback is not None:
self._callbacks[value_handle].add(callback)
if self._subscribed_handlers.get(value_handle, None) != properties:
self.char_write_handle(
characteristic_config_handle,
properties,
wait_for_response=wait_for_response
)
log.info("Subscribed to uuid=%s", uuid)
self._subscribed_handlers[value_handle] = properties
self._subscribed_uuids[uuid] = indication
else:
log.debug("Already subscribed to uuid=%s", uuid)
def unsubscribe(self, uuid, wait_for_response=True):
"""
Disable notification for a characteristic and de-register the callback.
"""
value_handle, characteristic_config_handle = (
self._notification_handles(uuid)
)
properties = bytearray([0x0, 0x0])
with self._lock:
if uuid in self._subscribed_uuids:
del(self._subscribed_uuids[uuid])
if value_handle in self._callbacks:
del(self._callbacks[value_handle])
if value_handle in self._subscribed_handlers:
del(self._subscribed_handlers[value_handle])
self.char_write_handle(
characteristic_config_handle,
properties,
wait_for_response=wait_for_response
)
log.info("Unsubscribed from uuid=%s", uuid)
else:
log.debug("Already unsubscribed from uuid=%s", uuid)
def subscribe_handle(self, handle, callback=None, indication=False,
wait_for_response=True):
"""
Like subscribe() but using handle instead of uuid.
handle -- handle as a integer of the characteristic to subscribe.
"""
value_handle = handle
characteristic_config_handle = value_handle + 1
properties = bytearray([
0x2 if indication else 0x1,
0x0
])
with self._lock:
if callback is not None:
self._callbacks[value_handle].add(callback)
if self._subscribed_handlers.get(value_handle, None) != properties:
self.char_write_handle(
characteristic_config_handle,
properties,
wait_for_response=wait_for_response
)
log.info("Subscribed to handle=0x%04x", value_handle)
self._subscribed_handlers[value_handle] = properties
else:
log.debug("Already subscribed to handle=0x%04x", value_handle)
def unsubscribe_handle(self, handle, wait_for_response=True):
"""
Like unsubscribe() but using handle instead of uuid.
handle -- handle as a integer of the characteristic to unsubscribe.
"""
value_handle = handle
characteristic_config_handle = value_handle + 1
properties = bytearray([0x0, 0x0])
with self._lock:
if value_handle in self._callbacks:
del(self._callbacks[value_handle])
if value_handle in self._subscribed_handlers:
del(self._subscribed_handlers[value_handle])
self.char_write_handle(
characteristic_config_handle,
properties,
wait_for_response=wait_for_response
)
log.info("Unsubscribed from handle=0x%04x", value_handle)
else:
log.debug(
"Already unsubscribed from handle=0x%04x",
value_handle
)
def get_handle(self, char_uuid):
"""
Look up and return the handle for an attribute by its UUID.
:param char_uuid: The UUID of the characteristic.
:type uuid: str
:return: None if the UUID was not found.
"""
if isinstance(char_uuid, string_type):
char_uuid = UUID(char_uuid)
log.debug("Looking up handle for characteristic %s", char_uuid)
if char_uuid not in self._characteristics:
self._characteristics = self.discover_characteristics()
characteristic = self._characteristics.get(char_uuid)
if characteristic is None:
message = "No characteristic found matching %s" % char_uuid
log.warn(message)
raise exceptions.BLEError(message)
# TODO support filtering by descriptor UUID, or maybe return the whole
# Characteristic object
log.debug("Found %s" % characteristic)
return characteristic.handle
def receive_notification(self, handle, value):
"""
Receive a notification from the connected device and propagate the value
to all registered callbacks.
"""
log.info('Received notification on handle=0x%x, value=0x%s',
handle, hexlify(value))
with self._lock:
if handle in self._callbacks:
for callback in self._callbacks[handle]:
callback(handle, value)
def exchange_mtu(self, mtu):
"""
ATT exchange Maximum Transmission Unit.
:param mtu: New MTU-value
:return: New MTU, as recognized by server.
"""
raise NotImplementedError()
def resubscribe_all(self):
"""
Reenable all notifications and indications for uuids that were
previously subscribed to.
This has to be called after a connection loss and subsequent reconnect.
"""
for uuid in self._subscribed_uuids:
value_handle, characteristic_config_handle = (
self._notification_handles(uuid)
)
properties = bytearray([
0x2 if self._subscribed_uuids[uuid] else 0x1,
0x0
])
with self._lock:
self.char_write_handle(
characteristic_config_handle,
properties,
wait_for_response=True
)
log.info("Resubscribed to uuid=%s", uuid)