| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307 |
- #!/usr/bin/env python3
- """Generate the one active 6400 manual UART + standard Host-I2C contract.
- 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.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- from pathlib import Path
- from typing import Any
- import yaml
- ROOT = Path(__file__).resolve().parents[1]
- CONTRACTS = ROOT / "contracts"
- OUT = ROOT / "generated" / "6400"
- def canon(value: Any) -> bytes:
- return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
- def load_yaml(name: str) -> Any:
- return yaml.safe_load((CONTRACTS / name).read_text(encoding="utf-8"))
- def load_json(name: str) -> Any:
- return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
- def contract_hash(manual: dict[str, Any], wire: dict[str, Any], snapshot: dict[str, Any], fan: dict[str, Any], evidence: dict[str, Any]) -> str:
- payload = {"manual": manual, "wire": wire, "snapshot": snapshot, "fan": fan, "host_i2c_evidence_sha256": evidence["evidence_sha256"]}
- return hashlib.sha256(canon(payload)).hexdigest()
- def snapshot_layout(snapshot: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:
- sizes = {"u8": 1, "u16": 2, "u32": 4, "bytes": 1}
- offset, rows = 0, []
- for field in snapshot["fields"]:
- size = sizes[field["type"]] * int(field.get("count", 1))
- row = dict(field)
- row.update(offset=offset, size=size)
- rows.append(row)
- offset += size
- return rows, offset
- def crc16(body: bytes) -> int:
- value = 0xFFFF
- for byte in body:
- value ^= byte << 8
- for _ in range(8):
- value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
- return value
- def frame(kind: int, payload: bytes) -> str:
- """New 16-bit-length frame: A5 5A | TYPE | LEN:u16le | PAYLOAD | CRC:u16le."""
- body = bytes((kind, len(payload) & 0xFF, (len(payload) >> 8) & 0xFF)) + payload
- return (bytes((0xA5, 0x5A)) + body + crc16(body).to_bytes(2, "little")).hex().upper()
- def ack(request_type: int, status: int, detail: int = 0) -> str:
- return frame(0x80, bytes((request_type, status, detail & 0xFF, (detail >> 8) & 0xFF)))
- BT = chr(96)
- # Fixed contract vectors (16-bit protocol). These must never be produced by
- # the RTL under test; they are the cross-check between two independent
- # implementations.
- VECTOR_GET_ALL = "A55A020000FCA2"
- VECTOR_GET_ALL_ACK = "A55A800400020000 00FEB1".replace(" ", "")
- VECTOR_KEEPALIVE = "A55A0500006C27"
- PARAMS_HEADER_STATIC = """__BT__define FB_CLOCK_HZ 25000000
- __BT__define FB_PTC_COUNT 24
- __BT__define FB_FRONT_FAN_COUNT 4
- __BT__define FB_REAR_FAN_COUNT 4
- __BT__define FB_OUTPUT_COUNT 32
- __BT__define FB_BMC_COUNT 24
- __BT__define FB_CT_COUNT 27
- __BT__define FB_PRIMARY_COUNT 18
- __BT__define FB_HOLDOUT_COUNT 6
- __BT__define FB_HOST_BAUD 921600
- __BT__define FB_BMC_BAUD 115200
- __BT__define FB_HOST_FIXED_CLKS_PER_BIT 27
- __BT__define FB_BMC_CLKS_PER_BIT 217
- __BT__define FB_PWM_PHASES 100
- __BT__define FB_PTC_PWM_HZ 500
- __BT__define FB_FAN_PWM_HZ 500
- __BT__define FB_PTC_PWM_PHASE_CLKS 500
- __BT__define FB_FAN_PWM_PHASE_CLKS 500
- __BT__define FB_PTC_PWM_PERIOD_CLKS 50000
- __BT__define FB_FAN_PWM_PERIOD_CLKS 50000
- __BT__define FAN_BOARD_INVERT_MASK 8'h0F
- __BT__define FRONT_FAN_CONNECTOR_MAP "CON25.7,CON8.7,CON24.7,CON26.7"
- __BT__define FRONT_FAN_FPGA_BALL_MAP "B1,C4,B5,A14"
- __BT__define REAR_FAN_CONNECTOR_MAP "CON64.4,CON66.4,CON62.4,CON60.4"
- __BT__define REAR_FAN_FPGA_BALL_MAP "P15,N15,M14,P5"
- __BT__define FB_BOARD_ID "fcb_fpga_mcu_v1_1_20260625"
- __BT__define FB_BOARD_EVIDENCE_SHA256 "db02938f7943b2ae532aa18208f61588364d32a70a0cc72f74b4a94aaab7e258"
- __BT__define FB_TEMP_CHANNEL_CLAMP 7600
- __BT__define FB_TEMP_LANE_HARD 7700
- __BT__define FB_TEMP_LANE_RELEASE 7200
- __BT__define FAN_SAFE_DUTY 20
- __BT__define FAN_STANDBY_DUTY `FAN_SAFE_DUTY
- __BT__define FB_FAN_RESET `FAN_STANDBY_DUTY
- __BT__define FB_FAN_HARD 100
- __BT__define CONTROL_WATCHDOG_SECONDS 30
- __BT__define SET_ALL_WATCHDOG_SECONDS `CONTROL_WATCHDOG_SECONDS
- __BT__define FB_OWNER_SAFE 3'd0
- __BT__define FB_OWNER_MANUAL 3'd1
- // Unified 16-bit-length protocol (2026 contract). The historical 8-bit
- // length frames are retired; there is no wire autodetect.
- __BT__define FB_FRAME_LENGTH_WIDTH 16
- __BT__define FB_CMD_SET_ALL 8'h01
- __BT__define FB_CMD_GET_ALL 8'h02
- __BT__define FB_CMD_MOTOR_QUEUE_WRITE 8'h03
- __BT__define FB_CMD_MOTOR_CONTROL 8'h04
- __BT__define FB_CMD_OUTPUT_KEEPALIVE 8'h05
- __BT__define FB_CMD_EVENT_READ 8'h08
- __BT__define FB_CMD_EVENT_CLEAR 8'h09
- __BT__define FB_RSP_ACK_NACK 8'h80
- __BT__define FB_RSP_ALL_STATUS_DATA 8'h81
- __BT__define FB_RSP_EVENT_DATA 8'h83
- __BT__define FB_STATUS_OK 8'd0
- __BT__define FB_STATUS_UNSUPPORTED 8'd1
- __BT__define FB_STATUS_BAD_LENGTH 8'd2
- __BT__define FB_STATUS_BAD_VALUE 8'd3
- __BT__define FB_STATUS_BUSY 8'd4
- __BT__define FB_STATUS_QUEUE_FULL 8'd5
- __BT__define FB_STATUS_BAD_AXIS 8'd6
- __BT__define FB_STATUS_BAD_MODE 8'd7
- __BT__define FB_STATUS_BAD_REGISTER 8'd8
- __BT__define FB_STATUS_NOT_READY 8'd9
- __BT__define FB_MAX_REQUEST_PAYLOAD 256
- __BT__define FB_MAX_RESPONSE_PAYLOAD 1024
- __BT__define FB_SNAPSHOT_LENGTH {snapshot_length}
- __BT__define FB_HOST_I2C_ADDRESS 7'h2A
- __BT__define FB_HOST_I2C_REGISTER_WIDTH 16
- """
- def params_text_render(sha: str, snapshot_length: int, snapshot_fields: list[dict[str, Any]]) -> str:
- """Render the params header entirely from contract inputs.
- Snapshot field offsets are computed from the schema exactly like the
- JSON layout, so the .vh can never drift from the JSON/GUI decoders
- (the historical +2-byte drift from ``manual_mode`` onwards is the
- regression this kills: D01).
- """
- lines = [f"// Generated manual contract SHA-256: {sha}"]
- lines.append(PARAMS_HEADER_STATIC
- .replace("{snapshot_length}", str(snapshot_length))
- .replace("__BT__", BT))
- for row in snapshot_fields:
- lines.append(f"{BT}define FB_SNAPSHOT_{row['name'].upper()}_OFFSET {row['offset']}")
- text = "\n".join(lines) + "\n"
- if "{" in text.replace("7'h", ""):
- raise RuntimeError("unresolved placeholder in params template")
- return text
- def generate() -> dict[Path, bytes]:
- manual = load_yaml("6400-manual.yaml")
- wire = load_yaml("6400-wire.yaml")
- snapshot = load_yaml("6400-snapshot.yaml")
- fan = load_yaml("fan-control-parameters.yaml")
- channel_source = load_yaml("channel-map.yaml")
- evidence = load_json("host-i2c-pin-evidence.json")
- sha = contract_hash(manual, wire, snapshot, fan, evidence)
- if manual['uart']['ack_type']!=wire['responses']['ACK_NACK']['type'] or manual['uart']['snapshot_type']!=wire['responses']['ALL_STATUS_DATA']['type']:
- raise ValueError('manual/wire response identifiers disagree')
- if manual['uart']['length_width_bits']!=wire['length_width_bits']:
- raise ValueError('manual/wire length widths disagree')
- fields, length = snapshot_layout(snapshot)
- channel_map = dict(channel_source)
- channel_map["contract_sha256"] = sha
- fan_output = {
- "schema": "prod2u-6400-manual-fan-control-v1",
- "contract_sha256": sha,
- "board_invert_mask": manual["outputs"]["fan_board_invert_mask"],
- "connector_duty_semantics": manual["outputs"]["fan_duty_semantics"],
- "ptc_hz": manual["outputs"]["ptc_pwm_hz"],
- "fan_hz": manual["outputs"]["fan_pwm_hz"],
- "safe_ptc_percent": manual["outputs"]["safe_ptc_percent"],
- "safe_front_percent": manual["outputs"]["safe_front_percent"],
- "safe_rear_percent": manual["outputs"]["safe_rear_percent"],
- "bmc_channel_off_c": manual["safety"]["bmc_single_channel_off_c"],
- "bmc_lane_hard_c": manual["safety"]["bmc_lane_hard_c"],
- "hardware_validation": "NOT_RUN",
- }
- i2c_regs = {
- "schema": "prod2u-6400-host-i2c-register-map-v1",
- "contract_sha256": sha,
- "address_7bit": 0x2A,
- "register_address_width_bits": 16,
- "pointer_msb_first": True,
- "clock_modes_khz": [100, 400],
- "clock_stretching": False,
- "sda_drive": "low_or_hiz_only",
- "registers": [
- {"address": 0x0000, "name": "DEVICE_STATUS", "access": "RO"},
- {"address": 0x0001, "name": "RESPONSE_OK", "access": "RO"},
- {"address": 0x0002, "name": "RESPONSE_COMMAND", "access": "RO"},
- {"address": 0x0003, "name": "RESPONSE_STATUS", "access": "RO"},
- {"address": 0x0004, "name": "RESPONSE_DETAIL", "access": "RO"},
- {"address": 0x0005, "name": "WATCHDOG_REMAINING_SECONDS", "access": "RO"},
- {"address": 0x0006, "name": "SET_ALL_BYTES_WRITTEN", "access": "RO"},
- {"address": 0x0007, "name": "SNAPSHOT_LENGTH_L", "access": "RO"},
- {"address": 0x0008, "name": "SNAPSHOT_LENGTH_H", "access": "RO"},
- {"address": 0x0010, "name": "COMMAND", "access": "WO"},
- {"address": 0x0100, "address_end": 0x011F, "name": "SET_ALL_STAGING", "access": "RW"},
- {"address": 0x0200, "address_end": 0x02FF, "name": "SNAPSHOT_DATA", "access": "RO"},
- ],
- }
- golden = {
- "schema": "prod2u-6400-manual-golden-v2-16bit",
- "contract_sha256": sha,
- "protocol": "A5 5A | TYPE | LENGTH:u16le | PAYLOAD | CRC:u16le (CRC-16/CCITT-FALSE over TYPE+LEN+PAYLOAD)",
- "fixed_vectors": {
- "get_all": VECTOR_GET_ALL,
- "get_all_ack": VECTOR_GET_ALL_ACK,
- "keepalive": VECTOR_KEEPALIVE,
- },
- "frames": {
- "set_all_safe": frame(0x01, bytes(24) + bytes([20]) * 8),
- "get_all": VECTOR_GET_ALL,
- "keepalive": VECTOR_KEEPALIVE,
- "unsupported_03_ack": ack(0x03, 0x01),
- "unsupported_04_ack": ack(0x04, 0x01),
- "unsupported_08_ack": ack(0x08, 0x01),
- "unsupported_09_ack": ack(0x09, 0x01),
- "get_all_ack": VECTOR_GET_ALL_ACK,
- "set_all_ack": ack(0x01, 0x00),
- "keepalive_ack": ack(0x05, 0x00),
- "bad_length_ack": ack(0x01, 0x02, 32),
- },
- }
- host = {
- "schema": "prod2u-6400-manual-host-contract-v1",
- "contract_sha256": sha,
- "product": manual["product"],
- "board": manual["board"],
- "device": manual["device"],
- "canonical_profiles": {
- "6400-front-rear": {
- "allowed_commands": ["SET_ALL", "GET_ALL", "OUTPUT_KEEPALIVE", "MOTOR_QUEUE_WRITE_UNSUPPORTED", "MOTOR_CONTROL_UNSUPPORTED", "EVENT_READ_UNSUPPORTED", "EVENT_CLEAR_UNSUPPORTED"],
- "production": True,
- "simulation_only": False,
- }
- },
- "wire": {
- "uart": manual["uart"],
- "host_i2c": manual["host_i2c"],
- "commands": wire["commands"],
- "responses": wire["responses"],
- },
- "snapshot": {"payload_length": length, "fields": fields},
- "i2c_register_map": i2c_regs,
- "outputs": manual["outputs"],
- "watchdog": manual["watchdog"],
- "safety": manual["safety"],
- }
- uart = {
- "schema": "prod2u-6400-manual-uart-v3-16bit",
- "contract_sha256": sha,
- "product": manual["product"],
- "board": manual["board"],
- "wire": {
- "uart": manual["uart"],
- "host_i2c": manual["host_i2c"],
- "commands": wire["commands"],
- "responses": wire["responses"],
- },
- "outputs": manual["outputs"],
- "watchdog": manual["watchdog"],
- "safety": manual["safety"],
- "snapshot": host["snapshot"],
- }
- params_text = f"{BT}ifndef PROD2U_6400_V1_PARAMS_VH\n{BT}define PROD2U_6400_V1_PARAMS_VH\n" + \
- params_text_render(sha, length, fields) + f"{BT}endif\n"
- return {
- OUT / "host-contract.json": canon(host),
- OUT / "manual-uart-contract.json": canon(uart),
- OUT / "host-i2c-register-map.json": canon(i2c_regs),
- 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(host["snapshot"]),
- OUT / "contract-sha256.txt": (sha + chr(10)).encode(),
- OUT / "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())
|