| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396 |
- #!/usr/bin/env python3
- """Generate the Prod2U Host device profile from the active generated contract.
- Reads the current working-tree host-contract.json and golden-vectors.json so the
- installed profile cannot drift from a hand-copied constant table. The output is
- a schema-validated JSON document plus a SHA-256 of the source contract.
- """
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import sys
- from pathlib import Path
- SCHEMA_ID = "hth-device-profile-v1"
- PROFILE_REVISION = "1"
- API_VERSION = "hth.api.v1"
- def _sha256_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
- def _unique_aliases(*names: str) -> list[str]:
- out: list[str] = []
- seen: set[str] = set()
- for name in names:
- if not name or name in seen:
- continue
- seen.add(name)
- out.append(name)
- return out
- def _load(path: Path) -> tuple[dict, bytes]:
- raw = path.read_bytes()
- return json.loads(raw.decode("utf-8")), raw
- def build_profile(contract: dict, golden: dict, contract_raw: bytes, golden_raw: bytes) -> dict:
- proto = contract["protocol"]
- crc = proto["crc"]
- outputs = contract["outputs"]
- temp = contract["temperature"]
- motors = contract["motors"]
- wd = contract["watchdog"]
- uart = contract["uart"]
- set_all = proto["set_all"]
- commands = proto["commands"]
- positioning = motors["positioning"]
- sensors = []
- for idx in range(int(temp["value_count"])):
- sensors.append(
- {
- "id": f"temperature.channel.{idx:02d}",
- "aliases": [],
- "display_name": f"Temperature channel {idx:02d}",
- "kind": "TEMPERATURE",
- "unit": "degC",
- "source_index": idx,
- "hood_id": "hood.0",
- "chamber_id": "",
- "dimm_id": "",
- "connector": "",
- "valid_range": {"min": 0, "max": int(temp["maximum_celsius"])},
- "resolution": 1,
- "source_timestamp": False,
- "mapping_confidence": "UNKNOWN",
- "calibration_version": str(temp["conversion"]["profile"]),
- "feedback_mode": "NONE",
- "notes": "Physical DIMM/chamber mapping is not proven by the serial contract.",
- }
- )
- for axis in motors["order"]:
- sensors.append(
- {
- "id": f"door.{axis}.estimated_close_percent",
- "aliases": [f"hood.0.chamber.1.door.{axis}.estimated_close_percent"],
- "display_name": f"Door {axis.upper()} estimated close percent",
- "kind": "ESTIMATED_POSITION",
- "unit": "percent",
- "source_index": motors["order"].index(axis),
- "hood_id": "hood.0",
- "chamber_id": "chamber.1",
- "dimm_id": "",
- "connector": motors["mapping"][axis]["step_connector"],
- "valid_range": {"min": 0, "max": 100},
- "resolution": 1,
- "source_timestamp": False,
- "mapping_confidence": "CONFIG",
- "calibration_version": "",
- "feedback_mode": "ESTIMATED_OPEN_LOOP",
- "notes": "Open-loop gated STEP estimate; endpoints may be limit-confirmed.",
- }
- )
- sensors.append(
- {
- "id": f"door.{axis}.open_limit",
- "aliases": [],
- "display_name": f"Door {axis.upper()} open limit",
- "kind": "LIMIT_SWITCH",
- "unit": "bool",
- "source_index": motors["order"].index(axis),
- "hood_id": "hood.0",
- "chamber_id": "chamber.1",
- "dimm_id": "",
- "connector": "",
- "valid_range": {"min": 0, "max": 1},
- "resolution": 1,
- "source_timestamp": False,
- "mapping_confidence": "CONFIG",
- "calibration_version": "",
- "feedback_mode": "LIMIT_SWITCH",
- "notes": "Reported in MOTOR_STATUS_DATA flags; not a raw GPIO read by Host.",
- }
- )
- sensors.append(
- {
- "id": f"door.{axis}.close_limit",
- "aliases": [],
- "display_name": f"Door {axis.upper()} close limit",
- "kind": "LIMIT_SWITCH",
- "unit": "bool",
- "source_index": motors["order"].index(axis),
- "hood_id": "hood.0",
- "chamber_id": "chamber.1",
- "dimm_id": "",
- "connector": "",
- "valid_range": {"min": 0, "max": 1},
- "resolution": 1,
- "source_timestamp": False,
- "mapping_confidence": "CONFIG",
- "calibration_version": "",
- "feedback_mode": "LIMIT_SWITCH",
- "notes": "Reported in MOTOR_STATUS_DATA flags; not a raw GPIO read by Host.",
- }
- )
- actuators = []
- for ch in outputs["fan_channels"]:
- chamber = int(ch["index"]) + 1
- actuators.append(
- {
- "id": f"fan.chamber.{chamber}",
- "aliases": _unique_aliases(f"fan{ch['index'] + 1}", ch.get("name") or ""),
- "display_name": f"Chamber {chamber} fan duty",
- "kind": "FAN",
- "unit": "percent",
- "command_range": {"min": int(set_all["duty_min"]), "max": int(set_all["duty_max"])},
- "resolution": 1,
- "control_mode": "CONTINUOUS_DUTY",
- "feedback_mode": "NONE",
- "idempotent": True,
- "one_shot": False,
- "safety_default": int(wd["target"]["fan"]),
- "max_slew_per_second": 100,
- "actual_feedback": False,
- "hood_id": "hood.0",
- "chamber_id": f"chamber.{chamber}",
- "connector": ch["connector"],
- "set_all_offset": int(set_all["fan_offset"]) + int(ch["index"]),
- "notes": "No RPM readback. FPGA output polarity is active-low.",
- }
- )
- for pair in outputs["chamber_ptc_pairs"]:
- chamber = int(pair["chamber"])
- actuators.append(
- {
- "id": f"ptc.chamber.{chamber}",
- "aliases": [f"heater.chamber.{chamber}"],
- "display_name": f"Chamber {chamber} PTC duty",
- "kind": "HEATER",
- "unit": "percent",
- "command_range": {"min": int(set_all["duty_min"]), "max": int(set_all["duty_max"])},
- "resolution": 1,
- "control_mode": "CONTINUOUS_DUTY",
- "feedback_mode": "NONE",
- "idempotent": True,
- "one_shot": False,
- "safety_default": int(wd["target"]["ptc"]),
- "max_slew_per_second": 100,
- "actual_feedback": False,
- "hood_id": "hood.0",
- "chamber_id": f"chamber.{chamber}",
- "connector": "",
- "set_all_offset": int(set_all["chamber_ptc_offset"]) + (chamber - 1),
- "physical_ptc_indices": pair["ptc_indices"],
- "notes": "One chamber command is duplicated onto two physical PTC PWM outputs.",
- }
- )
- door_offsets = {"z": int(set_all["z_door_offset"]), "x": int(set_all["exhaust_x_offset"]), "y": int(set_all["exhaust_y_offset"])}
- for axis in motors["order"]:
- actuators.append(
- {
- "id": f"door.{axis}.close_percent",
- "aliases": [f"hood.0.chamber.1.door.{axis}"],
- "display_name": f"Door {axis.upper()} close percent",
- "kind": "DOOR",
- "unit": "percent",
- "command_range": {
- "min": int(set_all["door_percent_min"]),
- "max": int(set_all["door_percent_max"]),
- },
- "resolution": 1,
- "control_mode": "PERCENT_CLOSE",
- "feedback_mode": "ESTIMATED_OPEN_LOOP",
- "idempotent": True,
- "one_shot": False,
- "safety_default": 0,
- "max_slew_per_second": 100,
- "actual_feedback": False,
- "hood_id": "hood.0",
- "chamber_id": "chamber.1",
- "connector": motors["mapping"][axis]["step_connector"],
- "set_all_offset": door_offsets[axis],
- "notes": (
- "0=full open, 100=full close. Value 0 is NOT a jog heartbeat no-op. "
- "Same target is idempotent; different target is latest-wins. "
- "Not auto-retried when dispatch outcome is unknown."
- ),
- }
- )
- return {
- "schema": SCHEMA_ID,
- "profile_id": contract["profile"],
- "profile_revision": PROFILE_REVISION,
- "project_id": contract["project_id"],
- "api_version": API_VERSION,
- "source_contract_schema": contract.get("schema", ""),
- "source_contract_sha256": _sha256_bytes(contract_raw),
- "source_golden_sha256": _sha256_bytes(golden_raw),
- "uart": {
- "baud": int(uart["baud"]),
- "data_bits": int(uart["data_bits"]),
- "parity": uart["parity"],
- "stop_bits": int(uart["stop_bits"]),
- "flow_control": uart["flow_control"],
- "inter_byte_timeout_ms": int(uart["inter_byte_timeout_ms"]),
- },
- "protocol": {
- "header_hex": proto["header_hex"],
- "crc": {
- "name": crc["name"],
- "polynomial": int(crc["polynomial"]),
- "initial": int(crc["initial"]),
- "reflect_input": bool(crc["reflect_input"]),
- "reflect_output": bool(crc["reflect_output"]),
- "xor_output": int(crc["xor_output"]),
- "coverage": crc["coverage"],
- "wire_order": crc["wire_order"],
- },
- "commands": {
- "set_all": int(commands["set_all"]),
- "get_temperature": int(commands["get_temperature"]),
- "get_motor_status": int(commands["get_motor_status"]),
- "temperature_data": int(commands["temperature_data"]),
- "motor_status_data": int(commands["motor_status_data"]),
- },
- "set_all": {
- "payload_length": int(set_all["payload_length"]),
- "fan_offset": int(set_all["fan_offset"]),
- "chamber_ptc_offset": int(set_all["chamber_ptc_offset"]),
- "chamber_ptc_count": int(set_all["chamber_ptc_count"]),
- "z_door_offset": int(set_all["z_door_offset"]),
- "x_door_offset": int(set_all["exhaust_x_offset"]),
- "y_door_offset": int(set_all["exhaust_y_offset"]),
- "legacy_payload_length_rejected": int(set_all["legacy_payload_length_rejected"]),
- "duty_min": int(set_all["duty_min"]),
- "duty_max": int(set_all["duty_max"]),
- "door_percent_min": int(set_all["door_percent_min"]),
- "door_percent_max": int(set_all["door_percent_max"]),
- "response": set_all["response"],
- "idempotent_same_target": bool(positioning.get("idempotent_same_target", True)),
- "retry_policy": "never_when_outcome_unknown",
- },
- "get_temperature": {"payload_length": 0, "response_payload_length": int(temp["value_count"])},
- "get_motor_status": {
- "payload_length": 0,
- "response_payload_length": int(proto["motor_status_data"]["payload_length"]),
- },
- "ack": False,
- "status_query": True,
- "max_payload_length": 64,
- },
- "timeouts": {
- "frame_inter_byte_ms": int(uart["inter_byte_timeout_ms"]),
- "host_get_response_ms": 5000,
- "temperature_scan_busy_ms": 5000,
- },
- "watchdog": {
- "timeout_seconds": int(wd["timeout_seconds"]),
- "fed_by": "valid_set_all_commit_after_startup_complete",
- "get_feeds_watchdog": False,
- "enable_after_startup_complete": bool(wd["enable_after_startup_complete"]),
- "target": {"ptc": int(wd["target"]["ptc"]), "fan": int(wd["target"]["fan"])},
- "heartbeat_repeats_door_percent": True,
- "heartbeat_must_not_rewrite_doors_to_zero": True,
- "host_heartbeat_period_ms": 5000,
- },
- "startup": {
- "get_temperature_dropped": True,
- "get_motor_status_allowed": True,
- "set_all_updates_thermal_only": True,
- "door_percent_ignored": True,
- "readiness_probe": "motor_status_startup_complete",
- },
- "temperature": {
- "value_count": int(temp["value_count"]),
- "invalid_value": int(temp["invalid_value"]),
- "maximum_celsius": int(temp["maximum_celsius"]),
- "unit": "degC",
- "source_timestamp": False,
- "sequential_scan": True,
- },
- "motors": {
- "order": list(motors["order"]),
- "control_mode": "PERCENT_CLOSE",
- "position_feedback": "ESTIMATED_OPEN_LOOP",
- "busy_readable": True,
- "percent_min": int(positioning["percent_min"]),
- "percent_max": int(positioning["percent_max"]),
- "open_endpoint_percent": int(positioning["open_endpoint_percent"]),
- "close_endpoint_percent": int(positioning["close_endpoint_percent"]),
- },
- "topology": {
- "hood_count": 1,
- "chamber_count": 4,
- "door_chamber": 1,
- },
- "safety": {
- "fan": int(wd["target"]["fan"]),
- "ptc": int(wd["target"]["ptc"]),
- "door_close_percent": 0,
- "notes": "User-space safe doors default to full open (0). This is a thermal/mechanical policy, not a jog no-op.",
- },
- "sensors": sensors,
- "actuators": actuators,
- "golden_vectors": {
- key: value
- for key, value in golden.items()
- if key != "notes"
- },
- "golden_notes": golden.get("notes", {}),
- "honesty": {
- "firmware_version": "NOT_SUPPORTED",
- "fan_rpm": "NOT_SUPPORTED",
- "ptc_actual_power": "NOT_SUPPORTED",
- "encoder_position": "NOT_SUPPORTED",
- "ack": False,
- "dimm_temperature_map": "UNKNOWN",
- "hardware_validation": "NOT_RUN",
- },
- }
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1])
- parser.add_argument("--out", type=Path, default=None)
- args = parser.parse_args()
- contract_path = args.repo_root / "src" / "generated" / "host-contract.json"
- golden_path = args.repo_root / "src" / "generated" / "golden-vectors.json"
- if not contract_path.is_file() or not golden_path.is_file():
- # The independent hth-platform repository preserves the Legacy inputs
- # as immutable, hash-checked split evidence instead of reaching back
- # into the CPLD repository or pretending the old directory still owns
- # Host production code.
- evidence = Path(__file__).resolve().parents[1] / "contracts" / "evidence"
- contract_path = evidence / "host-contract.json"
- golden_path = evidence / "golden-vectors.json"
- if not contract_path.is_file() or not golden_path.is_file():
- print(f"missing contract files under {args.repo_root}", file=sys.stderr)
- return 2
- contract, contract_raw = _load(contract_path)
- golden, golden_raw = _load(golden_path)
- profile = build_profile(contract, golden, contract_raw, golden_raw)
- out = args.out or (args.repo_root / "host" / "profiles" / "prod2u-door-temp" / "profile.json")
- out.parent.mkdir(parents=True, exist_ok=True)
- text = json.dumps(profile, indent=2, sort_keys=True) + "\n"
- out.write_text(text, encoding="utf-8")
- sidecar = out.with_suffix(".sha256")
- sidecar.write_text(_sha256_bytes(text.encode("utf-8")) + " " + out.name + "\n", encoding="utf-8")
- print(out)
- print("contract_sha256", profile["source_contract_sha256"])
- print("profile_sha256", _sha256_bytes(text.encode("utf-8")))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|