generate_6400_manual.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #!/usr/bin/env python3
  2. """Generate the one active 6400 manual UART + standard Host-I2C contract.
  3. Every generated artifact is rendered from the original contract inputs in
  4. ``contracts/`` (YAML/JSON sources). Generated outputs are never read back
  5. as templates: deleting ``generated/`` entirely and regenerating must
  6. produce byte-identical results, and ``--check`` never writes.
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import hashlib
  11. import json
  12. from pathlib import Path
  13. from typing import Any
  14. import yaml
  15. ROOT = Path(__file__).resolve().parents[1]
  16. CONTRACTS = ROOT / "contracts"
  17. OUT = ROOT / "generated" / "6400"
  18. def canon(value: Any) -> bytes:
  19. return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
  20. def load_yaml(name: str) -> Any:
  21. return yaml.safe_load((CONTRACTS / name).read_text(encoding="utf-8"))
  22. def load_json(name: str) -> Any:
  23. return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
  24. def contract_hash(manual: dict[str, Any], wire: dict[str, Any], snapshot: dict[str, Any], fan: dict[str, Any], evidence: dict[str, Any]) -> str:
  25. payload = {"manual": manual, "wire": wire, "snapshot": snapshot, "fan": fan, "host_i2c_evidence_sha256": evidence["evidence_sha256"]}
  26. return hashlib.sha256(canon(payload)).hexdigest()
  27. def snapshot_layout(snapshot: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:
  28. sizes = {"u8": 1, "u16": 2, "u32": 4, "bytes": 1}
  29. offset, rows = 0, []
  30. for field in snapshot["fields"]:
  31. size = sizes[field["type"]] * int(field.get("count", 1))
  32. row = dict(field)
  33. row.update(offset=offset, size=size)
  34. rows.append(row)
  35. offset += size
  36. return rows, offset
  37. def crc16(body: bytes) -> int:
  38. value = 0xFFFF
  39. for byte in body:
  40. value ^= byte << 8
  41. for _ in range(8):
  42. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  43. return value
  44. def frame(kind: int, payload: bytes) -> str:
  45. """New 16-bit-length frame: A5 5A | TYPE | LEN:u16le | PAYLOAD | CRC:u16le."""
  46. body = bytes((kind, len(payload) & 0xFF, (len(payload) >> 8) & 0xFF)) + payload
  47. return (bytes((0xA5, 0x5A)) + body + crc16(body).to_bytes(2, "little")).hex().upper()
  48. def ack(request_type: int, status: int, detail: int = 0) -> str:
  49. return frame(0x80, bytes((request_type, status, detail & 0xFF, (detail >> 8) & 0xFF)))
  50. BT = chr(96)
  51. # Fixed contract vectors (16-bit protocol). These must never be produced by
  52. # the RTL under test; they are the cross-check between two independent
  53. # implementations.
  54. VECTOR_GET_ALL = "A55A020000FCA2"
  55. VECTOR_GET_ALL_ACK = "A55A800400020000 00FEB1".replace(" ", "")
  56. VECTOR_KEEPALIVE = "A55A0500006C27"
  57. PARAMS_HEADER_STATIC = """__BT__define FB_CLOCK_HZ 25000000
  58. __BT__define FB_PTC_COUNT 24
  59. __BT__define FB_FRONT_FAN_COUNT 4
  60. __BT__define FB_REAR_FAN_COUNT 4
  61. __BT__define FB_OUTPUT_COUNT 32
  62. __BT__define FB_BMC_COUNT 24
  63. __BT__define FB_CT_COUNT 27
  64. __BT__define FB_PRIMARY_COUNT 18
  65. __BT__define FB_HOLDOUT_COUNT 6
  66. __BT__define FB_HOST_BAUD 921600
  67. __BT__define FB_BMC_BAUD 115200
  68. __BT__define FB_HOST_FIXED_CLKS_PER_BIT 27
  69. __BT__define FB_BMC_CLKS_PER_BIT 217
  70. __BT__define FB_PWM_PHASES 100
  71. __BT__define FB_PTC_PWM_HZ 500
  72. __BT__define FB_FAN_PWM_HZ 500
  73. __BT__define FB_PTC_PWM_PHASE_CLKS 500
  74. __BT__define FB_FAN_PWM_PHASE_CLKS 500
  75. __BT__define FB_PTC_PWM_PERIOD_CLKS 50000
  76. __BT__define FB_FAN_PWM_PERIOD_CLKS 50000
  77. __BT__define FAN_BOARD_INVERT_MASK 8'h0F
  78. __BT__define FRONT_FAN_CONNECTOR_MAP "CON25.7,CON8.7,CON24.7,CON26.7"
  79. __BT__define FRONT_FAN_FPGA_BALL_MAP "B1,C4,B5,A14"
  80. __BT__define REAR_FAN_CONNECTOR_MAP "CON64.4,CON66.4,CON62.4,CON60.4"
  81. __BT__define REAR_FAN_FPGA_BALL_MAP "P15,N15,M14,P5"
  82. __BT__define FB_BOARD_ID "fcb_fpga_mcu_v1_1_20260625"
  83. __BT__define FB_BOARD_EVIDENCE_SHA256 "db02938f7943b2ae532aa18208f61588364d32a70a0cc72f74b4a94aaab7e258"
  84. __BT__define FB_TEMP_CHANNEL_CLAMP 7600
  85. __BT__define FB_TEMP_LANE_HARD 7700
  86. __BT__define FB_TEMP_LANE_RELEASE 7200
  87. __BT__define FAN_SAFE_DUTY 20
  88. __BT__define FAN_STANDBY_DUTY `FAN_SAFE_DUTY
  89. __BT__define FB_FAN_RESET `FAN_STANDBY_DUTY
  90. __BT__define FB_FAN_HARD 100
  91. __BT__define CONTROL_WATCHDOG_SECONDS 30
  92. __BT__define SET_ALL_WATCHDOG_SECONDS `CONTROL_WATCHDOG_SECONDS
  93. __BT__define FB_OWNER_SAFE 3'd0
  94. __BT__define FB_OWNER_MANUAL 3'd1
  95. // Unified 16-bit-length protocol (2026 contract). The historical 8-bit
  96. // length frames are retired; there is no wire autodetect.
  97. __BT__define FB_FRAME_LENGTH_WIDTH 16
  98. __BT__define FB_CMD_SET_ALL 8'h01
  99. __BT__define FB_CMD_GET_ALL 8'h02
  100. __BT__define FB_CMD_MOTOR_QUEUE_WRITE 8'h03
  101. __BT__define FB_CMD_MOTOR_CONTROL 8'h04
  102. __BT__define FB_CMD_OUTPUT_KEEPALIVE 8'h05
  103. __BT__define FB_CMD_EVENT_READ 8'h08
  104. __BT__define FB_CMD_EVENT_CLEAR 8'h09
  105. __BT__define FB_RSP_ACK_NACK 8'h80
  106. __BT__define FB_RSP_ALL_STATUS_DATA 8'h81
  107. __BT__define FB_RSP_EVENT_DATA 8'h83
  108. __BT__define FB_STATUS_OK 8'd0
  109. __BT__define FB_STATUS_UNSUPPORTED 8'd1
  110. __BT__define FB_STATUS_BAD_LENGTH 8'd2
  111. __BT__define FB_STATUS_BAD_VALUE 8'd3
  112. __BT__define FB_STATUS_BUSY 8'd4
  113. __BT__define FB_STATUS_QUEUE_FULL 8'd5
  114. __BT__define FB_STATUS_BAD_AXIS 8'd6
  115. __BT__define FB_STATUS_BAD_MODE 8'd7
  116. __BT__define FB_STATUS_BAD_REGISTER 8'd8
  117. __BT__define FB_STATUS_NOT_READY 8'd9
  118. __BT__define FB_MAX_REQUEST_PAYLOAD 256
  119. __BT__define FB_MAX_RESPONSE_PAYLOAD 1024
  120. __BT__define FB_SNAPSHOT_LENGTH {snapshot_length}
  121. __BT__define FB_HOST_I2C_ADDRESS 7'h2A
  122. __BT__define FB_HOST_I2C_REGISTER_WIDTH 16
  123. """
  124. def params_text_render(sha: str, snapshot_length: int, snapshot_fields: list[dict[str, Any]]) -> str:
  125. """Render the params header entirely from contract inputs.
  126. Snapshot field offsets are computed from the schema exactly like the
  127. JSON layout, so the .vh can never drift from the JSON/GUI decoders
  128. (the historical +2-byte drift from ``manual_mode`` onwards is the
  129. regression this kills: D01).
  130. """
  131. lines = [f"// Generated manual contract SHA-256: {sha}"]
  132. lines.append(PARAMS_HEADER_STATIC
  133. .replace("{snapshot_length}", str(snapshot_length))
  134. .replace("__BT__", BT))
  135. for row in snapshot_fields:
  136. lines.append(f"{BT}define FB_SNAPSHOT_{row['name'].upper()}_OFFSET {row['offset']}")
  137. text = "\n".join(lines) + "\n"
  138. if "{" in text.replace("7'h", ""):
  139. raise RuntimeError("unresolved placeholder in params template")
  140. return text
  141. def generate() -> dict[Path, bytes]:
  142. manual = load_yaml("6400-manual.yaml")
  143. wire = load_yaml("6400-wire.yaml")
  144. snapshot = load_yaml("6400-snapshot.yaml")
  145. fan = load_yaml("fan-control-parameters.yaml")
  146. channel_source = load_yaml("channel-map.yaml")
  147. evidence = load_json("host-i2c-pin-evidence.json")
  148. sha = contract_hash(manual, wire, snapshot, fan, evidence)
  149. if manual['uart']['ack_type']!=wire['responses']['ACK_NACK']['type'] or manual['uart']['snapshot_type']!=wire['responses']['ALL_STATUS_DATA']['type']:
  150. raise ValueError('manual/wire response identifiers disagree')
  151. if manual['uart']['length_width_bits']!=wire['length_width_bits']:
  152. raise ValueError('manual/wire length widths disagree')
  153. fields, length = snapshot_layout(snapshot)
  154. channel_map = dict(channel_source)
  155. channel_map["contract_sha256"] = sha
  156. fan_output = {
  157. "schema": "prod2u-6400-manual-fan-control-v1",
  158. "contract_sha256": sha,
  159. "board_invert_mask": manual["outputs"]["fan_board_invert_mask"],
  160. "connector_duty_semantics": manual["outputs"]["fan_duty_semantics"],
  161. "ptc_hz": manual["outputs"]["ptc_pwm_hz"],
  162. "fan_hz": manual["outputs"]["fan_pwm_hz"],
  163. "safe_ptc_percent": manual["outputs"]["safe_ptc_percent"],
  164. "safe_front_percent": manual["outputs"]["safe_front_percent"],
  165. "safe_rear_percent": manual["outputs"]["safe_rear_percent"],
  166. "bmc_channel_off_c": manual["safety"]["bmc_single_channel_off_c"],
  167. "bmc_lane_hard_c": manual["safety"]["bmc_lane_hard_c"],
  168. "hardware_validation": "NOT_RUN",
  169. }
  170. i2c_regs = {
  171. "schema": "prod2u-6400-host-i2c-register-map-v1",
  172. "contract_sha256": sha,
  173. "address_7bit": 0x2A,
  174. "register_address_width_bits": 16,
  175. "pointer_msb_first": True,
  176. "clock_modes_khz": [100, 400],
  177. "clock_stretching": False,
  178. "sda_drive": "low_or_hiz_only",
  179. "registers": [
  180. {"address": 0x0000, "name": "DEVICE_STATUS", "access": "RO"},
  181. {"address": 0x0001, "name": "RESPONSE_OK", "access": "RO"},
  182. {"address": 0x0002, "name": "RESPONSE_COMMAND", "access": "RO"},
  183. {"address": 0x0003, "name": "RESPONSE_STATUS", "access": "RO"},
  184. {"address": 0x0004, "name": "RESPONSE_DETAIL", "access": "RO"},
  185. {"address": 0x0005, "name": "WATCHDOG_REMAINING_SECONDS", "access": "RO"},
  186. {"address": 0x0006, "name": "SET_ALL_BYTES_WRITTEN", "access": "RO"},
  187. {"address": 0x0007, "name": "SNAPSHOT_LENGTH_L", "access": "RO"},
  188. {"address": 0x0008, "name": "SNAPSHOT_LENGTH_H", "access": "RO"},
  189. {"address": 0x0010, "name": "COMMAND", "access": "WO"},
  190. {"address": 0x0100, "address_end": 0x011F, "name": "SET_ALL_STAGING", "access": "RW"},
  191. {"address": 0x0200, "address_end": 0x02FF, "name": "SNAPSHOT_DATA", "access": "RO"},
  192. ],
  193. }
  194. golden = {
  195. "schema": "prod2u-6400-manual-golden-v2-16bit",
  196. "contract_sha256": sha,
  197. "protocol": "A5 5A | TYPE | LENGTH:u16le | PAYLOAD | CRC:u16le (CRC-16/CCITT-FALSE over TYPE+LEN+PAYLOAD)",
  198. "fixed_vectors": {
  199. "get_all": VECTOR_GET_ALL,
  200. "get_all_ack": VECTOR_GET_ALL_ACK,
  201. "keepalive": VECTOR_KEEPALIVE,
  202. },
  203. "frames": {
  204. "set_all_safe": frame(0x01, bytes(24) + bytes([20]) * 8),
  205. "get_all": VECTOR_GET_ALL,
  206. "keepalive": VECTOR_KEEPALIVE,
  207. "unsupported_03_ack": ack(0x03, 0x01),
  208. "unsupported_04_ack": ack(0x04, 0x01),
  209. "unsupported_08_ack": ack(0x08, 0x01),
  210. "unsupported_09_ack": ack(0x09, 0x01),
  211. "get_all_ack": VECTOR_GET_ALL_ACK,
  212. "set_all_ack": ack(0x01, 0x00),
  213. "keepalive_ack": ack(0x05, 0x00),
  214. "bad_length_ack": ack(0x01, 0x02, 32),
  215. },
  216. }
  217. host = {
  218. "schema": "prod2u-6400-manual-host-contract-v1",
  219. "contract_sha256": sha,
  220. "product": manual["product"],
  221. "board": manual["board"],
  222. "device": manual["device"],
  223. "canonical_profiles": {
  224. "6400-front-rear": {
  225. "allowed_commands": ["SET_ALL", "GET_ALL", "OUTPUT_KEEPALIVE", "MOTOR_QUEUE_WRITE_UNSUPPORTED", "MOTOR_CONTROL_UNSUPPORTED", "EVENT_READ_UNSUPPORTED", "EVENT_CLEAR_UNSUPPORTED"],
  226. "production": True,
  227. "simulation_only": False,
  228. }
  229. },
  230. "wire": {
  231. "uart": manual["uart"],
  232. "host_i2c": manual["host_i2c"],
  233. "commands": wire["commands"],
  234. "responses": wire["responses"],
  235. },
  236. "snapshot": {"payload_length": length, "fields": fields},
  237. "i2c_register_map": i2c_regs,
  238. "outputs": manual["outputs"],
  239. "watchdog": manual["watchdog"],
  240. "safety": manual["safety"],
  241. }
  242. uart = {
  243. "schema": "prod2u-6400-manual-uart-v3-16bit",
  244. "contract_sha256": sha,
  245. "product": manual["product"],
  246. "board": manual["board"],
  247. "wire": {
  248. "uart": manual["uart"],
  249. "host_i2c": manual["host_i2c"],
  250. "commands": wire["commands"],
  251. "responses": wire["responses"],
  252. },
  253. "outputs": manual["outputs"],
  254. "watchdog": manual["watchdog"],
  255. "safety": manual["safety"],
  256. "snapshot": host["snapshot"],
  257. }
  258. params_text = f"{BT}ifndef PROD2U_6400_V1_PARAMS_VH\n{BT}define PROD2U_6400_V1_PARAMS_VH\n" + \
  259. params_text_render(sha, length, fields) + f"{BT}endif\n"
  260. return {
  261. OUT / "host-contract.json": canon(host),
  262. OUT / "manual-uart-contract.json": canon(uart),
  263. OUT / "host-i2c-register-map.json": canon(i2c_regs),
  264. OUT / "golden-vectors.json": canon(golden),
  265. OUT / "channel-map.json": canon(channel_map),
  266. OUT / "fan-control-parameters.json": canon(fan_output),
  267. OUT / "snapshot-layout.json": canon(host["snapshot"]),
  268. OUT / "contract-sha256.txt": (sha + chr(10)).encode(),
  269. OUT / "prod2u_6400_v1_params.vh": params_text.encode(),
  270. }
  271. def main() -> int:
  272. ap = argparse.ArgumentParser()
  273. ap.add_argument("--check", action="store_true")
  274. args = ap.parse_args()
  275. drift = []
  276. for path, data in generate().items():
  277. if args.check:
  278. if not path.is_file() or path.read_bytes() != data:
  279. drift.append(path.relative_to(ROOT).as_posix())
  280. else:
  281. path.parent.mkdir(parents=True, exist_ok=True)
  282. path.write_bytes(data)
  283. if drift:
  284. print("generated drift: " + ", ".join(drift))
  285. return 1
  286. print("PASS: manual 6400 generated")
  287. return 0
  288. if __name__ == "__main__":
  289. raise SystemExit(main())