| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 控制台自动化测试脚本(面向植物病菌孢子捕捉系统主控固件)
- 前置条件(现场接线):
- * 调试/控制台口(UART1, 115200-8N1) 接 PC 的 COM 口(默认 COM3)
- * UART2(RTU/DTU 口) 的 TX-RX 短接(自环回)
- * UART4(串口屏口) 的 TX-RX 短接(自环回)
- 测试项:
- T0 设备存活与控制台连通性
- T1 设备/驱动枚举(list_device 应含 uart1/uart2/uart4)
- T2 线程栈预算(解析 list_thread 的 max used 列;校验 Modbus 线程栈已放大)
- T3 UART2 自环回(统计 uart2 接收字节增长;无外部设备接入时的闭环流量)
- T4 UART4 自环回(ctr_lamp/ctr_led 触发 HMI 写 → 回环 → uart4 接收字节增长)
- T5 RTU 安全重启路径回归(cmd_rtu_restart 后串口可恢复、回环仍工作)
- T6 稳定性监测(扫描崩溃特征:stack overflow / hard fault / bus fault ...)
- T7 固件内建环回自检(若固件含 uart_loop_test 命令则执行精确校验)
- 用法:
- python console_test.py [--port COM3] [--baud 115200] [--monitor 60] [--skip-restart]
- 输出:
- doc/test_logs/console_<时间戳>.log 原始控制台日志
- doc/test_logs/自动化测试结果_<时间戳>.md 测试报告
- """
- import argparse
- import os
- import re
- import sys
- import time
- import datetime
- import serial
- ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
- CRASH_RE = re.compile(
- r"stack overflow|hard fault|hardfault|bus fault|usage fault|mem manage|"
- r"PRECISERR|IMPRECISERR|assert failed|data abort",
- re.IGNORECASE,
- )
- CRASH_THREAD_ROW_RE = re.compile(
- r"^(?P<name>\S+)\s+(?P<pri>\d+)\s+(?P<status>\S+)\s+"
- r"0x(?P<sp>[0-9a-fA-F]+)\s+0x(?P<size>[0-9a-fA-F]+)\s+"
- r"(?P<used>\d+)%\s+0x(?P<tick>[0-9a-fA-F]+)\s+(?P<err>\d+)"
- )
- RX2_RE = re.compile(r"串口2累计接收字节[::]\s*(\d+)")
- RX4_RE = re.compile(r"串口4累计接收字节[::]\s*(\d+)")
- TX2_RE = re.compile(r"串口2累计发送字节[::]\s*(\d+)")
- TX4_RE = re.compile(r"串口4累计发送字节[::]\s*(\d+)")
- class Console(object):
- def __init__(self, port, baud, logpath):
- self.port = port
- self.baud = baud
- self.logpath = logpath
- self.ser = None
- self.logf = None
- self.buf = ""
- def open(self):
- self.ser = serial.Serial(
- port=self.port, baudrate=self.baud, bytesize=8,
- parity="N", stopbits=1, timeout=0.05, write_timeout=1.0,
- )
- self.logf = open(self.logpath, "a", encoding="utf-8")
- self.raw("\n===== console opened %s @ %d =====\n" %
- (self.port, self.baud))
- def close(self):
- if self.logf:
- self.logf.flush()
- self.logf.close()
- self.logf = None
- if self.ser and self.ser.is_open:
- self.ser.close()
- def raw(self, text):
- if self.logf:
- self.logf.write(text)
- self.logf.flush()
- sys.stdout.write(text)
- sys.stdout.flush()
- def read_until_idle(self, idle=0.6, max_wait=8.0):
- """读到连续 idle 秒无数据为止(或超时)"""
- got = []
- t0 = time.time()
- last = time.time()
- while True:
- n = self.ser.in_waiting
- if n:
- data = self.ser.read(n)
- if data:
- got.append(data)
- last = time.time()
- else:
- time.sleep(0.03)
- now = time.time()
- if now - last >= idle or now - t0 >= max_wait:
- break
- text = b"".join(got).decode("utf-8", errors="replace")
- self.raw(text)
- self.buf += text
- return text
- def send(self, cmd, crlf="\r\n"):
- self.raw("\n>>> %s\n" % cmd)
- self.ser.write((cmd + crlf).encode())
- def cmd(self, cmd, idle=0.6, max_wait=8.0):
- self.send(cmd)
- return self.read_until_idle(idle=idle, max_wait=max_wait)
- def drain(self, seconds=1.0):
- return self.read_until_idle(idle=seconds, max_wait=seconds + 1)
- class TestReport(object):
- def __init__(self):
- self.rows = []
- self.logs = []
- def add(self, name, ok, detail):
- tag = "PASS" if ok else ("FAIL" if ok is False else "SKIP")
- self.rows.append((name, tag, detail))
- print("[%s] %s - %s" % (tag, name, detail))
- def note(self, text):
- self.logs.append(text)
- def crash_free(self, text):
- m = CRASH_RE.search(ANSI_RE.sub("", text))
- return (m is None), (m.group(0) if m else "")
- def markdown(self, extra):
- lines = []
- lines.append("# 控制台自动化测试结果\n")
- lines.append("- 生成时间: %s" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
- lines.append("- 串口: %s @ %d 8N1" % (extra.get("port"), extra.get("baud")))
- lines.append("- 接线: UART2 TX-RX 短接 / UART4 TX-RX 短接 / 调试口接 PC\n")
- lines.append("| 测试项 | 结果 | 说明 |")
- lines.append("| --- | --- | --- |")
- for name, tag, detail in self.rows:
- lines.append("| %s | **%s** | %s |" % (name, tag, detail.replace("|", "/")))
- if extra.get("stacks"):
- lines.append("\n## 线程栈实测(list_thread 的 max used)\n")
- lines.append("| 线程 | 栈大小(B) | max used | 占用率 | 状态 |")
- lines.append("| --- | --- | --- | --- | --- |")
- for r in extra["stacks"]:
- lines.append("| %s | %d | %d | %d%% | %s |" %
- (r["name"], r["size"], r["used_b"], r["used_pct"], r["status"]))
- if extra.get("counters"):
- lines.append("\n## 自环回流量统计\n")
- lines.append("| 项目 | 起始 | 结束 | 增量(B) |")
- lines.append("| --- | --- | --- | --- |")
- for k, (a, b) in extra["counters"].items():
- lines.append("| %s | %d | %d | %d |" % (k, a, b, b - a))
- if self.logs:
- lines.append("\n## 其它观测\n")
- for t in self.logs:
- lines.append("- " + t)
- lines.append("\n## 原始日志\n")
- lines.append("`%s`\n" % extra.get("logpath"))
- return "\n".join(lines)
- def parse_threads(text):
- rows = []
- for line in ANSI_RE.sub("", text).splitlines():
- m = CRASH_THREAD_ROW_RE.search(line.strip())
- if not m:
- continue
- size = int(m.group("size"), 16)
- pct = int(m.group("used"))
- rows.append({
- "name": m.group("name"),
- "status": m.group("status"),
- "size": size,
- "used_pct": pct,
- "used_b": size * pct // 100,
- })
- return rows
- def last_match(regex, text, default=None):
- vals = regex.findall(ANSI_RE.sub("", text))
- return int(vals[-1]) if vals else default
- def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--port", default="COM3")
- ap.add_argument("--baud", type=int, default=115200)
- ap.add_argument("--monitor", type=int, default=60, help="稳定性监测秒数")
- ap.add_argument("--skip-restart", action="store_true")
- ap.add_argument("--watch", type=int, default=0, help="纯监视模式秒数")
- args = ap.parse_args()
- if args.watch > 0:
- return watch(args)
- here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # doc/
- outdir = os.path.join(here, "test_logs")
- os.makedirs(outdir, exist_ok=True)
- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- logpath = os.path.join(outdir, "console_%s.log" % ts)
- mdpath = os.path.join(outdir, "自动化测试结果_%s.md" % ts)
- rpt = TestReport()
- con = Console(args.port, args.baud, logpath)
- try:
- con.open()
- except Exception as e:
- print("打开 %s 失败: %s" % (args.port, e))
- print("请确认串口未被其它终端占用后重试。")
- return 2
- extra = {"port": args.port, "baud": args.baud, "logpath": logpath,
- "stacks": [], "counters": {}}
- try:
- # ---------- T0 存活 + T1 设备枚举 ----------
- con.drain(1.5) # 先收集启动/周期日志
- alive_ok, crash = rpt.crash_free(con.buf)
- rpt.add("T0 设备存活/无崩溃日志", alive_ok,
- "未发现崩溃特征" if alive_ok else ("发现: " + crash))
- t1 = con.cmd("list_device")
- dev_ok = ("uart1" in t1) and ("uart2" in t1) and ("uart4" in t1)
- rpt.add("T1 设备枚举(uart1/2/4)", dev_ok,
- "uart1/uart2/uart4 均在设备表" if dev_ok else "设备表缺少期望串口")
- # ---------- T2 线程栈预算 ----------
- t2 = con.cmd("list_thread", idle=0.8, max_wait=6)
- stacks = parse_threads(t2)
- extra["stacks"] = sorted(stacks, key=lambda r: -r["used_pct"])
- if stacks:
- worst = extra["stacks"][0]
- over = [r for r in stacks if r["used_pct"] >= 80]
- mbth = [r for r in stacks if r["name"].startswith("md_m_s")]
- mb_ok = bool(mbth) and all(r["size"] >= 1024 for r in mbth)
- rpt.add("T2 线程栈预算", len(over) == 0,
- "共 %d 个线程, 最高占用 %s=%d%%; 无 >=80%% 的线程"
- % (len(stacks), worst["name"], worst["used_pct"])
- if not over else "存在高占用线程: " +
- ", ".join("%s=%d%%" % (r["name"], r["used_pct"]) for r in over))
- rpt.add("T2b Modbus 线程栈已放大(>=1024B)", mb_ok,
- ", ".join("%s=%dB" % (r["name"], r["size"]) for r in mbth) or
- "未找到 md_m_send/md_m_poll")
- else:
- rpt.add("T2 线程栈预算", None, "未能解析 list_thread 输出")
- # ---------- T3/T4 自环回:基线计数 ----------
- base = con.read_until_idle(idle=schedule_idle(args), max_wait=args.monitor)
- c2a = last_match(RX2_RE, base)
- c4a = last_match(RX4_RE, base)
- done_ok, crash = rpt.crash_free(base)
- # T4 主动触发 UART4 写(HMI 指令回环)
- con.cmd("ctr_lamp ON")
- con.cmd("ctr_led ON")
- time.sleep(0.5)
- con.cmd("ctr_lamp OFF")
- con.cmd("ctr_led OFF")
- # ---------- T5 RTU 安全重启回归 ----------
- if not args.skip_restart:
- rpt.add("T5 RTU 安全重启(关闭->30s->恢复->重注册RX)",
- True, "开始执行 cmd_rtu_restart ...")
- con.cmd("cmd_rtu_restart", idle=1.0, max_wait=5)
- t_after = con.read_until_idle(idle=schedule_idle(args), max_wait=60)
- alive2, crash2 = rpt.crash_free(t_after)
- rpt.add("T5b 重启后设备存活", alive2,
- "未发现崩溃特征" if alive2 else ("发现: " + crash2))
- t5 = con.cmd("list_thread", idle=0.8, max_wait=6)
- rpt.add("T5c 重启后线程表可读", len(parse_threads(t5)) > 3,
- "解析到 %d 个线程" % len(parse_threads(t5)))
- # ---------- T7 固件内建环回自检(可选) ----------
- t7 = con.cmd("uart_loop_test", idle=0.8, max_wait=5)
- if re.search(r"not found|未找到|command not", t7, re.IGNORECASE):
- rpt.add("T7 固件内建环回自检(uart_loop_test)", None,
- "当前固件未包含该命令(需烧录含自检命令的版本)")
- else:
- ok_all = True
- for plate in (("2", "64"), ("2", "512"), ("2", "2048"), ("4", "64"), ("4", "512")):
- out = con.cmd("uart_loop_test %s %s" % plate, idle=1.0, max_wait=12)
- if "PASS" not in out:
- ok_all = False
- rpt.add("T7 固件内建环回自检(uart_loop_test)", ok_all,
- "全部用例 PASS" if ok_all else "存在 FAIL 用例,详见日志")
- # ---------- T3/T6 最终计数 + 稳定性 ----------
- tail = con.read_until_idle(idle=schedule_idle(args), max_wait=args.monitor)
- c2b = last_match(RX2_RE, tail, c2a)
- c4b = last_match(RX4_RE, tail, c4a)
- c2xa = last_match(TX2_RE, base)
- c2xb = last_match(TX2_RE, tail, c2xa)
- if c2a is not None and c2b is not None:
- extra["counters"]["uart2_rx"] = (c2a, c2b)
- extra["counters"]["uart4_rx"] = (c4a or 0, c4b or 0)
- if c2xa is not None and c2xb is not None:
- extra["counters"]["uart2_tx"] = (c2xa, c2xb)
- rpt.add("T3 UART2 自环回(接收字节增长)", (c2b - c2a) > 0,
- "uart2 rx: %d -> %d (+%d)" % (c2a, c2b, c2b - c2a))
- rpt.add("T4 UART4 自环回(接收字节增长)", ((c4b or 0) - (c4a or 0)) > 0,
- "uart4 rx: %d -> %d (+%d)" % (c4a or 0, c4b or 0, (c4b or 0) - (c4a or 0)))
- else:
- rpt.add("T3 UART2 自环回", None,
- "未捕获到 sys_monitor 的串口计数日志(需要 LOG_D 级别日志)")
- whole = con.buf
- ok, crash = rpt.crash_free(whole)
- rpt.add("T6 全过程稳定性(无崩溃特征)", ok,
- "全程未出现 stack overflow/hard fault" if ok else ("发现: " + crash))
- rpt.note("累计捕获控制台日志 %d 字节" % len(whole))
- finally:
- con.close()
- md = rpt.markdown(extra)
- with open(mdpath, "w", encoding="utf-8") as f:
- f.write(md)
- print("\n=== 测试报告: %s ===" % mdpath)
- print("\n".join(md.splitlines()[4:16]))
- return 0
- def watch(args):
- """长时监视:周期采样串口计数/上传条数,捕获一次自然上传以验证自环回"""
- import re as _re
- here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- outdir = os.path.join(here, "test_logs")
- os.makedirs(outdir, exist_ok=True)
- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- logpath = os.path.join(outdir, "watch_%s.log" % ts)
- con = Console(args.port, args.baud, logpath)
- con.open()
- up_re = _re.compile(r"累计上传数据[::]\s*(\d+)")
- t_end = time.time() + args.watch
- last = {"uart2_tx": None, "uart2_rx": None, "uart4_tx": None,
- "uart4_rx": None, "upload": None}
- events = []
- crash_hit = None
- print("watch for %d s (sample every 15s) ..." % args.watch)
- try:
- while time.time() < t_end:
- txt = con.read_until_idle(idle=15.0, max_wait=20.0)
- clean = ANSI_RE.sub("", txt)
- for line in clean.splitlines():
- if CRASH_RE.search(line):
- crash_hit = line.strip()
- events.append(("CRASH", line.strip()))
- m = last_match(TX2_RE, clean)
- if m is None:
- m = last_match(RX2_RE, clean)
- vals = {
- "uart2_tx": last_match(TX2_RE, clean),
- "uart2_rx": last_match(RX2_RE, clean),
- "uart4_tx": last_match(TX4_RE, clean),
- "uart4_rx": last_match(RX4_RE, clean),
- "upload": last_match(up_re, clean),
- }
- stamp = datetime.datetime.now().strftime("%H:%M:%S")
- delta = []
- for k in vals:
- v = vals[k]
- if v is None:
- continue
- if last[k] is not None and v != last[k]:
- delta.append("%s %d->%d(+%d)" % (k, last[k], v, v - last[k]))
- last[k] = v
- info = ", ".join("%s=%s" % (k, vals[k]) for k in vals if vals[k] is not None)
- line_out = "[%s] %s%s" % (stamp, info, (" || " + "; ".join(delta)) if delta else "")
- print(line_out)
- events.append(("SAMPLE", line_out))
- finally:
- con.close()
- print("\n===== watch 汇总 =====")
- print("崩溃特征: %s" % (crash_hit if crash_hit else "无"))
- for tag, line in events:
- if tag == "SAMPLE" and "->" in line:
- print("变化事件: " + line)
- return 0
- def schedule_idle(args):
- """等待 sys_monitor 的 10s 周期日志至少出现两次"""
- return 11.0
- if __name__ == "__main__":
- sys.exit(main())
|