gen_profile.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #!/usr/bin/env python3
  2. """Generate the Prod2U Host device profile from the active generated contract.
  3. Reads the current working-tree host-contract.json and golden-vectors.json so the
  4. installed profile cannot drift from a hand-copied constant table. The output is
  5. a schema-validated JSON document plus a SHA-256 of the source contract.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import hashlib
  10. import json
  11. import sys
  12. from pathlib import Path
  13. SCHEMA_ID = "hth-device-profile-v1"
  14. PROFILE_REVISION = "1"
  15. API_VERSION = "hth.api.v1"
  16. def _sha256_bytes(data: bytes) -> str:
  17. return hashlib.sha256(data).hexdigest()
  18. def _unique_aliases(*names: str) -> list[str]:
  19. out: list[str] = []
  20. seen: set[str] = set()
  21. for name in names:
  22. if not name or name in seen:
  23. continue
  24. seen.add(name)
  25. out.append(name)
  26. return out
  27. def _load(path: Path) -> tuple[dict, bytes]:
  28. raw = path.read_bytes()
  29. return json.loads(raw.decode("utf-8")), raw
  30. def build_profile(contract: dict, golden: dict, contract_raw: bytes, golden_raw: bytes) -> dict:
  31. proto = contract["protocol"]
  32. crc = proto["crc"]
  33. outputs = contract["outputs"]
  34. temp = contract["temperature"]
  35. motors = contract["motors"]
  36. wd = contract["watchdog"]
  37. uart = contract["uart"]
  38. set_all = proto["set_all"]
  39. commands = proto["commands"]
  40. positioning = motors["positioning"]
  41. sensors = []
  42. for idx in range(int(temp["value_count"])):
  43. sensors.append(
  44. {
  45. "id": f"temperature.channel.{idx:02d}",
  46. "aliases": [],
  47. "display_name": f"Temperature channel {idx:02d}",
  48. "kind": "TEMPERATURE",
  49. "unit": "degC",
  50. "source_index": idx,
  51. "hood_id": "hood.0",
  52. "chamber_id": "",
  53. "dimm_id": "",
  54. "connector": "",
  55. "valid_range": {"min": 0, "max": int(temp["maximum_celsius"])},
  56. "resolution": 1,
  57. "source_timestamp": False,
  58. "mapping_confidence": "UNKNOWN",
  59. "calibration_version": str(temp["conversion"]["profile"]),
  60. "feedback_mode": "NONE",
  61. "notes": "Physical DIMM/chamber mapping is not proven by the serial contract.",
  62. }
  63. )
  64. for axis in motors["order"]:
  65. sensors.append(
  66. {
  67. "id": f"door.{axis}.estimated_close_percent",
  68. "aliases": [f"hood.0.chamber.1.door.{axis}.estimated_close_percent"],
  69. "display_name": f"Door {axis.upper()} estimated close percent",
  70. "kind": "ESTIMATED_POSITION",
  71. "unit": "percent",
  72. "source_index": motors["order"].index(axis),
  73. "hood_id": "hood.0",
  74. "chamber_id": "chamber.1",
  75. "dimm_id": "",
  76. "connector": motors["mapping"][axis]["step_connector"],
  77. "valid_range": {"min": 0, "max": 100},
  78. "resolution": 1,
  79. "source_timestamp": False,
  80. "mapping_confidence": "CONFIG",
  81. "calibration_version": "",
  82. "feedback_mode": "ESTIMATED_OPEN_LOOP",
  83. "notes": "Open-loop gated STEP estimate; endpoints may be limit-confirmed.",
  84. }
  85. )
  86. sensors.append(
  87. {
  88. "id": f"door.{axis}.open_limit",
  89. "aliases": [],
  90. "display_name": f"Door {axis.upper()} open limit",
  91. "kind": "LIMIT_SWITCH",
  92. "unit": "bool",
  93. "source_index": motors["order"].index(axis),
  94. "hood_id": "hood.0",
  95. "chamber_id": "chamber.1",
  96. "dimm_id": "",
  97. "connector": "",
  98. "valid_range": {"min": 0, "max": 1},
  99. "resolution": 1,
  100. "source_timestamp": False,
  101. "mapping_confidence": "CONFIG",
  102. "calibration_version": "",
  103. "feedback_mode": "LIMIT_SWITCH",
  104. "notes": "Reported in MOTOR_STATUS_DATA flags; not a raw GPIO read by Host.",
  105. }
  106. )
  107. sensors.append(
  108. {
  109. "id": f"door.{axis}.close_limit",
  110. "aliases": [],
  111. "display_name": f"Door {axis.upper()} close limit",
  112. "kind": "LIMIT_SWITCH",
  113. "unit": "bool",
  114. "source_index": motors["order"].index(axis),
  115. "hood_id": "hood.0",
  116. "chamber_id": "chamber.1",
  117. "dimm_id": "",
  118. "connector": "",
  119. "valid_range": {"min": 0, "max": 1},
  120. "resolution": 1,
  121. "source_timestamp": False,
  122. "mapping_confidence": "CONFIG",
  123. "calibration_version": "",
  124. "feedback_mode": "LIMIT_SWITCH",
  125. "notes": "Reported in MOTOR_STATUS_DATA flags; not a raw GPIO read by Host.",
  126. }
  127. )
  128. actuators = []
  129. for ch in outputs["fan_channels"]:
  130. chamber = int(ch["index"]) + 1
  131. actuators.append(
  132. {
  133. "id": f"fan.chamber.{chamber}",
  134. "aliases": _unique_aliases(f"fan{ch['index'] + 1}", ch.get("name") or ""),
  135. "display_name": f"Chamber {chamber} fan duty",
  136. "kind": "FAN",
  137. "unit": "percent",
  138. "command_range": {"min": int(set_all["duty_min"]), "max": int(set_all["duty_max"])},
  139. "resolution": 1,
  140. "control_mode": "CONTINUOUS_DUTY",
  141. "feedback_mode": "NONE",
  142. "idempotent": True,
  143. "one_shot": False,
  144. "safety_default": int(wd["target"]["fan"]),
  145. "max_slew_per_second": 100,
  146. "actual_feedback": False,
  147. "hood_id": "hood.0",
  148. "chamber_id": f"chamber.{chamber}",
  149. "connector": ch["connector"],
  150. "set_all_offset": int(set_all["fan_offset"]) + int(ch["index"]),
  151. "notes": "No RPM readback. FPGA output polarity is active-low.",
  152. }
  153. )
  154. for pair in outputs["chamber_ptc_pairs"]:
  155. chamber = int(pair["chamber"])
  156. actuators.append(
  157. {
  158. "id": f"ptc.chamber.{chamber}",
  159. "aliases": [f"heater.chamber.{chamber}"],
  160. "display_name": f"Chamber {chamber} PTC duty",
  161. "kind": "HEATER",
  162. "unit": "percent",
  163. "command_range": {"min": int(set_all["duty_min"]), "max": int(set_all["duty_max"])},
  164. "resolution": 1,
  165. "control_mode": "CONTINUOUS_DUTY",
  166. "feedback_mode": "NONE",
  167. "idempotent": True,
  168. "one_shot": False,
  169. "safety_default": int(wd["target"]["ptc"]),
  170. "max_slew_per_second": 100,
  171. "actual_feedback": False,
  172. "hood_id": "hood.0",
  173. "chamber_id": f"chamber.{chamber}",
  174. "connector": "",
  175. "set_all_offset": int(set_all["chamber_ptc_offset"]) + (chamber - 1),
  176. "physical_ptc_indices": pair["ptc_indices"],
  177. "notes": "One chamber command is duplicated onto two physical PTC PWM outputs.",
  178. }
  179. )
  180. door_offsets = {"z": int(set_all["z_door_offset"]), "x": int(set_all["exhaust_x_offset"]), "y": int(set_all["exhaust_y_offset"])}
  181. for axis in motors["order"]:
  182. actuators.append(
  183. {
  184. "id": f"door.{axis}.close_percent",
  185. "aliases": [f"hood.0.chamber.1.door.{axis}"],
  186. "display_name": f"Door {axis.upper()} close percent",
  187. "kind": "DOOR",
  188. "unit": "percent",
  189. "command_range": {
  190. "min": int(set_all["door_percent_min"]),
  191. "max": int(set_all["door_percent_max"]),
  192. },
  193. "resolution": 1,
  194. "control_mode": "PERCENT_CLOSE",
  195. "feedback_mode": "ESTIMATED_OPEN_LOOP",
  196. "idempotent": True,
  197. "one_shot": False,
  198. "safety_default": 0,
  199. "max_slew_per_second": 100,
  200. "actual_feedback": False,
  201. "hood_id": "hood.0",
  202. "chamber_id": "chamber.1",
  203. "connector": motors["mapping"][axis]["step_connector"],
  204. "set_all_offset": door_offsets[axis],
  205. "notes": (
  206. "0=full open, 100=full close. Value 0 is NOT a jog heartbeat no-op. "
  207. "Same target is idempotent; different target is latest-wins. "
  208. "Not auto-retried when dispatch outcome is unknown."
  209. ),
  210. }
  211. )
  212. return {
  213. "schema": SCHEMA_ID,
  214. "profile_id": contract["profile"],
  215. "profile_revision": PROFILE_REVISION,
  216. "project_id": contract["project_id"],
  217. "api_version": API_VERSION,
  218. "source_contract_schema": contract.get("schema", ""),
  219. "source_contract_sha256": _sha256_bytes(contract_raw),
  220. "source_golden_sha256": _sha256_bytes(golden_raw),
  221. "uart": {
  222. "baud": int(uart["baud"]),
  223. "data_bits": int(uart["data_bits"]),
  224. "parity": uart["parity"],
  225. "stop_bits": int(uart["stop_bits"]),
  226. "flow_control": uart["flow_control"],
  227. "inter_byte_timeout_ms": int(uart["inter_byte_timeout_ms"]),
  228. },
  229. "protocol": {
  230. "header_hex": proto["header_hex"],
  231. "crc": {
  232. "name": crc["name"],
  233. "polynomial": int(crc["polynomial"]),
  234. "initial": int(crc["initial"]),
  235. "reflect_input": bool(crc["reflect_input"]),
  236. "reflect_output": bool(crc["reflect_output"]),
  237. "xor_output": int(crc["xor_output"]),
  238. "coverage": crc["coverage"],
  239. "wire_order": crc["wire_order"],
  240. },
  241. "commands": {
  242. "set_all": int(commands["set_all"]),
  243. "get_temperature": int(commands["get_temperature"]),
  244. "get_motor_status": int(commands["get_motor_status"]),
  245. "temperature_data": int(commands["temperature_data"]),
  246. "motor_status_data": int(commands["motor_status_data"]),
  247. },
  248. "set_all": {
  249. "payload_length": int(set_all["payload_length"]),
  250. "fan_offset": int(set_all["fan_offset"]),
  251. "chamber_ptc_offset": int(set_all["chamber_ptc_offset"]),
  252. "chamber_ptc_count": int(set_all["chamber_ptc_count"]),
  253. "z_door_offset": int(set_all["z_door_offset"]),
  254. "x_door_offset": int(set_all["exhaust_x_offset"]),
  255. "y_door_offset": int(set_all["exhaust_y_offset"]),
  256. "legacy_payload_length_rejected": int(set_all["legacy_payload_length_rejected"]),
  257. "duty_min": int(set_all["duty_min"]),
  258. "duty_max": int(set_all["duty_max"]),
  259. "door_percent_min": int(set_all["door_percent_min"]),
  260. "door_percent_max": int(set_all["door_percent_max"]),
  261. "response": set_all["response"],
  262. "idempotent_same_target": bool(positioning.get("idempotent_same_target", True)),
  263. "retry_policy": "never_when_outcome_unknown",
  264. },
  265. "get_temperature": {"payload_length": 0, "response_payload_length": int(temp["value_count"])},
  266. "get_motor_status": {
  267. "payload_length": 0,
  268. "response_payload_length": int(proto["motor_status_data"]["payload_length"]),
  269. },
  270. "ack": False,
  271. "status_query": True,
  272. "max_payload_length": 64,
  273. },
  274. "timeouts": {
  275. "frame_inter_byte_ms": int(uart["inter_byte_timeout_ms"]),
  276. "host_get_response_ms": 5000,
  277. "temperature_scan_busy_ms": 5000,
  278. },
  279. "watchdog": {
  280. "timeout_seconds": int(wd["timeout_seconds"]),
  281. "fed_by": "valid_set_all_commit_after_startup_complete",
  282. "get_feeds_watchdog": False,
  283. "enable_after_startup_complete": bool(wd["enable_after_startup_complete"]),
  284. "target": {"ptc": int(wd["target"]["ptc"]), "fan": int(wd["target"]["fan"])},
  285. "heartbeat_repeats_door_percent": True,
  286. "heartbeat_must_not_rewrite_doors_to_zero": True,
  287. "host_heartbeat_period_ms": 5000,
  288. },
  289. "startup": {
  290. "get_temperature_dropped": True,
  291. "get_motor_status_allowed": True,
  292. "set_all_updates_thermal_only": True,
  293. "door_percent_ignored": True,
  294. "readiness_probe": "motor_status_startup_complete",
  295. },
  296. "temperature": {
  297. "value_count": int(temp["value_count"]),
  298. "invalid_value": int(temp["invalid_value"]),
  299. "maximum_celsius": int(temp["maximum_celsius"]),
  300. "unit": "degC",
  301. "source_timestamp": False,
  302. "sequential_scan": True,
  303. },
  304. "motors": {
  305. "order": list(motors["order"]),
  306. "control_mode": "PERCENT_CLOSE",
  307. "position_feedback": "ESTIMATED_OPEN_LOOP",
  308. "busy_readable": True,
  309. "percent_min": int(positioning["percent_min"]),
  310. "percent_max": int(positioning["percent_max"]),
  311. "open_endpoint_percent": int(positioning["open_endpoint_percent"]),
  312. "close_endpoint_percent": int(positioning["close_endpoint_percent"]),
  313. },
  314. "topology": {
  315. "hood_count": 1,
  316. "chamber_count": 4,
  317. "door_chamber": 1,
  318. },
  319. "safety": {
  320. "fan": int(wd["target"]["fan"]),
  321. "ptc": int(wd["target"]["ptc"]),
  322. "door_close_percent": 0,
  323. "notes": "User-space safe doors default to full open (0). This is a thermal/mechanical policy, not a jog no-op.",
  324. },
  325. "sensors": sensors,
  326. "actuators": actuators,
  327. "golden_vectors": {
  328. key: value
  329. for key, value in golden.items()
  330. if key != "notes"
  331. },
  332. "golden_notes": golden.get("notes", {}),
  333. "honesty": {
  334. "firmware_version": "NOT_SUPPORTED",
  335. "fan_rpm": "NOT_SUPPORTED",
  336. "ptc_actual_power": "NOT_SUPPORTED",
  337. "encoder_position": "NOT_SUPPORTED",
  338. "ack": False,
  339. "dimm_temperature_map": "UNKNOWN",
  340. "hardware_validation": "NOT_RUN",
  341. },
  342. }
  343. def main() -> int:
  344. parser = argparse.ArgumentParser()
  345. parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1])
  346. parser.add_argument("--out", type=Path, default=None)
  347. args = parser.parse_args()
  348. contract_path = args.repo_root / "src" / "generated" / "host-contract.json"
  349. golden_path = args.repo_root / "src" / "generated" / "golden-vectors.json"
  350. if not contract_path.is_file() or not golden_path.is_file():
  351. # The independent hth-platform repository preserves the Legacy inputs
  352. # as immutable, hash-checked split evidence instead of reaching back
  353. # into the CPLD repository or pretending the old directory still owns
  354. # Host production code.
  355. evidence = Path(__file__).resolve().parents[1] / "contracts" / "evidence"
  356. contract_path = evidence / "host-contract.json"
  357. golden_path = evidence / "golden-vectors.json"
  358. if not contract_path.is_file() or not golden_path.is_file():
  359. print(f"missing contract files under {args.repo_root}", file=sys.stderr)
  360. return 2
  361. contract, contract_raw = _load(contract_path)
  362. golden, golden_raw = _load(golden_path)
  363. profile = build_profile(contract, golden, contract_raw, golden_raw)
  364. out = args.out or (args.repo_root / "host" / "profiles" / "prod2u-door-temp" / "profile.json")
  365. out.parent.mkdir(parents=True, exist_ok=True)
  366. text = json.dumps(profile, indent=2, sort_keys=True) + "\n"
  367. out.write_text(text, encoding="utf-8")
  368. sidecar = out.with_suffix(".sha256")
  369. sidecar.write_text(_sha256_bytes(text.encode("utf-8")) + " " + out.name + "\n", encoding="utf-8")
  370. print(out)
  371. print("contract_sha256", profile["source_contract_sha256"])
  372. print("profile_sha256", _sha256_bytes(text.encode("utf-8")))
  373. return 0
  374. if __name__ == "__main__":
  375. raise SystemExit(main())