-
Notifications
You must be signed in to change notification settings - Fork 2
/
gattServer.py
852 lines (665 loc) · 28.5 KB
/
gattServer.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
#!/usr/bin/env python3
####################################################################################################################
#
# *****smartRemotes created by HeadHodge*****
#
# HeadHodge/smartRemotes is licensed under the MIT License
#
# A short and simple permissive license with conditions only requiring preservation of copyright and license notices.
# Licensed works, modifications, and larger works may be distributed under different terms and without source code.
#
####################################################################################################################
import dbus, dbus.exceptions
import dbus.mainloop.glib
import dbus.service
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
import sys
mainloop = None
hidService = None
BLUEZ_SERVICE_NAME = 'org.bluez'
GATT_MANAGER_IFACE = 'org.bluez.GattManager1'
DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager'
DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties'
GATT_SERVICE_IFACE = 'org.bluez.GattService1'
GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1'
GATT_DESC_IFACE = 'org.bluez.GattDescriptor1'
class InvalidArgsException(dbus.exceptions.DBusException):
_dbus_error_name = 'org.freedesktop.DBus.Error.InvalidArgs'
class NotSupportedException(dbus.exceptions.DBusException):
_dbus_error_name = 'org.bluez.Error.NotSupported'
class NotPermittedException(dbus.exceptions.DBusException):
_dbus_error_name = 'org.bluez.Error.NotPermitted'
class InvalidValueLengthException(dbus.exceptions.DBusException):
_dbus_error_name = 'org.bluez.Error.InvalidValueLength'
class FailedException(dbus.exceptions.DBusException):
_dbus_error_name = 'org.bluez.Error.Failed'
class Application(dbus.service.Object):
"""
org.bluez.GattApplication1 interface implementation
"""
def __init__(self, bus):
self.path = '/'
self.services = []
dbus.service.Object.__init__(self, bus, self.path)
self.add_service(HIDService(bus, 0))
self.add_service(DeviceInfoService(bus, 1))
self.add_service(BatteryService(bus, 2))
def get_path(self):
return dbus.ObjectPath(self.path)
def add_service(self, service):
self.services.append(service)
@dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')
def GetManagedObjects(self):
response = {}
print('GetManagedObjects')
for service in self.services:
response[service.get_path()] = service.get_properties()
chrcs = service.get_characteristics()
for chrc in chrcs:
response[chrc.get_path()] = chrc.get_properties()
descs = chrc.get_descriptors()
for desc in descs:
response[desc.get_path()] = desc.get_properties()
return response
class Service(dbus.service.Object):
"""
org.bluez.GattService1 interface implementation
"""
PATH_BASE = '/org/bluez/example/service'
def __init__(self, bus, index, uuid, primary):
self.path = self.PATH_BASE + str(index)
self.bus = bus
self.uuid = uuid
self.primary = primary
self.characteristics = []
dbus.service.Object.__init__(self, bus, self.path)
def get_properties(self):
return {
GATT_SERVICE_IFACE: {
'UUID': self.uuid,
'Primary': self.primary,
'Characteristics': dbus.Array(
self.get_characteristic_paths(),
signature='o')
}
}
def get_path(self):
return dbus.ObjectPath(self.path)
def add_characteristic(self, characteristic):
self.characteristics.append(characteristic)
def get_characteristic_paths(self):
result = []
for chrc in self.characteristics:
result.append(chrc.get_path())
return result
def get_characteristics(self):
return self.characteristics
@dbus.service.method(DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface):
if interface != GATT_SERVICE_IFACE:
raise InvalidArgsException()
return self.get_properties()[GATT_SERVICE_IFACE]
class Characteristic(dbus.service.Object):
"""
org.bluez.GattCharacteristic1 interface implementation
"""
def __init__(self, bus, index, uuid, flags, service):
self.path = service.path + '/char' + str(index)
self.bus = bus
self.uuid = uuid
self.service = service
self.flags = flags
self.descriptors = []
dbus.service.Object.__init__(self, bus, self.path)
def get_properties(self):
return {
GATT_CHRC_IFACE: {
'Service': self.service.get_path(),
'UUID': self.uuid,
'Flags': self.flags,
'Descriptors': dbus.Array(
self.get_descriptor_paths(),
signature='o')
}
}
def get_path(self):
return dbus.ObjectPath(self.path)
def add_descriptor(self, descriptor):
self.descriptors.append(descriptor)
def get_descriptor_paths(self):
result = []
for desc in self.descriptors:
result.append(desc.get_path())
return result
def get_descriptors(self):
return self.descriptors
@dbus.service.method(DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface):
if interface != GATT_CHRC_IFACE:
raise InvalidArgsException()
return self.get_properties()[GATT_CHRC_IFACE]
@dbus.service.method(GATT_CHRC_IFACE, in_signature='a{sv}', out_signature='ay')
def ReadValue(self, options):
print('Default ReadValue called, returning error')
raise NotSupportedException()
@dbus.service.method(GATT_CHRC_IFACE, in_signature='aya{sv}')
def WriteValue(self, value, options):
print('Default WriteValue called, returning error')
raise NotSupportedException()
@dbus.service.method(GATT_CHRC_IFACE)
def StartNotify(self):
print('Default StartNotify called, returning error')
raise NotSupportedException()
@dbus.service.method(GATT_CHRC_IFACE)
def StopNotify(self):
print('Default StopNotify called, returning error')
raise NotSupportedException()
@dbus.service.signal(DBUS_PROP_IFACE, signature='sa{sv}as')
def PropertiesChanged(self, interface, changed, invalidated):
pass
@dbus.service.signal(DBUS_PROP_IFACE, signature='ay')
def ReportValueChanged(self, reportValue):
pass
class Descriptor(dbus.service.Object):
"""
org.bluez.GattDescriptor1 interface implementation
"""
def __init__(self, bus, index, uuid, flags, characteristic):
self.path = characteristic.path + '/desc' + str(index)
self.bus = bus
self.uuid = uuid
self.flags = flags
self.chrc = characteristic
dbus.service.Object.__init__(self, bus, self.path)
def get_properties(self):
return {
GATT_DESC_IFACE: {
'Characteristic': self.chrc.get_path(),
'UUID': self.uuid,
'Flags': self.flags,
}
}
def get_path(self):
return dbus.ObjectPath(self.path)
@dbus.service.method(DBUS_PROP_IFACE,
in_signature='s',
out_signature='a{sv}')
def GetAll(self, interface):
if interface != GATT_DESC_IFACE:
raise InvalidArgsException()
return self.get_properties()[GATT_DESC_IFACE]
@dbus.service.method(GATT_DESC_IFACE,
in_signature='a{sv}',
out_signature='ay')
def ReadValue(self, options):
print ('Default ReadValue called, returning error')
raise NotSupportedException()
@dbus.service.method(GATT_DESC_IFACE, in_signature='aya{sv}')
def WriteValue(self, value, options):
print('Default WriteValue called, returning error')
raise NotSupportedException()
#sourceId="org.bluetooth.service.battery_service" type="primary" uuid="180F"
class BatteryService(Service):
"""
Fake Battery service that emulates a draining battery.
"""
SERVICE_UUID = '180f'
def __init__(self, bus, index):
Service.__init__(self, bus, index, self.SERVICE_UUID, True)
self.add_characteristic(BatteryLevelCharacteristic(bus, 0, self))
#name="Battery Level" sourceId="org.bluetooth.characteristic.battery_level" uuid="2A19"
class BatteryLevelCharacteristic(Characteristic):
"""
Fake Battery Level characteristic. The battery level is drained by 2 points
every 5 seconds.
"""
BATTERY_LVL_UUID = '2a19'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.BATTERY_LVL_UUID,
['read', 'notify'],
service)
self.notifying = False
self.notifyCnt = 0
self.battery_lvl = 100
#self.timer = GObject.timeout_add(60000, self.drain_battery)
def notify_battery_level(self):
self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': [dbus.Byte(self.battery_lvl)] }, [])
self.notifyCnt += 1
def drain_battery(self):
if not self.notifying: return True
if(self.notifyCnt > 2): return False #Update battery level 3 times then stop
if self.battery_lvl > 0:
self.battery_lvl -= 2
if self.battery_lvl < 5:
#self.battery_lvl = 0
GObject.source_remove(self.timer)
print('Battery Level drained: ' + repr(self.battery_lvl))
self.notify_battery_level()
return True
def ReadValue(self, options):
print('Battery Level read: ' + repr(self.battery_lvl))
return [dbus.Byte(self.battery_lvl)]
def StartNotify(self):
print('Start Battery Notify')
if self.notifying:
print('Already notifying, nothing to do')
return
self.notifying = True
self.timer = GObject.timeout_add(60000, self.drain_battery)
def StopNotify(self):
print('Stop Battery Notify')
if not self.notifying:
print('Not notifying, nothing to do')
return
self.notifying = False
#sourceId="org.bluetooth.service.device_information" type="primary" uuid="180A"
class DeviceInfoService(Service):
SERVICE_UUID = '180A'
def __init__(self, bus, index):
Service.__init__(self, bus, index, self.SERVICE_UUID, True)
self.add_characteristic(VendorCharacteristic(bus, 0, self))
self.add_characteristic(ProductCharacteristic(bus, 1, self))
self.add_characteristic(VersionCharacteristic(bus, 2, self))
#name="Manufacturer Name String" sourceId="org.bluetooth.characteristic.manufacturer_name_string" uuid="2A29"
class VendorCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A29'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
["read"],
service)
self.value = dbus.Array('HodgeCode'.encode(), signature=dbus.Signature('y'))
print(f'***VendorCharacteristic value***: {self.value}')
def ReadValue(self, options):
print(f'Read VendorCharacteristic: {self.value}')
return self.value
#sourceId="org.bluetooth.characteristic.model_number_string" uuid="2A24"
class ProductCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A24'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
["read"],
service)
self.value = dbus.Array('smartRemotes'.encode(), signature=dbus.Signature('y'))
print(f'***ProductCharacteristic value***: {self.value}')
def ReadValue(self, options):
print(f'Read ProductCharacteristic: {self.value}')
return self.value
#sourceId="org.bluetooth.characteristic.software_revision_string" uuid="2A28"
class VersionCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A28'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
["read"],
service)
self.value = dbus.Array('version 1.0.0'.encode(), signature=dbus.Signature('y'))
print(f'***VersionCharacteristic value***: {self.value}')
def ReadValue(self, options):
print(f'Read VersionCharacteristic: {self.value}')
return self.value
#name="Human Interface Device" sourceId="org.bluetooth.service.human_interface_device" type="primary" uuid="1812"
class HIDService(Service):
SERVICE_UUID = '1812'
def __init__(self, bus, index):
Service.__init__(self, bus, index, self.SERVICE_UUID, True)
self.protocolMode = ProtocolModeCharacteristic(bus, 0, self)
self.hidInfo = HIDInfoCharacteristic(bus, 1, self)
self.controlPoint = ControlPointCharacteristic(bus, 2, self)
self.reportMap = ReportMapCharacteristic(bus, 3, self)
self.report1 = Report1Characteristic(bus, 4, self)
self.report2 = Report2Characteristic(bus, 5, self)
self.add_characteristic(self.protocolMode)
self.add_characteristic(self.hidInfo)
self.add_characteristic(self.controlPoint)
self.add_characteristic(self.reportMap)
self.add_characteristic(self.report1)
self.add_characteristic(self.report2)
#name="Protocol Mode" sourceId="org.bluetooth.characteristic.protocol_mode" uuid="2A4E"
class ProtocolModeCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4E'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
["read", "write-without-response"],
service)
'''
<Field name="Protocol Mode Value">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Enumerations>
<Enumeration key="0" value="Boot Protocol Mode"/>
<Enumeration key="1" value="Report Protocol Mode"/>
<ReservedForFutureUse start="2" end="255"/>
</Enumerations>
'''
#self.value = dbus.Array([1], signature=dbus.Signature('y'))
self.parent = service
self.value = dbus.Array(bytearray.fromhex('01'), signature=dbus.Signature('y'))
print(f'***ProtocolMode value***: {self.value}')
def ReadValue(self, options):
print(f'Read ProtocolMode: {self.value}')
return self.value
def WriteValue(self, value, options):
print(f'Write ProtocolMode {value}')
self.value = value
#id="hid_information" name="HID Information" sourceId="org.bluetooth.characteristic.hid_information" uuid="2A4A"
class HIDInfoCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4A'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
['read'],
service)
'''
<Field name="bcdHID">
<InformativeText>16-bit unsigned integer representing version number of base USB HID Specification implemented by HID Device</InformativeText>
<Requirement>Mandatory</Requirement>
<Format>uint16</Format>
</Field>
<Field name="bCountryCode">
<InformativeText>Identifies which country the hardware is localized for. Most hardware is not localized and thus this value would be zero (0).</InformativeText>
<Requirement>Mandatory</Requirement>
<Format>8bit</Format>
</Field>
<Field name="Flags">
<Requirement>Mandatory</Requirement>
<Format>8bit</Format>
<BitField>
<Bit index="0" size="1" name="RemoteWake">
<Enumerations>
<Enumeration key="0" value="The device is not designed to be capable of providing wake-up signal to a HID host"/>
<Enumeration key="1" value="The device is designed to be capable of providing wake-up signal to a HID host"/>
</Enumerations>
</Bit>
<Bit index="1" size="1" name="NormallyConnectable">
<Enumerations>
<Enumeration key="0" value="The device is not normally connectable"/>
<Enumeration key="1" value="The device is normally connectable"/>
</Enumerations>
</Bit>
<ReservedForFutureUse index="2" size="6"/>
</BitField>
</Field>
'''
self.value = dbus.Array(bytearray.fromhex('01110002'), signature=dbus.Signature('y'))
print(f'***HIDInformation value***: {self.value}')
def ReadValue(self, options):
print(f'Read HIDInformation: {self.value}')
return self.value
#sourceId="org.bluetooth.characteristic.hid_control_point" uuid="2A4C"
class ControlPointCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4C'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
["write-without-response"],
service)
self.value = dbus.Array(bytearray.fromhex('00'), signature=dbus.Signature('y'))
print(f'***ControlPoint value***: {self.value}')
def WriteValue(self, value, options):
print(f'Write ControlPoint {value}')
self.value = value
#sourceId="org.bluetooth.characteristic.report_map" uuid="2A4B"
class ReportMapCharacteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4B'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
['read'],
service)
'''
<Field name="Report Map Value">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Repeated>true</Repeated>
</Field>
HID Report Descriptors https://www.usb.org/sites/default/files/documents/hid1_11.pdf
HID Report Parser https://eleccelerator.com/usbdescreqparser/
'''
##############################################################################################
# This Report Descriptor defines 2 Input Reports
# ReportMap designed by HeadHodge
#
# <Report Layouts>
# <Report>
# <ReportId>1</ReportId>
# <Description>HID Keyboard Input</Description>
# <Example>KeyCode capital 'M' = [dbus.Byte(0x02), dbus.Byte(0x10)]</Example>
# <Field>
# <Name>Keyboard Modifier</Name>
# <Size>uint8</Size>
# <Format>
# <Bit0>Left CTRL Key Pressed</Bit0>
# <Bit1>Left SHIFT Key Pressed</Bit1>
# <Bit2>Left ALT Key Pressed</Bit2>
# <Bit3>Left CMD(Window) Key Pressed</Bit3>
# <Bit4>Right CTRL Key Pressed</Bit4>
# <Bit5>Right SHIFT Key Pressed</Bit5>
# <Bit6>Right ALT Key Pressed</Bit6>
# <Bit7>Right CMD(Window) Key Pressed</Bit7>
# </Format>
# </Field>
# <Field>
# <Name>Keyboard Input KeyCode</Name>
# <Size>uint8</Size>
# </Field>
# </Report>
# <Report>
# <ReportId>2</ReportId>
# <Description>HID Consumer Input</Description>
# <Example>KeyCode 'VolumeUp' = [dbus.Byte(0xe9), dbus.Byte(0x00)]</Example>
# <Field>
# <Name>Consumer Input KeyCode</Name>
# <Size>uint16</Size>
# </Field>
# </Report>
# </Report Layouts>
##############################################################################################
#USB HID Report Descriptor
self.value = dbus.Array(bytearray.fromhex('05010906a1018501050719e029e71500250175019508810295017508150025650507190029658100c0050C0901A101850275109501150126ff0719012Aff078100C0'))
print(f'***ReportMap value***: {self.value}')
def ReadValue(self, options):
print(f'Read ReportMap: {self.value}')
return self.value
#id="report" name="Report" sourceId="org.bluetooth.characteristic.report" uuid="2A4D"
class Report1Characteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4D'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
['secure-read', 'notify'],
service)
'''
<Field name="Report Value">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Repeated>true</Repeated>
</Field>
Use standard key codes: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
'''
self.add_descriptor(Report1ReferenceDescriptor(bus, 1, self))
self.value = [dbus.Byte(0x00),dbus.Byte(0x00)]
print(f'***Report value***: {self.value}')
def send(self):
#send keyCode: 'M'
print(f'***send keyCode: "M"***');
self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': [dbus.Byte(0x02),dbus.Byte(0x10)] }, [])
self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': [dbus.Byte(0x00),dbus.Byte(0x00)] }, [])
print(f'***sent***')
return True
def ReadValue(self, options):
print(f'Read Report: {self.value}')
return self.value
def WriteValue(self, value, options):
print(f'Write Report {self.value}')
self.value = value
def StartNotify(self):
print(f'Start Start Report Keyboard Input')
GObject.timeout_add(10000, self.send)
def StopNotify(self):
print(f'Stop Report Keyboard Input')
#type="org.bluetooth.descriptor.report_reference" uuid="2908"
class Report1ReferenceDescriptor(Descriptor):
DESCRIPTOR_UUID = '2908'
def __init__(self, bus, index, characteristic):
Descriptor.__init__(
self, bus, index,
self.DESCRIPTOR_UUID,
['read'],
characteristic)
'''
<Field name="Report ID">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Minimum>0</Minimum>
<Maximum>255</Maximum>
</Field>
<Field name="Report Type">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Minimum>1</Minimum>
<Maximum>3</Maximum>
<Enumerations>
<Enumeration value="Input Report" key="1"/>
<Enumeration value="Output report" key="2"/>
<Enumeration value="Feature Report" key="3"/>
<ReservedForFutureUse start="4" end="255"/>
<ReservedForFutureUse1 start1="0" end1="0"/>
</Enumerations>
</Field>
'''
# This report uses ReportId 1 as defined in the ReportMap characteristic
self.value = dbus.Array(bytearray.fromhex('0101'), signature=dbus.Signature('y'))
print(f'***ReportReference***: {self.value}')
def ReadValue(self, options):
print(f'Read ReportReference: {self.value}')
return self.value
#id="report" name="Report" sourceId="org.bluetooth.characteristic.report" uuid="2A4D"
class Report2Characteristic(Characteristic):
CHARACTERISTIC_UUID = '2A4D'
def __init__(self, bus, index, service):
Characteristic.__init__(
self, bus, index,
self.CHARACTERISTIC_UUID,
['secure-read', 'notify'],
service)
'''
<Field name="Report Value">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Repeated>true</Repeated>
</Field>
Use standard key codes: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
'''
self.add_descriptor(Report2ReferenceDescriptor(bus, 1, self))
self.value = [dbus.Byte(0x00),dbus.Byte(0x00)]
print(f'***Report value***: {self.value}')
def send(self):
#send keyCode: 'VolumeUp'
print(f'***send keyCode: "VolumeUp"***');
self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': [dbus.Byte(0xe9), dbus.Byte(0x00)] }, [])
self.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': [dbus.Byte(0x00), dbus.Byte(0x00)] }, [])
print(f'***sent***')
return True
def ReadValue(self, options):
print(f'Read Report: {self.value}')
return self.value
def WriteValue(self, value, options):
print(f'Write Report {self.value}')
self.value = value
def StartNotify(self):
print(f'Start Report Consumer Input')
GObject.timeout_add(15000, self.send)
def StopNotify(self):
print(f'Stop Start Report Consumer Input')
#type="org.bluetooth.descriptor.report_reference" uuid="2908"
class Report2ReferenceDescriptor(Descriptor):
DESCRIPTOR_UUID = '2908'
def __init__(self, bus, index, characteristic):
Descriptor.__init__(
self, bus, index,
self.DESCRIPTOR_UUID,
['read'],
characteristic)
'''
<Field name="Report ID">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Minimum>0</Minimum>
<Maximum>255</Maximum>
</Field>
<Field name="Report Type">
<Requirement>Mandatory</Requirement>
<Format>uint8</Format>
<Minimum>1</Minimum>
<Maximum>3</Maximum>
<Enumerations>
<Enumeration value="Input Report" key="1"/>
<Enumeration value="Output report" key="2"/>
<Enumeration value="Feature Report" key="3"/>
<ReservedForFutureUse start="4" end="255"/>
<ReservedForFutureUse1 start1="0" end1="0"/>
</Enumerations>
</Field>
'''
# This report uses ReportId 2 as defined in the ReportMap characteristic
self.value = dbus.Array(bytearray.fromhex('0201'), signature=dbus.Signature('y'))
print(f'***ReportReference***: {self.value}')
def ReadValue(self, options):
print(f'Read ReportReference: {self.value}')
return self.value
######################################################
# MAIN
######################################################
def register_app_cb():
print('GATT application registered')
def register_app_error_cb(error):
print('Failed to register application: ' + str(error))
mainloop.quit()
def find_adapter(bus):
remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'),
DBUS_OM_IFACE)
objects = remote_om.GetManagedObjects()
for o, props in objects.items():
if GATT_MANAGER_IFACE in props.keys():
return o
return None
def main():
global mainloop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
adapter = find_adapter(bus)
if not adapter:
print('GattManager1 interface not found')
return
service_manager = dbus.Interface(
bus.get_object(BLUEZ_SERVICE_NAME, adapter),
GATT_MANAGER_IFACE)
app = Application(bus)
mainloop = GObject.MainLoop()
print('Registering GATT application...')
service_manager.RegisterApplication(app.get_path(), {},
reply_handler=register_app_cb,
error_handler=register_app_error_cb)
mainloop.run()
if __name__ == '__main__':
main()