6400_hex_gui.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #!/usr/bin/env python3
  2. """Contract-driven 6400 HEX generator/parser. It never opens a serial port."""
  3. from __future__ import annotations
  4. import json
  5. import re
  6. import sys
  7. from pathlib import Path
  8. from typing import Any, Iterable
  9. def asset(name: str) -> Path:
  10. if getattr(sys, "_MEIPASS", None):
  11. roots = [Path(sys._MEIPASS)]
  12. else:
  13. script_dir = Path(__file__).resolve().parent
  14. roots = [script_dir, script_dir / "generated" / "6400", script_dir.parent / "generated" / "6400"]
  15. for root in roots:
  16. direct = root / name
  17. if direct.exists():
  18. return direct
  19. tried = ", ".join(str(root / name) for root in roots)
  20. raise FileNotFoundError(f"GUI asset not found: {name}; tried: {tried}")
  21. CONTRACT = json.loads(asset("manual-uart-contract.json").read_text(encoding="utf-8"))
  22. GOLDEN = json.loads(asset("golden-vectors.json").read_text(encoding="utf-8"))
  23. try:
  24. METADATA = json.loads(asset("gui-build-metadata.json").read_text(encoding="utf-8"))
  25. except FileNotFoundError:
  26. METADATA = {"profile": "source", "commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
  27. WIRE = CONTRACT["wire"]
  28. COMMANDS = WIRE["commands"]
  29. RESPONSES = WIRE["responses"]
  30. STATUS = {int(value): name for name, value in RESPONSES["ACK_NACK"]["status"].items()}
  31. def crc16(data: Iterable[int]) -> int:
  32. value = 0xFFFF
  33. for byte in data:
  34. value ^= int(byte) << 8
  35. for _ in range(8):
  36. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  37. return value
  38. def encode(frame_type: int, payload: bytes = b"") -> bytes:
  39. body = bytes((frame_type, len(payload))) + payload
  40. check = crc16(body)
  41. return b"\xA5\x5A" + body + check.to_bytes(2, "little")
  42. def parse_hex(text: str) -> bytes:
  43. compact = re.sub(r"[\s:_-]+", "", text)
  44. if not compact or len(compact) % 2 or not re.fullmatch(r"[0-9A-Fa-f]+", compact):
  45. raise ValueError("HEX must contain an even number of hexadecimal digits")
  46. return bytes.fromhex(compact)
  47. def decode(frame: bytes) -> tuple[int, bytes]:
  48. if len(frame) < 6 or frame[:2] != b"\xA5\x5A":
  49. raise ValueError("bad A5 5A header or short frame")
  50. size = frame[3]
  51. if len(frame) != size + 6:
  52. raise ValueError(f"length mismatch: declared {size}, frame bytes {len(frame)}")
  53. expected = int.from_bytes(frame[-2:], "little")
  54. actual = crc16(frame[2:-2])
  55. if expected != actual:
  56. raise ValueError(f"CRC mismatch: wire {expected:04X}, calculated {actual:04X}")
  57. return frame[2], frame[4:-2]
  58. def frame_hex(frame: bytes) -> str:
  59. return " ".join(f"{byte:02X}" for byte in frame)
  60. def set_all(values: list[int]) -> bytes:
  61. if len(values) != 32 or any(not 0 <= value <= 100 for value in values):
  62. raise ValueError("SET_ALL requires 32 connector duties in 0..100")
  63. return encode(int(COMMANDS["SET_ALL"]["type"]), bytes(values))
  64. def describe(frame: bytes) -> str:
  65. kind, payload = decode(frame)
  66. if kind == int(RESPONSES["ACK_NACK"]["type"]):
  67. if len(payload) != 4:
  68. raise ValueError("ACK/NACK payload must be 4 bytes")
  69. ok, request, status, detail = payload
  70. return f"ACK/NACK ok={ok} request=0x{request:02X} status={STATUS.get(status, 'UNKNOWN')} detail={detail}"
  71. if kind == int(RESPONSES["SNAPSHOT_DATA"]["type"]):
  72. layout = CONTRACT["snapshot"]
  73. if len(payload) != int(layout["payload_length"]):
  74. raise ValueError("SNAPSHOT_DATA payload length mismatch")
  75. fields: list[str] = []
  76. for field in layout["fields"][:13]:
  77. chunk = payload[field["offset"]:field["offset"] + field["size"]]
  78. fields.append(f"{field['name']}={int.from_bytes(chunk, 'little')}")
  79. return "SNAPSHOT_DATA " + ", ".join(fields)
  80. return f"type=0x{kind:02X} payload={payload.hex(' ').upper()}"
  81. def run_gui() -> int:
  82. import tkinter as tk
  83. from tkinter import messagebox, ttk
  84. root = tk.Tk()
  85. profile = METADATA["profile"]
  86. root.title(f"6400 HEX GUI — {profile}")
  87. root.geometry("1180x820")
  88. notebook = ttk.Notebook(root)
  89. notebook.pack(fill="both", expand=True, padx=8, pady=8)
  90. output = tk.StringVar()
  91. def page(title: str) -> ttk.Frame:
  92. frame = ttk.Frame(notebook)
  93. notebook.add(frame, text=title)
  94. return frame
  95. summary = page("Build / Contract")
  96. facts = [
  97. ("Product", "6400-front-rear"), ("Board", "FCB V1.1"),
  98. ("Profile", profile), ("CPLD commit", METADATA["commit"]),
  99. ("Contract SHA", CONTRACT["contract_sha256"]),
  100. ("Bitstream SHA", METADATA["bitstream_sha256"]),
  101. ("Host", "RS232/TTL 921600 8N1"), ("BMC", "RS232 115200 8N1"),
  102. ("PTC PWM", f"{CONTRACT['fan_control']['pwm']['ptc_hz']} Hz"),
  103. ("FAN PWM", f"{CONTRACT['fan_control']['pwm']['fan_hz']} Hz"),
  104. ("SET_ALL watchdog", "30 s"), ("Control mode", "SAFE / MANUAL OPEN-LOOP"),
  105. ("FAN_BOARD_INVERT_MASK", "0x0F"),
  106. ]
  107. for row, (key, value) in enumerate(facts):
  108. ttk.Label(summary, text=key + ":", width=24).grid(row=row, column=0, sticky="w", padx=8, pady=5)
  109. ttk.Label(summary, text=str(value)).grid(row=row, column=1, sticky="w", padx=8, pady=5)
  110. set_page = page("SET_ALL 32 channels")
  111. variables = [tk.IntVar(value=0 if index < 24 else 20) for index in range(32)]
  112. 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)]
  113. for index, (label, variable) in enumerate(zip(labels, variables)):
  114. row, column = divmod(index, 8)
  115. cell = ttk.Frame(set_page)
  116. cell.grid(row=row, column=column, padx=6, pady=7)
  117. ttk.Label(cell, text=label).pack()
  118. ttk.Spinbox(cell, from_=0, to=100, width=7, textvariable=variable).pack()
  119. def make_set_all() -> None:
  120. try:
  121. output.set(frame_hex(set_all([value.get() for value in variables])))
  122. except Exception as exc:
  123. messagebox.showerror("SET_ALL", str(exc))
  124. ttk.Button(set_page, text="Generate SET_ALL", command=make_set_all).grid(row=5, column=0, columnspan=2, pady=10)
  125. 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")
  126. 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)
  127. 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)
  128. get_page = page("GET reply 06 -> 82")
  129. ttk.Button(get_page, text="Generate GET_SNAPSHOT", command=lambda: output.set(frame_hex(encode(2)))).pack(anchor="w", padx=10, pady=10)
  130. 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)
  131. retired = page("Retired commands")
  132. ttk.Label(retired, text="Automatic-control commands are removed from the active 6400 product.").pack(anchor="w", padx=10, pady=10)
  133. ttk.Label(retired, text="0x04 is reserved and must receive UNSUPPORTED; this GUI does not generate it.").pack(anchor="w", padx=10, pady=10)
  134. parser = page("ACK/NACK + Snapshot parser")
  135. parse_input = tk.Text(parser, height=8)
  136. parse_input.pack(fill="x", padx=10, pady=10)
  137. parsed = tk.StringVar()
  138. def parse_action() -> None:
  139. try:
  140. parsed.set(describe(parse_hex(parse_input.get("1.0", "end"))))
  141. except Exception as exc:
  142. parsed.set("ERROR: " + str(exc))
  143. ttk.Button(parser, text="Parse frame", command=parse_action).pack(anchor="w", padx=10)
  144. ttk.Label(parser, textvariable=parsed, wraplength=1080).pack(anchor="w", padx=10, pady=10)
  145. polarity = page("Fan polarity / 20% example")
  146. 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)
  147. 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)
  148. for value in (0, 20, 50, 100):
  149. ttk.Label(polarity, text=f"Connector {value:3d}% -> Front ball low {value:3d}% / Rear ball high {value:3d}%").pack(anchor="w", padx=10)
  150. footer = ttk.Frame(root)
  151. footer.pack(fill="x", padx=8, pady=(0, 8))
  152. ttk.Entry(footer, textvariable=output, font=("Consolas", 9)).pack(side="left", fill="x", expand=True)
  153. ttk.Button(footer, text="Copy HEX", command=lambda: (root.clipboard_clear(), root.clipboard_append(output.get()))).pack(side="left", padx=5)
  154. make_set_all()
  155. root.mainloop()
  156. return 0
  157. if __name__ == "__main__":
  158. raise SystemExit(run_gui())