tools/litex_term: exit on 2 consecutive CTRL-C
authorFlorent Kermarrec <florent@enjoy-digital.fr>
Mon, 10 Jun 2019 13:06:57 +0000 (15:06 +0200)
committerFlorent Kermarrec <florent@enjoy-digital.fr>
Mon, 10 Jun 2019 13:06:57 +0000 (15:06 +0200)
When running OS with LiteX and when LiteXTerm is use, we want to be able to
send CTRl-C to the OS. Ensure a specific sequence is sent to close the terminal.

litex/tools/litex_term.py

index 8d7e3d5c60f30dbf7ec852f30948b4d0a06ee2d0..f714fac7bf36a0262331ecca7efd9acd01ee4fef 100755 (executable)
@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 
 import sys
+import signal
 import os
 import time
 import serial
@@ -40,7 +41,6 @@ else:
         def getkey(self):
             return os.read(self.fd, 1)
 
-
 sfl_prompt_req = b"F7:    boot from serial\n"
 sfl_prompt_ack = b"\x06"
 
@@ -140,6 +140,9 @@ class LiteXTerm:
 
         self.console = Console()
 
+        signal.signal(signal.SIGINT, self.sigint)
+        self.sigint_time_last = 0
+
     def open(self, port, baudrate):
         if hasattr(self, "port"):
             return
@@ -151,6 +154,17 @@ class LiteXTerm:
         self.port.close()
         del self.port
 
+    def sigint(self, sig, frame):
+        self.port.write(b"\x03")
+        sigint_time_current = time.time()
+        # Exit term if 2 CTRL-C pressed in less than 0.5s.
+        if (sigint_time_current - self.sigint_time_last < 0.5):
+            self.console.unconfigure()
+            self.close()
+            sys.exit()
+        else:
+            self.sigint_time_last = sigint_time_current
+
     def send_frame(self, frame):
         retry = 1
         while retry:
@@ -316,15 +330,9 @@ def main():
     args = _get_args()
     term = LiteXTerm(args.serial_boot, args.kernel, args.kernel_adr, args.images)
     term.console.configure()
-    try:
-        term.open(args.port, int(float(args.speed)))
-        term.start()
-        term.join(True)
-    except KeyboardInterrupt:
-        term.console.unconfigure()
-    finally:
-        term.console.unconfigure()
-        term.close()
+    term.open(args.port, int(float(args.speed)))
+    term.start()
+    term.join(True)
 
 if __name__ == "__main__":
     main()