1111
1212import signal
1313import sys
14- import os
1514from datetime import datetime
1615from pathlib import Path
1716
@@ -43,37 +42,60 @@ def signal_handler(sig, frame):
4342
4443signal .signal (signal .SIGINT , signal_handler )
4544
46- # Make a new S500
47- myS500 = S500 ()
48- if args .device is not None :
49- myS500 .connect_serial (args .device , args .baudrate )
50- elif args .udp is not None :
51- (host , port ) = args .udp .split (':' )
52- myS500 .connect_udp (host , int (port ))
53- elif args .tcp is not None :
54- (host , port ) = args .tcp .split (':' )
55- myS500 .connect_tcp (host , int (port ))
56-
57- # Check for log argument
58- # If no log is specified, create one using date and time
59- # If a log is specified, existing log will be opened
45+ # Check for log argument and make new S500
46+ # If no .svlog is specified, create one using default directory
47+ # If directory specified, .svlog be created in specified directory
48+ # If a .svlog is specified, existing log will be opened
6049new_log = False
61- new_folder_name = None
50+ log_path = ""
51+ replay_path = None
52+ default_dir = Path ("logs/s500" ).resolve ()
6253if args .log is not None :
6354 if args .log is True :
55+ # Logging to default directory
56+ default_dir .mkdir (parents = True , exist_ok = True )
57+ myS500 = S500 (logging = True , log_directory = default_dir )
58+ # print(f"Logging to new file in: {default_dir}")
6459 new_log = True
6560 elif isinstance (args .log , str ):
66- log_path = os .path .join ("logs/sounder" , args .log )
67- if args .log .endswith (".txt" ):
68- new_log = False
69- elif os .path .exists (log_path ):
70- print (f"Replaying from existing log folder: { log_path } " )
71- new_log = False
72- else :
73- new_folder_name = args .log
61+ log_path = Path (args .log ).expanduser ()
62+
63+ if log_path .suffix == ".svlog" and log_path .parent == Path ("." ):
64+ log_path = default_dir / log_path .name
65+
66+ log_path = log_path .resolve ()
67+
68+ if log_path .suffix == ".svlog" :
69+ if log_path .exists () and log_path .is_file ():
70+ # File exists, replaying
71+ new_log = False
72+ myS500 = S500 (logging = False )
73+ replay_path = log_path
74+ print (f"Replaying from: { replay_path } " )
75+ else :
76+ raise FileNotFoundError (f"Log file not found: { log_path } " )
77+
78+ elif log_path .is_dir () or log_path .suffix == "" :
79+ # Path is directory, logging to that directory
80+ myS500 = S500 (logging = True , log_directory = log_path )
81+ # print(f"Logging to new file: {S500.current_log}")
7482 new_log = True
83+
84+ else :
85+ raise ValueError (f"Invalid log argument: { args .log } " )
86+ else :
87+ myS500 = S500 ()
7588
7689if args .log is None or new_log :
90+ if args .device is not None :
91+ myS500 .connect_serial (args .device , args .baudrate )
92+ elif args .udp is not None :
93+ (host , port ) = args .udp .split (':' )
94+ myS500 .connect_udp (host , int (port ))
95+ elif args .tcp is not None :
96+ (host , port ) = args .tcp .split (':' )
97+ myS500 .connect_tcp (host , int (port ))
98+
7799 if myS500 .initialize () is False :
78100 print ("Failed to initialize S500!" )
79101 exit (1 )
@@ -85,103 +107,23 @@ def signal_handler(sig, frame):
85107
86108input ("Press Enter to continue..." )
87109
88- # Running S500 from existing log file
110+ # Running s500Example.py from existing log file
89111if args .log is not None and not new_log :
90- log_path = Path ("logs/sounder" ) / args .log
91- if not log_path .exists ():
92- print (f"Log path does not exist: { log_path } " )
93- sys .exit (1 )
94-
95- if log_path .is_dir ():
96- for file in sorted (log_path .iterdir ()):
97- if file .suffix == ".txt" :
98- print (f"\n ---------Replaying File: { file .name } ---------" )
99- with open (file , 'rb' ) as f :
100- raw_bytes = f .read ()
101- data = PingMessage (msg_data = raw_bytes )
102-
103- if data :
104- print (data )
105- else :
106- print ("Failed to get report" )
107- elif log_path .is_file ():
108- print (f"\n ---------Replaying File: { log_path .name } ---------" )
109- with open (log_path , 'rb' ) as f :
110- raw_bytes = f .read ()
111- data = PingMessage (msg_data = raw_bytes )
112-
113- if data :
114- print (data )
115- else :
116- print ("Failed to get report" )
117- else :
118- print (f"Invalid log path: { log_path } " )
112+ with open (log_path , 'rb' ) as f :
113+ while True :
114+ data = S500 .read_packet (f )
119115
120- # Connected to physical S500
121- else :
122- if new_log :
123- if new_folder_name is None :
124- log_folder_name = datetime .now ().strftime ("%Y-%m-%d_%H-%M-%S" )
125- else :
126- log_folder_name = new_folder_name
127- log_path = os .path .join ("logs/sounder" , log_folder_name )
128- os .makedirs (log_path , exist_ok = True )
129- print (f"Logging new files in: { log_path } " )
130-
131- print ("\n -------Distance2-------" )
132- if args .range is not None :
133- parts = args .range .split (':' )
134- # Tell S500 to send distance 2 data
135- if len (parts ) == 2 :
136- myS500 .control_set_ping_params (
137- start_mm = int (parts [0 ]),
138- length_mm = int (parts [1 ]),
139- msec_per_ping = 0 ,
140- report_id = definitions .S500_DISTANCE2 ,
141- chirp = 1
142- )
143- elif len (parts ) == 1 :
144- myS500 .control_set_ping_params (
145- start_mm = 0 ,
146- length_mm = int (parts [0 ]),
147- msec_per_ping = 0 ,
148- report_id = definitions .S500_DISTANCE2 ,
149- chirp = 1
150- )
151- else :
152- print ("Invalid range input, using default range" )
153- myS500 .control_set_ping_params (
154- msec_per_ping = 0 ,
155- report_id = definitions .S500_DISTANCE2 ,
156- chirp = 1
157- )
158- else :
159- myS500 .control_set_ping_params (
160- msec_per_ping = 0 ,
161- report_id = definitions .S500_DISTANCE2 ,
162- chirp = 1
163- )
116+ if data == None :
117+ break # EOF or bad packet
164118
165- # Read and print distance2 data
166- data = myS500 .wait_message ([definitions .S500_DISTANCE2 ])
167- if data :
168- # Create new log if specified
169- if new_log :
170- distance2_path = os .path .join (log_path , "Distance2.txt" )
171- with open (distance2_path , 'ab' ) as f :
172- f .write (data .msg_data )
173-
174- print (f"Ping Distance: { data .ping_distance_mm } mm" )
175- print (f"Confidence: { data .ping_confidence } " )
176- print (f"Average Distance: { data .averaged_distance_mm } mm" )
177- print (f"Confidence of Average: { data .average_distance_confidence } " )
178- print (f"Timestamp: { data .timestamp } " )
119+ print (f"ID: { data .message_id } \t Name: { data .name } " )
179120
121+ # Connected to physical S500
122+ else :
180123 print ("\n -------Profile6-------" )
181124 # Tell S500 to send profile6 data
182125 if args .range is not None :
183126 parts = args .range .split (':' )
184- # Tell S500 to send distance 2 data
185127 if len (parts ) == 2 :
186128 myS500 .control_set_ping_params (
187129 start_mm = int (parts [0 ]),
@@ -212,34 +154,22 @@ def signal_handler(sig, frame):
212154 chirp = 1
213155 )
214156
215- # Read and print profile6 data
216- data = myS500 .wait_message ([definitions .S500_PROFILE6_T ])
217- if data :
218- # Create new log if specified
219- if new_log :
220- profile6_path = os .path .join (log_path , "Profile6.txt" )
221- with open (profile6_path , 'ab' ) as f :
222- f .write (data .msg_data )
223-
224- scaled_result = S500 .scale_power (data )
225-
226- if (data .num_results > 100 ):
227- for i in range (5 ):
228- print (f"{ i } :\t Not Scaled: { data .pwr_results [i ]} | Scaled: { scaled_result [i ]:.2f} dB" )
229- print (".\n .\n ." )
230- for i in range (5 , 0 , - 1 ):
231- print (f"{ data .num_results - i } :\t Not Scaled: { data .pwr_results [data .num_results - i ]} | Scaled: { scaled_result [data .num_results - i ]:.2f} dB" )
232- else :
233- for i in range (len (scaled_result )):
234- print (f"{ i + 1 } :\t Not scaled: { data .pwr_results [i ]} | Scaled: { scaled_result [i ]:.2f} dB" )
235-
236- print (f"Number of results: { data .num_results } " )
237- print (f"Min power: { data .min_pwr_db } dB" )
238- print (f"Max power: { data .max_pwr_db } dB" )
239- # print(data)
240-
157+ if new_log :
158+ print ("Logging...\n CTRL+C to stop logging" )
241159 else :
242- print ("Failed to get profile6 data" )
160+ print ("CTRL-C to end program..." )
161+ try :
162+ while True :
163+ # Read and print profile6 data
164+ data = myS500 .wait_message ([definitions .S500_PROFILE6_T ,
165+ definitions .S500_DISTANCE2 ])
166+ if data and not new_log :
167+ scaled_result = S500 .scale_power (data )
168+ print (f"Average power: { sum (scaled_result ) / len (scaled_result )} " )
169+ elif not data :
170+ print ("Failed to get message" )
171+ except KeyboardInterrupt :
172+ print ("Stopping logging..." )
243173
244174 # Stop pinging
245175 myS500 .control_set_ping_params (report_id = 0 )
0 commit comments