"""Log one or more serial ports to timestamped files until Ctrl+C. Usage: python tools/serial_logger.py COM9 # one port python tools/serial_logger.py COM8,COM9 # several ports python tools/serial_logger.py COM9 logs/ # custom output dir (default: wiki/raw/) Each port gets its own file, e.g. wiki/raw/serial-COM9-20260922-141503.log. Lines are echoed to the console prefixed with the port name. Read-only: nothing is ever written to the port, so it is safe next to a live bus. """ import os import sys import time import threading from datetime import datetime import serial ports = sys.argv[1].split(",") if len(sys.argv) > 1 else ["COM9"] out_dir = sys.argv[2] if len(sys.argv) > 2 else os.path.join("wiki", "raw") os.makedirs(out_dir, exist_ok=True) stop = threading.Event() print_lock = threading.Lock() def log_port(port): stamp = datetime.now().strftime("%Y%m%d-%H%M%S") path = os.path.join(out_dir, "serial-%s-%s.log" % (port, stamp)) with print_lock: print("[%s] logging to %s" % (port, path)) try: s = serial.Serial(port, 115200, timeout=0.5) except Exception as e: with print_lock: print("[%s] ERROR opening port: %s" % (port, e)) return with open(path, "wb") as f: pending = b"" while not stop.is_set(): data = s.read(4096) if not data: continue f.write(data) f.flush() pending += data while b"\n" in pending: line, pending = pending.split(b"\n", 1) with print_lock: print("[%s] %s" % (port, line.decode("utf-8", "replace").rstrip())) s.close() with print_lock: print("[%s] closed, log saved: %s" % (port, path)) threads = [threading.Thread(target=log_port, args=(p,)) for p in ports] for t in threads: t.start() try: while any(t.is_alive() for t in threads): time.sleep(0.2) except KeyboardInterrupt: stop.set() for t in threads: t.join()