long_term2.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/usr/bin/env python3
  2. """鲁棒版长测:自动重连 + 每秒心跳 + 命令注入"""
  3. import serial, time, json, threading, os, sys
  4. PORT, BAUD = 'COM9', 115200
  5. LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'long_term.log')
  6. class Watcher:
  7. def __init__(self):
  8. self.lock = threading.Lock()
  9. self.reset()
  10. def reset(self):
  11. self.start = time.time()
  12. self.json_cnt = 0
  13. self.last_json = 0
  14. self.json_fail_cnt = 0
  15. self.last_xy1_val = None
  16. self.cmd_ok = 0
  17. self.cmd_fail = 0
  18. def mins(self):
  19. return int((time.time() - self.start) / 60)
  20. def log(msg):
  21. ts = time.strftime('%H:%M:%S')
  22. line = f"[{ts}] {msg}"
  23. print(line, flush=True)
  24. with open(LOG_FILE, 'a', encoding='utf-8') as f:
  25. f.write(line + '\n')
  26. def open_serial():
  27. for attempt in range(5):
  28. try:
  29. s = serial.Serial(PORT, BAUD, timeout=0.1)
  30. log(f"串口打开成功 (attempt {attempt+1})")
  31. return s
  32. except Exception as e:
  33. log(f"打开串口失败 {e},5秒后重试...")
  34. time.sleep(5)
  35. return None
  36. def run():
  37. W = Watcher()
  38. s = open_serial()
  39. if not s: return
  40. log(f"=== 长时间测试启动 ({PORT}@{BAUD}) ===")
  41. line_buf = b''
  42. cmd_queue = ['{"zt":"xy1","neirong":"01"}', '{"zt":"sm2","neirong":"01"}']
  43. cmd_idx = 0
  44. next_cmd_time = W.start + 20 # 20秒后开始
  45. next_summary_time = W.start + 60
  46. while True:
  47. try:
  48. # 自动命令注入
  49. now = time.time()
  50. if now >= next_cmd_time:
  51. cmd = cmd_queue[cmd_idx % len(cmd_queue)]
  52. cmd_idx += 1
  53. try:
  54. s.write((cmd + '\n').encode())
  55. s.flush()
  56. log(f">>> {cmd}")
  57. except Exception as e:
  58. log(f"TX_ERR {e}")
  59. next_cmd_time = now + 60
  60. # 摘要每分钟一次
  61. if now >= next_summary_time:
  62. elapsed = int(now - W.start)
  63. with W.lock:
  64. log(f"⏱ {W.mins()}m | JSON={W.json_cnt} | 命令 OK={W.cmd_ok} FAIL={W.cmd_fail}")
  65. next_summary_time = now + 60
  66. # 读数据
  67. data = s.read(256)
  68. if not data: continue
  69. for b in data:
  70. if b in (b'\r', b'\n'):
  71. if not line_buf: continue
  72. text = line_buf.decode('ascii', errors='replace')
  73. line_buf = b''
  74. if text.startswith('{'):
  75. try:
  76. d = json.loads(text)
  77. with W.lock:
  78. W.json_cnt += 1
  79. W.last_json = now
  80. xl1 = d.get('xl1', '') or '(空)'
  81. xy1 = d.get('xy1', '') or '(空)'
  82. sm2 = d.get('sm2', '') or '(空)'
  83. xl2 = d.get('xl2', '') or '(空)'
  84. hx2 = d.get('hx2', '') or '(空)'
  85. with W.lock:
  86. jc = W.json_cnt
  87. log(f"JSON#{jc:>4} xl1={xl1} xy1={xy1} sm2={sm2} xl2={xl2} hx2={hx2}")
  88. except Exception as e:
  89. log(f"JSON? {text[:100]}")
  90. elif text.startswith('SM7OK'):
  91. pass # 睡眠带调试,不刷屏
  92. elif text.startswith('DBG') or text.startswith('FRX') or text.startswith('FT6'):
  93. pass
  94. else:
  95. log(f"DBG {text[:100]}")
  96. else:
  97. line_buf += bytes([b])
  98. except Exception as e:
  99. log(f"主循环错误 {e}")
  100. try: s.close()
  101. except: pass
  102. s = open_serial()
  103. time.sleep(3)
  104. if __name__ == '__main__':
  105. try:
  106. run()
  107. except KeyboardInterrupt:
  108. log("Ctrl+C 停止")