6400_hex_gui.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. def _vendor() -> Path:
  9. return Path(__file__).resolve().parent / "_vendor" / "hth_protocol.py"
  10. try:
  11. from hth_protocol import Type, decode_frame, encode_frame
  12. except ImportError:
  13. sys.path.insert(0, str(_vendor().parent))
  14. from hth_protocol import Type, decode_frame, encode_frame
  15. def asset(name: str) -> Path:
  16. if getattr(sys, "_MEIPASS", None):
  17. roots = [Path(sys._MEIPASS)]
  18. else:
  19. script_dir = Path(__file__).resolve().parent
  20. roots = [script_dir, script_dir / "generated" / "6400", script_dir.parent / "generated" / "6400"]
  21. for root in roots:
  22. direct = root / name
  23. if direct.exists():
  24. return direct
  25. tried = ", ".join(str(root / name) for root in roots)
  26. raise FileNotFoundError(f"GUI asset not found: {name}; tried: {tried}")
  27. CONTRACT = json.loads(asset("manual-uart-contract.json").read_text(encoding="utf-8"))
  28. GOLDEN = json.loads(asset("golden-vectors.json").read_text(encoding="utf-8"))
  29. try:
  30. METADATA = json.loads(asset("gui-build-metadata.json").read_text(encoding="utf-8"))
  31. except FileNotFoundError:
  32. METADATA = {"profile": "source", "commit": "WORKTREE", "bitstream_sha256": "NOT_BUILT"}
  33. WIRE = CONTRACT["wire"]
  34. UART_WIRE = WIRE.get("uart", WIRE)
  35. I2C_WIRE = WIRE.get("host_i2c", {})
  36. COMMANDS = WIRE["commands"]
  37. RESPONSES = WIRE["responses"]
  38. STATUS = {int(value): name for name, value in RESPONSES["ACK_NACK"]["status"].items()}
  39. def parse_hex(text: str) -> bytes:
  40. compact = re.sub(r"[\s:_-]+", "", text)
  41. if not compact or len(compact) % 2 or not re.fullmatch(r"[0-9A-Fa-f]+", compact):
  42. raise ValueError("HEX must contain an even number of hexadecimal digits")
  43. return bytes.fromhex(compact)
  44. def frame_hex(frame: bytes) -> str:
  45. return " ".join(f"{byte:02X}" for byte in frame)
  46. def set_all(values: list[int]) -> bytes:
  47. if len(values) != 32 or any(not 0 <= value <= 100 for value in values):
  48. raise ValueError("SET_ALL requires 32 connector duties in 0..100")
  49. return encode_frame(Type.SET_ALL, bytes(values))
  50. def describe(frame: bytes) -> str:
  51. parsed = decode_frame(frame)
  52. kind, payload, ok = parsed.frame_type, parsed.payload, parsed.crc_ok
  53. head = f"crc_ok={ok} "
  54. if kind == Type.ACK_NACK:
  55. if len(payload) != 4:
  56. raise ValueError("ACK/NACK payload must be 4 bytes")
  57. request, status, detail = payload[0], payload[1], int.from_bytes(payload[2:4], "little")
  58. return head + (f"ACK/NACK request=0x{request:02X} "
  59. f"status={STATUS.get(status, 'UNKNOWN')} detail={detail}")
  60. if kind == Type.ALL_STATUS_DATA:
  61. layout = CONTRACT["snapshot"]
  62. if len(payload) != int(layout["payload_length"]):
  63. raise ValueError("ALL_STATUS_DATA payload length mismatch")
  64. fields: list[str] = []
  65. for field in layout["fields"][:13]:
  66. chunk = payload[field["offset"]:field["offset"] + field["size"]]
  67. fields.append(f"{field['name']}={int.from_bytes(chunk, 'little')}")
  68. return head + "ALL_STATUS_DATA " + ", ".join(fields)
  69. return head + f"type=0x{kind:02X} payload={payload.hex(' ').upper()}"
  70. def self_test() -> int:
  71. """Offline generate/decode coverage; exit 0 = pass (no Tk, no COM)."""
  72. raw = set_all([0] * 24 + [20] * 8)
  73. parsed = decode_frame(raw)
  74. assert parsed.frame_type == Type.SET_ALL and parsed.crc_ok
  75. assert parsed.payload == bytes(24) + bytes([20] * 8)
  76. golden = GOLDEN["fixed_vectors"]
  77. assert decode_frame(bytes.fromhex(golden["get_all"])).frame_type == Type.GET_ALL
  78. ack = decode_frame(bytes.fromhex(golden["get_all_ack"]))
  79. assert ack.frame_type == Type.ACK_NACK and ack.payload[0] == Type.GET_ALL
  80. ka = decode_frame(bytes.fromhex(golden["keepalive"]))
  81. assert ka.frame_type == Type.OUTPUT_KEEPALIVE
  82. corrupted = bytearray(raw)
  83. corrupted[-1] ^= 0xFF
  84. assert not decode_frame(bytes(corrupted)).crc_ok
  85. assert STATUS[0] == "OK" and len(STATUS) == 10
  86. return 0
  87. def run_gui() -> int:
  88. import tkinter as tk
  89. from tkinter import messagebox, ttk
  90. root = tk.Tk()
  91. profile = METADATA["profile"]
  92. root.title(f"6400 HEX GUI — {profile}")
  93. root.geometry("1180x820")
  94. notebook = ttk.Notebook(root)
  95. notebook.pack(fill="both", expand=True, padx=8, pady=8)
  96. output = tk.StringVar()
  97. def page(title: str) -> ttk.Frame:
  98. frame = ttk.Frame(notebook)
  99. notebook.add(frame, text=title)
  100. return frame
  101. summary = page("Build / Contract")
  102. facts = [
  103. ("Product", "6400-front-rear"), ("Board", "FCB V1.1"),
  104. ("Profile", profile), ("CPLD commit", METADATA["commit"]),
  105. ("Contract SHA", CONTRACT["contract_sha256"]),
  106. ("Bitstream SHA", METADATA["bitstream_sha256"]),
  107. ("Host UART", f"{UART_WIRE['baud']} {UART_WIRE['format']}"),
  108. ("Host I2C", f"0x{int(I2C_WIRE['address_7bit']):02X} / 16-bit / CON36"),
  109. ("PTC PWM", f"{CONTRACT['outputs']['ptc_pwm_hz']} Hz"),
  110. ("FAN PWM", f"{CONTRACT['outputs']['fan_pwm_hz']} Hz"),
  111. ("SET_ALL watchdog", f"{CONTRACT['watchdog']['seconds']} s"),
  112. ("Control mode", "SAFE / MANUAL OPEN-LOOP"),
  113. ("FAN_BOARD_INVERT_MASK", f"0x{CONTRACT['outputs']['fan_board_invert_mask']:02X}"),
  114. ("Safety", "76C channel off / 77C lane hard"),
  115. ]
  116. for row, (key, value) in enumerate(facts):
  117. ttk.Label(summary, text=key + ":", width=24).grid(row=row, column=0, sticky="w", padx=8, pady=5)
  118. ttk.Label(summary, text=str(value)).grid(row=row, column=1, sticky="w", padx=8, pady=5)
  119. set_page = page("SET_ALL 32 channels")
  120. variables = [tk.IntVar(value=0 if index < 24 else 20) for index in range(32)]
  121. 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)]
  122. for index, (label, variable) in enumerate(zip(labels, variables)):
  123. row, column = divmod(index, 8)
  124. cell = ttk.Frame(set_page)
  125. cell.grid(row=row, column=column, padx=6, pady=7)
  126. ttk.Label(cell, text=label).pack()
  127. ttk.Spinbox(cell, from_=0, to=100, width=7, textvariable=variable).pack()
  128. def make_set_all() -> None:
  129. try:
  130. output.set(frame_hex(set_all([value.get() for value in variables])))
  131. except Exception as exc:
  132. messagebox.showerror("SET_ALL", str(exc))
  133. ttk.Button(set_page, text="Generate SET_ALL", command=make_set_all).grid(row=5, column=0, columnspan=2, pady=10)
  134. 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")
  135. 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)
  136. 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)
  137. i2c_set = page("I2C SET_ALL")
  138. ttk.Label(i2c_set, text="Standard 7-bit slave, 16-bit register pointer MSB first; no clock stretching.").pack(anchor="w", padx=10, pady=8)
  139. def make_i2c_set() -> None:
  140. values = [value.get() for value in variables]
  141. if len(values) != 32 or any(not 0 <= value <= 100 for value in values):
  142. messagebox.showerror("I2C SET_ALL", "All values must be 0..100")
  143. return
  144. payload = bytes(values)
  145. staging = bytes((0x01, 0x00)) + payload
  146. command = bytes((0x00, 0x10, 0x01))
  147. output.set("I2C 0x2A W: " + frame_hex(staging) + " | COMMAND W: " + frame_hex(command))
  148. ttk.Button(i2c_set, text="Generate staging + COMMAND=01", command=make_i2c_set).pack(anchor="w", padx=10, pady=8)
  149. 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)
  150. i2c_get = page("I2C GET_ALL")
  151. 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)
  152. 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)
  153. get_page = page("UART GET_ALL reply 80 -> 81")
  154. 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)
  155. 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)
  156. 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)
  157. retired = page("Retired commands")
  158. ttk.Label(retired, text="Automatic-control commands are removed from the active 6400 product.").pack(anchor="w", padx=10, pady=10)
  159. ttk.Label(retired, text="0x04 is reserved and must receive UNSUPPORTED; this GUI does not generate it.").pack(anchor="w", padx=10, pady=10)
  160. parser = page("ACK/NACK + Snapshot parser")
  161. parse_input = tk.Text(parser, height=8)
  162. parse_input.pack(fill="x", padx=10, pady=10)
  163. parsed = tk.StringVar()
  164. def parse_action() -> None:
  165. try:
  166. parsed.set(describe(parse_hex(parse_input.get("1.0", "end"))))
  167. except Exception as exc:
  168. parsed.set("ERROR: " + str(exc))
  169. ttk.Button(parser, text="Parse frame", command=parse_action).pack(anchor="w", padx=10)
  170. ttk.Label(parser, textvariable=parsed, wraplength=1080).pack(anchor="w", padx=10, pady=10)
  171. polarity = page("Fan polarity / 20% example")
  172. 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)
  173. 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)
  174. for value in (0, 20, 50, 100):
  175. ttk.Label(polarity, text=f"Connector {value:3d}% -> Front ball low {value:3d}% / Rear ball high {value:3d}%").pack(anchor="w", padx=10)
  176. footer = ttk.Frame(root)
  177. footer.pack(fill="x", padx=8, pady=(0, 8))
  178. ttk.Entry(footer, textvariable=output, font=("Consolas", 9)).pack(side="left", fill="x", expand=True)
  179. ttk.Button(footer, text="Copy HEX", command=lambda: (root.clipboard_clear(), root.clipboard_append(output.get()))).pack(side="left", padx=5)
  180. make_set_all()
  181. root.mainloop()
  182. return 0
  183. if __name__ == "__main__":
  184. if "--self-test" in sys.argv:
  185. raise SystemExit(self_test())
  186. raise SystemExit(run_gui())