#!/usr/bin/env python3 """ 板子实测脚本: 1. 同时监控 COM9 @ 115200 的所有输出 2. 定时往 COM9 发 JSON 命令,观察板子响应 3. 长循环运行,收集证据 """ import serial import time import threading import sys PORT = 'COM9' BAUD = 115200 # 命令序列 CMD_SEQ = [ '{"zt":"xy1","neirong":"01"}\n', '{"zt":"sm2","neirong":"01"}\n', '{"zt":"xy1","neirong":"02"}\n', '{"zt":"sm2","neirong":"02"}\n', ] def reader(s, stop_event): """后台线程:一直读串口,实时打印""" line = b'' while not stop_event.is_set(): try: data = s.read(1024) if data: for b in data: if b == 0x0D: continue if b == 0x0A: text = line.decode('ascii', errors='replace') if text.strip(): ts = time.strftime('%H:%M:%S') print(f"[{ts}] RX {text}") line = b'' else: line += bytes([b]) except Exception as e: print(f"[read error] {e}") break if line: print(f"[RX leftover] {line}") print(f"Opening {PORT} @ {BAUD}...", flush=True) try: s = serial.Serial(PORT, BAUD, timeout=0.1) except Exception as e: print(f"FAIL: {e}") sys.exit(1) print(f"OK. Starting reader thread...\n", flush=True) stop = threading.Event() t = threading.Thread(target=reader, args=(s, stop), daemon=True) t.start() # 先等 3 秒,观察板子自己输出什么 print("=== Phase 1: 观察板子上电后自发送(5秒)===") time.sleep(5) # 尝试发命令 print("\n=== Phase 2: 尝试发 JSON 命令(每 4 秒一条,等回复)===") for i, cmd in enumerate(CMD_SEQ): ts = time.strftime('%H:%M:%S') print(f"[{ts}] TX → {cmd.strip()}") try: s.write(cmd.encode('ascii')) s.flush() except Exception as e: print(f" TX ERROR: {e}") time.sleep(4) # 再等会儿看板子还有没有自发数据 print("\n=== Phase 3: 再观察 10 秒 ===") time.sleep(10) stop.set() time.sleep(0.5) s.close() print("\n=== Done ===")