-
Notifications
You must be signed in to change notification settings - Fork 112
/
localGATT.py
536 lines (430 loc) · 18.7 KB
/
localGATT.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
"""Classes required to create a Bluetooth Peripheral."""
# D-Bus imports
import dbus
import dbus.exceptions
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
# python-bluezero imports
from bluezero import async_tools
from bluezero import constants
from bluezero import dbus_tools
from bluezero import tools
DBusGMainLoop(set_as_default=True)
logger = tools.create_module_logger(__name__)
########################################
# Exception classes
#######################################
class InvalidArgsException(dbus.exceptions.DBusException):
"""This is a D-Bus exception class for Invalid Arguments.
All this class does is set the internal variable ``_dbus_error_name`` to
the object path for D-Bus Invalid Argument Exceptions.
"""
_dbus_error_name = 'org.freedesktop.DBus.Error.InvalidArgs'
class Application(dbus.service.Object):
"""Bluez Application Class.
This is the parent class for a python Bluez application.
"""
def __init__(self):
"""Default initialiser.
"""
# Initialise the D-Bus path and register it
self.bus = dbus.SystemBus()
self.path = dbus.ObjectPath(constants.BLUEZERO_DBUS_OBJECT)
dbus.service.Object.__init__(self, self.bus, self.path)
# Objects to be associated with this service
self.managed_objs = []
self.eventloop = async_tools.EventLoop()
@dbus.service.method(constants.DBUS_OM_IFACE,
out_signature='a{oa{sa{sv}}}')
def GetManagedObjects(self): # pylint: disable=invalid-name
"""Get all objects that are managed by the application.
Return type is a dictionary whose keys are each registered object and
values the properties of the given object.
"""
response = {}
for obj in self.managed_objs:
for iface in obj.props.keys():
response[obj.get_path()] = {iface: obj.GetAll(iface)}
return response
def add_managed_object(self, service_obj):
"""Add a service to the list of services offered by the Application.
:param service_obj: Python object of dbus path to be managed
"""
self.managed_objs.append(service_obj)
def get_path(self):
"""Return the DBus object path"""
return dbus.ObjectPath(self.path)
def start(self):
"""Start event loop"""
self.eventloop.run()
def stop(self):
"""Stop event loop"""
self.eventloop.quit()
class Service(dbus.service.Object):
"""Bluez Service Class.
This class represents a BLE Service.
:Example:
>>> your_service = localGATT.Service(service_id, UUID, primary)
"""
PATH_BASE = f'{constants.BLUEZERO_DBUS_OBJECT}/service'
def __init__(self, service_id, uuid, primary):
"""Default initialiser.
1. Registers the service on the D-Bus.
2. Sets up the service UUID and primary flags.
:param service_id:
:param uuid: service BLE UUID
:param primary: whether or not the service is a primary service
"""
# Setup D-Bus object paths and register service
self.path = self.PATH_BASE + str('{0:04d}'.format(service_id))
self.bus = dbus.SystemBus()
self.interface = constants.GATT_SERVICE_IFACE
dbus.service.Object.__init__(self, self.bus, self.path)
self.props = {
constants.GATT_SERVICE_IFACE: {
'UUID': uuid,
'Primary': primary}
}
def get_path(self):
"""Return the DBus object path"""
return dbus.ObjectPath(self.path)
@dbus.service.method(constants.DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface_name): # pylint: disable=invalid-name
"""Return the service properties.
This method is registered with the D-Bus at
``org.freedesktop.DBus.Properties``
:param interface_name: interface to get the properties of.
The interface must be ``org.bluez.GattService1`` otherwise an
exception is raised.
"""
if interface_name != constants.GATT_SERVICE_IFACE:
raise InvalidArgsException()
try:
return self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such interface ' + interface_name,
name=interface_name + '.UnknownInterface')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ss', out_signature='v')
def Get(self, # pylint: disable=invalid-name
interface_name, property_name):
"""
DBus API for getting a property value
:param interface_name:
:param property_name:
:return:
"""
if interface_name != constants.GATT_SERVICE_IFACE:
raise InvalidArgsException()
try:
return self.GetAll(interface_name)[property_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=interface_name + '.UnknownProperty')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ssv', out_signature='')
def Set(self, interface_name, # pylint: disable=invalid-name
property_name, value):
"""Standard D-Bus API for setting a property value"""
try:
iface_props = self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such interface ' + interface_name,
name=self.interface + '.UnknownInterface')
if property_name not in iface_props:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=self.interface + '.UnknownProperty')
iface_props[property_name] = value
self.PropertiesChanged(interface_name,
dbus.Dictionary({property_name: value},
signature='sv'),
dbus.Array([], signature='s'))
@dbus.service.signal(constants.DBUS_PROP_IFACE,
signature='sa{sv}as')
def PropertiesChanged(self, # pylint: disable=invalid-name
interface, changed, invalidated):
"""Emit a Properties Changed notification signal.
This signal is registered with the D-Bus at
``org.freedesktop.DBus.Properties``.
"""
logger.debug('Service properties changed: %s, %s, %s',
interface, changed, invalidated)
class Characteristic(dbus.service.Object):
"""
Bluez Characteristic Class.
This class represents a BLE Characteristic.
"""
def __init__(self,
service_id,
characteristic_id,
uuid,
value,
notifying,
flags,
read_callback=None,
write_callback=None,
notify_callback=None):
self.read_callback = read_callback
self.write_callback = write_callback
self.notify_callback = notify_callback
# Setup D-Bus object paths and register service
service_path = (f'{constants.BLUEZERO_DBUS_OBJECT}/'
f'service{service_id:04d}')
self.path = f'{service_path}/char{characteristic_id:04d}'
self.bus = dbus.SystemBus()
dbus.service.Object.__init__(self, self.bus, self.path)
self.props = {
constants.GATT_CHRC_IFACE: {
'UUID': uuid,
'Service': dbus_tools.get_dbus_obj(service_path),
'Value': dbus.Array(value, signature='y'),
'Notifying': notifying,
'Flags': flags}
}
for prop in self.props[constants.GATT_CHRC_IFACE].keys():
self.Set(constants.GATT_CHRC_IFACE,
prop,
self.props[constants.GATT_CHRC_IFACE][prop])
def get_path(self):
"""Return the DBus object path"""
return dbus.ObjectPath(self.path)
@property
def is_notifying(self):
"""Get the current notify status"""
return bool(self.Get(constants.GATT_CHRC_IFACE, 'Notifying'))
def set_value(self, value):
"""
Set the value of the characteristic. Will create notify event
if notifications are enabled
:param value: list of integers in little endian format
"""
self.Set(constants.GATT_CHRC_IFACE, 'Value',
dbus.Array(value, signature='y'))
@dbus.service.method(constants.DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface_name): # pylint: disable=invalid-name
"""Return the service properties.
This method is registered with the D-Bus at
``org.freedesktop.DBus.Properties``
:param interface_name: interface to get the properties of.
The interface must be ``org.bluez.GattCharacteristic1`` otherwise an
exception is raised.
"""
if interface_name != constants.GATT_CHRC_IFACE:
raise InvalidArgsException()
try:
return self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such interface ' + interface_name,
name=interface_name + '.UnknownInterface')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ss', out_signature='v')
def Get(self, # pylint: disable=invalid-name
interface_name, property_name):
"""DBus API for getting a property value.
This method is registered with the D-Bus at
``org.freedesktop.DBus.Properties``
:param interface_name: interface to get the properties of.
:param property_name: request this property
"""
if interface_name != constants.GATT_CHRC_IFACE:
raise InvalidArgsException()
try:
return self.GetAll(interface_name)[property_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=interface_name + '.UnknownProperty')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ssv', out_signature='')
def Set(self, interface_name, # pylint: disable=invalid-name
property_name, value):
"""Standard D-Bus API for setting a property value"""
if property_name not in self.props[constants.GATT_CHRC_IFACE]:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=constants.GATT_CHRC_IFACE + '.UnknownProperty')
self.props[constants.GATT_CHRC_IFACE][property_name] = value
return self.PropertiesChanged(interface_name,
dbus.Dictionary({property_name: value},
signature='sv'),
dbus.Array([], signature='s'))
@dbus.service.signal(constants.DBUS_PROP_IFACE,
signature='sa{sv}as')
def PropertiesChanged(self, # pylint: disable=invalid-name
interface, changed, invalidated):
"""Emit a Properties Changed notification signal.
This signal is registered with the D-Bus at
``org.freedesktop.DBus.Properties``.
"""
logger.debug('Char Prop Changed')
@dbus.service.method(constants.GATT_CHRC_IFACE,
in_signature='a{sv}', out_signature='ay')
def ReadValue(self, options): # pylint: disable=invalid-name
"""
DBus method for getting the characteristic value
:return: value
"""
if self.read_callback:
value = self.read_callback()
self.Set(constants.GATT_CHRC_IFACE, 'Value',
dbus.Array(value, signature='y'))
logger.debug('ReadValue: %s', value)
return self.GetAll(constants.GATT_CHRC_IFACE)['Value']
@dbus.service.method(constants.GATT_CHRC_IFACE,
in_signature='aya{sv}', out_signature='')
def WriteValue(self, value, options): # pylint: disable=invalid-name
"""
DBus method for setting the characteristic value
:return: value
"""
if self.write_callback:
self.write_callback(dbus_tools.dbus_to_python(value),
dbus_tools.dbus_to_python(options))
self.Set(constants.GATT_CHRC_IFACE, 'Value', value)
@dbus.service.method(constants.GATT_CHRC_IFACE,
in_signature='', out_signature='')
def StartNotify(self): # pylint: disable=invalid-name
"""
DBus method for enabling notifications of the characteristic value.
:return: value
"""
if self.props[constants.GATT_CHRC_IFACE]['Notifying'] is True:
logger.info('Notifying already, nothing to do')
return
self.Set(constants.GATT_CHRC_IFACE,
'Notifying',
dbus.Boolean(True, variant_level=1))
if self.notify_callback:
self.notify_callback(True, self)
@dbus.service.method(constants.GATT_CHRC_IFACE,
in_signature='', out_signature='')
def StopNotify(self): # pylint: disable=invalid-name
"""
DBus method for disabling notifications of the characteristic value.
:return: value
"""
if self.props[constants.GATT_CHRC_IFACE]['Notifying'] is False:
logger.info('Not Notifying, nothing to do')
return
self.Set(constants.GATT_CHRC_IFACE,
'Notifying',
dbus.Boolean(False, variant_level=1))
if self.notify_callback:
self.notify_callback(False, self)
class Descriptor(dbus.service.Object):
"""
Bluez Descriptor Class.
This class represents a BLE Descriptor.
"""
def __init__(self,
service_id,
characteristic_id,
descriptor_id,
uuid,
value,
flags):
# Setup D-Bus object paths and register service
char_path = (f'{constants.BLUEZERO_DBUS_OBJECT}/'
f'service{service_id:04d}/char{characteristic_id:04d}')
self.path = f'{char_path}/desc{descriptor_id:04d}'
self.bus = dbus.SystemBus()
dbus.service.Object.__init__(self, self.bus, self.path)
self.props = {
constants.GATT_DESC_IFACE: {
'UUID': uuid,
'Characteristic': dbus_tools.get_dbus_obj(char_path),
'Value': value,
'Flags': flags}
}
for prop in self.props[constants.GATT_DESC_IFACE].keys():
self.Set(constants.GATT_DESC_IFACE,
prop,
self.props[constants.GATT_DESC_IFACE][prop])
def get_path(self):
"""Return the DBus object path"""
return dbus.ObjectPath(self.path)
@dbus.service.method(constants.DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface_name): # pylint: disable=invalid-name
"""Return the descriptor properties.
This method is registered with the D-Bus at
``org.freedesktop.DBus.Properties``
:param interface: interface to get the properties of.
The interface must be ``org.bluez.GattDescriptor1`` otherwise an
exception is raised.
"""
if interface_name != constants.GATT_DESC_IFACE:
raise InvalidArgsException()
try:
return self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such interface ' + interface_name,
name=interface_name + '.UnknownInterface')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ss', out_signature='v')
def Get(self, # pylint: disable=invalid-name
interface_name, property_name):
"""DBus API for getting a property value.
This method is registered with the D-Bus at
``org.freedesktop.DBus.Properties``
:param interface_name: interface to get the properties of.
:param property_name: request this property
"""
if interface_name != constants.GATT_DESC_IFACE:
raise InvalidArgsException()
try:
return self.GetAll(interface_name)[property_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=interface_name + '.UnknownProperty')
@dbus.service.method(dbus.PROPERTIES_IFACE,
in_signature='ssv', out_signature='')
def Set(self, interface_name, # pylint: disable=invalid-name
property_name, value):
"""Standard D-Bus API for setting a property value"""
if property_name not in self.props[constants.GATT_DESC_IFACE]:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=constants.GATT_DESC_IFACE + '.UnknownProperty')
self.props[interface_name][property_name] = value
return self.PropertiesChanged(interface_name,
dbus.Dictionary({property_name: value},
signature='sv'),
dbus.Array([], signature='s'))
@dbus.service.signal(constants.DBUS_PROP_IFACE,
signature='sa{sv}as')
def PropertiesChanged(self, # pylint: disable=invalid-name
interface, changed, invalidated):
"""Emit a Properties Changed notification signal.
This signal is registered with the D-Bus at
``org.freedesktop.DBus.Properties``.
"""
return 0
@dbus.service.method(constants.GATT_DESC_IFACE,
in_signature='a{sv}', out_signature='ay')
def ReadValue(self, options): # pylint: disable=invalid-name
"""
DBus method for getting the characteristic value
:return: value
"""
return self.GetAll(constants.GATT_DESC_IFACE)['Value']
@dbus.service.method(constants.GATT_DESC_IFACE,
in_signature='aya{sv}', out_signature='')
def WriteValue(self, value, options): # pylint: disable=invalid-name
"""
DBus method for setting the descriptor value
:return:
"""
return self.Set(constants.GATT_DESC_IFACE, 'Value', value)