#!/usr/bin/env python3 """ 完整版:监控所有板子输出 + 发命令 + 等够时间让 JSON 多走两轮再看变化 """ import serial, time, json PORT, BAUD = 'COM9', 115200 def open_s(): return serial.Serial(PORT, BAUD, timeout=0.05) def watch(s, seconds, label=''): """持续看 seconds 秒,每行都打印,顺便提取 JSON""" print(f"\n--- [{time.strftime('%H:%M:%S')}] {label} ({seconds}s) ---") end = time.time() + seconds json_count = 0 while time.time() < end: line = b'' while True: b = s.read(1) if not b: break if b in (b'\r', b'\n'): break line += b if line: text = line.decode('ascii', errors='replace') if text.startswith('{'): json_count += 1 try: d = json.loads(text) # 打印关键字段摘要 summary = (f" xl1={d.get('xl1','')} xy1={d.get('xy1','')} " f"sm2={d.get('sm2','')} pl2={d.get('pl2','')} " f"zy2={d.get('zy2','')} xl2={d.get('xl2','')} hx2={d.get('hx2','')}") print(f" [JSON#{json_count}]{summary}") except: print(f" [JSON?] {text[:100]}") else: print(f" [DBG] {text[:120]}") print(f" → 共收到 {json_count} 帧 JSON") return json_count def send_cmd(s, cmd_str): full = cmd_str + '\n' s.write(full.encode()) s.flush() print(f"\n[{time.strftime('%H:%M:%S')}] >>> TX {cmd_str}") # ===== 主流程 ===== print(f"Opening {PORT} @ {BAUD}...") s = open_s() print(f"OK.\n") # 先清掉板子可能积压的缓冲 watch(s, 3, "观察3秒(清积压)") # 先发 sm2 停止 → 等 12 秒(至少 2 帧 JSON) send_cmd(s, '{"zt":"sm2","neirong":"02"}') watch(s, 12, "等待 sm2=02 生效") # 发 sm2 启动 → 等 12 秒 send_cmd(s, '{"zt":"sm2","neirong":"01"}') watch(s, 12, "等待 sm2=01 生效 → 蜂鸣器应响") # 发 xy1 启动 → 等 12 秒 send_cmd(s, '{"zt":"xy1","neirong":"01"}') watch(s, 12, "等待 xy1=01 生效 → 蜂鸣器应响 + 血氧开始上报") # 发 xy1 停止 → 等 8 秒 send_cmd(s, '{"zt":"xy1","neirong":"02"}') watch(s, 8, "等待 xy1=02 生效") s.close() print("\n=== 完成 ===")