import_6400_contract.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #!/usr/bin/env python3
  2. """Import generated CPLD contracts and derive Go/Python constants."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. from pathlib import Path
  8. import sys
  9. from typing import Any
  10. ROOT = Path(__file__).resolve().parents[1]
  11. DEFAULT_SOURCE = ROOT.parent / "cpld-temperature-control/generated/6400/host-contract.json"
  12. def json_bytes(value: Any) -> bytes:
  13. return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
  14. def camel(name: str) -> str:
  15. return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
  16. def outputs(source: Path) -> dict[Path, bytes]:
  17. raw = source.read_bytes()
  18. contract = json.loads(raw)
  19. contract_sha = contract["contract_sha256"]
  20. wire = contract["wire"]
  21. snapshot = contract["snapshot"]
  22. golden = contract["golden_vectors"]["frames"]
  23. go_lines = [
  24. "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
  25. "package protocol6400",
  26. "",
  27. f'const ContractSHA256 = "{contract_sha}"',
  28. f"const SnapshotPayloadLen = {snapshot['payload_length']}",
  29. f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
  30. f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
  31. f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
  32. f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
  33. f"const RspSnapshot byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
  34. f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
  35. f"const HostBaud = {wire['host_uart']['baud']}",
  36. "",
  37. ]
  38. for field in snapshot["fields"]:
  39. go_lines.append(f"const Snapshot{camel(field['name'])}Offset = {field['offset']}")
  40. go_lines.extend([
  41. "",
  42. f'const GoldenSetTargetStop = "{golden["set_target_stop"].lower()}"',
  43. f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
  44. f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
  45. f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
  46. f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
  47. "",
  48. ])
  49. py_lines = [
  50. '"""Generated 6400 wire and snapshot constants."""',
  51. f'CONTRACT_SHA256 = "{contract_sha}"',
  52. f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
  53. f"HOST_BAUD = {wire['host_uart']['baud']}",
  54. "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
  55. "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
  56. "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
  57. "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
  58. "",
  59. ]
  60. profile_common = {
  61. "schema": "hth-6400-profile-v1",
  62. "contract_sha256": contract_sha,
  63. "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
  64. "snapshot_payload_length": snapshot["payload_length"],
  65. "single_serial_owner": True,
  66. "one_outstanding_transaction": True,
  67. }
  68. production = {**profile_common, "profile_id": "6400-control", "stimulus_supported": False}
  69. identification = {**profile_common, "profile_id": "6400-identification", "stimulus_supported": True}
  70. imported_sha = hashlib.sha256(raw).hexdigest()
  71. return {
  72. ROOT / "contracts/6400/host-contract.json": raw,
  73. ROOT / "contracts/6400/SHA256SUMS": f"{imported_sha} host-contract.json\n".encode(),
  74. ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
  75. ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
  76. ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import * # noqa: F401,F403\n",
  77. ROOT / "profiles/6400-control/profile.json": json_bytes(production),
  78. ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
  79. }
  80. def main() -> int:
  81. parser = argparse.ArgumentParser()
  82. parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
  83. parser.add_argument("--check", action="store_true")
  84. args = parser.parse_args()
  85. expected = outputs(args.source)
  86. drift = []
  87. for path, content in expected.items():
  88. if args.check:
  89. if not path.exists() or path.read_bytes() != content:
  90. drift.append(str(path.relative_to(ROOT)))
  91. else:
  92. path.parent.mkdir(parents=True, exist_ok=True)
  93. if not path.exists() or path.read_bytes() != content:
  94. path.write_bytes(content)
  95. if drift:
  96. print("generated drift: " + ", ".join(drift), file=sys.stderr)
  97. return 1
  98. print(f"PASS: {len(expected)} imported files")
  99. return 0
  100. if __name__ == "__main__":
  101. sys.exit(main())