#!/usr/bin/env python3 """ log_serial.py — auto-detects the Arduino serial port, logs timestamped output to a file (always appending), and reconnects automatically if the Arduino is restarted or the cable is briefly disconnected. Intended to run as a systemd service on a Raspberry Pi so it starts on boot with no user interaction. See README.md in this folder for setup instructions. Usage: python3 log_serial.py # auto-detect port, log to arduino.log python3 log_serial.py --port /dev/ttyACM1 # force a specific port python3 log_serial.py --out /var/log/game.log # write to a different file python3 log_serial.py --list-ports # show available ports and exit Dependencies: pip install pyserial """ import argparse import time import serial import serial.tools.list_ports from datetime import datetime from pathlib import Path # ── Configuration ───────────────────────────────────────────────────────────── DEFAULT_BAUD = 9600 # must match Serial.begin() in the Arduino sketch DEFAULT_OUT = "arduino.log" # relative to this script's directory RECONNECT_DELAY_S = 3 # seconds to wait before reconnecting after a disconnect PORT_SCAN_DELAY_S = 5 # seconds to wait when no port is found yet # ────────────────────────────────────────────────────────────────────────────── def find_arduino_port() -> str | None: """ Return the device path of the most likely Arduino serial port, or None. Search order: 1. Any port whose description contains 'arduino' (official boards) 2. Any port whose description contains 'ch340' or 'ch341' (common clones) 3. Any ttyACM* or ttyUSB* device (generic USB-serial on Linux) """ ports = serial.tools.list_ports.comports() for p in ports: desc = p.description.lower() if "arduino" in desc: return p.device for p in ports: desc = p.description.lower() if "ch340" in desc or "ch341" in desc or "ftdi" in desc: return p.device for p in ports: if "ttyACM" in p.device or "ttyUSB" in p.device: return p.device return None def list_ports(): ports = serial.tools.list_ports.comports() if not ports: print(" (no serial ports found)") for p in ports: print(f" {p.device:25s} {p.description}") def log(f, message: str): """Write a timestamped line to the file and stdout.""" timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] entry = f"[{timestamp}] {message}" print(entry, flush=True) f.write(entry + "\n") f.flush() def run(port_override: str | None, baud: int, out: Path): print(f"Logging to {out} (Ctrl+C to stop)\n") with open(out, "a", encoding="utf-8") as f: # ── startup banner ──────────────────────────────────────────────────── banner = f"\n{'─' * 60}\nLogger started {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n{'─' * 60}" print(banner, flush=True) f.write(banner + "\n") f.flush() # ── outer loop: keeps reconnecting forever ──────────────────────────── try: while True: port = port_override or find_arduino_port() if port is None: log(f, f"[WAIT] No Arduino found — retrying in {PORT_SCAN_DELAY_S}s …") time.sleep(PORT_SCAN_DELAY_S) continue log(f, f"[CONNECT] Opening {port} at {baud} baud …") try: ser = serial.Serial(port, baud, timeout=1) except serial.SerialException as e: log(f, f"[ERROR] Could not open {port}: {e}") time.sleep(RECONNECT_DELAY_S) continue log(f, f"[CONNECT] Connected to {port}") # ── inner loop: read lines until disconnect ──────────────────── try: while True: raw = ser.readline() if not raw: continue # readline timeout — no data, keep waiting try: line = raw.decode("utf-8", errors="replace").rstrip("\r\n") except Exception: line = repr(raw) if line: log(f, line) except serial.SerialException as e: log(f, f"[DISCONNECT] Lost connection to {port}: {e}") log(f, f"[RECONNECT] Retrying in {RECONNECT_DELAY_S}s …") finally: try: ser.close() except Exception: pass time.sleep(RECONNECT_DELAY_S) except KeyboardInterrupt: footer = f"\nLogger stopped {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n" print(footer, flush=True) f.write(footer) if __name__ == "__main__": script_dir = Path(__file__).parent parser = argparse.ArgumentParser( description="Log Arduino serial output with timestamps. Auto-detects the USB port." ) parser.add_argument( "--port", default=None, help="Force a specific serial port (default: auto-detect)", ) parser.add_argument( "--baud", type=int, default=DEFAULT_BAUD, help=f"Baud rate (default: {DEFAULT_BAUD})", ) parser.add_argument( "--out", default=str(script_dir / DEFAULT_OUT), help=f"Log file path (default: