| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435 |
- #!/usr/bin/env python3
- """Generate the active 6400 V1.1 manual-uart contract artifacts.
- Every generated artifact is rendered from the original contract inputs in
- ``contracts/`` (YAML/JSON sources). Generated outputs are never read back as
- templates: deleting ``generated/`` entirely and regenerating must produce
- byte-identical results, and ``--check`` never writes.
- The wire 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, and no Host I2C.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import sys
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- site_pkg = Path("/workspace/site-packages")
- if site_pkg.is_dir() and str(site_pkg) not in sys.path:
- sys.path.insert(0, str(site_pkg))
- import yaml
- from tools.crc16_ccitt_table import crc16_ccitt_false_table # noqa: E402
- CONTRACTS = ROOT / "contracts"
- OUT = ROOT / "generated" / "6400"
- # Frozen macro names (docs/architecture/final-rtl-interfaces.md). The emitted
- # header defines exactly this set and nothing else.
- FB_FROZEN_MACROS = (
- "FB_CLOCK_HZ", "FB_PTC_COUNT", "FB_FRONT_FAN_COUNT", "FB_REAR_FAN_COUNT",
- "FB_OUTPUT_COUNT", "FB_BMC_COUNT", "FB_CT_COUNT", "FB_HOST_BAUD",
- "FB_BMC_BAUD", "FB_HOST_CLKS_PER_BIT", "FB_BMC_CLKS_PER_BIT",
- "FB_PWM_PHASES", "FB_PTC_PWM_HZ", "FB_FAN_PWM_HZ", "FB_PWM_PHASE_CLKS",
- "FB_PWM_PERIOD_CLKS", "FAN_BOARD_INVERT_MASK", "CONTROL_WATCHDOG_SECONDS",
- "FB_FRAME_LENGTH_WIDTH", "FB_CMD_SET_ALL", "FB_CMD_GET_ALL",
- "FB_RSP_SET_ACK", "FB_RSP_GET_ACK", "FB_RSP_GET_DATA", "FB_RSP_NACK",
- "FB_NACK_UNSUPPORTED", "FB_NACK_BAD_LENGTH", "FB_NACK_BAD_VALUE",
- "FB_NACK_QUEUE_FULL", "FB_NACK_BUSY", "FB_SET_ALL_BYTES",
- "FB_GET_DATA_BYTES", "FB_HOST_INTER_BYTE_TIMEOUT_CLKS",
- "FB_HOST_BAUD_DIV", "FB_HOST_BAUD_MUL",
- )
- FIELD_SIZES = {"u8": 1, "u16": 2, "u16le": 2, "u32": 4, "bytes": 1}
- def macro_key(name: str) -> str:
- """FB_* macros map to short value keys; FAN_/CONTROL_ names are literal."""
- return name[3:] if name.startswith("FB_") else name
- def canon(value: Any) -> bytes:
- return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
- def load_yaml(name: str, contracts: Path = CONTRACTS) -> Any:
- return yaml.safe_load((contracts / name).read_text(encoding="utf-8"))
- 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 layout 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 generate(root: Path | None = None, *, product: str = "6400") -> dict[Path, bytes]:
- base = root if root is not None else ROOT
- contracts = (base / "contracts") if root is not None else CONTRACTS
- if product not in ("6400", "6400-v2"):
- raise ValueError("unsupported 6400 product " + product)
- out = base / "generated" / product
- prefix = product
- manual = load_yaml(prefix + "-manual.yaml", contracts)
- wire = load_yaml(prefix + "-wire.yaml", contracts)
- snapshot = load_yaml(prefix + "-snapshot.yaml", contracts)
- fan = load_yaml("fan-control-parameters.yaml", contracts)
- channel_source = load_yaml("6400-v2-channel-map.yaml" if product == "6400-v2" else "channel-map.yaml", contracts)
- clock = int(manual["clock_hz"])
- if int(wire["clock_hz"]) != clock:
- raise ValueError("manual/wire clock disagreement")
- if wire["device"] != manual["device"]:
- raise ValueError("manual/wire device disagreement")
- uart = manual["uart"]
- if int(uart["length_width_bits"]) != 8 or int(wire["length_width_bits"]) != 8:
- raise ValueError("6400 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")
- commands = wire["commands"]
- responses = wire["responses"]
- if int(uart["set_all_type"]) != int(commands["SET_ALL"]["type"]):
- raise ValueError("manual/wire SET_ALL identifiers disagree")
- if int(uart["get_all_type"]) != int(commands["GET_ALL"]["type"]):
- raise ValueError("manual/wire GET_ALL identifiers disagree")
- if int(uart["set_ack_type"]) != int(responses["SET_ACK"]["type"]):
- raise ValueError("manual/wire SET_ACK identifiers disagree")
- if int(uart["get_ack_type"]) != int(responses["GET_ACK"]["type"]):
- raise ValueError("manual/wire GET_ACK identifiers disagree")
- if int(uart["get_data_type"]) != int(responses["GET_DATA"]["type"]):
- raise ValueError("manual/wire GET_DATA identifiers disagree")
- if int(uart["nack_type"]) != int(responses["NACK"]["type"]):
- raise ValueError("manual/wire NACK identifiers disagree")
- outputs = manual["outputs"]
- duty_count = int(outputs["ptc_count"]) + int(outputs["front_fan_count"]) + int(outputs["rear_fan_count"])
- ssr_count = int(outputs.get("ssr_count", 0))
- buzzer_count = int(outputs.get("buzzer_count", 0))
- output_count = duty_count + ssr_count + buzzer_count
- set_all_bytes = int(commands["SET_ALL"]["payload_length"])
- if set_all_bytes != int(uart["set_all_payload_bytes"]) or set_all_bytes != output_count:
- raise ValueError("SET_ALL payload must cover every output exactly once")
- fields, length = fields_layout(snapshot["fields"])
- if length != int(snapshot["payload_length"]) or length != int(uart["get_data_payload_bytes"]):
- raise ValueError("GET_DATA length disagreement")
- if fields["ptc_percent"]["offset"] != 0 or fields["front_fan_percent"]["offset"] != 24:
- raise ValueError("PTC/Front offsets must be 0/24")
- if fields["rear_fan_percent"]["offset"] != 28 or fields["rear_fan_percent"]["count"] != 4:
- raise ValueError("Rear block must be offset 28..31")
- if fields["bmc_temp_c"]["offset"] != 32 or fields["bmc_temp_c"]["count"] != 24:
- raise ValueError("BMC24 block must be offset 32..55")
- if fields["ct_temp_c"]["offset"] != 56 or fields["ct_temp_c"]["count"] != 27:
- raise ValueError("CT27 block must be offset 56..82")
- if ssr_count and (ssr_count != 3 or fields["ssr_percent"]["offset"] != 83 or fields["ssr_percent"]["count"] != 3):
- raise ValueError("V2 SSR block must append three bytes at 83..85")
- if buzzer_count:
- if (
- fields.get("estop_btn", {}).get("offset") != 86
- or fields.get("hood_open_btn", {}).get("offset") != 87
- or fields.get("hood_close_btn", {}).get("offset") != 88
- or fields.get("buzzer_state", {}).get("offset") != 89
- ):
- raise ValueError("V2 estop_btn/hood_open_btn/hood_close_btn/buzzer_state must append at 86..89")
- pwm = fan["pwm"]
- if int(pwm["ptc_hz"]) != int(outputs["ptc_pwm_hz"]) or int(pwm["fan_hz"]) != int(outputs["fan_pwm_hz"]):
- raise ValueError("PWM frequency disagreement")
- period_clks = clock // int(pwm["fan_hz"])
- if clock % int(pwm["fan_hz"]):
- raise ValueError("PWM frequency must divide the clock")
- phases = int(pwm["phases"])
- if period_clks % phases:
- raise ValueError("PWM phases must divide the period")
- phase_clks = period_clks // phases
- if int(pwm["ptc_phase_clks"]) != phase_clks or int(pwm["fan_phase_clks"]) != phase_clks:
- raise ValueError("PWM phase budget disagreement")
- host_baud = int(wire["host_uart"]["baud"])
- bmc_baud = int(wire["bmc_uart"]["baud"])
- host_clks_per_bit = int(wire["host_uart"]["fixed_candidate_clks_per_bit"])
- bmc_clks_per_bit = int(wire["bmc_uart"]["clks_per_bit"])
- if (clock + host_baud // 2) // host_baud != host_clks_per_bit:
- raise ValueError("host clks_per_bit mismatch")
- if (clock + bmc_baud // 2) // bmc_baud != bmc_clks_per_bit:
- raise ValueError("BMC clks_per_bit mismatch")
- # Retain the public mathematical ratio macros for compatibility. The
- # production UART uses HOST_CLKS_PER_BIT, a nearest-integer divider.
- from math import gcd
- baud_gcd = gcd(clock, host_baud)
- baud_div, baud_mul = clock // baud_gcd, host_baud // baud_gcd
- values = {
- "CLOCK_HZ": clock,
- "PTC_COUNT": int(outputs["ptc_count"]),
- "FRONT_FAN_COUNT": int(outputs["front_fan_count"]),
- "REAR_FAN_COUNT": int(outputs["rear_fan_count"]),
- "OUTPUT_COUNT": output_count,
- "BMC_COUNT": int(manual["temperature"]["bmc_channels"]),
- "CT_COUNT": int(manual["temperature"]["ct_channels"]),
- "HOST_BAUD": host_baud,
- "BMC_BAUD": bmc_baud,
- "HOST_CLKS_PER_BIT": host_clks_per_bit,
- "BMC_CLKS_PER_BIT": bmc_clks_per_bit,
- "PWM_PHASES": phases,
- "PTC_PWM_HZ": int(pwm["ptc_hz"]),
- "FAN_PWM_HZ": int(pwm["fan_hz"]),
- "PWM_PHASE_CLKS": phase_clks,
- "PWM_PERIOD_CLKS": period_clks,
- "FAN_BOARD_INVERT_MASK": "8'h%02X" % int(str(outputs["fan_board_invert_mask"]), 0),
- "CONTROL_WATCHDOG_SECONDS": int(manual["watchdog"]["seconds"]),
- "FRAME_LENGTH_WIDTH": int(wire["length_width_bits"]),
- "CMD_SET_ALL": "8'h%02X" % int(commands["SET_ALL"]["type"]),
- "CMD_GET_ALL": "8'h%02X" % int(commands["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_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,
- "HOST_INTER_BYTE_TIMEOUT_CLKS": int(wire["inter_byte_timeout_clks"]),
- "HOST_BAUD_DIV": baud_div,
- "HOST_BAUD_MUL": baud_mul,
- }
- if set(values) != set(macro_key(name) for name in FB_FROZEN_MACROS):
- raise ValueError("frozen macro set mismatch")
- if values["PWM_PHASE_CLKS"] * values["PWM_PHASES"] != values["PWM_PERIOD_CLKS"]:
- raise ValueError("PWM phase budget mismatch")
- sha = contract_sha256({"manual": manual, "wire": wire, "snapshot": snapshot,
- "fan": fan, "channel_map": channel_source})
- header = ["`ifndef PROD2U_6400_V1_PARAMS_VH", "`define PROD2U_6400_V1_PARAMS_VH",
- "// Generated from raw manual/wire/snapshot/fan/channel-map contracts; SHA256 " + sha]
- header += ["`define " + name + " " + str(values[macro_key(name)]) for name in FB_FROZEN_MACROS]
- header += ["`endif", ""]
- snapshot_layout = {
- "schema": snapshot["schema"],
- "contract_sha256": sha,
- "payload_type": int(snapshot["payload_type"]),
- "byte_order": snapshot["byte_order"],
- "length": length,
- "payload_length": length,
- "fields": fields,
- "temperature_encoding": snapshot["temperature_encoding"],
- "output_defaults": snapshot["output_defaults"],
- }
- channel_map = dict(channel_source)
- channel_map["contract_sha256"] = sha
- fan_output = {
- "schema": "prod2u-6400-manual-fan-control-v2",
- "contract_sha256": sha,
- "board_invert_mask": outputs["fan_board_invert_mask"],
- "connector_duty_semantics": outputs["fan_duty_semantics"],
- "ptc_hz": int(pwm["ptc_hz"]),
- "fan_hz": int(pwm["fan_hz"]),
- "pwm_phases": phases,
- "pwm_phase_clks": phase_clks,
- "pwm_period_clks": period_clks,
- "safe_ptc_percent": int(outputs["default_ptc_percent"]),
- "safe_front_percent": int(outputs["default_front_percent"]),
- "safe_rear_percent": int(outputs["default_rear_percent"]),
- "temperature": fan["temperature"],
- "hardware_validation": "NOT_RUN",
- }
- sample = (bytes([int(outputs["default_ptc_percent"])] * int(outputs["ptc_count"]))
- + bytes([int(outputs["default_front_percent"])] * int(outputs["front_fan_count"]))
- + bytes([int(outputs["default_rear_percent"])] * int(outputs["rear_fan_count"]))
- + bytes(25 + index for index in range(int(manual["temperature"]["bmc_channels"])))
- + bytes(60 + index for index in range(int(manual["temperature"]["ct_channels"]))))
- invalid = (bytes([int(outputs["default_ptc_percent"])] * int(outputs["ptc_count"]))
- + bytes([int(outputs["default_front_percent"])] * int(outputs["front_fan_count"]))
- + bytes([int(outputs["default_rear_percent"])] * int(outputs["rear_fan_count"]))
- + bytes([0xFF] * (int(manual["temperature"]["bmc_channels"]) + int(manual["temperature"]["ct_channels"]))))
- sample += bytes([int(outputs.get("default_ssr_percent", 0))] * ssr_count)
- invalid += bytes([int(outputs.get("default_ssr_percent", 0))] * ssr_count)
- if buzzer_count:
- sample += bytes([0, 0, 0, int(outputs.get("default_buzzer", 0))])
- invalid += bytes([0, 0, 0, int(outputs.get("default_buzzer", 0))])
- if len(sample) != length or len(invalid) != length:
- raise ValueError("GET_DATA sample length mismatch")
- set_all_idle = bytes([0] * int(outputs["ptc_count"])) + bytes(
- [int(outputs["default_front_percent"])] * int(outputs["front_fan_count"])
- ) + bytes([int(outputs["default_rear_percent"])] * int(outputs["rear_fan_count"]))
- set_all_idle += bytes([int(outputs.get("default_ssr_percent", 0))] * ssr_count)
- if buzzer_count:
- set_all_idle += bytes([int(outputs.get("default_buzzer", 0))])
- set_all_full = bytes([100] * (duty_count + ssr_count)) + (bytes([1]) if buzzer_count else b"")
- set_all_ptc_zero_fan_zero = bytes(output_count)
- fixed = {
- "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": frame(0x50, bytes((4, 2)) + (4387).to_bytes(2, "little")),
- "motor_done_axis4_both_limits_0": frame(0x50, bytes((4, 3, 0, 0))),
- }
- golden = {
- "schema": "prod2u-6400-manual-golden-v3-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": fixed["get_all_request"],
- "set_ack": fixed["set_ack"],
- "get_ack": fixed["get_ack"],
- "nack_set_queue_full": fixed["nack_set_queue_full"],
- },
- "protocol_fixed_vectors": fixed,
- "protocol_fixed_vectors_note": (
- "CRC anchors from the shared protocol table. MOTOR_DONE and QUEUE_FULL are "
- "MRDIMM-only behaviours; the 6400 encoder still produces these bytes and the "
- "independent CRC cross-check must agree. 6400 does not emit MOTOR_DONE."
- ),
- "frames": {
- "get_all_request": frame(0x02, b""),
- "get_ack": frame(0x82, b""),
- "set_ack": frame(0x81, b""),
- "set_all_idle_defaults": frame(0x01, set_all_idle),
- "set_all_ptc_zero_fan_zero": frame(0x01, set_all_ptc_zero_fan_zero),
- "set_all_all_100": frame(0x01, set_all_full),
- "nack_unsupported": nack(0x01, 0x01),
- "nack_bad_length": nack(0x01, 0x02),
- "nack_bad_value": nack(0x01, 0x03),
- "nack_queue_full_encoding": nack(0x01, 0x04),
- "nack_busy": nack(0x01, 0x05),
- "nack_unsupported_request_7f": nack(0x7F, 0x01),
- "get_data_sample": frame(0x42, sample),
- "get_data_invalid_temperature": frame(0x42, invalid),
- },
- "nack_reasons": {name: int(code) for name, code in responses["NACK"]["reason"].items()},
- }
- host = {
- "schema": "prod2u-6400-manual-host-contract-v2",
- "contract_sha256": sha,
- "product": manual["product"],
- "board": manual["board"],
- "device": manual["device"],
- "canonical_profiles": {
- "6400-front-rear": {
- "allowed_commands": ["SET_ALL", "GET_ALL"],
- "production": True,
- "simulation_only": False,
- }
- },
- "wire": {
- "frame": wire["frame"],
- "crc": wire["crc"],
- "uart": uart,
- "commands": commands,
- "responses": responses,
- "invalid_behavior": wire["invalid_behavior"],
- },
- "snapshot": {"payload_length": length, "payload_type": int(snapshot["payload_type"]), "fields": fields},
- "outputs": outputs,
- "watchdog": manual["watchdog"],
- "temperature": manual["temperature"],
- }
- uart_contract = {
- "schema": "prod2u-6400-manual-uart-v4-8bit",
- "contract_sha256": sha,
- "product": manual["product"],
- "board": manual["board"],
- "device": manual["device"],
- "wire": {
- "uart": uart,
- "commands": commands,
- "responses": responses,
- "inter_byte_timeout_clks": int(wire["inter_byte_timeout_clks"]),
- "inter_byte_timeout_us": int(wire["inter_byte_timeout_us"]),
- "host_uart": wire["host_uart"],
- "bmc_uart": wire["bmc_uart"],
- },
- "outputs": outputs,
- "watchdog": manual["watchdog"],
- "temperature": manual["temperature"],
- "snapshot": snapshot_layout,
- }
- params_text = "\n".join(header)
- if product == "6400-v2":
- params_text = params_text.replace("PROD2U_6400_V1_PARAMS_VH", "PROD2U_6400_V2_PARAMS_VH")
- host["canonical_profiles"] = {"6400-v2": host["canonical_profiles"]["6400-front-rear"]}
- return {
- out / "host-contract.json": canon(host),
- out / "manual-uart-contract.json": canon(uart_contract),
- out / "golden-vectors.json": canon(golden),
- out / "channel-map.json": canon(channel_map),
- out / "fan-control-parameters.json": canon(fan_output),
- out / "snapshot-layout.json": canon(snapshot_layout),
- out / "contract-sha256.txt": (sha + chr(10)).encode(),
- out / ("prod2u_6400_v2_params.vh" if product == "6400-v2" else "prod2u_6400_v1_params.vh"): params_text.encode(),
- }
- def main() -> int:
- ap = argparse.ArgumentParser()
- ap.add_argument("--check", action="store_true")
- args = ap.parse_args()
- drift = []
- for path, data in generate().items():
- if args.check:
- if not path.is_file() or path.read_bytes() != data:
- drift.append(path.relative_to(ROOT).as_posix())
- else:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(data)
- if drift:
- print("generated drift: " + ", ".join(drift))
- return 1
- print("PASS: manual 6400 generated")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|