Debian Codegraph @

test/example-gatt-server

raw symbols SCIP
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import dbus
5 import dbus.exceptions
6 import dbus.mainloop.glib
7 import dbus.service
8
9 import array
10 from gi.repository import GLib
11 import sys
12
13 from random import randint
14
15 mainloop = None
16
17 BLUEZ_SERVICE_NAME = 'org.bluez'
18 GATT_MANAGER_IFACE = 'org.bluez.GattManager1'
19 DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager'
20 DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties'
21
22 GATT_SERVICE_IFACE = 'org.bluez.GattService1'
23 GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1'
24 GATT_DESC_IFACE = 'org.bluez.GattDescriptor1'
25
26 class InvalidArgsException(dbus.exceptions.DBusException):
27 _dbus_error_name = 'org.freedesktop.DBus.Error.InvalidArgs'
28
29 class NotSupportedException(dbus.exceptions.DBusException):
30 _dbus_error_name = 'org.bluez.Error.NotSupported'
31
32 class NotPermittedException(dbus.exceptions.DBusException):
33 _dbus_error_name = 'org.bluez.Error.NotPermitted'
34
35 class InvalidValueLengthException(dbus.exceptions.DBusException):
36 _dbus_error_name = 'org.bluez.Error.InvalidValueLength'
37
38 class FailedException(dbus.exceptions.DBusException):
39 _dbus_error_name = 'org.bluez.Error.Failed'
40
41
42 class Application(dbus.service.Object):
43 """
44 org.bluez.GattApplication1 interface implementation
45 """
46 def __init__(self, bus):
47 self.path = '/'
48 self.services = []
49 dbus.service.Object.__init__(self, bus, self.path)
50 self.add_service(HeartRateService(bus, 0))
51 self.add_service(BatteryService(bus, 1))
52 self.add_service(TestService(bus, 2))
53
54 def get_path(self):
55 return dbus.ObjectPath(self.path)
56
57 def add_service(self, service):
58 self.services.append(service)
59
60 @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')
61 def GetManagedObjects(self):
62 response = {}
63 print('GetManagedObjects')
64
65 for service in self.services:
66 response[service.get_path()] = service.get_properties()
67 chrcs = service.get_characteristics()
68 for chrc in chrcs:
69 response[chrc.get_path()] = chrc.get_properties()
70 descs = chrc.get_descriptors()
71 for desc in descs:
72 response[desc.get_path()] = desc.get_properties()
73
74 return response
75
76
77 class Service(dbus.service.Object):
78 """
79 org.bluez.GattService1 interface implementation
80 """
81 PATH_BASE = '/org/bluez/example/service'
82
83 def __init__(self, bus, index, uuid, primary):
84 self.path = self.PATH_BASE + str(index)
85 self.bus = bus
86 self.uuid = uuid
87 self.primary = primary
88 self.characteristics = []
89 dbus.service.Object.__init__(self, bus, self.path)
90
91 def get_properties(self):
92 return {
93 GATT_SERVICE_IFACE: {
94 'UUID': self.uuid,
95 'Primary': self.primary,
96 'Characteristics': dbus.Array(
97 self.get_characteristic_paths(),
98 signature='o')
99 }
100 }
101
102 def get_path(self):
103 return dbus.ObjectPath(self.path)
104
105 def add_characteristic(self, characteristic):
106 self.characteristics.append(characteristic)
107
108 def get_characteristic_paths(self):
109 result = []
110 for chrc in self.characteristics:
111 result.append(chrc.get_path())
112 return result
113
114 def get_characteristics(self):
115 return self.characteristics
116
117 @dbus.service.method(DBUS_PROP_IFACE,
118 in_signature='s',
119 out_signature='a{sv}')
120 def GetAll(self, interface):
121 if interface != GATT_SERVICE_IFACE:
122 raise InvalidArgsException()
123
124 return self.get_properties()[GATT_SERVICE_IFACE]
125
126
127 class Characteristic(dbus.service.Object):
128 """
129 org.bluez.GattCharacteristic1 interface implementation
130 """
131 def __init__(self, bus, index, uuid, flags, service):
132 self.path = service.path + '/char' + str(index)
133 self.bus = bus
134 self.uuid = uuid
135 self.service = service
136 self.flags = flags
137 self.descriptors = []
138 dbus.service.Object.__init__(self, bus, self.path)
139
140 def get_properties(self):
141 return {
142 GATT_CHRC_IFACE: {
143 'Service': self.service.get_path(),
144 'UUID': self.uuid,
145 'Flags': self.flags,
146 'Descriptors': dbus.Array(
147 self.get_descriptor_paths(),
148 signature='o')
149 }
150 }
151
152 def get_path(self):
153 return dbus.ObjectPath(self.path)
154
155 def add_descriptor(self, descriptor):
156 self.descriptors.append(descriptor)
157
158 def get_descriptor_paths(self):
159 result = []
160 for desc in self.descriptors:
161 result.append(desc.get_path())
162 return result
163
164 def get_descriptors(self):
165 return self.descriptors
166
167 @dbus.service.method(DBUS_PROP_IFACE,
168 in_signature='s',
169 out_signature='a{sv}')
170 def GetAll(self, interface):
171 if interface != GATT_CHRC_IFACE:
172 raise InvalidArgsException()
173
174 return self.get_properties()[GATT_CHRC_IFACE]
175
176 @dbus.service.method(GATT_CHRC_IFACE,
177 in_signature='a{sv}',
178 out_signature='ay')
179 def ReadValue(self, options):
180 print('Default ReadValue called, returning error')
181 raise NotSupportedException()
182
183 @dbus.service.method(GATT_CHRC_IFACE, in_signature='aya{sv}')
184 def WriteValue(self, value, options):
185 print('Default WriteValue called, returning error')
186 raise NotSupportedException()
187
188 @dbus.service.method(GATT_CHRC_IFACE)
189 def StartNotify(self):
190 print('Default StartNotify called, returning error')
191 raise NotSupportedException()
192
193 @dbus.service.method(GATT_CHRC_IFACE)
194 def StopNotify(self):
195 print('Default StopNotify called, returning error')
196 raise NotSupportedException()
197
198 @dbus.service.signal(DBUS_PROP_IFACE,
199 signature='sa{sv}as')
200 def PropertiesChanged(self, interface, changed, invalidated):
201 pass
202
203
204 class Descriptor(dbus.service.Object):
205 """
206 org.bluez.GattDescriptor1 interface implementation
207 """
208 def __init__(self, bus, index, uuid, flags, characteristic):
209 self.path = characteristic.path + '/desc' + str(index)
210 self.bus = bus
211 self.uuid = uuid
212 self.flags = flags
213 self.chrc = characteristic
214 dbus.service.Object.__init__(self, bus, self.path)
215
216 def get_properties(self):
217 return {
218 GATT_DESC_IFACE: {
219 'Characteristic': self.chrc.get_path(),
220 'UUID': self.uuid,
221 'Flags': self.flags,
222 }
223 }
224
225 def get_path(self):
226 return dbus.ObjectPath(self.path)
227
228 @dbus.service.method(DBUS_PROP_IFACE,
229 in_signature='s',
230 out_signature='a{sv}')
231 def GetAll(self, interface):
232 if interface != GATT_DESC_IFACE:
233 raise InvalidArgsException()
234
235 return self.get_properties()[GATT_DESC_IFACE]
236
237 @dbus.service.method(GATT_DESC_IFACE,
238 in_signature='a{sv}',
239 out_signature='ay')
240 def ReadValue(self, options):
241 print ('Default ReadValue called, returning error')
242 raise NotSupportedException()
243
244 @dbus.service.method(GATT_DESC_IFACE, in_signature='aya{sv}')
245 def WriteValue(self, value, options):
246 print('Default WriteValue called, returning error')
247 raise NotSupportedException()
248
249
250 class HeartRateService(Service):
251 """
252 Fake Heart Rate Service that simulates a fake heart beat and control point
253 behavior.
254
255 """
256 HR_UUID = '0000180d-0000-1000-8000-00805f9b34fb'
257
258 def __init__(self, bus, index):
259 Service.__init__(self, bus, index, self.HR_UUID, True)
260 self.add_characteristic(HeartRateMeasurementChrc(bus, 0, self))
261 self.add_characteristic(BodySensorLocationChrc(bus, 1, self))
262 self.add_characteristic(HeartRateControlPointChrc(bus, 2, self))
263 self.energy_expended = 0
264
265
266 class HeartRateMeasurementChrc(Characteristic):
267 HR_MSRMT_UUID = '00002a37-0000-1000-8000-00805f9b34fb'
268
269 def __init__(self, bus, index, service):
270 Characteristic.__init__(
271 self, bus, index,
272 self.HR_MSRMT_UUID,
273 ['notify'],
274 service)
275 self.notifying = False
276 self.hr_ee_count = 0
277
278 def hr_msrmt_cb(self):
279 value = []
280 value.append(dbus.Byte(0x06))
281
282 value.append(dbus.Byte(randint(90, 130)))
283
284 if self.hr_ee_count % 10 == 0:
285 value[0] = dbus.Byte(value[0] | 0x08)
286 value.append(dbus.Byte(self.service.energy_expended & 0xff))
287 value.append(dbus.Byte((self.service.energy_expended >> 8) & 0xff))
288
289 self.service.energy_expended = \
290 min(0xffff, self.service.energy_expended + 1)
291 self.hr_ee_count += 1
292
293 print('Updating value: ' + repr(value))
294
295 self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': value }, [])
296
297 return self.notifying
298
299 def _update_hr_msrmt_simulation(self):
300 print('Update HR Measurement Simulation')
301
302 if not self.notifying:
303 return
304
305 GLib.timeout_add(1000, self.hr_msrmt_cb)
306
307 def StartNotify(self):
308 if self.notifying:
309 print('Already notifying, nothing to do')
310 return
311
312 self.notifying = True
313 self._update_hr_msrmt_simulation()
314
315 def StopNotify(self):
316 if not self.notifying:
317 print('Not notifying, nothing to do')
318 return
319
320 self.notifying = False
321 self._update_hr_msrmt_simulation()
322
323
324 class BodySensorLocationChrc(Characteristic):
325 BODY_SNSR_LOC_UUID = '00002a38-0000-1000-8000-00805f9b34fb'
326
327 def __init__(self, bus, index, service):
328 Characteristic.__init__(
329 self, bus, index,
330 self.BODY_SNSR_LOC_UUID,
331 ['read'],
332 service)
333
334 def ReadValue(self, options):
335 # Return 'Chest' as the sensor location.
336 return [ 0x01 ]
337
338 class HeartRateControlPointChrc(Characteristic):
339 HR_CTRL_PT_UUID = '00002a39-0000-1000-8000-00805f9b34fb'
340
341 def __init__(self, bus, index, service):
342 Characteristic.__init__(
343 self, bus, index,
344 self.HR_CTRL_PT_UUID,
345 ['write'],
346 service)
347
348 def WriteValue(self, value, options):
349 print('Heart Rate Control Point WriteValue called')
350
351 if len(value) != 1:
352 raise InvalidValueLengthException()
353
354 byte = value[0]
355 print('Control Point value: ' + repr(byte))
356
357 if byte != 1:
358 raise FailedException("0x80")
359
360 print('Energy Expended field reset!')
361 self.service.energy_expended = 0
362
363
364 class BatteryService(Service):
365 """
366 Fake Battery service that emulates a draining battery.
367
368 """
369 BATTERY_UUID = '180f'
370
371 def __init__(self, bus, index):
372 Service.__init__(self, bus, index, self.BATTERY_UUID, True)
373 self.add_characteristic(BatteryLevelCharacteristic(bus, 0, self))
374
375
376 class BatteryLevelCharacteristic(Characteristic):
377 """
378 Fake Battery Level characteristic. The battery level is drained by 2 points
379 every 5 seconds.
380
381 """
382 BATTERY_LVL_UUID = '2a19'
383
384 def __init__(self, bus, index, service):
385 Characteristic.__init__(
386 self, bus, index,
387 self.BATTERY_LVL_UUID,
388 ['read', 'notify'],
389 service)
390 self.notifying = False
391 self.battery_lvl = 100
392 GLib.timeout_add(5000, self.drain_battery)
393
394 def notify_battery_level(self):
395 if not self.notifying:
396 return
397 self.PropertiesChanged(
398 GATT_CHRC_IFACE,
399 { 'Value': [dbus.Byte(self.battery_lvl)] }, [])
400
401 def drain_battery(self):
402 if not self.notifying:
403 return True
404 if self.battery_lvl > 0:
405 self.battery_lvl -= 2
406 if self.battery_lvl < 0:
407 self.battery_lvl = 0
408 print('Battery Level drained: ' + repr(self.battery_lvl))
409 self.notify_battery_level()
410 return True
411
412 def ReadValue(self, options):
413 print('Battery Level read: ' + repr(self.battery_lvl))
414 return [dbus.Byte(self.battery_lvl)]
415
416 def StartNotify(self):
417 if self.notifying:
418 print('Already notifying, nothing to do')
419 return
420
421 self.notifying = True
422 self.notify_battery_level()
423
424 def StopNotify(self):
425 if not self.notifying:
426 print('Not notifying, nothing to do')
427 return
428
429 self.notifying = False
430
431
432 class TestService(Service):
433 """
434 Dummy test service that provides characteristics and descriptors that
435 exercise various API functionality.
436
437 """
438 TEST_SVC_UUID = '12345678-1234-5678-1234-56789abcdef0'
439
440 def __init__(self, bus, index):
441 Service.__init__(self, bus, index, self.TEST_SVC_UUID, True)
442 self.add_characteristic(TestCharacteristic(bus, 0, self))
443 self.add_characteristic(TestEncryptCharacteristic(bus, 1, self))
444 self.add_characteristic(TestSecureCharacteristic(bus, 2, self))
445
446 class TestCharacteristic(Characteristic):
447 """
448 Dummy test characteristic. Allows writing arbitrary bytes to its value, and
449 contains "extended properties", as well as a test descriptor.
450
451 """
452 TEST_CHRC_UUID = '12345678-1234-5678-1234-56789abcdef1'
453
454 def __init__(self, bus, index, service):
455 Characteristic.__init__(
456 self, bus, index,
457 self.TEST_CHRC_UUID,
458 ['read', 'write', 'writable-auxiliaries'],
459 service)
460 self.value = []
461 self.add_descriptor(TestDescriptor(bus, 0, self))
462 self.add_descriptor(
463 CharacteristicUserDescriptionDescriptor(bus, 1, self))
464
465 def ReadValue(self, options):
466 print('TestCharacteristic Read: ' + repr(self.value))
467 return self.value
468
469 def WriteValue(self, value, options):
470 print('TestCharacteristic Write: ' + repr(value))
471 self.value = value
472
473
474 class TestDescriptor(Descriptor):
475 """
476 Dummy test descriptor. Returns a static value.
477
478 """
479 TEST_DESC_UUID = '12345678-1234-5678-1234-56789abcdef2'
480
481 def __init__(self, bus, index, characteristic):
482 Descriptor.__init__(
483 self, bus, index,
484 self.TEST_DESC_UUID,
485 ['read', 'write'],
486 characteristic)
487
488 def ReadValue(self, options):
489 return [
490 dbus.Byte('T'), dbus.Byte('e'), dbus.Byte('s'), dbus.Byte('t')
491 ]
492
493
494 class CharacteristicUserDescriptionDescriptor(Descriptor):
495 """
496 Writable CUD descriptor.
497
498 """
499 CUD_UUID = '2901'
500
501 def __init__(self, bus, index, characteristic):
502 self.writable = 'writable-auxiliaries' in characteristic.flags
503 self.value = array.array('B', b'This is a characteristic for testing')
504 self.value = self.value.tolist()
505 Descriptor.__init__(
506 self, bus, index,
507 self.CUD_UUID,
508 ['read', 'write'],
509 characteristic)
510
511 def ReadValue(self, options):
512 return self.value
513
514 def WriteValue(self, value, options):
515 if not self.writable:
516 raise NotPermittedException()
517 self.value = value
518
519 class TestEncryptCharacteristic(Characteristic):
520 """
521 Dummy test characteristic requiring encryption.
522
523 """
524 TEST_CHRC_UUID = '12345678-1234-5678-1234-56789abcdef3'
525
526 def __init__(self, bus, index, service):
527 Characteristic.__init__(
528 self, bus, index,
529 self.TEST_CHRC_UUID,
530 ['encrypt-read', 'encrypt-write'],
531 service)
532 self.value = []
533 self.add_descriptor(TestEncryptDescriptor(bus, 2, self))
534 self.add_descriptor(
535 CharacteristicUserDescriptionDescriptor(bus, 3, self))
536
537 def ReadValue(self, options):
538 print('TestEncryptCharacteristic Read: ' + repr(self.value))
539 return self.value
540
541 def WriteValue(self, value, options):
542 print('TestEncryptCharacteristic Write: ' + repr(value))
543 self.value = value
544
545 class TestEncryptDescriptor(Descriptor):
546 """
547 Dummy test descriptor requiring encryption. Returns a static value.
548
549 """
550 TEST_DESC_UUID = '12345678-1234-5678-1234-56789abcdef4'
551
552 def __init__(self, bus, index, characteristic):
553 Descriptor.__init__(
554 self, bus, index,
555 self.TEST_DESC_UUID,
556 ['encrypt-read', 'encrypt-write'],
557 characteristic)
558
559 def ReadValue(self, options):
560 return [
561 dbus.Byte('T'), dbus.Byte('e'), dbus.Byte('s'), dbus.Byte('t')
562 ]
563
564
565 class TestSecureCharacteristic(Characteristic):
566 """
567 Dummy test characteristic requiring secure connection.
568
569 """
570 TEST_CHRC_UUID = '12345678-1234-5678-1234-56789abcdef5'
571
572 def __init__(self, bus, index, service):
573 Characteristic.__init__(
574 self, bus, index,
575 self.TEST_CHRC_UUID,
576 ['secure-read', 'secure-write'],
577 service)
578 self.value = []
579 self.add_descriptor(TestSecureDescriptor(bus, 2, self))
580 self.add_descriptor(
581 CharacteristicUserDescriptionDescriptor(bus, 3, self))
582
583 def ReadValue(self, options):
584 print('TestSecureCharacteristic Read: ' + repr(self.value))
585 return self.value
586
587 def WriteValue(self, value, options):
588 print('TestSecureCharacteristic Write: ' + repr(value))
589 self.value = value
590
591
592 class TestSecureDescriptor(Descriptor):
593 """
594 Dummy test descriptor requiring secure connection. Returns a static value.
595
596 """
597 TEST_DESC_UUID = '12345678-1234-5678-1234-56789abcdef6'
598
599 def __init__(self, bus, index, characteristic):
600 Descriptor.__init__(
601 self, bus, index,
602 self.TEST_DESC_UUID,
603 ['secure-read', 'secure-write'],
604 characteristic)
605
606 def ReadValue(self, options):
607 return [
608 dbus.Byte('T'), dbus.Byte('e'), dbus.Byte('s'), dbus.Byte('t')
609 ]
610
611 def register_app_cb():
612 print('GATT application registered')
613
614
615 def register_app_error_cb(error):
616 print('Failed to register application: ' + str(error))
617 mainloop.quit()
618
619
620 def find_adapter(bus):
621 remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'),
622 DBUS_OM_IFACE)
623 objects = remote_om.GetManagedObjects()
624
625 for o, props in objects.items():
626 if GATT_MANAGER_IFACE in props.keys():
627 return o
628
629 return None
630
631 def main():
632 global mainloop
633
634 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
635
636 bus = dbus.SystemBus()
637
638 adapter = find_adapter(bus)
639 if not adapter:
640 print('GattManager1 interface not found')
641 return
642
643 service_manager = dbus.Interface(
644 bus.get_object(BLUEZ_SERVICE_NAME, adapter),
645 GATT_MANAGER_IFACE)
646
647 app = Application(bus)
648
649 mainloop = GLib.MainLoop()
650
651 print('Registering GATT application...')
652
653 service_manager.RegisterApplication(app.get_path(), {},
654 reply_handler=register_app_cb,
655 error_handler=register_app_error_cb)
656
657 mainloop.run()
658
659 if __name__ == '__main__':
660 main()