generate_mrdimm_params.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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(fan: list[int], ptc: list[int], axes: list[tuple[int, int, int]]) -> bytes:
  74. if len(fan) != 4 or len(ptc) != 4 or len(axes) != 12:
  75. raise ValueError("SET_ALL sample shape mismatch")
  76. payload = bytes(fan) + bytes(ptc)
  77. for action, steps, half in axes:
  78. payload += bytes((action & 0xFF,)) + int(steps).to_bytes(2, "little") + int(half).to_bytes(2, "little")
  79. return payload
  80. def motor_done(axis: int, reason: int, steps: int) -> str:
  81. return frame(0x50, bytes((axis & 0xFF, reason & 0xFF)) + int(steps).to_bytes(2, "little"))
  82. def generate(root: Path | None = None) -> dict[Path, bytes]:
  83. base = root if root is not None else ROOT
  84. out = (base / "generated/mrdimm") if root is not None else OUT
  85. wire = yaml.safe_load((base / "contracts/mrdimm-wire.yaml").read_text(encoding="utf-8"))
  86. status = yaml.safe_load((base / "contracts/mrdimm-status.yaml").read_text(encoding="utf-8"))
  87. project = json.loads((base / "projects/mrdimm-chamber/project.json").read_text(encoding="utf-8"))
  88. ct_format = json.loads((base / "contracts/ct7428-format.json").read_text(encoding="utf-8"))
  89. clock = int(project["board"]["clock_hz"])
  90. outputs = project["outputs"]
  91. motors = project["motors"]
  92. if int(wire["clock_hz"]) != clock:
  93. raise ValueError("wire/project clock disagreement")
  94. if int(wire["length_width_bits"]) != 8:
  95. raise ValueError("MRDIMM frame LENGTH must be one byte")
  96. if wire["frame"]["fields"][1] != {"length": "u8"}:
  97. raise ValueError("frame schema must declare length: u8")
  98. if wire["crc"]["coverage"] != "type_length_payload":
  99. raise ValueError("CRC coverage must be TYPE+LENGTH+PAYLOAD")
  100. set_all = wire["commands"]["SET_ALL"]
  101. get_all = wire["commands"]["GET_ALL"]
  102. responses = wire["responses"]
  103. axis_slots = next(f for f in set_all["payload_fields"] if f["name"] == "axis_slots")
  104. slot = axis_slots["slot_layout"]
  105. if slot["action"]["offset"] != 0 or slot["steps"]["offset"] != 1 or slot["half_period_us"]["offset"] != 3:
  106. raise ValueError("axis slot layout mismatch")
  107. if int(axis_slots["count"]) != int(motors["count"]) or int(motors["logical_axes"]) != int(axis_slots["count"]):
  108. raise ValueError("axis count disagreement")
  109. slot_base = int(axis_slots["offset"])
  110. slot_bytes = int(axis_slots["stride"])
  111. set_all_bytes = int(set_all["payload_length"])
  112. if set_all_bytes != slot_base + int(axis_slots["count"]) * slot_bytes:
  113. raise ValueError("SET_ALL length does not match the axis slot table")
  114. fields, length = fields_layout(status["fields"])
  115. if length != int(status["payload_length"]) or length != int(responses["GET_DATA"]["payload_length"]):
  116. raise ValueError("GET_DATA length disagreement")
  117. if fields["lower_limit_mask"]["offset"] != 59 or fields["upper_limit_mask"]["offset"] != 61:
  118. raise ValueError("limit mask offsets must be 59..62")
  119. if fields["bmc_temp_c"]["offset"] != 8 or fields["bmc_temp_c"]["count"] != 24:
  120. raise ValueError("BMC24 block must be offset 8..31")
  121. if fields["ct_temp_c"]["offset"] != 32 or fields["ct_temp_c"]["count"] != 27:
  122. raise ValueError("CT27 block must be offset 32..58")
  123. pwm = wire["pwm"]
  124. if int(pwm["fan_hz"]) != int(outputs["fan_pwm_hz"]) or int(pwm["ptc_hz"]) != int(outputs["ptc_pwm_hz"]):
  125. raise ValueError("PWM frequency disagreement")
  126. period_clks = clock // int(pwm["fan_hz"])
  127. if clock % int(pwm["fan_hz"]) or period_clks != int(outputs["pwm_period_clks"]):
  128. raise ValueError("PWM period disagreement")
  129. if int(pwm["phases"]) * (period_clks // int(pwm["phases"])) != period_clks:
  130. raise ValueError("PWM phases must divide the period")
  131. phase_clks = period_clks // int(pwm["phases"])
  132. host_clks_per_bit = int(wire["host_uart"]["clks_per_bit"])
  133. bmc_clks_per_bit = int(wire["bmc_uart"]["clks_per_bit"])
  134. if (clock + int(wire["host_uart"]["baud"]) // 2) // int(wire["host_uart"]["baud"]) != host_clks_per_bit:
  135. raise ValueError("host clks_per_bit mismatch")
  136. if (clock + int(wire["bmc_uart"]["baud"]) // 2) // int(wire["bmc_uart"]["baud"]) != bmc_clks_per_bit:
  137. raise ValueError("bmc clks_per_bit mismatch")
  138. limit_active_high = 1 if str(motors["limits"]["active_level"]) == "high" else 0
  139. inter_byte_timeout = int(wire["inter_byte_timeout_clks"])
  140. values = {
  141. "CLOCK_HZ": clock,
  142. "HOST_BAUD": int(wire["host_uart"]["baud"]),
  143. "HOST_CLKS_PER_BIT": host_clks_per_bit,
  144. "BMC_BAUD": int(wire["bmc_uart"]["baud"]),
  145. "BMC_CLKS_PER_BIT": bmc_clks_per_bit,
  146. "FRAME_LENGTH_WIDTH": int(wire["length_width_bits"]),
  147. "CMD_SET_ALL": "8'h%02X" % int(set_all["type"]),
  148. "CMD_GET_ALL": "8'h%02X" % int(get_all["type"]),
  149. "RSP_SET_ACK": "8'h%02X" % int(responses["SET_ACK"]["type"]),
  150. "RSP_GET_ACK": "8'h%02X" % int(responses["GET_ACK"]["type"]),
  151. "RSP_GET_DATA": "8'h%02X" % int(responses["GET_DATA"]["type"]),
  152. "RSP_MOTOR_DONE": "8'h%02X" % int(responses["MOTOR_DONE"]["type"]),
  153. "RSP_NACK": "8'h%02X" % int(responses["NACK"]["type"]),
  154. "NACK_UNSUPPORTED": "8'd%d" % int(responses["NACK"]["reason"]["UNSUPPORTED"]),
  155. "NACK_BAD_LENGTH": "8'd%d" % int(responses["NACK"]["reason"]["BAD_LENGTH"]),
  156. "NACK_BAD_VALUE": "8'd%d" % int(responses["NACK"]["reason"]["BAD_VALUE"]),
  157. "NACK_QUEUE_FULL": "8'd%d" % int(responses["NACK"]["reason"]["QUEUE_FULL"]),
  158. "NACK_BUSY": "8'd%d" % int(responses["NACK"]["reason"]["BUSY"]),
  159. "SET_ALL_BYTES": set_all_bytes,
  160. "GET_DATA_BYTES": length,
  161. "MOTOR_DONE_BYTES": int(responses["MOTOR_DONE"]["payload_length"]),
  162. "AXIS_COUNT": int(axis_slots["count"]),
  163. "SLOTS_PER_AXIS": int(motors["queue"]["slots_per_axis"]),
  164. "SLOT_BYTES": slot_bytes,
  165. "AXIS_SLOT_BASE": slot_base,
  166. "FAN_COUNT": int(outputs["fan_count"]),
  167. "PTC_COUNT": int(outputs["chamber_ptc_count"]),
  168. "PTC_PHYSICAL": int(outputs["physical_ptc_count"]),
  169. "PWM_HZ": int(pwm["fan_hz"]),
  170. "PWM_PHASES": int(pwm["phases"]),
  171. "PWM_PHASE_CLKS": phase_clks,
  172. "PWM_PERIOD_CLKS": period_clks,
  173. "LIMIT_ACTIVE_HIGH": limit_active_high,
  174. "BOOT_FAN_PERCENT": int(outputs["boot"]["fan_percent"]),
  175. "BOOT_PTC_PERCENT": int(outputs["boot"]["ptc_percent"]),
  176. "HOST_INTER_BYTE_TIMEOUT_CLKS": inter_byte_timeout,
  177. }
  178. if set(values) != set(name[3:] for name in MR_FROZEN_MACROS):
  179. raise ValueError("frozen macro set mismatch: " + ", ".join(sorted(set(values) ^ {n[3:] for n in MR_FROZEN_MACROS})))
  180. if values["SLOTS_PER_AXIS"] != 32 or values["SLOT_BYTES"] != 5 or values["AXIS_SLOT_BASE"] != 8:
  181. raise ValueError("queue geometry must be 32 slots x 5 bytes at base 8")
  182. if values["MOTOR_DONE_BYTES"] != 4:
  183. raise ValueError("MOTOR_DONE must be 4 bytes")
  184. if values["PWM_PHASES"] * values["PWM_PHASE_CLKS"] != values["PWM_PERIOD_CLKS"]:
  185. raise ValueError("PWM phase budget mismatch")
  186. sha = contract_sha256({"wire": wire, "status": status, "project": project, "ct_format": ct_format})
  187. header = [BT + "ifndef PROD2U_MRDIMM_PARAMS_VH", BT + "define PROD2U_MRDIMM_PARAMS_VH",
  188. "// Generated from raw wire/status/project contracts; SHA256 " + sha]
  189. header += [BT + "define " + name + " " + str(values[name[3:]]) for name in MR_FROZEN_MACROS]
  190. header += [BT + "endif", ""]
  191. layout = {
  192. "schema": status["schema"],
  193. "product": project["project_id"],
  194. "contract_sha256": sha,
  195. "payload_type": int(status["payload_type"]),
  196. "byte_order": status["byte_order"],
  197. "length": length,
  198. "fields": fields,
  199. "limit_masks": status["limit_masks"],
  200. "temperature_encoding": status["temperature_encoding"],
  201. "output_defaults": status["output_defaults"],
  202. "fan_ptc_mapping": status["fan_ptc_mapping"],
  203. "motor_axes": {
  204. **status["motor_axes"],
  205. "slots_per_axis": values["SLOTS_PER_AXIS"],
  206. "slot_bytes": values["SLOT_BYTES"],
  207. "axis_slot_base": values["AXIS_SLOT_BASE"],
  208. "slot_layout": slot,
  209. "actions": normalize(set_all["actions"]),
  210. "implemented_min_half_period_us": int(set_all["implemented_min_half_period_us"]),
  211. "speed_hz": set_all["speed_hz"],
  212. },
  213. "control": {"wire": normalize(wire), "outputs": outputs, "board": project["board"]},
  214. }
  215. nothing = int(list(set_all["actions"].keys())[list(set_all["actions"].values()).index("NOTHING")])
  216. push_down = int([k for k, v in set_all["actions"].items() if v == "PUSH_DOWN"][0])
  217. push_up = int([k for k, v in set_all["actions"].items() if v == "PUSH_UP"][0])
  218. stop_clear = int([k for k, v in set_all["actions"].items() if v == "STOP_CLEAR"][0])
  219. reasons = responses["MOTOR_DONE"]["reasons"]
  220. reason_steps = int([k for k, v in reasons.items() if v == "steps_complete"][0])
  221. reason_lower = int([k for k, v in reasons.items() if v == "lower_limit"][0])
  222. reason_upper = int([k for k, v in reasons.items() if v == "upper_limit"][0])
  223. reason_both = int([k for k, v in reasons.items() if v == "both_limits"][0])
  224. boot_fan = int(values["BOOT_FAN_PERCENT"])
  225. boot_ptc = int(values["BOOT_PTC_PERCENT"])
  226. idle_axes = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  227. stop_axes = [(stop_clear, 0, 0)] * values["AXIS_COUNT"]
  228. push_axis = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  229. push_axis[0] = (push_down, 100, 1000)
  230. push_axis[11] = (push_up, 65535, 1)
  231. stop_one = [(nothing, 0, 0)] * values["AXIS_COUNT"]
  232. stop_one[4] = (stop_clear, 0, 0)
  233. data_sample = (bytes([boot_fan] * 4) + bytes([boot_ptc] * 4)
  234. + bytes(25 + index for index in range(24))
  235. + bytes(60 + index for index in range(27))
  236. + (0x0002).to_bytes(2, "little") + (0x0800).to_bytes(2, "little"))
  237. data_invalid = bytes([boot_fan] * 4) + bytes([boot_ptc] * 4) + bytes([0xFF] * 51) + bytes(4)
  238. golden = {
  239. "schema": "prod2u-mrdimm-golden-v1-8bit",
  240. "contract_sha256": sha,
  241. "protocol": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H (CRC-16/CCITT-FALSE over TYPE+LENGTH+PAYLOAD)",
  242. "fixed_vectors": {
  243. "get_all_request": frame(0x02, b""),
  244. "set_ack": frame(0x81, b""),
  245. "get_ack": frame(0x82, b""),
  246. "nack_set_queue_full": nack(0x01, 0x04),
  247. "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
  248. "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
  249. },
  250. "frames": {
  251. "get_all_request": frame(0x02, b""),
  252. "get_ack": frame(0x82, b""),
  253. "set_ack": frame(0x81, b""),
  254. "set_all_idle": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, idle_axes)),
  255. "set_all_push_down_axis0_100hz": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, push_axis)),
  256. "set_all_stop_clear_all_axes": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_axes)),
  257. "set_all_stop_clear_axis4_only": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_one)),
  258. "nack_unsupported": nack(0x01, 0x01),
  259. "nack_bad_length": nack(0x01, 0x02),
  260. "nack_bad_value": nack(0x01, 0x03),
  261. "nack_set_queue_full": nack(0x01, 0x04),
  262. "nack_busy": nack(0x01, 0x05),
  263. "nack_unsupported_request_7f": nack(0x7F, 0x01),
  264. "motor_done_axis0_steps_complete": motor_done(0, reason_steps, 1),
  265. "motor_done_axis3_lower_limit": motor_done(3, reason_lower, 250),
  266. "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
  267. "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
  268. "motor_done_axis11_steps_complete_65535": motor_done(11, reason_steps, 65535),
  269. "get_data_sample": frame(0x42, data_sample),
  270. "get_data_invalid_temperature": frame(0x42, data_invalid),
  271. },
  272. "action_codes": normalize(set_all["actions"]),
  273. "motor_done_reasons": normalize(reasons),
  274. }
  275. if len(data_sample) != length or len(data_invalid) != length:
  276. raise ValueError("GET_DATA sample length mismatch")
  277. doc = ["# MRDIMM GET_DATA (type 0x42)", "",
  278. f"Length: {length} bytes. Little endian. Low 12 bits of a limit mask are Axis0..Axis11; the high 4 bits are zero.", "",
  279. "| Field | Offset | Bytes |", "|---|---:|---:|"]
  280. doc += [f"| {name} | {field['offset']} | {field['size']} |" for name, field in fields.items()]
  281. doc += ["", "## SET_ALL axis slot (offset 8 + 5*i)", "",
  282. "| Field | Offset | Bytes |", "|---|---:|---:|"]
  283. doc += [f"| {name} | {entry['offset']} | {FIELD_SIZES[entry['type']]} |" for name, entry in slot.items()]
  284. doc += ["", "Actions: " + ", ".join(f"{code:02X}={name}" for code, name in sorted(set_all["actions"].items())), ""]
  285. return {
  286. out / "prod2u_mrdimm_params.vh": ("\n".join(header)).encode(),
  287. out / "snapshot-layout.json": canon(layout),
  288. out / "golden-vectors.json": canon(golden),
  289. out / "status-layout.md": ("\n".join(doc) + "\n").encode(),
  290. out / "contract-sha256.txt": (sha + "\n").encode(),
  291. }
  292. def main() -> int:
  293. parser = argparse.ArgumentParser()
  294. parser.add_argument("--check", action="store_true")
  295. args = parser.parse_args()
  296. drift = []
  297. for path, content in generate().items():
  298. if args.check:
  299. if not path.is_file() or path.read_bytes() != content:
  300. drift.append(path.relative_to(ROOT).as_posix())
  301. else:
  302. path.parent.mkdir(parents=True, exist_ok=True)
  303. path.write_bytes(content)
  304. if drift:
  305. print("generated drift: " + ", ".join(drift))
  306. return 1
  307. print("PASS: mrdimm params, GET_DATA layout and golden vectors generated")
  308. return 0
  309. if __name__ == "__main__":
  310. raise SystemExit(main())