| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374 |
- #!/usr/bin/env python3
- """Generate the MRDIMM constants, GET_DATA layout and golden vectors.
- Every emitted byte is rendered from the raw contracts (``contracts/`` plus the
- product ``project.json``). Generated outputs are never read back as inputs:
- deleting ``generated/`` and regenerating reproduces byte-identical files, and
- ``--check`` never writes.
- The frame protocol is the single 8-bit-length frame:
- A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H
- CRC-16/CCITT-FALSE covers TYPE, LENGTH and PAYLOAD; the header is excluded and
- the low byte goes first. There is no version, product id, sequence number, Tag,
- TLV or historical autodetection.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import sys
- from pathlib import Path
- from typing import Any
- import yaml
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tools.crc16_ccitt_table import crc16_ccitt_false_table # noqa: E402
- OUT = ROOT / "generated/mrdimm"
- BT = chr(96)
- # Frozen macro names (docs/architecture/final-rtl-interfaces.md). The emitted
- # header defines exactly this set and nothing else.
- MR_FROZEN_MACROS = (
- "MR_CLOCK_HZ", "MR_HOST_BAUD", "MR_HOST_CLKS_PER_BIT", "MR_BMC_BAUD",
- "MR_BMC_CLKS_PER_BIT", "MR_FRAME_LENGTH_WIDTH", "MR_CMD_SET_ALL",
- "MR_CMD_GET_ALL", "MR_RSP_SET_ACK", "MR_RSP_GET_ACK", "MR_RSP_GET_DATA",
- "MR_RSP_MOTOR_DONE", "MR_RSP_NACK", "MR_NACK_UNSUPPORTED",
- "MR_NACK_BAD_LENGTH", "MR_NACK_BAD_VALUE", "MR_NACK_QUEUE_FULL",
- "MR_NACK_BUSY", "MR_SET_ALL_BYTES", "MR_GET_DATA_BYTES",
- "MR_MOTOR_DONE_BYTES", "MR_AXIS_COUNT", "MR_SLOTS_PER_AXIS", "MR_SLOT_BYTES",
- "MR_AXIS_SLOT_BASE", "MR_FAN_COUNT", "MR_PTC_COUNT", "MR_PTC_PHYSICAL",
- "MR_PWM_HZ", "MR_PWM_PHASES", "MR_PWM_PHASE_CLKS", "MR_PWM_PERIOD_CLKS",
- "MR_LIMIT_ACTIVE_HIGH", "MR_BOOT_FAN_PERCENT", "MR_BOOT_PTC_PERCENT",
- "MR_HOST_INTER_BYTE_TIMEOUT_CLKS",
- )
- FIELD_SIZES = {"u8": 1, "u16": 2, "u16le": 2, "u24": 3, "u32": 4, "s32": 4}
- def normalize(value: Any) -> Any:
- if isinstance(value, dict):
- return {str(k): normalize(v) for k, v in value.items()}
- if isinstance(value, list):
- return [normalize(v) for v in value]
- return value
- def canon(value: Any) -> bytes:
- return (json.dumps(normalize(value), sort_keys=True, separators=(",", ":")) + "\n").encode()
- def contract_sha256(payload: Any) -> str:
- return hashlib.sha256(canon(payload)).hexdigest()
- def fields_layout(fields: list[dict[str, Any]]) -> tuple[dict[str, dict[str, Any]], int]:
- result: dict[str, dict[str, Any]] = {}
- offset = 0
- for field in fields:
- name = str(field["name"])
- if name in result:
- raise ValueError("duplicate GET_DATA field " + name)
- if field["type"] not in FIELD_SIZES:
- raise ValueError(f"unsupported field type {field['type']!r} for {name}")
- count = int(field.get("count", 1))
- size = FIELD_SIZES[field["type"]] * count
- result[name] = {**field, "count": count, "offset": offset, "size": size}
- offset += size
- return result, offset
- def frame(frame_type: int, payload: bytes) -> str:
- """New 8-bit-length frame, CRC-16/CCITT-FALSE low byte first."""
- body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + payload
- return (b"\xA5\x5A" + body + crc16_ccitt_false_table(body).to_bytes(2, "little")).hex().upper()
- def nack(request_type: int, reason: int) -> str:
- return frame(0xC0, bytes((request_type & 0xFF, reason & 0xFF)))
- def set_all_payload(
- fan: list[int],
- ptc: list[int],
- axes: list[tuple[int, int, int]],
- *,
- buzzer: int | None = None,
- ) -> bytes:
- if len(fan) != 4 or len(ptc) != 4 or len(axes) != 12:
- raise ValueError("SET_ALL sample shape mismatch")
- payload = bytes(fan) + bytes(ptc)
- for action, steps, half in axes:
- payload += bytes((action & 0xFF,)) + int(steps).to_bytes(2, "little") + int(half).to_bytes(2, "little")
- if buzzer is not None:
- payload += bytes((int(buzzer) & 0x01,))
- return payload
- def motor_done(axis: int, reason: int, steps: int) -> str:
- return frame(0x50, bytes((axis & 0xFF, reason & 0xFF)) + int(steps).to_bytes(2, "little"))
- def generate(root: Path | None = None) -> dict[Path, bytes]:
- base = root if root is not None else ROOT
- out = (base / "generated/mrdimm") if root is not None else OUT
- wire = yaml.safe_load((base / "contracts/mrdimm-wire.yaml").read_text(encoding="utf-8"))
- status = yaml.safe_load((base / "contracts/mrdimm-status.yaml").read_text(encoding="utf-8"))
- project = json.loads((base / "projects/mrdimm-chamber/project.json").read_text(encoding="utf-8"))
- ct_format = json.loads((base / "contracts/ct7428-format.json").read_text(encoding="utf-8"))
- clock = int(project["board"]["clock_hz"])
- outputs = project["outputs"]
- motors = project["motors"]
- if int(wire["clock_hz"]) != clock:
- raise ValueError("wire/project clock disagreement")
- if int(wire["length_width_bits"]) != 8:
- raise ValueError("MRDIMM frame LENGTH must be one byte")
- if wire["frame"]["fields"][1] != {"length": "u8"}:
- raise ValueError("frame schema must declare length: u8")
- if wire["crc"]["coverage"] != "type_length_payload":
- raise ValueError("CRC coverage must be TYPE+LENGTH+PAYLOAD")
- set_all = wire["commands"]["SET_ALL"]
- get_all = wire["commands"]["GET_ALL"]
- responses = wire["responses"]
- axis_slots = next(f for f in set_all["payload_fields"] if f["name"] == "axis_slots")
- slot = axis_slots["slot_layout"]
- if slot["action"]["offset"] != 0 or slot["steps"]["offset"] != 1 or slot["half_period_us"]["offset"] != 3:
- raise ValueError("axis slot layout mismatch")
- if int(axis_slots["count"]) != int(motors["count"]) or int(motors["logical_axes"]) != int(axis_slots["count"]):
- raise ValueError("axis count disagreement")
- slot_base = int(axis_slots["offset"])
- slot_bytes = int(axis_slots["stride"])
- has_buzzer = any(f["name"] == "buzzer_ctrl" for f in set_all["payload_fields"])
- set_all_bytes = int(set_all["payload_length"])
- expected_set_bytes = slot_base + int(axis_slots["count"]) * slot_bytes + (1 if has_buzzer else 0)
- if set_all_bytes != expected_set_bytes:
- raise ValueError("SET_ALL length does not match the axis slot table")
- fields, length = fields_layout(status["fields"])
- if length != int(status["payload_length"]) or length != int(responses["GET_DATA"]["payload_length"]):
- raise ValueError("GET_DATA length disagreement")
- if fields["lower_limit_mask"]["offset"] != 59 or fields["upper_limit_mask"]["offset"] != 61:
- raise ValueError("limit mask offsets must be 59..62")
- if fields["bmc_temp_c"]["offset"] != 8 or fields["bmc_temp_c"]["count"] != 24:
- raise ValueError("BMC24 block must be offset 8..31")
- if fields["ct_temp_c"]["offset"] != 32 or fields["ct_temp_c"]["count"] != 27:
- raise ValueError("CT27 block must be offset 32..58")
- if has_buzzer:
- if fields.get("hood_switch", {}).get("offset") != 63 or fields.get("buzzer_state", {}).get("offset") != 64:
- raise ValueError("MRDIMM hood_switch/buzzer_state must append at 63..64")
- pwm = wire["pwm"]
- if int(pwm["fan_hz"]) != int(outputs["fan_pwm_hz"]) or int(pwm["ptc_hz"]) != int(outputs["ptc_pwm_hz"]):
- raise ValueError("PWM frequency disagreement")
- period_clks = clock // int(pwm["fan_hz"])
- if clock % int(pwm["fan_hz"]) or period_clks != int(outputs["pwm_period_clks"]):
- raise ValueError("PWM period disagreement")
- if int(pwm["phases"]) * (period_clks // int(pwm["phases"])) != period_clks:
- raise ValueError("PWM phases must divide the period")
- phase_clks = period_clks // int(pwm["phases"])
- host_clks_per_bit = int(wire["host_uart"]["clks_per_bit"])
- bmc_clks_per_bit = int(wire["bmc_uart"]["clks_per_bit"])
- if (clock + int(wire["host_uart"]["baud"]) // 2) // int(wire["host_uart"]["baud"]) != host_clks_per_bit:
- raise ValueError("host clks_per_bit mismatch")
- if (clock + int(wire["bmc_uart"]["baud"]) // 2) // int(wire["bmc_uart"]["baud"]) != bmc_clks_per_bit:
- raise ValueError("bmc clks_per_bit mismatch")
- limit_active_high = 1 if str(motors["limits"]["active_level"]) == "high" else 0
- inter_byte_timeout = int(wire["inter_byte_timeout_clks"])
- values = {
- "CLOCK_HZ": clock,
- "HOST_BAUD": int(wire["host_uart"]["baud"]),
- "HOST_CLKS_PER_BIT": host_clks_per_bit,
- "BMC_BAUD": int(wire["bmc_uart"]["baud"]),
- "BMC_CLKS_PER_BIT": bmc_clks_per_bit,
- "FRAME_LENGTH_WIDTH": int(wire["length_width_bits"]),
- "CMD_SET_ALL": "8'h%02X" % int(set_all["type"]),
- "CMD_GET_ALL": "8'h%02X" % int(get_all["type"]),
- "RSP_SET_ACK": "8'h%02X" % int(responses["SET_ACK"]["type"]),
- "RSP_GET_ACK": "8'h%02X" % int(responses["GET_ACK"]["type"]),
- "RSP_GET_DATA": "8'h%02X" % int(responses["GET_DATA"]["type"]),
- "RSP_MOTOR_DONE": "8'h%02X" % int(responses["MOTOR_DONE"]["type"]),
- "RSP_NACK": "8'h%02X" % int(responses["NACK"]["type"]),
- "NACK_UNSUPPORTED": "8'd%d" % int(responses["NACK"]["reason"]["UNSUPPORTED"]),
- "NACK_BAD_LENGTH": "8'd%d" % int(responses["NACK"]["reason"]["BAD_LENGTH"]),
- "NACK_BAD_VALUE": "8'd%d" % int(responses["NACK"]["reason"]["BAD_VALUE"]),
- "NACK_QUEUE_FULL": "8'd%d" % int(responses["NACK"]["reason"]["QUEUE_FULL"]),
- "NACK_BUSY": "8'd%d" % int(responses["NACK"]["reason"]["BUSY"]),
- "SET_ALL_BYTES": set_all_bytes,
- "GET_DATA_BYTES": length,
- "MOTOR_DONE_BYTES": int(responses["MOTOR_DONE"]["payload_length"]),
- "AXIS_COUNT": int(axis_slots["count"]),
- "SLOTS_PER_AXIS": int(motors["queue"]["slots_per_axis"]),
- "SLOT_BYTES": slot_bytes,
- "AXIS_SLOT_BASE": slot_base,
- "FAN_COUNT": int(outputs["fan_count"]),
- "PTC_COUNT": int(outputs["chamber_ptc_count"]),
- "PTC_PHYSICAL": int(outputs["physical_ptc_count"]),
- "PWM_HZ": int(pwm["fan_hz"]),
- "PWM_PHASES": int(pwm["phases"]),
- "PWM_PHASE_CLKS": phase_clks,
- "PWM_PERIOD_CLKS": period_clks,
- "LIMIT_ACTIVE_HIGH": limit_active_high,
- "BOOT_FAN_PERCENT": int(outputs["boot"]["fan_percent"]),
- "BOOT_PTC_PERCENT": int(outputs["boot"]["ptc_percent"]),
- "HOST_INTER_BYTE_TIMEOUT_CLKS": inter_byte_timeout,
- }
- if set(values) != set(name[3:] for name in MR_FROZEN_MACROS):
- raise ValueError("frozen macro set mismatch: " + ", ".join(sorted(set(values) ^ {n[3:] for n in MR_FROZEN_MACROS})))
- if values["SLOTS_PER_AXIS"] != 1 or values["SLOT_BYTES"] != 5 or values["AXIS_SLOT_BASE"] != 8:
- raise ValueError("actuator geometry must be one latest-wins slot per axis; wire slots are 5 bytes at base 8")
- if values["MOTOR_DONE_BYTES"] != 4:
- raise ValueError("MOTOR_DONE must be 4 bytes")
- if values["PWM_PHASES"] * values["PWM_PHASE_CLKS"] != values["PWM_PERIOD_CLKS"]:
- raise ValueError("PWM phase budget mismatch")
- sha = contract_sha256({"wire": wire, "status": status, "project": project, "ct_format": ct_format})
- header = [BT + "ifndef PROD2U_MRDIMM_PARAMS_VH", BT + "define PROD2U_MRDIMM_PARAMS_VH",
- "// Generated from raw wire/status/project contracts; SHA256 " + sha]
- header += [BT + "define " + name + " " + str(values[name[3:]]) for name in MR_FROZEN_MACROS]
- header += [BT + "endif", ""]
- layout = {
- "schema": status["schema"],
- "product": project["project_id"],
- "contract_sha256": sha,
- "payload_type": int(status["payload_type"]),
- "byte_order": status["byte_order"],
- "length": length,
- "fields": fields,
- "limit_masks": status["limit_masks"],
- "temperature_encoding": status["temperature_encoding"],
- "output_defaults": status["output_defaults"],
- "fan_ptc_mapping": status["fan_ptc_mapping"],
- "motor_axes": {
- **status["motor_axes"],
- "slots_per_axis": values["SLOTS_PER_AXIS"],
- "slot_bytes": values["SLOT_BYTES"],
- "axis_slot_base": values["AXIS_SLOT_BASE"],
- "slot_layout": slot,
- "actions": normalize(set_all["actions"]),
- "implemented_min_half_period_us": int(set_all["implemented_min_half_period_us"]),
- "speed_hz": set_all["speed_hz"],
- },
- "control": {"wire": normalize(wire), "outputs": outputs, "board": project["board"]},
- }
- nothing = int(list(set_all["actions"].keys())[list(set_all["actions"].values()).index("NOTHING")])
- push_down = int([k for k, v in set_all["actions"].items() if v == "PUSH_DOWN"][0])
- push_up = int([k for k, v in set_all["actions"].items() if v == "PUSH_UP"][0])
- stop_clear = int([k for k, v in set_all["actions"].items() if v == "STOP_CLEAR"][0])
- reasons = responses["MOTOR_DONE"]["reasons"]
- reason_steps = int([k for k, v in reasons.items() if v == "steps_complete"][0])
- reason_lower = int([k for k, v in reasons.items() if v == "lower_limit"][0])
- reason_upper = int([k for k, v in reasons.items() if v == "upper_limit"][0])
- reason_both = int([k for k, v in reasons.items() if v == "both_limits"][0])
- boot_fan = int(values["BOOT_FAN_PERCENT"])
- boot_ptc = int(values["BOOT_PTC_PERCENT"])
- idle_axes = [(nothing, 0, 0)] * values["AXIS_COUNT"]
- stop_axes = [(stop_clear, 0, 0)] * values["AXIS_COUNT"]
- push_axis = [(nothing, 0, 0)] * values["AXIS_COUNT"]
- push_axis[0] = (push_down, 100, 1000)
- push_axis[11] = (push_up, 65535, 1)
- stop_one = [(nothing, 0, 0)] * values["AXIS_COUNT"]
- stop_one[4] = (stop_clear, 0, 0)
- data_sample = (bytes([boot_fan] * 4) + bytes([boot_ptc] * 4)
- + bytes(25 + index for index in range(24))
- + bytes(60 + index for index in range(27))
- + (0x0002).to_bytes(2, "little") + (0x0800).to_bytes(2, "little")
- + (bytes((0, 0)) if has_buzzer else b""))
- data_invalid = (bytes([boot_fan] * 4) + bytes([boot_ptc] * 4) + bytes([0xFF] * 51) + bytes(4)
- + (bytes((0, 0)) if has_buzzer else b""))
- buzzer_arg = 0 if has_buzzer else None
- golden = {
- "schema": "prod2u-mrdimm-golden-v1-8bit",
- "contract_sha256": sha,
- "protocol": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H (CRC-16/CCITT-FALSE over TYPE+LENGTH+PAYLOAD)",
- "fixed_vectors": {
- "get_all_request": frame(0x02, b""),
- "set_ack": frame(0x81, b""),
- "get_ack": frame(0x82, b""),
- "nack_set_queue_full": nack(0x01, 0x04),
- "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
- "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
- },
- "frames": {
- "get_all_request": frame(0x02, b""),
- "get_ack": frame(0x82, b""),
- "set_ack": frame(0x81, b""),
- "set_all_idle": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, idle_axes, buzzer=buzzer_arg)),
- "set_all_push_down_axis0_100hz": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, push_axis, buzzer=buzzer_arg)),
- "set_all_stop_clear_all_axes": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_axes, buzzer=buzzer_arg)),
- "set_all_stop_clear_axis4_only": frame(0x01, set_all_payload([boot_fan] * 4, [boot_ptc] * 4, stop_one, buzzer=buzzer_arg)),
- "nack_unsupported": nack(0x01, 0x01),
- "nack_bad_length": nack(0x01, 0x02),
- "nack_bad_value": nack(0x01, 0x03),
- "nack_set_queue_full": nack(0x01, 0x04),
- "nack_busy": nack(0x01, 0x05),
- "nack_unsupported_request_7f": nack(0x7F, 0x01),
- "motor_done_axis0_steps_complete": motor_done(0, reason_steps, 1),
- "motor_done_axis3_lower_limit": motor_done(3, reason_lower, 250),
- "motor_done_axis4_upper_limit_4387": motor_done(4, reason_upper, 4387),
- "motor_done_axis4_both_limits_0": motor_done(4, reason_both, 0),
- "motor_done_axis11_steps_complete_65535": motor_done(11, reason_steps, 65535),
- "get_data_sample": frame(0x42, data_sample),
- "get_data_invalid_temperature": frame(0x42, data_invalid),
- },
- "action_codes": normalize(set_all["actions"]),
- "motor_done_reasons": normalize(reasons),
- }
- if len(data_sample) != length or len(data_invalid) != length:
- raise ValueError("GET_DATA sample length mismatch")
- doc = ["# MRDIMM GET_DATA (type 0x42)", "",
- f"Length: {length} bytes. Little endian. Low 12 bits of a limit mask are Axis0..Axis11; the high 4 bits are zero.", "",
- "| Field | Offset | Bytes |", "|---|---:|---:|"]
- doc += [f"| {name} | {field['offset']} | {field['size']} |" for name, field in fields.items()]
- doc += ["", "## SET_ALL axis slot (offset 8 + 5*i)", "",
- "| Field | Offset | Bytes |", "|---|---:|---:|"]
- doc += [f"| {name} | {entry['offset']} | {FIELD_SIZES[entry['type']]} |" for name, entry in slot.items()]
- doc += ["", "Actions: " + ", ".join(f"{code:02X}={name}" for code, name in sorted(set_all["actions"].items())), ""]
- return {
- out / "prod2u_mrdimm_params.vh": ("\n".join(header)).encode(),
- out / "snapshot-layout.json": canon(layout),
- out / "golden-vectors.json": canon(golden),
- out / "status-layout.md": ("\n".join(doc) + "\n").encode(),
- out / "contract-sha256.txt": (sha + "\n").encode(),
- }
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--check", action="store_true")
- args = parser.parse_args()
- drift = []
- for path, content in generate().items():
- if args.check:
- if not path.is_file() or path.read_bytes() != content:
- drift.append(path.relative_to(ROOT).as_posix())
- else:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(content)
- if drift:
- print("generated drift: " + ", ".join(drift))
- return 1
- print("PASS: mrdimm params, GET_DATA layout and golden vectors generated")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|