#!/usr/bin/env python3 """Validate a project configuration and emit deterministic contract artifacts.""" from __future__ import annotations import argparse import json import re from pathlib import Path from typing import Any, Mapping from jsonschema import Draft202012Validator PROFILE = "prod2u-normal-multiproject-115200-v1" PROFILE_6400 = "thermal-24ptc-8fan-v1" SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schemas" / "project.schema.json" SOURCE_CLOSURE_PATH = Path(__file__).resolve().parents[1] / "config" / "source_closure.json" CAL_COUNTER_WIDTH_BITS = 13 CAL_COUNTER_MAX = (1 << CAL_COUNTER_WIDTH_BITS) - 1 FORBIDDEN_MOTOR_KEYS = { "fixed_steps", "busy_wait_ms", "command_values", "heartbeat_value", } FORBIDDEN_STARTUP_KEYS = { "backoff_step_count", "close_step_count", "direction_value", "direction_meaning", } _TOP_LEVEL_KEYS = { "project_id", "profile", "display_name", "device", "uart", "outputs", "doors", "motors", "limits", "temperature", "pins", "resource_policy", "protocol", "timeouts", "watchdog", } def _require(condition: bool, message: str) -> None: if not condition: raise ValueError(message) def _load_source_closure() -> tuple[str, ...]: payload = json.loads(SOURCE_CLOSURE_PATH.read_text(encoding="utf-8")) _require(isinstance(payload, Mapping), "source closure root must be an object") _require(payload.get("schema") == "prod2u-source-closure-v1", "source closure schema mismatch") _require(payload.get("project_id") == "prod2u-door-temp", "source closure project_id mismatch") sources = payload.get("sources") _require(isinstance(sources, list) and sources, "source closure must contain a non-empty sources list") normalized = [] for value in sources: _require(isinstance(value, str) and value, "source closure entry must be a non-empty string") parts = Path(value).parts _require(".." not in parts and not Path(value).is_absolute(), "source closure entry must be a relative safe path") normalized.append(value) _require(len(normalized) == len(set(normalized)), "source closure contains duplicate paths") missing = [path for path in normalized if not (SOURCE_CLOSURE_PATH.parents[1] / path).is_file()] _require(not missing, f"source closure references missing files: {missing}") return tuple(normalized) ACTIVE_SOURCE_PATHS = _load_source_closure() def _object(value: Any, name: str) -> Mapping[str, Any]: _require(isinstance(value, dict), f"{name} must be an object") return value def _keys(value: Mapping[str, Any], expected: set[str], name: str) -> None: _require(set(value) == expected, f"{name} keys mismatch") def _integer(value: Any, name: str, *, minimum: int | None = None, maximum: int | None = None) -> None: _require(isinstance(value, int) and not isinstance(value, bool), f"{name} must be an integer") if minimum is not None: _require(value >= minimum, f"{name} is below the minimum") if maximum is not None: _require(value <= maximum, f"{name} is above the maximum") def _number(value: Any, name: str) -> None: _require(isinstance(value, (int, float)) and not isinstance(value, bool), f"{name} must be numeric") def _list(value: Any, name: str, length: int | None = None) -> list[Any]: _require(isinstance(value, list), f"{name} must be an array") if length is not None: _require(len(value) == length, f"{name} must contain {length} items") return value def _axis_mask_literal(values: list[Any], axis_count: int) -> str: """Build AXIS_COUNT'b... with bit0=X (LSB / rightmost), index0=X,1=Y,2=Z.""" _require(len(values) == axis_count, "axis mask length mismatch") bits_lsb_first: list[str] = [] for value in values: if isinstance(value, bool): bits_lsb_first.append("1" if value else "0") else: bits_lsb_first.append("1" if int(value) else "0") return f"{axis_count}'b" + "".join(reversed(bits_lsb_first)) def _validate_channel(channel: Any, index: int, kind: str) -> None: item = _object(channel, f"{kind}_channels[{index}]") _keys(item, {"index", "name", "signal", "board_signal", "ball", "connector", "connector_pin", "polarity"}, f"{kind}_channels[{index}]") _require(item["index"] == index, f"{kind} channel index mismatch at {index}") _require(item["name"] == f"{kind}{index + 1}", f"{kind} channel name mismatch at {index}") _require(item["signal"] == f"{kind}_pwm_out[{index}]", f"{kind} channel signal mismatch at {index}") _require(isinstance(item["board_signal"], str) and item["board_signal"], f"invalid {kind} board signal at {index}") _require(item["polarity"] in {"active_high", "active_low"}, f"invalid {kind} polarity at {index}") _require(re.fullmatch(r"[A-Z][0-9]+", str(item["ball"])) is not None, f"invalid {kind} ball at {index}") _require(re.fullmatch(r"CON[0-9]+", str(item["connector"])) is not None, f"invalid {kind} connector at {index}") _integer(item["connector_pin"], f"{kind} channel connector pin", minimum=1) def _validate_project(payload: Mapping[str, Any]) -> None: _keys(payload, _TOP_LEVEL_KEYS, "project") _require(re.fullmatch(r"[a-z0-9-]+", str(payload["project_id"])) is not None, "invalid project_id") _require(isinstance(payload["profile"], str) and payload["profile"], "invalid project profile") _require(isinstance(payload["display_name"], str) and payload["display_name"], "invalid display_name") device = _object(payload["device"], "device") _keys(device, {"family", "part", "clock_hz", "clock_ball"}, "device") _require(isinstance(device["family"], str) and device["family"], "invalid device family") _require(isinstance(device["part"], str) and device["part"], "invalid device part") _integer(device["clock_hz"], "device.clock_hz", minimum=1) _require(re.fullmatch(r"[A-Z][0-9]+", str(device["clock_ball"])) is not None, "invalid clock ball") uart = _object(payload["uart"], "uart") _keys(uart, {"baud", "data_bits", "parity", "stop_bits", "flow_control", "clks_per_bit", "inter_byte_timeout_ms", "rx_ball", "tx_ball"}, "uart") _integer(uart["baud"], "uart.baud", minimum=1) _integer(uart["data_bits"], "uart.data_bits", minimum=1) _integer(uart["stop_bits"], "uart.stop_bits", minimum=1) _integer(uart["clks_per_bit"], "uart.clks_per_bit", minimum=1) _require(uart["parity"] in {"N", "E", "O"}, "invalid UART parity") _require(isinstance(uart["flow_control"], str), "invalid UART flow control") _integer(uart["inter_byte_timeout_ms"], "uart.inter_byte_timeout_ms", minimum=1) outputs = _object(payload["outputs"], "outputs") _keys( outputs, { "ptc_count", "fan_count", "chamber_ptc_count", "chamber_ptc_pairs", "ptc_channels", "fan_channels", "pwm_bits", "pwm_internal_width", "pwm_max_duty", "pwm_phase_count", "pwm_slot_clks", "pwm_frequency_hz", "pwm_actual_frequency_hz", "ptc_polarity", "fan_polarity", "ptc_default", "fan_default", "fan_connector_active_level", "fan_board_inverts", "boot_targets", }, "outputs", ) _integer(outputs["ptc_count"], "outputs.ptc_count", minimum=1) _integer(outputs["fan_count"], "outputs.fan_count", minimum=1) _require(outputs["ptc_count"] == len(outputs["ptc_channels"]), "PTC count/list mismatch") _require(outputs["fan_count"] == len(outputs["fan_channels"]), "FAN count/list mismatch") _integer(outputs["chamber_ptc_count"], "outputs.chamber_ptc_count", minimum=1) chamber_pairs = _list(outputs["chamber_ptc_pairs"], "outputs.chamber_ptc_pairs", outputs["chamber_ptc_count"]) for index, pair in enumerate(chamber_pairs): item = _object(pair, f"outputs.chamber_ptc_pairs[{index}]") _keys(item, {"chamber", "ptc_indices"}, f"outputs.chamber_ptc_pairs[{index}]") _require(item["chamber"] == index + 1, "chamber index mismatch in chamber_ptc_pairs") indices = _list(item["ptc_indices"], f"outputs.chamber_ptc_pairs[{index}].ptc_indices", 2) _require(all(isinstance(value, int) and 0 <= value < outputs["ptc_count"] for value in indices), "invalid PTC pair indices") _require(indices[0] + 1 == indices[1], "PTC pair indices must be adjacent") for index, channel in enumerate(outputs["ptc_channels"]): _validate_channel(channel, index, "ptc") for index, channel in enumerate(outputs["fan_channels"]): _validate_channel(channel, index, "fan") _integer(outputs["pwm_bits"], "outputs.pwm_bits", minimum=1) _integer(outputs["pwm_internal_width"], "outputs.pwm_internal_width", minimum=1) _integer(outputs["pwm_max_duty"], "outputs.pwm_max_duty", minimum=0) _require(outputs["pwm_max_duty"] < (1 << outputs["pwm_bits"]), "PWM maximum exceeds protocol width") _integer(outputs["pwm_phase_count"], "outputs.pwm_phase_count", minimum=1) _integer(outputs["pwm_slot_clks"], "outputs.pwm_slot_clks", minimum=1) _number(outputs["pwm_frequency_hz"], "outputs.pwm_frequency_hz") _number(outputs["pwm_actual_frequency_hz"], "outputs.pwm_actual_frequency_hz") _require(outputs["ptc_polarity"] == "active_high" and outputs["fan_polarity"] == "active_low", "PWM polarity mismatch") _require(0 <= outputs["ptc_default"] <= outputs["pwm_max_duty"], "invalid PTC boot target") _require(0 <= outputs["fan_default"] <= outputs["pwm_max_duty"], "invalid FAN boot target") _require(outputs["fan_connector_active_level"] == "high" and outputs["fan_board_inverts"] is True, "FAN board metadata mismatch") boot_targets = _object(outputs["boot_targets"], "outputs.boot_targets") _keys(boot_targets, {"ptc", "fan"}, "outputs.boot_targets") _require(boot_targets == {"ptc": 0, "fan": 10}, "boot target mapping mismatch") doors = _object(payload["doors"], "doors") _keys(doors, {"scope", "chamber_controlled", "door_axes"}, "doors") door_axes = _list(doors["door_axes"], "doors.door_axes", 3) _require(door_axes == ["x", "y", "z"], "door_axes must be x,y,z") motors = _object(payload["motors"], "motors") forbidden_motor = FORBIDDEN_MOTOR_KEYS & set(motors) _require(not forbidden_motor, f"obsolete motors keys present: {sorted(forbidden_motor)}") _keys( motors, { "count", "order", "role", "execution", "step_rate_hz", "step_half_cycles", "motion_service_us", "motion_service_clks", "phase_factor", "profile_full", "profile_scale_q8", "cal_ramp_unit", "scheme", "dir_setup_cycles", "open_dir_value", "close_dir_value", "dir_close_level", "positioning", "mapping", "enable_n", }, "motors", ) _integer(motors["count"], "motors.count", minimum=1) _require(len(motors["order"]) == motors["count"] and all(isinstance(axis, str) and axis for axis in motors["order"]), "motor order mismatch") _require(isinstance(motors["role"], str) and motors["role"], "invalid motor role") _require(motors["execution"] == "overlap", "motor execution must be overlap") _integer(motors["step_rate_hz"], "motors.step_rate_hz", minimum=1) _require(motors["step_rate_hz"] == 1000, "motor peak step rate must be 1000") _integer(motors["step_half_cycles"], "motors.step_half_cycles", minimum=1) # 500 us watchdog/dir-setup reference tick only — not the sole motor speed generator. _require(motors["step_half_cycles"] == 12500, "watchdog/dir reference half cycles must be 12500") _integer(motors["motion_service_us"], "motors.motion_service_us", minimum=1, maximum=50) _integer(motors["motion_service_clks"], "motors.motion_service_clks", minimum=1) clock_hz = payload["device"]["clock_hz"] _require( motors["motion_service_clks"] == (clock_hz * motors["motion_service_us"]) // 1_000_000, "motion_service_clks must equal clock_hz * motion_service_us / 1e6", ) _integer(motors["phase_factor"], "motors.phase_factor", minimum=1) _integer(motors["profile_full"], "motors.profile_full", minimum=1) _require(motors["profile_full"] == 256, "profile_full must be 256") _require( motors["phase_factor"] == (clock_hz // motors["motion_service_clks"]) * motors["profile_full"] // (2 * motors["step_rate_hz"]), "phase_factor must equal SERVICE_HZ * PROFILE_FULL / (2 * MAX_STEP_HZ)", ) scales = _list(motors["profile_scale_q8"], "motors.profile_scale_q8", length=16) _require( scales == [64, 66, 73, 84, 98, 114, 132, 150, 170, 188, 206, 222, 236, 247, 254, 256], "profile_scale_q8 mismatch", ) _integer(motors["cal_ramp_unit"], "motors.cal_ramp_unit", minimum=1) _require(motors["cal_ramp_unit"] == 8, "cal_ramp_unit must be 8") _require( motors["scheme"] == "A_full_feature_per_axis_kernels_shared_slow_arith", "motors.scheme must be full-feature Scheme A", ) _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0) _require(motors["dir_setup_cycles"] == 25000, "motor dir setup cycles must be 25000") _integer(motors["open_dir_value"], "motors.open_dir_value", minimum=0) _integer(motors["close_dir_value"], "motors.close_dir_value", minimum=0) _require(motors["open_dir_value"] == 0, "logical open_dir_value must be 0") _require(motors["close_dir_value"] == 1, "logical close_dir_value must be 1") dir_close_level = _list(motors["dir_close_level"], "motors.dir_close_level", length=motors["count"]) for index, level in enumerate(dir_close_level): _require(isinstance(level, int) and not isinstance(level, bool) and level in (0, 1), f"motors.dir_close_level[{index}] must be 0 or 1") positioning = _object(motors["positioning"], "motors.positioning") _keys( positioning, { "mode", "percent_min", "percent_max", "open_endpoint_percent", "close_endpoint_percent", "mid_percent_min", "mid_percent_max", "rounding", "mid_clamp", "latest_wins", "idempotent_same_target", "command_interrupt", "shared_percent_planner", "planner_count", "endpoint_guard_extra_steps", }, "motors.positioning", ) _require(positioning["mode"] == "percent_close", "positioning mode must be percent_close") _integer(positioning["percent_min"], "motors.positioning.percent_min", minimum=0) _integer(positioning["percent_max"], "motors.positioning.percent_max", minimum=0) _require(positioning["percent_min"] == 0 and positioning["percent_max"] == 100, "percent range must be 0..100") _require(positioning["open_endpoint_percent"] == 0, "open endpoint percent must be 0") _require(positioning["close_endpoint_percent"] == 100, "close endpoint percent must be 100") _require(positioning["mid_percent_min"] == 1, "mid percent min must be 1") _require(positioning["mid_percent_max"] == 99, "mid percent max must be 99") _require(positioning["rounding"] == "half_up", "rounding must be half_up") _require(positioning["mid_clamp"] == "1_to_travel_minus_1", "mid clamp policy mismatch") _require(positioning["latest_wins"] is True, "latest_wins must be true") _require(positioning["idempotent_same_target"] is True, "idempotent_same_target must be true") _require( positioning["command_interrupt"] == "finish_current_high_pulse_then_replan", "command interrupt policy mismatch", ) _require(positioning["shared_percent_planner"] is True, "shared_percent_planner must be true") _integer(positioning["planner_count"], "motors.positioning.planner_count", minimum=1) _require(positioning["planner_count"] == 1, "planner_count must be 1") _integer(positioning["endpoint_guard_extra_steps"], "motors.positioning.endpoint_guard_extra_steps", minimum=0) _require(positioning["endpoint_guard_extra_steps"] == 500, "endpoint guard extra steps must be 500") mapping = _object(motors["mapping"], "motors.mapping") _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z") _keys(mapping, {"x", "y", "z"}, "motors.mapping") for axis in ("x", "y", "z"): item = _object(mapping[axis], f"motors.mapping.{axis}") required = {"axis", "role", "step_ball", "dir_ball"} _require(required <= set(item), f"motors.mapping.{axis} missing required keys") _require(item["axis"] == axis and item["role"] == "door", f"motor {axis} role mismatch") enable = _object(motors["enable_n"], "motors.enable_n") _require({"ball", "active_level", "policy"} <= set(enable), "motors.enable_n missing required keys") _require(isinstance(enable["ball"], str) and enable["ball"], "invalid motor enable ball") _require(enable["active_level"] == "low", "motor enable must be active low") _require(enable["policy"] == "permanent_high", "motor enable policy must be permanent_high") limits = _object(payload["limits"], "limits") _keys( limits, { "limit_count", "active_level", "limit_active_high", "close_limit_is_ls", "functional_use", "runtime_use", "startup", "channels", }, "limits", ) _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch") # limits.active_level is legacy / deprecated / non-authoritative. Accept the # historical string enum only; do not bind it to per-axis arrays or RTL masks. _require( limits["active_level"] in ("high", "low") and limits["functional_use"] is True, "limits.active_level must be legacy enum high|low and functional_use true", ) _require(limits["runtime_use"] is True, "runtime limit use must be true") limit_active_high = _list(limits["limit_active_high"], "limits.limit_active_high", length=motors["count"]) for index, active_high in enumerate(limit_active_high): _require(isinstance(active_high, bool), f"limits.limit_active_high[{index}] must be a boolean") close_limit_is_ls = _list(limits["close_limit_is_ls"], "limits.close_limit_is_ls", length=motors["count"]) for index, close_is_ls in enumerate(close_limit_is_ls): _require(isinstance(close_is_ls, bool), f"limits.close_limit_is_ls[{index}] must be a boolean") # Per-axis limit_active_high / close_limit_is_ls / dir_close_level alone decide # generated masks. Mixed-axis configs must not force active_level sync. startup = _object(limits["startup"], "limits.startup") forbidden_startup = FORBIDDEN_STARTUP_KEYS & set(startup) _require(not forbidden_startup, f"obsolete limits.startup keys present: {sorted(forbidden_startup)}") _keys( startup, { "enabled", "mode", "max_steps", "min_travel_steps", "step_rate_hz", "axis_order", "calibration_schedule", "runtime_overlap_allowed", "final_position", "limit_stop_during_move", "stop_semantics", "additional_rising_edges_after_synchronized_limit", "runtime_limit_use", "partial_axis_failure_allowed", "fault_lock_until_reset", }, "limits.startup", ) _require(startup["enabled"] is True, "startup must be enabled") _require(startup["mode"] == "seek_close_then_measure_open", "startup mode must be seek_close_then_measure_open") _require(startup["calibration_schedule"] == "serial_xyz", "startup calibration_schedule must be serial_xyz") _require(startup["runtime_overlap_allowed"] is True, "runtime_overlap_allowed must be true") _require(startup["final_position"] == "open", "startup final position must be open") _require(startup["limit_stop_during_move"] is True, "startup limit stop during move must be enabled") _require( startup["stop_semantics"] == "truncate_current_high_pulse_immediately_after_synchronized_limit", "unsupported stop semantics", ) _require(startup["additional_rising_edges_after_synchronized_limit"] == 0, "additional rising edges after limit must be zero") _require(startup["runtime_limit_use"] is True, "startup runtime limit use must be true") _require(startup["partial_axis_failure_allowed"] is True, "partial axis failure must be allowed") _require(startup["fault_lock_until_reset"] is True, "fault lock until reset must be true") _integer(startup["max_steps"], "limits.startup.max_steps", minimum=1) _integer(startup["min_travel_steps"], "limits.startup.min_travel_steps", minimum=0) _integer(startup["step_rate_hz"], "limits.startup.step_rate_hz", minimum=1) _require(startup["max_steps"] == 5000, "startup max_steps must be 5000") _require(startup["min_travel_steps"] >= 2, "min_travel_steps must be >= 2") _require(startup["min_travel_steps"] == 2, "startup min_travel_steps must be 2") _require(startup["step_rate_hz"] == 1000, "startup step rate must be 1000") _require(startup["max_steps"] <= CAL_COUNTER_MAX, "max_steps exceeds calibration counter width") endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"] _require(endpoint_guard_max <= CAL_COUNTER_MAX, "endpoint guard max exceeds calibration counter width") _require(endpoint_guard_max == 5500, "endpoint guard max must be 5500") _require(len(startup["axis_order"]) == 3 and startup["axis_order"] == ["x", "y", "z"], "startup axis order mismatch") expected_limit_names = [ "x_limit_ls", "x_limit_hs", "y_limit_ls", "y_limit_hs", "z_limit_ls", "z_limit_hs", ] for index, item in enumerate(limits["channels"]): entry = _object(item, f"limits.channels[{index}]") _keys(entry, {"name", "ball", "connector", "connector_pin", "side"}, f"limits.channels[{index}]") _require(entry["name"] == expected_limit_names[index], "invalid limit channel order/name") temperature = _object(payload["temperature"], "temperature") _keys( temperature, { "value_count", "device_addresses", "registers", "scl_ball", "sda_ball", "bus", "device", "invalid_value", "maximum_celsius", "conversion", }, "temperature", ) _integer(temperature["value_count"], "temperature.value_count", minimum=1) _require(temperature["value_count"] == len(temperature["device_addresses"]) * len(temperature["registers"]), "temperature count/list mismatch") _require(all(isinstance(value, int) and 0 <= value < 128 for value in temperature["device_addresses"]), "invalid temperature address") _require(all(isinstance(value, int) and 0 <= value <= 255 for value in temperature["registers"]), "invalid temperature register") _require(isinstance(temperature["device"], str) and temperature["device"], "invalid temperature device") _integer(temperature["invalid_value"], "temperature.invalid_value", minimum=0) _require(temperature["invalid_value"] <= 255, "temperature.invalid_value exceeds byte") _integer(temperature["maximum_celsius"], "temperature.maximum_celsius", minimum=0) conversion = _object(temperature["conversion"], "temperature.conversion") _keys(conversion, {"profile", "raw_shift", "raw_width", "reject_sign_bit"}, "temperature.conversion") _require(conversion == {"profile": "ct7428-msb-integer", "raw_shift": 7, "raw_width": 9, "reject_sign_bit": True}, "temperature conversion mismatch") pins = _object(payload["pins"], "pins") _keys( pins, { "host_uart_rx", "host_uart_tx", "temp_scl", "temp_sda", "ptc_pwm", "fan_pwm", "motor_en_n", "x_step", "x_dir", "y_step", "y_dir", "z_step", "z_dir", "x_limit_ls", "x_limit_hs", "y_limit_ls", "y_limit_hs", "z_limit_ls", "z_limit_hs", }, "pins", ) _require(pins["host_uart_rx"] == uart["rx_ball"] and pins["host_uart_tx"] == uart["tx_ball"], "UART pin duplication mismatch") _require(pins["temp_scl"] == temperature["scl_ball"] and pins["temp_sda"] == temperature["sda_ball"], "I2C pin duplication mismatch") _require(pins["ptc_pwm"] == [item["ball"] for item in outputs["ptc_channels"]], "PTC pin/list mismatch") _require( pins["fan_pwm"] == [item["ball"] for item in outputs["fan_channels"]], "FAN pin/list mismatch", ) _require(pins["motor_en_n"] == enable["ball"], "motor enable pin mismatch") for axis in ("x", "y", "z"): _require(pins[f"{axis}_step"] == mapping[axis]["step_ball"], f"{axis} step pin mismatch") _require(pins[f"{axis}_dir"] == mapping[axis]["dir_ball"], f"{axis} dir pin mismatch") for channel in limits["channels"]: _require(pins[channel["name"]] == channel["ball"], f"{channel['name']} pin mismatch") resources = _object(payload["resource_policy"], "resource_policy") _keys( resources, { "target_ram", "request_ram", "temperature_ram", "dsp", "bram", "shared_pwm_comparators", "shared_percent_planner", "shared_i2c_readers", }, "resource_policy", ) for key, value in resources.items(): if key in {"target_ram", "request_ram", "temperature_ram", "dsp", "bram"}: _require( value in {"optional", "required", "forbidden"}, f"resource_policy.{key} must be optional, required, or forbidden", ) else: _integer(value, f"resource_policy.{key}", minimum=0) _require(resources["dsp"] == "optional", "resource_policy.dsp must be optional") _require(resources["bram"] == "optional", "resource_policy.bram must be optional") _require(resources["shared_percent_planner"] == 1, "resource_policy.shared_percent_planner must be 1") _require(resources["shared_percent_planner"] == positioning["planner_count"], "shared planner count mismatch") protocol = _object(payload["protocol"], "protocol") _keys( protocol, { "header_hex", "crc", "commands", "set_all", "get_motor_status", "temperature_data", "motor_status_data", }, "protocol", ) _require(isinstance(protocol["header_hex"], str) and protocol["header_hex"], "frame header missing") crc = _object(protocol["crc"], "protocol.crc") _keys(crc, {"name", "polynomial", "initial", "reflect_input", "reflect_output", "xor_output", "coverage", "wire_order"}, "protocol.crc") _require( crc == { "name": "CRC-16/CCITT-FALSE", "polynomial": 0x1021, "initial": 0xFFFF, "reflect_input": False, "reflect_output": False, "xor_output": 0, "coverage": "type_length_payload", "wire_order": "little", }, "CRC contract mismatch", ) commands = _object(protocol["commands"], "protocol.commands") _keys( commands, {"set_all", "get_temperature", "get_motor_status", "temperature_data", "motor_status_data"}, "protocol.commands", ) _require(commands["set_all"] == 1, "SET_ALL command type mismatch") _require(commands["get_temperature"] == 2, "GET_TEMPERATURE command type mismatch") _require(commands["get_motor_status"] == 3, "GET_MOTOR_STATUS command type mismatch") _require(commands["temperature_data"] == 130, "TEMPERATURE_DATA command type mismatch") _require(commands["motor_status_data"] == 131, "MOTOR_STATUS_DATA command type mismatch") command_values = list(commands.values()) _require(len(command_values) == len(set(command_values)), "duplicate protocol command types") _require("door_values" not in protocol.get("set_all", {}), "obsolete set_all.door_values present") set_all = _object(protocol["set_all"], "protocol.set_all") set_all_keys = { "payload_length", "fan_offset", "chamber_ptc_offset", "chamber_ptc_count", "z_door_offset", "exhaust_x_offset", "exhaust_y_offset", "legacy_payload_length_rejected", "duty_min", "duty_max", "door_percent_min", "door_percent_max", "response", } optional_set_all = {"door_percent_rejected_example"} _require(set_all_keys <= set(set_all), "protocol.set_all missing required keys") _require(set(set_all) <= (set_all_keys | optional_set_all), "protocol.set_all keys mismatch") _require(set_all["fan_offset"] == 0, "SET_ALL FAN offset mismatch") _require(set_all["chamber_ptc_offset"] == outputs["fan_count"], "SET_ALL chamber PTC offset mismatch") _require(set_all["chamber_ptc_count"] == outputs["chamber_ptc_count"], "SET_ALL chamber PTC count mismatch") _require(set_all["z_door_offset"] == set_all["chamber_ptc_offset"] + set_all["chamber_ptc_count"], "SET_ALL Z offset mismatch") _require(set_all["exhaust_x_offset"] == set_all["z_door_offset"] + 1, "SET_ALL exhaust X offset mismatch") _require(set_all["exhaust_y_offset"] == set_all["exhaust_x_offset"] + 1, "SET_ALL exhaust Y offset mismatch") _require(set_all["payload_length"] == set_all["exhaust_y_offset"] + 1, "SET_ALL length mismatch") _require(set_all["legacy_payload_length_rejected"] == 14, "legacy payload length marker mismatch") _require(set_all["duty_min"] <= set_all["duty_max"], "SET_ALL duty range mismatch") _require(set_all["door_percent_min"] == positioning["percent_min"], "SET_ALL door percent min mismatch") _require(set_all["door_percent_max"] == positioning["percent_max"], "SET_ALL door percent max mismatch") _require(set_all["response"] == "none", "SET_ALL response must be none") if "door_percent_rejected_example" in set_all: _integer(set_all["door_percent_rejected_example"], "protocol.set_all.door_percent_rejected_example", minimum=0) _require( set_all["door_percent_rejected_example"] > set_all["door_percent_max"], "door percent rejected example must exceed door_percent_max", ) get_motor_status = _object(protocol["get_motor_status"], "protocol.get_motor_status") _keys(get_motor_status, {"payload_length", "response"}, "protocol.get_motor_status") _require(get_motor_status["payload_length"] == 0, "GET_MOTOR_STATUS payload length must be 0") _require(get_motor_status["response"] == "motor_status_data", "GET_MOTOR_STATUS response mismatch") temperature_data = _object(protocol["temperature_data"], "protocol.temperature_data") _keys(temperature_data, {"payload_length", "frame_length"}, "protocol.temperature_data") _require(temperature_data["payload_length"] == temperature["value_count"], "temperature payload length mismatch") _require(temperature_data["frame_length"] == temperature_data["payload_length"] + 6, "temperature frame length mismatch") motor_status_data = _object(protocol["motor_status_data"], "protocol.motor_status_data") _keys(motor_status_data, {"payload_length", "frame_length", "layout"}, "protocol.motor_status_data") _require(motor_status_data["payload_length"] == 31, "motor status payload length must be 31") _require(motor_status_data["frame_length"] == 37, "motor status frame length must be 37") _require( motor_status_data["frame_length"] == motor_status_data["payload_length"] + 6, "motor status frame length mismatch", ) _require(motor_status_data["layout"] == "host-contract", "motor status layout marker mismatch") timeouts = _object(payload["timeouts"], "timeouts") _keys(timeouts, {"frame_inter_byte_ms", "host_get_response_ms"}, "timeouts") _integer(timeouts["frame_inter_byte_ms"], "timeouts.frame_inter_byte_ms", minimum=1) _integer(timeouts["host_get_response_ms"], "timeouts.host_get_response_ms", minimum=1) watchdog = _object(payload["watchdog"], "watchdog") _keys( watchdog, {"timeout_seconds", "tick_us", "tick_clks", "timeout_ticks", "enable_after_startup_complete", "target"}, "watchdog", ) _integer(watchdog["timeout_seconds"], "watchdog.timeout_seconds", minimum=1) _integer(watchdog["tick_us"], "watchdog.tick_us", minimum=1) _integer(watchdog["tick_clks"], "watchdog.tick_clks", minimum=1) _require(watchdog["tick_clks"] == device["clock_hz"] * watchdog["tick_us"] // 1_000_000, "watchdog tick clock mismatch") _integer(watchdog["timeout_ticks"], "watchdog.timeout_ticks", minimum=1) _require(watchdog["timeout_ticks"] == watchdog["timeout_seconds"] * 1_000_000 // watchdog["tick_us"], "watchdog tick count mismatch") _require(watchdog["timeout_seconds"] == 30, "watchdog timeout_seconds must be 30") _require(watchdog["timeout_ticks"] == 60000, "watchdog timeout_ticks must be 60000") _require(watchdog["enable_after_startup_complete"] is True, "watchdog must enable after startup complete") target = _object(watchdog["target"], "watchdog.target") _keys(target, {"ptc", "fan"}, "watchdog.target") _require(target == {"ptc": 0, "fan": 10}, "watchdog target mismatch") def load_project(path: Path) -> dict[str, Any]: project_path = Path(path) payload = json.loads(project_path.read_text(encoding="utf-8")) _require(isinstance(payload, dict), "project root must be an object") if payload.get("profile") == PROFILE_6400: from tools.generate_6400 import load_6400_project return load_6400_project(project_path) schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda error: list(error.absolute_path)) if errors: location = ".".join(str(part) for part in errors[0].absolute_path) or "project" raise ValueError(f"project schema violation at {location}: {errors[0].message}") _validate_project(payload) return payload def _active_interface(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]: outputs = project["outputs"] pins = project["pins"] motors = project["motors"] interface = ( ("sys_clk", project["device"]["clock_ball"]), ("host_uart_rx", pins["host_uart_rx"]), ("host_uart_tx", pins["host_uart_tx"]), ("temp_scl", pins["temp_scl"]), ("temp_sda", pins["temp_sda"]), *tuple((item["signal"], item["ball"]) for item in outputs["ptc_channels"]), *tuple((item["signal"], item["ball"]) for item in outputs["fan_channels"]), ("motor_en_n", pins["motor_en_n"]), ("x_step", motors["mapping"]["x"]["step_ball"]), ("x_dir", motors["mapping"]["x"]["dir_ball"]), ("y_step", motors["mapping"]["y"]["step_ball"]), ("y_dir", motors["mapping"]["y"]["dir_ball"]), ("z_step", motors["mapping"]["z"]["step_ball"]), ("z_dir", motors["mapping"]["z"]["dir_ball"]), *tuple((item["name"], item["ball"]) for item in project["limits"]["channels"]), ) return interface def render_adc(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]: """Return the ordered active interface as (signal, ball) pairs.""" return _active_interface(project) def project_summary(path: Path) -> dict[str, Any]: project = load_project(path) outputs = project["outputs"] temperature = project["temperature"] watchdog = project["watchdog"] total_channels = outputs["ptc_count"] + outputs["fan_count"] pwm_period_clks = outputs["pwm_slot_clks"] * total_channels * outputs["pwm_phase_count"] actual_frequency_hz = project["device"]["clock_hz"] / pwm_period_clks frequency_error_percent = abs(actual_frequency_hz - outputs["pwm_frequency_hz"]) / outputs["pwm_frequency_hz"] * 100.0 return { "project_id": project["project_id"], "profile": project["profile"], "uart_clks_per_bit": project["uart"]["clks_per_bit"], "pwm_bits": outputs["pwm_bits"], "pwm_internal_width": outputs["pwm_internal_width"], "pwm_max_duty": outputs["pwm_max_duty"], "pwm_phase_count": outputs["pwm_phase_count"], "pwm_frequency_hz": outputs["pwm_frequency_hz"], "pwm_slot_clks": outputs["pwm_slot_clks"], "pwm_period_clks": pwm_period_clks, "pwm_period_seconds": round(pwm_period_clks / project["device"]["clock_hz"], 9), "actual_frequency_hz": round(actual_frequency_hz, 9), "frequency_error_percent": round(frequency_error_percent, 9), "ptc_default": outputs["ptc_default"], "fan_default": outputs["fan_default"], "ptc_polarity": outputs["ptc_polarity"], "fan_polarity": outputs["fan_polarity"], "fan_connector_active_level": outputs["fan_connector_active_level"], "fan_board_inverts": outputs["fan_board_inverts"], "set_all_payload_len": project["protocol"]["set_all"]["payload_length"], "set_all_frame_len": project["protocol"]["set_all"]["payload_length"] + 6, "temperature_payload_len": temperature["value_count"], "temperature_frame_len": temperature["value_count"] + 6, "temperature_addresses": list(temperature["device_addresses"]), "boot_targets": dict(outputs["boot_targets"]), "watchdog_timeout_seconds": watchdog["timeout_seconds"], "watchdog_tick_clks": watchdog["tick_clks"], "watchdog_timeout_ticks": watchdog["timeout_ticks"], "watchdog_target": dict(watchdog["target"]), } def _write_json(path: Path, payload: Mapping[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") def _crc16_ccitt_false(data: bytes) -> int: crc = 0xFFFF for value in data: crc ^= value << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def _frame_hex(frame_type: int, payload: bytes) -> str: body = bytes((frame_type, len(payload))) + payload crc = _crc16_ccitt_false(body) return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper() def _render_params(project: Mapping[str, Any]) -> str: outputs = project["outputs"] motors = project["motors"] positioning = motors["positioning"] limits = project["limits"] startup = limits["startup"] temperature = project["temperature"] uart = project["uart"] watchdog = project["watchdog"] protocol = project["protocol"] commands = protocol["commands"] axis_count = motors["count"] _require(motors["dir_setup_cycles"] % watchdog["tick_clks"] == 0, "motor direction setup is not an integral tick count") motor_dir_setup_ticks = motors["dir_setup_cycles"] // watchdog["tick_clks"] frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000 startup_dir_bit = motors["close_dir_value"] startup_dir_mask = f"{axis_count}'b" + (str(startup_dir_bit) * axis_count) limit_active_high_mask = _axis_mask_literal(limits["limit_active_high"], axis_count) dir_close_level_mask = _axis_mask_literal(motors["dir_close_level"], axis_count) close_limit_is_ls_mask = _axis_mask_literal(limits["close_limit_is_ls"], axis_count) endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"] lines = [ "// Generated from project.json. Do not edit.", f"`define P4_AXIS_COUNT {axis_count}", f"`define P4_LIMIT_COUNT {limits['limit_count']}", f"`define P4_RUNTIME_LIMIT_USE {1 if limits['runtime_use'] else 0}", f"`define P4_LIMIT_ACTIVE_HIGH_MASK {limit_active_high_mask}", f"`define P4_DIR_CLOSE_LEVEL_MASK {dir_close_level_mask}", f"`define P4_CLOSE_LIMIT_IS_LS_MASK {close_limit_is_ls_mask}", f"`define P4_CLOCK_HZ {project['device']['clock_hz']}", f"`define P4_UART_BAUD {uart['baud']}", f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}", f"`define P4_PTC_COUNT {outputs['ptc_count']}", f"`define P4_FAN_COUNT {outputs['fan_count']}", f"`define P4_OUTPUT_CHANNEL_COUNT {outputs['ptc_count'] + outputs['fan_count']}", f"`define P4_PWM_PROTOCOL_WIDTH {outputs['pwm_bits']}", f"`define P4_PWM_INTERNAL_WIDTH {outputs['pwm_internal_width']}", f"`define P4_PWM_MAX_DUTY {outputs['pwm_max_duty']}", f"`define P4_PWM_PHASE_COUNT {outputs['pwm_phase_count']}", f"`define P4_PWM_FREQUENCY_HZ {outputs['pwm_frequency_hz']}", f"`define P4_PWM_SLOT_CLKS {outputs['pwm_slot_clks']}", f"`define P4_CMD_SET_ALL 8'h{commands['set_all']:02X}", f"`define P4_CMD_GET_TEMPERATURE 8'h{commands['get_temperature']:02X}", f"`define P4_CMD_GET_MOTOR_STATUS 8'h{commands['get_motor_status']:02X}", f"`define P4_CMD_TEMPERATURE_DATA 8'h{commands['temperature_data']:02X}", f"`define P4_CMD_MOTOR_STATUS_DATA 8'h{commands['motor_status_data']:02X}", f"`define P4_RSP_TEMPERATURE 8'h{commands['temperature_data']:02X}", f"`define P4_RSP_MOTOR_STATUS 8'h{commands['motor_status_data']:02X}", f"`define P4_SET_ALL_PAYLOAD_LENGTH {protocol['set_all']['payload_length']}", f"`define P4_CHAMBER_PTC_COUNT {outputs['chamber_ptc_count']}", f"`define P4_SET_ALL_FAN_OFFSET {protocol['set_all']['fan_offset']}", f"`define P4_SET_ALL_CHAMBER_PTC_OFFSET {protocol['set_all']['chamber_ptc_offset']}", f"`define P4_SET_ALL_Z_DOOR_OFFSET {protocol['set_all']['z_door_offset']}", f"`define P4_SET_ALL_EXHAUST_X_OFFSET {protocol['set_all']['exhaust_x_offset']}", f"`define P4_SET_ALL_EXHAUST_Y_OFFSET {protocol['set_all']['exhaust_y_offset']}", f"`define P4_DOOR_PERCENT_MIN {positioning['percent_min']}", f"`define P4_DOOR_PERCENT_MAX {positioning['percent_max']}", f"`define P4_OPEN_ENDPOINT_PERCENT {positioning['open_endpoint_percent']}", f"`define P4_CLOSE_ENDPOINT_PERCENT {positioning['close_endpoint_percent']}", f"`define P4_MID_PERCENT_MIN {positioning['mid_percent_min']}", f"`define P4_MID_PERCENT_MAX {positioning['mid_percent_max']}", f"`define P4_MOTOR_STATUS_PAYLOAD_LENGTH {protocol['motor_status_data']['payload_length']}", f"`define P4_MOTOR_STATUS_FRAME_LENGTH {protocol['motor_status_data']['frame_length']}", f"`define P4_MOTOR_OPEN_DIR 1'b{motors['open_dir_value']}", f"`define P4_MOTOR_CLOSE_DIR 1'b{motors['close_dir_value']}", f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}", f"`define P4_MOTOR_STEP_RATE_HZ {motors['step_rate_hz']}", f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}", f"`define P4_MOTION_SERVICE_US {motors['motion_service_us']}", f"`define P4_MOTION_SERVICE_CLKS {motors['motion_service_clks']}", f"`define P4_PHASE_FACTOR {motors['phase_factor']}", f"`define P4_PROFILE_FULL {motors['profile_full']}", f"`define P4_CAL_RAMP_UNIT {motors['cal_ramp_unit']}", f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}", f"`define P4_MOTOR_DIR_SETUP_TICKS {motor_dir_setup_ticks}", f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}", f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}", f"`define P4_TEMPERATURE_FRAME_LENGTH {temperature['value_count'] + 6}", f"`define P4_TEMP_MAX_CELSIUS {temperature['maximum_celsius']}", f"`define P4_PTC_ACTIVE_HIGH {1 if outputs['ptc_polarity'] == 'active_high' else 0}", f"`define P4_FAN_ACTIVE_HIGH {1 if outputs['fan_polarity'] == 'active_high' else 0}", f"`define P4_PTC_DEFAULT_TARGET 8'h{outputs['ptc_default']:02X}", f"`define P4_FAN_DEFAULT_TARGET 8'h{outputs['fan_default']:02X}", f"`define P4_WATCHDOG_TIMEOUT_SECONDS {watchdog['timeout_seconds']}", f"`define P4_WATCHDOG_TICK_US {watchdog['tick_us']}", f"`define P4_WATCHDOG_TICK_CLKS {watchdog['tick_clks']}", f"`define P4_WATCHDOG_TIMEOUT_TICKS {watchdog['timeout_ticks']}", f"`define P4_WATCHDOG_ENABLE_AFTER_STARTUP {1 if watchdog['enable_after_startup_complete'] else 0}", f"`define P4_WATCHDOG_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}", f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}", f"`define P4_STARTUP_ENABLED {1 if startup['enabled'] else 0}", f"`define P4_STARTUP_DIR_MASK {startup_dir_mask}", f"`define P4_CAL_MAX_STEPS {startup['max_steps']}", f"`define P4_CAL_MIN_TRAVEL {startup['min_travel_steps']}", f"`define P4_ENDPOINT_GUARD_EXTRA {positioning['endpoint_guard_extra_steps']}", f"`define P4_ENDPOINT_GUARD_MAX {endpoint_guard_max}", f"`define P4_STARTUP_STEP_RATE_HZ {startup['step_rate_hz']}", f"`define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH {1 if motors['enable_n']['policy'] == 'permanent_high' else 0}", "`define P4_STATE_CAL_SEEK_CLOSE 8'd0", "`define P4_STATE_CAL_MEASURE_OPEN 8'd1", "`define P4_STATE_IDLE 8'd2", "`define P4_STATE_MOVE_OPEN 8'd3", "`define P4_STATE_MOVE_CLOSE 8'd4", "`define P4_STATE_WAIT_REPLAN 8'd5", "`define P4_STATE_FAULT 8'd6", "`define P4_FAULT_NONE 8'd0", "`define P4_FAULT_BOTH_LIMITS_ACTIVE 8'd1", "`define P4_FAULT_CAL_CLOSE_TIMEOUT 8'd2", "`define P4_FAULT_CAL_OPEN_TIMEOUT 8'd3", "`define P4_FAULT_INVALID_ZERO_OR_TINY_TRAVEL 8'd4", "`define P4_FAULT_ENDPOINT_TIMEOUT 8'd5", ] lines.extend( f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}" for index, address in enumerate(temperature["device_addresses"]) ) lines.extend( f"`define P4_TEMP_REGISTER_{index} 8'h{register:02X}" for index, register in enumerate(temperature["registers"]) ) lines.append("") return "\n".join(lines) def render_adc_text(project: Mapping[str, Any]) -> str: lines = [ "# Generated from project.json. Do not edit.", "# Active interface only; reserved board loads are intentionally absent.", ] active_interface = list(render_adc(project)) for signal, ball in active_interface: lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") return "\n".join(lines) + "\n" def generate_project( project_path: Path, output_root: Path, *, generated_rel: str | None = None, source_closure_path: Path | None = None, target_alias: str | None = None, ) -> dict[str, Any]: peek = json.loads(Path(project_path).read_text(encoding="utf-8")) if isinstance(peek, dict) and peek.get("profile") == PROFILE_6400: from tools.generate_6400 import generate_6400 return generate_6400( Path(project_path), Path(output_root), generated_rel=generated_rel or "generated", source_closure_path=source_closure_path, target_alias=target_alias or "6400", ) project = load_project(project_path) output = Path(output_root) / (generated_rel or "generated") output.mkdir(parents=True, exist_ok=True) params_name = f"{project['project_id'].replace('-', '_')}_params.vh" (output / params_name).write_text( _render_params(project), encoding="ascii", newline="\n" ) summary = project_summary(project_path) positioning = project["motors"]["positioning"] motor_status_layout = { "byte0_global": { "bit0_2": "calibrated_mask_xyz", "bit3_5": "fault_mask_xyz", "bit6": "startup_complete", "bit7": "watchdog_tripped", }, "per_axis_bytes": 10, "axis_order": ["x", "y", "z"], "axis_fields": [ "state", "flags", "requested_percent", "current_position_le16", "target_position_le16", "travel_steps_le16", "fault_code", ], "states": { "CAL_SEEK_CLOSE": 0, "CAL_MEASURE_OPEN": 1, "IDLE": 2, "MOVE_OPEN": 3, "MOVE_CLOSE": 4, "WAIT_REPLAN": 5, "FAULT": 6, }, "flags": { "open_limit": 0, "close_limit": 1, "calibrated": 2, "moving": 3, "endpoint_mode": 4, "target_valid": 5, "replan_pending": 6, "reserved": 7, }, "fault_codes": { "NONE": 0, "BOTH_LIMITS_ACTIVE": 1, "CAL_CLOSE_TIMEOUT": 2, "CAL_OPEN_TIMEOUT": 3, "INVALID_ZERO_OR_TINY_TRAVEL": 4, "ENDPOINT_TIMEOUT": 5, }, } contract = { "schema": "prod2u-simple-host-contract-v1", "project_id": project["project_id"], "profile": project["profile"], "axis_count": project["motors"]["count"], "limit_count": project["limits"]["limit_count"], "runtime_limit_use": project["limits"]["runtime_use"], "uart": project["uart"], "protocol": project["protocol"], "commands": { "set_all": { "type": "0x01", "payload_length": summary["set_all_payload_len"], "response": "none", "duty_range": [0, 100], "door_percent_range": [positioning["percent_min"], positioning["percent_max"]], "door_percent_semantics": { "0": "full_open_endpoint", "1_to_99": "mid_percent_close", "100": "full_close_endpoint", "all_zero_frame": "fan_ptc_zero_and_all_doors_full_open_not_heartbeat", "0x65": "rejected_out_of_range", }, "field_order": [ "fan_chamber_1", "fan_chamber_2", "fan_chamber_3", "fan_chamber_4", "ptc_chamber_1", "ptc_chamber_2", "ptc_chamber_3", "ptc_chamber_4", "door_z_percent", "door_x_percent", "door_y_percent", ], }, "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"}, "get_motor_status": {"type": "0x03", "payload_length": 0, "response": "MOTOR_STATUS_DATA"}, "temperature_data": { "type": "0x82", "payload_length": summary["temperature_payload_len"], "frame_length": summary["temperature_frame_len"], }, "motor_status_data": { "type": "0x83", "payload_length": project["protocol"]["motor_status_data"]["payload_length"], "frame_length": project["protocol"]["motor_status_data"]["frame_length"], "layout": motor_status_layout, }, }, "outputs": project["outputs"], "motors": project["motors"], "limits": project["limits"], "temperature": project["temperature"], "watchdog": project["watchdog"], } _write_json(output / "host-contract.json", contract) _write_json(output / "project-summary.json", summary) # Representative status: startup_complete + all calibrated, idle at open, travel=1000. status_axis = bytes((0x02, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE8, 0x03, 0x00)) status_payload = bytes((0x47,)) + status_axis * 3 _write_json( output / "golden-vectors.json", { "set_all_all_zero_full_open": _frame_hex(0x01, bytes(11)), "set_all_doors_0_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 0, 0, 0))), "set_all_doors_50_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 50, 50, 50))), "set_all_doors_100_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 100, 100, 100))), "set_all_door_0x65_rejected": "65", "set_all_legacy_14_rejected": "0E", "get_temperature": _frame_hex(0x02, b""), "get_motor_status": _frame_hex(0x03, b""), "motor_status_data_example": _frame_hex(0x83, status_payload), "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * project["temperature"]["value_count"])), "notes": { "set_all_all_zero_full_open": "Legal SET_ALL: FAN/PTC 0 and doors 0/0/0 = full open; not a jog heartbeat no-op.", "set_all_door_0x65_rejected": "Door percent 0x65 (101) is out of 0..100 and must be rejected.", "get_motor_status": "Exact request frame A55A03005C48.", }, }, ) source_payload = { "schema": "prod2u-simple-source-manifest-template-v1", "project_id": project["project_id"], "sources": list(_load_source_closure()), "generated_from": "project.json", "contract": { "uart": project["uart"], "protocol": project["protocol"], "set_all_payload_length": summary["set_all_payload_len"], "temperature_frame_length": summary["temperature_frame_len"], "axis_count": project["motors"]["count"], "limit_count": project["limits"]["limit_count"], "runtime_limit_use": project["limits"]["runtime_use"], }, "active_interface": [ {"signal": signal, "ball": ball} for signal, ball in render_adc(project) ], } _write_json(output / "td-source-manifest.json", source_payload) (output / f"{project['project_id'].replace('-', '_')}.adc").write_text( render_adc_text(project), encoding="ascii", newline="\n" ) return summary def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--target", help="registry alias (mrdimm or 6400)") parser.add_argument("project", type=Path, nargs="?") parser.add_argument("output", type=Path, nargs="?") args = parser.parse_args() if args.target: from tools.generate_target import generate_named_target generate_named_target(args.target) return 0 if args.project is None or args.output is None: parser.error("project and output are required unless --target is set") generate_project(args.project, args.output) return 0 if __name__ == "__main__": raise SystemExit(main())