| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190 |
- #!/usr/bin/env python3
- """Validate a project.json and emit deterministic compile-time artifacts."""
- from __future__ import annotations
- import argparse
- import json
- import re
- from pathlib import Path
- from typing import Any, Mapping
- PROFILE = "prod2u-normal-multiproject-115200-v1"
- 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/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",
- )
- def _require(condition: bool, message: str) -> None:
- if not condition:
- raise ValueError(message)
- 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")
- _require(re.fullmatch(r"[a-z0-9-]+", str(payload.get("project_id", ""))) is not None, "invalid project_id")
- _require(payload.get("profile") == PROFILE, "unsupported project profile")
- device = payload.get("device")
- uart = payload.get("uart")
- outputs = payload.get("outputs")
- motors = payload.get("motors")
- temperature = payload.get("temperature")
- protocol = payload.get("protocol")
- for name, value in (("device", device), ("uart", uart), ("outputs", outputs), ("motors", motors), ("temperature", temperature), ("protocol", protocol)):
- _require(isinstance(value, dict), f"{name} must be an object")
- _require(device["part"] == "EF2L45BG256B" and device["clock_hz"] == 25_000_000, "device constants mismatch")
- _require(uart == {**uart, "baud": 115200, "data_bits": 8, "parity": "N", "stop_bits": 1, "flow_control": "none", "clks_per_bit": 217}, "UART constants mismatch")
- _require(outputs["ptc_count"] == 24 and outputs["fan_count"] == 4 and outputs["pwm_bits"] == 8, "output counts mismatch")
- _require(motors["count"] == 2 and motors["fixed_steps"] == 450 and motors["execution"] == "serial", "motor constants mismatch")
- _require(motors["order"] == ["inlet", "outlet"] and motors["direction_values"] == [0, 1], "motor order mismatch")
- _require(temperature["value_count"] == 27 and temperature["device_addresses"] == [73, 72, 75], "temperature constants mismatch")
- _require(temperature["registers"] == list(range(9)), "temperature register order mismatch")
- _require(protocol["commands"] == {"set_all": 1, "get_temperature": 2, "temperature_data": 130}, "protocol type mismatch")
- _require(protocol["crc"]["polynomial"] == 0x1021 and protocol["crc"]["initial"] == 0xFFFF, "CRC constants mismatch")
- _require(len(payload["pins"]["ptc_pwm"]) == 24 and len(payload["pins"]["fan_pwm"]) == 4, "pin count mismatch")
- return payload
- def project_summary(path: Path) -> dict[str, Any]:
- project = load_project(path)
- ptc_count = project["outputs"]["ptc_count"]
- fan_count = project["outputs"]["fan_count"]
- temperature_count = project["temperature"]["value_count"]
- return {
- "project_id": project["project_id"],
- "profile": project["profile"],
- "uart_clks_per_bit": project["uart"]["clks_per_bit"],
- "set_all_payload_len": ptc_count + fan_count + 2,
- "set_all_frame_len": ptc_count + fan_count + 8,
- "temperature_payload_len": temperature_count,
- "temperature_frame_len": temperature_count + 6,
- "temperature_addresses": tuple(project["temperature"]["device_addresses"]),
- }
- 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"]
- 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_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
- 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_TEMPERATURE_COUNT {temperature['value_count']}",
- f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}",
- 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}",
- ]
- 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 generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
- project = load_project(project_path)
- temperature_count = project["temperature"]["value_count"]
- 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"],
- "commands": {
- "set_all": {"type": "0x01", "payload_length": summary["set_all_payload_len"], "response": "none"},
- "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"]},
- },
- "crc": project["protocol"]["crc"],
- "motors": project["motors"],
- "temperature": project["temperature"],
- }
- _write_json(output / "host-contract.json", contract)
- _write_json(output / "project-summary.json", summary)
- _write_json(
- output / "golden-vectors.json",
- {
- "get_temperature": _frame_hex(0x02, b""),
- "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * temperature_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",
- },
- )
- 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())
|