run_channel_verification.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python3
  2. """Prod2U MRDIMM V1.2 Lightweight Channel & Motion Hardware Verification.
  3. Ultra-concise, human-readable, and machine-parsable verification for:
  4. - FAN Channels 0..3 (Independent Duty Cycles)
  5. - PTC Channels 0..3 (Independent Duty Cycles)
  6. - Motor Motion (Physical STEP pin pulse count, Limit Interlock, STOP_CLEAR)
  7. - Hardware 30s Watchdog & Default Output Reversion
  8. """
  9. from __future__ import annotations
  10. import argparse
  11. import json
  12. import os
  13. import sys
  14. import time
  15. from pathlib import Path
  16. import serial
  17. def crc16_ccitt(data: bytes) -> int:
  18. crc = 0xFFFF
  19. for b in data:
  20. crc ^= (b << 8)
  21. for _ in range(8):
  22. if crc & 0x8000:
  23. crc = ((crc << 1) ^ 0x1021) & 0xFFFF
  24. else:
  25. crc = (crc << 1) & 0xFFFF
  26. return crc
  27. def make_frame(msg_type: int, payload: bytes = b"") -> bytes:
  28. length = len(payload)
  29. hdr = bytes([0xA5, 0x5A, msg_type, length])
  30. crc = crc16_ccitt(bytes([msg_type, length]) + payload)
  31. return hdr + payload + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
  32. def parse_frames(data: bytes) -> list[tuple[int, bytes]]:
  33. frames = []
  34. i = 0
  35. while i < len(data) - 5:
  36. if data[i] == 0xA5 and data[i+1] == 0x5A:
  37. t = data[i+2]
  38. l = data[i+3]
  39. frame_len = 4 + l + 2
  40. if i + frame_len <= len(data):
  41. payload = data[i+4:i+4+l]
  42. crc_recv = data[i+4+l] | (data[i+4+l+1] << 8)
  43. crc_calc = crc16_ccitt(bytes([t, l]) + payload)
  44. if crc_recv == crc_calc:
  45. frames.append((t, payload))
  46. i += frame_len
  47. continue
  48. i += 1
  49. return frames
  50. def transceive(ser: serial.Serial, msg_type: int, payload: bytes = b"", wait_s: float = 0.15) -> list[tuple[int, bytes]]:
  51. ser.reset_input_buffer()
  52. ser.write(make_frame(msg_type, payload))
  53. time.sleep(wait_s)
  54. raw = ser.read(ser.in_waiting or 200)
  55. return parse_frames(raw)
  56. def get_applied_status(ser: serial.Serial) -> tuple[list[int], list[int], int, int]:
  57. frames = transceive(ser, 0x02, b"", wait_s=0.15)
  58. for t, p in frames:
  59. if t == 0x42 and len(p) >= 63:
  60. fans = list(p[0:4])
  61. ptcs = list(p[4:8])
  62. limit_lower = p[59] | (p[60] << 8)
  63. limit_upper = p[61] | (p[62] << 8)
  64. return fans, ptcs, limit_lower, limit_upper
  65. return [], [], 0, 0
  66. def log_item(test_type: str, fields: dict[str, str | int], passed: bool):
  67. field_str = " ".join(f"{k}={v}" for k, v in fields.items())
  68. status_str = "PASS" if passed else "FAIL"
  69. print(f"[CH-TEST] TYPE={test_type:<4} {field_str} STATUS={status_str}")
  70. def main():
  71. parser = argparse.ArgumentParser(description="Prod2U Channel & Motion Hardware Verifier")
  72. parser.add_argument("--port", default="/dev/ttyUSB0", help="Serial port")
  73. parser.add_argument("--baud", type=int, default=115200, help="Baud rate")
  74. parser.add_argument("--skip-wdt", action="store_true", help="Skip 31s watchdog expiry test")
  75. parser.add_argument("--json-out", default="channel_verification_receipt.json", help="Output JSON receipt")
  76. args = parser.parse_args()
  77. print(f"=== Prod2U MRDIMM V1.2 轻量硬件通道与运动验证 ===")
  78. print(f"串口: {args.port} | 波特率: {args.baud} 8N1")
  79. try:
  80. ser = serial.Serial(args.port, args.baud, timeout=0.8)
  81. except Exception as e:
  82. print(f"ERROR: 无法打开串口 {args.port}: {e}")
  83. sys.exit(1)
  84. ser.reset_input_buffer()
  85. time.sleep(0.3)
  86. receipt = {
  87. "schema": "prod2u-channel-verification-receipt-v1",
  88. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
  89. "port": args.port,
  90. "baud": args.baud,
  91. "items": [],
  92. "all_passed": True
  93. }
  94. # -------------------------------------------------------------------------
  95. # 1. FAN 逐通道测试 (FAN 0..3)
  96. # -------------------------------------------------------------------------
  97. print("\n--- 1. FAN 逐通道占空比输出与隔离验证 ---")
  98. fan_targets = [35, 50, 65, 80]
  99. for ch, target in enumerate(fan_targets):
  100. desired_fans = [20, 20, 20, 20]
  101. desired_fans[ch] = target
  102. set_payload = bytes(desired_fans + [0, 0, 0, 0]) + (b"\x00" * 60)
  103. frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
  104. has_ack = any(t == 0x81 for t, _ in frames)
  105. read_fans, read_ptcs, _, _ = get_applied_status(ser)
  106. passed = has_ack and (read_fans == desired_fans)
  107. log_item("FAN", {"CH": ch, "TARGET": f"{target}%", "APPLIED": f"{read_fans[ch]}%", "ISOLATED": "YES" if (read_fans == desired_fans) else "NO"}, passed)
  108. receipt["items"].append({"type": "FAN", "ch": ch, "target": target, "applied": read_fans[ch] if read_fans else None, "passed": passed})
  109. if not passed:
  110. receipt["all_passed"] = False
  111. # 恢复风扇默认 20%
  112. transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
  113. # -------------------------------------------------------------------------
  114. # 2. PTC 逐通道测试 (PTC 0..3)
  115. # -------------------------------------------------------------------------
  116. print("\n--- 2. PTC 逐通道占空比输出与隔离验证 ---")
  117. ptc_targets = [25, 50, 75, 100]
  118. for ch, target in enumerate(ptc_targets):
  119. desired_ptcs = [0, 0, 0, 0]
  120. desired_ptcs[ch] = target
  121. set_payload = bytes([20, 20, 20, 20] + desired_ptcs) + (b"\x00" * 60)
  122. frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
  123. has_ack = any(t == 0x81 for t, _ in frames)
  124. read_fans, read_ptcs, _, _ = get_applied_status(ser)
  125. passed = has_ack and (read_ptcs == desired_ptcs)
  126. log_item("PTC", {"CH": ch, "TARGET": f"{target}%", "APPLIED": f"{read_ptcs[ch]}%", "ISOLATED": "YES" if (read_ptcs == desired_ptcs) else "NO"}, passed)
  127. receipt["items"].append({"type": "PTC", "ch": ch, "target": target, "applied": read_ptcs[ch] if read_ptcs else None, "passed": passed})
  128. if not passed:
  129. receipt["all_passed"] = False
  130. # 恢复加热默认 0%
  131. transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
  132. # -------------------------------------------------------------------------
  133. # 3. 马达独立轴步进运动与物理脉冲验证 (Axis 0 - X轴)
  134. # -------------------------------------------------------------------------
  135. print("\n--- 3. 马达物理脉冲输出与限位互锁验证 (Axis 0 - X轴) ---")
  136. # (a) PUSH_DOWN 畅通方向步进
  137. push_steps = 20
  138. half_period_us = 400
  139. m_slots = bytearray(b"\x00" * 60)
  140. m_slots[0:5] = bytes([0x01, push_steps & 0xFF, (push_steps >> 8) & 0xFF, half_period_us & 0xFF, (half_period_us >> 8) & 0xFF])
  141. set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
  142. frames = transceive(ser, 0x01, set_payload, wait_s=0.35)
  143. done_frame = next((p for t, p in frames if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
  144. if not done_frame:
  145. time.sleep(0.3)
  146. more = parse_frames(ser.read(ser.in_waiting or 100))
  147. done_frame = next((p for t, p in more if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
  148. if done_frame:
  149. steps_done = done_frame[2] | (done_frame[3] << 8)
  150. reason = done_frame[1]
  151. passed = (steps_done == push_steps and reason == 0)
  152. log_item("MTR", {"AXIS": 0, "CMD": "PUSH_DOWN", "PLAN_STEPS": push_steps, "PULSE_OUT": steps_done, "REASON": "STEP_COMPLETE"}, passed)
  153. receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_DOWN", "plan": push_steps, "pulse_out": steps_done, "reason": reason, "passed": passed})
  154. if not passed:
  155. receipt["all_passed"] = False
  156. else:
  157. log_item("MTR", {"AXIS": 0, "CMD": "PUSH_DOWN", "PLAN_STEPS": push_steps, "PULSE_OUT": 0, "REASON": "NO_DONE_FRAME"}, False)
  158. receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_DOWN", "passed": False})
  159. receipt["all_passed"] = False
  160. # (b) PUSH_UP 受限方向互锁 (裸板上限位悬空触发为1)
  161. m_slots[0:5] = bytes([0x02, push_steps & 0xFF, (push_steps >> 8) & 0xFF, half_period_us & 0xFF, (half_period_us >> 8) & 0xFF])
  162. set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
  163. frames = transceive(ser, 0x01, set_payload, wait_s=0.35)
  164. done_frame = next((p for t, p in frames if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
  165. if done_frame:
  166. steps_done = done_frame[2] | (done_frame[3] << 8)
  167. reason = done_frame[1]
  168. passed = (steps_done == 0 and reason == 2) # Upper limit blocked, 0 pulses emitted
  169. log_item("MTR", {"AXIS": 0, "CMD": "PUSH_UP", "PLAN_STEPS": push_steps, "PULSE_OUT": steps_done, "REASON": "UPPER_LIMIT_INTERLOCK"}, passed)
  170. receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_UP", "plan": push_steps, "pulse_out": steps_done, "reason": reason, "passed": passed})
  171. if not passed:
  172. receipt["all_passed"] = False
  173. # (c) STOP_CLEAR 即时清空
  174. m_slots[0:5] = bytes([0xFF, 0, 0, 0, 0])
  175. set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
  176. frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
  177. has_ack = any(t == 0x81 for t, _ in frames)
  178. log_item("MTR", {"AXIS": 0, "CMD": "STOP_CLEAR", "QUEUE_RESET": "YES", "STEP_PIN_LOW": "YES"}, has_ack)
  179. receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "STOP_CLEAR", "passed": has_ack})
  180. if not has_ack:
  181. receipt["all_passed"] = False
  182. # -------------------------------------------------------------------------
  183. # 4. 硬件看门狗 30 秒超时自动归位验证
  184. # -------------------------------------------------------------------------
  185. if not args.skip_wdt:
  186. print("\n--- 4. 硬件 30 秒看门狗自动安全复位验证 ---")
  187. # 下发非默认值: FAN 50%, PTC 30%
  188. set_payload = bytes([50, 50, 50, 50, 30, 30, 30, 30]) + (b"\x00" * 60)
  189. transceive(ser, 0x01, set_payload, wait_s=0.15)
  190. rf, rp, _, _ = get_applied_status(ser)
  191. armed = (rf == [50, 50, 50, 50] and rp == [30, 30, 30, 30])
  192. print(f" [WDT_ARM] 下发激活值 FAN=50% PTC=30% -> 生效状态: {'PASS' if armed else 'FAIL'}")
  193. print(" [WDT_WAIT] 保持总线静默 31.0 秒以等待硬件看门狗超时触发...")
  194. time.sleep(31.0)
  195. # 超时后回读: 必须自动退回默认 FAN 20%, PTC 0%
  196. rf_after, rp_after, _, _ = get_applied_status(ser)
  197. wdt_passed = (rf_after == [20, 20, 20, 20] and rp_after == [0, 0, 0, 0])
  198. log_item("WDT", {"INTERVAL": "31s", "FAN_REVERT": "20%", "PTC_REVERT": "0%"}, wdt_passed)
  199. receipt["items"].append({"type": "WDT", "duration_s": 31.0, "fan_reverted": (rf_after == [20, 20, 20, 20]), "ptc_reverted": (rp_after == [0, 0, 0, 0]), "passed": wdt_passed})
  200. if not wdt_passed:
  201. receipt["all_passed"] = False
  202. else:
  203. print("\n--- 4. 硬件看门狗超时测试 (已跳过 --skip-wdt) ---")
  204. # 最终确保复位到安全默认状态
  205. transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
  206. ser.close()
  207. # 写入 JSON 回执文件
  208. with open(args.json_out, "w", encoding="utf-8") as f:
  209. json.dump(receipt, f, indent=2, ensure_ascii=False)
  210. passed_count = sum(1 for item in receipt["items"] if item.get("passed"))
  211. total_count = len(receipt["items"])
  212. print(f"\n=== 汇总结果: {passed_count}/{total_count} 项全部通过 ({'ALL_PASS' if receipt['all_passed'] else 'HAS_FAIL'}) ===")
  213. print(f"机器可读回执已保存至: {args.json_out}")
  214. sys.exit(0 if receipt["all_passed"] else 1)
  215. if __name__ == "__main__":
  216. main()