Repository navigation
Expand file tree
/
Copy pathsireader2.py
More file actions
1808 lines (1617 loc) · 80.9 KB
/
Copy pathsireader2.py
File metadata and controls
1808 lines (1617 loc) · 80.9 KB
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
#
# Copyright (C) 2008-2014 Gaudenz Steinlin <gaudenz@durcheinandertal.ch>
# 2014 Simon Harston <simon@harston.de>
# 2015 Jan Vorwerk <jan.vorwerk@angexis.com>
# 2019 Per Magnusson <per.magnusson@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
sireader2.py - Classes to read out si card data and backup
memory from BSM-7/8 stations.
Also contains functions to read and modify the configuration of stations.
The code contains documentation of much of the communication protocol
used by Sportident stations.
Additions and modifications by Per Magnusson:
- A few more parts of the SYS_VAL structure were worked out and described.
- The format of the data when reading out the backup memory was reverse
engineered and documented, both for stations in legacy and extended
protocol modes.
- Added function to read out backup memory of stations in legacy and
extended protocol modes.
- Added function to save the backup data to a CSV file of the same
format as that used by Sportident Config+.
- Added functions to set the station in direct and remote mode.
- A wakeup byte is sent as default before packets to stations.
This seems to make the communication more robust.
- Made the serial port search smarter for Windows.
- Fixed an issue with "raise StopIteration" in the _crc routine,
which no longer works in Python 3.7 (PEP 479).
- Compatibility with Python 2 is probably no longer preserved.
- Added sysval_ functions to access configuration data in SYS_VAL.
"""
from __future__ import print_function
from six import int2byte, byte2int, iterbytes, PY3
if PY3:
# Make byte2int on Python 3.x compatible with
# the fact that indexing into a byte variable
# already returns an integer. With this byte2int(b[0])
# works on 2.x and 3.x
def byte2int(x):
try:
return x[0]
except TypeError:
return x
from serial import Serial
from serial.serialutil import SerialException
import serial.tools.list_ports
from datetime import datetime, timedelta, time
from binascii import hexlify
import os, re, sys
import csv
class SIReader(object):
"""Base protocol functions and constants to interact with SI Stations.
This class has a lot of constants defined that are not (yet) used.
This is mainly for documentation purpose as most of this is not
documented by SportIdent."""
CRC_POLYNOM = 0x8005
CRC_BITF = 0x8000
# Protocol characters
STX = b'\x02' # Start of transmission
ETX = b'\x03' # End of transmission
ACK = b'\x06' # when sent to BSx3..6 with a card inserted, causes beep until SI-card taken out
NAK = b'\x15' # Negative ACK
DLE = b'\x10' # Delimiter (only used in legacy autosend data?)
WAKEUP = b'\xFF' # Send this byte first to wake a station up
# Basic (legacy) protocol commands, currently unused
BC_SET_CARDNO = b'\x30'
BC_GET_SI5 = b'\x31' # read out SI-card 5 data
BC_TRANS_REC = b'\x33' # autosend timestamp (online control) in very old stations (BSF3)
BC_SI5_WRITE = b'\x43' # write SI-card 5 data page: 02 43 (page: 0x30 to 0x37) (16 bytes) 03
BC_SI5_DET = b'\x46' # SI-card 5 inserted (46 49) or removed (46 4F)
BC_TRANS_REC2 = b'\x53' # autosend timestamp (online control)
BC_TRANS_TIME = b'\x54' # autosend timestamp (lightbeam trigger)
BC_GET_SI6 = b'\x61' # read out SI-card 6 data (and in compatibility mode:
# model SI-card 8/9/10/11/SIAC/pCard/tCard as SI-card 6)
BC_SI6_WRITEPAGE = b'\x62' # write SI-card 6 data page: 02 62 (block: 0x00 to 0x07)
# (page: 0x00 to 0x07) (16 bytes) 03
BC_SI6_READWORD = b'\x63' # read SI-card 6 data word: 02 63 (block: 0x00 to 0x07)
# (page: 0x00 to 0x07) (word: 0x00 to 0x03) 03
BC_SI6_WRITEWORD = b'\x64' # write SI-card 6 data word: 02 64 (block: 0x00 to 0x07)
# (page: 0x00 to 0x07) (word: 0x00 to 0x03) (4 bytes) 03
BC_SI6_DET = b'\x66' # SI-card 6 inserted
BC_SET_MS = b'\x70' # \x4D="M"aster, \x53="S"lave
BC_GET_MS = b'\x71'
BC_SET_SYS_VAL = b'\x72'
BC_GET_SYS_VAL = b'\x73'
BC_GET_BACKUP = b'\x74' # Note: response carries b'\xC4'!
BC_ERASE_BACKUP = b'\x75'
BC_SET_TIME = b'\x76'
BC_GET_TIME = b'\x77'
BC_OFF = b'\x78'
BC_RESET = b'\x79'
BC_GET_BACKUP2 = b'\x7A' # (for extended start and extended finish only) Note: response carries b'\xCA'!
BC_SET_BAUD = b'\x7E' # \x00=4800 baud, \x01=38400 baud
# Sportident documentation says that also command 0xC4 is among the legacy commands,
# but it does not say what that command does.
# Extended protocol commands
C_GET_BACKUP = b'\x81' # Takes four bytes as parameters:
# Three bytes as starting address and one byte as byte count.
# The count (probably) should not be larger than 0x80.
C_SET_SYS_VAL = b'\x82'
C_GET_SYS_VAL = b'\x83'
C_SRR_WRITE = b'\xA2' # ShortRangeRadio - SysData write
C_SRR_READ = b'\xA3' # ShortRangeRadio - SysData read
C_SRR_QUERY = b'\xA6' # ShortRangeRadio - network device query
C_SRR_PING = b'\xA7' # ShortRangeRadio - heartbeat from linked devices, every 50 seconds
C_SRR_ADHOC = b'\xA8' # ShortRangeRadio - ad-hoc message, e.g. from SI-ActiveCard
C_GET_SI5 = b'\xB1' # read out SI-card 5 data
C_SI5_WRITE = b'\xC3' # write SI-card 5 data page: 02 C3 11 (page: 0x00 to 0x07) (16 bytes) (CRC) 03
C_TRANS_REC = b'\xD3' # autosend timestamp (online control)
C_CLEAR_CARD = b'\xE0' # found on SI-dev-forum: 02 E0 00 E0 00 03 (http://www.sportident.com/index.php?option=com_kunena&view=topic&catid=8&id=56#59)
C_GET_SI6 = b'\xE1' # read out SI-card 6 data block
C_SI5_DET = b'\xE5' # SI-card 5 inserted
C_SI6_DET = b'\xE6' # SI-card 6 inserted
C_SI_REM = b'\xE7' # SI-card removed
C_SI9_DET = b'\xE8' # SI-card 8/9/10/11/p/t inserted
C_SI9_WRITE = b'\xEA' # write data page (double-word)
C_GET_SI9 = b'\xEF' # read out SI-card 8/9/10/11/p/t data block
C_SET_MS = b'\xF0' # \x4D="M"aster, \x53="S"lave
C_GET_MS = b'\xF1'
C_ERASE_BACKUP = b'\xF5'
C_SET_TIME = b'\xF6'
C_GET_TIME = b'\xF7'
C_OFF = b'\xF8'
C_BEEP = b'\xF9' # 02 F9 01 (number of beeps) (CRC16) 03
C_SET_BAUD = b'\xFE' # \x00=4800 baud, \x01=38400 baud
# This is what Sportident Config+ sends to turn off the remote station.
# It does not at all look like other commands.
C_REMOTE_OFF = b'\xFF\x40\x0F\x80\xB2\xB6\x50\xC0'
# Protocol Parameters
P_MS_DIRECT = b'\x4D' # "M"aster (direct)
P_MS_INDIRECT = b'\x53' # "S"lave (remote)
P_SI6_CB = b'\x08' # CardBlocks (see also O_SI6_CB)
# Offsets in system data (accessed by C_SET_SYS_VAL and C_GET_SYS_VAL)
# Thanks to Simon Harston <simon@harston.de> for most of this information
# currently only O_MODE, O_STATION_CODE and O_PROTO are used
O_OLD_SERIAL = b'\x00' # 2 bytes - only up to BSx6, numbers < 65.536
O_OLD_CPU_ID = b'\x02' # 2 bytes - only up to BSx6, numbers < 65.536
O_SERIAL_NO = b'\x00' # 4 bytes - only after BSx7, numbers > 70.000
# (if byte 0x00 > 0, better use OLD offsets)
O_SRR_CFG = b'\x04' # 1 byte - SRR-dongle configuration, bit mask value:
# xxxxxx1xb Auto send SIAC data
# xxxxx1xxb Sync time via radio
O_FIRMWARE = b'\x05' # 3 bytes, ASCII code (e.g. "656")
O_BUILD_DATE = b'\x08' # 3 bytes - YYMMDD
O_MODEL_ID = b'\x0B' # 2 bytes:
# 6F21: SIMSRR1-AP (ShortRangeRadio AccessPoint = SRR-dongle)
# 8003: BSF3 (serial numbers > 1.000)
# 8004: BSF4 (serial numbers > 10.000)
# 8084: BSM4-RS232
# 8086: BSM6-RS232 / BSM6-USB
# 8115: BSF5 (serial numbers > 50.000)
# 8117 / 8118: BSF7 / BSF8 (serial no. 70.000...70.521, 72.002...72.009)
# 8146: BSF6 (serial numbers > 30.000)
# 8187 / 8188: BS7-SI-Master / BS8-SI-Master
# 8197: BSF7 (serial numbers > 71.000, apart from 72.002...72.009)
# 8198: BSF8 (serial numbers > 80.000)
# 9197 / 9198: BSM7-RS232, BSM7-USB / BSM8-USB, BSM8-SRR
# 9199: unknown
# 9597: BS7-S (Sprinter)
# 9D9A: BS11-BL (SIAC / Air+)
# B197 / B198: BS7-P / BS8-P (Printer)
# B897: BS7-GSM
# CD9B: BS11-BS-red / BS11-BS-blue (SIAC / Air+)
O_MEM_SIZE = b'\x0D' # 1 byte - in KB
O_BAT_DATE = b'\x15' # 3 bytes - YYMMDD
O_BAT_CAP = b'\x19' # 2 bytes - battery capacity in mAh (as multiples of 16/225 = 0.0711 mAh?!)
O_BACKUP_PTR_HI = b'\x1C' # 2 bytes - high bytes of backup memory pointer
O_BACKUP_PTR_LO = b'\x21' # 2 bytes - low bytes of backup pointer
# The pointer information can be used with the C_GET_BACKUP command.
O_SI6_CB = b'\x33' # 1 byte - bitfield defining which SI Card 6 blocks to read:
# \x00=\xC1=read block0,6,7; \x08=\xFF=read all 8 blocks
# all 8 blocks are used when supporting 192 punches
O_SRR_CHANNEL = b'\x34' # 1 byte - SRR-dongle frequency band: 0x00="red", 0x01="blue"
O_USED_BAT_CAP = b'\x35' # 3 byte - Used battery capacity. Multiply by 2.778e-5 to get percent used
# (Comment used to say 'multiply by 1.38e-3', but this seems incorrect)
O_MEM_OVERFLOW = b'\x3D' # 1 byte - memory overflow if != 0x00
O_BAT_VOLT = b'\x50' # 2 byte - battery voltage, multiply by 5/65536 V
O_PROGRAM = b'\x70' # 1 byte - station program: xx0xxxxxb competition, xx1xxxxxb training
O_MODE = b'\x71' # 1 byte - see SI station modes below
O_STATION_CODE = b'\x72' # 1 byte - lower bits of station code
O_FEEDBACK = b'\x73' # 1 byte - feedback on punch, MSBits of code
# (and other unknown bits), bit mask value:
# xxxxxxx1b optical feedback
# xxxxx1xxb audible feedback
# 11xxxxxxb MSBits of station code
O_PROTO = b'\x74' # 1 byte - protocol configuration, bit mask value:
# xxxxxxx1b extended protocol
# xxxxxx1xb auto send out
# xxxxx1xxb handshake (only valid for card readout)
# xxx1xxxxb access with password only
# 1xxxxxxxb read out SI-card after punch (only for punch modes;
# depends on bit 2: auto send out or handshake)
O_WAKEUP_DATE = b'\x75' # 3 bytes - YYMMDD
O_WAKEUP_TIME = b'\x78' # 3 bytes - 1 byte day (see below), 2 bytes seconds after midnight/midday
O_SLEEP_TIME = b'\x7B' # 3 bytes - 1 byte day (see below), 2 bytes seconds after midnight/midday
# xxxxxxx0b - seconds relative to midnight/midday: 0 = am, 1 = pm
# xxxx000xb - day of week: 000 = Sunday, 110 = Saturday
# xx00xxxxb - week counter 0..3, relative to programming date
O_ACTIVE_TIME = b'\x7E' # 2 bytes - station active time in minutes, max 5759 minutes (< 96h)
# SI station modes
M_SIAC_SPECIAL = 0x01 # SI Air+ special register set (ON, OFF, Radio_ReadOut, etc.)
M_CONTROL = 0x02
M_START = 0x03
M_FINISH = 0x04
M_READOUT = 0x05
M_CLEAR_OLD = 0x06 # without start-number (not used anymore)
M_CLEAR = 0x07 # with start-number = standard
M_CHECK = 0x0A
M_PRINTOUT = 0x0B # BS7-P Printer-station (Note: also used by SRR-Receiver-module)
M_START_TRIG = 0x0C # BS7-S (Sprinter) with external trigger
M_FINISH_TRIG = 0x0D # BS7-S (Sprinter) with external trigger
M_BC_CONTROL = 0x12 # SI Air+ / SIAC Beacon mode
M_BC_START = 0x13 # SI Air+ / SIAC Beacon mode
M_BC_FINISH = 0x14 # SI Air+ / SIAC Beacon mode
M_BC_READOUT = 0x15 # SI Air+ / SIAC Beacon mode
SUPPORTED_MODES = (M_CONTROL, M_START, M_FINISH, M_READOUT, M_CLEAR, M_CHECK)
SUPPORTED_READ_BACKUP_MODES \
= (M_CONTROL, M_START, M_FINISH, M_CLEAR_OLD, M_CLEAR, M_CHECK)
MODE2NAME = {M_SIAC_SPECIAL : 'SIAC special',
M_CONTROL : 'Control',
M_START : 'Start',
M_FINISH : 'Finish',
M_READOUT : 'Readout',
M_CLEAR_OLD : 'Clear old',
M_CLEAR : 'Clear',
M_CHECK : 'Check',
M_PRINTOUT : 'Printout',
M_START_TRIG : 'Start trig',
M_FINISH_TRIG : 'Finish trig',
M_BC_CONTROL : 'BC control',
M_BC_START : 'BC start',
M_BC_FINISH : 'BC finish',
M_BC_READOUT : 'BC readout'}
MODEL2NAME = {0x6F21 : 'SIMSRR1-AP', # (ShortRangeRadio AccessPoint = SRR-dongle)
0x8003 : 'BSF3', # BSF3 (serial numbers > 1.000)
0x8004 : 'BSF4', # (serial numbers > 10.000)
0x8084 : 'BSM4-RS232',
0x8086 : 'BSM6-RS232/USB',
0x8115 : 'BSF5', # (serial numbers > 50.000)
0x8117 : 'BSF7', # (serial no. 70.000...70.521, 72.002...72.009)
0x8118 : 'BSF8', # (serial no. 70.000...70.521, 72.002...72.009)
0x8146 : 'BSF6', # (serial numbers > 30.000)
0x8187 : 'BS7-SI-Master',
0x8188 : 'BS8-SI-Master',
0x8197 : 'BSF7', # (serial numbers > 71.000, apart from 72.002...72.009)
0x8198 : 'BSF8', # (serial numbers > 80.000)
0x9197 : 'BSM7-RS232/USB',
0x9198 : 'BSM8-USB/SRR',
0x9199 : 'unknown',
0x9597 : 'BS7-S', # (Sprinter)
0x9D9A : 'BS11-BL', # (SIAC / Air+)
0xB197 : 'BS7-P', # (Printer)
0xB198 : 'BS8-P', # (Printer)
0xB897 : 'BS7-GSM',
0xCD9B : 'BS11-BS' #-red / -blue (SIAC / Air+)
}
# Weekday encoding (only for reference, currently unused)
D_SUNDAY = 0b000
D_MONDAY = 0b001
D_TUESDAY = 0b010
D_WEDNESDAY = 0b011
D_THURSDAY = 0b100
D_FRIDAY = 0b101
D_SATURDAY = 0b110
D_UNKNOWN = 0b111 # in D3-message from SIAC-beacon where no weekday-info is transmitted
# Backup memory record length
REC_LEN = 8 # Only in extended protocol, otherwise 6!
# General card data structure values
TIME_RESET = b'\xEE\xEE'
# SI Card data structures
CARD = {'SI5':{'CN2': 6, # card number byte 2
'CN1': 4, # card number byte 1
'CN0': 5, # card number byte 0
'STD': None,# start time day
'ST' : 19, # start time
'FTD': None,# finish time day
'FT' : 21, # finish time
'CTD': None,# check time day
'CT' : 25, # check time
'LTD': None,# clear time day
'LT' : None,# clear time
'RC' : 23, # punch counter
'P1' : 32, # first punch
'PL' : 3, # punch data length in bytes
'PM' : 30, # punch maximum (punches 31-36 have no time)
'CN' : 0, # control number offset in punch record
'PTD': None,# punchtime day byte offset in punch record
'PTH': 1, # punchtime high byte offset in punch record
'PTL': 2, # punchtime low byte offset in punch record
},
'SI6':{'CN2': 11,
'CN1': 12,
'CN0': 13,
'STD': 24,
'ST' : 26,
'FTD': 20,
'FT' : 22,
'CTD': 28,
'CT' : 30,
'LTD': 32,
'LT' : 34,
'RC' : 18,
'P1' : 128,
'PL' : 4,
'PM' : 64,
'PTD': 0, # Day of week byte, SI6 and newer
'CN' : 1,
'PTH': 2,
'PTL': 3,
},
'SI8':{'CN2': 25,
'CN1': 26,
'CN0': 27,
'STD': 12,
'ST' : 14,
'FTD': 16,
'FT' : 18,
'CTD': 8,
'CT' : 10,
'LTD': None,
'LT' : None,
'RC' : 22,
'P1' : 136,
'PL' : 4,
'PM' : 50,
'PTD': 0,
'CN' : 1,
'PTH': 2,
'PTL': 3,
'BC' : 2, # number of blocks on card (only relevant for SI8 and above = those read with C_GET_SI9)
},
'SI9':{'CN2': 25,
'CN1': 26,
'CN0': 27,
'STD': 12,
'ST' : 14,
'FTD': 16,
'FT' : 18,
'CTD': 8,
'CT' : 10,
'LTD': None,
'LT' : None,
'RC' : 22,
'P1' : 56,
'PL' : 4,
'PM' : 50,
'PTD': 0, # Day of week byte, SI6 and newer
'CN' : 1,
'PTH': 2,
'PTL': 3,
'BC' : 2,
},
'pCard':{'CN2': 25, # Similar to SI9/10 but not identical
'CN1': 26,
'CN0': 27,
'STD': 12,
'ST' : 14,
'FTD': 16,
'FT' : 18,
'CTD': 8,
'CT' : 10,
'LTD': None,
'LT' : None,
'RC' : 22,
'P1' : 176, # Location of Punch 1 I believe
'PL' : 4,
'PM' : 20,
'PTD': 0, # Day of week byte, SI6 and newer
'CN' : 1,
'PTH': 2,
'PTL': 3,
'BC' : 2,
},
'SI10':{'CN2': 25, # Same data structure for SI11
'CN1': 26,
'CN0': 27,
'STD': 12,
'ST' : 14,
'FTD': 16,
'FT' : 18,
'CTD': 8,
'CT' : 10,
'LTD': None,
'LT' : None,
'RC' : 22,
'P1' : 128, # would be 512 if all blocks were read, but blocks 1-3 are skipped on readout
'PL' : 4,
'PM' : 64,
'PTD': 0, # Day of week byte, SI6 and newer
'CN' : 1,
'PTH': 2,
'PTL': 3,
'BC' : 8,
},
}
# punch trigger in control mode data structure
T_OFFSET = 8
T_CN = 0
T_TIME = 5
# backup memory in control mode
BC_CN = 3
BC_TIME = 8
# offsets in backup memory readout of controls, extended protocol
BUX_FIRST = 2 # First punch begins at this offset in the data (add 1 like for the O_ constants)
BUX_SIZE = 8 # Each record is 8 bytes long
# offsets within each punch record
BUX_CN = 0 # 3 bytes, MSB to LSB
BUX_YM = 3 # 1 byte, bits 7..2: year (0 means 2000), bits 1..0: upper bits of month
BUX_MDAP = 4 # 1 byte, bits 7..6: lower bits of month, bits 5..1: day of month, bit 0: AM/PM
BUX_SECS = 5 # 2 bytes, seconds since midnight or midday
BUX_MS = 7 # 1 byte, divide by 256 to get fractions of seconds
# offsets in backup memory readout of controls, legacy protocol
BUL_FIRST = 2 # First punch begins at this offset in the data (add 1 like for the O_ constants)
BUL_SIZE = 6 # Each record is 6 bytes long
# offsets within each punch record
BUL_CN = 0 # 2 bytes, lower part of card number
BUL_SECS = 2 # 2 bytes, seconds since midnight/midday
BUL_PTD = 4 # 1 byte
# bit 0 - am/pm
# bit 3...1 - day of week, 000 = Sunday, 110 = Saturday
# bit 5...4 - week counter 0...3, relative, not used, seems to always be 0
# bit 7...6 - control station code number high
# (...511)
BUL_CNS = 5 # 1 byte, card number series(?)
# Multiply by 100 000 if <= 4 (SI5), otherwise multiply by 65536 (?)
def __init__(self, *args, **kwargs):
"""Initializes communication with si station at port.
@param port: Serial device for the connection if port is None it
scans all available ports and connects to the first
reader found
port = None, debug = False, logfile = None
"""
self._serial = None # Serial port object
self._debug = kwargs['debug'] if 'debug' in kwargs else False
self.proto_config = None
self._station_code = None
self._serno = 0 # Serial number of station
self.direct = True # Direct or remote mode
self._noconnect = kwargs['noconnect'] if 'noconnect' in kwargs else False
self._lowspeed = kwargs['lowspeed'] if 'lowspeed' in kwargs else False
if 'logfile' in kwargs:
self._logfile = open(kwargs['logfile'], 'ab')
else:
self._logfile = None
self.sysval = '' # The most recently read station configuration information
errors = ''
if 'port' in kwargs:
self._connect_reader(kwargs['port'])
return
else:
scan_ports = self.guessSerialPorts()
if len(scan_ports) == 0:
errors = 'no serial ports found'
for port in scan_ports:
try:
print('Trying ' + port)
self._connect_reader(port)
return
except (SIReaderException, SIReaderTimeout) as msg:
errors = '%sport: %s: %s\n' % (errors, port, msg)
pass
raise SIReaderException('No SI Reader found. Possible reasons: %s' % errors)
def __del__(self):
if self._logfile != None:
self._logfile.close()
@classmethod
def guessSerialPorts(self, ttyS=False):
"""Look for a COM port that might be connected to a Sportident station."""
def port_sort_fn(portinfo):
"""Function used when sorting ranked COM ports."""
return -portinfo[0]
found = []
if sys.platform.startswith('linux'):
found = [os.path.join('/dev', f) for f in os.listdir('/dev')
if re.match('ttyS.*|ttyUSB.*' if ttyS else 'ttyUSB.*', f)]
elif sys.platform.startswith('darwin'):
with os.scandir('/dev') as it:
for entry in it:
# assume that silabs.com CP210x USB to UART bridge is used
if entry.name.startswith('tty.SLAB'):
found.append(os.path.join('/dev', entry.name))
elif sys.platform.startswith('win'):
# Rank ports based on some kind of criteria of how
# likely they are to be the correct port.
portname = False
ports = list(serial.tools.list_ports.comports())
ranked_ports = []
for p in ports:
"""
print(p[0])
print(p[1])
print(p[2])
"""
portname = p[0]
portname1 = p[1]
portname2 = p[2]
points = 0
if portname == 'COM1':
# COM1 is often not accessible on modern computers
points -= 1
if 'sportident' in portname1.lower():
points += 10
if 'acpi' in portname2.lower():
points -= 5
ranked_ports.append([points, portname, portname1, portname2])
# Sort on ranking
ranked_ports.sort(key=port_sort_fn)
# Try out the ports in the order they are ranked
for portinfo in ranked_ports:
try:
s = Serial(portinfo[1])
found.append(s.portstr)
s.close()
except SerialException:
pass
else:
raise SIReaderException('Unsupported OS: %s' % sys.platform)
return found
@classmethod
def scanStations(self, lowspeed=False):
'''Scans all the possible serial ports and tries to find a SportIdent station
@return: array of (serial port name, station code)
'''
import threading
found = []
def _run(port):
si = self(port=port, debug=True, lowspeed=lowspeed)
stationCode = si.get_station_code()
found.append( (port, stationCode) )
si.disconnect()
threads = []
# Search in parallel
for port in self.guessSerialPorts():
t = threading.Thread(target=_run, args=(port,))
threads.append(t)
t.start()
for t in threads:
t.join()
return found
def flush(self):
self._serial.flushInput()
self._serial.flushOutput()
def set_extended_protocol(self, extended = True):
"""Configure extended protocol mode of si station.
@param extended: Set extended protocol if True, legacy protocol if
False.
"""
config = self.proto_config.copy()
config['ext_proto'] = extended
self._set_proto_config(config)
def set_autosend(self, autosend = True):
"""Set si station into autosend mode.
@param autosend: Set autosend mode if True, unset otherwise.
"""
config = self.proto_config.copy()
config['auto_send'] = autosend
config['handshake'] = not autosend
self._set_proto_config(config)
def set_operating_mode(self, mode):
"""Set si station operating mode.
@param mode: operating mode, supported modes: M_CONTROL, M_START, M_FINISH, M_READOUT, M_CLEAR, M_CHECK
"""
if not mode in SIReader.SUPPORTED_MODES:
raise SIReaderException("Unsupported mode '%i'!" % mode)
try:
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_MODE + int2byte(mode))
finally:
self._update_proto_config()
def set_station_code(self, code):
"""Set si station control code.
@param code: control code (1-1023)
"""
if code < 1 or code > 1023:
raise SIReaderException("Invalid control code: '%i'! Supported code range: 1-1023." % code)
# lower byte of control code
code_low = int2byte(code & 0xFF)
# high byte of control code, only the first 2 bits are used, the rest are set to 1
code_high = int2byte((code >> 2) | 0b00111111)
try:
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_STATION_CODE + code_low + code_high)
finally:
self._update_proto_config()
def set_baud_rate_4800(self):
"""Set the baudrate to 4800 of the direct or remote station depending on
which one is currently being communicated with.
"""
try:
self._send_command(SIReader.C_SET_BAUD, b'\x00')
self._serial.baudrate == 4800
finally:
pass
def set_baud_rate_38400(self):
"""Set the baudrate to 38400 of the direct or remote station depending on
which one is currently being communicated with.
"""
try:
self._send_command(SIReader.C_SET_BAUD, b'\x01')
self._serial.baudrate == 38400
finally:
pass
def refresh_sysval(self):
"""Read the entire station configuration information (SYS_VAL) and store in the object
so that the sysval_ functions can return good information.
@return : -
"""
self.sysval = self._send_command(SIReader.C_GET_SYS_VAL, b'\x00\x80')[1]
def save_sys_val(self, filename=None):
"""Save the station configuration data (SYS_VAL) to a CSV file.
Two values per row, offset and byte, in decimal format.
If no filename is given, a name is created consisting of the code of the station
and the current date and time.
@param filename: optional name of CSV file
@return: The name of the CSV file
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
code = self.sysval_code()
datestr = datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
if filename is None:
filename = str(code) + '_' + datestr + '_sysval.csv'
with open(filename, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=';',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
header = ['Offset', 'Value']
csvwriter.writerow(header)
offs = 0
for byte in self.sysval[1:]:
csvwriter.writerow([offs, byte])
offs += 1
return filename
return ""
def sysval_serno(self):
"""Return the station serial number from the most recent reading of SYS_VAL.
@return : station serial number as an integer
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_SERIAL_NO, 4))
def sysval_fwver(self):
"""Return the station firmware version from the most recent reading of SYS_VAL.
@return : firmware station serial number as a 3-character string
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._extract_sysval(self.sysval, SIReader.O_FIRMWARE, 3).decode('ascii')
def sysval_model_id(self):
"""Return the station model id from the most recent reading of SYS_VAL.
@return : model id, an integer
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_MODEL_ID, 2))
def sysval_model_str(self):
"""Return the station model (as a string) from the most recent reading of SYS_VAL.
@return : model, a string
"""
model_id = self.sysval_model_id()
if model_id in SIReader.MODEL2NAME:
model_str = SIReader.MODEL2NAME[model_id]
else:
mode_str = "0x%04x" % model_id
return model_str
def sysval_build_date(self):
"""Return the station build date from the most recent reading of SYS_VAL.
@return : build-date as a string YYYY-MM-DD
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
date_str = SIReader._extract_sysval(self.sysval, SIReader.O_BUILD_DATE, 3)
date_str = "20%02d-%02d-%02d" % (date_str[0], date_str[1], date_str[2])
return date_str
def sysval_battery_date(self):
"""Return the station battery date from the most recent reading of SYS_VAL.
@return : build-date as a string YYYY-MM-DD
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
date_str = SIReader._extract_sysval(self.sysval, SIReader.O_BAT_DATE, 3)
date_str = "20%02d-%02d-%02d" % (date_str[0], date_str[1], date_str[2])
return date_str
def sysval_mem_size(self):
"""Return the station's memory size from the most recent reading of SYS_VAL.
@return : station's memory size in kB
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_MEM_SIZE, 1))
def sysval_volt(self):
"""Return the station voltage from the most recent reading of SYS_VAL.
@return : voltage, a float, V
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return (SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_BAT_VOLT, 2))*5.0)/65536.0
def sysval_battery_capacity(self):
"""Return the station's battery capacity from the most recent reading of SYS_VAL.
@return : capacity, a float, mAh
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return (SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_BAT_CAP, 2))*16.0)/225.0
def sysval_used_battery(self):
"""Return the station's used battery capacity from the most recent reading of SYS_VAL.
@return : used capacity, a float, %
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_USED_BAT_CAP, 3))*2.778e-5
def sysval_mode_str(self):
"""Return the station operating mode from the most recent reading of SYS_VAL.
@return : mode, a string
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
mode = SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_MODE, 1))
if mode in SIReader.MODE2NAME:
mode_str = SIReader.MODE2NAME[mode]
else:
mode_str = "0x%02x" % mode
return mode_str
def sysval_code(self):
"""Return the station code from the most recent reading of SYS_VAL.
@return : code, 1-1023
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
code_low = SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_STATION_CODE, 1))
# Also contains high bits of code
feedback = SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_FEEDBACK, 1))
self._station_code = code_low + ((feedback & 0b11000000)<<2)
return self._station_code
def sysval_feedback(self):
"""Return the station feedback byte from the most recent reading of SYS_VAL.
@return : feedback, an integer, 0-255
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_FEEDBACK, 1))
def sysval_192_punches(self):
"""Return the station's setting regarding 192 punches for SI card 6
from the most recent reading of SYS_VAL.
@return : True if it is set, False if not, a byte is the value is unexpected
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
si6_192 = SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_SI6_CB, 1))
if si6_192 == 0 or si6_192 == 0xC1:
return False
if si6_192 == 0x08 or si6_192 == 0xFF:
return True
return si6_192
def sysval_protocol(self):
"""Return the station protocol byte from the most recent reading of SYS_VAL.
@return : protocol, an integer, 0-255
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_PROTO, 1))
def sysval_active_time(self):
"""Return the station active time from the most recent reading of SYS_VAL.
@return : active time, an integer 0-5759 minutes
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
return SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_ACTIVE_TIME, 2))
def set_feedback(self, audible = True, optical = True):
"""Set the optical and audible feedback of the station.
Default is to turn them both on.
@param audible : Boolean (optional, default True)
@param optical : Boolean (optional, default True)
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
feedback = SIReader._to_int(SIReader._extract_sysval(self.sysval, SIReader.O_FEEDBACK, 1))
if optical:
feedback |= 0b00000001
else:
feedback &= ~0b00000001
if audible:
feedback |= 0b00000100
else:
feedback &= ~0b00000100
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_FEEDBACK + int2byte(feedback))
def set_active_time(self, time):
"""Set the active time.
@param time : minutes, 0-5759
"""
if len(self.sysval) < 0x80:
self.refresh_sysval()
time_barr = SIReader._to_str(time, 2)
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_ACTIVE_TIME + time_barr)
def set_si6_192(self, enable=False):
"""Set whether the station shall support SI card 6 with 192 punches.
@param enable : Boolean, default is False
"""
if enable:
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_SI6_CB + b'\xFF')
else:
self._send_command(SIReader.C_SET_SYS_VAL, SIReader.O_SI6_CB + b'\xC1')
def get_station_code(self):
"""Get si station control code.
@return : control code (1-1023)
"""
return self._station_code
def get_time(self):
"""Read out station's internal time.
@return: datetime
"""
bintime = self._send_command(SIReader.C_GET_TIME, b'')[1]
year = byte2int(bintime[0]) + 2000
month = byte2int(bintime[1])
day = byte2int(bintime[2])
am_pm = byte2int(bintime[3]) & 0b1
second = SIReader._to_int(bintime[4:6])
hour = am_pm * 12 + second // 3600
second %= 3600
minute = second // 60
second %= 60
ms = int(round(byte2int(bintime[6]) / 256.0 * 1000000))
try:
return datetime(year, month, day, hour, minute, second, ms)
except ValueError:
# return None if the time reported by the station is impossible
return None
def set_time(self, time):
"""Set si station internal time.
@param time: time as a python datetime object.
"""
bintime = (SIReader._to_str(int(time.strftime('%y')), 1)
+ SIReader._to_str(time.month, 1)
+ SIReader._to_str(time.day, 1)
+ SIReader._to_str(((time.isoweekday() % 7) << 1) + time.hour//12, 1)
+ SIReader._to_str((time.hour % 12)*3600 + time.minute*60 + time.second, 2)
+ SIReader._to_str(int(round(time.microsecond / 1000000.0 * 256)), 1)
)
self._send_command(SIReader.C_SET_TIME, bintime)
def beep(self, count = 1):
"""Beep and blink control station. This even works if now sicard is
inserted into the station.
@param count: Count of beeps
"""
self._send_command(SIReader.C_BEEP, int2byte(count))
def set_direct(self):
"""Set the station to direct (master) mode."""
self._send_command(SIReader.C_SET_MS, SIReader.P_MS_DIRECT)
self.direct = True
def set_remote(self):
"""Set the station to remote (slave, indirect) mode."""
self._send_command(SIReader.C_SET_MS, SIReader.P_MS_INDIRECT)
self.direct = False
def read_backup(self, progress=0):
"""Read out the entire backup memory of a station configured as
control, check, clear, start or finish.
Before calling this function: set the station in direct or remote mode
depending on whether the master or slave should be read.
The station connected to the computer has to be in extended protocol mode.
The remote station can be in either extended or legacy mode.
@param progress: Set this to 1 to have the function print out
progress indications.
@return: A list of tuples: (date, cardnr, error)
'date' is a datetime object with the punch time
'cardnr' is an int with the card number
'error' is an empty string if there was
no error in the punch and a string like "ErrA"
etc if there was an error.
In case of error, the 'date' field is set to
midnight or noon of the actual date.
"""
# Check which protocol is in use and which mode the station is in
self._update_proto_config()
if not self.proto_config['mode'] in SIReader.SUPPORTED_READ_BACKUP_MODES:
raise SIReaderException('Station is in unsupported mode: %s' %
SIReader.MODE2NAME[self.proto_config['mode']])
# Read out backup memory pointers
ret = self._send_command(SIReader.C_GET_SYS_VAL, b'\x00\x80')[1]
offs1 = byte2int(SIReader.O_BACKUP_PTR_HI)+1
offs2 = byte2int(SIReader.O_BACKUP_PTR_LO)+1
end_ptr = SIReader._to_int(ret[offs1:offs1+2] + ret[offs2:offs2+2])
# Read out entire used backup memory.
# It seems like we can only read out 0x80 bytes at a time, so we might need
# to divide the read into several commands.
bakmem = b''
read_ptr = 0x100 # This is where reading always seems to start
while read_ptr < end_ptr:
read_ptr_bytes = (int2byte(read_ptr>>16) +
int2byte((read_ptr>>8)&0xff) +
int2byte(read_ptr&0xff))
byte_cnt = b'\x80'
if end_ptr-read_ptr < 0x80:
byte_cnt = int2byte(end_ptr-read_ptr)
ret = self._send_command(SIReader.C_GET_BACKUP, read_ptr_bytes + byte_cnt)[1]
if progress > 0:
print('.', end='')
sys.stdout.flush()
if self.proto_config['ext_proto']:
# Extended protocol
bakmem += ret[SIReader.BUX_FIRST+1:]
step = SIReader.BUX_SIZE
else:
# Legacy protocol
bakmem += ret[SIReader.BUL_FIRST+1:]
step = SIReader.BUL_SIZE
read_ptr += byte2int(byte_cnt)
# Gather some time-information to help guessing what dates