| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- #!/usr/bin/env python3
- """Offline MRDIMM V1.2 HEX encoder/decoder and small Tk GUI (2026 contract).
- No serial, I2C, JTAG, or hardware access is performed. Emits/decodes the
- unified 16-bit-length wire frames via the shared codec (vendored copy is
- hash-checked against hth-platform at build time).
- """
- from __future__ import annotations
- import hashlib, json, re, sys
- from pathlib import Path
- def _vendor() -> Path:
- return Path(__file__).resolve().parent / "_vendor" / "hth_protocol.py"
- try:
- from hth_protocol import (FrameParser, Type, encode_frame, decode_frame)
- except ImportError:
- sys.path.insert(0, str(_vendor().parent))
- from hth_protocol import (FrameParser, Type, encode_frame, decode_frame)
- def _asset(name: str) -> Path:
- roots = [Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))]
- roots += [Path(__file__).resolve().parent.parent / "generated" / "mrdimm"]
- for root in roots:
- p = root / name
- if p.is_file(): return p
- raise FileNotFoundError(name)
- try:
- METADATA = json.loads(_asset("gui-build-metadata.json").read_text(encoding="utf-8"))
- except FileNotFoundError:
- METADATA = {"commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
- ENDPOINTS = {"lower": 0x00, "upper": 0x64, "unchanged": 0xFF}
- def parse_hex(text: str) -> bytes:
- text = re.sub(r"[\s:_-]+", "", text)
- if not text or len(text) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", text): raise ValueError("invalid HEX")
- return bytes.fromhex(text)
- def set_all(fan: list[int], ptc: list[int], motor: dict[str, str]) -> bytes:
- """MRDIMM SET_ALL: FAN0..3, PTC0..3 (0..100) + Z,X,Y endpoints.
- Omitted motor axes default to ``unchanged`` (0xFF), never 0x00."""
- if len(fan) != 4 or len(ptc) != 4: raise ValueError("fan/ptc must have 4 values each")
- if set(motor) - {"x", "y", "z"}: raise ValueError("motor axes are x/y/z only")
- vals = [*fan, *ptc]
- if any(not 0 <= int(v) <= 100 for v in vals): raise ValueError("duties must be 0..100")
- for name in ("z", "x", "y"):
- e = motor.get(name, "unchanged")
- if e not in ENDPOINTS: raise ValueError(f"motor[{name}] must be lower/upper/unchanged")
- vals.append(ENDPOINTS[e])
- return encode_frame(Type.SET_ALL, bytes(vals))
- def describe(frame: bytes) -> str:
- f = decode_frame(frame)
- if f.frame_type == Type.ACK_NACK and len(f.payload) == 4:
- rt, st = f.payload[0], f.payload[1]
- detail = int.from_bytes(f.payload[2:4], "little")
- try: st = f"{st} ({Type(rt).name})"
- except ValueError: pass
- return f"ACK_NACK request=0x{f.payload[0]:02X} status={st} detail={detail} crc_ok={f.crc_ok}"
- return f"type=0x{f.frame_type:02X} len={len(f.payload)} payload={f.payload.hex(' ').upper()} crc_ok={f.crc_ok}"
- def self_test() -> int:
- """Offline generate/decode coverage; exit 0 = pass (no Tk, no COM)."""
- raw = set_all([20] * 4, [0] * 4, {"x": "lower", "y": "unchanged", "z": "upper"})
- f = decode_frame(raw)
- assert f.frame_type == Type.SET_ALL and len(f.payload) == 11
- # wire order Z,X,Y; unchanged must be FF, lower 00, upper 64
- assert f.payload[8:] == bytes([0x64, 0x00, 0xFF])
- assert f.payload[:8] == bytes([20] * 4 + [0] * 4)
- # fixed contract vector round trip
- assert decode_frame(bytes.fromhex("A55A020000FCA2")).frame_type == Type.GET_ALL
- ack = decode_frame(bytes.fromhex("A55A80040002000000FEB1"))
- assert ack.frame_type == Type.ACK_NACK and ack.payload[0] == Type.GET_ALL
- # bad CRC is surfaced, not silently accepted
- bad = bytearray(raw); bad[-1] ^= 0xFF
- assert not decode_frame(bytes(bad)).crc_ok
- return 0
- def run_gui() -> int:
- import tkinter as tk
- from tkinter import ttk, messagebox
- root = tk.Tk(); root.title("Prod2U MRDIMM V1.2 HEX GUI"); root.geometry("900x560")
- out = tk.StringVar()
- vals = [tk.IntVar(value=20 if i < 4 else 0) for i in range(8)]
- ep = {a: tk.StringVar(value="unchanged") for a in ("z", "x", "y")}
- ttk.Label(root, text=(f"MRDIMM V1.2 commit={METADATA.get('commit')} "
- f"bitstream={str(METADATA.get('bitstream_sha256'))[:16]}")).pack(anchor="w", padx=10, pady=8)
- ttk.Label(root, text="Position Steps 是 CPLD 已输出的指令脉冲计数,不是编码器测得的机械位置。"
- " Motor 端点 00=向下 64=向上 FF=不变;相同端点再次发送会重新触发运动。", wraplength=860, justify="left").pack(anchor="w", padx=10)
- grid = ttk.Frame(root); grid.pack(padx=10, pady=6)
- labels = [*(f"FAN{i}" for i in range(4)), *(f"PTC{i}" for i in range(4))]
- for i, label in enumerate(labels):
- cell = ttk.Frame(grid); cell.grid(row=i//4, column=i%4, padx=6, pady=4)
- ttk.Label(cell, text=label).pack(); ttk.Spinbox(cell, from_=0, to=100, width=6, textvariable=vals[i]).pack()
- egrid = ttk.Frame(root); egrid.pack(padx=10, pady=4)
- for i, a in enumerate(("Z", "X", "Y")):
- cell = ttk.Frame(egrid); cell.grid(row=0, column=i, padx=12)
- ttk.Label(cell, text=f"Motor {a}").pack()
- ttk.OptionMenu(cell, ep[a.lower()], "unchanged", *ENDPOINTS).pack()
- def emit():
- try:
- fan = [v.get() for v in vals[:4]]
- ptc = [v.get() for v in vals[4:8]]
- motor = {a: v.get() for a, v in ep.items()}
- out.set(" ".join(f"{b:02X}" for b in set_all(fan, ptc, motor)))
- except Exception as e: messagebox.showerror("SET_ALL", str(e))
- def emit_simple(kind):
- out.set(" ".join(f"{b:02X}" for b in encode_frame(kind)))
- ttk.Button(root, text="Generate SET_ALL", command=emit).pack(anchor="w", padx=10, pady=4)
- ttk.Button(root, text="GET_ALL (02)", command=lambda: emit_simple(Type.GET_ALL)).pack(anchor="w", padx=10, pady=2)
- ttk.Button(root, text="OUTPUT_KEEPALIVE (05)", command=lambda: emit_simple(Type.OUTPUT_KEEPALIVE)).pack(anchor="w", padx=10, pady=2)
- ttk.Button(root, text="EVENT_READ max=8 (08)", command=lambda: out.set("A5 5A 08 00 01 08 " +
- encode_frame(Type.EVENT_READ, bytes([8]))[-4:-2].hex(' ').upper() +
- " " + encode_frame(Type.EVENT_READ, bytes([8]))[-2:].hex(' ').upper())).pack(anchor="w", padx=10, pady=2)
- ttk.Entry(root, textvariable=out, font=("Consolas", 11)).pack(fill="x", padx=10, pady=8)
- ttk.Label(root, text="解析帧(ACK_NACK: request_type, status, detail):").pack(anchor="w", padx=10)
- parsed = tk.StringVar()
- ttk.Entry(root, textvariable=parsed, font=("Consolas", 11)).pack(fill="x", padx=10, pady=(0, 4))
- def parse_action():
- try: parsed.set(describe(parse_hex(out.get())))
- except Exception as e: messagebox.showerror("Parse", str(e))
- ttk.Button(root, text="Parse frame", command=parse_action).pack(anchor="w", padx=10)
- emit(); root.mainloop(); return 0
- if __name__ == "__main__":
- if "--self-test" in sys.argv:
- raise SystemExit(self_test())
- raise SystemExit(run_gui())
|