-
Notifications
You must be signed in to change notification settings - Fork 2
/
protocol.py
executable file
·1188 lines (952 loc) · 35.1 KB
/
protocol.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
#!/usr/bin/env python3
# The MIT License (MIT)
#
# Copyright (c) 2016 Ivor Wanders
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import ctypes
import struct
import crcmod
#############################################################################
# Mixins & structures
#############################################################################
# Convenience mixin to allow construction of struct from a byte like object.
class Readable:
@classmethod
def read(cls, byte_object):
a = cls()
ctypes.memmove(ctypes.addressof(a), bytes(byte_object),
min(len(byte_object), ctypes.sizeof(cls)))
return a
# Mixin to allow conversion of a ctypes structure to and from a dictionary.
class Dictionary:
# Implement the iterator method such that dict(...) results in the correct
# dictionary.
def __iter__(self):
for k, t in self._fields_:
if (issubclass(t, ctypes.Structure)):
if (hasattr(self, "_anonymous_") and (k in self._anonymous_)):
# have to iterate through it here.
for kk, tt, in dict(getattr(self, k)).items():
yield (kk, tt)
else:
yield (k, dict(getattr(self, k)))
else:
yield (k, getattr(self, k))
# Implement the reverse method, with some special handling for dict's and
# lists.
def from_dict(self, dict_object):
for k, t in self._fields_:
set_value = dict_object[k]
if (isinstance(set_value, dict)):
v = t()
v.from_dict(set_value)
setattr(self, k, v)
elif (isinstance(set_value, list)):
v = getattr(self, k)
for j in range(0, len(set_value)):
v[j] = set_value[j]
setattr(self, k, v)
else:
setattr(self, k, set_value)
def __str__(self):
return str(dict(self))
#############################################################################
# Protocol specific parameters.
#############################################################################
crc_proto = crcmod.mkCrcFun(poly=0x11021, initCrc=0xFFFF, rev=False, xorOut=0)
USB_PACKET_SIZE = 64
MAX_PACKET_SIZE = 540 # maximum protocol packet size. (Split over USBPackets)
USB_PACKET_MESSAGE_PART_FIRST = 0x5D
USB_PACKET_MESSAGE_PART_NEXT = 0x5E
#############################################################################
# USB Packet handling.
#############################################################################
class USBPacketHeader(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
# https://github.com/openambitproject/openambit/blob/master/src/libambit/protocol.c#L41
_fields_ = [("magic", ctypes.c_uint8),
("usb_length", ctypes.c_uint8),
("message_part", ctypes.c_uint8),
("message_length", ctypes.c_uint8),
("sequence", ctypes.c_uint16),
("header_checksum", ctypes.c_uint16)]
def is_correct(self):
header_bytes = bytes(self)[2:-2]
calc_crc = crc_proto(header_bytes)
return (calc_crc == self.header_checksum) and \
(self.usb_length == self.message_length + 8) and \
(self.magic == 0x3f)
def make_correct(self):
header_bytes = bytes(self)[2:-2]
calc_crc = crc_proto(header_bytes)
self.header_checksum = calc_crc
self.magic = 0x3F
def is_first(self):
return self.message_part == USB_PACKET_MESSAGE_PART_FIRST
def get_part_counter(self):
return self.sequence
def __str__(self):
is_ok = self.is_correct()
if (not is_ok):
return "damaged header part({: >1d}) len: {: >3d}".format(
self.get_part_counter(), self.message_length)
if (self.is_first()):
return "start({: >1d}) len: {: >3d}".format(
self.get_part_counter(), self.message_length)
else:
return "part({: >1d}) len: {: >3d}".format(
self.get_part_counter(), self.message_length)
# Class which represents all messages. That is; it holds all the structs.
class USBPacket(ctypes.LittleEndianStructure, Readable, Dictionary):
_pack_ = 1
_fields_ = [("header", USBPacketHeader),
("payload", ctypes.c_uint8 * (
USB_PACKET_SIZE-ctypes.sizeof(USBPacketHeader)))]
max_data = (USB_PACKET_SIZE - ctypes.sizeof(USBPacketHeader)-2)
# Pretty print the message according to its type.
def __str__(self):
message_field = str(self.header)
return "<USBPacket {}: data({})>".format(
message_field, len(self.data) if self.data else "-")
@property
def data(self):
data_len = self.header.message_length
data = self.payload[0:data_len]
crc_val, = struct.unpack("<H",
bytes(self.payload[data_len:data_len+2]))
crc_calcd = crc_proto(bytes(data), crc=self.header.header_checksum)
if (crc_val == crc_calcd):
return data
else:
return None
@data.setter
def data(self, value):
data_len = len(value)
self.header.message_length = min(USBPacket.max_data, len(value))
self.header.usb_length = self.header.message_length+8
self.header.make_correct()
self.payload[0:data_len] = bytes(value)
crc_calcd = crc_proto(bytes(self.payload[0:data_len]),
crc=self.header.header_checksum)
struct.pack_into("<H", self.payload, data_len, crc_calcd)
# returns one or multiple usb packets.
def usbpacketizer(msgdata):
# http://stackoverflow.com/a/312464
d = bytes(msgdata)
n = USBPacket.max_data
chunked = [d[i:i + n] for i in range(0, len(d), n)]
packets = []
# creating the first packet.
p = USBPacket()
p.header.message_part = USB_PACKET_MESSAGE_PART_FIRST
p.header.sequence = len(chunked)
p.data = chunked[0]
packets.append(p)
for i in range(1, len(chunked)):
p = USBPacket()
p.header.message_part = USB_PACKET_MESSAGE_PART_NEXT
p.header.sequence = i
p.data = chunked[i]
packets.append(p)
return packets
class USBPacketFeed:
def __init__(self):
self.packets = []
self.first = None
def packet(self, packet):
# print("USB packetfeed: {}".format(packet))
if (packet.header.is_first()):
# this is the first fragment of a packet.
if ((len(self.packets) != 0)):
# problem right there, we already have fragments.
print("Detected new packet while old packet isn't finished.")
self.first = None
self.packets = []
# self.packets.append((packet.header.get_part_counter(), packet))
self.first = packet
else:
self.packets.append((packet.header.get_part_counter(), packet))
# keep them ordered by their part counter.
self.packets.sort(key=lambda x: x[0])
# we have the right number of fragments, combine the data and return.
if (self.first is not None) and \
(len(self.packets) == self.first.header.get_part_counter()-1):
# packet is finished!
packet_data = []
packet_data += self.first.data
for i, j in self.packets:
if (j.data):
packet_data += j.data
else:
print("Checksum failed, discarding data")
self.packets = []
return None
self.packets = []
return packet_data
#############################################################################
# Higher level protocol messages. Often composed of several USBPackets
#############################################################################
class Command(ctypes.LittleEndianStructure, Dictionary, Readable):
_pack_ = 1
_fields_ = [
("command", ctypes.c_uint16),
("direction", ctypes.c_uint16),
("format", ctypes.c_uint16),
("packet_sequence", ctypes.c_uint16),
("packet_length", ctypes.c_uint32)
]
def __str__(self):
return "cmd 0x{:0>4X}, dir:0x{:0>4X} fmt 0x{:0>2X}"\
", packseq 0x{:0>2X}, len {:0>2d}".format(
self.command, self.direction, self.format,
self.packet_sequence, self.packet_length)
class BodyDeviceInfo(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("model", ctypes.c_char * 16),
("serial", ctypes.c_char * 16),
("fw_version", ctypes.c_uint8 * 4),
("hw_version", ctypes.c_uint8 * 4),
("bsl_version", ctypes.c_uint8 * 4)
]
def __str__(self):
version_string = ""
for k, t in self._fields_:
if (k.endswith("_version")):
v = getattr(self, k)
version_string += "{}: {}.{}.{}.{} ".format(
k.replace("_version", ""), *v)
return "Model: {}, Serial: {}, {}".format(
self.model.decode('ascii'), self.serial.decode('ascii'),
version_string)
class BodyDeviceInfoRequest(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("version", ctypes.c_uint8 * 4)
]
def __str__(self):
return "version: " + ".".join(
["{:>02d}".format(a) for a in self.version])
class BodyDateTime(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("year", ctypes.c_uint16),
("month", ctypes.c_uint8),
("day", ctypes.c_uint8),
("hour", ctypes.c_uint8),
("minute", ctypes.c_uint8),
("ms", ctypes.c_uint16)
]
class BodyDeviceStatus(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("pad_", ctypes.c_uint8),
("charge", ctypes.c_uint8)
]
def __str__(self):
return "Charge: {}%".format(self.charge)
class BodyLogCount(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("pad_", ctypes.c_uint16),
("log_count", ctypes.c_uint16)
]
def __str__(self):
return "Log count: {}".format(self.log_count)
class BodyLogHeaderStep(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("step", ctypes.c_uint32)
]
def __str__(self):
return "Step: {}".format(self.step)
class BodyLogHeaderEntry(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("type", ctypes.c_uint16),
("header_part", ctypes.c_uint16),
("length", ctypes.c_uint32),
("data", ctypes.c_uint8*MAX_PACKET_SIZE),
]
def __str__(self):
data_str = " ".join(["{:0>X}".format(self.data[i])
for i in range(self.length)])
return "type:{},{}, length: {}, data:{}".format(self.type,
self.header_part,
self.length,
data_str)
class BodyDataRequest(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("position", ctypes.c_uint32),
("length", ctypes.c_uint32)
]
def __str__(self):
return "0x{:>04X},0x{:>04X},".format(self.position, self.length)
class BodyDataReply(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("position", ctypes.c_uint32),
("length", ctypes.c_uint32),
("data", ctypes.c_uint8*512)
]
def __str__(self):
return "0x{:>04X},0x{:>04X},".format(self.position, self.length)
# + " ".join(["{:>02X}".format(a) for a in self.data])
class BodySetSettingsRequest(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = [
("frontpadding", ctypes.c_uint8*26),
("sounds_", ctypes.c_uint8), # Should equal 2 for off, 1 for on.
("rearpadding", ctypes.c_uint8*(70 - 26 - 1)),
]
def __str__(self):
return "Sounds: {}".format("on" if (self.sounds_ == 1) else "off")
# + " ".join(["{:>02X}".format(a) for a in self.data])
class BodySGEEDate(ctypes.LittleEndianStructure, Dictionary, Readable):
_pack_ = 1
_fields_ = [
("entry_", ctypes.c_uint8),
("year", ctypes.c_uint16),
("month", ctypes.c_uint8),
("day", ctypes.c_uint8),
("seconds", ctypes.c_uint32),
]
def __str__(self):
return "{}-{}-{}, {}".format(
self.year, self.month, self.day, self.seconds)
# + " ".join(["{:>02X}".format(a) for a in self.data])
class BodySetLogSettingsRequest(ctypes.LittleEndianStructure, Dictionary):
settings_true_size = (52 - 4 - 4 + 2 + 2 + 2 + 10 + 1 + 1 + 2)
_pack_ = 1
_fields_ = [
("write_position", ctypes.c_uint32),
("write_length", ctypes.c_uint32),
("start_of_settings", ctypes.c_uint8 * (52 - 4 - 4)),
("log_interval1_", ctypes.c_uint16),
("log_interval2_", ctypes.c_uint16),
("autolap_", ctypes.c_uint16),
("midpadding", ctypes.c_uint8 * 10),
("autostart_", ctypes.c_uint8), # 1 for on, 0 for off.
("more_zeros", ctypes.c_uint8),
("autosleep_", ctypes.c_uint16), # is in minutes
("rearpadding", ctypes.c_uint8 * (284 - 52 \
- 2 - 2 - 2 - 10 - 1 - 1 - 2)),
]
def __repr__(self):
# print(" ".join(["{:>02X}".format(a) for a in self.frontpadding]))
return "Log interval1: {:d}, Log interval1: {:d}, autolap: {:d},"\
" autostart:{:d}, autosleep:{:d}".format(self.log_interval1_,
self.log_interval2_,
self.autolap_,
self.autostart_,
self.autosleep_)
def __str__(self):
return "interval: {: >2d}s, autostart: {: >3}, autosleep: {:d} min, "\
"autolap: {: >3d} m".format(self.log_interval1_,
"on" if self.autostart_ else "off",
self.autosleep_,
self.autolap_)
@classmethod
def load_settings(cls, b):
a = cls()
ctypes.memmove(ctypes.addressof(a.start_of_settings), bytes(b),
min(len(b), ctypes.sizeof(a)))
return a
class BodyEmpty(ctypes.LittleEndianStructure, Dictionary):
_pack_ = 1
_fields_ = []
class MessageBody_(ctypes.Union):
_fields_ = [("raw", ctypes.c_uint8 * (
MAX_PACKET_SIZE - ctypes.sizeof(Command))),
("device_info", BodyDeviceInfo),
("device_info_request", BodyDeviceInfoRequest),
("device_status", BodyDeviceStatus),
("log_count", BodyLogCount),
("log_header_step", BodyLogHeaderStep),
("log_header_entry", BodyLogHeaderEntry),
("date_time", BodyDateTime),
("data_request", BodyDataRequest),
("data_reply", BodyDataReply),
("empty", BodyEmpty),
("personal_settings", BodySetSettingsRequest),
("set_settings_request", BodySetLogSettingsRequest),
("sgee_date", BodySGEEDate),
]
class Message(ctypes.LittleEndianStructure, Readable):
_pack_ = 1
_fields_ = [("command", Command),
("_body", MessageBody_)]
_anonymous_ = ["_body", ]
command_id = 0
direction_id = 0
packet_format = 0x09
body_field = "raw"
def __init__(self):
message_body = getattr(self, self.body_field)
self.command.format = self.packet_format
self.command.command = self.command_id
self.command.direction = self.direction_id
self.body_length = ctypes.sizeof(message_body)
self.command.packet_length = self.body_length
@classmethod
def read(cls, byte_object):
a = cls()
a.body_length = len(byte_object) - ctypes.sizeof(Command)
ctypes.memmove(ctypes.addressof(a), bytes(byte_object),
min(len(byte_object), ctypes.sizeof(cls)))
return a
@property
def body(self):
return getattr(self, self.body_field)
def __str__(self):
if (self.body_field == "raw"):
body_str = "".join(
[" {:>02X}".format(a) for a in self.raw[0:self.body_length]])
return "<{} {}, {}>".format(
self.__class__.__name__, self.command, body_str)
else:
message_body = str(getattr(self, self.body_field))
return "<{} {}, {}>".format(
self.__class__.__name__, self.command, message_body)
def __bytes__(self):
length = self.body_length + ctypes.sizeof(Command)
a = ctypes.create_string_buffer(length)
ctypes.memmove(ctypes.addressof(a), ctypes.addressof(self), length)
return bytes(a)
def __format__(self, format_spec):
if (format_spec == "r") or (self.body_field == "raw"):
return str(self)
if (format_spec == "s"):
return str(getattr(self, self.body_field))
known_messages = []
def register_msg(a):
known_messages.append(a)
return a
@register_msg
class DeviceInfoReply(Message):
command_id = 0x0200
direction_id = 0x0002
body_field = "device_info"
@register_msg
class DeviceInfoRequest(Message):
command_id = 0x0000
direction_id = 0x0001
packet_format = 0x0000
body_field = "device_info_request"
def __init__(self):
super().__init__()
self.device_info_request.version[0] = 2
self.device_info_request.version[1] = 4
self.device_info_request.version[2] = 89
# ------
@register_msg
class DeviceStatusRequest(Message):
command_id = 0x0603
direction_id = 0x0005
body_field = "empty"
@register_msg
class DeviceStatusReply(Message):
command_id = 0x0603
direction_id = 0x000a
body_field = "device_status"
# ------
@register_msg
class LogCountRequest(Message):
command_id = 0x060b
direction_id = 0x0005
body_field = "empty"
@register_msg
class LogCountReply(Message):
command_id = 0x060b
direction_id = 0x000a
body_field = "log_count"
# ------
@register_msg
class LogHeaderRewindRequest(Message):
command_id = 0x070b
direction_id = 0x0005
body_field = "empty"
@register_msg
class LogHeaderRewindReply(Message):
command_id = 0x070b
direction_id = 0x000a
body_field = "log_header_step"
# ------
@register_msg
class LogHeaderStepRequest(Message):
command_id = 0x0a0b
direction_id = 0x0005
body_field = "empty"
@register_msg
class LogHeaderStepReply(Message):
command_id = 0x0a0b
direction_id = 0x000a
body_field = "log_header_step"
# ------
@register_msg
class LogHeaderEntryRequest(Message):
command_id = 0x0b0b
direction_id = 0x0005
body_field = "empty"
@register_msg
class LogHeaderEntryReply(Message):
command_id = 0x0b0b
direction_id = 0x000a
body_field = "log_header_entry"
# ------
@register_msg
class LogHeaderPeekRequest(Message):
command_id = 0x080b
direction_id = 0x0005
body_field = "empty"
@register_msg
class LogHeaderPeekReply(Message):
command_id = 0x080b
direction_id = 0x000a
body_field = "log_header_step"
# ------
"""
The log header commands work as follows:
First, logcount is used to retrieve the number of logs.
In case of 4 logs, client does:
1. logcount is used to retrieve the number of logs.
2. a rewind request is triggered to reset the pointer?
3. A step is made (reply is always 0x200?)
4. Log header part1 is retrieved
5. Log header part2 is retrieved
6. Logpeek is used (0x400, more values?)
7. Step
8. Log header part1 is retrieved
9. Logpeek is used (0x400, more values?)
10. Step
11. Log header part1 is retrieved
12. Logpeek is used (0x400, more values?)
13. Step
14. Log header part1 is retrieved
15. Logpeek no more entries: 0xc00
-> Data acquisition starts with command 0x0070
After decoding the PMEM format it is known that the log header is just a
log entry... So log entries ar retrieved with the logheader retrieval.
"""
@register_msg
class DataRequest(Message):
command_id = 0x0007
direction_id = 0x0005
body_field = "data_request"
block_size = 512
def __init__(self):
super().__init__()
self.data_request.length = self.block_size
def pos(self, v):
self.data_request.position = v
@register_msg
class DataReply(Message):
command_id = 0x0007
direction_id = 0x000a
body_field = "data_reply"
def position(self):
return self.data_reply.position
def length(self):
return self.data_reply.length
def content(self):
return bytes(self.data_reply.data)
"""
The maximum position retrieved is 0x3BFE00, with size 0x0200 consistently.
This means that 0x3c0000 (3.932.160) bytes are retrieved in total, this is a
fat16 file system, which can even be mounted with:
mount -t vfat /tmp/reconstructed_data.bin /tmp/mounted/ -o loop
In this volume exists a BBPMEM.DAT file, which is exactly 3750000 bytes.
In this file, the logs seem to start at: 0x000f4240
"""
# ------
@register_msg
class SetDateRequest(Message):
command_id = 0x0203
direction_id = 0x0005
body_field = "date_time"
@register_msg
class SetDateReply(Message):
command_id = 0x0203
direction_id = 0x000a
body_field = "empty"
# ------
@register_msg
class SetTimeRequest(Message):
command_id = 0x0003
direction_id = 0x0005
body_field = "date_time"
@register_msg
class SetTimeReply(Message):
command_id = 0x0003
direction_id = 0x000a
body_field = "empty"
# ------
@register_msg
class LockStatusRequest(Message):
command_id = 0x190B
direction_id = 0x0005
body_field = "empty"
@register_msg
class LockStatusReply(Message):
command_id = 0x190B
direction_id = 0x0202
body_field = "empty"
# ------
@register_msg
class ReadSettingsRequest(Message):
command_id = 0x000B
direction_id = 0x0005
body_field = "empty"
@register_msg
class ReadSettingsReply(Message):
command_id = 0x000B
direction_id = 0x000A
body_field = "personal_settings"
# ------
@register_msg
class SetSettingsRequest(Message):
command_id = 0x010B
direction_id = 0x0005
body_field = "personal_settings"
def __new__(self):
b = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"\
" 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"\
" 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"\
" 00 00 00 00 00 00 00"
byte_object = bytes([int(a, 16) for a in b.split(" ")])
a = super().__new__(self)
ctypes.memmove(ctypes.addressof(a.set_settings_request),
bytes(byte_object), len(byte_object))
return a
# Should equal 2 for off, 1 for on.
@property
def sounds(self):
return self.personal_settings.sounds_ == 1
@sounds.setter
def sounds(self, enabled):
self.personal_settings.sounds_ = 1 if enabled else 2
@register_msg
class SetSettingsReply(Message):
command_id = 0x010B
direction_id = 0x000a
body_field = "empty"
# ------
@register_msg
class SetUnknownRequestAlpha(Message):
"""
Is always sent before writing the settings.
"""
command_id = 0x0F0B
direction_id = 0x0005
body_field = "empty"
@register_msg
class SetUnknownReplyAlpha(Message):
command_id = 0x0F0B
direction_id = 0x000a
body_field = "empty"
# ------
"""
# A forced settings synchronization contains the following:
devicestatus
lockstatus
readsound
setsound
alpha
setlogparam
bravo
readsgee
lockstatus
devicestatus
So, we assume we can discard the status message, as with the sounds
readsgee is only triggered because they try to update it. Lock is only
sent because this displays a notice on the watches?
So reduced:
alpha
setlogparam
bravo
The alpha and bravo are both unknown commands, but lets stick with sending
them, they might be required to write the settings to the disk or
something like that.
"""
@register_msg
class SetLogSettingsRequest(Message):
command_id = 0x100B
direction_id = 0x0005
body_field = "set_settings_request"
# Try to make this message correct by default, these are the default
# settings, the unknown bytes do NOT differ between two units.
# Also, the settings can also be found around 0xDA00 in the filesystem.
# By now it is discerned that this message corresponds to the 0x2000
# position in the filesystem. Combined with the fact that this one starts
# with 0x00000000, 0x00000114 (276 = message length from 03)
# From there on, so from 03 00 10 .. it aligns with the FS from 0x2000
def __new__(self):
b = "00 00 00 00 14 01 00 00 03 00 10 01 00 01 0C 01 0B 01 02 00"\
" 02 00 01 01 02 01 02 01 2A 00 47 50 53 20 54 72 61 63 6B 20"\
" 50 4F 44 00 00 00 01 00 00 00 02 00 01 00 01 00 00 00 00 00"\
" 00 00 00 00 00 00 00 00 01 00 00 00 05 01 D0 00 06 01 3C 00"\
" 07 01 02 00 11 01 08 01 08 00 09 01 04 00 00 00 08 00 08 01"\
" 08 00 09 01 04 00 01 00 08 00 08 01 1A 00 09 01 04 00 02 00"\
" 00 00 0A 01 02 00 10 00 0A 01 02 00 01 00 0A 01 02 00 FE FF"\
" 06 01 42 00 07 01 02 00 23 01 08 01 08 00 09 01 04 00 00 00"\
" 08 00 08 01 08 00 09 01 04 00 01 00 28 00 08 01 20 00 09 01"\
" 04 00 02 00 00 00 0A 01 02 00 10 00 0A 01 02 00 08 00 0A 01"\
" 02 00 01 00 0A 01 02 00 FE FF 06 01 3C 00 07 01 02 00 22 01"\
" 08 01 08 00 09 01 04 00 00 00 18 00 08 01 08 00 09 01 04 00"\
" 01 00 19 00 08 01 1A 00 09 01 04 00 02 00 00 00 0A 01 02 00"\
" 32 00 0A 01 02 00 1A 00 0A 01 02 00 10 00 06 01 06 00 07 01"\
" 02 00 50 01"
byte_object = bytes([int(a, 16) for a in b.split(" ")])
a = super().__new__(self)
ctypes.memmove(ctypes.addressof(a.set_settings_request),
bytes(byte_object), len(byte_object))
return a
@property
def autostart(self):
return self.set_settings_request.autostart_ == 1
@autostart.setter
def autostart(self, enabled):
self.set_settings_request.autostart_ = 1 if enabled else 0
@property
def autolap(self):
return self.set_settings_request.autolap_
@autolap.setter
def autolap(self, meters):
self.set_settings_request.autolap_ = meters
@property
def autosleep(self):
return self.set_settings_request.autosleep_
@autosleep.setter
def autosleep(self, minutes):
if (minutes in [0, 10, 30, 60]):
self.set_settings_request.autosleep_ = minutes
else:
print("Invalid value for autosleep minute field, ignoring!")
@property
def interval(self):
return self.set_settings_request.log_interval1_
@interval.setter
def interval(self, seconds):
if (seconds in [1, 60]):
self.set_settings_request.log_interval1_ = seconds
self.set_settings_request.log_interval2_ = seconds
else:
print("Invalid value for logging interval, ignoring!")
@register_msg
class SetLogSettingsReply(Message):
command_id = 0x100B
direction_id = 0x000a
body_field = "empty"
# ------
@register_msg
class SetUnknownRequestBravo(Message):
"""
Sent after settings were set.
-> Perhaps to reinitialize with the settings? Or commit them to disk?
"""
command_id = 0x110B
direction_id = 0x0005
body_field = "empty"
@register_msg
class SetUnknownReplyBravo(Message):
command_id = 0x110B
direction_id = 0x000a
body_field = "empty"
# ------
"""
Commands prior to firmware update...
0x0212
0x0411
0x0202
0x0301
0x000E
after firmware reset
0x0002
perhaps a reset?
"""
@register_msg
class SendFirmwareRequest(Message):
command_id = 0x010E
direction_id = 0x0005
# consecutive bytes?
body_field = "empty"
@register_msg
class SendFirmwareReply(Message):
command_id = 0x010E
direction_id = 0x000a
body_field = "empty"
# ------
@register_msg
class SendResetRequest(Message):
"""
This correlates with the packetcaptures -> yes, causes a USB stack reset.
Internal log has the Version:1.6.39 start with very few records.
"""