| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- #!/usr/bin/env python3
- """Import generated CPLD contracts and derive Go/Python constants."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- from pathlib import Path
- import sys
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- DEFAULT_SOURCE = ROOT.parent / "cpld-temperature-control/generated/6400/host-contract.json"
- def json_bytes(value: Any) -> bytes:
- return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
- def camel(name: str) -> str:
- return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
- def outputs(source: Path) -> dict[Path, bytes]:
- raw = source.read_bytes()
- contract = json.loads(raw)
- contract_sha = contract["contract_sha256"]
- wire = contract["wire"]
- snapshot = contract["snapshot"]
- golden = contract["golden_vectors"]["frames"]
- go_lines = [
- "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
- "package protocol6400",
- "",
- f'const ContractSHA256 = "{contract_sha}"',
- f"const SnapshotPayloadLen = {snapshot['payload_length']}",
- f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
- f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
- f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
- f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
- f"const RspSnapshot byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
- f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
- f"const HostBaud = {wire['host_uart']['baud']}",
- "",
- ]
- for field in snapshot["fields"]:
- go_lines.append(f"const Snapshot{camel(field['name'])}Offset = {field['offset']}")
- go_lines.extend([
- "",
- f'const GoldenSetTargetStop = "{golden["set_target_stop"].lower()}"',
- f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
- f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
- f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
- f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
- "",
- ])
- py_lines = [
- '"""Generated 6400 wire and snapshot constants."""',
- f'CONTRACT_SHA256 = "{contract_sha}"',
- f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
- f"HOST_BAUD = {wire['host_uart']['baud']}",
- "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
- "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
- "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
- "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
- "",
- ]
- profile_common = {
- "schema": "hth-6400-profile-v1",
- "contract_sha256": contract_sha,
- "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
- "snapshot_payload_length": snapshot["payload_length"],
- "single_serial_owner": True,
- "one_outstanding_transaction": True,
- }
- production = {**profile_common, "profile_id": "6400-control", "stimulus_supported": False}
- identification = {**profile_common, "profile_id": "6400-identification", "stimulus_supported": True}
- imported_sha = hashlib.sha256(raw).hexdigest()
- return {
- ROOT / "contracts/6400/host-contract.json": raw,
- ROOT / "contracts/6400/SHA256SUMS": f"{imported_sha} host-contract.json\n".encode(),
- ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
- ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
- ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import * # noqa: F401,F403\n",
- ROOT / "profiles/6400-control/profile.json": json_bytes(production),
- ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
- }
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
- parser.add_argument("--check", action="store_true")
- args = parser.parse_args()
- expected = outputs(args.source)
- drift = []
- for path, content in expected.items():
- if args.check:
- if not path.exists() or path.read_bytes() != content:
- drift.append(str(path.relative_to(ROOT)))
- else:
- path.parent.mkdir(parents=True, exist_ok=True)
- if not path.exists() or path.read_bytes() != content:
- path.write_bytes(content)
- if drift:
- print("generated drift: " + ", ".join(drift), file=sys.stderr)
- return 1
- print(f"PASS: {len(expected)} imported files")
- return 0
- if __name__ == "__main__":
- sys.exit(main())
|