This repository has been archived by the owner on Feb 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
xdc.py
1441 lines (1116 loc) · 53.4 KB
/
xdc.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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import asyncio
import struct
import typing
import bleak # for BLE communication
# SECTION: general utility funcitons/classes
#
# these are general functions/classes for doing stuff like printing
# classes, parsing binary, etc.
# returns a pretty-printed representation of an arbitrary class
def _pretty_print(obj) -> str:
return f"{obj.__class__.__name__}({', '.join('%s=%s' % item for item in vars(obj).items())})"
# a helper class that encapsulates a reader "cursor" that indexes a
# location in an array of bytes.
#
# Provides methods for reading multi-byte sequences (floats, ints, etc.) from the
# array, advancing the cursor as it reads. Multi-byte sequences are parsed according
# to XSens's binary spec (little-endian integers, IEE754 floats)
class _ResponseReader:
# initializes a reader that's pointing to the start of `data`
def __init__(self, data):
self.pos = 0
self.data = data
# returns number of remaining bytes that the reader can still read
def remaining(self) -> int:
return len(self.data) - self.pos
# read `n` raw bytes from the reader's current position and advance
# the current position by `n`
def read_bytes(self, n : int) -> bytes:
rv = self.data[self.pos:self.pos+n]
self.pos += n
return rv
# read 1 byte as an unsigned int
def read_u8(self) -> int:
return int.from_bytes(self.read_bytes(1), "little", signed=False)
# read 2 bytes as an unsigned little-endian int
def read_u16(self) -> int:
return int.from_bytes(self.read_bytes(2), "little", signed=False)
# read 4 bytes as an unsigned little-endian int
def read_u32(self) -> int:
return int.from_bytes(self.read_bytes(4), "little", signed=False)
# read 8 bytes as an unsigned little-endian int
def read_u64(self) -> int:
return int.from_bytes(self.read_bytes(8), "little", signed=False)
# read 4 bytes as a IEE754 floating point number
def read_f32(self) -> float:
return struct.unpack('f', self.read_bytes(4))
# SECTION: SERVICES (as defined in the BLE spec)
#
# the XSens DOT provides BLE services with the following prefixes on the
# UUID:
#
# 0x1000 (e.g. 15171000-4947-...): configuration service
# 0x2000 : measurement service
# 0x3000 : charging status/battery level service
# 0x7000 : message service
# Configuration Service: Device Info Characteristic (sec 2.1, p8 in the BLE spec)
#
# read-only characteristic for top-level device information
class DeviceInfoCharacteristic:
UUID = "15171001-4947-11E9-8646-D663BD873D93"
SIZE = 34
# returns a `DeviceInfoCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= DeviceInfoCharacteristic.SIZE
rv = DeviceInfoCharacteristic()
rv.address = reader.read_bytes(6)
rv.version_major = reader.read_u8()
rv.version_minor = reader.read_u8()
rv.version_revision = reader.read_u8()
rv.build_year = reader.read_u16() # 2019 ~ 2100
rv.build_month = reader.read_u8() # 1 ~ 12
rv.build_date = reader.read_u8() # 1 ~ 31
rv.build_hour = reader.read_u8() # 1 ~ 23
rv.build_minute = reader.read_u8() # 0 ~ 59
rv.build_second = reader.read_u8() # 0 ~ 59
rv.softdevice_version = reader.read_u32()
rv.serial_number = reader.read_u64()
rv.short_product_code = reader.read_bytes(6) # e.g. "XS-T01"
return rv
# returns a `DeviceInfoCharacteristic` parsed from bytes
def from_bytes(bites):
reader = _ResponseReader(bites)
return DeviceInfoCharacteristic._from_reader(reader)
def __repr__(self):
return _pretty_print(self)
# Configuration Service: Device Control Characteristic (sec 2.2, p9 in the BLE spec)
#
# read/write characteristic for top-level control (i.e. mode) of the DOT.
class DeviceControlCharacteristic:
UUID = "15171002-4947-11E9-8646-D663BD873D93"
SIZE = 16
# returns a `DeviceControlCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= DeviceControlCharacteristic.SIZE
rv = DeviceControlCharacteristic()
rv.visit_index = reader.read_u8()
rv.identifying = reader.read_u8()
rv.power_options = reader.read_u8()
rv.power_saving_timeout_x_mins = reader.read_u8() # 0 ~ 30
rv.power_saving_timeout_x_secs = reader.read_u8() # 0 ~ 60
rv.power_saving_timeout_y_mins = reader.read_u8() # 0 ~ 30
rv.power_saving_timeout_y_secs = reader.read_u8() # 0 ~ 60
rv.device_tag_len = reader.read_u8()
rv.device_tag = reader.read_bytes(16) # default "Xsens DOT"
rv.output_rate = reader.read_u16() # 1, 4, 10, 12, 15, 20, 30, 60, 120hz
rv.filter_profile_index = reader.read_u8()
rv.reserved = reader.read_bytes(5) # just in case someone's interested
return rv
# returns a `DeviceControlCharacteristic` parsed from bytes
def from_bytes(bites):
reader = _ResponseReader(bites)
return DeviceControlCharacteristic._from_reader(reader)
# returns bytes serialized from the `DeviceControlCharacteristic`'s data
def to_bytes(self):
rv = bytearray()
rv += self.visit_index.to_bytes(1, "little")
rv += self.identifying.to_bytes(1, "little")
rv += self.power_options.to_bytes(1, "little")
rv += self.power_saving_timeout_x_mins.to_bytes(1, "little")
rv += self.power_saving_timeout_x_secs.to_bytes(1, "little")
rv += self.power_saving_timeout_y_mins.to_bytes(1, "little")
rv += self.power_saving_timeout_y_secs.to_bytes(1, "little")
rv += self.device_tag_len.to_bytes(1, "little")
rv += self.device_tag
rv += self.output_rate.to_bytes(2, "little")
rv += self.filter_profile_index.to_bytes(1, "little")
rv += self.reserved
return rv
def __repr__(self):
return _pretty_print(self)
# Configuration Service: Device Report Characteristic (sec 2.3, p10 in the BLE spec)
#
# notification characteristic for various events the DOT may emit (e.g.
# power off, button pressed)
class DeviceReportCharacteristic:
UUID = "15171004-4947-11E9-8646-D663BD873D93"
SIZE = 36
# returns a `DeviceReportCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= DeviceReportCharacteristic.SIZE
rv = DeviceReportCharacteristic()
rv.typeid = reader.read_u8()
if rv.typeid == 1:
# power off report
pass
elif rv.typeid == 4:
# power saving report
pass
elif rv.typeid == 5:
# button callback report
rv.length = reader.read_u8()
if rv.length == 4:
rv.timestamp = reader.read_u32()
elif rv.length == 8:
rv.timestamp = reader.read_u64()
else:
# unknown report type
pass
# record unused bytes in-case future DOT devices make them
# contain useful information (so users can still use this lib
# to parse them afterwards)
rv.unused = reader.read_bytes(reader.end - reader.pos)
return rv
# returns a `DeviceReportCharacteristic` parsed from bytes
def from_bytes(bites):
reader = _ResponseReader(bites)
return DeviceReportCharacteristic._from_reader(reader)
def __repr__(self):
return _pretty_print(self)
# Measurement Service: Control Characteristic (sec 3.1, p12 in the BLE spec)
#
# read/write characteristic that controls the DOT's measurement state (i.e. if/what
# measurements are enabled)
class ControlCharacteristic:
UUID = "15172001-4947-11E9-8646-D663BD873D93"
SIZE = 3
# returns a `ControlCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ControlCharacteristic.SIZE
rv = ControlCharacteristic()
rv.Type = reader.read_u8()
rv.action = reader.read_u8()
rv.payload_mode = reader.read_u8()
return rv
# parse bytes as characteristic data
def from_bytes(bites):
reader = _ResponseReader(bites)
return ControlCharacteristic.read(reader)
# convert characteristic data back to bytes
def to_bytes(self):
assert self.Type < 0xff
assert self.action <= 1
assert self.payload_mode <= 24
rv = bytearray()
rv += self.Type.to_bytes(1, "little")
rv += self.action.to_bytes(1, "little")
rv += self.payload_mode.to_bytes(1, "little")
return rv
def __repr__(self):
return _pretty_print(self)
# the next bunch of classes are parsers etc. for the wide variety of measurement structs
# that the measurement service can emit
# measurement data (sec. 3.5 in BLE spec): timestamp: "Timestamp of the sensor in microseconds"
class Timestamp:
SIZE = 4
# returns a `Timestamp` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Timestamp.SIZE
rv = Timestamp()
rv.microseconds = reader.read_u32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in BLE spec): quaternion: "The orientation expressed as a quaternion"
class Quaternion:
SIZE = 16
# returns a `Quaternion` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Quaternion.size
rv = Quaternion()
rv.w = reader.read_f32()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in BLE spec): euler angles: "The orientation expressed as Euler angles, degree"
class EulerAngles:
SIZE = 12
# returns a `EulerAngles` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= EulerAngles.SIZE
rv = EulerAngles()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): free acceleration: "Acceleration in local earth coordinate and the local gravity is deducted, m/s^2"
class FreeAcceleration:
SIZE = 12
# returns a `FreeAcceleration` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= FreeAcceleration.SIZE
rv = FreeAcceleration()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in BLE spec): dq: "Orientation change during a time interval"
class Dq:
SIZE = 16
# returns a `Dq` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Dq.SIZE
rv = Dq()
rv.w = reader.read_f32()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): dv: "Velocity change during a time interval, m/s"
class Dv:
SIZE = 12
# returns a `Dv` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Dv.SIZE
rv = Dv()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): Acceleration: "Calibrated acceleration in sensor coordinate, m/s^2"
class Acceleration:
SIZE = 12
# returns a `Acceleration` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Acceleration.SIZE
rv = Acceleration()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): Angular Velocity: "Rate of turn in sensor coordinate, dps"
class AngularVelocity:
SIZE = 12
# returns an `AngularVelocity` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= AngularVelocity.SIZE
rv = AngularVelocity()
rv.x = reader.read_f32()
rv.y = reader.read_f32()
rv.z = reader.read_f32()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): Magnetic Field: "Magnetic field in the sensor coordinate, a.u."
class MagneticField:
SIZE = 6
# returns a `MagneticField` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MagneticField.SIZE
rv = MagneticField()
rv.x = reader.read_bytes(2)
rv.y = reader.read_bytes(2)
rv.z = reader.read_bytes(2)
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5 in the BLE spec): Status: "See section 3.5.1 of the BLE spec"
class Status:
SIZE = 2
# returns a `Status` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= Status.SIZE
rv = Status()
rv.value = reader.read_u16()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5. in the BLE spec): ClipCountAcc: "Count of ClipAcc in status"
class ClipCountAcc:
SIZE = 1
# returns a `ClipCountAcc` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ClipCountAcc.SIZE
rv = ClipCountAcc()
rv.value = reader.read_u8()
return rv
def __repr__(self):
return _pretty_print(self)
# measurement data (sec. 3.5. in the BLE spec): ClipCountGyr: "Count of ClipGyr in status"
class ClipCountGyr:
SIZE = 1
# returns a `ClipCountGyr` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ClipCountGyr.SIZE
rv = ClipCountGyr()
rv.value = reader.read_u8()
return rv
def __repr__(self):
return _pretty_print(self)
# data for long-payload measurements
#
# the DOT can emit data in long (63-byte), medium (40-byte), and short (20-byte) lengths.
# What those bytes parse out to depends on the payload mode (see "Measurement Service Control
# Characteristic") is set to.
class LongPayloadCharacteristic:
UUID = "15172002-4947-11E9-8646-D663BD873D93"
# a long payload measurement response called "Custom Mode 4" in the BLE spec
class LongPayloadCustomMode4:
SIZE = 51
# no parser: it's not officially supported by XSens
# data for medium-payload measurements
#
# the DOT can emit data in long (63-byte), medium (40-byte), and short (20-byte) lengths.
# What those bytes parse out to depends on the payload mode (see "Measurement Service Control
# Characteristic") is set to.
class MediumPayloadCharacteristic:
UUID = "15172003-4947-11E9-8646-D663BD873D93"
# a medium-payload measurement response that contains "Extended Quaternion" data
class MediumPayloadExtendedQuaternion:
SIZE = 36
# returns a `MediumPayloadExtendedQuaternion` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadExtendedQuaternion.SIZE
rv = MediumPayloadExtendedQuaternion()
rv.timestamp = Timestamp._from_reader(reader)
rv.quaternion = Quaternion._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
rv.status = Status._from_reader(reader)
rv.clip_count_acc = ClipCountAcc._from_reader(reader)
rv.clip_count_gyr = ClipCountGyr._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Complete Quaternion" data
class MediumPayloadCompleteQuaternion:
SIZE = 32
# returns a `MediumPayloadCompleteQuaternion` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadCompleteQuaternion.SIZE
rv = MediumPayloadCompleteQuaternion()
rv.timestamp = Timestamp._from_reader(reader)
rv.quaternion = Quaternion._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Extended Euler" data
class MediumPayloadExtendedEuler:
SIZE = 32
# returns a `MediumPayloadExtendedEuler` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadExtendedEuler.SIZE
rv = MediumPayloadExtendedEuler()
rv.timestamp = Timestamp._from_reader(reader)
rv.euler = EulerAngles._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
rv.status = Status._from_reader(reader)
rv.clip_count_acc = ClipCountAcc._from_reader(reader)
rv.clip_count_gyr = ClipCountGyr._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Complete Euler" data
class MediumPayloadCompleteEuler:
SIZE = 28
# returns a `MediumPayloadCompleteEuler` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadCompleteEuler.SIZE
rv = MediumPayloadCompleteEuler()
rv.timestamp = Timestamp._from_reader(reader)
rv.euler = EulerAngles._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement reponse that contains "High Fidelity (with mag)" data
class MediumPayloadHighFidelityWithMag:
SIZE = 35
# no parser: XSens claims you need to use the SDK to get this
# a medium-payload measurement response that contains "High Fidelity" data
class MediumPayloadHighFidelity:
SIZE = 29
# no parser: XSens claims you need to use the SDK to get this
# a medium-payload measurement response that contains "Delta Quantities (with Mag)" data
class MediumPayloadDeltaQuantitiesWithMag:
SIZE = 38
# returns a `MediumPayloadDeltaQuantitiesWithMag` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadDeltaQuantitiesWithMag.SIZE
rv = MediumPayloadDeltaQuantitiesWithMag()
rv.timestamp = Timestamp._from_reader(reader)
rv.dq = Dq._from_reader(reader)
rv.dv = Dv._from_reader(reader)
rv.magnetic_field = MagneticField._from_reader(reader)
return rv
# a medium-payload measurement response that contains "Delta Quantites" data
class MediumPayloadDeltaQuantities:
SIZE = 32
# returns a `MediumPayloadDeltaQuantities` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadDeltaQuantities.SIZE
rv = MediumPayloadDeltaQuantities()
rv.timestamp = Timestamp._from_reader(reader)
rv.dq = Dq._from_reader(reader)
rv.dv = Dv._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Rate Quantities (with Mag)" data
class MediumPayloadRateQuantitiesWithMag:
SIZE = 34
# returns a `MediumPayloadRateQuantitiesWithMag` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadRateQuantitiesWithMag.SIZE
rv = MediumPayloadRateQuantitiesWithMag()
rv.timestamp = Timestamp._from_reader(reader)
rv.acceleration = Acceleration._from_reader(reader)
rv.angular_velocity = AngularVelocity._from_reader(reader)
rv.magnetic_field = MagneticField._from_reader(reader)
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Rate Quantities" data
class MediumPayloadRateQuantities:
SIZE = 28
# returns a `MediumPayloadRateQuantities` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadRateQuantities.SIZE
rv = MediumPayloadRateQuantities()
rv.timestamp = Timestamp._from_reader(reader)
rv.acceleration = Acceleration._from_reader(reader)
rv.angular_velocity = AngularVelocity._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Custom Mode 1" data
class MediumPayloadCustomMode1:
SIZE = 40
# returns a `MediumPayloadCustomMode1` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadCustomMode1.SIZE
rv = MediumPayloadCustomMode1()
rv.timestamp = Timestamp._from_reader(reader)
rv.euler = EulerAngles._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
rv.angular_velocity = AngularVelocity._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Custom Mode 2" data
class MediumPayloadCustomMode2:
SIZE = 34
# returns a `MediumPayloadCustomMode2` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadCustomMode2.SIZE
rv = MediumPayloadCustomMode2()
rv.timestamp = Timestamp._from_reader(reader)
rv.euler = EulerAngles._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
rv.magnetic_field = MagneticField._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a medium-payload measurement response that contains "Custom Mode 3" data
class MediumPayloadCustomMode3:
SIZE = 32
# returns a `MediumPayloadCustomMode3` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= MediumPayloadCustomMode3.SIZE
rv = MediumPayloadCustomMode3()
rv.timestamp = Timestamp._from_reader(reader)
rv.quaternion = Quaternion._from_reader(reader)
rv.angular_velocity = AngularVelocity._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# data for short-payload measurements
#
# the DOT can emit data in long (63-byte), medium (40-byte), and short (20-byte) lengths.
# What those bytes parse out to depends on the payload mode (see "Measurement Service Control
# Characteristic") is set to.
class ShortPayloadCharacteristic:
UUID = "15172004-4947-11E9-8646-D663BD873D93"
# a short-payload measurement response that contains "Orientation Euler" data
class ShortPayloadOrientationEuler:
SIZE = 16
# returns a `ShortPayloadOrientationEuler` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ShortPayloadOrientationEuler.SIZE
rv = ShortPayloadOrientationEuler()
rv.timestamp = Timestamp._from_reader(reader)
rv.euler = EulerAngles._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a short-payload measurement response that contains "Orientation Quaternion" data
class ShortPayloadOrientationQuaternion:
SIZE = 20
# returns a `ShortPayloadOrientationQuaternion` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ShortPayloadOrientationQuaternion.SIZE
rv = ShortPayloadOrientationQuaternion()
rv.timestamp = Timestamp._from_reader(reader)
rv.quaternion = Quaternion._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# a short-payload measurement response that contains "Free Acceleration" data
class ShortPayloadFreeAcceleration:
SIZE = 16
# returns a `ShortPayloadFreeAcceleration` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= ShortPayloadFreeAcceleration.SIZE
rv = ShortPayloadFreeAcceleration()
rv.timestamp = Timestamp._from_reader(reader)
rv.free_acceleration = FreeAcceleration._from_reader(reader)
return rv
def __repr__(self):
return _pretty_print(self)
# Measurement Service: Orientation Reset Control Characteristic (sec. 3.6, p17 in the BLE spec)
class OrientationResetControlCharacteristic:
UUID = "15172006-4947-11E9-8646-D663BD873D93"
SIZE = 2
# returns a `OrientationResetControlCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= OrientationResetControlCharacteristic.SIZE
rv = OrientationResetControlCharacteristic()
rv.Type = reader.read_u16()
return rv
# returns a `OrientationResetControlCharacteristic` parsed from a byte sequence
def from_bytes(bites):
reader = _ResponseReader(bites)
return OrientationResetControlCharacteristic.read(reader)
# returns a serialized representation of the `OrientationResetControlCharacteristic`
def to_bytes(self):
rv = bytearray()
rv += self.Type.to_bytes(2, "little")
return rv
def __repr__(self):
return _pretty_print(self)
# Measurement Service: Orientation Reset Status Characteristic (sec. 3.7, p17 in the BLE spec)
class OrientationResetStatusCharacteristic:
UUID = "15172007-4947-11E9-8646-D663BD873D93"
SIZE = 1
# returns a `OrientationResetStatusCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= OrientationResetStatusCharacteristic.SIZE
rv = OrientationResetStatusCharacteristic()
rv.reset_result = reader.read_u8()
return rv
# returns a `OrientationResetStatusCharacteristic` parsed from a byte sequence
def from_bytes(bites):
reader = _ResponseReader(bites)
return OrientationResetStatusCharacteristic._from_reader(reader)
def __repr__(self):
return _pretty_print(self)
# OrientationResetDataCharacteristic: not for public use
# Battery Service: Battery Characteristic (sec. 4.1, p19 in the BLE spec)
class BatteryCharacteristic:
UUID = "15173001-4947-11E9-8646-D663BD873D93"
SIZE = 2
# returns a `BatteryCharacteristic` read from a `_ResponseReader`
def _from_reader(reader : _ResponseReader):
assert reader.remaining() >= BatteryCharacteristic.SIZE
rv = BatteryCharacteristic()
rv.battery_level = reader.read_u8()
rv.charging_status = reader.read_u8()
return rv
# returns a `BatteryCharacteristic` parsed from a byte sequence
def from_bytes(bites):
reader = _ResponseReader(bites)
return BatteryCharacteristic._from_reader(reader)
def __repr__(self):
return _pretty_print(self)
# SECTION: `Dot` context manager
#
# this is a lifetime wrapper around a BLE connection to a single DOT
# The `Dot` class provides:
#
# - Methods for connecting to the underlying DOT device through the Bluetooth Low-Energy
# (BLE) connection (`Dot.connect`, `Dot.disconnect`, `with`, and `async with`)
#
# - Low-level methods for reading, writing, and receiving notifications from the low-level
# BLE characteristic the DOT exposes
#
# - High-level methods that use the low-level methods (e.g. turn the DOT on, identify it)
#
# This class acts as a lifetime wrapper around the underlying BLE connection, so
# you should use it in something like a `with` or `async with` block. Using the async
# API (methods prefixed with `a`) and `async with` block is better. The underlying BLE
# implementation is asynchronous. The synchronous API (other methods and plain `with`
# blocks) is more convenient, but has to hop into an asynchronous event loop until the
# entire method call is complete. The asynchronous equivalents have the opportunity to
# cooperatively yield so that other events can be processed while waiting for the response.
# It is practically a necessity to use the async API if handling a large amount of DOTs
# from one thread (otherwise, you will experience head-of-line blocking and have a harder
# time handling the side-effects of notications).
class Dot:
# init/enter/exit: connect/disconnect to the DOT
# init a new `Dot` instance
#
# initializes the underlying connection client, but does not connect to
# the DOT. Use `.connect`/`.disconnect`, or (better) a context manager
# (`with Dot(ble) as dot`), or (better again) an async context manager
# (`async with Dot(ble) as dot`) to setup/teardown the connection
def __init__(self, ble_device):
self.dev = ble_device
self.client = bleak.BleakClient(self.dev.address)
# automatically called when entering `async with` blocks
async def __aenter__(self):
await self.client.__aenter__()
return self
# automatically called when exiting `async with` blocks
async def __aexit__(self, exc_type, value, traceback):
await self.client.__aexit__(exc_type, value, traceback)
# automatically called when entering (synchronous) `with` blocks
def __enter__(self):
self.loop = asyncio.new_event_loop()
self.loop.run_until_complete(self.__aenter__())
return self
# automatically called when exiting (synchronous) `with` blocks
def __exit__(self, exc_type, value, traceback):
self.loop.run_until_complete(self.__aexit__(exc_type, value, traceback))
# (dis)connection methods
# asynchronously establishes a connection to the DOT
async def aconnect(self):
return await self.client.connect()
# synchronously establishes a connection to the DOT
def connect(self):
self.loop.run_until_complete(self.aconnect())
# asynchronously terminates the connection to the DOT
async def adisconnect(self):
return await self.client.disconnect()
# synchronously terminates the connection to the DOT
def disconnect(self):
return self.loop.run_until_complete(self.adisconnect())
# low-level characteristic accessors
# asynchronously reads the "Device Info Characteristic" (sec. 2.1 in the BLE spec)
async def adevice_info_read(self):
resp = await self.client.read_gatt_char(DeviceInfoCharacteristic.UUID)
return DeviceInfoCharacteristic.from_bytes(resp)
# synchronously reads the "Device Info Characteristic" (sec. 2.1 in the BLE spec)
def device_info_read(self):
return self.loop.run_until_complete(self.adevice_info_read())
# asynchronously reads the "Device Control Characteristic" (sec. 2.2. in the BLE spec)
async def adevice_control_read(self):
resp = await self.client.read_gatt_char(DeviceControlCharacteristic.UUID)
return DeviceControlCharacteristic.from_bytes(resp)
# synchronously reads the "Device Control Characteristic" (sec. 2.2. in the BLE spec)
def device_control_read(self):
return self.loop.run_until_complete(self.adevice_control_read())
# asynchronously writes the "Device Control Characteristic" (sec. 2.2. in the BLE spec)
#
# arg must be a `DeviceControlCharacteristic` with its fields set to appropriate
# values (read the BLE spec to see which values are supported)
async def adevice_control_write(self, device_control_characteristic : DeviceControlCharacteristic):
msg_bytes = device_control_characteristic.to_bytes()
await self.client.write_gatt_char(DeviceControlCharacteristic.UUID, msg_bytes, True)
# synchronously writes the "Device Control Characteristic" (sec. 2.2. in the BLE spec)
#
# arg must be a `DeviceControlCharacteristic` with its fields set to appropriate
# values (read the BLE spec to see which values are supported)
def device_control_write(self, device_control_characteristic : DeviceControlCharacteristic):
self.loop.run_until_complete(self.adevice_control_write(device_control_characteristic))
# asynchronously enable notifications from the "Device Report Characteristic" (sec.
# 2.3 in the BLE spec)
#
# once notifications are enabled, `callback` will be called with two arguments:
# a message ID and the raw message bytes (which can be parsed using
# `DeviceReportCharacteristic.parse`). Notifications arrive from the DOT whenever
# a significant event happens (e.g. a button press). See the BLE spec for which
# events trigger from which actions.
async def adevice_report_start_notify(self, callback):
await self.client.start_notify(DeviceReportCharacteristic.UUID, callback)
# synchronously enable notifications from the "Device Report Characteristic" (sec.
# 2.3 in the BLE spec)
#
# once notifications are enabled, `callback` will be called with two arguments:
# a message ID and the raw message bytes (which can be parsed using
# `DeviceReportCharacteristic.parse`). Notifications arrive from the DOT whenever
# a significant event happens (e.g. a button press). See the BLE spec for which
# events trigger from which actions.
def device_report_start_notify(self, callback):
self.loop.run_until_complete(self.adevice_report_start_notify(callback))
# asynchronously disable notifications from the "Device Report Characteristic" (sec.
# 2.3 in the BLE spec)
#
# this disables notifications that were enabled by the `device_report_start_notify`
# method. After this action completes, the `callback` in the enable call will no longer
# be called
async def adevice_report_stop_notify(self):
await self.client.stop_notify(DeviceReportCharacteristic.UUID)
# synchronously disable notifications from the "Device Report Characteristic" (sec.
# 2.3 in the BLE spec)
#
# this disables notifications that were enabled by the `device_report_start_notify`
# method. After this action completes, the `callback` in the enable call will no longer
# be called
def device_report_stop_notify(self):
self.loop.run_until_complete(self.adevice_report_stop_notify())
# asynchronously read the "Control Characteristic" (sec. 3.1 in the BLE spec)
async def acontrol_read(self):
resp = await self.client.read_gatt_char(ControlCharacteristic.UUID)
return ControlCharacteristic.from_bytes(resp)
# asynchronously read the "Control Characteristic" (sec. 3.1 in the BLE spec)
def control_read(self):
return self.loop.run_until_complete(self.acontrol_read())
# asynchronously write the "Control Characteristic" (sec. 3.1 in the BLE spec)
async def acontrol_write(self, control_characteristic : ControlCharacteristic):