Skip to content

Instantly share code, notes, and snippets.

@unixnut
Forked from mortie/sercom.py
Created March 25, 2020 05:05
Show Gist options
  • Save unixnut/8b377ba4a5d42885e3c559ca520a8d7c to your computer and use it in GitHub Desktop.
Save unixnut/8b377ba4a5d42885e3c559ca520a8d7c to your computer and use it in GitHub Desktop.
Better serial console.
#!/usr/bin/env python3
import serial
import sys
import os
import threading
import traceback
if len(sys.argv) not in (2, 3):
print(f"Usage: {sys.argv[0]} <path> [baud]")
exit(1)
if len(sys.argv) == 2:
ser = serial.Serial(sys.argv[1])
else:
ser = serial.Serial(sys.argv[1], baudrate=sys.argv[2])
print(str(ser))
print("Hit 'Ctrl-A q' to exit.")
def terminate(code=1):
os.system("stty sane")
ser.close()
print()
os._exit(code)
def read_loop():
try:
while True:
ch = ser.read(1)
sys.stdout.buffer.write(ch)
sys.stdout.buffer.flush()
except:
traceback.print_exc()
terminate()
def write_loop():
try:
cmd_mode = False
while True:
ch = sys.stdin.buffer.read(1)
if ch == b'\x01':
if cmd_mode:
ser.write(ch)
cmd_mode = False
else:
cmd_mode = True
elif cmd_mode:
if ch == b'q':
terminate(0)
cmd_mode = False
else:
ser.write(ch)
except:
traceback.print_exc()
terminate()
os.system("stty raw -echo")
try:
read_thread = threading.Thread(target=read_loop)
write_thread = threading.Thread(target=write_loop)
read_thread.start()
write_thread.start()
read_thread.join()
write_thread.join()
except:
traceback.print_exc()
terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment