#!/usr/bin/env python3 """Contract-driven 6400 HEX generator/parser. It never opens a serial port.""" from __future__ import annotations import json import re import sys from pathlib import Path from typing import Any, Iterable def asset(name: str) -> Path: base = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[1])) direct = base / name return direct if direct.exists() else base / "generated" / "6400" / name CONTRACT = json.loads(asset("host-contract.json").read_text(encoding="utf-8")) GOLDEN = json.loads(asset("golden-vectors.json").read_text(encoding="utf-8")) METADATA = json.loads(asset("gui-build-metadata.json").read_text(encoding="utf-8")) if asset("gui-build-metadata.json").exists() else { "profile": "source", "commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT" } WIRE = CONTRACT["wire"] COMMANDS = WIRE["commands"] 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): raise ValueError("HEX must contain an even number of hexadecimal digits") 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) 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)) def describe(frame: bytes) -> str: kind, payload = decode(frame) if kind == int(RESPONSES["ACK_NACK"]["type"]): 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"]): layout = CONTRACT["snapshot"] if len(payload) != int(layout["payload_length"]): raise ValueError("SNAPSHOT_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()}" def run_gui() -> int: import tkinter as tk from tkinter import messagebox, ttk root = tk.Tk() profile = METADATA["profile"] root.title(f"6400 HEX GUI — {profile}") root.geometry("1180x820") notebook = ttk.Notebook(root) notebook.pack(fill="both", expand=True, padx=8, pady=8) output = tk.StringVar() def page(title: str) -> ttk.Frame: frame = ttk.Frame(notebook) notebook.add(frame, text=title) return frame summary = page("Build / Contract") facts = [ ("Product", "6400-front-rear"), ("Board", "FCB V1.1"), ("Profile", profile), ("CPLD commit", METADATA["commit"]), ("Contract SHA", CONTRACT["contract_sha256"]), ("Bitstream SHA", METADATA["bitstream_sha256"]), ("Host", "RS232/TTL 921600 8N1"), ("BMC", "RS232 115200 8N1"), ("PTC PWM", f"{CONTRACT['fan_control']['pwm']['ptc_hz']} Hz"), ("FAN PWM", f"{CONTRACT['fan_control']['pwm']['fan_hz']} Hz"), ("SET_ALL watchdog", "30 s"), ("Default PID target", "70 C"), ("FAN_BOARD_INVERT_MASK", "0x0F"), ] for row, (key, value) in enumerate(facts): ttk.Label(summary, text=key + ":", width=24).grid(row=row, column=0, sticky="w", padx=8, pady=5) ttk.Label(summary, text=str(value)).grid(row=row, column=1, sticky="w", padx=8, pady=5) set_page = page("SET_ALL 32 channels") variables = [tk.IntVar(value=0 if index < 24 else 20) for index in range(32)] labels = [f"PTC{i}" for i in range(24)] + [f"Front{i}" for i in range(4)] + [f"Rear{i}" for i in range(4)] for index, (label, variable) in enumerate(zip(labels, variables)): row, column = divmod(index, 8) cell = ttk.Frame(set_page) cell.grid(row=row, column=column, padx=6, pady=7) ttk.Label(cell, text=label).pack() ttk.Spinbox(cell, from_=0, to=100, width=7, textvariable=variable).pack() def make_set_all() -> None: try: output.set(frame_hex(set_all([value.get() for value in variables]))) except Exception as exc: messagebox.showerror("SET_ALL", str(exc)) ttk.Button(set_page, text="Generate SET_ALL", command=make_set_all).grid(row=5, column=0, columnspan=2, pady=10) ttk.Label(set_page, text="Order: PTC0..23, Front0..3, Rear0..3. Values are connector high-level duty.").grid(row=5, column=2, columnspan=6, sticky="w") ttk.Label(set_page, text="MANUAL OPEN-LOOP — BMC TEMPERATURE MAY BE UNAVAILABLE", foreground="red").grid(row=6, column=0, columnspan=8, sticky="w", padx=8) ttk.Label(set_page, text="MANUAL WITHOUT BMC HAS NO BMC-BASED OVERTEMPERATURE PROTECTION", foreground="red").grid(row=7, column=0, columnspan=8, sticky="w", padx=8) get_page = page("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) pid_page = page("SET_PID_TARGET") pid = tk.IntVar(value=70) ttk.Spinbox(pid_page, from_=20, to=70, textvariable=pid, width=8).pack(anchor="w", padx=10, pady=10) ttk.Button(pid_page, text="Generate SET_PID_TARGET", command=lambda: output.set(frame_hex(encode(4, bytes((pid.get(),)))))).pack(anchor="w", padx=10) ttk.Label(pid_page, text="Updates the next PID_AUTO target only; it does not start PID, change Manual output, or feed watchdog.").pack(anchor="w", padx=10, pady=10) stimulus = page("0x03 profile behavior") enabled = "Valid SET_STIMULUS preserves type/payload and receives UNSUPPORTED NACK" ttk.Label(stimulus, text=enabled).pack(anchor="w", padx=10, pady=10) parser = page("ACK/NACK + Snapshot parser") parse_input = tk.Text(parser, height=8) parse_input.pack(fill="x", padx=10, pady=10) parsed = tk.StringVar() def parse_action() -> None: try: parsed.set(describe(parse_hex(parse_input.get("1.0", "end")))) except Exception as exc: parsed.set("ERROR: " + str(exc)) ttk.Button(parser, text="Parse frame", command=parse_action).pack(anchor="w", padx=10) ttk.Label(parser, textvariable=parsed, wraplength=1080).pack(anchor="w", padx=10, pady=10) polarity = page("Fan polarity / 20% example") ttk.Label(polarity, text="Contract, GUI, Snapshot, Requested and Applied FAN values are connector-side high-level duty.", wraplength=1050).pack(anchor="w", padx=10, pady=8) ttk.Label(polarity, text="Single adapter mask 0x0F: Front balls are inverted, Rear balls are direct. At connector 20%: each 50,000-clock period has 10,000 connector-high clocks; Front ball low 10,000; Rear ball high 10,000.", wraplength=1050).pack(anchor="w", padx=10, pady=8) for value in (0, 20, 50, 100): ttk.Label(polarity, text=f"Connector {value:3d}% -> Front ball low {value:3d}% / Rear ball high {value:3d}%").pack(anchor="w", padx=10) footer = ttk.Frame(root) footer.pack(fill="x", padx=8, pady=(0, 8)) ttk.Entry(footer, textvariable=output, font=("Consolas", 9)).pack(side="left", fill="x", expand=True) ttk.Button(footer, text="Copy HEX", command=lambda: (root.clipboard_clear(), root.clipboard_append(output.get()))).pack(side="left", padx=5) make_set_all() root.mainloop() return 0 if __name__ == "__main__": raise SystemExit(run_gui())