console_test.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 控制台自动化测试脚本(面向植物病菌孢子捕捉系统主控固件)
  5. 前置条件(现场接线):
  6. * 调试/控制台口(UART1, 115200-8N1) 接 PC 的 COM 口(默认 COM3)
  7. * UART2(RTU/DTU 口) 的 TX-RX 短接(自环回)
  8. * UART4(串口屏口) 的 TX-RX 短接(自环回)
  9. 测试项:
  10. T0 设备存活与控制台连通性
  11. T1 设备/驱动枚举(list_device 应含 uart1/uart2/uart4)
  12. T2 线程栈预算(解析 list_thread 的 max used 列;校验 Modbus 线程栈已放大)
  13. T3 UART2 自环回(统计 uart2 接收字节增长;无外部设备接入时的闭环流量)
  14. T4 UART4 自环回(ctr_lamp/ctr_led 触发 HMI 写 → 回环 → uart4 接收字节增长)
  15. T5 RTU 安全重启路径回归(cmd_rtu_restart 后串口可恢复、回环仍工作)
  16. T6 稳定性监测(扫描崩溃特征:stack overflow / hard fault / bus fault ...)
  17. T7 固件内建环回自检(若固件含 uart_loop_test 命令则执行精确校验)
  18. 用法:
  19. python console_test.py [--port COM3] [--baud 115200] [--monitor 60] [--skip-restart]
  20. 输出:
  21. doc/test_logs/console_<时间戳>.log 原始控制台日志
  22. doc/test_logs/自动化测试结果_<时间戳>.md 测试报告
  23. """
  24. import argparse
  25. import os
  26. import re
  27. import sys
  28. import time
  29. import datetime
  30. import serial
  31. ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
  32. CRASH_RE = re.compile(
  33. r"stack overflow|hard fault|hardfault|bus fault|usage fault|mem manage|"
  34. r"PRECISERR|IMPRECISERR|assert failed|data abort",
  35. re.IGNORECASE,
  36. )
  37. CRASH_THREAD_ROW_RE = re.compile(
  38. r"^(?P<name>\S+)\s+(?P<pri>\d+)\s+(?P<status>\S+)\s+"
  39. r"0x(?P<sp>[0-9a-fA-F]+)\s+0x(?P<size>[0-9a-fA-F]+)\s+"
  40. r"(?P<used>\d+)%\s+0x(?P<tick>[0-9a-fA-F]+)\s+(?P<err>\d+)"
  41. )
  42. RX2_RE = re.compile(r"串口2累计接收字节[::]\s*(\d+)")
  43. RX4_RE = re.compile(r"串口4累计接收字节[::]\s*(\d+)")
  44. TX2_RE = re.compile(r"串口2累计发送字节[::]\s*(\d+)")
  45. TX4_RE = re.compile(r"串口4累计发送字节[::]\s*(\d+)")
  46. class Console(object):
  47. def __init__(self, port, baud, logpath):
  48. self.port = port
  49. self.baud = baud
  50. self.logpath = logpath
  51. self.ser = None
  52. self.logf = None
  53. self.buf = ""
  54. def open(self):
  55. self.ser = serial.Serial(
  56. port=self.port, baudrate=self.baud, bytesize=8,
  57. parity="N", stopbits=1, timeout=0.05, write_timeout=1.0,
  58. )
  59. self.logf = open(self.logpath, "a", encoding="utf-8")
  60. self.raw("\n===== console opened %s @ %d =====\n" %
  61. (self.port, self.baud))
  62. def close(self):
  63. if self.logf:
  64. self.logf.flush()
  65. self.logf.close()
  66. self.logf = None
  67. if self.ser and self.ser.is_open:
  68. self.ser.close()
  69. def raw(self, text):
  70. if self.logf:
  71. self.logf.write(text)
  72. self.logf.flush()
  73. sys.stdout.write(text)
  74. sys.stdout.flush()
  75. def read_until_idle(self, idle=0.6, max_wait=8.0):
  76. """读到连续 idle 秒无数据为止(或超时)"""
  77. got = []
  78. t0 = time.time()
  79. last = time.time()
  80. while True:
  81. n = self.ser.in_waiting
  82. if n:
  83. data = self.ser.read(n)
  84. if data:
  85. got.append(data)
  86. last = time.time()
  87. else:
  88. time.sleep(0.03)
  89. now = time.time()
  90. if now - last >= idle or now - t0 >= max_wait:
  91. break
  92. text = b"".join(got).decode("utf-8", errors="replace")
  93. self.raw(text)
  94. self.buf += text
  95. return text
  96. def send(self, cmd, crlf="\r\n"):
  97. self.raw("\n>>> %s\n" % cmd)
  98. self.ser.write((cmd + crlf).encode())
  99. def cmd(self, cmd, idle=0.6, max_wait=8.0):
  100. self.send(cmd)
  101. return self.read_until_idle(idle=idle, max_wait=max_wait)
  102. def drain(self, seconds=1.0):
  103. return self.read_until_idle(idle=seconds, max_wait=seconds + 1)
  104. class TestReport(object):
  105. def __init__(self):
  106. self.rows = []
  107. self.logs = []
  108. def add(self, name, ok, detail):
  109. tag = "PASS" if ok else ("FAIL" if ok is False else "SKIP")
  110. self.rows.append((name, tag, detail))
  111. print("[%s] %s - %s" % (tag, name, detail))
  112. def note(self, text):
  113. self.logs.append(text)
  114. def crash_free(self, text):
  115. m = CRASH_RE.search(ANSI_RE.sub("", text))
  116. return (m is None), (m.group(0) if m else "")
  117. def markdown(self, extra):
  118. lines = []
  119. lines.append("# 控制台自动化测试结果\n")
  120. lines.append("- 生成时间: %s" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
  121. lines.append("- 串口: %s @ %d 8N1" % (extra.get("port"), extra.get("baud")))
  122. lines.append("- 接线: UART2 TX-RX 短接 / UART4 TX-RX 短接 / 调试口接 PC\n")
  123. lines.append("| 测试项 | 结果 | 说明 |")
  124. lines.append("| --- | --- | --- |")
  125. for name, tag, detail in self.rows:
  126. lines.append("| %s | **%s** | %s |" % (name, tag, detail.replace("|", "/")))
  127. if extra.get("stacks"):
  128. lines.append("\n## 线程栈实测(list_thread 的 max used)\n")
  129. lines.append("| 线程 | 栈大小(B) | max used | 占用率 | 状态 |")
  130. lines.append("| --- | --- | --- | --- | --- |")
  131. for r in extra["stacks"]:
  132. lines.append("| %s | %d | %d | %d%% | %s |" %
  133. (r["name"], r["size"], r["used_b"], r["used_pct"], r["status"]))
  134. if extra.get("counters"):
  135. lines.append("\n## 自环回流量统计\n")
  136. lines.append("| 项目 | 起始 | 结束 | 增量(B) |")
  137. lines.append("| --- | --- | --- | --- |")
  138. for k, (a, b) in extra["counters"].items():
  139. lines.append("| %s | %d | %d | %d |" % (k, a, b, b - a))
  140. if self.logs:
  141. lines.append("\n## 其它观测\n")
  142. for t in self.logs:
  143. lines.append("- " + t)
  144. lines.append("\n## 原始日志\n")
  145. lines.append("`%s`\n" % extra.get("logpath"))
  146. return "\n".join(lines)
  147. def parse_threads(text):
  148. rows = []
  149. for line in ANSI_RE.sub("", text).splitlines():
  150. m = CRASH_THREAD_ROW_RE.search(line.strip())
  151. if not m:
  152. continue
  153. size = int(m.group("size"), 16)
  154. pct = int(m.group("used"))
  155. rows.append({
  156. "name": m.group("name"),
  157. "status": m.group("status"),
  158. "size": size,
  159. "used_pct": pct,
  160. "used_b": size * pct // 100,
  161. })
  162. return rows
  163. def last_match(regex, text, default=None):
  164. vals = regex.findall(ANSI_RE.sub("", text))
  165. return int(vals[-1]) if vals else default
  166. def main():
  167. ap = argparse.ArgumentParser()
  168. ap.add_argument("--port", default="COM3")
  169. ap.add_argument("--baud", type=int, default=115200)
  170. ap.add_argument("--monitor", type=int, default=60, help="稳定性监测秒数")
  171. ap.add_argument("--skip-restart", action="store_true")
  172. ap.add_argument("--watch", type=int, default=0, help="纯监视模式秒数")
  173. args = ap.parse_args()
  174. if args.watch > 0:
  175. return watch(args)
  176. here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # doc/
  177. outdir = os.path.join(here, "test_logs")
  178. os.makedirs(outdir, exist_ok=True)
  179. ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  180. logpath = os.path.join(outdir, "console_%s.log" % ts)
  181. mdpath = os.path.join(outdir, "自动化测试结果_%s.md" % ts)
  182. rpt = TestReport()
  183. con = Console(args.port, args.baud, logpath)
  184. try:
  185. con.open()
  186. except Exception as e:
  187. print("打开 %s 失败: %s" % (args.port, e))
  188. print("请确认串口未被其它终端占用后重试。")
  189. return 2
  190. extra = {"port": args.port, "baud": args.baud, "logpath": logpath,
  191. "stacks": [], "counters": {}}
  192. try:
  193. # ---------- T0 存活 + T1 设备枚举 ----------
  194. con.drain(1.5) # 先收集启动/周期日志
  195. alive_ok, crash = rpt.crash_free(con.buf)
  196. rpt.add("T0 设备存活/无崩溃日志", alive_ok,
  197. "未发现崩溃特征" if alive_ok else ("发现: " + crash))
  198. t1 = con.cmd("list_device")
  199. dev_ok = ("uart1" in t1) and ("uart2" in t1) and ("uart4" in t1)
  200. rpt.add("T1 设备枚举(uart1/2/4)", dev_ok,
  201. "uart1/uart2/uart4 均在设备表" if dev_ok else "设备表缺少期望串口")
  202. # ---------- T2 线程栈预算 ----------
  203. t2 = con.cmd("list_thread", idle=0.8, max_wait=6)
  204. stacks = parse_threads(t2)
  205. extra["stacks"] = sorted(stacks, key=lambda r: -r["used_pct"])
  206. if stacks:
  207. worst = extra["stacks"][0]
  208. over = [r for r in stacks if r["used_pct"] >= 80]
  209. mbth = [r for r in stacks if r["name"].startswith("md_m_s")]
  210. mb_ok = bool(mbth) and all(r["size"] >= 1024 for r in mbth)
  211. rpt.add("T2 线程栈预算", len(over) == 0,
  212. "共 %d 个线程, 最高占用 %s=%d%%; 无 >=80%% 的线程"
  213. % (len(stacks), worst["name"], worst["used_pct"])
  214. if not over else "存在高占用线程: " +
  215. ", ".join("%s=%d%%" % (r["name"], r["used_pct"]) for r in over))
  216. rpt.add("T2b Modbus 线程栈已放大(>=1024B)", mb_ok,
  217. ", ".join("%s=%dB" % (r["name"], r["size"]) for r in mbth) or
  218. "未找到 md_m_send/md_m_poll")
  219. else:
  220. rpt.add("T2 线程栈预算", None, "未能解析 list_thread 输出")
  221. # ---------- T3/T4 自环回:基线计数 ----------
  222. base = con.read_until_idle(idle=schedule_idle(args), max_wait=args.monitor)
  223. c2a = last_match(RX2_RE, base)
  224. c4a = last_match(RX4_RE, base)
  225. done_ok, crash = rpt.crash_free(base)
  226. # T4 主动触发 UART4 写(HMI 指令回环)
  227. con.cmd("ctr_lamp ON")
  228. con.cmd("ctr_led ON")
  229. time.sleep(0.5)
  230. con.cmd("ctr_lamp OFF")
  231. con.cmd("ctr_led OFF")
  232. # ---------- T5 RTU 安全重启回归 ----------
  233. if not args.skip_restart:
  234. rpt.add("T5 RTU 安全重启(关闭->30s->恢复->重注册RX)",
  235. True, "开始执行 cmd_rtu_restart ...")
  236. con.cmd("cmd_rtu_restart", idle=1.0, max_wait=5)
  237. t_after = con.read_until_idle(idle=schedule_idle(args), max_wait=60)
  238. alive2, crash2 = rpt.crash_free(t_after)
  239. rpt.add("T5b 重启后设备存活", alive2,
  240. "未发现崩溃特征" if alive2 else ("发现: " + crash2))
  241. t5 = con.cmd("list_thread", idle=0.8, max_wait=6)
  242. rpt.add("T5c 重启后线程表可读", len(parse_threads(t5)) > 3,
  243. "解析到 %d 个线程" % len(parse_threads(t5)))
  244. # ---------- T7 固件内建环回自检(可选) ----------
  245. t7 = con.cmd("uart_loop_test", idle=0.8, max_wait=5)
  246. if re.search(r"not found|未找到|command not", t7, re.IGNORECASE):
  247. rpt.add("T7 固件内建环回自检(uart_loop_test)", None,
  248. "当前固件未包含该命令(需烧录含自检命令的版本)")
  249. else:
  250. ok_all = True
  251. for plate in (("2", "64"), ("2", "512"), ("2", "2048"), ("4", "64"), ("4", "512")):
  252. out = con.cmd("uart_loop_test %s %s" % plate, idle=1.0, max_wait=12)
  253. if "PASS" not in out:
  254. ok_all = False
  255. rpt.add("T7 固件内建环回自检(uart_loop_test)", ok_all,
  256. "全部用例 PASS" if ok_all else "存在 FAIL 用例,详见日志")
  257. # ---------- T3/T6 最终计数 + 稳定性 ----------
  258. tail = con.read_until_idle(idle=schedule_idle(args), max_wait=args.monitor)
  259. c2b = last_match(RX2_RE, tail, c2a)
  260. c4b = last_match(RX4_RE, tail, c4a)
  261. c2xa = last_match(TX2_RE, base)
  262. c2xb = last_match(TX2_RE, tail, c2xa)
  263. if c2a is not None and c2b is not None:
  264. extra["counters"]["uart2_rx"] = (c2a, c2b)
  265. extra["counters"]["uart4_rx"] = (c4a or 0, c4b or 0)
  266. if c2xa is not None and c2xb is not None:
  267. extra["counters"]["uart2_tx"] = (c2xa, c2xb)
  268. rpt.add("T3 UART2 自环回(接收字节增长)", (c2b - c2a) > 0,
  269. "uart2 rx: %d -> %d (+%d)" % (c2a, c2b, c2b - c2a))
  270. rpt.add("T4 UART4 自环回(接收字节增长)", ((c4b or 0) - (c4a or 0)) > 0,
  271. "uart4 rx: %d -> %d (+%d)" % (c4a or 0, c4b or 0, (c4b or 0) - (c4a or 0)))
  272. else:
  273. rpt.add("T3 UART2 自环回", None,
  274. "未捕获到 sys_monitor 的串口计数日志(需要 LOG_D 级别日志)")
  275. whole = con.buf
  276. ok, crash = rpt.crash_free(whole)
  277. rpt.add("T6 全过程稳定性(无崩溃特征)", ok,
  278. "全程未出现 stack overflow/hard fault" if ok else ("发现: " + crash))
  279. rpt.note("累计捕获控制台日志 %d 字节" % len(whole))
  280. finally:
  281. con.close()
  282. md = rpt.markdown(extra)
  283. with open(mdpath, "w", encoding="utf-8") as f:
  284. f.write(md)
  285. print("\n=== 测试报告: %s ===" % mdpath)
  286. print("\n".join(md.splitlines()[4:16]))
  287. return 0
  288. def watch(args):
  289. """长时监视:周期采样串口计数/上传条数,捕获一次自然上传以验证自环回"""
  290. import re as _re
  291. here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  292. outdir = os.path.join(here, "test_logs")
  293. os.makedirs(outdir, exist_ok=True)
  294. ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  295. logpath = os.path.join(outdir, "watch_%s.log" % ts)
  296. con = Console(args.port, args.baud, logpath)
  297. con.open()
  298. up_re = _re.compile(r"累计上传数据[::]\s*(\d+)")
  299. t_end = time.time() + args.watch
  300. last = {"uart2_tx": None, "uart2_rx": None, "uart4_tx": None,
  301. "uart4_rx": None, "upload": None}
  302. events = []
  303. crash_hit = None
  304. print("watch for %d s (sample every 15s) ..." % args.watch)
  305. try:
  306. while time.time() < t_end:
  307. txt = con.read_until_idle(idle=15.0, max_wait=20.0)
  308. clean = ANSI_RE.sub("", txt)
  309. for line in clean.splitlines():
  310. if CRASH_RE.search(line):
  311. crash_hit = line.strip()
  312. events.append(("CRASH", line.strip()))
  313. m = last_match(TX2_RE, clean)
  314. if m is None:
  315. m = last_match(RX2_RE, clean)
  316. vals = {
  317. "uart2_tx": last_match(TX2_RE, clean),
  318. "uart2_rx": last_match(RX2_RE, clean),
  319. "uart4_tx": last_match(TX4_RE, clean),
  320. "uart4_rx": last_match(RX4_RE, clean),
  321. "upload": last_match(up_re, clean),
  322. }
  323. stamp = datetime.datetime.now().strftime("%H:%M:%S")
  324. delta = []
  325. for k in vals:
  326. v = vals[k]
  327. if v is None:
  328. continue
  329. if last[k] is not None and v != last[k]:
  330. delta.append("%s %d->%d(+%d)" % (k, last[k], v, v - last[k]))
  331. last[k] = v
  332. info = ", ".join("%s=%s" % (k, vals[k]) for k in vals if vals[k] is not None)
  333. line_out = "[%s] %s%s" % (stamp, info, (" || " + "; ".join(delta)) if delta else "")
  334. print(line_out)
  335. events.append(("SAMPLE", line_out))
  336. finally:
  337. con.close()
  338. print("\n===== watch 汇总 =====")
  339. print("崩溃特征: %s" % (crash_hit if crash_hit else "无"))
  340. for tag, line in events:
  341. if tag == "SAMPLE" and "->" in line:
  342. print("变化事件: " + line)
  343. return 0
  344. def schedule_idle(args):
  345. """等待 sys_monitor 的 10s 周期日志至少出现两次"""
  346. return 11.0
  347. if __name__ == "__main__":
  348. sys.exit(main())