Переглянути джерело

feat(gui): migrate both product GUIs to the unified 16-bit protocol; D10 bitstream-hash hardening

6400_hex_gui.py and mrdimm_hex_gui.py drop their private retired 8-bit
codecs and generate/parse frames through the shared hth_protocol codec,
vendored at tools/_vendor with a sha256 record so the frozen EXE and the
host SDK share one implementation.  MRDIMM GUI rebuilt for the section-10
contract: SET_ALL carries motor endpoint selections (lower/upper/
unchanged, unchanged default FF, wire order Z,X,Y) instead of the retired
percent doors; buttons now emit GET_ALL / OUTPUT_KEEPALIVE / EVENT_READ;
the parser surfaces the new ACK_NACK layout (request_type, status,
detail:u16le) plus crc_ok.

Both GUIs grow a --self-test mode (offline generate/decode coverage over
the fixed contract vectors, bad-CRC surfacing, ACK layout) that exits 0
without Tk or COM.  I2C instruction pages updated to the fixed mailbox
(LENGTH_L/H staging session, COMMAND submit, response registers,
0x0200..05FF window).

D10: both PyInstaller builders now require --bitstream PATH and compute
the SHA-256 from the real TD bitstream file - a hand-typed hash or
NOT_BUILT can no longer reach gui-build-metadata.json - and bundle the
shared codec via --paths/--hidden-import.  Builder --help smoke passed.
codex 2 місяців тому
батько
коміт
d421b1d516

+ 50 - 45
tools/6400_hex_gui.py

@@ -7,7 +7,15 @@ import json
 import re
 import sys
 from pathlib import Path
-from typing import Any, Iterable
+
+def _vendor() -> Path:
+    return Path(__file__).resolve().parent / "_vendor" / "hth_protocol.py"
+
+try:
+    from hth_protocol import Type, decode_frame, encode_frame
+except ImportError:
+    sys.path.insert(0, str(_vendor().parent))
+    from hth_protocol import Type, decode_frame, encode_frame
 
 
 def asset(name: str) -> Path:
@@ -38,21 +46,6 @@ RESPONSES = WIRE["responses"]
 STATUS = {int(value): name for name, value in RESPONSES["ACK_NACK"]["status"].items()}
 
 
-def crc16(data: Iterable[int]) -> int:
-    value = 0xFFFF
-    for byte in data:
-        value ^= int(byte) << 8
-        for _ in range(8):
-            value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
-    return value
-
-
-def encode(frame_type: int, payload: bytes = b"") -> bytes:
-    body = bytes((frame_type, len(payload))) + payload
-    check = crc16(body)
-    return b"\xA5\x5A" + body + check.to_bytes(2, "little")
-
-
 def parse_hex(text: str) -> bytes:
     compact = re.sub(r"[\s:_-]+", "", text)
     if not compact or len(compact) % 2 or not re.fullmatch(r"[0-9A-Fa-f]+", compact):
@@ -60,19 +53,6 @@ def parse_hex(text: str) -> bytes:
     return bytes.fromhex(compact)
 
 
-def decode(frame: bytes) -> tuple[int, bytes]:
-    if len(frame) < 6 or frame[:2] != b"\xA5\x5A":
-        raise ValueError("bad A5 5A header or short frame")
-    size = frame[3]
-    if len(frame) != size + 6:
-        raise ValueError(f"length mismatch: declared {size}, frame bytes {len(frame)}")
-    expected = int.from_bytes(frame[-2:], "little")
-    actual = crc16(frame[2:-2])
-    if expected != actual:
-        raise ValueError(f"CRC mismatch: wire {expected:04X}, calculated {actual:04X}")
-    return frame[2], frame[4:-2]
-
-
 def frame_hex(frame: bytes) -> str:
     return " ".join(f"{byte:02X}" for byte in frame)
 
@@ -80,26 +60,48 @@ def frame_hex(frame: bytes) -> str:
 def set_all(values: list[int]) -> bytes:
     if len(values) != 32 or any(not 0 <= value <= 100 for value in values):
         raise ValueError("SET_ALL requires 32 connector duties in 0..100")
-    return encode(int(COMMANDS["SET_ALL"]["type"]), bytes(values))
+    return encode_frame(Type.SET_ALL, bytes(values))
 
 
 def describe(frame: bytes) -> str:
-    kind, payload = decode(frame)
-    if kind == int(RESPONSES["ACK_NACK"]["type"]):
+    parsed = decode_frame(frame)
+    kind, payload, ok = parsed.frame_type, parsed.payload, parsed.crc_ok
+    head = f"crc_ok={ok} "
+    if kind == Type.ACK_NACK:
         if len(payload) != 4:
             raise ValueError("ACK/NACK payload must be 4 bytes")
-        ok, request, status, detail = payload
-        return f"ACK/NACK ok={ok} request=0x{request:02X} status={STATUS.get(status, 'UNKNOWN')} detail={detail}"
-    if kind == int(RESPONSES["SNAPSHOT_DATA"]["type"]):
+        request, status, detail = payload[0], payload[1], int.from_bytes(payload[2:4], "little")
+        return head + (f"ACK/NACK request=0x{request:02X} "
+                       f"status={STATUS.get(status, 'UNKNOWN')} detail={detail}")
+    if kind == Type.ALL_STATUS_DATA:
         layout = CONTRACT["snapshot"]
         if len(payload) != int(layout["payload_length"]):
-            raise ValueError("SNAPSHOT_DATA payload length mismatch")
+            raise ValueError("ALL_STATUS_DATA payload length mismatch")
         fields: list[str] = []
         for field in layout["fields"][:13]:
             chunk = payload[field["offset"]:field["offset"] + field["size"]]
             fields.append(f"{field['name']}={int.from_bytes(chunk, 'little')}")
-        return "SNAPSHOT_DATA " + ", ".join(fields)
-    return f"type=0x{kind:02X} payload={payload.hex(' ').upper()}"
+        return head + "ALL_STATUS_DATA " + ", ".join(fields)
+    return head + f"type=0x{kind:02X} payload={payload.hex(' ').upper()}"
+
+
+def self_test() -> int:
+    """Offline generate/decode coverage; exit 0 = pass (no Tk, no COM)."""
+    raw = set_all([0] * 24 + [20] * 8)
+    parsed = decode_frame(raw)
+    assert parsed.frame_type == Type.SET_ALL and parsed.crc_ok
+    assert parsed.payload == bytes(24) + bytes([20] * 8)
+    golden = GOLDEN["fixed_vectors"]
+    assert decode_frame(bytes.fromhex(golden["get_all"])).frame_type == Type.GET_ALL
+    ack = decode_frame(bytes.fromhex(golden["get_all_ack"]))
+    assert ack.frame_type == Type.ACK_NACK and ack.payload[0] == Type.GET_ALL
+    ka = decode_frame(bytes.fromhex(golden["keepalive"]))
+    assert ka.frame_type == Type.OUTPUT_KEEPALIVE
+    corrupted = bytearray(raw)
+    corrupted[-1] ^= 0xFF
+    assert not decode_frame(bytes(corrupted)).crc_ok
+    assert STATUS[0] == "OK" and len(STATUS) == 10
+    return 0
 
 
 def run_gui() -> int:
@@ -171,15 +173,16 @@ def run_gui() -> int:
         command = bytes((0x00, 0x10, 0x01))
         output.set("I2C 0x2A W: " + frame_hex(staging) + " | COMMAND W: " + frame_hex(command))
     ttk.Button(i2c_set, text="Generate staging + COMMAND=01", command=make_i2c_set).pack(anchor="w", padx=10, pady=8)
-    ttk.Label(i2c_set, text="Write 0x0100..0x011F (32 bytes), then write 0x0010=0x01; poll 0x0000..0x0008 for response.").pack(anchor="w", padx=10)
+    ttk.Label(i2c_set, text="Mailbox: write LENGTH_L 0x0011=0x20 (fresh staging session), LENGTH_H 0x0012=0x00, payload 0x0100..0x011F sequentially, then COMMAND 0x0010=0x01 to submit. Poll DEVICE_STATUS 0x0000 bit1 for response_valid; read RESPONSE_* 0x0001..0x0006.").pack(anchor="w", padx=10)
 
-    i2c_get = page("I2C GET_SNAPSHOT")
-    ttk.Label(i2c_get, text="Write 0x0010=0x02, poll response registers, read length at 0x0007/0x0008, then read 0x0200.. sequentially.").pack(anchor="w", padx=10, pady=8)
-    ttk.Button(i2c_get, text="Generate COMMAND=02", command=lambda: output.set("I2C 0x2A W: 00 10 02 | STATUS: 00 00 00 08 | DATA: 02 00 ...")).pack(anchor="w", padx=10, pady=8)
+    i2c_get = page("I2C GET_ALL")
+    ttk.Label(i2c_get, text="Write LENGTH_L 0x0011=0x00 (length 0 needs no payload), then COMMAND 0x0010=0x02. After response_valid, read RESPONSE_LENGTH 0x0005/0x0006 and the data window 0x0200..0x05FF.").pack(anchor="w", padx=10, pady=8)
+    ttk.Button(i2c_get, text="Generate COMMAND=02 sequence", command=lambda: output.set("I2C 0x2A W: 00 11 00 (LENGTH_L=0) | 00 10 02 (COMMAND=GET_ALL) | read 0x0000 bit1 | read 0x0005/0x0006 + 0x0200..")).pack(anchor="w", padx=10, pady=8)
 
-    get_page = page("UART GET reply 06 -> 82")
-    ttk.Button(get_page, text="Generate GET_SNAPSHOT", command=lambda: output.set(frame_hex(encode(2)))).pack(anchor="w", padx=10, pady=10)
-    ttk.Label(get_page, text="Device replies exactly: 0x06 ACK/NACK, then 0x82 SNAPSHOT_DATA. Banks and Host port remain locked through DATA stop bit.", wraplength=1050).pack(anchor="w", padx=10)
+    get_page = page("UART GET_ALL reply 80 -> 81")
+    ttk.Button(get_page, text="Generate GET_ALL", command=lambda: output.set(frame_hex(encode_frame(Type.GET_ALL)))).pack(anchor="w", padx=10, pady=10)
+    ttk.Button(get_page, text="Generate OUTPUT_KEEPALIVE (05)", command=lambda: output.set(frame_hex(encode_frame(Type.OUTPUT_KEEPALIVE)))).pack(anchor="w", padx=10, pady=4)
+    ttk.Label(get_page, text="Device latches the snapshot, replies 0x80 ACK/NACK then 0x81 ALL_STATUS_DATA. Banks and Host port remain locked through DATA stop bit.", wraplength=1050).pack(anchor="w", padx=10)
 
     retired = page("Retired commands")
     ttk.Label(retired, text="Automatic-control commands are removed from the active 6400 product.").pack(anchor="w", padx=10, pady=10)
@@ -213,4 +216,6 @@ def run_gui() -> int:
 
 
 if __name__ == "__main__":
+    if "--self-test" in sys.argv:
+        raise SystemExit(self_test())
     raise SystemExit(run_gui())

+ 205 - 0
tools/_vendor/hth_protocol.py

@@ -0,0 +1,205 @@
+"""Unified Prod2U host protocol codec (16-bit length, 2026 contract).
+
+Wire format (both 6400-front-rear and mrdimm-chamber products):
+
+    A5 5A | TYPE:u8 | LENGTH:u16le | PAYLOAD | CRC:u16le
+
+CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, xorout 0.
+CRC covers TYPE + LENGTH_LOW + LENGTH_HIGH + PAYLOAD; the A5 5A preamble
+is not covered.
+
+This module is the independent host-side reference implementation.  It is
+deliberately written from the protocol contract text, not shared with the
+RTL frame parser, so the fixed contract vectors below are a cross-check
+between two independent implementations.
+
+Breaking change vs the historical 8-bit-length frames: old consumers must
+not be fed these frames and vice versa; there is no legacy autodetect.
+"""
+
+from __future__ import annotations
+
+from enum import IntEnum
+
+PREAMBLE = b"\xA5\x5A"
+HEADER_SIZE = 4  # preamble(2) + type(1) + length(2)... preamble excluded from CRC
+MAX_REQUEST_PAYLOAD = 256
+MAX_RESPONSE_PAYLOAD = 1024
+
+
+class Type(IntEnum):
+    SET_ALL = 0x01
+    GET_ALL = 0x02
+    MOTOR_QUEUE_WRITE = 0x03
+    MOTOR_CONTROL = 0x04
+    OUTPUT_KEEPALIVE = 0x05
+    EVENT_READ = 0x08
+    EVENT_CLEAR = 0x09
+    ACK_NACK = 0x80
+    ALL_STATUS_DATA = 0x81
+    EVENT_DATA = 0x83
+
+
+REQUEST_TYPES = frozenset(
+    {
+        Type.SET_ALL,
+        Type.GET_ALL,
+        Type.MOTOR_QUEUE_WRITE,
+        Type.MOTOR_CONTROL,
+        Type.OUTPUT_KEEPALIVE,
+        Type.EVENT_READ,
+        Type.EVENT_CLEAR,
+    }
+)
+
+RESPONSE_TYPES = frozenset({Type.ACK_NACK, Type.ALL_STATUS_DATA, Type.EVENT_DATA})
+
+
+class Status(IntEnum):
+    OK = 0
+    UNSUPPORTED = 1
+    BAD_LENGTH = 2
+    BAD_VALUE = 3
+    BUSY = 4
+    QUEUE_FULL = 5
+    BAD_AXIS = 6
+    BAD_MODE = 7
+    BAD_REGISTER = 8
+    NOT_READY = 9
+
+
+def crc16_ccitt_false(data: bytes) -> int:
+    """CRC-16/CCITT-FALSE over ``data`` (MSB first, init 0xFFFF)."""
+    value = 0xFFFF
+    for byte in data:
+        value ^= byte << 8
+        for _ in range(8):
+            value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
+    return value
+
+
+def encode_frame(frame_type: int, payload: bytes = b"") -> bytes:
+    """Encode one frame.  Payload must be at most 65535 bytes."""
+    if not 0 <= int(frame_type) <= 0xFF:
+        raise ValueError("frame type must fit in u8")
+    if len(payload) > 0xFFFF:
+        raise ValueError("payload longer than 16-bit length field")
+    body = bytes([int(frame_type), len(payload) & 0xFF, (len(payload) >> 8) & 0xFF]) + payload
+    return PREAMBLE + body + crc16_ccitt_false(body).to_bytes(2, "little")
+
+
+def encode_ack(request_type: int, status: int, detail: int = 0) -> bytes:
+    """ACK_NACK (0x80): fixed 4-byte payload request_type/status/detail:u16le."""
+    return encode_frame(
+        Type.ACK_NACK,
+        bytes([int(request_type) & 0xFF, int(status) & 0xFF]) + int(detail).to_bytes(2, "little"),
+    )
+
+
+class Frame:
+    __slots__ = ("frame_type", "payload", "crc_ok")
+
+    def __init__(self, frame_type: int, payload: bytes, crc_ok: bool) -> None:
+        self.frame_type = frame_type
+        self.payload = payload
+        self.crc_ok = crc_ok
+
+    def __repr__(self) -> str:  # pragma: no cover - debug aid
+        return f"Frame(type=0x{self.frame_type:02X}, len={len(self.payload)}, crc_ok={self.crc_ok})"
+
+
+class FrameParser:
+    """Streaming byte-at-a-time frame parser.
+
+    Semantics required by the contract:
+
+    - Syncs on the A5 5A preamble; garbage before a preamble is skipped.
+    - Once a header is accepted the declared 16-bit length is trusted: the
+      whole payload plus trailing CRC is consumed even if the CRC fails
+      (an over-long declared length is consumed, not used to bound RAM).
+    - An A5 5A inside a payload is never treated as a new frame.
+    - Frames with bad CRC are surfaced with ``crc_ok=False`` so the caller
+      can drop them silently; nothing else is emitted for them.
+    """
+
+    _SYNC0, _SYNC1, _TYPE, _LEN_LO, _LEN_HI, _PAYLOAD, _CRC_LO, _CRC_HI = range(8)
+
+    def __init__(self) -> None:
+        self._state = self._SYNC0
+        self._frame_type = 0
+        self._length = 0
+        self._remaining = 0
+        self._body = bytearray()  # type + length bytes + payload (CRC input)
+        self._payload = bytearray()
+        self._crc = 0
+
+    def feed(self, data: bytes) -> list[Frame]:
+        frames: list[Frame] = []
+        for byte in data:
+            frame = self._step(byte)
+            if frame is not None:
+                frames.append(frame)
+        return frames
+
+    def _step(self, byte: int) -> Frame | None:
+        state = self._state
+        if state == self._SYNC0:
+            if byte == 0xA5:
+                self._state = self._SYNC1
+            return None
+        if state == self._SYNC1:
+            if byte == 0x5A:
+                self._state = self._TYPE
+            elif byte == 0xA5:
+                self._state = self._SYNC1
+            else:
+                self._state = self._SYNC0
+            return None
+        if state == self._TYPE:
+            self._frame_type = byte
+            self._body = bytearray([byte])
+            self._state = self._LEN_LO
+            return None
+        if state == self._LEN_LO:
+            self._length = byte
+            self._body.append(byte)
+            self._state = self._LEN_HI
+            return None
+        if state == self._LEN_HI:
+            self._length |= byte << 8
+            self._body.append(byte)
+            self._remaining = self._length
+            self._payload = bytearray()
+            self._state = self._PAYLOAD if self._length else self._CRC_LO
+            return None
+        if state == self._PAYLOAD:
+            self._payload.append(byte)
+            self._body.append(byte)
+            self._remaining -= 1
+            if self._remaining == 0:
+                self._state = self._CRC_LO
+            return None
+        if state == self._CRC_LO:
+            self._crc = byte
+            self._state = self._CRC_HI
+            return None
+        # _CRC_HI
+        self._crc |= byte << 8
+        self._state = self._SYNC0
+        expected = crc16_ccitt_false(bytes(self._body))
+        return Frame(self._frame_type, bytes(self._payload), self._crc == expected)
+
+
+def decode_frame(raw: bytes) -> Frame:
+    """Decode one complete frame from ``raw`` (must be exactly one frame)."""
+    frames = FrameParser().feed(raw)
+    if not frames:
+        raise ValueError("no complete frame in input")
+    return frames[0]
+
+
+# Fixed contract vectors (verified independently against this codec by the
+# test suite; they must never be regenerated by the RTL under test).
+VECTOR_GET_ALL = bytes.fromhex("A55A020000FCA2")
+VECTOR_GET_ALL_ACK = bytes.fromhex("A55A800400020000 00FEB1".replace(" ", ""))
+VECTOR_KEEPALIVE = bytes.fromhex("A55A0500006C27")

+ 1 - 0
tools/_vendor/hth_protocol.sha256

@@ -0,0 +1 @@
+089aa238c1b4ce836fc4a30d2566953d71a091c898570336882ee0bc5c0c148a

+ 10 - 3
tools/build_6400_hex_gui.py

@@ -22,9 +22,14 @@ def main() -> int:
     parser = argparse.ArgumentParser()
     parser.add_argument("--profile", choices=("6400-front-rear",), default="6400-front-rear")
     parser.add_argument("--output-dir", type=Path, required=True)
-    parser.add_argument("--bitstream-sha256", required=True)
+    parser.add_argument("--bitstream", type=Path, required=True,
+                        help="real TD bitstream file; its SHA-256 is computed here")
     parser.add_argument("--wsl-source-root")
     args = parser.parse_args()
+    bitstream = args.bitstream.resolve()
+    if not bitstream.is_file():
+        raise SystemExit(f"bitstream file not found: {bitstream}")
+    bitstream_sha = hashlib.sha256(bitstream.read_bytes()).hexdigest()
     contract_path = ROOT / "generated/6400/host-contract.json"
     golden_path = ROOT / "generated/6400/golden-vectors.json"
     contract = json.loads(contract_path.read_text(encoding="utf-8"))
@@ -43,7 +48,7 @@ def main() -> int:
         raise SystemExit("GUI packaging requires an exact clean commit")
     output = args.output_dir.resolve()
     output.mkdir(parents=True, exist_ok=True)
-    meta = {"profile": args.profile, "commit": commit, "contract_sha256": contract["contract_sha256"], "bitstream_sha256": args.bitstream_sha256}
+    meta = {"profile": args.profile, "commit": commit, "contract_sha256": contract["contract_sha256"], "bitstream_sha256": bitstream_sha}
     meta_path = output / "gui-build-metadata.json"
     meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
     name = f"6400-HEX-GUI-{args.profile}-{commit[:8]}-{contract['contract_sha256'][:8]}"
@@ -52,7 +57,9 @@ def main() -> int:
     command = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", "--onefile", "--windowed",
         "--name", name, "--distpath", str(output), "--workpath", str(work), "--specpath", str(work),
         "--add-data", f"{contract_path}{sep}generated/6400", "--add-data", f"{golden_path}{sep}generated/6400",
-        "--add-data", f"{meta_path}{sep}.", str(ROOT / "tools/6400_hex_gui.py")]
+        "--add-data", f"{meta_path}{sep}.",
+        "--paths", str(ROOT / "tools/_vendor"), "--hidden-import", "hth_protocol",
+        str(ROOT / "tools/6400_hex_gui.py")]
     subprocess.run(command, cwd=ROOT, check=True)
     exe = output / (name + (".exe" if sys.platform == "win32" else ""))
     if sys.platform != "win32" or exe.read_bytes()[:2] != b"MZ":

+ 6 - 3
tools/build_mrdimm_hex_gui.py

@@ -5,17 +5,20 @@ import argparse, hashlib, json, shutil, subprocess, sys
 from pathlib import Path
 ROOT = Path(__file__).resolve().parents[1]
 def main() -> int:
-    ap = argparse.ArgumentParser(); ap.add_argument("--output-dir", type=Path, required=True); ap.add_argument("--bitstream-sha256", default="NOT_BUILT"); a = ap.parse_args()
+    ap = argparse.ArgumentParser(); ap.add_argument("--output-dir", type=Path, required=True); ap.add_argument("--bitstream", type=Path, required=True, help="real TD bitstream file"); a = ap.parse_args()
+    bitstream = a.bitstream.resolve()
+    if not bitstream.is_file(): raise SystemExit(f"bitstream file not found: {bitstream}")
+    bitstream_sha = hashlib.sha256(bitstream.read_bytes()).hexdigest()
     contract_path = ROOT/"src/generated/host-contract.json"
     contract = json.loads(contract_path.read_text(encoding="utf-8")); out = a.output_dir.resolve(); out.mkdir(parents=True, exist_ok=True)
     contract_sha = contract.get("contract_sha256") or hashlib.sha256(contract_path.read_bytes()).hexdigest()
     commit = subprocess.check_output(["git","rev-parse","HEAD"], cwd=ROOT, text=True).strip()
     if subprocess.check_output(["git","status","--porcelain"], cwd=ROOT, text=True).strip(): raise SystemExit("GUI packaging requires clean commit")
-    meta = {"product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"contract_sha256":contract_sha,"bitstream_sha256":a.bitstream_sha256}
+    meta = {"product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"contract_sha256":contract_sha,"bitstream_sha256":bitstream_sha}
     (out/"gui-build-metadata.json").write_text(json.dumps(meta, indent=2)+"\n", encoding="utf-8")
     name = f"Prod2U-MRDIMM-V1.2-HEX-GUI-{commit[:8]}-{meta['contract_sha256'][:8]}"
     work = out/("pyinstaller-"+name); sep = ";" if sys.platform == "win32" else ":"
-    cmd=[sys.executable,"-m","PyInstaller","--noconfirm","--clean","--onefile","--windowed","--name",name,"--distpath",str(out),"--workpath",str(work),"--specpath",str(work),"--add-data",f"{contract_path}{sep}.","--add-data",f"{out/'gui-build-metadata.json'}{sep}.",str(ROOT/"tools/mrdimm_hex_gui.py")]
+    cmd=[sys.executable,"-m","PyInstaller","--noconfirm","--clean","--onefile","--windowed","--name",name,"--distpath",str(out),"--workpath",str(work),"--specpath",str(work),"--add-data",f"{contract_path}{sep}.","--add-data",f"{out/'gui-build-metadata.json'}{sep}.","--paths",str(ROOT/"tools/_vendor"),"--hidden-import","hth_protocol",str(ROOT/"tools/mrdimm_hex_gui.py")]
     subprocess.run(cmd,cwd=ROOT,check=True); exe=out/(name+(".exe" if sys.platform=="win32" else ""))
     if sys.platform=="win32" and exe.read_bytes()[:2] != b"MZ": raise SystemExit("not a Windows PE")
     zip_path=out/(name+".zip"); shutil.make_archive(str(zip_path.with_suffix("")),"zip",root_dir=out,base_dir=exe.name)

+ 93 - 45
tools/mrdimm_hex_gui.py

@@ -1,83 +1,131 @@
 #!/usr/bin/env python3
-"""Offline MRDIMM V1.2 HEX encoder/decoder and small Tk GUI.
+"""Offline MRDIMM V1.2 HEX encoder/decoder and small Tk GUI (2026 contract).
 
-No serial, I2C, JTAG, or hardware access is performed.  The executable is
-bound to the generated MRDIMM contract and only emits/decodes wire frames.
+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
-from typing import Iterable
+
+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 / "src" / "generated"]
+    roots += [Path(__file__).resolve().parent.parent / "generated" / "mrdimm"]
     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
+try:
+    METADATA = json.loads(_asset("gui-build-metadata.json").read_text(encoding="utf-8"))
+except FileNotFoundError:
+    METADATA = {"commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
 
-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]
+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], 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 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:
-    kind, payload = decode(frame)
-    return f"type=0x{kind:02X} payload_len={len(payload)} payload={payload.hex(' ').upper()}"
+    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(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 %"]
+    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//6, column=i%6, padx=6, pady=6)
+        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]]
-            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)))
+            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))
-    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)
+    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__": raise SystemExit(run_gui())
+if __name__ == "__main__":
+    if "--self-test" in sys.argv:
+        raise SystemExit(self_test())
+    raise SystemExit(run_gui())