| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """在命令执行前后采集串口计数器,判断"自检发送的数据是否真的被硬件接收"。
- 用法: python counter_probe.py <port> <command> [pre_seconds] [post_seconds]
- """
- import re
- import sys
- import time
- import serial
- ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
- RX2 = re.compile(r"串口2累计接收字节[::]\s*(\d+)")
- TX2 = re.compile(r"串口2累计发送字节[::]\s*(\d+)")
- RX4 = re.compile(r"串口4累计接收字节[::]\s*(\d+)")
- TX4 = re.compile(r"串口4累计发送字节[::]\s*(\d+)")
- UP = re.compile(r"累计上传数据[::]\s*(\d+)")
- def collect(ser, seconds):
- """读取 seconds 秒,返回最后一次看到的各计数器值"""
- last = {}
- keys = [("rx2", RX2), ("tx2", TX2), ("rx4", RX4), ("tx4", TX4), ("up", UP)]
- deadline = time.time() + seconds
- buf = ""
- while time.time() < deadline:
- chunk = ser.read(4096)
- if not chunk:
- continue
- buf += ANSI.sub("", chunk.decode("utf-8", "replace"))
- for name, rx in keys:
- m = rx.findall(buf)
- if m:
- last[name] = int(m[-1])
- # 保留尾部,避免 buf 无限增长(一个报文可能跨 chunk)
- if len(buf) > 20000:
- buf = buf[-4000:]
- return last
- def main():
- port = sys.argv[1] if len(sys.argv) > 1 else "COM3"
- cmd = sys.argv[2] if len(sys.argv) > 2 else "uart_loop_test 2 64"
- pre = float(sys.argv[3]) if len(sys.argv) > 3 else 4.0
- post = float(sys.argv[4]) if len(sys.argv) > 4 else 8.0
- with serial.Serial(port, 115200, timeout=0.2, write_timeout=2) as ser:
- ser.reset_input_buffer()
- print("[*] 基线采集 %.0fs ..." % pre)
- before = collect(ser, pre)
- print(" before:", before)
- print("[*] 发送命令: %s" % cmd)
- ser.write(cmd.encode("utf-8", "replace") + b"\r\n")
- ser.flush()
- print("[*] 后置采集 %.0fs ..." % post)
- after = collect(ser, post)
- print(" after :", after)
- print("\n[*] 增量:")
- for k in ("rx2", "tx2", "rx4", "tx4", "up"):
- b, a = before.get(k), after.get(k)
- if b is None or a is None:
- print(" %-4s : (缺数据)" % k)
- else:
- print(" %-4s : %d -> %d (%+d)" % (k, b, a, a - b))
- return 0
- if __name__ == "__main__":
- sys.exit(main())
|