1+ from contextlib import contextmanager
12from functools import cached_property
23
34import pexpect
@@ -11,6 +12,7 @@ class UbootConsoleClient(CompositeClient):
1112 def prompt (self ) -> str :
1213 return self .call ("get_prompt" )
1314
15+ @contextmanager
1416 def reboot_to_console (self ) -> None :
1517 """
1618 Reboot to U-Boot console
@@ -22,6 +24,7 @@ def reboot_to_console(self) -> None:
2224 self .power .cycle ()
2325
2426 self .logger .info ("Waiting for U-Boot prompt..." )
27+
2528 with self .serial .pexpect () as p :
2629 for _ in range (100 ): # TODO: configurable retries
2730 try :
@@ -30,21 +33,30 @@ def reboot_to_console(self) -> None:
3033 except pexpect .TIMEOUT :
3134 continue
3235
33- return
34-
35- raise RuntimeError ("Failed to get U-Boot prompt" )
36-
37- def run_command (self , cmd : str , timeout : int = 60 ) -> bytes :
38- self .logger .info (f"Running command: { cmd } " )
39- with self .serial .pexpect () as p :
40- p .sendline ("" )
41- p .expect_exact (self .prompt , timeout = timeout )
42- p .sendline (cmd )
43- p .expect_exact (self .prompt , timeout = timeout )
44- return p .before
36+ break
37+ else :
38+ raise RuntimeError ("Failed to get U-Boot prompt" )
39+
40+ self .p = p
41+ try :
42+ yield
43+ finally :
44+ delattr (self , "p" )
45+
46+ def run_command (self , cmd : str , timeout : int = 60 , * , _internal_log = True ) -> bytes :
47+ if _internal_log :
48+ self .logger .info (f"Running command: { cmd } " )
49+ if not hasattr (self , "p" ):
50+ raise RuntimeError ("Not in a reboot_to_console context" )
51+ self .p .sendline ("" )
52+ self .p .expect_exact (self .prompt , timeout = timeout )
53+ self .p .sendline (cmd )
54+ self .p .expect_exact (self .prompt , timeout = timeout )
55+ return self .p .before
4556
4657 def run_command_checked (self , cmd : str , timeout : int = 60 , check = True ) -> list [str ]:
47- output = self .run_command ("{}; echo $?" .format (cmd ))
58+ self .logger .info (f"Running command checked: { cmd } " )
59+ output = self .run_command ("{}; echo $?" .format (cmd ), _internal_log = False )
4860 parsed = output .strip ().decode ().splitlines ()
4961
5062 if len (parsed ) < 2 :
0 commit comments