| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612 |
- #!/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"
- SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schemas" / "project.schema.json"
- ACTIVE_SOURCE_PATHS = (
- "src/generated/prod2u_door_temp_params.vh",
- "src/common/uart_rx_byte.v",
- "src/common/uart_tx_byte.v",
- "src/common/crc16_serial.v",
- "src/common/frame_rx.v",
- "src/common/frame_tx.v",
- "src/common/payload_ram.v",
- "src/modules/output_target_ram.v",
- "src/modules/pwm_scheduler.v",
- "src/modules/shared_500us_tick.v",
- "src/modules/host_watchdog.v",
- "src/modules/door_motor_engine.v",
- "src/modules/i2c_word_reader.v",
- "src/modules/temperature_reader.v",
- "src/modules/temperature_ram.v",
- "src/project/command_controller.v",
- "src/project/project_adapter.v",
- "src/rtl/prod2u_por.v",
- "src/rtl/prod2u_p4_i2c_stop_start_read.v",
- "src/top/prod2u_p4_normal_v3_top.v",
- )
- _TOP_LEVEL_KEYS = {
- "project_id",
- "profile",
- "display_name",
- "device",
- "uart",
- "outputs",
- "motors",
- "limits",
- "temperature",
- "pins",
- "resource_policy",
- "protocol",
- "timeouts",
- "watchdog",
- }
- def _require(condition: bool, message: str) -> None:
- if not condition:
- raise ValueError(message)
- 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) -> 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")
- 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 _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",
- "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")
- 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")
- motors = _object(payload["motors"], "motors")
- _keys(
- motors,
- {
- "count",
- "order",
- "role",
- "fixed_steps",
- "execution",
- "busy_wait_ms",
- "step_rate_hz",
- "step_half_cycles",
- "dir_setup_cycles",
- "command_values",
- "heartbeat_value",
- "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"] in {"overlap", "serial"}, "invalid motor execution")
- _integer(motors["busy_wait_ms"], "motors.busy_wait_ms", minimum=0)
- _integer(motors["fixed_steps"], "motors.fixed_steps", minimum=1)
- _integer(motors["step_rate_hz"], "motors.step_rate_hz", minimum=1)
- _integer(motors["step_half_cycles"], "motors.step_half_cycles", minimum=1)
- _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0)
- _require(isinstance(motors["command_values"], list) and motors["command_values"], "invalid motor commands")
- _require(motors["heartbeat_value"] in motors["command_values"], "motor heartbeat is not a command")
- mapping = _object(motors["mapping"], "motors.mapping")
- _keys(mapping, {"x", "y"}, "motors.mapping")
- for axis in ("x", "y"):
- item = _object(mapping[axis], f"motors.mapping.{axis}")
- _keys(item, {"axis", "role", "step_ball", "dir_ball"}, f"motors.mapping.{axis}")
- _require(item["axis"] == axis and item["role"] == "exhaust", f"motor {axis} role mismatch")
- enable = _object(motors["enable_n"], "motors.enable_n")
- _keys(enable, {"ball", "active_level", "policy"}, "motors.enable_n")
- _require(enable == {"ball": "A10", "active_level": "low", "policy": "shared_constant_low"}, "motor enable mapping mismatch")
- limits = _object(payload["limits"], "limits")
- _keys(limits, {"limit_count", "active_level", "functional_use", "channels"}, "limits")
- _require(limits["limit_count"] == len(limits["channels"]) == 2, "limit count/list mismatch")
- _require(limits["active_level"] == "high" and limits["functional_use"] is False, "limit policy mismatch")
- for index, item in enumerate(limits["channels"]):
- entry = _object(item, f"limits.channels[{index}]")
- _keys(entry, {"name", "ball"}, f"limits.channels[{index}]")
- _require(entry["name"] in {"x_limit_raw", "y_limit_raw"}, "invalid limit 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",
- "x_limit_raw",
- "y_limit_raw",
- },
- "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")
- _require(pins["x_step"] == mapping["x"]["step_ball"] and pins["x_dir"] == mapping["x"]["dir_ball"], "X motor pin mismatch")
- _require(pins["y_step"] == mapping["y"]["step_ball"] and pins["y_dir"] == mapping["y"]["dir_ball"], "Y motor pin mismatch")
- _require([pins["x_limit_raw"], pins["y_limit_raw"]] == [item["ball"] for item in limits["channels"]], "limit pin mismatch")
- resources = _object(payload["resource_policy"], "resource_policy")
- _keys(
- resources,
- {
- "target_ram",
- "request_ram",
- "temperature_ram",
- "dsp",
- "shared_pwm_comparators",
- "shared_motor_executors",
- "shared_i2c_readers",
- },
- "resource_policy",
- )
- for key, value in resources.items():
- if key in {"target_ram", "request_ram", "temperature_ram"}:
- _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)
- protocol = _object(payload["protocol"], "protocol")
- _keys(protocol, {"header_hex", "crc", "commands", "set_all", "temperature_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",
- )
- _require(set(protocol["commands"]) == {"set_all", "get_temperature", "temperature_data"}, "protocol command keys mismatch")
- set_all = _object(protocol["set_all"], "protocol.set_all")
- _keys(set_all, {"payload_length", "ptc_offset", "fan_offset", "motor_x_offset", "motor_y_offset", "duty_min", "duty_max", "motor_values", "heartbeat", "response"}, "protocol.set_all")
- _require(set_all["ptc_offset"] == 0, "SET_ALL PTC offset mismatch")
- _require(set_all["fan_offset"] == outputs["ptc_count"], "SET_ALL FAN offset mismatch")
- _require(set_all["motor_x_offset"] == outputs["ptc_count"] + outputs["fan_count"], "SET_ALL X offset mismatch")
- _require(set_all["motor_y_offset"] == set_all["motor_x_offset"] + 1, "SET_ALL Y offset mismatch")
- _require(set_all["payload_length"] == set_all["motor_y_offset"] + 1, "SET_ALL length mismatch")
- _require(set_all["duty_min"] <= set_all["duty_max"], "SET_ALL duty range mismatch")
- _require(isinstance(set_all["motor_values"], list) and set_all["heartbeat"] == [motors["heartbeat_value"]] * len(motors["order"]), "SET_ALL motor contract 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")
- 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", "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")
- target = _object(watchdog["target"], "watchdog.target")
- _keys(target, {"ptc", "fan"}, "watchdog.target")
- _require(target == {"ptc": 0, "fan": 20}, "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")
- 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"]
- limits = project["limits"]
- return (
- ("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"]),
- *tuple((item["name"], item["ball"]) for item in limits["channels"]),
- )
- 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"]
- temperature = project["temperature"]
- uart = project["uart"]
- watchdog = project["watchdog"]
- _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
- lines = [
- "// Generated from project.json. Do not edit.",
- 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_SET_ALL_PAYLOAD_LENGTH {project['protocol']['set_all']['payload_length']}",
- f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}",
- f"`define P4_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
- 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_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
- f"`define P4_MOTOR_DIR_SETUP_TICKS {motor_dir_setup_ticks}",
- f"`define P4_MOTOR_HEARTBEAT_COMMAND 2'd{motors['heartbeat_value']}",
- 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_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}",
- f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}",
- ]
- 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) -> dict[str, Any]:
- project = load_project(project_path)
- output = Path(output_root) / "generated"
- output.mkdir(parents=True, exist_ok=True)
- (output / f"{project['project_id'].replace('-', '_')}_params.vh").write_text(
- _render_params(project), encoding="ascii", newline="\n"
- )
- summary = project_summary(project_path)
- contract = {
- "schema": "prod2u-simple-host-contract-v1",
- "project_id": project["project_id"],
- "uart": project["uart"],
- "protocol": project["protocol"],
- "commands": {
- "set_all": {
- "type": "0x01",
- "payload_length": summary["set_all_payload_len"],
- "response": "none",
- "duty_range": [0, 100],
- "motor_values": [0, 1, 2],
- "heartbeat": [0, 0],
- },
- "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
- "temperature_data": {
- "type": "0x82",
- "payload_length": summary["temperature_payload_len"],
- "frame_length": summary["temperature_frame_len"],
- },
- },
- "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)
- _write_json(
- output / "golden-vectors.json",
- {
- "set_all": _frame_hex(0x01, bytes(range(8)) + bytes((10, 20, 30, 40, 1, 2))),
- "get_temperature": _frame_hex(0x02, b""),
- "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * project["temperature"]["value_count"])),
- },
- )
- _write_json(
- output / "td-source-manifest.json",
- {
- "schema": "prod2u-simple-source-manifest-template-v1",
- "project_id": project["project_id"],
- "sources": list(ACTIVE_SOURCE_PATHS),
- "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"],
- },
- "active_interface": [
- {"signal": signal, "ball": ball}
- for signal, ball in render_adc(project)
- ],
- },
- )
- (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("project", type=Path)
- parser.add_argument("output", type=Path)
- args = parser.parse_args()
- generate_project(args.project, args.output)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|