counter_probe.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """在命令执行前后采集串口计数器,判断"自检发送的数据是否真的被硬件接收"。
  4. 用法: python counter_probe.py <port> <command> [pre_seconds] [post_seconds]
  5. """
  6. import re
  7. import sys
  8. import time
  9. import serial
  10. ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
  11. RX2 = re.compile(r"串口2累计接收字节[::]\s*(\d+)")
  12. TX2 = re.compile(r"串口2累计发送字节[::]\s*(\d+)")
  13. RX4 = re.compile(r"串口4累计接收字节[::]\s*(\d+)")
  14. TX4 = re.compile(r"串口4累计发送字节[::]\s*(\d+)")
  15. UP = re.compile(r"累计上传数据[::]\s*(\d+)")
  16. def collect(ser, seconds):
  17. """读取 seconds 秒,返回最后一次看到的各计数器值"""
  18. last = {}
  19. keys = [("rx2", RX2), ("tx2", TX2), ("rx4", RX4), ("tx4", TX4), ("up", UP)]
  20. deadline = time.time() + seconds
  21. buf = ""
  22. while time.time() < deadline:
  23. chunk = ser.read(4096)
  24. if not chunk:
  25. continue
  26. buf += ANSI.sub("", chunk.decode("utf-8", "replace"))
  27. for name, rx in keys:
  28. m = rx.findall(buf)
  29. if m:
  30. last[name] = int(m[-1])
  31. # 保留尾部,避免 buf 无限增长(一个报文可能跨 chunk)
  32. if len(buf) > 20000:
  33. buf = buf[-4000:]
  34. return last
  35. def main():
  36. port = sys.argv[1] if len(sys.argv) > 1 else "COM3"
  37. cmd = sys.argv[2] if len(sys.argv) > 2 else "uart_loop_test 2 64"
  38. pre = float(sys.argv[3]) if len(sys.argv) > 3 else 4.0
  39. post = float(sys.argv[4]) if len(sys.argv) > 4 else 8.0
  40. with serial.Serial(port, 115200, timeout=0.2, write_timeout=2) as ser:
  41. ser.reset_input_buffer()
  42. print("[*] 基线采集 %.0fs ..." % pre)
  43. before = collect(ser, pre)
  44. print(" before:", before)
  45. print("[*] 发送命令: %s" % cmd)
  46. ser.write(cmd.encode("utf-8", "replace") + b"\r\n")
  47. ser.flush()
  48. print("[*] 后置采集 %.0fs ..." % post)
  49. after = collect(ser, post)
  50. print(" after :", after)
  51. print("\n[*] 增量:")
  52. for k in ("rx2", "tx2", "rx4", "tx4", "up"):
  53. b, a = before.get(k), after.get(k)
  54. if b is None or a is None:
  55. print(" %-4s : (缺数据)" % k)
  56. else:
  57. print(" %-4s : %d -> %d (%+d)" % (k, b, a, a - b))
  58. return 0
  59. if __name__ == "__main__":
  60. sys.exit(main())