#!/usr/bin/env python3 """鲁棒版长测:自动重连 + 每秒心跳 + 命令注入""" import serial, time, json, threading, os, sys PORT, BAUD = 'COM9', 115200 LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'long_term.log') class Watcher: def __init__(self): self.lock = threading.Lock() self.reset() def reset(self): self.start = time.time() self.json_cnt = 0 self.last_json = 0 self.json_fail_cnt = 0 self.last_xy1_val = None self.cmd_ok = 0 self.cmd_fail = 0 def mins(self): return int((time.time() - self.start) / 60) def log(msg): ts = time.strftime('%H:%M:%S') line = f"[{ts}] {msg}" print(line, flush=True) with open(LOG_FILE, 'a', encoding='utf-8') as f: f.write(line + '\n') def open_serial(): for attempt in range(5): try: s = serial.Serial(PORT, BAUD, timeout=0.1) log(f"串口打开成功 (attempt {attempt+1})") return s except Exception as e: log(f"打开串口失败 {e},5秒后重试...") time.sleep(5) return None def run(): W = Watcher() s = open_serial() if not s: return log(f"=== 长时间测试启动 ({PORT}@{BAUD}) ===") line_buf = b'' cmd_queue = ['{"zt":"xy1","neirong":"01"}', '{"zt":"sm2","neirong":"01"}'] cmd_idx = 0 next_cmd_time = W.start + 20 # 20秒后开始 next_summary_time = W.start + 60 while True: try: # 自动命令注入 now = time.time() if now >= next_cmd_time: cmd = cmd_queue[cmd_idx % len(cmd_queue)] cmd_idx += 1 try: s.write((cmd + '\n').encode()) s.flush() log(f">>> {cmd}") except Exception as e: log(f"TX_ERR {e}") next_cmd_time = now + 60 # 摘要每分钟一次 if now >= next_summary_time: elapsed = int(now - W.start) with W.lock: log(f"⏱ {W.mins()}m | JSON={W.json_cnt} | 命令 OK={W.cmd_ok} FAIL={W.cmd_fail}") next_summary_time = now + 60 # 读数据 data = s.read(256) if not data: continue for b in data: if b in (b'\r', b'\n'): if not line_buf: continue text = line_buf.decode('ascii', errors='replace') line_buf = b'' if text.startswith('{'): try: d = json.loads(text) with W.lock: W.json_cnt += 1 W.last_json = now xl1 = d.get('xl1', '') or '(空)' xy1 = d.get('xy1', '') or '(空)' sm2 = d.get('sm2', '') or '(空)' xl2 = d.get('xl2', '') or '(空)' hx2 = d.get('hx2', '') or '(空)' with W.lock: jc = W.json_cnt log(f"JSON#{jc:>4} xl1={xl1} xy1={xy1} sm2={sm2} xl2={xl2} hx2={hx2}") except Exception as e: log(f"JSON? {text[:100]}") elif text.startswith('SM7OK'): pass # 睡眠带调试,不刷屏 elif text.startswith('DBG') or text.startswith('FRX') or text.startswith('FT6'): pass else: log(f"DBG {text[:100]}") else: line_buf += bytes([b]) except Exception as e: log(f"主循环错误 {e}") try: s.close() except: pass s = open_serial() time.sleep(3) if __name__ == '__main__': try: run() except KeyboardInterrupt: log("Ctrl+C 停止")