watch_com9.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python3
  2. """监控 COM9(板子唯一的 USB 转 232 口)的全部输出,持续 30 秒。"""
  3. import serial
  4. import serial.tools.list_ports
  5. import time
  6. import sys
  7. PORT = 'COM9'
  8. BAUD = 9600
  9. print(f"Opening {PORT} @ {BAUD}...", flush=True)
  10. try:
  11. s = serial.Serial(PORT, BAUD, timeout=0.1)
  12. except Exception as e:
  13. print(f"FAIL: {e}")
  14. sys.exit(1)
  15. print(f"OK. Watching for 30s...", flush=True)
  16. start = time.time()
  17. rx_total = 0
  18. line_buf = b''
  19. while time.time() - start < 30:
  20. data = s.read(1024)
  21. if data:
  22. rx_total += len(data)
  23. for b in data:
  24. if b == 0x0D:
  25. continue
  26. if b == 0x0A:
  27. print(f" RX[{rx_total:5d}]: {line_buf.decode('ascii', errors='replace')}", flush=True)
  28. line_buf = b''
  29. else:
  30. line_buf += bytes([b])
  31. else:
  32. # 每 5 秒打印一次 "alive"
  33. elapsed = int(time.time() - start)
  34. if elapsed % 5 == 0 and not hasattr(s, '_last_print'):
  35. pass
  36. # flush remaining
  37. if line_buf:
  38. print(f" RX[{rx_total:5d}]: {line_buf.decode('ascii', errors='replace')}", flush=True)
  39. s.close()
  40. print(f"\nDone. Total received: {rx_total} bytes in 30s")