mrdimm_hex_gui.py 4.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python3
  2. """Offline MRDIMM V1.2 HEX encoder/decoder and small Tk GUI.
  3. No serial, I2C, JTAG, or hardware access is performed. The executable is
  4. bound to the generated MRDIMM contract and only emits/decodes wire frames.
  5. """
  6. from __future__ import annotations
  7. import hashlib, json, re, sys
  8. from pathlib import Path
  9. from typing import Iterable
  10. def _asset(name: str) -> Path:
  11. roots = [Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))]
  12. roots += [Path(__file__).resolve().parent.parent / "src" / "generated"]
  13. for root in roots:
  14. p = root / name
  15. if p.is_file(): return p
  16. raise FileNotFoundError(name)
  17. _contract_path = _asset("host-contract.json")
  18. CONTRACT = json.loads(_contract_path.read_text(encoding="utf-8"))
  19. CONTRACT.setdefault("contract_sha256", hashlib.sha256(_contract_path.read_bytes()).hexdigest())
  20. try: METADATA = json.loads(_asset("gui-build-metadata.json").read_text(encoding="utf-8"))
  21. except FileNotFoundError: METADATA = {"commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
  22. def crc16(data: Iterable[int]) -> int:
  23. c = 0xFFFF
  24. for b in data:
  25. c ^= int(b) << 8
  26. for _ in range(8): c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
  27. return c
  28. def encode(kind: int, payload: bytes = b"") -> bytes:
  29. body = bytes((kind, len(payload))) + payload
  30. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  31. def decode(frame: bytes) -> tuple[int, bytes]:
  32. if len(frame) < 6 or frame[:2] != b"\xA5\x5A": raise ValueError("bad A5 5A header")
  33. if len(frame) != frame[3] + 6: raise ValueError("length mismatch")
  34. if int.from_bytes(frame[-2:], "little") != crc16(frame[2:-2]): raise ValueError("CRC mismatch")
  35. return frame[2], frame[4:-2]
  36. def parse_hex(text: str) -> bytes:
  37. text = re.sub(r"[\s:_-]+", "", text)
  38. if not text or len(text) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", text): raise ValueError("invalid HEX")
  39. return bytes.fromhex(text)
  40. def set_all(fan: list[int], ptc: list[int], doors: dict[str, int]) -> bytes:
  41. if len(fan) != 4 or len(ptc) != 4 or set(doors) != {"x", "y", "z"}: raise ValueError("MRDIMM SET_ALL shape")
  42. vals = [*fan, *ptc, doors["z"], doors["x"], doors["y"]]
  43. if any(not 0 <= int(v) <= 100 for v in vals): raise ValueError("all values must be 0..100")
  44. return encode(0x01, bytes(vals))
  45. def describe(frame: bytes) -> str:
  46. kind, payload = decode(frame)
  47. return f"type=0x{kind:02X} payload_len={len(payload)} payload={payload.hex(' ').upper()}"
  48. def run_gui() -> int:
  49. import tkinter as tk
  50. from tkinter import ttk, messagebox
  51. root = tk.Tk(); root.title("Prod2U MRDIMM V1.2 HEX GUI"); root.geometry("900x560")
  52. out = tk.StringVar(); vals = [tk.IntVar(value=20 if i < 4 else 0) for i in range(11)]
  53. ttk.Label(root, text=f"MRDIMM V1.2 commit={METADATA.get('commit')} contract={CONTRACT.get('project_id')}").pack(anchor="w", padx=10, pady=8)
  54. grid = ttk.Frame(root); grid.pack(padx=10)
  55. labels = [*(f"FAN{i}" for i in range(4)), *(f"PTC{i}" for i in range(4)), "Z %", "X %", "Y %"]
  56. for i, label in enumerate(labels):
  57. cell = ttk.Frame(grid); cell.grid(row=i//6, column=i%6, padx=6, pady=6)
  58. ttk.Label(cell, text=label).pack(); ttk.Spinbox(cell, from_=0, to=100, width=6, textvariable=vals[i]).pack()
  59. def emit():
  60. try:
  61. fan = [v.get() for v in vals[:4]]
  62. ptc = [v.get() for v in vals[4:8]]
  63. doors = dict(zip(("z", "x", "y"), [v.get() for v in vals[8:]]))
  64. out.set(" ".join(f"{b:02X}" for b in set_all(fan, ptc, doors)))
  65. except Exception as e: messagebox.showerror("SET_ALL", str(e))
  66. ttk.Button(root, text="Generate SET_ALL", command=emit).pack(anchor="w", padx=10, pady=8)
  67. ttk.Button(root, text="GET_TEMPERATURE", command=lambda: out.set(" ".join(f"{b:02X}" for b in encode(2)))).pack(anchor="w", padx=10, pady=4)
  68. ttk.Button(root, text="GET_MOTOR_STATUS", command=lambda: out.set(" ".join(f"{b:02X}" for b in encode(3)))).pack(anchor="w", padx=10, pady=4)
  69. ttk.Label(root, text="Position Steps 是 CPLD 已输出的指令脉冲计数,不是编码器测得的机械绝对位置。", foreground="darkred").pack(anchor="w", padx=10, pady=8)
  70. ttk.Entry(root, textvariable=out, font=("Consolas", 11)).pack(fill="x", padx=10, pady=8)
  71. emit(); root.mainloop(); return 0
  72. if __name__ == "__main__": raise SystemExit(run_gui())