Skip to content
Navigation Menu
{{ message }}
forked from LC-Linkous/tinySA_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinySA_python.py
More file actions
2262 lines (1862 loc) · 82.1 KB
/
Copy pathtinySA_python.py
File metadata and controls
2262 lines (1862 loc) · 82.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python3
##------------------------------------------------------------------------------------------------\
# tinySA_python
# './tinySA_python.py'
# UNOFFICIAL Python API based on the tinySA official documentation at https://www.tinysa.org/wiki/
#
# references:
# https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands (NOTE: backwards compat not tested!)
# http://athome.kaashoek.com/tinySA/python/tinySA.py (existing library with some examples)
#
#
#
# Author(s): Lauren Linkous
# Last update: June 8, 2025
##--------------------------------------------------------------------------------------------------\
import serial
import serial.tools.list_ports # COM search method wants full path
import numpy as np
import re
try:
from src.device_config.device_config import deviceConfig
except:
from device_config.device_config import deviceConfig
class tinySA():
def __init__(self, parent=None):
# serial port
self.ser = None
# user device class (to account for custom settings)
self.dev = deviceConfig #TODO, finish this class and integrate
# message feedback
self.verboseEnabled = False
self.returnErrorByte = False
# VARS BELOW HERE will be largely replaced with device class config calls
# # this will allow for user settings and device presets
# other overrides
self.ultraEnabled = False
self.abortEnabled = False
self.harmonicEnabled = False
#select device vars - hardcoding for the Ultra for now
# device params
self.maxPoints = 450
# spectrum analyzer
self.minSADeviceFreq = 100e3 #100 kHz
self.maxSADeviceFreq = 11e9 #5.3 GHz for normal operation, but 12 GHz for edge of harmonics
# signal generator
self.minSGDeviceFreq = 100e3 #100 kHz
self.maxSGDeviceFreq = 960e6 #960 MHz
# battery
self.maxDeviceBattery = 4095
# screen
self.screenWidth = 480
self.screenHeight = 320
######################################################################
# Error and information printout
# set/get_verbose() - set how detailed the error printouts are
# print_message() - deal with the bool in one place
######################################################################
def set_verbose(self, verbose=False):
self.verboseEnabled = verbose
def get_verbose(self):
return self.verboseEnabled
def print_message(self, msg):
if self.verboseEnabled == True:
print(msg)
######################################################################
# Explicit error return
# set_error_byte_return() - set if explicit b'ERROR' is returned
# get_error_byte_return() - get the return mode True/False
# error_byte_return() - return 'ERROR' message or empty.
######################################################################
def set_error_byte_return(self, errByte=False):
self.returnErrorByte = errByte
def get_error_byte_return(self):
return self.returnErrorByte
def error_byte_return(self):
if self.returnErrorByte == True:
return bytearray(b'ERROR')
else:
return bytearray(b'') # the default
######################################################################
# Set Device Params
# Library specific functions. These set the boundaries & features for
# error checking in the library
#
# WARNING: these DO NOT change the settings on the DEVICE. just the library.
######################################################################
def select_existing_device(self, tinySAModel):
# uses pre-set config files.
# tinySAModel var must be one of the following:
# "BASIC", "ZS405", "ZS406", "ZS407"
try:
noErrors = self.dev.select_preset_model(tinySAModel)
if noErrors == False:
print("ERROR: device configuration unable to be set.This feature is underdevelopment")
return
# set variables from device configs.
# these are placeholders tes for now
# device params
self.maxPoints = 450
# spectrum analyzer
self.minSADeviceFreq = 100e3 #100 kHz
self.maxSADeviceFreq = 12e9 #5.3 GHz for normal operation, but 12 GHz for edge of harmonics
# signal generator
self.minSGDeviceFreq = 100e3 #100 kHz
self.maxSGDeviceFreq = 960e6 #960 MHz
# battery
self.maxDeviceBattery = 4095
# screen
self.screenWidth = 480
self.screenHeight = 320
except:
print("ERROR: device configuration unable to be set.This feature is underdevelopment")
def load_custom_config(self, configFile):
# TODO: for loading modified or other devices working on the same firmware
pass
######################################################################
# Direct overrides
# These are used during DEBUG or when device state/model is already known
# Not recommended unless you are sure of the device state
# and which settings each device has
# WARNING: these DO NOT change the settings on the DEVICE. just the library.
######################################################################
# error check bools
def set_ultra_mode(self, ultraMode=False):
self.ultraEnabled = ultraMode
def set_abort_mode(self, abortMode=False):
self.abortEnabled = abortMode
def set_harmonic_mode(self, harmonicMode=False):
self.harmonicEnabled = harmonicMode
# error check boundaries
## signal analyzer specific
def set_min_SA_freq(self, f):
self.minSADeviceFreq = float(f)
def get_min_SA_freq(self):
return self.minSADeviceFreq
def set_max_SA_freq(self, f):
self.maxSADeviceFreq = float(f)
def get_max_SA_freq(self):
return self.maxSADeviceFreq
## signal generator specific
def set_min_SG_freq(self, f):
self.minSGDeviceFreq = float(f)
def get_min_SG_freq(self):
return self.minSGDeviceFreq
def set_max_SG_freq(self, f):
self.maxSGDeviceFreq = float(f)
def get_max_SG_freq(self):
return self.maxSGDeviceFreq
######################################################################
# Serial management and message processing
######################################################################
def autoconnect(self, timeout=1):
# attempt to autoconnect to a detected port.
# returns: found_bool, connected_bool
# True if successful, False otherwise
# List all available serial ports
ports = serial.tools.list_ports.comports()
# loop through the ports and print out info
for port_info in ports:
# print out which port we're trying
port = port_info.device
self.print_message(f"Checking port: {port}")
vid = port_info.vid
pid = port_info.pid
# check if it's a tinySA or nanoVNA:
if (vid==None):
pass
elif (hex(vid) == '0x483') and (hex(pid)=='0x5740'):
self.print_message(f"tinySA device identified at port: {port}")
connected_bool = self.connect(port, timeout)
return True, connected_bool
return False, False # no tinySA found, not connected
def connect(self, port, timeout=1):
# attempt connection to provided port.
# returns: True if successful, False otherwise
try:
self.ser = serial.Serial(port=port, timeout=timeout)
return True
except Exception as err:
self.print_message("ERROR: cannot open port at " + str(port))
self.print_message(err)
return False
def disconnect(self):
# closes the serial port
self.ser.close()
def tinySA_serial(self, writebyte, printBool=False, pts=None):
# write out to serial, get message back, clean up, return
# clear INPUT buffer
self.ser.reset_input_buffer()
# clear OUTPUT buffer
self.ser.reset_output_buffer()
self.ser.write(bytes(writebyte, 'utf-8'))
msgbytes = self.get_serial_return()
msgbytes = self.clean_return(msgbytes)
if printBool == True:
print(msgbytes) #overrides verbose for debug
return msgbytes
def get_serial_return(self):
# while there's a buffer, read in the returned message
# original buffer reading from: https://groups.io/g/tinysa/topic/tinysa_screen_capture_using/82218670
buffer = bytes()
while True:
if self.ser.in_waiting > 0:
buffer += self.ser.read(self.ser.in_waiting)
try:
# split the stream to take a chunk at a time
# get up to '>' of the prompt
complete = buffer[:buffer.index(b'>')+1]
# leave the rest in buffer
buffer = buffer[buffer.index(b'ch>')+1:]
except ValueError:
# this is an acceptable err, so can skip it and keep looping
continue
except Exception as err:
# otherwise, something else is wrong
self.print_message("ERROR: exception thrown while reading serial")
self.print_message(err)
return None
break
return bytearray(complete)
def read_until_end_marker(self, end_marker=b'}', timeout=10.0):
# scan and scan raw might return early with tinySA_serial
# so this is written to
import time
buffer = bytes()
start_time = time.time()
while True:
if self.ser.in_waiting > 0:
buffer += self.ser.read(self.ser.in_waiting)
# Check if we have the end marker
if end_marker in buffer:
# Find the position after the end marker
end_pos = buffer.find(end_marker) + len(end_marker)
complete = buffer[:end_pos]
# Keep any remaining data for next read
self.remaining_buffer = buffer[end_pos:]
return bytearray(complete)
# Timeout check
if time.time() - start_time > timeout:
self.print_message(f"WARNING: Timeout waiting for end marker {end_marker}")
break
time.sleep(0.01)
return bytearray(buffer)
def clean_return(self, data):
# takes in a bytearray and removes 1) the text up to the first '\r\n' (includes the command), an 2) the ending 'ch>'
# Find the first occurrence of \r\n (carriage return + newline)
first_newline_index = data.find(b'\r\n')
if first_newline_index != -1:
# Slice the bytearray to remove everything before and including the first '\r\n'
data = data[first_newline_index + 2:] # Skip past '\r\n'
# Check if the message ends with 'ch>'
if data.endswith(b'ch>'):
# Remove 'ch>' from the end
data = data[:-4] # Remove the last 4 bytes ('ch>')
return data
######################################################################
# Reusable format checking functions
######################################################################
def convert_frequency(self, txtstr):
# this takes the user input (as text) and converts it.
# From documentation:
# Frequencies can be specified using an integer optionally postfixed with a the letter
# 'k' for kilo 'M' for Mega or 'G' for Giga. E.g. 0.1M (100kHz), 500k (0.5MHz) or 12000000 (12MHz)
# However the abbreviation makes error checking with numerics more difficult. so convert everything to Hz.
# e notation is fine
pass
def convert_time(self, txtstr):
# this takes the user input (as text) and converts it.
# From documentation:
# Time is specified in seconds optionally postfixed with the letters 'm' for mili
# or 'u' for micro. E.g. 1 (1 second), 2.5 (2.5 seconds), 120m (120 milliseconds)
pass
def is_rgb24(self, hexStr):
# check if the string matches the pattern 0xRRGGBB
pattern = r"^0x[0-9A-Fa-f]{6}$"
return bool(re.match(pattern, hexStr))
######################################################################
# Serial command config, input error checking
######################################################################
def abort(self, val=None):
# Sets the abort enabled status (on/off)
# usage: abort [off|on]
# example return: bytearray(b'')
# #explicitly allowed vals
accepted_vals = ["off", "on"]
#check input
if (str(val) in accepted_vals): #toggle state
writebyte = 'abort '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
if val == "on":
self.print_message("ABORT option ENABLED")
self.abortEnabled = True
elif val == "off":
self.print_message("ABORT option DISABLED")
self.abortEnabled = False
elif val == None: #action
if self.abortEnabled == True:
writebyte = 'abort\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
else:
self.print_message("ABORT option must be ENABLED before use")
msgbytes = bytearray(b'')
else:
self.print_message("ERROR: abort() takes NONE|\"off\"|\"on\" as arguments")
msgbytes = bytearray(b'')
return msgbytes
def enable_abort(self):
# alias for abort()
return self.abort( "on")
def disable_abort(self):
# alias for abort()
return self.abort("off")
def abort_action(self):
# alias for abort()
return self.abort()
def actual_freq(self, val=None):
# Sets or gets the frequency correction set by CORRECT FREQUENCY menu in the expert menu settings
# related to freq_corr
# usage: actual_freq [{frequency}]
# example return: bytearray(b'3000000000\r')
if val == None:
#get the dac
writebyte = 'actual_freq\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
elif (isinstance(val, (int, float))) and (self.minSADeviceFreq <= val <=self.maxSADeviceFreq ):
writebyte = 'actual_freq '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("actual_freq set to " + str(val))
else:
self.print_message("ERROR: actual_freq() takes either None or integers")
msgbytes = self.error_byte_return()
return msgbytes
def set_actual_freq(self, val):
# alias for actual_freq()
return self.actual_freq(val)
def get_actual_freq(self):
# alias for actual_freq()
return self.actual_freq(None)
def agc(self, val='auto'):
# Enables/disables the build in Automatic Gain Control
# usage: agc 0..7|auto
# example return: bytearray(b'')
#explicitly allowed vals
accepted_vals = np.arange(0, 8, 1) # max exclusive
#check input
if (str(val) == "auto") or (val in accepted_vals):
writebyte = 'agc '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("agc() set with " + str(val))
else:
self.print_message("ERROR: agc() takes vals [0 - 7]|\"auto\"")
msgbytes = self.error_byte_return()
return msgbytes
def set_agc(self, val):
# alias for agc()
return self.agc(val)
def attenuate(self, val='auto'):
# sets the internal attenuation to automatic or a specific value
# usage: attenuate [auto|0-31]
# example return: bytearray(b'')
#explicitly allowed vals
accepted_vals = np.arange(0, 31, 1) # max exclusive
#check input
if (str(val) == "auto") or (val in accepted_vals):
writebyte = 'attenuate '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("attenuate() set with " + str(val))
else:
self.print_message("ERROR: attenuate() takes vals [0 - 31]|\"auto\"")
msgbytes = self.error_byte_return()
return msgbytes
def set_attenuation(self, val):
# alias for attenuate()
return self.attenuate(val)
def bulk(self):
# sent by tinySA when in auto refresh mode
# format: "bulk\r\n{X}{Y}{Width}{Height}
# {Pixeldata}\r\n"
# where all numbers are binary coded 2
# bytes little endian. The Pixeldata is
# encoded as 2 bytes per pixel. similar to fill()
writebyte = 'bulk\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("bulk() called for screen data")
return msgbytes
def get_bulk_data(self):
# alias for bulk()
return self.bulk()
def calc(self, val="off"):
# sets or cancels one of the measurement modes
# the commands are the same as those listed
# in the MEASURE menu
# usage: calc off|minh|maxh|maxd|aver4|aver16|quasip
# example return:
#explicitly allowed vals
accepted_vals = ["off", "minh", "maxh", "maxd",
"aver4", "aver16", "quasip"]
#check input
if (str(val) in accepted_vals):
writebyte = 'calc '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("calc() set with " + str(val))
else:
self.print_message("ERROR: calc() takes vals \"off\"|\"minh\"|\"maxh\"|\"maxd\"|\"aver4\"|\"aver16\"|\"quasip\"")
msgbytes = self.error_byte_return()
return msgbytes
def set_calc_off(self):
return self.calc("off")
def set_calc_minh(self):
return self.calc("minh")
def set_calc_maxh(self):
return self.calc("maxh")
def set_calc_maxd(self):
return self.calc("maxd")
def set_calc_aver4(self):
return self.calc("aver4")
def set_calc_aver16(self):
return self.calc("aver16")
def set_calc_quasip(self):
return self.calc("quasip")
def cal_output(self, val="off"):
# disables or sets the caloutput to a specified frequency in MHz
# usage: caloutput off|30|15|10|4|3|2|1
# example return: bytearray(b'')
#explicitly allowed vals
accepted_vals = ["off", 'off', 1,2,3,4,10,15,30]
#check input
if (val in accepted_vals):
writebyte = 'caloutput '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("caloutput() set with " + str(val))
else:
self.print_message("ERROR: caloutput() takes vals 1|2|3|4|10|15|30|\"off\"")
msgbytes = self.error_byte_return()
return msgbytes
def set_cal_output_off(self):
# alias for cal_output()
return self.caloutput("off")
def set_cal_output_30(self):
# alias for cal_output()
return self.caloutput(30)
def set_cal_output_15(self):
# alias for cal_output()
return self.caloutput(15)
def set_cal_output_10(self):
# alias for cal_output()
return self.caloutput(10)
def set_cal_output_4(self):
# alias for cal_output()
return self.caloutput(4)
def set_cal_output_3(self):
# alias for cal_output()
return self.caloutput(3)
def set_cal_output_2(self):
# alias for cal_output()
return self.caloutput(2)
def set_cal_output_1(self):
# alias for cal_output()
return self.caloutput(1)
def capture(self):
# requests a screen dump to be sent in binary format
# of 320x240 pixels of each 2 bytes
# usage: capture
# example return: bytearray(b'\x00 ...\x00\x00\x00')
writebyte = 'capture\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("capture() called for screen data")
return msgbytes
def capture_screen(self):
return self.capture()
def clear_config(self):
# resets the configuration data to factory defaults. requires password
# NOTE: does take other commands to fully clear all
# usage: clearconfig 1234
# example return: bytearray(b'Config and all cal data cleared.
# \r\nDo reset manually to take effect.
# Then do touch cal and save.\r')
writebyte = 'clearconfig 1234\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("clear_config() with password. Config and all cal data cleared. \
Reset manually to take effect.")
return msgbytes
def clear_and_reset(self):
# alias function for full clear and reset process
self.clear_config()
self.reset()
def color(self, ID=None, RGB='0xF8FCF8'):
# sets or dumps the colors used
# usage: color [{id} {rgb24}]
# example return:
# explicitly allowed vals
accepted_ID = np.arange(0, 31, 1) # max exclusive
if ID == None:
# get the color
writebyte = 'color\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
elif (ID in accepted_ID) and (self.is_rgb24(RGB)==True):
# set the color based on ID
writebyte = 'color ' + str(ID) + ' ' + str(RGB) + '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("color() set with ID: " +str(ID) + " RGB: " + str(RGB))
else:
self.print_message("ERROR: color() takes either None, or ID as int 0..31 and RGB as a hex value")
msgbytes = self.error_byte_return()
return msgbytes
def get_all_colors(self):
# alias for color(). returns array of all colors
return self.color()
def get_color(self, ID):
# alias for color(). val must be int 1-31
msgbytes = self.color()
# check if something has been returned, otherwise pass the error through
if len(msgbytes) > 10:
# Use regex to find the value at index ID
pattern = rf'\b{int(ID)}:\s*0x([0-9A-Fa-f]+)'
match = re.search(pattern, msgbytes)
if match:
return f"0x{match.group(1)}" #return rgb24 value if found
# if not found, then
self.print_message("ERROR: color() takes either None, or ID as int 0..31 and RGB as a hex value")
msgbytes = self.error_byte_return()
return msgbytes
def set_color(self, ID, val):
# alias for color()
return self.color(ID, val)
def command(self, val):
# if the command isn't already a function,
# use existing func setup to send command
writebyte = str(val) + '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("command() called with ::" + str(val))
return msgbytes
def correction(self, argName="low", slot=None, freq=None, val=None):
# sets or dumps the frequency level orrection table
# usage: correction [0..9 {frequency} {level dB}]
# usage: correction low|lna|ultra|ultra_lna|direct|direct_lna|harm|harm_lna|out|out_direct|out_adf|out_ultra|off|on 0-19 frequency(Hz) value(dB)
# example return:
# explicitly allowed vals
accepted_table_args = ["low", "lna", "ultra", "ultra_lna",
"direct", "direct_lna", "harm",
"harm_lna", "out", "out_direct",
"out_adf", "out_ultra", "off", "on"]
accepted_slots = np.arange(0, 20, 1) # max exclusive.
if (argName in accepted_table_args) and (slot==None):
# prints out the table as it currently is
writebyte = 'correction ' + str(argName)+ '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
else:
# check error conditions quickly since there's 4
if not(argName in accepted_table_args):
self.print_message("ERROR: correction() requires a table indicator. see documentation")
msgbytes = self.error_byte_return()
return msgbytes
if not(slot in accepted_slots):
self.print_message("ERROR: correction() requires a slot from ["+ str(accepted_slots) + "]. see documentation")
msgbytes = self.error_byte_return()
return msgbytes
if not(self.minSADeviceFreq<=freq) and not(freq<=self.maxSADeviceFreq):
self.print_message("ERROR: correction() frequency outside of device specs. see documentation")
msgbytes = self.error_byte_return()
return msgbytes
if not(-10<=val) and not(val<=35):
self.print_message("ERROR: correction() val dB outside of specs. see documentation")
msgbytes = self.error_byte_return()
return msgbytes
writebyte = 'correction ' + str(argName) + ' ' + str(slot) +\
' ' + str(freq) + ' ' + str(val) + '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("correction() set with " + str(argName) + " " + str(slot) +\
" " + str(freq) + " " + str(val))
return msgbytes
#TODO ADD the CORRECTION setter shortcuts here.
def dac(self, val=None):
# sets or dumps the dac value
# usage: dac [0..4095]
# example return: bytearray(b'usage: dac {value(0-4095)}\r\ncurrent value: 1922\r')
if val == None:
#get the dac
writebyte = 'dac\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
elif (isinstance(val, (int, float))) and (0<= val <=4095):
writebyte = 'dac '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("dac set to " + str(val))
else:
self.print_message("ERROR: dac() takes either None or integers")
msgbytes = self.error_byte_return()
return msgbytes
def set_dac(self, val):
# alias for dac()
return self.dac(val)
def get_dac(self):
# alias for dac()
return self.dac()
def data(self, val=0):
# dumps the trace data.
# usage: data [0-2]
# 0=temp value, 1=stored trace, 2=measurement
# example return: bytearray(b'-8.671875e+01\r\n... -8.337500e+01\r\n-8.237500e+01\r')
#explicitly allowed vals
accepted_vals = [0,1,2]
#check input
if val in accepted_vals:
writebyte = 'data '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
if val == 0:
self.print_message("returning temp value data")
elif val == 1:
self.print_message("returning stored trace data")
elif val == 2:
self.print_message("returning measurement data")
else:
self.print_message("ERROR: data() takes vals [0-2]")
msgbytes = self.error_byte_return()
return msgbytes
def get_temporary_data(self):
# alias func for data()
return self.data(val=0)
def get_stored_trace_data(self):
# alias func for data()
return self.data(val=1)
def dump_measurement_data(self):
# alias func for data()
return self.data(val=2)
def device_id(self, ID=None):
# sets or dumps a user settable number that can be used to identify a specific tinySA
# usage: deviceid [{number}]
# example return: bytearray(b'deviceid 12\r')
if ID == None:
#get the device ID
writebyte = 'deviceid\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
elif isinstance(ID, int):
writebyte = 'deviceid '+str(ID)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("device ID set to " + str(ID))
else:
self.print_message("ERROR: device_id() takes either None or integers")
msgbytes = self.error_byte_return()
return msgbytes
def get_device_id(self):
# alias for device_id()
return self.device_id()
def set_device_id(self, ID):
# alias for device_id()
return self.device_id(ID)
def direct(self, val, freq):
# Output mode for generating a square wave signal between 830MHz and 1130MHz
# usage: direct {start|stop|on|off} {freq(Hz)}
# example return: ''
#explicitly allowed vals
accepted_vals = ["start", "stop",
"on", "off"]
#check input
if (str(val)=="on") or (str(val) =="off"):
writebyte = 'direct '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("direct() set with " + str(val))
elif (str(val)=="start") or (str(val)=="stop"):
#TODO: add frequency checking here
writebyte = 'direct '+str(val)+' ' +str(freq)+ '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("direct() set with " + str(val) + "frequency of " + str(freq))
else:
self.print_message("ERROR: direct() takes val={'on', 'off', 'start', 'stop'}, freq=INT")
msgbytes = self.error_byte_return()
return msgbytes
def set_direct_on(self):
# alias for direct()
return self.direct("on")
def set_direct_off(self):
# alias for direct()
return self.direct("off")
def set_direct_start(self, freq):
# alias for direct()
return self.direct("start", freq)
def set_direct_stop(self, freq):
# alias for direct()
return self.direct("stop", freq)
def ext_gain(self, val):
# sets the external attenuation/amplification.
# Works in both input and output mode
# usage: ext_gain -100..100
# example return: ''
#check input
if (isinstance(val, (int, float))) and (-100<= val <=100):
writebyte = 'ext_gain '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("ext_gain() set to " + str(val))
else:
self.print_message("ERROR: ext_gain() takes vals [-100 - 100]")
msgbytes = self.error_byte_return()
return msgbytes
def set_ext_gain(self, val):
# alias for ext_gain()
return self.ext_gain(val)
def fill(self):
# sent by tinySA when in auto refresh mode
# format: "fill\r\n{X}{Y}{Width}{Height}
# {Color}\r\n"
# where all numbers are binary coded 2
# bytes little endian. Similar ot bulk()
writebyte = 'fill\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("fill() called for screen data")
return msgbytes
def get_fill_data(self):
# alias for fill()
return self.fill()
def freq(self, val):
# pauses the sweep and sets the measurement frequency.
# usage: freq {frequency}
# example return: bytearray(b'')
#check input
if (isinstance(val, (int, float))) and (self.minSADeviceFreq<= val <=self.maxSADeviceFreq):
writebyte = 'freq '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("freq() set to " + str(val))
else:
self.print_message("ERROR: freq() takes integer vals [100 kHz - 5.3 GHz] as Hz for the tinySA Ultra")
msgbytes = self.error_byte_return()
return msgbytes
def set_freq(self, val):
# freq() alias
return self.freq(val)
def freq_corr(self):
# get frequency correction
# usage: freq_corr
# example return: bytearray(b'0 ppb\r')
writebyte = 'freq_corr\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("getting frequency correction")
return msgbytes
def get_frequency_correction(self):
# alias for freq_corr()
return self.freq_corr()
def frequencies(self):
# gets the frequencies used by the last sweep
# usage: frequencies
# example return: bytearray(b'1500000000\r\n... \r\n3000000000\r')
writebyte = 'frequencies\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("getting frequencies from the last sweep")
return msgbytes
def get_last_freqs(self):
# get frequencies of last sweep
return self.frequencies()
def hop(self, start, stop, inc, outmask=None):
# this is a measurement, maybe a sample measurement. format looks like hop freqval integer
# usage: hop {start(Hz)} {stop(Hz)} {step(Hz) | points} [outmask]
# outmask: 1 is frequency, 2 is level
# example return: ''
if (isinstance(start, (int, float))) and (isinstance(stop, (int, float))) and (isinstance(inc, (int, float))):
if (isinstance(outmask, int)) and (0<outmask<3):
writebyte = 'hop ' + str(start) + ' ' + str(stop) + ' ' + str(inc) + ' ' + str(outmask) + '\r\n'
elif outmask ==None:
writebyte = 'hop ' + str(start) + ' ' + str(stop) + ' ' + str(inc) + '\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("sampling over frequency range")
return msgbytes
else:
self.print_message("hop() takes arguments start=Int, stop=Int, inc=Int, outmask=None|Int")
return None
def get_sample_pts(self, start, stop, pts):
# alias for hop()
return self.hop(start, stop, pts, outmask=1)
def set_IF(self, val=0):
# the IF call, but avoiding reserved keywords
# sets the IF to automatic or a specific value. 0 means automatic
# usage: if ( 0 | 433M..435M )
# example return: ''
#check input
if (val == 0) or (val=='auto'):
writebyte = 'if '+str(0)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("setIF() set to auto")
elif ((433e6) <=val <=(435e6)):
writebyte = 'if '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("setIF() set to " + str(val))
else:
self.print_message("ERROR: if() takes vals ['auto'|0|433M...435M] in Hz as integers")
msgbytes = self.error_byte_return()
return msgbytes
def set_IF1(self, val):
# usage: if1 {975M..979M}\r\n977.555902MHz
# example return: ''
#check input
if (val == 0) or (val=='auto'):
writebyte = 'if1 '+str(0)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("setIF1() set to auto")
elif ((975e6) <=val <=(979e6)):
writebyte = 'if1 '+str(val)+'\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("setIF() set to " + str(val))
else:
self.print_message("ERROR: if1() takes vals ['auto'|0|975M...979M] in Hz as integers")
msgbytes = self.error_byte_return()
return msgbytes
def info(self):
# displays various SW and HW information
# usage: info
# example return: bytearray(b'tinySA ...\r')
writebyte = 'info\r\n'
msgbytes = self.tinySA_serial(writebyte, printBool=False)
self.print_message("returning device info()")
return msgbytes
def get_info(self):
# alias for info()
return self.info()
def level(self, val):
# sets the output level. Not all values in the range are available
# usage: level -76..13
# example return: b''
# explicitly allowed vals
You can’t perform that action at this time.
