generate_project.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. #!/usr/bin/env python3
  2. """Validate a project configuration and emit deterministic contract 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. from jsonschema import Draft202012Validator
  10. PROFILE = "prod2u-normal-multiproject-115200-v1"
  11. SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schemas" / "project.schema.json"
  12. SOURCE_CLOSURE_PATH = Path(__file__).resolve().parents[1] / "config" / "source_closure.json"
  13. _TOP_LEVEL_KEYS = {
  14. "project_id",
  15. "profile",
  16. "display_name",
  17. "device",
  18. "uart",
  19. "outputs",
  20. "doors",
  21. "motors",
  22. "limits",
  23. "temperature",
  24. "pins",
  25. "resource_policy",
  26. "protocol",
  27. "timeouts",
  28. "watchdog",
  29. }
  30. def _require(condition: bool, message: str) -> None:
  31. if not condition:
  32. raise ValueError(message)
  33. def _load_source_closure() -> tuple[str, ...]:
  34. payload = json.loads(SOURCE_CLOSURE_PATH.read_text(encoding="utf-8"))
  35. _require(isinstance(payload, Mapping), "source closure root must be an object")
  36. _require(payload.get("schema") == "prod2u-source-closure-v1", "source closure schema mismatch")
  37. _require(payload.get("project_id") == "prod2u-door-temp", "source closure project_id mismatch")
  38. sources = payload.get("sources")
  39. _require(isinstance(sources, list) and sources, "source closure must contain a non-empty sources list")
  40. normalized = []
  41. for value in sources:
  42. _require(isinstance(value, str) and value, "source closure entry must be a non-empty string")
  43. parts = Path(value).parts
  44. _require(".." not in parts and not Path(value).is_absolute(), "source closure entry must be a relative safe path")
  45. normalized.append(value)
  46. _require(len(normalized) == len(set(normalized)), "source closure contains duplicate paths")
  47. missing = [path for path in normalized if not (SOURCE_CLOSURE_PATH.parents[1] / path).is_file()]
  48. _require(not missing, f"source closure references missing files: {missing}")
  49. return tuple(normalized)
  50. ACTIVE_SOURCE_PATHS = _load_source_closure()
  51. def _object(value: Any, name: str) -> Mapping[str, Any]:
  52. _require(isinstance(value, dict), f"{name} must be an object")
  53. return value
  54. def _keys(value: Mapping[str, Any], expected: set[str], name: str) -> None:
  55. _require(set(value) == expected, f"{name} keys mismatch")
  56. def _integer(value: Any, name: str, *, minimum: int | None = None) -> None:
  57. _require(isinstance(value, int) and not isinstance(value, bool), f"{name} must be an integer")
  58. if minimum is not None:
  59. _require(value >= minimum, f"{name} is below the minimum")
  60. def _number(value: Any, name: str) -> None:
  61. _require(isinstance(value, (int, float)) and not isinstance(value, bool), f"{name} must be numeric")
  62. def _list(value: Any, name: str, length: int | None = None) -> list[Any]:
  63. _require(isinstance(value, list), f"{name} must be an array")
  64. if length is not None:
  65. _require(len(value) == length, f"{name} must contain {length} items")
  66. return value
  67. def _axis_mask_literal(values: list[Any], axis_count: int) -> str:
  68. """Build AXIS_COUNT'b... with bit0=X (LSB / rightmost), index0=X,1=Y,2=Z."""
  69. _require(len(values) == axis_count, "axis mask length mismatch")
  70. bits_lsb_first: list[str] = []
  71. for value in values:
  72. if isinstance(value, bool):
  73. bits_lsb_first.append("1" if value else "0")
  74. else:
  75. bits_lsb_first.append("1" if int(value) else "0")
  76. return f"{axis_count}'b" + "".join(reversed(bits_lsb_first))
  77. def _validate_channel(channel: Any, index: int, kind: str) -> None:
  78. item = _object(channel, f"{kind}_channels[{index}]")
  79. _keys(item, {"index", "name", "signal", "board_signal", "ball", "connector", "connector_pin", "polarity"}, f"{kind}_channels[{index}]")
  80. _require(item["index"] == index, f"{kind} channel index mismatch at {index}")
  81. _require(item["name"] == f"{kind}{index + 1}", f"{kind} channel name mismatch at {index}")
  82. _require(item["signal"] == f"{kind}_pwm_out[{index}]", f"{kind} channel signal mismatch at {index}")
  83. _require(isinstance(item["board_signal"], str) and item["board_signal"], f"invalid {kind} board signal at {index}")
  84. _require(item["polarity"] in {"active_high", "active_low"}, f"invalid {kind} polarity at {index}")
  85. _require(re.fullmatch(r"[A-Z][0-9]+", str(item["ball"])) is not None, f"invalid {kind} ball at {index}")
  86. _require(re.fullmatch(r"CON[0-9]+", str(item["connector"])) is not None, f"invalid {kind} connector at {index}")
  87. _integer(item["connector_pin"], f"{kind} channel connector pin", minimum=1)
  88. def _validate_project(payload: Mapping[str, Any]) -> None:
  89. _keys(payload, _TOP_LEVEL_KEYS, "project")
  90. _require(re.fullmatch(r"[a-z0-9-]+", str(payload["project_id"])) is not None, "invalid project_id")
  91. _require(isinstance(payload["profile"], str) and payload["profile"], "invalid project profile")
  92. _require(isinstance(payload["display_name"], str) and payload["display_name"], "invalid display_name")
  93. device = _object(payload["device"], "device")
  94. _keys(device, {"family", "part", "clock_hz", "clock_ball"}, "device")
  95. _require(isinstance(device["family"], str) and device["family"], "invalid device family")
  96. _require(isinstance(device["part"], str) and device["part"], "invalid device part")
  97. _integer(device["clock_hz"], "device.clock_hz", minimum=1)
  98. _require(re.fullmatch(r"[A-Z][0-9]+", str(device["clock_ball"])) is not None, "invalid clock ball")
  99. uart = _object(payload["uart"], "uart")
  100. _keys(uart, {"baud", "data_bits", "parity", "stop_bits", "flow_control", "clks_per_bit", "inter_byte_timeout_ms", "rx_ball", "tx_ball"}, "uart")
  101. _integer(uart["baud"], "uart.baud", minimum=1)
  102. _integer(uart["data_bits"], "uart.data_bits", minimum=1)
  103. _integer(uart["stop_bits"], "uart.stop_bits", minimum=1)
  104. _integer(uart["clks_per_bit"], "uart.clks_per_bit", minimum=1)
  105. _require(uart["parity"] in {"N", "E", "O"}, "invalid UART parity")
  106. _require(isinstance(uart["flow_control"], str), "invalid UART flow control")
  107. _integer(uart["inter_byte_timeout_ms"], "uart.inter_byte_timeout_ms", minimum=1)
  108. outputs = _object(payload["outputs"], "outputs")
  109. _keys(
  110. outputs,
  111. {
  112. "ptc_count",
  113. "fan_count",
  114. "chamber_ptc_count",
  115. "chamber_ptc_pairs",
  116. "ptc_channels",
  117. "fan_channels",
  118. "pwm_bits",
  119. "pwm_internal_width",
  120. "pwm_max_duty",
  121. "pwm_phase_count",
  122. "pwm_slot_clks",
  123. "pwm_frequency_hz",
  124. "pwm_actual_frequency_hz",
  125. "ptc_polarity",
  126. "fan_polarity",
  127. "ptc_default",
  128. "fan_default",
  129. "fan_connector_active_level",
  130. "fan_board_inverts",
  131. "boot_targets",
  132. },
  133. "outputs",
  134. )
  135. _integer(outputs["ptc_count"], "outputs.ptc_count", minimum=1)
  136. _integer(outputs["fan_count"], "outputs.fan_count", minimum=1)
  137. _require(outputs["ptc_count"] == len(outputs["ptc_channels"]), "PTC count/list mismatch")
  138. _require(outputs["fan_count"] == len(outputs["fan_channels"]), "FAN count/list mismatch")
  139. _integer(outputs["chamber_ptc_count"], "outputs.chamber_ptc_count", minimum=1)
  140. chamber_pairs = _list(outputs["chamber_ptc_pairs"], "outputs.chamber_ptc_pairs", outputs["chamber_ptc_count"])
  141. for index, pair in enumerate(chamber_pairs):
  142. item = _object(pair, f"outputs.chamber_ptc_pairs[{index}]")
  143. _keys(item, {"chamber", "ptc_indices"}, f"outputs.chamber_ptc_pairs[{index}]")
  144. _require(item["chamber"] == index + 1, "chamber index mismatch in chamber_ptc_pairs")
  145. indices = _list(item["ptc_indices"], f"outputs.chamber_ptc_pairs[{index}].ptc_indices", 2)
  146. _require(all(isinstance(value, int) and 0 <= value < outputs["ptc_count"] for value in indices), "invalid PTC pair indices")
  147. _require(indices[0] + 1 == indices[1], "PTC pair indices must be adjacent")
  148. for index, channel in enumerate(outputs["ptc_channels"]):
  149. _validate_channel(channel, index, "ptc")
  150. for index, channel in enumerate(outputs["fan_channels"]):
  151. _validate_channel(channel, index, "fan")
  152. _integer(outputs["pwm_bits"], "outputs.pwm_bits", minimum=1)
  153. _integer(outputs["pwm_internal_width"], "outputs.pwm_internal_width", minimum=1)
  154. _integer(outputs["pwm_max_duty"], "outputs.pwm_max_duty", minimum=0)
  155. _require(outputs["pwm_max_duty"] < (1 << outputs["pwm_bits"]), "PWM maximum exceeds protocol width")
  156. _integer(outputs["pwm_phase_count"], "outputs.pwm_phase_count", minimum=1)
  157. _integer(outputs["pwm_slot_clks"], "outputs.pwm_slot_clks", minimum=1)
  158. _number(outputs["pwm_frequency_hz"], "outputs.pwm_frequency_hz")
  159. _number(outputs["pwm_actual_frequency_hz"], "outputs.pwm_actual_frequency_hz")
  160. _require(outputs["ptc_polarity"] == "active_high" and outputs["fan_polarity"] == "active_low", "PWM polarity mismatch")
  161. _require(0 <= outputs["ptc_default"] <= outputs["pwm_max_duty"], "invalid PTC boot target")
  162. _require(0 <= outputs["fan_default"] <= outputs["pwm_max_duty"], "invalid FAN boot target")
  163. _require(outputs["fan_connector_active_level"] == "high" and outputs["fan_board_inverts"] is True, "FAN board metadata mismatch")
  164. boot_targets = _object(outputs["boot_targets"], "outputs.boot_targets")
  165. _keys(boot_targets, {"ptc", "fan"}, "outputs.boot_targets")
  166. _require(boot_targets == {"ptc": 0, "fan": 10}, "boot target mapping mismatch")
  167. doors = _object(payload["doors"], "doors")
  168. _keys(doors, {"scope", "chamber_controlled", "door_axes"}, "doors")
  169. door_axes = _list(doors["door_axes"], "doors.door_axes", 3)
  170. _require(door_axes == ["x", "y", "z"], "door_axes must be x,y,z")
  171. motors = _object(payload["motors"], "motors")
  172. _keys(
  173. motors,
  174. {
  175. "count",
  176. "order",
  177. "role",
  178. "fixed_steps",
  179. "execution",
  180. "busy_wait_ms",
  181. "step_rate_hz",
  182. "step_half_cycles",
  183. "dir_setup_cycles",
  184. "command_values",
  185. "heartbeat_value",
  186. "open_dir_value",
  187. "close_dir_value",
  188. "dir_close_level",
  189. "mapping",
  190. "enable_n",
  191. },
  192. "motors",
  193. )
  194. _integer(motors["count"], "motors.count", minimum=1)
  195. _require(len(motors["order"]) == motors["count"] and all(isinstance(axis, str) and axis for axis in motors["order"]), "motor order mismatch")
  196. _require(isinstance(motors["role"], str) and motors["role"], "invalid motor role")
  197. _require(motors["execution"] in {"overlap", "serial"}, "invalid motor execution")
  198. _integer(motors["busy_wait_ms"], "motors.busy_wait_ms", minimum=0)
  199. _integer(motors["fixed_steps"], "motors.fixed_steps", minimum=1)
  200. _integer(motors["step_rate_hz"], "motors.step_rate_hz", minimum=1)
  201. _integer(motors["step_half_cycles"], "motors.step_half_cycles", minimum=1)
  202. _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0)
  203. _require(isinstance(motors["command_values"], list) and motors["command_values"], "invalid motor commands")
  204. _require(motors["heartbeat_value"] in motors["command_values"], "motor heartbeat is not a command")
  205. _integer(motors["open_dir_value"], "motors.open_dir_value", minimum=0)
  206. _integer(motors["close_dir_value"], "motors.close_dir_value", minimum=0)
  207. _require(motors["open_dir_value"] == 0, "logical open_dir_value must be 0")
  208. _require(motors["close_dir_value"] == 1, "logical close_dir_value must be 1")
  209. dir_close_level = _list(motors["dir_close_level"], "motors.dir_close_level", length=motors["count"])
  210. for index, level in enumerate(dir_close_level):
  211. _require(isinstance(level, int) and not isinstance(level, bool) and level in (0, 1),
  212. f"motors.dir_close_level[{index}] must be 0 or 1")
  213. # Per-axis dir_close_level is the sole authority; mixed 0/1 configs are allowed.
  214. mapping = _object(motors["mapping"], "motors.mapping")
  215. _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z")
  216. _keys(mapping, {"x", "y", "z"}, "motors.mapping")
  217. for axis in ("x", "y", "z"):
  218. item = _object(mapping[axis], f"motors.mapping.{axis}")
  219. required = {"axis", "role", "step_ball", "dir_ball"}
  220. _require(required <= set(item), f"motors.mapping.{axis} missing required keys")
  221. _require(item["axis"] == axis and item["role"] == "door", f"motor {axis} role mismatch")
  222. enable = _object(motors["enable_n"], "motors.enable_n")
  223. _require({"ball", "active_level", "policy"} <= set(enable), "motors.enable_n missing required keys")
  224. _require(isinstance(enable["ball"], str) and enable["ball"], "invalid motor enable ball")
  225. _require(enable["active_level"] == "low", "motor enable must be active low")
  226. _require(enable["policy"] == "permanent_high", "motor enable policy must be permanent_high")
  227. limits = _object(payload["limits"], "limits")
  228. _keys(
  229. limits,
  230. {
  231. "limit_count",
  232. "active_level",
  233. "limit_active_high",
  234. "close_limit_is_ls",
  235. "functional_use",
  236. "runtime_use",
  237. "startup",
  238. "channels",
  239. },
  240. "limits",
  241. )
  242. _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch")
  243. # limits.active_level is legacy / deprecated / non-authoritative. Accept the
  244. # historical string enum only; do not bind it to per-axis arrays or RTL masks.
  245. _require(
  246. limits["active_level"] in ("high", "low") and limits["functional_use"] is True,
  247. "limits.active_level must be legacy enum high|low and functional_use true",
  248. )
  249. _require(limits["runtime_use"] is True, "runtime limit use must be true")
  250. limit_active_high = _list(limits["limit_active_high"], "limits.limit_active_high", length=motors["count"])
  251. for index, active_high in enumerate(limit_active_high):
  252. _require(isinstance(active_high, bool), f"limits.limit_active_high[{index}] must be a boolean")
  253. close_limit_is_ls = _list(limits["close_limit_is_ls"], "limits.close_limit_is_ls", length=motors["count"])
  254. for index, close_is_ls in enumerate(close_limit_is_ls):
  255. _require(isinstance(close_is_ls, bool), f"limits.close_limit_is_ls[{index}] must be a boolean")
  256. # Per-axis limit_active_high / close_limit_is_ls / dir_close_level alone decide
  257. # generated masks. Mixed-axis configs must not force active_level sync.
  258. startup = _object(limits["startup"], "limits.startup")
  259. _keys(
  260. startup,
  261. {
  262. "enabled",
  263. "direction_value",
  264. "direction_meaning",
  265. "close_step_count",
  266. "backoff_step_count",
  267. "step_rate_hz",
  268. "axis_order",
  269. "limit_stop_during_move",
  270. "stop_semantics",
  271. "additional_rising_edges_after_synchronized_limit",
  272. "runtime_limit_use",
  273. },
  274. "limits.startup",
  275. )
  276. _require(startup["enabled"] is True, "startup must be enabled")
  277. _require(startup["direction_meaning"] == "close", "startup direction must be close")
  278. _require(startup["limit_stop_during_move"] is True, "startup limit stop during move must be enabled")
  279. _require(
  280. startup["stop_semantics"] == "truncate_current_high_pulse_immediately_after_synchronized_limit",
  281. "unsupported stop semantics",
  282. )
  283. _require(startup["additional_rising_edges_after_synchronized_limit"] == 0, "additional rising edges after limit must be zero")
  284. _require(startup["runtime_limit_use"] is True, "startup runtime limit use must be true")
  285. _integer(startup["direction_value"], "limits.startup.direction_value", minimum=0)
  286. _integer(startup["close_step_count"], "limits.startup.close_step_count", minimum=1)
  287. _integer(startup["backoff_step_count"], "limits.startup.backoff_step_count", minimum=0)
  288. _integer(startup["step_rate_hz"], "limits.startup.step_rate_hz", minimum=1)
  289. _require(startup["close_step_count"] == 5000, "startup close step count must be 5000")
  290. _require(startup["backoff_step_count"] == 500, "startup backoff step count must be 500")
  291. _require(len(startup["axis_order"]) == 3 and startup["axis_order"] == ["x", "y", "z"], "startup axis order mismatch")
  292. expected_limit_names = [
  293. "x_limit_ls",
  294. "x_limit_hs",
  295. "y_limit_ls",
  296. "y_limit_hs",
  297. "z_limit_ls",
  298. "z_limit_hs",
  299. ]
  300. for index, item in enumerate(limits["channels"]):
  301. entry = _object(item, f"limits.channels[{index}]")
  302. _keys(entry, {"name", "ball", "connector", "connector_pin", "side"}, f"limits.channels[{index}]")
  303. _require(entry["name"] == expected_limit_names[index], "invalid limit channel order/name")
  304. temperature = _object(payload["temperature"], "temperature")
  305. _keys(
  306. temperature,
  307. {
  308. "value_count",
  309. "device_addresses",
  310. "registers",
  311. "scl_ball",
  312. "sda_ball",
  313. "bus",
  314. "device",
  315. "invalid_value",
  316. "maximum_celsius",
  317. "conversion",
  318. },
  319. "temperature",
  320. )
  321. _integer(temperature["value_count"], "temperature.value_count", minimum=1)
  322. _require(temperature["value_count"] == len(temperature["device_addresses"]) * len(temperature["registers"]), "temperature count/list mismatch")
  323. _require(all(isinstance(value, int) and 0 <= value < 128 for value in temperature["device_addresses"]), "invalid temperature address")
  324. _require(all(isinstance(value, int) and 0 <= value <= 255 for value in temperature["registers"]), "invalid temperature register")
  325. _require(isinstance(temperature["device"], str) and temperature["device"], "invalid temperature device")
  326. _integer(temperature["invalid_value"], "temperature.invalid_value", minimum=0)
  327. _require(temperature["invalid_value"] <= 255, "temperature.invalid_value exceeds byte")
  328. _integer(temperature["maximum_celsius"], "temperature.maximum_celsius", minimum=0)
  329. conversion = _object(temperature["conversion"], "temperature.conversion")
  330. _keys(conversion, {"profile", "raw_shift", "raw_width", "reject_sign_bit"}, "temperature.conversion")
  331. _require(conversion == {"profile": "ct7428-msb-integer", "raw_shift": 7, "raw_width": 9, "reject_sign_bit": True}, "temperature conversion mismatch")
  332. pins = _object(payload["pins"], "pins")
  333. _keys(
  334. pins,
  335. {
  336. "host_uart_rx",
  337. "host_uart_tx",
  338. "temp_scl",
  339. "temp_sda",
  340. "ptc_pwm",
  341. "fan_pwm",
  342. "motor_en_n",
  343. "x_step",
  344. "x_dir",
  345. "y_step",
  346. "y_dir",
  347. "z_step",
  348. "z_dir",
  349. "x_limit_ls",
  350. "x_limit_hs",
  351. "y_limit_ls",
  352. "y_limit_hs",
  353. "z_limit_ls",
  354. "z_limit_hs",
  355. },
  356. "pins",
  357. )
  358. _require(pins["host_uart_rx"] == uart["rx_ball"] and pins["host_uart_tx"] == uart["tx_ball"], "UART pin duplication mismatch")
  359. _require(pins["temp_scl"] == temperature["scl_ball"] and pins["temp_sda"] == temperature["sda_ball"], "I2C pin duplication mismatch")
  360. _require(pins["ptc_pwm"] == [item["ball"] for item in outputs["ptc_channels"]], "PTC pin/list mismatch")
  361. _require(
  362. pins["fan_pwm"] == [item["ball"] for item in outputs["fan_channels"]],
  363. "FAN pin/list mismatch",
  364. )
  365. _require(pins["motor_en_n"] == enable["ball"], "motor enable pin mismatch")
  366. for axis in ("x", "y", "z"):
  367. _require(pins[f"{axis}_step"] == mapping[axis]["step_ball"], f"{axis} step pin mismatch")
  368. _require(pins[f"{axis}_dir"] == mapping[axis]["dir_ball"], f"{axis} dir pin mismatch")
  369. for channel in limits["channels"]:
  370. _require(pins[channel["name"]] == channel["ball"], f"{channel['name']} pin mismatch")
  371. resources = _object(payload["resource_policy"], "resource_policy")
  372. _keys(
  373. resources,
  374. {
  375. "target_ram",
  376. "request_ram",
  377. "temperature_ram",
  378. "dsp",
  379. "shared_pwm_comparators",
  380. "shared_motor_executors",
  381. "shared_i2c_readers",
  382. },
  383. "resource_policy",
  384. )
  385. for key, value in resources.items():
  386. if key in {"target_ram", "request_ram", "temperature_ram"}:
  387. _require(
  388. value in {"optional", "required", "forbidden"},
  389. f"resource_policy.{key} must be optional, required, or forbidden",
  390. )
  391. else:
  392. _integer(value, f"resource_policy.{key}", minimum=0)
  393. protocol = _object(payload["protocol"], "protocol")
  394. _keys(protocol, {"header_hex", "crc", "commands", "set_all", "temperature_data"}, "protocol")
  395. _require(isinstance(protocol["header_hex"], str) and protocol["header_hex"], "frame header missing")
  396. crc = _object(protocol["crc"], "protocol.crc")
  397. _keys(crc, {"name", "polynomial", "initial", "reflect_input", "reflect_output", "xor_output", "coverage", "wire_order"}, "protocol.crc")
  398. _require(
  399. crc
  400. == {
  401. "name": "CRC-16/CCITT-FALSE",
  402. "polynomial": 0x1021,
  403. "initial": 0xFFFF,
  404. "reflect_input": False,
  405. "reflect_output": False,
  406. "xor_output": 0,
  407. "coverage": "type_length_payload",
  408. "wire_order": "little",
  409. },
  410. "CRC contract mismatch",
  411. )
  412. _require(set(protocol["commands"]) == {"set_all", "get_temperature", "temperature_data"}, "protocol command keys mismatch")
  413. set_all = _object(protocol["set_all"], "protocol.set_all")
  414. _keys(
  415. set_all,
  416. {
  417. "payload_length",
  418. "fan_offset",
  419. "chamber_ptc_offset",
  420. "chamber_ptc_count",
  421. "z_door_offset",
  422. "exhaust_x_offset",
  423. "exhaust_y_offset",
  424. "legacy_payload_length_rejected",
  425. "duty_min",
  426. "duty_max",
  427. "door_values",
  428. "response",
  429. },
  430. "protocol.set_all",
  431. )
  432. _require(set_all["fan_offset"] == 0, "SET_ALL FAN offset mismatch")
  433. _require(set_all["chamber_ptc_offset"] == outputs["fan_count"], "SET_ALL chamber PTC offset mismatch")
  434. _require(set_all["chamber_ptc_count"] == outputs["chamber_ptc_count"], "SET_ALL chamber PTC count mismatch")
  435. _require(set_all["z_door_offset"] == set_all["chamber_ptc_offset"] + set_all["chamber_ptc_count"], "SET_ALL Z offset mismatch")
  436. _require(set_all["exhaust_x_offset"] == set_all["z_door_offset"] + 1, "SET_ALL exhaust X offset mismatch")
  437. _require(set_all["exhaust_y_offset"] == set_all["exhaust_x_offset"] + 1, "SET_ALL exhaust Y offset mismatch")
  438. _require(set_all["payload_length"] == set_all["exhaust_y_offset"] + 1, "SET_ALL length mismatch")
  439. _require(set_all["legacy_payload_length_rejected"] == 14, "legacy payload length marker mismatch")
  440. _require(set_all["duty_min"] <= set_all["duty_max"], "SET_ALL duty range mismatch")
  441. _require(set_all["door_values"] == motors["command_values"], "SET_ALL door values mismatch")
  442. temperature_data = _object(protocol["temperature_data"], "protocol.temperature_data")
  443. _keys(temperature_data, {"payload_length", "frame_length"}, "protocol.temperature_data")
  444. _require(temperature_data["payload_length"] == temperature["value_count"], "temperature payload length mismatch")
  445. _require(temperature_data["frame_length"] == temperature_data["payload_length"] + 6, "temperature frame length mismatch")
  446. timeouts = _object(payload["timeouts"], "timeouts")
  447. _keys(timeouts, {"frame_inter_byte_ms", "host_get_response_ms"}, "timeouts")
  448. _integer(timeouts["frame_inter_byte_ms"], "timeouts.frame_inter_byte_ms", minimum=1)
  449. _integer(timeouts["host_get_response_ms"], "timeouts.host_get_response_ms", minimum=1)
  450. watchdog = _object(payload["watchdog"], "watchdog")
  451. _keys(watchdog, {"timeout_seconds", "tick_us", "tick_clks", "timeout_ticks", "target"}, "watchdog")
  452. _integer(watchdog["timeout_seconds"], "watchdog.timeout_seconds", minimum=1)
  453. _integer(watchdog["tick_us"], "watchdog.tick_us", minimum=1)
  454. _integer(watchdog["tick_clks"], "watchdog.tick_clks", minimum=1)
  455. _require(watchdog["tick_clks"] == device["clock_hz"] * watchdog["tick_us"] // 1_000_000, "watchdog tick clock mismatch")
  456. _integer(watchdog["timeout_ticks"], "watchdog.timeout_ticks", minimum=1)
  457. _require(watchdog["timeout_ticks"] == watchdog["timeout_seconds"] * 1_000_000 // watchdog["tick_us"], "watchdog tick count mismatch")
  458. target = _object(watchdog["target"], "watchdog.target")
  459. _keys(target, {"ptc", "fan"}, "watchdog.target")
  460. _require(target == {"ptc": 0, "fan": 20}, "watchdog target mismatch")
  461. def load_project(path: Path) -> dict[str, Any]:
  462. project_path = Path(path)
  463. payload = json.loads(project_path.read_text(encoding="utf-8"))
  464. _require(isinstance(payload, dict), "project root must be an object")
  465. schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
  466. errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda error: list(error.absolute_path))
  467. if errors:
  468. location = ".".join(str(part) for part in errors[0].absolute_path) or "project"
  469. raise ValueError(f"project schema violation at {location}: {errors[0].message}")
  470. _validate_project(payload)
  471. return payload
  472. def _active_interface(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]:
  473. outputs = project["outputs"]
  474. pins = project["pins"]
  475. motors = project["motors"]
  476. interface = (
  477. ("sys_clk", project["device"]["clock_ball"]),
  478. ("host_uart_rx", pins["host_uart_rx"]),
  479. ("host_uart_tx", pins["host_uart_tx"]),
  480. ("temp_scl", pins["temp_scl"]),
  481. ("temp_sda", pins["temp_sda"]),
  482. *tuple((item["signal"], item["ball"]) for item in outputs["ptc_channels"]),
  483. *tuple((item["signal"], item["ball"]) for item in outputs["fan_channels"]),
  484. ("motor_en_n", pins["motor_en_n"]),
  485. ("x_step", motors["mapping"]["x"]["step_ball"]),
  486. ("x_dir", motors["mapping"]["x"]["dir_ball"]),
  487. ("y_step", motors["mapping"]["y"]["step_ball"]),
  488. ("y_dir", motors["mapping"]["y"]["dir_ball"]),
  489. ("z_step", motors["mapping"]["z"]["step_ball"]),
  490. ("z_dir", motors["mapping"]["z"]["dir_ball"]),
  491. *tuple((item["name"], item["ball"]) for item in project["limits"]["channels"]),
  492. )
  493. return interface
  494. def render_adc(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]:
  495. """Return the ordered active interface as (signal, ball) pairs."""
  496. return _active_interface(project)
  497. def project_summary(path: Path) -> dict[str, Any]:
  498. project = load_project(path)
  499. outputs = project["outputs"]
  500. temperature = project["temperature"]
  501. watchdog = project["watchdog"]
  502. total_channels = outputs["ptc_count"] + outputs["fan_count"]
  503. pwm_period_clks = outputs["pwm_slot_clks"] * total_channels * outputs["pwm_phase_count"]
  504. actual_frequency_hz = project["device"]["clock_hz"] / pwm_period_clks
  505. frequency_error_percent = abs(actual_frequency_hz - outputs["pwm_frequency_hz"]) / outputs["pwm_frequency_hz"] * 100.0
  506. return {
  507. "project_id": project["project_id"],
  508. "profile": project["profile"],
  509. "uart_clks_per_bit": project["uart"]["clks_per_bit"],
  510. "pwm_bits": outputs["pwm_bits"],
  511. "pwm_internal_width": outputs["pwm_internal_width"],
  512. "pwm_max_duty": outputs["pwm_max_duty"],
  513. "pwm_phase_count": outputs["pwm_phase_count"],
  514. "pwm_frequency_hz": outputs["pwm_frequency_hz"],
  515. "pwm_slot_clks": outputs["pwm_slot_clks"],
  516. "pwm_period_clks": pwm_period_clks,
  517. "pwm_period_seconds": round(pwm_period_clks / project["device"]["clock_hz"], 9),
  518. "actual_frequency_hz": round(actual_frequency_hz, 9),
  519. "frequency_error_percent": round(frequency_error_percent, 9),
  520. "ptc_default": outputs["ptc_default"],
  521. "fan_default": outputs["fan_default"],
  522. "ptc_polarity": outputs["ptc_polarity"],
  523. "fan_polarity": outputs["fan_polarity"],
  524. "fan_connector_active_level": outputs["fan_connector_active_level"],
  525. "fan_board_inverts": outputs["fan_board_inverts"],
  526. "set_all_payload_len": project["protocol"]["set_all"]["payload_length"],
  527. "set_all_frame_len": project["protocol"]["set_all"]["payload_length"] + 6,
  528. "temperature_payload_len": temperature["value_count"],
  529. "temperature_frame_len": temperature["value_count"] + 6,
  530. "temperature_addresses": list(temperature["device_addresses"]),
  531. "boot_targets": dict(outputs["boot_targets"]),
  532. "watchdog_timeout_seconds": watchdog["timeout_seconds"],
  533. "watchdog_tick_clks": watchdog["tick_clks"],
  534. "watchdog_timeout_ticks": watchdog["timeout_ticks"],
  535. "watchdog_target": dict(watchdog["target"]),
  536. }
  537. def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
  538. path.parent.mkdir(parents=True, exist_ok=True)
  539. path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  540. def _crc16_ccitt_false(data: bytes) -> int:
  541. crc = 0xFFFF
  542. for value in data:
  543. crc ^= value << 8
  544. for _ in range(8):
  545. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  546. return crc
  547. def _frame_hex(frame_type: int, payload: bytes) -> str:
  548. body = bytes((frame_type, len(payload))) + payload
  549. crc = _crc16_ccitt_false(body)
  550. return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper()
  551. def _render_params(project: Mapping[str, Any]) -> str:
  552. outputs = project["outputs"]
  553. motors = project["motors"]
  554. limits = project["limits"]
  555. startup = limits["startup"]
  556. temperature = project["temperature"]
  557. uart = project["uart"]
  558. watchdog = project["watchdog"]
  559. axis_count = motors["count"]
  560. _require(motors["dir_setup_cycles"] % watchdog["tick_clks"] == 0, "motor direction setup is not an integral tick count")
  561. motor_dir_setup_ticks = motors["dir_setup_cycles"] // watchdog["tick_clks"]
  562. frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000
  563. startup_dir_bit = startup["direction_value"]
  564. startup_dir_mask = f"{axis_count}'b" + (str(startup_dir_bit) * axis_count)
  565. limit_active_high_mask = _axis_mask_literal(limits["limit_active_high"], axis_count)
  566. dir_close_level_mask = _axis_mask_literal(motors["dir_close_level"], axis_count)
  567. close_limit_is_ls_mask = _axis_mask_literal(limits["close_limit_is_ls"], axis_count)
  568. lines = [
  569. "// Generated from project.json. Do not edit.",
  570. f"`define P4_AXIS_COUNT {axis_count}",
  571. f"`define P4_LIMIT_COUNT {limits['limit_count']}",
  572. f"`define P4_RUNTIME_LIMIT_USE {1 if limits['runtime_use'] else 0}",
  573. f"`define P4_LIMIT_ACTIVE_HIGH_MASK {limit_active_high_mask}",
  574. f"`define P4_DIR_CLOSE_LEVEL_MASK {dir_close_level_mask}",
  575. f"`define P4_CLOSE_LIMIT_IS_LS_MASK {close_limit_is_ls_mask}",
  576. f"`define P4_CLOCK_HZ {project['device']['clock_hz']}",
  577. f"`define P4_UART_BAUD {uart['baud']}",
  578. f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}",
  579. f"`define P4_PTC_COUNT {outputs['ptc_count']}",
  580. f"`define P4_FAN_COUNT {outputs['fan_count']}",
  581. f"`define P4_OUTPUT_CHANNEL_COUNT {outputs['ptc_count'] + outputs['fan_count']}",
  582. f"`define P4_PWM_PROTOCOL_WIDTH {outputs['pwm_bits']}",
  583. f"`define P4_PWM_INTERNAL_WIDTH {outputs['pwm_internal_width']}",
  584. f"`define P4_PWM_MAX_DUTY {outputs['pwm_max_duty']}",
  585. f"`define P4_PWM_PHASE_COUNT {outputs['pwm_phase_count']}",
  586. f"`define P4_PWM_FREQUENCY_HZ {outputs['pwm_frequency_hz']}",
  587. f"`define P4_PWM_SLOT_CLKS {outputs['pwm_slot_clks']}",
  588. f"`define P4_SET_ALL_PAYLOAD_LENGTH {project['protocol']['set_all']['payload_length']}",
  589. f"`define P4_CHAMBER_PTC_COUNT {outputs['chamber_ptc_count']}",
  590. f"`define P4_SET_ALL_FAN_OFFSET {project['protocol']['set_all']['fan_offset']}",
  591. f"`define P4_SET_ALL_CHAMBER_PTC_OFFSET {project['protocol']['set_all']['chamber_ptc_offset']}",
  592. f"`define P4_SET_ALL_Z_DOOR_OFFSET {project['protocol']['set_all']['z_door_offset']}",
  593. f"`define P4_SET_ALL_EXHAUST_X_OFFSET {project['protocol']['set_all']['exhaust_x_offset']}",
  594. f"`define P4_SET_ALL_EXHAUST_Y_OFFSET {project['protocol']['set_all']['exhaust_y_offset']}",
  595. f"`define P4_MOTOR_OPEN_DIR 1'b{motors['open_dir_value']}",
  596. f"`define P4_MOTOR_CLOSE_DIR 1'b{motors['close_dir_value']}",
  597. f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}",
  598. f"`define P4_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
  599. f"`define P4_MOTOR_STEP_RATE_HZ {motors['step_rate_hz']}",
  600. f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}",
  601. f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
  602. f"`define P4_MOTOR_DIR_SETUP_TICKS {motor_dir_setup_ticks}",
  603. f"`define P4_MOTOR_HEARTBEAT_COMMAND 2'd{motors['heartbeat_value']}",
  604. f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}",
  605. f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}",
  606. f"`define P4_TEMPERATURE_FRAME_LENGTH {temperature['value_count'] + 6}",
  607. f"`define P4_TEMP_MAX_CELSIUS {temperature['maximum_celsius']}",
  608. f"`define P4_PTC_ACTIVE_HIGH {1 if outputs['ptc_polarity'] == 'active_high' else 0}",
  609. f"`define P4_FAN_ACTIVE_HIGH {1 if outputs['fan_polarity'] == 'active_high' else 0}",
  610. f"`define P4_PTC_DEFAULT_TARGET 8'h{outputs['ptc_default']:02X}",
  611. f"`define P4_FAN_DEFAULT_TARGET 8'h{outputs['fan_default']:02X}",
  612. f"`define P4_WATCHDOG_TIMEOUT_SECONDS {watchdog['timeout_seconds']}",
  613. f"`define P4_WATCHDOG_TICK_US {watchdog['tick_us']}",
  614. f"`define P4_WATCHDOG_TICK_CLKS {watchdog['tick_clks']}",
  615. f"`define P4_WATCHDOG_TIMEOUT_TICKS {watchdog['timeout_ticks']}",
  616. f"`define P4_WATCHDOG_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}",
  617. f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}",
  618. f"`define P4_STARTUP_ENABLED {1 if startup['enabled'] else 0}",
  619. f"`define P4_STARTUP_DIR_MASK {startup_dir_mask}",
  620. f"`define P4_STARTUP_CLOSE_STEPS {startup['close_step_count']}",
  621. f"`define P4_STARTUP_BACKOFF_STEPS {startup['backoff_step_count']}",
  622. f"`define P4_STARTUP_STEP_RATE_HZ {startup['step_rate_hz']}",
  623. f"`define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH {1 if motors['enable_n']['policy'] == 'permanent_high' else 0}",
  624. ]
  625. lines.extend(
  626. f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}"
  627. for index, address in enumerate(temperature["device_addresses"])
  628. )
  629. lines.extend(
  630. f"`define P4_TEMP_REGISTER_{index} 8'h{register:02X}"
  631. for index, register in enumerate(temperature["registers"])
  632. )
  633. lines.append("")
  634. return "\n".join(lines)
  635. def render_adc_text(project: Mapping[str, Any]) -> str:
  636. lines = [
  637. "# Generated from project.json. Do not edit.",
  638. "# Active interface only; reserved board loads are intentionally absent.",
  639. ]
  640. active_interface = list(render_adc(project))
  641. for signal, ball in active_interface:
  642. lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}")
  643. return "\n".join(lines) + "\n"
  644. def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
  645. project = load_project(project_path)
  646. output = Path(output_root) / "generated"
  647. output.mkdir(parents=True, exist_ok=True)
  648. params_name = f"{project['project_id'].replace('-', '_')}_params.vh"
  649. (output / params_name).write_text(
  650. _render_params(project), encoding="ascii", newline="\n"
  651. )
  652. summary = project_summary(project_path)
  653. contract = {
  654. "schema": "prod2u-simple-host-contract-v1",
  655. "project_id": project["project_id"],
  656. "profile": project["profile"],
  657. "axis_count": project["motors"]["count"],
  658. "limit_count": project["limits"]["limit_count"],
  659. "runtime_limit_use": project["limits"]["runtime_use"],
  660. "uart": project["uart"],
  661. "protocol": project["protocol"],
  662. "commands": {
  663. "set_all": {
  664. "type": "0x01",
  665. "payload_length": summary["set_all_payload_len"],
  666. "response": "none",
  667. "duty_range": [0, 100],
  668. "door_values": [0, 1, 2],
  669. "field_order": [
  670. "fan_chamber_1",
  671. "fan_chamber_2",
  672. "fan_chamber_3",
  673. "fan_chamber_4",
  674. "ptc_chamber_1",
  675. "ptc_chamber_2",
  676. "ptc_chamber_3",
  677. "ptc_chamber_4",
  678. "door_z",
  679. "door_x",
  680. "door_y",
  681. ],
  682. },
  683. "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
  684. "temperature_data": {
  685. "type": "0x82",
  686. "payload_length": summary["temperature_payload_len"],
  687. "frame_length": summary["temperature_frame_len"],
  688. },
  689. },
  690. "outputs": project["outputs"],
  691. "motors": project["motors"],
  692. "limits": project["limits"],
  693. "temperature": project["temperature"],
  694. "watchdog": project["watchdog"],
  695. }
  696. _write_json(output / "host-contract.json", contract)
  697. _write_json(output / "project-summary.json", summary)
  698. _write_json(
  699. output / "golden-vectors.json",
  700. {
  701. "set_all_all_zero": _frame_hex(0x01, bytes(11)),
  702. "set_all_mixed": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 1, 2, 0))),
  703. "set_all_legacy_14_rejected": "0E",
  704. "get_temperature": _frame_hex(0x02, b""),
  705. "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * project["temperature"]["value_count"])),
  706. },
  707. )
  708. source_payload = {
  709. "schema": "prod2u-simple-source-manifest-template-v1",
  710. "project_id": project["project_id"],
  711. "sources": list(_load_source_closure()),
  712. "generated_from": "project.json",
  713. "contract": {
  714. "uart": project["uart"],
  715. "protocol": project["protocol"],
  716. "set_all_payload_length": summary["set_all_payload_len"],
  717. "temperature_frame_length": summary["temperature_frame_len"],
  718. "axis_count": project["motors"]["count"],
  719. "limit_count": project["limits"]["limit_count"],
  720. "runtime_limit_use": project["limits"]["runtime_use"],
  721. },
  722. "active_interface": [
  723. {"signal": signal, "ball": ball}
  724. for signal, ball in render_adc(project)
  725. ],
  726. }
  727. _write_json(output / "td-source-manifest.json", source_payload)
  728. (output / f"{project['project_id'].replace('-', '_')}.adc").write_text(
  729. render_adc_text(project), encoding="ascii", newline="\n"
  730. )
  731. return summary
  732. def main() -> int:
  733. parser = argparse.ArgumentParser()
  734. parser.add_argument("project", type=Path)
  735. parser.add_argument("output", type=Path)
  736. args = parser.parse_args()
  737. generate_project(args.project, args.output)
  738. return 0
  739. if __name__ == "__main__":
  740. raise SystemExit(main())