generate_mrdimm_params.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. #!/usr/bin/env python3
  2. """Generate the MRDIMM constants, GET_DATA layout and golden vectors.
  3. Every emitted byte is rendered from the raw contracts (``contracts/`` plus the
  4. product ``project.json``). Generated outputs are never read back as inputs:
  5. deleting ``generated/`` and regenerating reproduces byte-identical files, and
  6. ``--check`` never writes.
  7. The frame protocol is the single 8-bit-length frame:
  8. A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H
  9. CRC-16/CCITT-FALSE covers TYPE, LENGTH and PAYLOAD; the header is excluded and
  10. the low byte goes first. There is no version, product id, sequence number, Tag,
  11. TLV or historical autodetection.
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import hashlib
  16. import json
  17. import sys
  18. from pathlib import Path
  19. from typing import Any
  20. import yaml
  21. ROOT = Path(__file__).resolve().parents[1]
  22. if str(ROOT) not in sys.path:
  23. sys.path.insert(0, str(ROOT))
  24. from tools.crc16_ccitt_table import crc16_ccitt_false_table # noqa: E402
  25. OUT = ROOT / "generated/mrdimm"
  26. BT = chr(96)
  27. # Frozen macro names (docs/architecture/final-rtl-interfaces.md). The emitted
  28. # header defines exactly this set and nothing else.
  29. MR_FROZEN_MACROS = (
  30. "MR_CLOCK_HZ", "MR_HOST_BAUD", "MR_HOST_CLKS_PER_BIT", "MR_BMC_BAUD",
  31. "MR_BMC_CLKS_PER_BIT", "MR_FRAME_LENGTH_WIDTH", "MR_CMD_SET_ALL",
  32. "MR_CMD_GET_ALL", "MR_RSP_SET_ACK", "MR_RSP_GET_ACK", "MR_RSP_GET_DATA",
  33. "MR_RSP_MOTOR_DONE", "MR_RSP_NACK", "MR_NACK_UNSUPPORTED",
  34. "MR_NACK_BAD_LENGTH", "MR_NACK_BAD_VALUE", "MR_NACK_QUEUE_FULL",
  35. "MR_NACK_BUSY", "MR_SET_ALL_BYTES", "MR_GET_DATA_BYTES",
  36. "MR_MOTOR_DONE_BYTES", "MR_AXIS_COUNT", "MR_SLOTS_PER_AXIS", "MR_SLOT_BYTES",
  37. "MR_AXIS_SLOT_BASE", "MR_FAN_COUNT", "MR_PTC_COUNT", "MR_PTC_PHYSICAL",
  38. "MR_PWM_HZ", "MR_PWM_PHASES", "MR_PWM_PHASE_CLKS", "MR_PWM_PERIOD_CLKS",
  39. "MR_LIMIT_ACTIVE_HIGH", "MR_BOOT_FAN_PERCENT", "MR_BOOT_PTC_PERCENT",
  40. "MR_HOST_INTER_BYTE_TIMEOUT_CLKS",
  41. )
  42. FIELD_SIZES = {"u8": 1, "u16": 2, "u16le": 2, "u24": 3, "u32": 4, "s32": 4}
  43. def normalize(value: Any) -> Any:
  44. if isinstance(value, dict):
  45. return {str(k): normalize(v) for k, v in value.items()}
  46. if isinstance(value, list):
  47. return [normalize(v) for v in value]
  48. return value
  49. def canon(value: Any) -> bytes:
  50. return (json.dumps(normalize(value), sort_keys=True, separators=(",", ":")) + "\n").encode()
  51. def contract_sha256(payload: Any) -> str:
  52. return hashlib.sha256(canon(payload)).hexdigest()
  53. def fields_layout(fields: list[dict[str, Any]]) -> tuple[dict[str, dict[str, Any]], int]:
  54. result: dict[str, dict[str, Any]] = {}
  55. offset = 0
  56. for field in fields:
  57. name = str(field["name"])
  58. if name in result:
  59. raise ValueError("duplicate GET_DATA field " + name)
  60. if field["type"] not in FIELD_SIZES:
  61. raise ValueError(f"unsupported field type {field['type']!r} for {name}")
  62. count = int(field.get("count", 1))
  63. size = FIELD_SIZES[field["type"]] * count
  64. result[name] = {**field, "count": count, "offset": offset, "size": size}
  65. offset += size
  66. return result, offset
  67. def frame(frame_type: int, payload: bytes) -> str:
  68. """New 8-bit-length frame, CRC-16/CCITT-FALSE low byte first."""
  69. body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + payload
  70. return (b"\xA5\x5A" + body + crc16_ccitt_false_table(body).to_bytes(2, "little")).hex().upper()
  71. def nack(request_type: int, reason: int) -> str:
  72. return frame(0xC0, bytes((request_type & 0xFF, reason & 0xFF)))
  73. def set_all_payload(
  74. fan: list[int],
  75. ptc: list[int],
  76. axes: list[tuple[int, int, int]],
  77. *,
  78. buzzer: int | None = None,
  79. ) -> bytes:
  80. if len(fan) != 4 or len(ptc) != 4 or len(axes) != 12:
  81. raise ValueError("SET_ALL sample shape mismatch")
  82. payload = bytes(fan) + bytes(ptc)
  83. for action, steps, half in axes:
  84. payload += bytes((action & 0xFF,)) + int(steps).to_bytes(2, "little") + int(half).to_bytes(2, "little")
  85. if buzzer is not None:
  86. payload += bytes((int(buzzer) & 0x01,))
  87. return payload
  88. def motor_done(axis: int, reason: int, steps: int) -> str:
  89. return frame(0x50, bytes((axis & 0xFF, reason & 0xFF)) + int(steps).to_bytes(2, "little"))
  90. def generate(root: Path | None = None) -> dict[Path, bytes]:
  91. base = root if root is not None else ROOT
  92. out = (base / "generated/mrdimm") if root is not None else OUT
  93. wire = yaml.safe_load((base / "contracts/mrdimm-wire.yaml").read_text(encoding="utf-8"))
  94. status = yaml.safe_load((base / "contracts/mrdimm-status.yaml").read_text(encoding="utf-8"))
  95. project = json.loads((base / "projects/mrdimm-chamber/project.json").read_text(encoding="utf-8"))
  96. ct_format = json.loads((base / "contracts/ct7428-format.json").read_text(encoding="utf-8"))
  97. clock = int(project["board"]["clock_hz"])
  98. outputs = project["outputs"]
  99. motors = project["motors"]
  100. if int(wire["clock_hz"]) != clock:
  101. raise ValueError("wire/project clock disagreement")
  102. if int(wire["length_width_bits"]) != 8:
  103. raise ValueError("MRDIMM frame LENGTH must be one byte")
  104. if wire["frame"]["fields"][1] != {"length": "u8"}:
  105. raise ValueError("frame schema must declare length: u8")
  106. if wire["crc"]["coverage"] != "type_length_payload":
  107. raise ValueError("CRC coverage must be TYPE+LENGTH+PAYLOAD")
  108. set_all = wire["commands"]["SET_ALL"]
  109. get_all = wire["commands"]["GET_ALL"]
  110. responses = wire["responses"]
  111. axis_slots = next(f for f in set_all["payload_fields"] if f["name"] == "axis_slots")
  112. slot = axis_slots["slot_layout"]
  113. if slot["action"]["offset"] != 0 or slot["steps"]["offset"] != 1 or slot["half_period_us"]["offset"] != 3:
  114. raise ValueError("axis slot layout mismatch")
  115. if int(axis_slots["count"]) != int(motors["count"]) or int(motors["logical_axes"]) != int(axis_slots["count"]):
  116. raise ValueError("axis count disagreement")
  117. slot_base = int(axis_slots["offset"])
  118. slot_bytes = int(axis_slots["stride"])
  119. has_buzzer = any(f["name"] == "buzzer_ctrl" for f in set_all["payload_fields"])
  120. set_all_bytes = int(set_all["payload_length"])
  121. expected_set_bytes = slot_base + int(axis_slots["count"]) * slot_bytes + (1 if has_buzzer else 0)
  122. if set_all_bytes != expected_set_bytes:
  123. raise ValueError("SET_ALL length does not match the axis slot table")
  124. fields, length = fields_layout(status["fields"])
  125. if length != int(status["payload_length"]) or length != int(responses["GET_DATA"]["payload_length"]):
  126. raise ValueError("GET_DATA length disagreement")
  127. if fields["lower_limit_mask"]["offset"] != 59 or fields["upper_limit_mask"]["offset"] != 61:
  128. raise ValueError("limit mask offsets must be 59..62")
  129. if fields["bmc_temp_c"]["offset"] != 8 or fields["bmc_temp_c"]["count"] != 24:
  130. raise ValueError("BMC24 block must be offset 8..31")
  131. if fields["ct_temp_c"]["offset"] != 32 or fields["ct_temp_c"]["count"] != 27:
  132. raise ValueError("CT27 block must be offset 32..58")
  133. if has_buzzer:
  134. if fields.get("hood_switch", {}).get("offset") != 63 or fields.get("buzzer_state", {}).get("offset") != 64:
  135. raise ValueError("MRDIMM hood_switch/buzzer_state must append at 63..64")
  136. pwm = wire["pwm"]
  137. if int(pwm["fan_hz"]) != int(outputs["fan_pwm_hz"]) or int(pwm["ptc_hz"]) != int(outputs["ptc_pwm_hz"]):
  138. raise ValueError("PWM frequency disagreement")
  139. period_clks = clock // int(pwm["fan_hz"])
  140. if clock % int(pwm["fan_hz"]) or period_clks != int(outputs["pwm_period_clks"]):
  141. raise ValueError("PWM period disagreement")
  142. if int(pwm["phases"]) * (period_clks // int(pwm["phases"])) != period_clks:
  143. raise ValueError("PWM phases must divide the period")
  144. phase_clks = period_clks // int(pwm["phases"])
  145. host_clks_per_bit = int(wire["host_uart"]["clks_per_bit"])
  146. bmc_clks_per_bit = int(wire["bmc_uart"]["clks_per_bit"])
  147. if (clock + int(wire["host_uart"]["baud"]) // 2) // int(wire["host_uart"]["baud"]) != host_clks_per_bit:
  148. raise ValueError("host clks_per_bit mismatch")
  149. if (clock + int(wire["bmc_uart"]["baud"]) // 2) // int(wire["bmc_uart"]["baud"]) != bmc_clks_per_bit:
  150. raise ValueError("bmc clks_per_bit mismatch")
  151. limit_active_high = 1 if str(motors["limits"]["active_level"]) == "high" else 0
  152. inter_byte_timeout = int(wire["inter_byte_timeout_clks"])
  153. values = {
  154. "CLOCK_HZ": clock,
  155. "HOST_BAUD": int(wire["host_uart"]["baud"]),
  156. "HOST_CLKS_PER_BIT": host_clks_per_bit,
  157. "BMC_BAUD": int(wire["bmc_uart"]["baud"]),
  158. "BMC_CLKS_PER_BIT": bmc_clks_per_bit,
  159. "FRAME_LENGTH_WIDTH": int(wire["length_width_bits"]),
  160. "CMD_SET_ALL": "8'h%02X" % int(set_all["type"]),
  161. "CMD_GET_ALL": "8'h%02X" % int(get_all["type"]),
  162. "RSP_SET_ACK": "8'h%02X" % int(responses["SET_ACK"]["type"]),
  163. "RSP_GET_ACK": "8'h%02X" % int(responses["GET_ACK"]["type"]),
  164. "RSP_GET_DATA": "8'h%02X" % int(responses["GET_DATA"]["type"]),
  165. "RSP_MOTOR_DONE": "8'h%02X" % int(responses["MOTOR_DONE"]["type"]),
  166. "RSP_NACK": "8'h%02X" % int(responses["NACK"]["type"]),
  167. "NACK_UNSUPPORTED": "8'd%d" % int(responses["NACK"]["reason"]["UNSUPPORTED"]),
  168. "NACK_BAD_LENGTH": "8'd%d" % int(responses["NACK"]["reason"]["BAD_LENGTH"]),
  169. "NACK_BAD_VALUE": "8'd%d" % int(responses["NACK"]["reason"]["BAD_VALUE"]),
  170. "NACK_QUEUE_FULL": "8'd%d" % int(responses["NACK"]["reason"]["QUEUE_FULL"]),
  171. "NACK_BUSY": "8'd%d" % int(responses["NACK"]["reason"]["BUSY"]),
  172. "SET_ALL_BYTES": set_all_bytes,
  173. "GET_DATA_BYTES": length,
  174. "MOTOR_DONE_BYTES": int(responses["MOTOR_DONE"]["payload_length"]),
  175. "AXIS_COUNT": int(axis_slots["count"]),
  176. "SLOTS_PER_AXIS": int(motors["queue"]["slots_per_axis"]),
  177. "SLOT_BYTES": slot_bytes,
  178. "AXIS_SLOT_BASE": slot_base,
  179. "FAN_COUNT": int(outputs["fan_count"]),
  180. "PTC_COUNT": int(outputs["chamber_ptc_count"]),
  181. "PTC_PHYSICAL": int(outputs["physical_ptc_count"]),
  182. "PWM_HZ": int(pwm["fan_hz"]),
  183. "PWM_PHASES": int(pwm["phases"]),
  184. "PWM_PHASE_CLKS": phase_clks,
  185. "PWM_PERIOD_CLKS": period_clks,
  186. "LIMIT_ACTIVE_HIGH": limit_active_high,
  187. "BOOT_FAN_PERCENT": int(outputs["boot"]["fan_percent"]),
  188. "BOOT_PTC_PERCENT": int(outputs["boot"]["ptc_percent"]),
  189. "HOST_INTER_BYTE_TIMEOUT_CLKS": inter_byte_timeout,
  190. }
  191. if set(values) != set(name[3:] for name in MR_FROZEN_MACROS):
  192. raise ValueError("frozen macro set mismatch: " + ", ".join(sorted(set(values) ^ {n[3:] for n in MR_FROZEN_MACROS})))
  193. if values["SLOTS_PER_AXIS"] != 1 or values["SLOT_BYTES"] != 5 or values["AXIS_SLOT_BASE"] != 8:
  194. raise ValueError("actuator geometry must be one latest-wins slot per axis; wire slots are 5 bytes at base 8")
  195. if values["MOTOR_DONE_BYTES"] != 4:
  196. raise ValueError("MOTOR_DONE must be 4 bytes")
  197. if values["PWM_PHASES"] * values["PWM_PHASE_CLKS"] != values["PWM_PERIOD_CLKS"]:
  198. raise ValueError("PWM phase budget mismatch")
  199. sha = contract_sha256({"wire": wire, "status": status, "project": project, "ct_format": ct_format})
  200. header = [BT + "ifndef PROD2U_MRDIMM_PARAMS_VH", BT + "define PROD2U_MRDIMM_PARAMS_VH",
  201. "// Generated from raw wire/status/project contracts; SHA256 " + sha]
  202. header += [BT + "define " + name + " " + str(values[name[3:]]) for name in MR_FROZEN_MACROS]
  203. header += [BT + "endif", ""]
  204. layout = {
  205. "schema": status["schema"],
  206. "product": project["project_id"],
  207. "contract_sha256": sha,
  208. "payload_type": int(status["payload_type"]),
  209. "byte_order": status["byte_order"],
  210. "length": length,
  211. "fields": fields,
  212. "limit_masks": status["limit_masks"],
  213. "temperature_encoding": status["temperature_encoding"],
  214. "output_defaults": status["output_defaults"],
  215. "fan_ptc_mapping": status["fan_ptc_mapping"],
  216. "motor_axes": {
  217. **status["motor_axes"],
  218. "slots_per_axis": values["SLOTS_PER_AXIS"],
  219. "slot_bytes": values["SLOT_BYTES"],
  220. "axis_slot_base": values["AXIS_SLOT_BASE"],
  221. "slot_layout": slot,
  222. "actions": normalize(set_all["actions"]),
  223. "implemented_min_half_period_us": int(set_all["implemented_min_half_period_us"]),
  224. "speed_hz": set_all["speed_hz"],
  225. },
  226. "control": {"wire": normalize(wire), "outputs": outputs, "board": project["board"]},
  227. }
  228. nothing = int(list(set_all["actions"].keys())[list(set_all["actions"].values()).index("NOTHING")])
  229. push_down = int([k for k, v in set_all["actions"].items() if v == "PUSH_DOWN"][0])
  230. push_up = int([k for k, v in set_all["actions"].items() if v == "PUSH_UP"][0])
  231. stop_clear = int([k for k, v in set_all["actions"].items() if v == "STOP_CLEAR"][0])
  232. reasons = responses["MOTOR_DONE"]["reasons"]
  233. reason_steps = int([k for k, v in reasons.items() if v == "steps_complete"][0])
  234. reason_lower = int([k for k, v in reasons.items() if v == "lower_limit"][0])
  235. reason_upper = int([k for k, v in reasons.items() if v == "upper_limit"][0])
  236. reason_both = int([k for k, v in reasons.items() if v == "both_limits"][0])
  237. boot_fan = int(values["BOOT_FAN_PERCENT"])
  238. boot_ptc = int(values["BOOT_PTC_PERCENT"])
  239. idle_axes = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  240. stop_axes = [(stop_clear, 0, 0)] * values["AXIS_COUNT"]
  241. push_axis = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  242. push_axis[0] = (push_down, 100, 1000)
  243. push_axis[11] = (push_up, 65535, 1)
  244. stop_one = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  245. stop_one[4] = (stop_clear, 0, 0)
  246. data_sample = (bytes([boot_fan] * 4) + bytes([boot_ptc] * 4)
  247. + bytes(25 + index for index in range(24))
  248. + bytes(60 + index for index in range(27))
  249. + (0x0002).to_bytes(2, "little") + (0x0800).to_bytes(2, "little")
  250. + (bytes((0, 0)) if has_buzzer else b""))
  251. data_invalid = (bytes([boot_fan] * 4) + bytes([boot_ptc] * 4) + bytes([0xFF] * 51) + bytes(4)
  252. + (bytes((0, 0)) if has_buzzer else b""))
  253. buzzer_arg = 0 if has_buzzer else None
  254. golden = {
  255. "schema": "prod2u-mrdimm-golden-v1-8bit",
  256. "contract_sha256": sha,
  257. "protocol": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H (CRC-16/CCITT-FALSE over TYPE+LENGTH+PAYLOAD)",
  258. "fixed_vectors": {
  259. "get_all_request": frame(0x02, b""),
  260. "set_ack": frame(0x81, b""),
  261. "get_ack": frame(0x82, b""),
  262. "nack_set_queue_full": nack(0x01, 0x04),
  263. "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
  264. "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
  265. },
  266. "frames": {
  267. "get_all_request": frame(0x02, b""),
  268. "get_ack": frame(0x82, b""),
  269. "set_ack": frame(0x81, b""),
  270. "set_all_idle": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, idle_axes, buzzer=buzzer_arg)),
  271. "set_all_push_down_axis0_100hz": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, push_axis, buzzer=buzzer_arg)),
  272. "set_all_stop_clear_all_axes": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_axes, buzzer=buzzer_arg)),
  273. "set_all_stop_clear_axis4_only": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_one, buzzer=buzzer_arg)),
  274. "nack_unsupported": nack(0x01, 0x01),
  275. "nack_bad_length": nack(0x01, 0x02),
  276. "nack_bad_value": nack(0x01, 0x03),
  277. "nack_set_queue_full": nack(0x01, 0x04),
  278. "nack_busy": nack(0x01, 0x05),
  279. "nack_unsupported_request_7f": nack(0x7F, 0x01),
  280. "motor_done_axis0_steps_complete": motor_done(0, reason_steps, 1),
  281. "motor_done_axis3_lower_limit": motor_done(3, reason_lower, 250),
  282. "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
  283. "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
  284. "motor_done_axis11_steps_complete_65535": motor_done(11, reason_steps, 65535),
  285. "get_data_sample": frame(0x42, data_sample),
  286. "get_data_invalid_temperature": frame(0x42, data_invalid),
  287. },
  288. "action_codes": normalize(set_all["actions"]),
  289. "motor_done_reasons": normalize(reasons),
  290. }
  291. if len(data_sample) != length or len(data_invalid) != length:
  292. raise ValueError("GET_DATA sample length mismatch")
  293. doc = ["# MRDIMM GET_DATA (type 0x42)", "",
  294. f"Length: {length} bytes. Little endian. Low 12 bits of a limit mask are Axis0..Axis11; the high 4 bits are zero.", "",
  295. "| Field | Offset | Bytes |", "|---|---:|---:|"]
  296. doc += [f"| {name} | {field['offset']} | {field['size']} |" for name, field in fields.items()]
  297. doc += ["", "## SET_ALL axis slot (offset 8 + 5*i)", "",
  298. "| Field | Offset | Bytes |", "|---|---:|---:|"]
  299. doc += [f"| {name} | {entry['offset']} | {FIELD_SIZES[entry['type']]} |" for name, entry in slot.items()]
  300. doc += ["", "Actions: " + ", ".join(f"{code:02X}={name}" for code, name in sorted(set_all["actions"].items())), ""]
  301. return {
  302. out / "prod2u_mrdimm_params.vh": ("\n".join(header)).encode(),
  303. out / "snapshot-layout.json": canon(layout),
  304. out / "golden-vectors.json": canon(golden),
  305. out / "status-layout.md": ("\n".join(doc) + "\n").encode(),
  306. out / "contract-sha256.txt": (sha + "\n").encode(),
  307. }
  308. def main() -> int:
  309. parser = argparse.ArgumentParser()
  310. parser.add_argument("--check", action="store_true")
  311. args = parser.parse_args()
  312. drift = []
  313. for path, content in generate().items():
  314. if args.check:
  315. if not path.is_file() or path.read_bytes() != content:
  316. drift.append(path.relative_to(ROOT).as_posix())
  317. else:
  318. path.parent.mkdir(parents=True, exist_ok=True)
  319. path.write_bytes(content)
  320. if drift:
  321. print("generated drift: " + ", ".join(drift))
  322. return 1
  323. print("PASS: mrdimm params, GET_DATA layout and golden vectors generated")
  324. return 0
  325. if __name__ == "__main__":
  326. raise SystemExit(main())