-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathapi_shared.py
More file actions
1115 lines (993 loc) · 36.9 KB
/
api_shared.py
File metadata and controls
1115 lines (993 loc) · 36.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
# Copyright 2026 OpenC3, Inc.
# All Rights Reserved.
#
# 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 LICENSE.md for more details.
# This file may also be used under the terms of a commercial license
# if purchased from OpenC3, Inc.
import json
import sys
import time
import traceback
from contextlib import contextmanager
import openc3.script
from openc3.environment import OPENC3_SCOPE
from openc3.utilities.extract import (
extract_fields_from_check_text,
extract_fields_from_tlm_text,
extract_operator_and_operand_from_comparison,
)
from .exceptions import CheckError
DEFAULT_TLM_POLLING_RATE = 0.25
# NOTE: The formatting applied throughout uses :.Xf meaning X decimal points
# This allows extremely small wait times to simply be displayed 0.000.
# Without the 'f' :.X means display X significant figures
def check(*args, type="CONVERTED", scope="DEFAULT"):
"""Check the converted value of a telmetry item against a condition
Always print the value of the telemetry item to STDOUT
If the condition check fails, raise an error
Supports two signatures:
check(target_name, packet_name, item_name, comparison_to_eval)
or
check('target_name packet_name item_name > 1')
"""
return _check(*args, type=type, scope=scope)
def check_raw(*args, scope="DEFAULT"):
"""Check the raw value of a telmetry item against a condition
Always print the value of the telemetry item to STDOUT
If the condition check fails, raise an error
Supports two signatures:
check(target_name, packet_name, item_name, comparison_to_eval)
or
check('target_name packet_name item_name > 1')
"""
return _check(*args, type="RAW", scope=scope)
def check_formatted(*args, scope="DEFAULT"):
"""Check the formatted value of a telmetry item against a condition
Always print the value of the telemetry item to STDOUT
If the condition check fails, raise an error
Supports two signatures:
check(target_name, packet_name, item_name, comparison_to_eval)
or
check('target_name packet_name item_name > 1')
"""
return _check(*args, type="FORMATTED", scope=scope)
# DEPRECATED
def check_with_units(*args, scope="DEFAULT"):
"""Check the formatted with units value of a telmetry item against a condition
Always print the value of the telemetry item to STDOUT
If the condition check fails, raise an error
Supports two signatures:
check(target_name, packet_name, item_name, comparison_to_eval)
or
check('target_name packet_name item_name > 1')
"""
return _check(*args, type="FORMATTED", scope=scope)
def check_exception(method_name, *args, **kwargs):
"""Executes the passed method and expects an exception to be raised.
Raises a CheckError if an Exception is not raised.
Usage: check_exception(method_name, method_params}"""
try:
method = method_name
orig_kwargs = kwargs.copy()
if "scope" not in kwargs:
kwargs["scope"] = OPENC3_SCOPE
getattr(sys.modules[__name__], method_name)(*args, **kwargs)
method = f"{method_name}({', '.join(args)}"
if orig_kwargs:
method += f", {orig_kwargs}"
method += ")"
except Exception:
print(f"CHECK: {method} raised {traceback.format_exc()}")
else:
raise CheckError(f"{method} should have raised an exception but did not.")
def check_tolerance(*args, type="CONVERTED", scope=OPENC3_SCOPE):
"""Check the converted value of a telmetry item against an expected value with a tolerance
Always print the value of the telemetry item to STDOUT
If the condition check fails, raise an error
Supports two signatures:
check_tolerance(target_name, packet_name, item_name, expected_value, tolerance)
or
check_tolerance('target_name packet_name item_name', expected_value, tolerance)
"""
if type not in ["RAW", "CONVERTED"]:
raise RuntimeError(f"Invalid type '{type}' for check_tolerance")
(
target_name,
packet_name,
item_name,
expected_value,
tolerance,
) = _check_tolerance_process_args(args)
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=type, scope=scope)
if isinstance(value, list):
expected_value, tolerance = _array_tolerance_process_args(
len(value), expected_value, tolerance, "check_tolerance"
)
message = ""
all_checks_ok = True
for i in range(len(value)):
range_bottom = expected_value[i] - tolerance[i]
range_top = expected_value[i] + tolerance[i]
check_str = f"CHECK: {_upcase(target_name, packet_name, item_name)}[{i}]"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value[i]}"
if value[i] >= range_bottom and value[i] <= range_top:
message += f"{check_str} was within {range_str}\n"
else:
message += f"{check_str} failed to be within {range_str}\n"
all_checks_ok = False
if all_checks_ok:
print(message)
else:
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
else:
range_bottom = expected_value - tolerance
range_top = expected_value + tolerance
check_str = f"CHECK: {_upcase(target_name, packet_name, item_name)}"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value}"
if value >= range_bottom and value <= range_top:
print(f"{check_str} was within {range_str}")
else:
message = f"{check_str} failed to be within {range_str}"
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
def check_expression(exp_to_eval, globals=None, locals=None):
"""Check to see if an expression is true without waiting. If the expression
is not true, the script will pause."""
success = _openc3_script_wait_expression(exp_to_eval, 0, DEFAULT_TLM_POLLING_RATE, globals, locals)
if success:
print(f"CHECK: {exp_to_eval} is TRUE")
else:
message = f"CHECK: {exp_to_eval} is FALSE"
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
def wait(*args, type="CONVERTED", quiet=False, scope=OPENC3_SCOPE):
"""Wait on an expression to be true. On a timeout, the script will continue.
Supports multiple signatures:
wait(time)
wait('target_name packet_name item_name > 1', timeout, polling_rate)
wait('target_name', 'packet_name', 'item_name', comparison_to_eval, timeout, polling_rate)
"""
time_diff = None
match len(args):
# wait() # indefinitely until they click Go
case 0:
start_time = time.time()
openc3_script_sleep()
time_diff = time.time() - start_time
if not quiet:
print(f"WAIT: Indefinite for actual time of {time_diff:.3f} seconds")
return time_diff
# wait(5) # absolute wait time
case 1:
try:
value = float(args[0])
except ValueError:
raise RuntimeError("Non-numeric wait time specified") from None
start_time = time.time()
openc3_script_sleep(value)
time_diff = time.time() - start_time
if not quiet:
print(f"WAIT: {value} seconds with actual time of {time_diff:.3f} seconds")
return time_diff
# wait('target_name packet_name item_name > 1', timeout, polling_rate) # polling_rate is optional
case 2 | 3:
(
target_name,
packet_name,
item_name,
comparison_to_eval,
) = extract_fields_from_check_text(args[0])
timeout = args[1]
if len(args) == 3:
polling_rate = args[2]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
return _execute_wait(
target_name,
packet_name,
item_name,
type,
comparison_to_eval,
timeout,
polling_rate,
quiet,
scope,
)
# wait('target_name', 'packet_name', 'item_name', comparison_to_eval, timeout, polling_rate) # polling_rate is optional
case 5 | 6:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
comparison_to_eval = args[3]
timeout = args[4]
if len(args) == 6:
polling_rate = args[5]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
return _execute_wait(
target_name,
packet_name,
item_name,
type,
comparison_to_eval,
timeout,
polling_rate,
quiet,
scope,
)
case _:
# Invalid number of arguments
raise RuntimeError(f"ERROR: Invalid number of arguments ({len(args)}) passed to wait()")
def wait_tolerance(*args, type="CONVERTED", quiet=False, scope=OPENC3_SCOPE):
"""Wait on an expression to be true. On a timeout, the script will continue.
Supports multiple signatures:
wait_tolerance('target_name packet_name item_name', expected_value, tolerance, timeout, polling_rate)
wait_tolerance('target_name', 'packet_name', 'item_name', expected_value, tolerance, timeout, polling_rate)
"""
if type not in ["RAW", "CONVERTED"]:
raise RuntimeError(f"Invalid type '{type}' for wait_tolerance")
(
target_name,
packet_name,
item_name,
expected_value,
tolerance,
timeout,
polling_rate,
) = _wait_tolerance_process_args(args, "wait_tolerance")
start_time = time.time()
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=type, scope=scope)
if isinstance(value, list):
expected_value, tolerance = _array_tolerance_process_args(
len(value), expected_value, tolerance, "wait_tolerance"
)
success, value = _openc3_script_wait_array_tolerance(
len(value),
target_name,
packet_name,
item_name,
type,
expected_value,
tolerance,
timeout,
polling_rate,
)
time_diff = time.time() - start_time
message = ""
for i in range(0, len(value)):
range_bottom = expected_value[i] - tolerance[i]
range_top = expected_value[i] + tolerance[i]
check_str = f"WAIT: {_upcase(target_name, packet_name, item_name)}[{i}]"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value[i]} after waiting {time_diff:.3f} seconds"
if value[i] >= range_bottom and value[i] <= range_top:
message += f"{check_str} was within {range_str}\n"
else:
message += f"{check_str} failed to be within {range_str}\n"
if not quiet:
if success:
print(message)
else:
print(f"WARN: {message}")
else:
success, value = _openc3_script_wait_tolerance(
target_name,
packet_name,
item_name,
type,
expected_value,
tolerance,
timeout,
polling_rate,
)
time_diff = time.time() - start_time
range_bottom = expected_value - tolerance
range_top = expected_value + tolerance
wait_str = f"WAIT: {_upcase(target_name, packet_name, item_name)}"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value} after waiting {time_diff:.3f} seconds"
if not quiet:
if success:
print(f"{wait_str} was within {range_str}")
else:
print(f"WARN: {wait_str} failed to be within {range_str}")
return success
def wait_expression(
exp_to_eval,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
globals=None,
locals=None,
quiet=False,
):
"""Wait on a custom expression to be true"""
start_time = time.time()
success = _openc3_script_wait_expression(exp_to_eval, timeout, polling_rate, globals, locals)
time_diff = time.time() - start_time
if not quiet:
if success:
print(f"WAIT: {exp_to_eval} is TRUE after waiting {time_diff:.3f} seconds")
else:
print(f"WARN: WAIT: {exp_to_eval} is FALSE after waiting {time_diff:.3f} seconds")
return success
def wait_check(*args, type="CONVERTED", scope=OPENC3_SCOPE):
"""Wait for the converted value of a telmetry item against a condition or for a timeout
and then check against the condition
Supports two signatures:
wait_check(target_name, packet_name, item_name, comparison_to_eval, timeout, polling_rate)
or
wait_check('target_name packet_name item_name > 1', timeout, polling_rate)"""
(
target_name,
packet_name,
item_name,
comparison_to_eval,
timeout,
polling_rate,
) = _wait_check_process_args(args)
start_time = time.time()
success, value = _openc3_script_wait_value(
target_name,
packet_name,
item_name,
type,
comparison_to_eval,
timeout,
polling_rate,
)
if isinstance(value, str):
value = f"'{value}'" # Show user the check against a quoted string
time_diff = time.time() - start_time
check_str = f"CHECK: {_upcase(target_name, packet_name, item_name)}"
if comparison_to_eval:
check_str += f" {comparison_to_eval}"
with_value_str = f"with value == {value} after waiting {time_diff:.3f} seconds"
if success:
print(f"{check_str} success {with_value_str}")
else:
message = f"{check_str} failed {with_value_str}"
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
return time_diff
def wait_check_tolerance(*args, type="CONVERTED", scope=OPENC3_SCOPE):
"""Wait for the value of a telmetry item to be within a tolerance of a value
and then check against the condition.
Supports two signatures:
wait_check_tolerance('target_name packet_name item_name', expected_value, tolerance, timeout, polling_rate)
or
wait_check_tolerance('target_name', 'packet_name', 'item_name', expected_value, tolerance, timeout, polling_rate)
"""
if type not in ["RAW", "CONVERTED"]:
raise RuntimeError(f"Invalid type '{type}' for wait_check_tolerance")
(
target_name,
packet_name,
item_name,
expected_value,
tolerance,
timeout,
polling_rate,
) = _wait_tolerance_process_args(args, "wait_check_tolerance")
start_time = time.time()
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=type, scope=scope)
if isinstance(value, list):
expected_value, tolerance = _array_tolerance_process_args(
len(value), expected_value, tolerance, "wait_check_tolerance"
)
success, value = _openc3_script_wait_array_tolerance(
len(value),
target_name,
packet_name,
item_name,
type,
expected_value,
tolerance,
timeout,
polling_rate,
)
time_diff = time.time() - start_time
message = ""
for i in range(0, len(value)):
range_bottom = expected_value[i] - tolerance[i]
range_top = expected_value[i] + tolerance[i]
check_str = f"CHECK: {_upcase(target_name, packet_name, item_name)}[{i}]"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value[i]} after waiting {time_diff:.3f} seconds"
if value[i] >= range_bottom and value[i] <= range_top:
message += f"{check_str} was within {range_str}\n"
else:
message += f"{check_str} failed to be within {range_str}\n"
if success:
print(message)
else:
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
else:
success, value = _openc3_script_wait_tolerance(
target_name,
packet_name,
item_name,
type,
expected_value,
tolerance,
timeout,
polling_rate,
scope,
)
time_diff = time.time() - start_time
range_bottom = expected_value - tolerance
range_top = expected_value + tolerance
check_str = f"CHECK: {_upcase(target_name, packet_name, item_name)}"
range_str = f"range {_frange(range_bottom)} to {_frange(range_top)} with value == {value} after waiting {time_diff:.3f} seconds"
if success:
print(f"{check_str} was within {range_str}")
else:
message = f"{check_str} failed to be within {range_str}"
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
return time_diff
def wait_check_expression(
exp_to_eval,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
globals=None,
locals=None,
):
"""Wait on an expression to be true. On a timeout, the script will pause"""
start_time = time.time()
success = _openc3_script_wait_expression(exp_to_eval, timeout, polling_rate, globals, locals)
time_diff = time.time() - start_time
if success:
print(f"CHECK: {exp_to_eval} is TRUE after waiting {time_diff:.3f} seconds")
else:
message = f"CHECK: {exp_to_eval} is FALSE after waiting {time_diff:.3f} seconds"
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
return time_diff
def wait_packet(
target_name,
packet_name,
num_packets,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
quiet=False,
scope=OPENC3_SCOPE,
):
success, _ = _wait_packet(
False,
target_name,
packet_name,
num_packets,
timeout,
polling_rate,
quiet,
scope,
)
return success
def wait_check_packet(
target_name,
packet_name,
num_packets,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
quiet=False,
scope=OPENC3_SCOPE,
):
"""Wait for a telemetry packet to be received a certain number of times or timeout and raise an error"""
_, time_diff = _wait_packet(True, target_name, packet_name, num_packets, timeout, polling_rate, quiet, scope)
return time_diff
@contextmanager
def disable_instrumentation():
if openc3.script.RUNNING_SCRIPT:
openc3.script.RUNNING_SCRIPT.instance.use_instrumentation = False
try:
yield
finally:
openc3.script.RUNNING_SCRIPT.instance.use_instrumentation = True
else:
yield
def set_line_delay(delay):
if openc3.script.RUNNING_SCRIPT and delay >= 0.0:
openc3.script.RUNNING_SCRIPT.line_delay = delay
print(f"set_line_delay({delay})")
def get_line_delay():
if openc3.script.RUNNING_SCRIPT:
return openc3.script.RUNNING_SCRIPT.line_delay
def set_max_output(characters):
if openc3.script.RUNNING_SCRIPT:
openc3.script.RUNNING_SCRIPT.max_output_characters = int(characters)
def get_max_output():
if openc3.script.RUNNING_SCRIPT:
return openc3.script.RUNNING_SCRIPT.max_output_characters
###########################################################################
# Scripts Outside of ScriptRunner Support
# ScriptRunner overrides these methods to work in the OpenC3 cluster
# They are only here to allow for scripts to have a chance to work
# unaltered outside of the cluster
###########################################################################
# Exec a procedure
def start(procedure_name):
with open(procedure_name) as f:
exec(f.read())
def goto(line_no_or_procedure_name, line_no=None):
raise RuntimeError("goto is not supported outside of ScriptRunner")
# Require an additional python file
def load_utility(procedure_name):
raise RuntimeError("load_utility not supported outside of Script Runner")
###########################################################################
# Private implementation details
###########################################################################
def openc3_script_sleep(sleep_time=None):
if sleep_time is not None:
time.sleep(float(sleep_time))
else:
input("Press any key to continue...")
def _upcase(target_name, packet_name, item_name):
"""Creates a string with the parameters upcased"""
return f"{target_name.upper()} {packet_name.upper()} {item_name.upper()}"
def _check(*args, type="CONVERTED", scope=OPENC3_SCOPE):
"""Implementation of the various check commands. It yields back to the
caller to allow the return of the value through various telemetry calls.
This method should not be called directly by application code."""
target_name, packet_name, item_name, comparison_to_eval = _check_process_args(args, "check")
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=type, scope=scope)
if comparison_to_eval:
return _check_eval(target_name, packet_name, item_name, comparison_to_eval, value)
else:
print(f"CHECK: {_upcase(target_name, packet_name, item_name)} == {value}")
def _check_process_args(args, method_name):
match len(args):
case 1:
(
target_name,
packet_name,
item_name,
comparison_to_eval,
) = extract_fields_from_check_text(args[0])
case 3:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
comparison_to_eval = None
case 4:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
comparison_to_eval = args[3]
case _:
# Invalid number of arguments
raise RuntimeError(f"ERROR: Invalid number of arguments ({len(args)}) passed to {method_name}()")
if comparison_to_eval and not comparison_to_eval.isascii():
raise RuntimeError(f"ERROR: Invalid comparison to non-ascii value: {comparison_to_eval}")
return target_name, packet_name, item_name, comparison_to_eval
def _check_tolerance_process_args(args):
length = len(args)
if length == 3:
target_name, packet_name, item_name = extract_fields_from_tlm_text(args[0])
expected_value = args[1]
if isinstance(args[2], list):
tolerance = [abs(x) for x in args[2]]
else:
tolerance = abs(args[2])
elif length == 5:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
expected_value = args[3]
if isinstance(args[4], list):
tolerance = [abs(x) for x in args[4]]
else:
tolerance = abs(args[4])
else:
# Invalid number of arguments
raise RuntimeError(f"ERROR: Invalid number of arguments ({length}) passed to check_tolerance()")
return target_name, packet_name, item_name, expected_value, tolerance
def _wait_packet(
check,
target_name,
packet_name,
num_packets,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
quiet=False,
scope=OPENC3_SCOPE,
):
"""Wait for a telemetry packet to be received a certain number of times or timeout"""
if check:
type = "CHECK"
else:
type = "WAIT"
initial_count = openc3.script.API_SERVER.tlm(target_name, packet_name, "RECEIVED_COUNT", scope=scope)
# If the packet has not been received the initial_count could be None
if initial_count is None:
initial_count = 0
start_time = time.time()
success, value = _openc3_script_wait_value(
target_name,
packet_name,
"RECEIVED_COUNT",
"CONVERTED",
f">= {initial_count + num_packets}",
timeout,
polling_rate,
scope,
)
# If the packet has not been received the value could be None
if not value:
value = 0
time_diff = time.time() - start_time
if success:
if not quiet:
print(
f"{type}: {target_name.upper()} {packet_name.upper()} received {value - initial_count} times after waiting {time_diff:.3f} seconds"
)
else:
message = f"{type}: {target_name.upper()} {packet_name.upper()} expected to be received {num_packets} times but only received {value - initial_count} times after waiting {time_diff:.3f} seconds"
if check:
if openc3.script.DISCONNECT:
print(f"ERROR: {message}")
else:
raise CheckError(message)
elif not quiet:
print(f"WARN: {message}")
return success, time_diff
def _execute_wait(
target_name,
packet_name,
item_name,
value_type,
comparison_to_eval,
timeout,
polling_rate,
quiet,
scope,
):
start_time = time.time()
success, value = _openc3_script_wait_value(
target_name,
packet_name,
item_name,
value_type,
comparison_to_eval,
timeout,
polling_rate,
scope,
)
if isinstance(value, str):
value = f"'{value}'" # Show user the check against a quoted string
time_diff = time.time() - start_time
wait_str = f"WAIT: {_upcase(target_name, packet_name, item_name)} {comparison_to_eval}"
value_str = f"with value == {value} after waiting {time_diff:.3f} seconds"
if not quiet:
if success:
print(f"{wait_str} success {value_str}")
else:
print(f"WARN: {wait_str} failed {value_str}")
return success
def _wait_tolerance_process_args(args, function_name):
length = len(args)
if length == 4 or length == 5:
target_name, packet_name, item_name = extract_fields_from_tlm_text(args[0])
expected_value = args[1]
if isinstance(args[2], list):
tolerance = [abs(x) for x in args[2]]
else:
tolerance = abs(args[2])
timeout = args[3]
if length == 5:
polling_rate = args[4]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
elif length == 6 or length == 7:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
expected_value = args[3]
if isinstance(args[4], list):
tolerance = [abs(x) for x in args[4]]
else:
tolerance = abs(args[4])
timeout = args[5]
if length == 7:
polling_rate = args[6]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
else:
# Invalid number of arguments
raise RuntimeError(f"ERROR: Invalid number of arguments ({length}) passed to {function_name}()")
return (
target_name,
packet_name,
item_name,
expected_value,
tolerance,
timeout,
polling_rate,
)
def _array_tolerance_process_args(array_size, expected_value, tolerance, function_name):
"""
When testing an array with a tolerance, the expected value and tolerance
can both be supplied as either an array or a single value. If a single
value is passed in, that value will be used for all array elements.
"""
if isinstance(expected_value, list):
if array_size != len(expected_value):
raise RuntimeError(f"ERROR: Invalid array size for expected_value passed to {function_name}()")
else:
expected_value = [expected_value] * array_size
if isinstance(tolerance, list):
if array_size != len(tolerance):
raise RuntimeError(f"ERROR: Invalid array size for tolerance passed to {function_name}()")
else:
tolerance = [tolerance] * array_size
return expected_value, tolerance
def _wait_check_process_args(args):
length = len(args)
if length == 2 or length == 3:
(
target_name,
packet_name,
item_name,
comparison_to_eval,
) = extract_fields_from_check_text(args[0])
timeout = args[1]
if length == 3:
polling_rate = args[2]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
elif length == 5 or length == 6:
target_name = args[0]
packet_name = args[1]
item_name = args[2]
comparison_to_eval = args[3]
timeout = args[4]
if length == 6:
polling_rate = args[5]
else:
polling_rate = DEFAULT_TLM_POLLING_RATE
else:
# Invalid number of arguments
raise RuntimeError(f"ERROR: Invalid number of arguments ({len(args)}) passed to wait_check()")
return (
target_name,
packet_name,
item_name,
comparison_to_eval,
timeout,
polling_rate,
)
def _openc3_script_wait(
target_name,
packet_name,
item_name,
value_type,
timeout,
polling_rate,
exp_to_eval,
scope,
):
value = None
end_time = time.time() + timeout
if exp_to_eval and not exp_to_eval.isascii():
raise RuntimeError("ERROR: Invalid comparison to non-ascii value")
try:
while True:
work_start = time.time()
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=value_type, scope=scope)
try:
if eval(exp_to_eval):
return True, value
# We get TypeError when trying to eval None >= 0 (for example)
# In this case we just continue and see if eventually we get a good value from tlm()
except TypeError:
pass
if time.time() >= end_time:
break
delta = time.time() - work_start
sleep_time = polling_rate - delta
end_delta = end_time - time.time()
if end_delta < sleep_time:
sleep_time = end_delta
if sleep_time < 0:
sleep_time = 0
canceled = openc3_script_sleep(sleep_time)
if canceled:
value = openc3.script.API_SERVER.tlm(target_name, packet_name, item_name, type=value_type, scope=scope)
try:
if eval(exp_to_eval):
return True, value
else:
return False, value
# We get TypeError when trying to eval None >= 0 (for example)
except TypeError:
return False, value
except NameError as error:
parts = error.args[0].split("'")
new_error = NameError(f"Uninitialized constant {parts[1]}. Did you mean '{parts[1]}' as a string?")
raise new_error from error
return False, value
# Wait for a converted telemetry item to pass a comparison
def _openc3_script_wait_value(
target_name,
packet_name,
item_name,
value_type,
comparison_to_eval,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
scope=OPENC3_SCOPE,
):
if comparison_to_eval:
exp_to_eval = "value " + comparison_to_eval
else:
exp_to_eval = None
return _openc3_script_wait(
target_name,
packet_name,
item_name,
value_type,
timeout,
polling_rate,
exp_to_eval,
scope,
)
def _openc3_script_wait_tolerance(
target_name,
packet_name,
item_name,
value_type,
expected_value,
tolerance,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
scope=OPENC3_SCOPE,
):
exp_to_eval = f"(value >= ({expected_value} - {abs(tolerance)}) and value <= ({expected_value} + {abs(tolerance)}))"
return _openc3_script_wait(
target_name,
packet_name,
item_name,
value_type,
timeout,
polling_rate,
exp_to_eval,
scope,
)
def _openc3_script_wait_array_tolerance(
array_size,
target_name,
packet_name,
item_name,
value_type,
expected_value,
tolerance,
timeout,
polling_rate=DEFAULT_TLM_POLLING_RATE,
scope=OPENC3_SCOPE,
):
statements = []
for i in range(array_size):
statements.append(
f"(value[{i}] >= ({expected_value[i]} - {abs(tolerance[i])}) and value[{i}] <= ({expected_value[i]} + {abs(tolerance[i])}))"
)
exp_to_eval = " and ".join(statements)
return _openc3_script_wait(
target_name,
packet_name,
item_name,
value_type,
timeout,
polling_rate,
exp_to_eval,