-
Notifications
You must be signed in to change notification settings - Fork 59
/
buck50.py
executable file
·6782 lines (6118 loc) · 283 KB
/
buck50.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
# buck50: Test and measurement firmware for “Blue Pill” STM32F103 development board
# Copyright (C) 2019, 2020, 2021 Mark R. Rubin aka "thanks4opensource"
#
# This file is part of buck50.
#
# The buck50 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.
#
# The buck50 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
# (LICENSE.txt) along with the buck50 program. If not, see
# <https:#www.gnu.org/licenses/gpl.html>
import argparse
import collections
import copy
import fcntl
import functools
import math
import os
import re
import random
import readline
import select
import shlex
import shutil
import socket
import string
import struct
import subprocess
import sys
import termios
import time
import tty
### copyright and version
#
#
VERSION = (0, 9, 6)
COPYRIGHT = '''%s %d.%d.%d
Copyright 2020 Mark R. Rubin aka "thanks4opensource"''' \
% (os.path.basename(sys.argv[0]), *VERSION)
BANNER = COPYRIGHT + """
This is free software with ABSOLUTELY NO WARRANTY.
For details type "warranty" or "help warranty".
Type "using" for program usage.
Type "help" for commands, configurations, parameters, values.
"""
WARRANTY="""
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, write to
The Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor
Boston, MA 02110-1335 USA
"""
### preliminary constants (must precede utils, actions, etc)
#
#
CPU_MHZ = 72
CPU_HZ = float(CPU_MHZ) * 1e6
# python select() time type limit (C _PyTime_t):
# (1<<63)/1e9 == 9223372035.854776 seconds == 292.47120864582627 years
# 72e6 * (1<<63)/1e9 = 6.640827866535438e+17
# int(72e6 * (1<<63)/1e9) = 664082786653543808
# hex(int(72e6 * (1<<63)/1e9)) = 0x9374bc6a7ef9d80
# 0x7ffffffffffffff (largest mask)
MAX_DURATION = 0x7ffffffffffffff
MAX_PYTIME = (1 << 63) / 1e9
### preliminary utils
# (used by classes and helpers, must precede both for module-level
# init of objects)
#
#
def quoted_sequence(sequence):
return ['"%s"' % element for element in sequence]
def comma_or_concat(sequence, conjunction='or'):
if len(sequence) == 2:
return (" %s " % conjunction).join(quoted_sequence(sequence))
elif len(sequence) > 2:
return "%s, %s \"%s\"" % (", ".join(quoted_sequence(sequence[:-1])),
conjunction ,
sequence[-1] )
elif len(sequence) == 1:
return sequence[0]
else:
return ''
### action utils (must precede configs/actions below)
#
#
# reset_config actions
#
def adjust_cpu_hz():
global CPU_HZ
CPU_HZ = float(CPU_MHZ) * 1e6 * configure_config['trim'].val
def config_set(configuration, parameter, value):
configuration[parameter].val = value
def usb_connect():
global dev_acm, usb_fd
if usb_fd != -1:
os.close(usb_fd)
try:
usb_fd = os.open(dev_acm, os.O_RDWR)
except Exception as error:
sys.stderr.write( "Can't open CDC/ACM file %s: %s\n"
% (dev_acm, str(error)) )
sys.exit(1)
if os.isatty(usb_fd): # for testing
tty.setraw(usb_fd)
def check_version(quiet):
global firmware_version
vers_rsp = cmd_rsp(VERS_CMD, 3, "VERS")
if vers_rsp is not None:
firmware_version = struct.unpack('BBB', vers_rsp)
if firmware_version == VERSION:
if not quiet:
sys.stdout.write( "Firmware version match: %s\n"
% '.'.join([str(elem) for elem in VERSION]))
else:
if firmware_version[0] != VERSION[0]\
or firmware_version[1] < VERSION[1]:
mismatch = "ERROR"
else:
mismatch = "Warning"
sys.stdout.write( "%s: Firmware version mismatch: "
"firmware: %s software: %s\n"
% (mismatch,
'.'.join([str(elem) for elem in
firmware_version] ),
'.'.join([str(elem) for elem in VERSION])))
def firmware_connect(quiet=False):
while True:
if not os.isatty(usb_fd): break # for testing
if not quiet:
sys.stdout.write("Connecting to buck50 device "
"(press CTRL-C to abort ... )\n")
os.write(usb_fd, struct.pack('20B', *SIGNATURE))
response = wait_read(4, 1)
if response is WAIT_READ_STDIN:
sys.exit(1)
elif response is not None:
response = struct.unpack('I', response)[0]
if response == IDENTITY:
if not quiet:
sys.stdout.write( "Firmware identity match: 0x%08x\n"
% IDENTITY)
else:
sys.stdout.write( "buck50 device identity mismatch: "
"hardware: 0x%08x "
"software: 0x%08x\n"
% (response, IDENTITY) )
break
elif not os.isatty(usb_fd): # for testing
break
else:
sys.stderr.write("Will retry sending signature data in 1 second\n")
time.sleep(1)
if not os.isatty(usb_fd): return # for testing
# check version and report serial number
check_version(quiet)
if not quiet:
serial_number()
def reset_connect():
global dev_acm, usb_fd
if r_u_sure( "Disconnect USB port/driver (currently "
"\"%s\") and connect to (use usb=... to "
"change) \"%s\"?"
% (dev_acm, reset_config['usb'].val) ):
dev_acm = reset_config['usb'].val
usb_connect() # will exit program on failure
def serial_number():
serial = None
response = cmd_rsp(SRNO_CMD, 1, "serial_number")
if response:
serial = wait_read(response[0], 2)
if serial in (WAIT_READ_STDIN, None):
sys.stderr.write("Failure receiving serial number\n")
return
Pager()("Device serial number: %s\n" % serial.decode('utf-8'),
immed=True, one_line=True)
def blink_user_led():
'''
Pager()("Blinking device LED, <ENTER> to halt ...",
immed=True, one_line=True )
'''
cmnd_cmd(BLNK_CMD)
safe_input("Blinking device LED, <ENTER> to halt ... ",
"blink_user_led" )
cmnd_cmd(HALT_CMD)
# trigger_config actions
#
def check_triggers():
max_trig = max([ndx for ndx in triggers_config])
errors = 0
for (num, trig) in triggers_config.items():
if trig.mach() not in triggers_config:
sys.stderr.write( "trigger %d=%s: pass %d isn't in triggers %s\n"
% (num, trig, trig.mach(), list(triggers_config)))
errors += 1
if trig.fail() not in triggers_config: # and trig.mask() != 0x00:
sys.stderr.write( "trigger %d=%s: fail %d isn't in triggers %s\n"
% (num, trig, trig.fail(), list(triggers_config)))
errors += 1
if trig.mach () != num \
and trig.mask () != 0 \
and trig.mach () in triggers_config \
and trig.mask_bits() == triggers_config[trig.mach()].mask_bits():
sys.stderr.write( "trigger %d=%s: pass -> %d has "
"same test (%s) -- disallowd\n"
% (num, trig, trig.mach(), trig.mask_bits()))
errors += 1
if trig.fail () != num \
and trig.mask () != 0 \
and trig.fail () in triggers_config \
and trig.mask_bits() == triggers_config[trig.fail()].mask_bits():
sys.stderr.write( "trigger %d=%s: fail -> %d has "
"same test (%s) -- disallowd\n"
% (num, trig, trig.fail(), trig.mask_bits()))
errors += 1
if num == 0:
continue
if trig.mach() == trig.fail() and trig.fail() != 0 and trig.mask() != 0:
sys.stderr.write( "trigger %d=%s: not allowed pass same as fail "
"(%d)\n"
% (num, trig, trig.mach()) )
errors += 1
for trigger in triggers_config:
machs = []
check = trigger
while True:
machs.append(check)
next = triggers_config[check].mach()
if not next in triggers_config: # already checked above
break
if next == 0:
break
if next in machs:
machs.append(next)
sys.stderr.write( "Infinite triggers \"pass\" loop: %s\n"
% " -> ".join([str(mach) for mach in machs]))
errors += 1
break
check = next
for trigger in triggers_config:
fails = []
start = trigger
check = trigger
while True:
if triggers_config[check].mask() == 0:
break
fails.append(check)
next = triggers_config[check].fail()
if not next in triggers_config: # already checked above
break
# if triggers_config[next].mask() == 0:
# break
if next in fails:
if next == start:
break
else:
sys.stderr.write( "Bad triggers fail chain, doesn't end "
"at start or at \"xxxxxxxx-X-Y\": %s\n"
% " -> ".join([ str(fail)
for fail
in fails] ) )
errors += 1
break
check = next
if errors:
sys.stderr.write( "%d trigger error%s\n"
% (errors, '' if errors == 1 else 's'))
return False
else:
return True
def triggers_undo():
global triggers_config, triggers_backup
if r_u_sure("Restore triggers to before last change or delete?"):
triggers_config = copy.deepcopy(triggers_backup)
sys.stdout.write("Triggers restored\n")
# configure_config actions
#
def configure_save():
global configure_loadsave_error
if configure_config['file'].val is None:
sys.stderr.write("Set \"file=\" parameter\n")
configure_loadsave_error = True
return
filename = configure_config['file'].val
if not filename.endswith(CONFIG_FILE_EXTENSION):
filename += CONFIG_FILE_EXTENSION
file = safe_open(filename, " for saving configuration")
if not file:
sys.stderr.write("Not saving to file \"%s\"\n" % filename)
configure_loadsave_error = True
return
if file:
file.write("idnt 0x%x\n" % IDENTITY)
file.write("vers %d %d %d\n" % VERSION )
configs_print([ key
for key in SETTINGS.keys()
if key not in ('confige' ,
'help' ,
'warranty',
'quit' )],
file )
file.close()
sys.stdout.write("Saved confguration to file %s\n" % filename)
def configure_load():
global configure_loadsave_error
if configure_config['file'].val is None:
sys.stderr.write("Set \"file=\" parameter\n")
configure_loadsave_error = True
else:
filename = configure_config['file'].val
if load_config_file(filename):
sys.stdout.write("Loaded from file %s\n" % filename)
else:
configure_loadsave_error = True
### classes/types
#
#
# helpers
#
def disambiguate(choice, choices, case_sensitive=False):
if case_sensitive:
matches = [ check
for check
in choices
if check.startswith(choice)]
else:
choice_lower = choice.lower()
matches = [ check
for check
in choices
if check.lower().startswith(choice_lower)]
# matches.sort()
number_of_matches = len(matches)
if number_of_matches == 0:
good_match = None
exact_match = None
# check_match = None
error = "\"%s\" is not prefix of any: %s" \
% (choice, comma_or_concat(tuple(choices), 'or'))
# tuple in case called with
# dict_keys
elif number_of_matches == 1:
good_match = matches[0]
if case_sensitive:
if matches[0] == choice:
exact_match = matches[0]
else:
exact_match = None
else:
if matches[0].lower() == choice_lower:
exact_match = matches[0]
else:
exact_match = None
if exact_match:
error = None
if not exact_match:
error = "\"%s\" does not exactly match \"%s\"" % (good_match,
matches[0])
else:
if case_sensitive:
if choice in matches:
exact_match = choice
else:
exact_match = None
else:
matches_lower = [check.lower() for check in matches]
if choice_lower in matches_lower:
exact_match = matches[matches_lower.index(choice_lower)]
else:
exact_match = None
if exact_match:
good_match = exact_match
else:
matches.sort()
good_match = matches[0]
error = "\"%s\" is ambiguous prefix of: %s" \
% (choice, comma_or_concat(matches, 'and'))
return collections.namedtuple("disambig" ,
"good exact count matches error") \
(good_match ,
exact_match ,
number_of_matches,
matches ,
error )
def float_completer(text, units):
if not text:
return [char for char in '+-0123456789.']
alloweds = '0123456789'
if '.' not in text: alloweds += '.'
if 'e' not in text.lower(): alloweds += 'eE'
if text[-1].lower() == 'e': alloweds += '+-'
if text[-1] in '0123456789.eE+-':
# will cause problems if any in units starts with 'e' or 'E'
completes = [text + char for char in alloweds]
if not text[-1] in 'eE+-':
completes += [text + unit for unit in units]
else:
found = re.search('[^.0123456789eE+-]', text)
# will cause problems if any in units starts with 'e' or 'E'
if found:
pos = found.span()[0]
letters = text[pos:]
# can't do case-insensitive, either manually here or
# with disambiguate() because GNUreadline won't allow
# replacing e.g. "1m" with "1MHz" (wipes out the "m"
# leaving "1" for second completion, doesn't show choices)
completes = [ text[:pos] + unit + " "
for unit
in units
if unit.startswith(letters)]
else:
completes = []
return completes
### base classes
#
class RangeInt(object):
__slots__ = ['_val', '_min', '_max', '_help']
def __init__(self, value=0, min=0, max=0):
self._min = min
self._max = max
self.val = value
def __str__(self):
return '%d' % self._val
@property
def val(self):
return self._val
def set_value(self, value):
try:
if type(value) is str:
value = int(value, 16 if 'x' in value.lower() else 10)
else:
value = int(value)
assert(value >= self._min and value <= self._max)
self._val = value
except Exception as error:
raise ValueError( "\"%s\" is not %s" % (value, self.suitable()))
@val.setter
def val(self, value):
self.set_value(value)
def suitable(self):
return "decimal or hex integer in range [%d ... %d]" % (self._min,
self._max)
def complete(self, text):
return [text + digit for digit in 'x0123456789abcde']
class SpecialInt(RangeInt):
UNITS = ('unlimited', '<number>')
_slots_ = ['_val', '_special', '_min', '_max', '_specval']
def __init__(self, value=0, special='unlimited', min=0,max=0, specval=None):
self._min = min
self._max = max
self._special = special
self._specval = max if specval is None else specval
self.val = value
def __str__(self):
if self._val >= self._max:
return self._special
else:
return '%d' % self._val
def is_special(self):
return self._val >= self._specval
def special_str(self):
return self._special
@property
def val(self):
return self._val
@val.setter
def val(self, value):
if value.lower()[0] == self._special[0]:
self._val = self._specval
return
try:
RangeInt.set_value(self, value)
# value = int(value)
# assert(value >= self._min and value <= self._max)
# self._val = value
except Exception as error:
raise ValueError("\"%s\" is not %s" % (value, self.suitable()))
def suitable(self):
return "\"%s\" or integer " "in range [%d ... %d]" \
% (self._special, self._min, self._max)
def complete(self, text):
completed = []
if text and text[0].lower() == self._special[0]:
return ["%s " % self._special]
if not text:
completed = ["%s " % self._special]
return completed + RangeInt.complete(self, text)
class StringsAndValues(object):
__slots__ = ['__val', '__str', '__case', '_help']
def __init__(self, init='', case=False):
self.__case = case
self.val = init
def str(self):
return self.__str
def __str__(self):
return self.str()
@classmethod
def __getitem__(self, key):
return self.strings_and_values[key]
@classmethod
def keys(self):
return self.strings_and_values.keys()
@classmethod
def choices(self):
return '|'.join(self.strings_and_values.keys())
@property
def val(self):
return self.__val
@val.setter
def val(self, value):
if type(value) is not str:
self.set_by_val(value)
return
if value == '':
raise ValueError( "Empty value not allowed -- "
"not changing \"%s\""
% self.str() )
disambig = disambiguate(value ,
tuple(self.strings_and_values.keys()),
self.__case )
if disambig.good:
self.__str = disambig.good
self.__val = self.strings_and_values[disambig.good]
else: # can only be non-zero with poorly-constructed self.s_a_v
raise ValueError(disambig.error)
def set_by_val(self, value):
try:
string = dict(map(reversed, self.strings_and_values.items()))[value]
self.__str = string
self.__val = value
except Exception as error:
raise ValueError("%s is not valid %s value" % (value, type(self)))
def suitable(self):
return comma_or_concat(tuple(self.keys()))
def complete(self, text):
return [key + " " for key in self.keys() if key.startswith(text)]
class TimeVal(object):
# derived can't access if '__min','__max'
__slots__ = ['__value', '_error', '_min', '_max', '_help']
UNITS = tuple("y d our min s ms us μs ns".split())
def __init__(self, init, min=0.0, max=sys.float_info.max):
self._min = min
self._max = max
self._error = None
self.val = init
@staticmethod
def suffixed(value, signed='%g'):
if abs(value) < 1e-9:
return (signed + 'ps' ) % (value * 1e12)
if abs(value) < 1e-6:
return (signed + 'ns' ) % (value * 1e9)
if abs(value) < 1e-3:
return (signed + 'μs' ) % (value * 1e6)
if abs(value) < 1.0:
return (signed + 'ms' ) % (value * 1e3)
if abs(value) < 60:
return (signed + 's' ) % value
if abs(value) < 60 * 60:
return (signed + 'min') % (value / 60)
if abs(value) < 60 * 60 * 24:
return (signed + 'our' ) % (value / (60 * 60))
if abs(value) < 60 * 60 * 24 * 365:
return (signed + 'd' ) % (value / (60 * 60 * 24))
return (signed + 'y' ) % (value / (60 * 60 * 24 * 365))
@staticmethod
def str(value, error=None):
if error:
return "%s(error:%s)" % (TimeVal.suffixed(value ),
TimeVal.suffixed(error, '%+g'))
else:
return TimeVal.suffixed(value)
def __str__(self):
return self.str(self.__value, self._error)
def parse(self, text):
found = re.search('[^.0123456789eE+-]', text)
if not found:
raise ValueError("\"%s\" is not %s" % (text, self.suitable()))
value = text[:found.span()[0] ]
units = text[ found.span()[0]:]
if units != text: # number-less input
disambig = disambiguate(units, self.UNITS)
if disambig.count != 1:
raise ValueError(disambig.error)
units = disambig.good
if units == 'ms': scale = 1e-3
elif units in ('us', 'μs'): scale = 1e-6
elif units == 'ns': scale = 1e-9
elif units == 's': scale = 1.0
elif units == 'min': scale = 60.0
elif units == 'our': scale = 60.0 * 60.0
elif units == 'd': scale = 60.0 * 60.0 * 24.0
elif units == 'y': scale = 60.0 * 60.0 * 24.0 * 365.0
else: scale = 1.0
try:
scaled = scale * float(value)
assert(scaled >= self._min and scaled <= self._max)
return scaled
except Exception as error:
raise ValueError("\"%s\" is not %s" % (text, self.suitable()))
@property
def val(self):
return self.__value
@val.setter
def val(self, value):
self.__value = self.parse(value)
def suitable(self):
return "floating point number with %s suffix in range [%s ... %s]" \
% (comma_or_concat(self.UNITS),
self.str(self._min) ,
self.str(self._max) )
def complete(self, text):
return float_completer(text, self.UNITS)
class TimeFreqVal(TimeVal):
__slots__ = ['__value']
UNITS = tuple("y d our min s ms us μs ns Hz kHz MHz GHz".split())
def __init__(self, init, min= 0, max=sys.float_info.max):
super().__init__(init, min, max)
@staticmethod
def suffixed(value, signed='%g'):
if value == 0.0:
return '0Hz(approx)'
if abs(value) <= 1e-12:
return (signed + 'THz' ) % (1e-12 / value)
if abs(value) <= 1e-9:
return (signed + 'GHz' ) % (1e-9 / value)
if abs(value) <= 1e-6:
return (signed + 'MHz' ) % (1e-6 / value)
if abs(value) <= 1e-3:
return (signed + 'kHz' ) % (1e-3 / value)
if abs(value) > 1e10:
return (signed + 'pHz' ) % (1e12 / value)
if abs(value) > 1e7:
return (signed + 'nHz' ) % (1e9 / value)
if abs(value) > 1e4:
return (signed + 'μHz' ) % (1e6 / value)
if abs(value) > 1e1:
return (signed + 'milliHz') % (1e3 / value)
return (signed + 'Hz' ) % (1.0 / value)
@staticmethod
def str(value, error=None):
if error:
if abs(error) > 1e-18: # check for underflow, causes divide by zero
hz_error = 1.0 / (1.0 / value - 1.0 / (value - error))
else:
hz_error = 0.0
return "%s=%s(error:%s,%s)" \
% (TimeFreqVal.suffixed( value ),
TimeVal .suffixed( value ),
TimeFreqVal.suffixed(hz_error, '%+g'),
TimeVal .suffixed( error, '%+g'))
else:
return '%s=%s' % (TimeFreqVal.suffixed(value),
TimeVal .suffixed(value))
def __str__(self):
return self.str(self.__value, self._error)
def parse(self, text):
found = re.search('[^.0123456789eE+-]', text)
if not found:
raise ValueError("\"%s\" is not %s" % (text, self.suitable()))
value = text[:found.span()[0] ]
units = text[ found.span()[0]:]
if units != text: # number-less input
disambig = disambiguate(units, self.UNITS)
if disambig.count != 1:
raise ValueError(disambig.error)
units = disambig.good
if units == 'kHz': scale = 1e-3
elif units == 'MHz': scale = 1e-6
elif units == 'GHz': scale = 1e-9
elif units == 'Hz' : scale = 1.0
else: scale = None
try:
if scale:
scaled = scale / float(value)
assert(scaled >= self._min and scaled <= self._max)
return scaled
else:
return TimeVal.parse(self, text)
except Exception as error:
raise ValueError("\"%s\" is not %s" % (text, self.suitable()))
@property
def val(self):
return self.__value
@val.setter
def val(self, value=''):
self.__value = self.parse(value)
def suitable(self):
return "floating point number with %s suffix in range [%s ... %s]" \
% (comma_or_concat(self.UNITS),
self.str(self._min) ,
self.str(self._max) )
def complete(self, text):
return float_completer(text, self.UNITS)
class TimePcntVal(TimeVal):
__slots__ = ['__value', '__parnt', '__prcnt', '__time', '_help']
UNITS = tuple("% s ms us μs ns Hz kHz MHz GHz".split())
def __init__(self, init='50%', parnt=None):
self.__parnt = parnt
super().__init__(init, 0, 0xffff)
if parnt: parnt.dependent(self)
self.val = init
@staticmethod
def str(value, prcnt=None, error=None):
if prcnt:
return '%g%%=%s' % (prcnt * 100.0, TimeVal.str(value, error))
else:
return TimeVal.str(value, error)
def __str__(self):
return self.str(self.as_time(self.__value), self.__prcnt, self._error)
def as_time(self, value):
return (value + 1) * (self.__parnt.psc() + 1) / CPU_HZ
def check_set_val(self, time):
value = int(round(time * CPU_HZ / (self.__parnt.psc() + 1))) - 1
if not 0 <= value <= self.__parnt.arr():
sys.stderr.write( "%s not in range [%s ... %s] possible with "
"current timer prescaler\n"
% (TimeVal.str(time ),
TimeVal.str(self.as_time(0) ),
TimeVal.str(self.as_time(self.__parnt.arr()))))
self.__value = 0 if value < 0 else self.__parnt.arr()
sys.stderr.write( "Setting to %s (was %s)\n"
% (self, TimeVal.str(self.__time)))
self.__time = self.as_time(self.__value)
else:
self.__value = value
def compute_error(self):
if self.__prcnt:
self._error = self.as_time(self.__parnt.arr() * self.__prcnt) \
- self.as_time(self.__value)
else:
self._error = self.__time - self.as_time(self.__value)
def update(self, time):
if self.__prcnt:
self.__value = int(round(self.__prcnt * self.__parnt.arr()))
else:
self.check_set_val(self.__time)
self.compute_error()
@property
def val(self):
return self.__value
@val.setter
def val(self, input):
if type(input) is str and input.endswith('%'):
percent = 0.01 * float(input[:-1])
if not 0.0 <= percent <=1.0:
raise ValueError("\"%s\" not in range [0%% ... 100%%]" % input)
self.__prcnt = percent
self.__value = int(round(self.__prcnt * self.__parnt.arr()))
self.__time = self.as_time(self.__value)
else:
time = TimeVal.parse(self, input) # can raise ValueError
self.__prcnt = None
self.__time = time
self.check_set_val(time) # can clamp
self.compute_error()
def suitable(self):
return TimeFreqVal.suitable(self) \
+ " or <xxx>% (xxx floating point number in range [0 ... 100])"
class TimeSpecialVal(TimeVal):
__slots__ = ['__value', '_help', '_special', '_help']
def __init__(self, init, min = 1, max = 0xffffffff, special='unlimited'):
self._special = special
super().__init__(init, min / CPU_HZ , max / CPU_HZ)
self.val = init
def __str__(self):
if self.__value == 0: return self._special
else: return self.str(self.as_float(), self._error)
def as_float(self):
return self.__value / CPU_HZ
@property
def val(self):
return self.__value
@val.setter
def val(self, value):
if not value:
raise ValueError("Bad time//special value (blank/empty)")
if value.lower()[0] == self._special.lower()[0]:
self.__value = 0
self._error = None
else:
parsed = self.parse(value) # can raise exception
self.__value = int(round(parsed * CPU_HZ)) # & 0xffffffff
self._error = self.as_float() - parsed
def suitable(self):
return "%s, or \"%s\"" % (TimeVal.suitable(self),
self._special )
def complete(self, text):
special = []
if text and text[0].lower() == self._special.lower()[0]:
return [self._special + " "]
if not text:
special = [self._special + " "]
return special + TimeVal.complete(self, text)
class TimeFreqSpecialVal(TimeFreqVal):
__slots__ = ['__value', '_help', '_special', '_help']
def __init__(self, init, min = 1, max = 0xffffffff, special='unlimited'):
self._special = special
super().__init__(init, min / CPU_HZ , max / CPU_HZ)
self.val = init
def __str__(self):
if self.__value == 0: return self._special
else: return self.str(self.as_float(), self._error)
def as_float(self):
return self.__value / CPU_HZ
@property
def val(self):
return self.__value
@val.setter
def val(self, value):
if not value:
raise ValueError("Bad time/freq/special value (blank/empty)")
if value.lower()[0] == self._special.lower()[0]:
self.__value = 0
self._error = None
else:
time = self.parse(value) # can raise exception
self.__value = int(round(time * CPU_HZ)) # & 0xffffffff
self._error = self.as_float() - time
def suitable(self):
return "%s, or \"%s\"" % (TimeFreqVal.suitable(self),
self._special )
def complete(self, text):
special = []
if text and text[0].lower() == self._special.lower()[0]:
return [self._special + " "]
if not text:
special = [self._special + " "]
return special + TimeFreqVal.complete(self, text)
class TimeFreqPscArrVal(TimeFreqVal):
__slots__ = ['__psc', '__arr', '__dependents', '_help']
def __init__(self, init, min = 1.0 / CPU_HZ, max = 0xffffffff / CPU_HZ):
self.__dependents = [] # must be first for super()->update_dependents()
super().__init__(init, min, max)
self.val = init
def __str__(self):
return self.str(self.as_float(), self._error)
def as_float(self):
return (self.__psc + 1) * (self.__arr + 1) / CPU_HZ
def psc(self):
return self.__psc
def arr(self): return self.__arr
@property
def val(self):
return (self.__psc, self.__arr)
@val.setter
def val(self, value=''):
time = TimeFreqVal.parse(self, value)
psc = int(math.ceil(time * CPU_HZ / (1<<16)))
self.__arr = int(round (time * CPU_HZ / psc )) - 1
self.__psc = psc - 1
self._error = self.as_float() - time
self.update_dependents(time)
def dependent(self, dependent):
self.__dependents.append(dependent)
def update_dependents(self, value):
for dependent in self.__dependents:
dependent.update(value)
class Duration(TimeVal):
UNITS = tuple("y d our min s ms us μs ns".split())
__slots__ = ['__value', '__tick', '__arr', '_help']
def __init__(self, init, tick=(1<<16)/CPU_HZ, min=1, max=0xffff, arr=0):
self.__tick = tick
self.__arr = arr
super().__init__(init, min * tick, max * tick)
self.val = init
def __str__(self):
if self.enabled():
return self.str(self.as_float(), self._error)