| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- #!/usr/bin/env python3
- """Prod2U MRDIMM V1.2 Lightweight Channel & Motion Hardware Verification.
- Ultra-concise, human-readable, and machine-parsable verification for:
- - FAN Channels 0..3 (Independent Duty Cycles)
- - PTC Channels 0..3 (Independent Duty Cycles)
- - Motor Motion (Physical STEP pin pulse count, Limit Interlock, STOP_CLEAR)
- - Hardware 30s Watchdog & Default Output Reversion
- """
- from __future__ import annotations
- import argparse
- import json
- import os
- import sys
- import time
- from pathlib import Path
- import serial
- def crc16_ccitt(data: bytes) -> int:
- crc = 0xFFFF
- for b in data:
- crc ^= (b << 8)
- for _ in range(8):
- if crc & 0x8000:
- crc = ((crc << 1) ^ 0x1021) & 0xFFFF
- else:
- crc = (crc << 1) & 0xFFFF
- return crc
- def make_frame(msg_type: int, payload: bytes = b"") -> bytes:
- length = len(payload)
- hdr = bytes([0xA5, 0x5A, msg_type, length])
- crc = crc16_ccitt(bytes([msg_type, length]) + payload)
- return hdr + payload + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
- def parse_frames(data: bytes) -> list[tuple[int, bytes]]:
- frames = []
- i = 0
- while i < len(data) - 5:
- if data[i] == 0xA5 and data[i+1] == 0x5A:
- t = data[i+2]
- l = data[i+3]
- frame_len = 4 + l + 2
- if i + frame_len <= len(data):
- payload = data[i+4:i+4+l]
- crc_recv = data[i+4+l] | (data[i+4+l+1] << 8)
- crc_calc = crc16_ccitt(bytes([t, l]) + payload)
- if crc_recv == crc_calc:
- frames.append((t, payload))
- i += frame_len
- continue
- i += 1
- return frames
- def transceive(ser: serial.Serial, msg_type: int, payload: bytes = b"", wait_s: float = 0.15) -> list[tuple[int, bytes]]:
- ser.reset_input_buffer()
- ser.write(make_frame(msg_type, payload))
- time.sleep(wait_s)
- raw = ser.read(ser.in_waiting or 200)
- return parse_frames(raw)
- def get_applied_status(ser: serial.Serial) -> tuple[list[int], list[int], int, int]:
- frames = transceive(ser, 0x02, b"", wait_s=0.15)
- for t, p in frames:
- if t == 0x42 and len(p) >= 63:
- fans = list(p[0:4])
- ptcs = list(p[4:8])
- limit_lower = p[59] | (p[60] << 8)
- limit_upper = p[61] | (p[62] << 8)
- return fans, ptcs, limit_lower, limit_upper
- return [], [], 0, 0
- def log_item(test_type: str, fields: dict[str, str | int], passed: bool):
- field_str = " ".join(f"{k}={v}" for k, v in fields.items())
- status_str = "PASS" if passed else "FAIL"
- print(f"[CH-TEST] TYPE={test_type:<4} {field_str} STATUS={status_str}")
- def main():
- parser = argparse.ArgumentParser(description="Prod2U Channel & Motion Hardware Verifier")
- parser.add_argument("--port", default="/dev/ttyUSB0", help="Serial port")
- parser.add_argument("--baud", type=int, default=115200, help="Baud rate")
- parser.add_argument("--skip-wdt", action="store_true", help="Skip 31s watchdog expiry test")
- parser.add_argument("--json-out", default="channel_verification_receipt.json", help="Output JSON receipt")
- args = parser.parse_args()
- print(f"=== Prod2U MRDIMM V1.2 轻量硬件通道与运动验证 ===")
- print(f"串口: {args.port} | 波特率: {args.baud} 8N1")
- try:
- ser = serial.Serial(args.port, args.baud, timeout=0.8)
- except Exception as e:
- print(f"ERROR: 无法打开串口 {args.port}: {e}")
- sys.exit(1)
- ser.reset_input_buffer()
- time.sleep(0.3)
- receipt = {
- "schema": "prod2u-channel-verification-receipt-v1",
- "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
- "port": args.port,
- "baud": args.baud,
- "items": [],
- "all_passed": True
- }
- # -------------------------------------------------------------------------
- # 1. FAN 逐通道测试 (FAN 0..3)
- # -------------------------------------------------------------------------
- print("\n--- 1. FAN 逐通道占空比输出与隔离验证 ---")
- fan_targets = [35, 50, 65, 80]
- for ch, target in enumerate(fan_targets):
- desired_fans = [20, 20, 20, 20]
- desired_fans[ch] = target
- set_payload = bytes(desired_fans + [0, 0, 0, 0]) + (b"\x00" * 60)
-
- frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
- has_ack = any(t == 0x81 for t, _ in frames)
- read_fans, read_ptcs, _, _ = get_applied_status(ser)
-
- passed = has_ack and (read_fans == desired_fans)
- log_item("FAN", {"CH": ch, "TARGET": f"{target}%", "APPLIED": f"{read_fans[ch]}%", "ISOLATED": "YES" if (read_fans == desired_fans) else "NO"}, passed)
- receipt["items"].append({"type": "FAN", "ch": ch, "target": target, "applied": read_fans[ch] if read_fans else None, "passed": passed})
- if not passed:
- receipt["all_passed"] = False
- # 恢复风扇默认 20%
- transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
- # -------------------------------------------------------------------------
- # 2. PTC 逐通道测试 (PTC 0..3)
- # -------------------------------------------------------------------------
- print("\n--- 2. PTC 逐通道占空比输出与隔离验证 ---")
- ptc_targets = [25, 50, 75, 100]
- for ch, target in enumerate(ptc_targets):
- desired_ptcs = [0, 0, 0, 0]
- desired_ptcs[ch] = target
- set_payload = bytes([20, 20, 20, 20] + desired_ptcs) + (b"\x00" * 60)
- frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
- has_ack = any(t == 0x81 for t, _ in frames)
- read_fans, read_ptcs, _, _ = get_applied_status(ser)
- passed = has_ack and (read_ptcs == desired_ptcs)
- log_item("PTC", {"CH": ch, "TARGET": f"{target}%", "APPLIED": f"{read_ptcs[ch]}%", "ISOLATED": "YES" if (read_ptcs == desired_ptcs) else "NO"}, passed)
- receipt["items"].append({"type": "PTC", "ch": ch, "target": target, "applied": read_ptcs[ch] if read_ptcs else None, "passed": passed})
- if not passed:
- receipt["all_passed"] = False
- # 恢复加热默认 0%
- transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
- # -------------------------------------------------------------------------
- # 3. 马达独立轴步进运动与物理脉冲验证 (Axis 0 - X轴)
- # -------------------------------------------------------------------------
- print("\n--- 3. 马达物理脉冲输出与限位互锁验证 (Axis 0 - X轴) ---")
- # (a) PUSH_DOWN 畅通方向步进
- push_steps = 20
- half_period_us = 400
- m_slots = bytearray(b"\x00" * 60)
- m_slots[0:5] = bytes([0x01, push_steps & 0xFF, (push_steps >> 8) & 0xFF, half_period_us & 0xFF, (half_period_us >> 8) & 0xFF])
- set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
- frames = transceive(ser, 0x01, set_payload, wait_s=0.35)
- done_frame = next((p for t, p in frames if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
- if not done_frame:
- time.sleep(0.3)
- more = parse_frames(ser.read(ser.in_waiting or 100))
- done_frame = next((p for t, p in more if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
- if done_frame:
- steps_done = done_frame[2] | (done_frame[3] << 8)
- reason = done_frame[1]
- passed = (steps_done == push_steps and reason == 0)
- log_item("MTR", {"AXIS": 0, "CMD": "PUSH_DOWN", "PLAN_STEPS": push_steps, "PULSE_OUT": steps_done, "REASON": "STEP_COMPLETE"}, passed)
- receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_DOWN", "plan": push_steps, "pulse_out": steps_done, "reason": reason, "passed": passed})
- if not passed:
- receipt["all_passed"] = False
- else:
- log_item("MTR", {"AXIS": 0, "CMD": "PUSH_DOWN", "PLAN_STEPS": push_steps, "PULSE_OUT": 0, "REASON": "NO_DONE_FRAME"}, False)
- receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_DOWN", "passed": False})
- receipt["all_passed"] = False
- # (b) PUSH_UP 受限方向互锁 (裸板上限位悬空触发为1)
- m_slots[0:5] = bytes([0x02, push_steps & 0xFF, (push_steps >> 8) & 0xFF, half_period_us & 0xFF, (half_period_us >> 8) & 0xFF])
- set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
- frames = transceive(ser, 0x01, set_payload, wait_s=0.35)
- done_frame = next((p for t, p in frames if t == 0x50 and len(p) >= 4 and p[0] == 0), None)
- if done_frame:
- steps_done = done_frame[2] | (done_frame[3] << 8)
- reason = done_frame[1]
- passed = (steps_done == 0 and reason == 2) # Upper limit blocked, 0 pulses emitted
- log_item("MTR", {"AXIS": 0, "CMD": "PUSH_UP", "PLAN_STEPS": push_steps, "PULSE_OUT": steps_done, "REASON": "UPPER_LIMIT_INTERLOCK"}, passed)
- receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "PUSH_UP", "plan": push_steps, "pulse_out": steps_done, "reason": reason, "passed": passed})
- if not passed:
- receipt["all_passed"] = False
- # (c) STOP_CLEAR 即时清空
- m_slots[0:5] = bytes([0xFF, 0, 0, 0, 0])
- set_payload = bytes([20, 20, 20, 20, 0, 0, 0, 0]) + bytes(m_slots)
- frames = transceive(ser, 0x01, set_payload, wait_s=0.15)
- has_ack = any(t == 0x81 for t, _ in frames)
- log_item("MTR", {"AXIS": 0, "CMD": "STOP_CLEAR", "QUEUE_RESET": "YES", "STEP_PIN_LOW": "YES"}, has_ack)
- receipt["items"].append({"type": "MTR", "axis": 0, "cmd": "STOP_CLEAR", "passed": has_ack})
- if not has_ack:
- receipt["all_passed"] = False
- # -------------------------------------------------------------------------
- # 4. 硬件看门狗 30 秒超时自动归位验证
- # -------------------------------------------------------------------------
- if not args.skip_wdt:
- print("\n--- 4. 硬件 30 秒看门狗自动安全复位验证 ---")
- # 下发非默认值: FAN 50%, PTC 30%
- set_payload = bytes([50, 50, 50, 50, 30, 30, 30, 30]) + (b"\x00" * 60)
- transceive(ser, 0x01, set_payload, wait_s=0.15)
- rf, rp, _, _ = get_applied_status(ser)
- armed = (rf == [50, 50, 50, 50] and rp == [30, 30, 30, 30])
- print(f" [WDT_ARM] 下发激活值 FAN=50% PTC=30% -> 生效状态: {'PASS' if armed else 'FAIL'}")
- print(" [WDT_WAIT] 保持总线静默 31.0 秒以等待硬件看门狗超时触发...")
- time.sleep(31.0)
- # 超时后回读: 必须自动退回默认 FAN 20%, PTC 0%
- rf_after, rp_after, _, _ = get_applied_status(ser)
- wdt_passed = (rf_after == [20, 20, 20, 20] and rp_after == [0, 0, 0, 0])
- log_item("WDT", {"INTERVAL": "31s", "FAN_REVERT": "20%", "PTC_REVERT": "0%"}, wdt_passed)
- 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})
- if not wdt_passed:
- receipt["all_passed"] = False
- else:
- print("\n--- 4. 硬件看门狗超时测试 (已跳过 --skip-wdt) ---")
- # 最终确保复位到安全默认状态
- transceive(ser, 0x01, bytes([20, 20, 20, 20, 0, 0, 0, 0]) + (b"\x00" * 60), wait_s=0.1)
- ser.close()
- # 写入 JSON 回执文件
- with open(args.json_out, "w", encoding="utf-8") as f:
- json.dump(receipt, f, indent=2, ensure_ascii=False)
- passed_count = sum(1 for item in receipt["items"] if item.get("passed"))
- total_count = len(receipt["items"])
- print(f"\n=== 汇总结果: {passed_count}/{total_count} 项全部通过 ({'ALL_PASS' if receipt['all_passed'] else 'HAS_FAIL'}) ===")
- print(f"机器可读回执已保存至: {args.json_out}")
- sys.exit(0 if receipt["all_passed"] else 1)
- if __name__ == "__main__":
- main()
|