-
Notifications
You must be signed in to change notification settings - Fork 1
/
gdev_scout.py
2054 lines (1593 loc) · 76.1 KB
/
gdev_scout.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
# -*- coding: UTF-8 -*-
"""
gdev_scout.py - GeigerLog commands to handle the Gamma-Scout Geiger counter
Standard, Alert, Rechargeable, Online
"""
###############################################################################
# This file is part of GeigerLog.
#
# GeigerLog 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.
#
# GeigerLog 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 GeigerLog. If not, see <http://www.gnu.org/licenses/>.
###############################################################################
__author__ = "ullix"
__copyright__ = "Copyright 2016, 2017, 2018, 2019, 2020, 2021"
__credits__ = [""]
__license__ = "GPL3"
"""
NOTES:
GeigerLog supports Gamma-Scout models Standard, Alert, Rechargeable, and Online
Since Standard, Alert, and Rechargeable do not support logging from these
devices, GeigerLog implements their use for logging such that those GS
counters return only empty values (= NAN values) as logged data.
The Online Gamma-Scout .... tbd
Logging requires that a connection exists to a GS device, even if only as a
simulator, see next.
SIMULATION:
If a GS device is not available, it can be simulated. To do so start program
GLgammascoutsim.py in a separate Terminal window as SUDO (!):
sudo ./GLgammascoutsim.py
and start GeigerLog with the command GStesting, like:
'python3 geigerlog GStesting'.
GS will be connectable and allows downloading from the simulated device.
DOWNLOADING:
Gamma-Scout_Communication_Interface_V1.7.txt
from: https://www.gamma-scout.com/wp-content/uploads/Gamma-Scout_Communication_Interface_V1.7.txt
The contents of the protocol memory consists of either 2 byte pulse entries or
special codes. It must be interpreted byte by byte. Special codes start with a
byte with its high-nibble being 0xF. If the high-nibble is not 0xF, this byte
will be the first byte of a 2 byte pulse entry.
This 2 byte pulse entry represents the number of pulses collected during the
last protocol interval (or the number of pulse during an out-of-band protocol
interval, see below). The highest 5 bits contain the exponent, the lower 11
bits the mantissa. E.g.:
0x3E27 = %0011111000100111 = 2^7 (exponent) * 1575 (mantissa) = 201600
TUBE:
Gamma-Scout tube: LND712
https://www.lndinc.com/products/geiger-mueller-tubes/712/
Spec.Sheet:
GAMMA SENSITIVITY CO60 (CPS/mR/HR) : 18
MAXIMUM BACKGROUND SHIELDED 50MM PB + 3MM AL (CPM) : 10
Calculated:
Gamma Sensitivity : 18 CPS/mR/h = 1080 CPM/mR/h = 1080 CPM/10µSv/h = 108 CPM/µSv/h
invers: : 1/108 = 0.00926 µSv/h/CPM
Compare with M4011: (0.00926 / 0.0065 = 1.42 (1/1.42=0.70)
: LND712 has only 70% of sensitivity of M4011 for gamma
Memory: (manual 2018 page 16)
Wenn im Speicher nur noch 256 Bytes (von den
65280 Bytes) zum Beschreiben zur Verfügung
stehen, schaltet der GAMMA-SCOUT® automa-
tisch auf 7 Tage Protokollintervall zurück. In die-
sem Fall sind kürzere Protokollintervalle erst nach
dem Löschen des Speichers wieder einstellbar.
"""
from gsup_utils import *
import gsup_sql # database handling
try:
import serial # serial port (module has name: 'pyserial'!)
import serial.tools.list_ports # allows listing of serial ports
except Exception as e:
msg = "Module 'serial' could not be loaded\n"
msg += "Verify that 'pyserial' is installed using gtools/GLpipcheck.py"
exceptPrint(e, msg)
edprint("Halting GeigerLog")
playWav("err")
sys.exit()
#
# Private Constants
#
# intervals in sec as used in GammaScout
# this is the list of intervals for the 'Online' breed of counters. The Classic
# list is reached with using 'index + 1'
#
# "The device now supports stopping the protocol. Since a protocol interval of 0
# (zero) now denotes a stopped protocol, the remaining protocol intervals have
# shiftet +1."
_protocol_interval_online = {
0x00 : 0 , # User disabled the protocol
0x01 : 7 * 24 * 60 * 60, # User selected a protocol interval of 1 week
0x02 : 3 * 24 * 60 * 60, # User selected a protocol interval of 3 days
0x03 : 1 * 24 * 60 * 60, # User selected a protocol interval of 1 day
0x04 : 12 * 60 * 60, # User selected a protocol interval of 12 hours
0x05 : 2 * 60 * 60, # User selected a protocol interval of 2 hours
0x06 : 1 * 60 * 60, # User selected a protocol interval of 1 hour
0x07 : 30 * 60, # User selected a protocol interval of 30 minutes
0x08 : 10 * 60, # User selected a protocol interval of 10 minutes
0x09 : 5 * 60, # User selected a protocol interval of 5 minutes
0x0A : 2 * 60, # User selected a protocol interval of 2 minutes
0x0B : 1 * 60, # User selected a protocol interval of 1 minute
0x0C : 30, # User selected a protocol interval of 30 seconds
0x0D : 10, # User selected a protocol interval of 10 seconds
}
def printTestValues():
# test values for floating formatting
testraws = [0x3e27, # = 201600 # example from Gamma Scout company
0x00aa, # = 170
0x01bb, # = 443
0x02cc, # = 716
0x03dd, # = 989
0x04ee, # = 1262
0x05ff, # = 1535
0x1234, # = 3176
0b0000011111111110, # = 2046
0b0000011111111111, # = 2047
0b0000111111111111, # = 4094
0b0001111111111111, # = 16376
0xabcd, # = 2094006272
0x7fff, # max des Gerätes 0xF signalisiert Funktion
0xffff, # max test
0x0DAE, # aus *.dat
]
for raw in testraws:
print("raw: 0x {:04X}, 0b {:016b}, value: {:17,d}".format(raw, raw, _getValue(raw)))
print("\n")
#
# Private Functions
#
def _getValue(raw):
"""Gamma-Scout_Communication_Interface; raw is a 2 byte value. The highest
5 bits contain the exponent, the lower 11 bits the mantissa. E.g.:
0x3E27 = %0011 1 110 0010 0111 = 2^7 (exponent) * 1575 (mantissa) = 201600
"""
exponent = raw >> 11
mantissa = raw & 0b0000011111111111
counts = mantissa * (2 ** exponent)
#print("raw: {:6d} 0x{:04X} 0b{:016b} {} {}".format(raw, raw, raw, "{:016b}".format(raw)[0:5], "{:016b}".format(raw)[5:]), end= " ")
#print("exponent: {:3d}, mantissa: {:5d}".format(exponent, mantissa ), end =" ")
#print("counts: {:17,d}".format(counts))
return counts
def _getDateByte(raw):
"""hex value to be interpreted as alphanumeric: 0x37 = decimal 37!"""
rdate = 10 * (raw >> 4) + (raw & 0x0f)
return "{:02d}".format(rdate)
def _num2datstr(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
return str(dt)
def _New_parseCommentAdder(i, countertime, dbtype):
rectime = _num2datstr(countertime)
datalist = [None] * 4 # 4 x None
datalist[0] = i # byte index
datalist[1] = rectime # Date&Time
datalist[2] = "0 hours" # the modifier for julianday; here: no modification
datalist[3] = dbtype # Date&Time Stamp Info
#print("#{:5d}, {:19s}, {:}".format(i, rectime, dbtype))
gglobs.HistoryCommentList.append(datalist)
def _New_parseValueAdder(i, countertime, counts, parsecomment, cpm_calc, interval):
"""Add the parse results to the *.his list and commented *.his.parse list"""
# create the data for the database; datalist covers:
# Index, DateTime, <modifier>, CPM, CPS, CPM1st, CPS1st, CPM2nd, CPS2nd, CPM3rd, CPS3rd, Temp, Press, Humid, X
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
rectime = _num2datstr(countertime)
datalist = [None] * (gglobs.datacolsDefault + 2) # (13 + 2)=15 x None
datalist[0] = i # byte index
datalist[1] = rectime # Date&Time
datalist[2] = "0 hours" # the modifier for julianday; here: no modification
datalist[9] = cpm_calc # the cpm CALCULATED by adding up counts for last 60 sec
datalist[10] = counts # the counts in whatever the interval had been
datalist[14] = interval # the interval of counting
#print("_New_parseValueAdder: datalist: ", datalist)
gglobs.HistoryDataList.append (datalist)
gglobs.HistoryParseList.append([i, parsecomment])
def GSgetParsedHistory(hisbytes, maxbytes=0xFFFF):
"""For Gamma-Scout Classic and ONLINE: Parse the history as bytes dump"""
# startPH = time.time()
fncname = "GSgetParsedHistory: "
vprint(fncname)
setDebugIndent(1)
try:
index = hisbytes.index(0xF5) # =245 =start location of history
except Exception as e:
msg = "ERROR: Cannot find start byte 0xF5 (=245) in downloaded Online History"
exceptPrint(e, msg)
efprint(msg)
return
parsecounter = 0
parsecountlimit = 30 # max number of count records to be printed
parsecountpos = 300 # print every parsecountpos record
lastinterval = None #the last interval used, needed to see changes
interval = 0
countertime = 0
timestamp = 0
datestr = ""
cpmHistfreq = 6 # number of measurements taken per minute (6 when interval is 10sec)
cpmcalc = None # for storing last Counts_per_Xsec values as long as X <= 60
while True:
raw = hisbytes[index] # raw is SINGLE byte!
# Special code - Flag for more bytes to check
if raw == 0xF5:
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d})".format("Code-Follows Flag", raw, raw)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1
raw = hisbytes[index] # take next byte; raw is SINGLE byte!
# interval
if raw >= 0x00 and raw <= 0x0d:
if gglobs.GStype == "Online": interval_offset = 0
else: interval_offset = 1
interval = _protocol_interval_online[raw + interval_offset]
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}), Interval[sec]: old:{} new:{} ".format("Protocol Interval", raw, raw, lastinterval, interval)
dbtype2 = HILITECOLOR + dbtype + NORMALCOLOR
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype2))
_New_parseCommentAdder(index, countertime, dbtype)
if interval != lastinterval:
if interval <= 60:
cpmHistfreq = int(60 / interval)
cpmcalc = np.full(cpmHistfreq, gglobs.NAN) # for storing last cpmHistfreq of count values, fill with NANs
else:
cpmcalc = None
#edprint("interval != lastinterval: {} {} cpmcalc: {}".format(interval, lastinterval, cpmcalc))
lastinterval = interval
index += 1
# timestamp Online -- 6 bytes
# 0xED format: ssmmhhDDMMYY
elif raw == 0xED:
ss = _getDateByte(hisbytes[index + 1])
mm = _getDateByte(hisbytes[index + 2])
hh = _getDateByte(hisbytes[index + 3])
DD = _getDateByte(hisbytes[index + 4])
MM = _getDateByte(hisbytes[index + 5])
YY = _getDateByte(hisbytes[index + 6])
tbytes = "6 Bytes hex:" + " ".join("%02X" % e for e in hisbytes[index + 1: index + 7]) + " "
tstamp = "20{}-{}-{} {}:{}:{}".format(YY, MM, DD, hh, mm, ss)
countertime = datestr2num(tstamp)
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): {} ({})".format("Timestamp Online", raw, raw, tbytes, tstamp)
dbtype2 = HILITECOLOR + dbtype + NORMALCOLOR
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype2))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1 + 6
# timestamp Classic -- 5 bytes
# 0xEF format: mmhhDDMMYY
elif raw == 0xEF:
ss = "00" # added here, not defined in firmware of the Classics
mm = _getDateByte(hisbytes[index + 1])
hh = _getDateByte(hisbytes[index + 2])
DD = _getDateByte(hisbytes[index + 3])
MM = _getDateByte(hisbytes[index + 4])
YY = _getDateByte(hisbytes[index + 5])
#tbytes = "hexbytes:" + " ".join("%02X" % e for e in hisbytes[index + 1: index + 6])
tbytes = "5 Bytes hex:" + " ".join("%02X" % e for e in hisbytes[index + 1: index + 6]) + " "
tstamp = "20{}-{}-{} {}:{}:{}".format(YY, MM, DD, hh, mm, ss)
countertime = datestr2num(tstamp)
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): {} ({})".format("Timestamp Classic", raw, raw, tbytes, tstamp)
dbtype2 = HILITECOLOR + dbtype + NORMALCOLOR
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype2))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1 + 5
# out of band
elif raw == 0xEE:
nextbyte1 = hisbytes[index + 1] # nextbyte1 and 2 give number of 10 sec to be added to time
nextbyte2 = hisbytes[index + 2]
addedtime = (nextbyte2 * 256 + nextbyte1) * 10 # multiples of 10 sec
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): protocol interval: 0x{:02X} 0x{:02X} => addedTime:{}".format("Out-Of-Band", raw, raw, nextbyte1, nextbyte2, addedtime)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
extra = 0
while hisbytes[index + 3 + extra] == 0xFC:
extra += 1 #das Alarm byte sollte nie innerhalb einer anderen Sequenz vorkommen!
dbtype = "{:20s}: 0x{:02X} ({:3d}): Dose (rate) alarm fired".format("Alarm", 0xFC, 0xFC)
wprint("index:{:5d} {}".format(index + 3 + extra, dbtype))
_New_parseCommentAdder(index + 3 + extra, countertime, dbtype)
raw1 = hisbytes[index + 3 + extra]
raw2 = hisbytes[index + 4 + extra]
count = _getValue(raw1 << 8 | raw2)
dbtype = "{:20s}: 0x{:02X} 0x{:02X} : => count:{}".format("Out-of-Band pulses", raw1, raw2, count)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
if addedtime > 0:
dbtype = "{:19s}, {:10d}, {:9,.1f}, {:8d}".format(_num2datstr(countertime), count, count/addedtime * 60, addedtime)
wprint("index:{:5d} {:5d} : {} # Out-of-Band pulses, excluded from parsing result".format(index, 0, dbtype))
#_New_parseValueAdder (index, countertime, count, parsecomment, count/addedtime * 60, addedtime)
#parsecounter += 1 # wäre notwendig wenn _parseValueAdder zum Zuge gekommen wäre
#~countertime += interval + addedtime
#~countertime += interval
countertime += addedtime
index += 1 + 4 + extra
# ignore debug - seems relevant only for Classic but does not harm Online
# "0xF0-0xFE debug flags, must be ignored"
elif raw >= 0xF0 and raw <= 0xFE:
dbtype = "{:20s} must be ignored: 0x{:02X} ({:3d}): ".format("Debug flags", raw, raw)
wprint(dbtype)
_New_parseCommentAdder(index, countertime, dbtype)
index += 1
# skip byte
# "0xF8 This is a new internal special byte. The following size byte denotes
# the amount of additionally following bytes (including this size byte
# but not including the special byte 0xF8) which have to be ignored and
# skipped over in the protocol stream."
elif raw == 0xF8:
nextbyte = hisbytes[index + 1]
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): Bytes to skip: {}".format("Skip Byte", raw, raw, nextbyte)
dbtype2 = HILITECOLOR + dbtype + NORMALCOLOR
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype2))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1 + nextbyte
# Special code - Dose overflow - Classic Only
elif raw == 0xFA and gglobs.GStype == "Classic":
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): Dose rate overflowed (> 1000 uSv/h) during the current protocol interval at least once.".format("Overflow Code", raw, raw)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1
# special codes 0xF9 with 0xFF
# 0xF9 Dose rate overflowed
# 0xFA Dose alarm fired
# 0xFB Dose alarm fired + Dose rate overflowed
# 0xFC Dose rate alarm fired
# 0xFD Dose rate alarm fired + Dose rate overflowed
# 0xFE Dose rate alarm fired + Dose alarm fired
# 0xFF Dose rate alarm fired + Dose alarm fired + Dose rate overflowed
elif raw >= 0xF9 and raw <= 0xFF:
rtime = _num2datstr(countertime)
dbtype = "{:20s}: 0x{:02X} ({:3d}): Dose or Dose rate alarm overflowed/fired".format("Alarm", raw, raw)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
index += 1
# counts
else:
raw1 = hisbytes[index ]
raw2 = hisbytes[index + 1]
count = _getValue(raw1 << 8 | raw2)
if cpmcalc is not None: # use only when interval <= 60
cpmcalc = np.append(cpmcalc, count)[-cpmHistfreq:] # append, but then take last cpmHistfreq values only
cpi = float(np.sum(cpmcalc))
else:
cpi = gglobs.NAN # cannot calculate true CPM if interval > 60!
parsecomment = "# raw bytes: 0x{:02X}{:02X}".format(raw1, raw2)
_New_parseValueAdder (index, countertime, count, parsecomment, cpi, interval)
parsecounter += 1
# printouts, like first 50, then every 150th, then last 50
if parsecounter < parsecountlimit or parsecounter % parsecountpos == 0 or (maxbytes - index) < (parsecountlimit * 2) :
rtime = _num2datstr(countertime)
dbtype = "{:10d}, {:9,.1f}, {:8d}, # raw bytes: 0x{:02X}{:02X}".format(count, cpi, interval, raw1, raw2)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, parsecounter, rtime, dbtype))
countertime += interval
index += 1 + 1
if index >= maxbytes:
rtime = _num2datstr(countertime)
dbtype = "# maxbytes reached or exceeded: index:{}, maxbytes:{} (0x{:04X})".format(index, maxbytes, maxbytes)
wprint("index:{:5d} {:5d} : {:19s}, {}".format(index, 0, rtime, dbtype))
_New_parseCommentAdder(index, countertime, dbtype)
break
if index >= len(hisbytes) - 1:
break
setDebugIndent(0)
def GSreadDataFromFile(dat_path):
"""read an ASCII file as readlines and return as list of byte values"""
fncname = "GSreadDataFromFile: "
dumpdata = []
wprint(fncname)
setDebugIndent(1)
if not gglobs.GSConnection: return dumpdata
try:
with open(dat_path) as f:
filedata = f.readlines() # reads data as list of STRINGS
# last char in each line is LF (value: 0x10)
except Exception as e:
exceptPrint(e, fncname + "Exception at f.readlines()")
return dumpdata
wprint(fncname + "filedata: type:{}, lines:{}".format(type(filedata), len(filedata)))
if gglobs.werbose:
wprint(fncname + "filedata - begin ------------------------------------")
limit = 13
for i, a in enumerate(filedata):
if i == limit: print("...")
if i < limit or i > len(filedata) - limit:
print(" i: {:5d} : ".format(i), a, end="")
print()
wprint(fncname + "filedata - end ------------------------------------")
# write *.dat data to database
gsup_sql.DB_insertBin (gglobs.hisConn, "".join(filedata))
for a in filedata: # remove last char LF
dumpdata.append(a[:-1])
wprint(fncname + "dumpdata: type:{}, lines:{}".format(type(dumpdata), len(dumpdata)))
dashline = fncname + "-" * 80
wprint(dashline)
for a in dumpdata[ :12]: wprint(a)
wprint("...")
for a in dumpdata[-10:]: wprint(a)
wprint(dashline)
setDebugIndent(0)
return dumpdata
def GSclearPipeline():
"""Clearing pipeline"""
if not gglobs.GSConnection: return
fncname = "GSclearPipeline: "
wprint(fncname)
start2 = time.time()
wait2 = 0.1 # sec waiting in while loop
try:
bw = gglobs.GSser.in_waiting
except Exception as e:
exceptPrint(e, fncname + "#1 GSser.in_waiting Exception")
bw = 0
while (time.time() - start2) < wait2 or bw > 0:
if bw > 0:
bytedata = gglobs.GSser.read(bw) # reads data as BYTES
wprint(fncname + "{:6.1f} ms, waiting bytes:{} ".format((time.time() - start2) * 1000, bw), bytedata)
time.sleep(0.02)
try:
bw = gglobs.GSser.in_waiting
except Exception as e:
exceptPrint(e, fncname + "#2 GSser.in_waiting Exception")
bw = 0
#wprint(fncname + "returning: {:6.1f} ms, waiting bytes:{} ".format((time.time() - start2) * 1000, bw))
def GSreadAll(bytecount=None, waittime=4):
"""Read all waiting data"""
fncname = "GSreadAll: "
if bytecount == None: msg = ""
else: msg = "requested bytes to read: {}".format(bytecount)
wprint(fncname + msg)
alldata, msg = _GSread_waiting(bytecount=bytecount, waittime=waittime)
if msg > "":
setDebugIndent(1)
wprint(fncname + msg)
setDebugIndent(0)
return alldata
def _GSread_waiting(bytecount=None, waittime=4):
"""read all waiting bytes and return decoded and stripped string"""
fncname = "_GSread_waiting: "
bytedata = b""
alldata = ""
msg = ""
if gglobs.GSser is None:
return alldata, "no connection"
# wait for the first bytes appearing in_waiting
start1 = time.time()
while (time.time() - start1) < waittime: # could take more than 3 sec!
try:
bw = gglobs.GSser.in_waiting
except Exception as e:
exceptPrint(e, fncname + "#1 GSser.in_waiting Exception")
bw = 0
#print(".", end="", flush=True)
time.sleep(0.01)
if bw > 0: break
#print()
wprint(fncname + "1st wait: {:6.1f} ms, now waiting: {} bytes".format((time.time() - start1) * 1000, bw)) # 400 ... 1000 ms
# at this point there are some bytes waiting
if bytecount != None: bytedata += gglobs.GSser.read(bytecount) # reads bytecount data BYTES
else: bytedata += gglobs.GSser.read(bw) # reads bw data as BYTES
# wait for any late bytes
start2 = time.time()
last = start2
wait2 = 0.05 # sec waiting in while loop
try:
bw = gglobs.GSser.in_waiting
except Exception as e:
exceptPrint(e, fncname + "#2 GSser.in_waiting Exception")
bw = 0
while time.time() - start2 < wait2 or bw > 0:
if bw > 0:
bytedata += gglobs.GSser.read(bw) # reads data as BYTES
now = time.time()
wprint(fncname + "2nd wait: {:6.1f} ms, now waiting: {} bytes".format((now - last) * 1000, bw))
last = now
time.sleep(0.02)
try:
bw = gglobs.GSser.in_waiting
except Exception as e:
exceptPrint(e, fncname + "#3 GSser.in_waiting Exception")
bw = 0
wprint(fncname + "total wait: {:6.1f} ms, got total : {} bytes".format((time.time() - start1) * 1000, len(bytedata))) # 400 ... 1000 ms
######################
#~sbytedata = bytedata.strip().split(b"\r\n")
#~for i, a in enumerate(sbytedata):
#~print("_GSread_waiting: {:3d} len: {:3d} {}".format(i, len(a), a))
################
# check Null values #######################################################
if 0x00 in bytedata:
msg0 = "Bytes read from device contain the illegal value 0x00 !"
msg1 = "<br>There may be a problem with the device or with the transmission."
msg1 += "You can try to unplug/replug <br>the device with the computer.<br>"
msg1 += "Any records containing wrong chracters will be ignored in the anaylsis. "
msg1 += "You can continue,<br>but be aware of possibly missing records."
setDebugIndent(1)
edprint(msg0, debug=True)
setDebugIndent(0)
efprint(msg0 + msg1)
qefprint("Count of 0x00 in transferred 7-bit bytes: {}. First occurence at position: {} of {}."\
.format(bytedata.count(0x00), bytedata.index(0x00), len(bytedata)))
bytedata = bytedata.replace(b"\x00", b"\x01")
playWav("err")
# End Check Null Values ###################################################
alldata = bytedata.decode("UTF-8").strip()
lenalldata = len(alldata)
msg = ""
if lenalldata > 0:
msg = "Read data: decoded: len:{}".format(lenalldata)
if lenalldata < 100:
msg += " '{}'" .format(alldata)
else:
limit = 200
msg += "\n{}".format(alldata[0:limit])
if lenalldata >= limit: msg += " <more>"
return alldata, msg
def GSwriteToDevice(wdata, purpose=""):
"""writing wdata to device; type(wdata)=bytes
returns True if ok, otherwise False"""
fncname = "GSwriteToDevice: "
if gglobs.GSser is None:
edprint(fncname + "Serial Port is closed; cannot write to it!")
return False
wprint(fncname + "Writing '{}' (len:{}) to device -- purpose: '{}'".format( wdata, len(wdata),purpose))
bytesWritten = None
try:
bytesWritten = gglobs.GSser.write(wdata) # this line writes the data to the port; takes <0.1ms
if bytesWritten == len(wdata):
ok = True
else:
ok = False
setDebugIndent(1)
wprint(fncname + "FAILURE writing '{}' to device: {} bytes written, but write data has length {}".format(wdata, bytesWritten, len(wdata)))
setDebugIndent(0)
except Exception as e:
ok = False
msg = "ERROR: Writing data '{}' to device".format(wdata)
exceptPrint(e, msg)
efprint(msg)
return ok
def GSconvertDumpToBinList(dumpdata):
"""take ascii coded hex values from readlines str data and convert to list of bytes"""
# e,g,: dumpdata[12]: len=67: f5ef5923130819f507f5ee0300000af50c00020001000100050004000500030096
# ends with '96' as any LF or CR+LF has been removed!
fncname = "GSconvertDumpToBinList: "
len_dumpdata = len(dumpdata)
vprint(fncname + "len(dumpdata): {}".format(len_dumpdata))
setDebugIndent(1)
if len_dumpdata == 0:
vprint(fncname + "No data to convert")
setDebugIndent(0)
return []
index = 0
# search for text "GAMMA-SCOUT Protokoll"
for i in range(0, len_dumpdata):
if dumpdata[i].startswith("GAMMA-SCOUT Protokoll"):
index = i
strwprint = "i={:5d} dumpdata[i]: {}".format(i, dumpdata[i])
wprint(strwprint)
break
# search for text "f5" beginning at "GAMMA-SCOUT Protokoll"
for i in range(index, len_dumpdata):
if dumpdata[i].startswith("f5"):
index = i
break
# convert double-chr to byte and add to list
listdumpdata = []
for i in range(index, len_dumpdata):
lendata = len(dumpdata[i])
###########################################
if lendata > 66:
strwprint = "i={:5d} dumpdata[i]: {} lendata: {}".format(i, dumpdata[i], lendata)
edprint(strwprint + " ************ wrong data *************")
continue # to avoid wrong records!!!!!!!!!!!!!!!!
###########################################
# limited printout
if i == index + 10: wprint("....")
if i < index + 10 or i > (len_dumpdata - 10):
strwprint = "i={:5d} dumpdata[i]: {} lendata: {}".format(i, dumpdata[i], lendata)
try:
checksum = 0
for j in range(0, lendata - 2, 2):
newval = int(dumpdata[i][j:j+2], 16)
#print(newval, end=" ")
checksum += newval
checksum = checksum & 0xFF
strwprint += " Checksum: {:02x}".format(checksum)
strwprint += " Delta to dumpdata ...{}: {:3d}".format(dumpdata[i][-2:], checksum - int(dumpdata[i][-2:], 16))
except Exception as e:
msg = "Checksum calculation gave Exception, i:{} j:{}".format(i, j)
msg += strwprint
exceptPrint(e, msg)
wprint(strwprint)
# get byte data from ASCII list
for j in range(0, lendata - 2, 2):
#print("j={}".format(j), end=" ")
try:
lbyte = int(dumpdata[i][j : j + 2], 16)
except Exception as e:
msg = fncname + "Exception in 'lbyte = int(dumpdata[i][j : j + 2], 16)': i:{}, j={}".format(i,j)
msg += " dumpdata[i][j : j + 2], =" + str(dumpdata[i][j : j + 2])
exceptPrint(e, msg)
lbyte = 0xFA # overflow single byte value
listdumpdata.append(lbyte)
wprint(fncname + "listdumpdata : len: {} (0x{:04X}) ".format(len(listdumpdata), len(listdumpdata)))
wprint(fncname + "first 30 : ", listdumpdata[:30])
wprint(fncname + "last 30 : ", listdumpdata[-30:])
wprint(fncname + "======================================")
setDebugIndent(0)
return listdumpdata
def GSextractExtendedInfo(infoline):
"""to extract info from infoline
return: nothing (all returns via gglobs)
"""
"""
PC mode up to fw 6.1x:
'v' returns: fw version, SN, number of used bytes in the protocol memory, date and time
changes in PC mode starting with fw 6.90:
'v' returns: fw version, CPU version, SN, number of used bytes in the protocol memory, date and time
changes in PC mode starting with fw 7.03:
'v' returns: fw version, SN, number of used bytes in the protocol memory, date and time
GSfwtype
e.g.: 610: infoline = 'Version 6.10 d93683 4217 18.08.19 17:43:57'
702: infoline = 'Version 7.02Lb07 1020 073160 4bde 18.02.21 15:42:39'
703: infoline = 'Version 7.03xyz 073160 4bde 18.02.21 15:42:39'
"""
#~gglobs.GStype = None
#~gglobs.GSFirmware = (None, None) # major, minor fw number
#~gglobs.GSSerialNumber = None
#~gglobs.GSusedMemory = None
#~gglobs.GSDateTime = None
gglobs.GStype = ""
gglobs.GSFirmware = ("", "") # major, minor fw number
gglobs.GSSerialNumber = ""
gglobs.GSusedMemory = 0
gglobs.GSDateTime = ""
fncname = "GSextractExtendedInfo: "
dprint(fncname + "infoline: '{}'".format(infoline))
setDebugIndent(1)
if infoline is None: return
if len(infoline) == 0:
dprint(fncname + "No data in infoline: '{}'".format(infoline))
else:
infolist = infoline.split(" ")
wprint(fncname + "infolist: '{}'".format(infolist))
#~fwtemp = infolist[1].split(".", 1)
#~wprint(fncname + "fwtemp: '{}'".format(fwtemp))
fw = tuple(infolist[1].split(".", 1))
wprint(fncname + "fw: '{}'".format(fw))
#~try:
#~fw_version = float(re.findall("\d+\.\d+", infolist[1])[0])
#~except Exception as e:
#~exceptPrint(e, "cannot get float of :{}".format(infolist[1]))
#~fw_version = 6.1
#~#wprint(fncname + "fw_version: {}".format(fw_version))
gglobs.GSFirmware = fw
fw0 = fw[0]
fw1 = fw[1][0:2]
if fw0 < "6":
gglobs.GStype = "Old"
gglobs.GSfwtype = None
elif fw0 == "6" and (fw1 > "017" and fw1 < "90"):
gglobs.GStype = "Classic"
gglobs.GSfwtype = "610"
elif fw0 == "7" and (fw1 >= "01" and fw1 <= "02"):
gglobs.GStype = "Online"
gglobs.GSfwtype = "702"
elif fw0 == "7" and (fw1 >= "03"):
gglobs.GStype = "Online"
gglobs.GSfwtype = "703"
else:
gglobs.GStype = "OnlineX"
gglobs.GSfwtype = "999"
wprint(fncname + "Firmware: fw:{} GStype:{} GSfwtype:{}".format(fw, gglobs.GStype, gglobs.GSfwtype))
if gglobs.GSfwtype == "610":
gglobs.GSSerialNumber = infolist[2]
gglobs.GSusedMemory = int(infolist[3], 16)
dt = infolist[4] + " " + infolist[5] # 14.08.2019 18:37:00
elif gglobs.GSfwtype == "702":
gglobs.GSSerialNumber = infolist[3]
gglobs.GSusedMemory = int(infolist[4], 16)
dt = infolist[5] + " " + infolist[6] # 14.08.2019 18:37:00
elif gglobs.GSfwtype == "703":
gglobs.GSSerialNumber = infolist[2]
gglobs.GSusedMemory = int(infolist[4], 16)
dt = infolist[5] + " " + infolist[6] # 14.08.2019 18:37:00
elif gglobs.GSfwtype == "999": # just guessing
gglobs.GSSerialNumber = infolist[2]
gglobs.GSusedMemory = int(infolist[4], 16)
dt = infolist[5] + " " + infolist[6] # 14.08.2019 18:37:00
else: #gglobs.GStype == "Old", gglobs.GSfwtype = None
msg = "Gamma-Scout versions older than Classic are not supported by GeigerLog"
dprint(fncname + msg, debug=True)
efprint(msg)
setDebugIndent(0)
return
try:
timestamp = time.mktime(datetime.datetime.strptime(dt, "%d.%m.%y %H:%M:%S").timetuple())
device_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
except Exception as e:
edprint(fncname + "Exception timestamp: ", e)
device_time = "Failure"
gglobs.GSDateTime = device_time
setDebugIndent(0)
def GSgetCalibData():
"""get the Gamma-Scout internal calibration data"""
"""
# 'c' dumps internal calibration data
from an old file produced with Gamma-Scout software:
b0 07 0078
0b000000a4f8a29c3b01
48010000450783fa1c02
77040000db06fcf91c02
ce110000ca6918fe7602
de5a0000eb26b5fb5802
9e050100df1f27ff6702
e0ff1f00bf038efdb202
produced by this function on a Gamma-Scout Online firmware 7.02:
GAMMA-SCOUT SoftCal gueltig
b0 00 07 7e 00
cd0900001a05f6da2d00
9a210000c1e1acb12d00
9a7d00002f0995c63c00
00a0020002009af24b00
9a46080004001cc23c00
c47d130085010e9e2d00
15dd4400990210b32d00
"""
gglobs.GSCalibData = None
fncname = "GSgetCalibData: "
wprint(fncname)
setDebugIndent(1)
ok = GSwriteToDevice(b'c', "get calib data")
mode_response = GSreadAll() # decoded and stripped
#wprint(fncname + "mode_response: ", mode_response)
if mode_response > "": gglobs.GSCalibData = mode_response
setDebugIndent(0)
def GSgetVersionDetails():
"""writing 'v' to the counter, while in PC Mode, to return Details:
like: ['', 'Version 6.10 d93683 4213 18.08.19 17:42:05'],
then extract:
- fw version
- SN
- number of used bytes in the protocol memory
- date and time
Valid in PC mode up to fw 6.1x
"""
gglobs.GSinPCmode = False
version = None
fncname = "GSgetVersionDetails: "
wprint(fncname)
setDebugIndent(1)
GSclearPipeline()
GSgetMode()
if gglobs.GScurrentMode == "Failure": return False
if not gglobs.GScurrentMode == "PC": # if not in PC Mode then switch to it
GSsetModePC()
dprint(fncname + "1st: Device is in {} Mode".format(gglobs.GScurrentMode))
GSgetMode() # now to get the version
if gglobs.GScurrentMode == "Failure": return False
else:
dprint(fncname + "Device is in {} Mode".format(gglobs.GScurrentMode))
GSextractExtendedInfo(gglobs.GSversion)
setDebugIndent(0)
return True
def GSreadMemoryData(saveToBin=False, bytecount=None):
"""read data from the Gamma Scout device"""
fncname = "GSreadMemoryData: "
vprint(fncname)
setDebugIndent(1)
Qt_update()
start = time.time()
devicedata = GSreadAll(bytecount=bytecount)
dtime = time.time() - start
data = devicedata.strip()
dumpdata = data.split("\r\n")
wprint(fncname + "devicedata: type: {:16s}, total length: {}".format(str(type(devicedata)), len(devicedata)))
wprint(fncname + "dumpdata: type: {:16s}, total length: {}".format(str(type(dumpdata)), len(dumpdata)))
#wprint(fncname + "Data (devicedata after stripping and decoding):\n{}".format(data)) # too much data
lendevdata = int(len(dumpdata) * 64 / 2) # transfer in 7bit format! takes 2 bytes for 1 byte
msg = "Got {} byte-values in {:0.1f} s --> {:0.1f} kBytes/s".format(lendevdata, dtime, lendevdata / dtime / 1000)