generate_project.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #!/usr/bin/env python3
  2. """Validate a project.json and emit deterministic compile-time artifacts."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import re
  7. from pathlib import Path
  8. from typing import Any, Mapping
  9. PROFILE = "prod2u-normal-multiproject-115200-v1"
  10. ACTIVE_SOURCE_PATHS = (
  11. "src/generated/prod2u_door_temp_params.vh",
  12. "src/common/uart_rx_byte.v",
  13. "src/common/uart_tx_byte.v",
  14. "src/common/crc16_serial.v",
  15. "src/common/frame_rx.v",
  16. "src/common/frame_tx.v",
  17. "src/common/payload_ram.v",
  18. "src/modules/output_target_ram.v",
  19. "src/modules/pwm_scheduler.v",
  20. "src/modules/door_motor_engine.v",
  21. "src/modules/i2c_word_reader.v",
  22. "src/modules/temperature_reader.v",
  23. "src/modules/temperature_ram.v",
  24. "src/project/command_controller.v",
  25. "src/project/project_adapter.v",
  26. "src/rtl/prod2u_por.v",
  27. "src/rtl/prod2u_p4_i2c_stop_start_read.v",
  28. "src/top/prod2u_p4_normal_v3_top.v",
  29. )
  30. def _require(condition: bool, message: str) -> None:
  31. if not condition:
  32. raise ValueError(message)
  33. def load_project(path: Path) -> dict[str, Any]:
  34. project_path = Path(path)
  35. payload = json.loads(project_path.read_text(encoding="utf-8"))
  36. _require(isinstance(payload, dict), "project root must be an object")
  37. _require(re.fullmatch(r"[a-z0-9-]+", str(payload.get("project_id", ""))) is not None, "invalid project_id")
  38. _require(payload.get("profile") == PROFILE, "unsupported project profile")
  39. device = payload.get("device")
  40. uart = payload.get("uart")
  41. outputs = payload.get("outputs")
  42. motors = payload.get("motors")
  43. temperature = payload.get("temperature")
  44. protocol = payload.get("protocol")
  45. for name, value in (("device", device), ("uart", uart), ("outputs", outputs), ("motors", motors), ("temperature", temperature), ("protocol", protocol)):
  46. _require(isinstance(value, dict), f"{name} must be an object")
  47. _require(device["part"] == "EF2L45BG256B" and device["clock_hz"] == 25_000_000, "device constants mismatch")
  48. _require(uart == {**uart, "baud": 115200, "data_bits": 8, "parity": "N", "stop_bits": 1, "flow_control": "none", "clks_per_bit": 217}, "UART constants mismatch")
  49. _require(outputs["ptc_count"] == 24 and outputs["fan_count"] == 4 and outputs["pwm_bits"] == 8, "output counts mismatch")
  50. _require(motors["count"] == 2 and motors["fixed_steps"] == 450 and motors["execution"] == "serial", "motor constants mismatch")
  51. _require(motors["order"] == ["inlet", "outlet"] and motors["direction_values"] == [0, 1], "motor order mismatch")
  52. _require(temperature["value_count"] == 27 and temperature["device_addresses"] == [73, 72, 75], "temperature constants mismatch")
  53. _require(temperature["registers"] == list(range(9)), "temperature register order mismatch")
  54. _require(protocol["commands"] == {"set_all": 1, "get_temperature": 2, "temperature_data": 130}, "protocol type mismatch")
  55. _require(protocol["crc"]["polynomial"] == 0x1021 and protocol["crc"]["initial"] == 0xFFFF, "CRC constants mismatch")
  56. _require(len(payload["pins"]["ptc_pwm"]) == 24 and len(payload["pins"]["fan_pwm"]) == 4, "pin count mismatch")
  57. return payload
  58. def project_summary(path: Path) -> dict[str, Any]:
  59. project = load_project(path)
  60. ptc_count = project["outputs"]["ptc_count"]
  61. fan_count = project["outputs"]["fan_count"]
  62. temperature_count = project["temperature"]["value_count"]
  63. return {
  64. "project_id": project["project_id"],
  65. "profile": project["profile"],
  66. "uart_clks_per_bit": project["uart"]["clks_per_bit"],
  67. "set_all_payload_len": ptc_count + fan_count + 2,
  68. "set_all_frame_len": ptc_count + fan_count + 8,
  69. "temperature_payload_len": temperature_count,
  70. "temperature_frame_len": temperature_count + 6,
  71. "temperature_addresses": tuple(project["temperature"]["device_addresses"]),
  72. }
  73. def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
  74. path.parent.mkdir(parents=True, exist_ok=True)
  75. path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  76. def _crc16_ccitt_false(data: bytes) -> int:
  77. crc = 0xFFFF
  78. for value in data:
  79. crc ^= value << 8
  80. for _ in range(8):
  81. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  82. return crc
  83. def _frame_hex(frame_type: int, payload: bytes) -> str:
  84. body = bytes((frame_type, len(payload))) + payload
  85. crc = _crc16_ccitt_false(body)
  86. return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper()
  87. def _render_params(project: Mapping[str, Any]) -> str:
  88. outputs = project["outputs"]
  89. motors = project["motors"]
  90. temperature = project["temperature"]
  91. uart = project["uart"]
  92. lines = [
  93. "// Generated from project.json. Do not edit.",
  94. f"`define P4_CLOCK_HZ {project['device']['clock_hz']}",
  95. f"`define P4_UART_BAUD {uart['baud']}",
  96. f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}",
  97. f"`define P4_PTC_COUNT {outputs['ptc_count']}",
  98. f"`define P4_FAN_COUNT {outputs['fan_count']}",
  99. f"`define P4_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
  100. f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}",
  101. f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
  102. f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}",
  103. f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}",
  104. f"`define P4_TEMP_MAX_CELSIUS {temperature['maximum_celsius']}",
  105. f"`define P4_PTC_ACTIVE_HIGH {1 if outputs['ptc_polarity'] == 'active_high' else 0}",
  106. f"`define P4_FAN_ACTIVE_HIGH {1 if outputs['fan_polarity'] == 'active_high' else 0}",
  107. ]
  108. lines.extend(
  109. f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}"
  110. for index, address in enumerate(temperature["device_addresses"])
  111. )
  112. lines.extend(
  113. f"`define P4_TEMP_REGISTER_{index} 8'h{register:02X}"
  114. for index, register in enumerate(temperature["registers"])
  115. )
  116. lines.append("")
  117. return "\n".join(lines)
  118. def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
  119. project = load_project(project_path)
  120. temperature_count = project["temperature"]["value_count"]
  121. output = Path(output_root) / "generated"
  122. output.mkdir(parents=True, exist_ok=True)
  123. (output / f"{project['project_id'].replace('-', '_')}_params.vh").write_text(_render_params(project), encoding="ascii", newline="\n")
  124. summary = project_summary(project_path)
  125. contract = {
  126. "schema": "prod2u-simple-host-contract-v1",
  127. "project_id": project["project_id"],
  128. "uart": project["uart"],
  129. "commands": {
  130. "set_all": {"type": "0x01", "payload_length": summary["set_all_payload_len"], "response": "none"},
  131. "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
  132. "temperature_data": {"type": "0x82", "payload_length": summary["temperature_payload_len"], "frame_length": summary["temperature_frame_len"]},
  133. },
  134. "crc": project["protocol"]["crc"],
  135. "motors": project["motors"],
  136. "temperature": project["temperature"],
  137. }
  138. _write_json(output / "host-contract.json", contract)
  139. _write_json(output / "project-summary.json", summary)
  140. _write_json(
  141. output / "golden-vectors.json",
  142. {
  143. "get_temperature": _frame_hex(0x02, b""),
  144. "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * temperature_count)),
  145. },
  146. )
  147. _write_json(
  148. output / "td-source-manifest.json",
  149. {
  150. "schema": "prod2u-simple-source-manifest-template-v1",
  151. "project_id": project["project_id"],
  152. "sources": list(ACTIVE_SOURCE_PATHS),
  153. "generated_from": "project.json",
  154. },
  155. )
  156. return summary
  157. def main() -> int:
  158. parser = argparse.ArgumentParser()
  159. parser.add_argument("project", type=Path)
  160. parser.add_argument("output", type=Path)
  161. args = parser.parse_args()
  162. generate_project(args.project, args.output)
  163. return 0
  164. if __name__ == "__main__":
  165. raise SystemExit(main())