| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #!/usr/bin/env python3
- """Offline MRDIMM V1.2 HEX encoder/decoder and small Tk GUI.
- No serial, I2C, JTAG, or hardware access is performed. The executable is
- bound to the generated MRDIMM contract and only emits/decodes wire frames.
- """
- from __future__ import annotations
- import hashlib, json, re, sys
- from pathlib import Path
- from typing import Iterable
- def _asset(name: str) -> Path:
- roots = [Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))]
- roots += [Path(__file__).resolve().parent.parent / "src" / "generated"]
- for root in roots:
- p = root / name
- if p.is_file(): return p
- raise FileNotFoundError(name)
- _contract_path = _asset("host-contract.json")
- CONTRACT = json.loads(_contract_path.read_text(encoding="utf-8"))
- CONTRACT.setdefault("contract_sha256", hashlib.sha256(_contract_path.read_bytes()).hexdigest())
- try: METADATA = json.loads(_asset("gui-build-metadata.json").read_text(encoding="utf-8"))
- except FileNotFoundError: METADATA = {"commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
- def crc16(data: Iterable[int]) -> int:
- c = 0xFFFF
- for b in data:
- c ^= int(b) << 8
- for _ in range(8): c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
- return c
- def encode(kind: int, payload: bytes = b"") -> bytes:
- body = bytes((kind, len(payload))) + payload
- return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
- def decode(frame: bytes) -> tuple[int, bytes]:
- if len(frame) < 6 or frame[:2] != b"\xA5\x5A": raise ValueError("bad A5 5A header")
- if len(frame) != frame[3] + 6: raise ValueError("length mismatch")
- if int.from_bytes(frame[-2:], "little") != crc16(frame[2:-2]): raise ValueError("CRC mismatch")
- return frame[2], frame[4:-2]
- 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], doors: dict[str, int]) -> bytes:
- if len(fan) != 4 or len(ptc) != 4 or set(doors) != {"x", "y", "z"}: raise ValueError("MRDIMM SET_ALL shape")
- vals = [*fan, *ptc, doors["z"], doors["x"], doors["y"]]
- if any(not 0 <= int(v) <= 100 for v in vals): raise ValueError("all values must be 0..100")
- return encode(0x01, bytes(vals))
- def describe(frame: bytes) -> str:
- kind, payload = decode(frame)
- return f"type=0x{kind:02X} payload_len={len(payload)} payload={payload.hex(' ').upper()}"
- 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(11)]
- ttk.Label(root, text=f"MRDIMM V1.2 commit={METADATA.get('commit')} contract={CONTRACT.get('project_id')}").pack(anchor="w", padx=10, pady=8)
- grid = ttk.Frame(root); grid.pack(padx=10)
- labels = [*(f"FAN{i}" for i in range(4)), *(f"PTC{i}" for i in range(4)), "Z %", "X %", "Y %"]
- for i, label in enumerate(labels):
- cell = ttk.Frame(grid); cell.grid(row=i//6, column=i%6, padx=6, pady=6)
- ttk.Label(cell, text=label).pack(); ttk.Spinbox(cell, from_=0, to=100, width=6, textvariable=vals[i]).pack()
- def emit():
- try:
- fan = [v.get() for v in vals[:4]]
- ptc = [v.get() for v in vals[4:8]]
- doors = dict(zip(("z", "x", "y"), [v.get() for v in vals[8:]]))
- out.set(" ".join(f"{b:02X}" for b in set_all(fan, ptc, doors)))
- except Exception as e: messagebox.showerror("SET_ALL", str(e))
- ttk.Button(root, text="Generate SET_ALL", command=emit).pack(anchor="w", padx=10, pady=8)
- 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)
- 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)
- ttk.Label(root, text="Position Steps 是 CPLD 已输出的指令脉冲计数,不是编码器测得的机械绝对位置。", foreground="darkred").pack(anchor="w", padx=10, pady=8)
- ttk.Entry(root, textvariable=out, font=("Consolas", 11)).pack(fill="x", padx=10, pady=8)
- emit(); root.mainloop(); return 0
- if __name__ == "__main__": raise SystemExit(run_gui())
|