@@ -342,6 +342,45 @@ def configure_case(kind: str) -> list[str]:
342342 return commands
343343
344344
345+ def sitl_log_counts (sitl : SitlProcess ) -> tuple [int , int ]:
346+ try :
347+ text = sitl .log_path .read_text (encoding = "utf-8" , errors = "replace" )
348+ except OSError :
349+ return 0 , 0
350+ return text .count ("[SYSTEM] Reset" ), text .count ("[SYSTEM] Init..." )
351+
352+
353+ def wait_for_sitl_reboot (
354+ sitl : SitlProcess ,
355+ reset_count_before : int ,
356+ init_count_before : int ,
357+ timeout_s : float = 8.0 ,
358+ ) -> None :
359+ """Wait for CLI `save` to actually reset and finish re-execing SITL.
360+
361+ Waiting for the TCP port alone is insufficient: the pre-reset listener can
362+ still accept a client while the delayed CLI reboot is pending, after which
363+ systemReset() closes that just-opened MSP connection underneath the test.
364+ """
365+ deadline = time .monotonic () + timeout_s
366+ saw_reset = False
367+ last_reset_count = reset_count_before
368+ last_init_count = init_count_before
369+ while time .monotonic () < deadline :
370+ sitl .check_alive ()
371+ last_reset_count , last_init_count = sitl_log_counts (sitl )
372+ if last_reset_count > reset_count_before :
373+ saw_reset = True
374+ if saw_reset and last_init_count > init_count_before :
375+ return
376+ time .sleep (0.02 )
377+ raise TestFailure (
378+ "SITL did not complete CLI save/reboot cycle within "
379+ f"{ timeout_s :.1f} s (reset { reset_count_before } ->{ last_reset_count } , "
380+ f"init { init_count_before } ->{ last_init_count } )\n { sitl .tail_log (lines = 80 )} "
381+ )
382+
383+
345384def run_case (kind : str , binary : Path , repo : Path , tcp_base : int , temp_dir : Path ) -> None :
346385 eeprom = temp_dir / f"{ kind } .bin"
347386 log_path = temp_dir / f"{ kind } .log"
@@ -354,8 +393,9 @@ def run_case(kind: str, binary: Path, repo: Path, tcp_base: int, temp_dir: Path)
354393 msp_port = tcp_port (tcp_base , UART_MSP )
355394 wait_tcp ("127.0.0.1" , msp_port , 8.0 , sitl )
356395 time .sleep (0.15 )
396+ reset_count , init_count = sitl_log_counts (sitl )
357397 configure_cli ("127.0.0.1" , msp_port , configure_case (kind ))
358- time . sleep ( 1.0 )
398+ wait_for_sitl_reboot ( sitl , reset_count , init_count )
359399 wait_tcp ("127.0.0.1" , msp_port , 8.0 , sitl )
360400
361401 msp = MspClient ("127.0.0.1" , msp_port , timeout_s = 2.0 )
0 commit comments