generate_project.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. CAL_COUNTER_WIDTH_BITS = 13
  14. CAL_COUNTER_MAX = (1 << CAL_COUNTER_WIDTH_BITS) - 1
  15. FORBIDDEN_MOTOR_KEYS = {
  16. "fixed_steps",
  17. "busy_wait_ms",
  18. "command_values",
  19. "heartbeat_value",
  20. }
  21. FORBIDDEN_STARTUP_KEYS = {
  22. "backoff_step_count",
  23. "close_step_count",
  24. "direction_value",
  25. "direction_meaning",
  26. }
  27. _TOP_LEVEL_KEYS = {
  28. "project_id",
  29. "profile",
  30. "display_name",
  31. "device",
  32. "uart",
  33. "outputs",
  34. "doors",
  35. "motors",
  36. "limits",
  37. "temperature",
  38. "pins",
  39. "resource_policy",
  40. "protocol",
  41. "timeouts",
  42. "watchdog",
  43. }
  44. def _require(condition: bool, message: str) -> None:
  45. if not condition:
  46. raise ValueError(message)
  47. def _load_source_closure() -> tuple[str, ...]:
  48. payload = json.loads(SOURCE_CLOSURE_PATH.read_text(encoding="utf-8"))
  49. _require(isinstance(payload, Mapping), "source closure root must be an object")
  50. _require(payload.get("schema") == "prod2u-source-closure-v1", "source closure schema mismatch")
  51. _require(payload.get("project_id") == "prod2u-door-temp", "source closure project_id mismatch")
  52. sources = payload.get("sources")
  53. _require(isinstance(sources, list) and sources, "source closure must contain a non-empty sources list")
  54. normalized = []
  55. for value in sources:
  56. _require(isinstance(value, str) and value, "source closure entry must be a non-empty string")
  57. parts = Path(value).parts
  58. _require(".." not in parts and not Path(value).is_absolute(), "source closure entry must be a relative safe path")
  59. normalized.append(value)
  60. _require(len(normalized) == len(set(normalized)), "source closure contains duplicate paths")
  61. missing = [path for path in normalized if not (SOURCE_CLOSURE_PATH.parents[1] / path).is_file()]
  62. _require(not missing, f"source closure references missing files: {missing}")
  63. return tuple(normalized)
  64. ACTIVE_SOURCE_PATHS = _load_source_closure()
  65. def _object(value: Any, name: str) -> Mapping[str, Any]:
  66. _require(isinstance(value, dict), f"{name} must be an object")
  67. return value
  68. def _keys(value: Mapping[str, Any], expected: set[str], name: str) -> None:
  69. _require(set(value) == expected, f"{name} keys mismatch")
  70. def _integer(value: Any, name: str, *, minimum: int | None = None) -> None:
  71. _require(isinstance(value, int) and not isinstance(value, bool), f"{name} must be an integer")
  72. if minimum is not None:
  73. _require(value >= minimum, f"{name} is below the minimum")
  74. def _number(value: Any, name: str) -> None:
  75. _require(isinstance(value, (int, float)) and not isinstance(value, bool), f"{name} must be numeric")
  76. def _list(value: Any, name: str, length: int | None = None) -> list[Any]:
  77. _require(isinstance(value, list), f"{name} must be an array")
  78. if length is not None:
  79. _require(len(value) == length, f"{name} must contain {length} items")
  80. return value
  81. def _axis_mask_literal(values: list[Any], axis_count: int) -> str:
  82. """Build AXIS_COUNT'b... with bit0=X (LSB / rightmost), index0=X,1=Y,2=Z."""
  83. _require(len(values) == axis_count, "axis mask length mismatch")
  84. bits_lsb_first: list[str] = []
  85. for value in values:
  86. if isinstance(value, bool):
  87. bits_lsb_first.append("1" if value else "0")
  88. else:
  89. bits_lsb_first.append("1" if int(value) else "0")
  90. return f"{axis_count}'b" + "".join(reversed(bits_lsb_first))
  91. def _validate_channel(channel: Any, index: int, kind: str) -> None:
  92. item = _object(channel, f"{kind}_channels[{index}]")
  93. _keys(item, {"index", "name", "signal", "board_signal", "ball", "connector", "connector_pin", "polarity"}, f"{kind}_channels[{index}]")
  94. _require(item["index"] == index, f"{kind} channel index mismatch at {index}")
  95. _require(item["name"] == f"{kind}{index + 1}", f"{kind} channel name mismatch at {index}")
  96. _require(item["signal"] == f"{kind}_pwm_out[{index}]", f"{kind} channel signal mismatch at {index}")
  97. _require(isinstance(item["board_signal"], str) and item["board_signal"], f"invalid {kind} board signal at {index}")
  98. _require(item["polarity"] in {"active_high", "active_low"}, f"invalid {kind} polarity at {index}")
  99. _require(re.fullmatch(r"[A-Z][0-9]+", str(item["ball"])) is not None, f"invalid {kind} ball at {index}")
  100. _require(re.fullmatch(r"CON[0-9]+", str(item["connector"])) is not None, f"invalid {kind} connector at {index}")
  101. _integer(item["connector_pin"], f"{kind} channel connector pin", minimum=1)
  102. def _validate_project(payload: Mapping[str, Any]) -> None:
  103. _keys(payload, _TOP_LEVEL_KEYS, "project")
  104. _require(re.fullmatch(r"[a-z0-9-]+", str(payload["project_id"])) is not None, "invalid project_id")
  105. _require(isinstance(payload["profile"], str) and payload["profile"], "invalid project profile")
  106. _require(isinstance(payload["display_name"], str) and payload["display_name"], "invalid display_name")
  107. device = _object(payload["device"], "device")
  108. _keys(device, {"family", "part", "clock_hz", "clock_ball"}, "device")
  109. _require(isinstance(device["family"], str) and device["family"], "invalid device family")
  110. _require(isinstance(device["part"], str) and device["part"], "invalid device part")
  111. _integer(device["clock_hz"], "device.clock_hz", minimum=1)
  112. _require(re.fullmatch(r"[A-Z][0-9]+", str(device["clock_ball"])) is not None, "invalid clock ball")
  113. uart = _object(payload["uart"], "uart")
  114. _keys(uart, {"baud", "data_bits", "parity", "stop_bits", "flow_control", "clks_per_bit", "inter_byte_timeout_ms", "rx_ball", "tx_ball"}, "uart")
  115. _integer(uart["baud"], "uart.baud", minimum=1)
  116. _integer(uart["data_bits"], "uart.data_bits", minimum=1)
  117. _integer(uart["stop_bits"], "uart.stop_bits", minimum=1)
  118. _integer(uart["clks_per_bit"], "uart.clks_per_bit", minimum=1)
  119. _require(uart["parity"] in {"N", "E", "O"}, "invalid UART parity")
  120. _require(isinstance(uart["flow_control"], str), "invalid UART flow control")
  121. _integer(uart["inter_byte_timeout_ms"], "uart.inter_byte_timeout_ms", minimum=1)
  122. outputs = _object(payload["outputs"], "outputs")
  123. _keys(
  124. outputs,
  125. {
  126. "ptc_count",
  127. "fan_count",
  128. "chamber_ptc_count",
  129. "chamber_ptc_pairs",
  130. "ptc_channels",
  131. "fan_channels",
  132. "pwm_bits",
  133. "pwm_internal_width",
  134. "pwm_max_duty",
  135. "pwm_phase_count",
  136. "pwm_slot_clks",
  137. "pwm_frequency_hz",
  138. "pwm_actual_frequency_hz",
  139. "ptc_polarity",
  140. "fan_polarity",
  141. "ptc_default",
  142. "fan_default",
  143. "fan_connector_active_level",
  144. "fan_board_inverts",
  145. "boot_targets",
  146. },
  147. "outputs",
  148. )
  149. _integer(outputs["ptc_count"], "outputs.ptc_count", minimum=1)
  150. _integer(outputs["fan_count"], "outputs.fan_count", minimum=1)
  151. _require(outputs["ptc_count"] == len(outputs["ptc_channels"]), "PTC count/list mismatch")
  152. _require(outputs["fan_count"] == len(outputs["fan_channels"]), "FAN count/list mismatch")
  153. _integer(outputs["chamber_ptc_count"], "outputs.chamber_ptc_count", minimum=1)
  154. chamber_pairs = _list(outputs["chamber_ptc_pairs"], "outputs.chamber_ptc_pairs", outputs["chamber_ptc_count"])
  155. for index, pair in enumerate(chamber_pairs):
  156. item = _object(pair, f"outputs.chamber_ptc_pairs[{index}]")
  157. _keys(item, {"chamber", "ptc_indices"}, f"outputs.chamber_ptc_pairs[{index}]")
  158. _require(item["chamber"] == index + 1, "chamber index mismatch in chamber_ptc_pairs")
  159. indices = _list(item["ptc_indices"], f"outputs.chamber_ptc_pairs[{index}].ptc_indices", 2)
  160. _require(all(isinstance(value, int) and 0 <= value < outputs["ptc_count"] for value in indices), "invalid PTC pair indices")
  161. _require(indices[0] + 1 == indices[1], "PTC pair indices must be adjacent")
  162. for index, channel in enumerate(outputs["ptc_channels"]):
  163. _validate_channel(channel, index, "ptc")
  164. for index, channel in enumerate(outputs["fan_channels"]):
  165. _validate_channel(channel, index, "fan")
  166. _integer(outputs["pwm_bits"], "outputs.pwm_bits", minimum=1)
  167. _integer(outputs["pwm_internal_width"], "outputs.pwm_internal_width", minimum=1)
  168. _integer(outputs["pwm_max_duty"], "outputs.pwm_max_duty", minimum=0)
  169. _require(outputs["pwm_max_duty"] < (1 << outputs["pwm_bits"]), "PWM maximum exceeds protocol width")
  170. _integer(outputs["pwm_phase_count"], "outputs.pwm_phase_count", minimum=1)
  171. _integer(outputs["pwm_slot_clks"], "outputs.pwm_slot_clks", minimum=1)
  172. _number(outputs["pwm_frequency_hz"], "outputs.pwm_frequency_hz")
  173. _number(outputs["pwm_actual_frequency_hz"], "outputs.pwm_actual_frequency_hz")
  174. _require(outputs["ptc_polarity"] == "active_high" and outputs["fan_polarity"] == "active_low", "PWM polarity mismatch")
  175. _require(0 <= outputs["ptc_default"] <= outputs["pwm_max_duty"], "invalid PTC boot target")
  176. _require(0 <= outputs["fan_default"] <= outputs["pwm_max_duty"], "invalid FAN boot target")
  177. _require(outputs["fan_connector_active_level"] == "high" and outputs["fan_board_inverts"] is True, "FAN board metadata mismatch")
  178. boot_targets = _object(outputs["boot_targets"], "outputs.boot_targets")
  179. _keys(boot_targets, {"ptc", "fan"}, "outputs.boot_targets")
  180. _require(boot_targets == {"ptc": 0, "fan": 10}, "boot target mapping mismatch")
  181. doors = _object(payload["doors"], "doors")
  182. _keys(doors, {"scope", "chamber_controlled", "door_axes"}, "doors")
  183. door_axes = _list(doors["door_axes"], "doors.door_axes", 3)
  184. _require(door_axes == ["x", "y", "z"], "door_axes must be x,y,z")
  185. motors = _object(payload["motors"], "motors")
  186. forbidden_motor = FORBIDDEN_MOTOR_KEYS & set(motors)
  187. _require(not forbidden_motor, f"obsolete motors keys present: {sorted(forbidden_motor)}")
  188. _keys(
  189. motors,
  190. {
  191. "count",
  192. "order",
  193. "role",
  194. "execution",
  195. "step_rate_hz",
  196. "step_half_cycles",
  197. "dir_setup_cycles",
  198. "open_dir_value",
  199. "close_dir_value",
  200. "dir_close_level",
  201. "positioning",
  202. "mapping",
  203. "enable_n",
  204. },
  205. "motors",
  206. )
  207. _integer(motors["count"], "motors.count", minimum=1)
  208. _require(len(motors["order"]) == motors["count"] and all(isinstance(axis, str) and axis for axis in motors["order"]), "motor order mismatch")
  209. _require(isinstance(motors["role"], str) and motors["role"], "invalid motor role")
  210. _require(motors["execution"] == "overlap", "motor execution must be overlap")
  211. _integer(motors["step_rate_hz"], "motors.step_rate_hz", minimum=1)
  212. _require(motors["step_rate_hz"] == 1000, "motor step rate must be 1000")
  213. _integer(motors["step_half_cycles"], "motors.step_half_cycles", minimum=1)
  214. _require(motors["step_half_cycles"] == 12500, "motor step half cycles must be 12500")
  215. _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0)
  216. _require(motors["dir_setup_cycles"] == 25000, "motor dir setup cycles must be 25000")
  217. _integer(motors["open_dir_value"], "motors.open_dir_value", minimum=0)
  218. _integer(motors["close_dir_value"], "motors.close_dir_value", minimum=0)
  219. _require(motors["open_dir_value"] == 0, "logical open_dir_value must be 0")
  220. _require(motors["close_dir_value"] == 1, "logical close_dir_value must be 1")
  221. dir_close_level = _list(motors["dir_close_level"], "motors.dir_close_level", length=motors["count"])
  222. for index, level in enumerate(dir_close_level):
  223. _require(isinstance(level, int) and not isinstance(level, bool) and level in (0, 1),
  224. f"motors.dir_close_level[{index}] must be 0 or 1")
  225. positioning = _object(motors["positioning"], "motors.positioning")
  226. _keys(
  227. positioning,
  228. {
  229. "mode",
  230. "percent_min",
  231. "percent_max",
  232. "open_endpoint_percent",
  233. "close_endpoint_percent",
  234. "mid_percent_min",
  235. "mid_percent_max",
  236. "rounding",
  237. "mid_clamp",
  238. "latest_wins",
  239. "idempotent_same_target",
  240. "command_interrupt",
  241. "shared_percent_planner",
  242. "planner_count",
  243. "endpoint_guard_extra_steps",
  244. },
  245. "motors.positioning",
  246. )
  247. _require(positioning["mode"] == "percent_close", "positioning mode must be percent_close")
  248. _integer(positioning["percent_min"], "motors.positioning.percent_min", minimum=0)
  249. _integer(positioning["percent_max"], "motors.positioning.percent_max", minimum=0)
  250. _require(positioning["percent_min"] == 0 and positioning["percent_max"] == 100, "percent range must be 0..100")
  251. _require(positioning["open_endpoint_percent"] == 0, "open endpoint percent must be 0")
  252. _require(positioning["close_endpoint_percent"] == 100, "close endpoint percent must be 100")
  253. _require(positioning["mid_percent_min"] == 1, "mid percent min must be 1")
  254. _require(positioning["mid_percent_max"] == 99, "mid percent max must be 99")
  255. _require(positioning["rounding"] == "half_up", "rounding must be half_up")
  256. _require(positioning["mid_clamp"] == "1_to_travel_minus_1", "mid clamp policy mismatch")
  257. _require(positioning["latest_wins"] is True, "latest_wins must be true")
  258. _require(positioning["idempotent_same_target"] is True, "idempotent_same_target must be true")
  259. _require(
  260. positioning["command_interrupt"] == "finish_current_high_pulse_then_replan",
  261. "command interrupt policy mismatch",
  262. )
  263. _require(positioning["shared_percent_planner"] is True, "shared_percent_planner must be true")
  264. _integer(positioning["planner_count"], "motors.positioning.planner_count", minimum=1)
  265. _require(positioning["planner_count"] == 1, "planner_count must be 1")
  266. _integer(positioning["endpoint_guard_extra_steps"], "motors.positioning.endpoint_guard_extra_steps", minimum=0)
  267. _require(positioning["endpoint_guard_extra_steps"] == 500, "endpoint guard extra steps must be 500")
  268. mapping = _object(motors["mapping"], "motors.mapping")
  269. _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z")
  270. _keys(mapping, {"x", "y", "z"}, "motors.mapping")
  271. for axis in ("x", "y", "z"):
  272. item = _object(mapping[axis], f"motors.mapping.{axis}")
  273. required = {"axis", "role", "step_ball", "dir_ball"}
  274. _require(required <= set(item), f"motors.mapping.{axis} missing required keys")
  275. _require(item["axis"] == axis and item["role"] == "door", f"motor {axis} role mismatch")
  276. enable = _object(motors["enable_n"], "motors.enable_n")
  277. _require({"ball", "active_level", "policy"} <= set(enable), "motors.enable_n missing required keys")
  278. _require(isinstance(enable["ball"], str) and enable["ball"], "invalid motor enable ball")
  279. _require(enable["active_level"] == "low", "motor enable must be active low")
  280. _require(enable["policy"] == "permanent_high", "motor enable policy must be permanent_high")
  281. limits = _object(payload["limits"], "limits")
  282. _keys(
  283. limits,
  284. {
  285. "limit_count",
  286. "active_level",
  287. "limit_active_high",
  288. "close_limit_is_ls",
  289. "functional_use",
  290. "runtime_use",
  291. "startup",
  292. "channels",
  293. },
  294. "limits",
  295. )
  296. _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch")
  297. # limits.active_level is legacy / deprecated / non-authoritative. Accept the
  298. # historical string enum only; do not bind it to per-axis arrays or RTL masks.
  299. _require(
  300. limits["active_level"] in ("high", "low") and limits["functional_use"] is True,
  301. "limits.active_level must be legacy enum high|low and functional_use true",
  302. )
  303. _require(limits["runtime_use"] is True, "runtime limit use must be true")
  304. limit_active_high = _list(limits["limit_active_high"], "limits.limit_active_high", length=motors["count"])
  305. for index, active_high in enumerate(limit_active_high):
  306. _require(isinstance(active_high, bool), f"limits.limit_active_high[{index}] must be a boolean")
  307. close_limit_is_ls = _list(limits["close_limit_is_ls"], "limits.close_limit_is_ls", length=motors["count"])
  308. for index, close_is_ls in enumerate(close_limit_is_ls):
  309. _require(isinstance(close_is_ls, bool), f"limits.close_limit_is_ls[{index}] must be a boolean")
  310. # Per-axis limit_active_high / close_limit_is_ls / dir_close_level alone decide
  311. # generated masks. Mixed-axis configs must not force active_level sync.
  312. startup = _object(limits["startup"], "limits.startup")
  313. forbidden_startup = FORBIDDEN_STARTUP_KEYS & set(startup)
  314. _require(not forbidden_startup, f"obsolete limits.startup keys present: {sorted(forbidden_startup)}")
  315. _keys(
  316. startup,
  317. {
  318. "enabled",
  319. "mode",
  320. "max_steps",
  321. "min_travel_steps",
  322. "step_rate_hz",
  323. "axis_order",
  324. "final_position",
  325. "limit_stop_during_move",
  326. "stop_semantics",
  327. "additional_rising_edges_after_synchronized_limit",
  328. "runtime_limit_use",
  329. "partial_axis_failure_allowed",
  330. "fault_lock_until_reset",
  331. },
  332. "limits.startup",
  333. )
  334. _require(startup["enabled"] is True, "startup must be enabled")
  335. _require(startup["mode"] == "seek_close_then_measure_open", "startup mode must be seek_close_then_measure_open")
  336. _require(startup["final_position"] == "open", "startup final position must be open")
  337. _require(startup["limit_stop_during_move"] is True, "startup limit stop during move must be enabled")
  338. _require(
  339. startup["stop_semantics"] == "truncate_current_high_pulse_immediately_after_synchronized_limit",
  340. "unsupported stop semantics",
  341. )
  342. _require(startup["additional_rising_edges_after_synchronized_limit"] == 0, "additional rising edges after limit must be zero")
  343. _require(startup["runtime_limit_use"] is True, "startup runtime limit use must be true")
  344. _require(startup["partial_axis_failure_allowed"] is True, "partial axis failure must be allowed")
  345. _require(startup["fault_lock_until_reset"] is True, "fault lock until reset must be true")
  346. _integer(startup["max_steps"], "limits.startup.max_steps", minimum=1)
  347. _integer(startup["min_travel_steps"], "limits.startup.min_travel_steps", minimum=0)
  348. _integer(startup["step_rate_hz"], "limits.startup.step_rate_hz", minimum=1)
  349. _require(startup["max_steps"] == 5000, "startup max_steps must be 5000")
  350. _require(startup["min_travel_steps"] >= 2, "min_travel_steps must be >= 2")
  351. _require(startup["min_travel_steps"] == 2, "startup min_travel_steps must be 2")
  352. _require(startup["step_rate_hz"] == 1000, "startup step rate must be 1000")
  353. _require(startup["max_steps"] <= CAL_COUNTER_MAX, "max_steps exceeds calibration counter width")
  354. endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"]
  355. _require(endpoint_guard_max <= CAL_COUNTER_MAX, "endpoint guard max exceeds calibration counter width")
  356. _require(endpoint_guard_max == 5500, "endpoint guard max must be 5500")
  357. _require(len(startup["axis_order"]) == 3 and startup["axis_order"] == ["x", "y", "z"], "startup axis order mismatch")
  358. expected_limit_names = [
  359. "x_limit_ls",
  360. "x_limit_hs",
  361. "y_limit_ls",
  362. "y_limit_hs",
  363. "z_limit_ls",
  364. "z_limit_hs",
  365. ]
  366. for index, item in enumerate(limits["channels"]):
  367. entry = _object(item, f"limits.channels[{index}]")
  368. _keys(entry, {"name", "ball", "connector", "connector_pin", "side"}, f"limits.channels[{index}]")
  369. _require(entry["name"] == expected_limit_names[index], "invalid limit channel order/name")
  370. temperature = _object(payload["temperature"], "temperature")
  371. _keys(
  372. temperature,
  373. {
  374. "value_count",
  375. "device_addresses",
  376. "registers",
  377. "scl_ball",
  378. "sda_ball",
  379. "bus",
  380. "device",
  381. "invalid_value",
  382. "maximum_celsius",
  383. "conversion",
  384. },
  385. "temperature",
  386. )
  387. _integer(temperature["value_count"], "temperature.value_count", minimum=1)
  388. _require(temperature["value_count"] == len(temperature["device_addresses"]) * len(temperature["registers"]), "temperature count/list mismatch")
  389. _require(all(isinstance(value, int) and 0 <= value < 128 for value in temperature["device_addresses"]), "invalid temperature address")
  390. _require(all(isinstance(value, int) and 0 <= value <= 255 for value in temperature["registers"]), "invalid temperature register")
  391. _require(isinstance(temperature["device"], str) and temperature["device"], "invalid temperature device")
  392. _integer(temperature["invalid_value"], "temperature.invalid_value", minimum=0)
  393. _require(temperature["invalid_value"] <= 255, "temperature.invalid_value exceeds byte")
  394. _integer(temperature["maximum_celsius"], "temperature.maximum_celsius", minimum=0)
  395. conversion = _object(temperature["conversion"], "temperature.conversion")
  396. _keys(conversion, {"profile", "raw_shift", "raw_width", "reject_sign_bit"}, "temperature.conversion")
  397. _require(conversion == {"profile": "ct7428-msb-integer", "raw_shift": 7, "raw_width": 9, "reject_sign_bit": True}, "temperature conversion mismatch")
  398. pins = _object(payload["pins"], "pins")
  399. _keys(
  400. pins,
  401. {
  402. "host_uart_rx",
  403. "host_uart_tx",
  404. "temp_scl",
  405. "temp_sda",
  406. "ptc_pwm",
  407. "fan_pwm",
  408. "motor_en_n",
  409. "x_step",
  410. "x_dir",
  411. "y_step",
  412. "y_dir",
  413. "z_step",
  414. "z_dir",
  415. "x_limit_ls",
  416. "x_limit_hs",
  417. "y_limit_ls",
  418. "y_limit_hs",
  419. "z_limit_ls",
  420. "z_limit_hs",
  421. },
  422. "pins",
  423. )
  424. _require(pins["host_uart_rx"] == uart["rx_ball"] and pins["host_uart_tx"] == uart["tx_ball"], "UART pin duplication mismatch")
  425. _require(pins["temp_scl"] == temperature["scl_ball"] and pins["temp_sda"] == temperature["sda_ball"], "I2C pin duplication mismatch")
  426. _require(pins["ptc_pwm"] == [item["ball"] for item in outputs["ptc_channels"]], "PTC pin/list mismatch")
  427. _require(
  428. pins["fan_pwm"] == [item["ball"] for item in outputs["fan_channels"]],
  429. "FAN pin/list mismatch",
  430. )
  431. _require(pins["motor_en_n"] == enable["ball"], "motor enable pin mismatch")
  432. for axis in ("x", "y", "z"):
  433. _require(pins[f"{axis}_step"] == mapping[axis]["step_ball"], f"{axis} step pin mismatch")
  434. _require(pins[f"{axis}_dir"] == mapping[axis]["dir_ball"], f"{axis} dir pin mismatch")
  435. for channel in limits["channels"]:
  436. _require(pins[channel["name"]] == channel["ball"], f"{channel['name']} pin mismatch")
  437. resources = _object(payload["resource_policy"], "resource_policy")
  438. _keys(
  439. resources,
  440. {
  441. "target_ram",
  442. "request_ram",
  443. "temperature_ram",
  444. "dsp",
  445. "shared_pwm_comparators",
  446. "shared_percent_planner",
  447. "shared_i2c_readers",
  448. },
  449. "resource_policy",
  450. )
  451. for key, value in resources.items():
  452. if key in {"target_ram", "request_ram", "temperature_ram"}:
  453. _require(
  454. value in {"optional", "required", "forbidden"},
  455. f"resource_policy.{key} must be optional, required, or forbidden",
  456. )
  457. else:
  458. _integer(value, f"resource_policy.{key}", minimum=0)
  459. _require(resources["dsp"] == 0, "resource_policy.dsp must be 0")
  460. _require(resources["shared_percent_planner"] == 1, "resource_policy.shared_percent_planner must be 1")
  461. _require(resources["shared_percent_planner"] == positioning["planner_count"], "shared planner count mismatch")
  462. protocol = _object(payload["protocol"], "protocol")
  463. _keys(
  464. protocol,
  465. {
  466. "header_hex",
  467. "crc",
  468. "commands",
  469. "set_all",
  470. "get_motor_status",
  471. "temperature_data",
  472. "motor_status_data",
  473. },
  474. "protocol",
  475. )
  476. _require(isinstance(protocol["header_hex"], str) and protocol["header_hex"], "frame header missing")
  477. crc = _object(protocol["crc"], "protocol.crc")
  478. _keys(crc, {"name", "polynomial", "initial", "reflect_input", "reflect_output", "xor_output", "coverage", "wire_order"}, "protocol.crc")
  479. _require(
  480. crc
  481. == {
  482. "name": "CRC-16/CCITT-FALSE",
  483. "polynomial": 0x1021,
  484. "initial": 0xFFFF,
  485. "reflect_input": False,
  486. "reflect_output": False,
  487. "xor_output": 0,
  488. "coverage": "type_length_payload",
  489. "wire_order": "little",
  490. },
  491. "CRC contract mismatch",
  492. )
  493. commands = _object(protocol["commands"], "protocol.commands")
  494. _keys(
  495. commands,
  496. {"set_all", "get_temperature", "get_motor_status", "temperature_data", "motor_status_data"},
  497. "protocol.commands",
  498. )
  499. _require(commands["set_all"] == 1, "SET_ALL command type mismatch")
  500. _require(commands["get_temperature"] == 2, "GET_TEMPERATURE command type mismatch")
  501. _require(commands["get_motor_status"] == 3, "GET_MOTOR_STATUS command type mismatch")
  502. _require(commands["temperature_data"] == 130, "TEMPERATURE_DATA command type mismatch")
  503. _require(commands["motor_status_data"] == 131, "MOTOR_STATUS_DATA command type mismatch")
  504. command_values = list(commands.values())
  505. _require(len(command_values) == len(set(command_values)), "duplicate protocol command types")
  506. _require("door_values" not in protocol.get("set_all", {}), "obsolete set_all.door_values present")
  507. set_all = _object(protocol["set_all"], "protocol.set_all")
  508. set_all_keys = {
  509. "payload_length",
  510. "fan_offset",
  511. "chamber_ptc_offset",
  512. "chamber_ptc_count",
  513. "z_door_offset",
  514. "exhaust_x_offset",
  515. "exhaust_y_offset",
  516. "legacy_payload_length_rejected",
  517. "duty_min",
  518. "duty_max",
  519. "door_percent_min",
  520. "door_percent_max",
  521. "response",
  522. }
  523. optional_set_all = {"door_percent_rejected_example"}
  524. _require(set_all_keys <= set(set_all), "protocol.set_all missing required keys")
  525. _require(set(set_all) <= (set_all_keys | optional_set_all), "protocol.set_all keys mismatch")
  526. _require(set_all["fan_offset"] == 0, "SET_ALL FAN offset mismatch")
  527. _require(set_all["chamber_ptc_offset"] == outputs["fan_count"], "SET_ALL chamber PTC offset mismatch")
  528. _require(set_all["chamber_ptc_count"] == outputs["chamber_ptc_count"], "SET_ALL chamber PTC count mismatch")
  529. _require(set_all["z_door_offset"] == set_all["chamber_ptc_offset"] + set_all["chamber_ptc_count"], "SET_ALL Z offset mismatch")
  530. _require(set_all["exhaust_x_offset"] == set_all["z_door_offset"] + 1, "SET_ALL exhaust X offset mismatch")
  531. _require(set_all["exhaust_y_offset"] == set_all["exhaust_x_offset"] + 1, "SET_ALL exhaust Y offset mismatch")
  532. _require(set_all["payload_length"] == set_all["exhaust_y_offset"] + 1, "SET_ALL length mismatch")
  533. _require(set_all["legacy_payload_length_rejected"] == 14, "legacy payload length marker mismatch")
  534. _require(set_all["duty_min"] <= set_all["duty_max"], "SET_ALL duty range mismatch")
  535. _require(set_all["door_percent_min"] == positioning["percent_min"], "SET_ALL door percent min mismatch")
  536. _require(set_all["door_percent_max"] == positioning["percent_max"], "SET_ALL door percent max mismatch")
  537. _require(set_all["response"] == "none", "SET_ALL response must be none")
  538. if "door_percent_rejected_example" in set_all:
  539. _integer(set_all["door_percent_rejected_example"], "protocol.set_all.door_percent_rejected_example", minimum=0)
  540. _require(
  541. set_all["door_percent_rejected_example"] > set_all["door_percent_max"],
  542. "door percent rejected example must exceed door_percent_max",
  543. )
  544. get_motor_status = _object(protocol["get_motor_status"], "protocol.get_motor_status")
  545. _keys(get_motor_status, {"payload_length", "response"}, "protocol.get_motor_status")
  546. _require(get_motor_status["payload_length"] == 0, "GET_MOTOR_STATUS payload length must be 0")
  547. _require(get_motor_status["response"] == "motor_status_data", "GET_MOTOR_STATUS response mismatch")
  548. temperature_data = _object(protocol["temperature_data"], "protocol.temperature_data")
  549. _keys(temperature_data, {"payload_length", "frame_length"}, "protocol.temperature_data")
  550. _require(temperature_data["payload_length"] == temperature["value_count"], "temperature payload length mismatch")
  551. _require(temperature_data["frame_length"] == temperature_data["payload_length"] + 6, "temperature frame length mismatch")
  552. motor_status_data = _object(protocol["motor_status_data"], "protocol.motor_status_data")
  553. _keys(motor_status_data, {"payload_length", "frame_length", "layout"}, "protocol.motor_status_data")
  554. _require(motor_status_data["payload_length"] == 31, "motor status payload length must be 31")
  555. _require(motor_status_data["frame_length"] == 37, "motor status frame length must be 37")
  556. _require(
  557. motor_status_data["frame_length"] == motor_status_data["payload_length"] + 6,
  558. "motor status frame length mismatch",
  559. )
  560. _require(motor_status_data["layout"] == "host-contract", "motor status layout marker mismatch")
  561. timeouts = _object(payload["timeouts"], "timeouts")
  562. _keys(timeouts, {"frame_inter_byte_ms", "host_get_response_ms"}, "timeouts")
  563. _integer(timeouts["frame_inter_byte_ms"], "timeouts.frame_inter_byte_ms", minimum=1)
  564. _integer(timeouts["host_get_response_ms"], "timeouts.host_get_response_ms", minimum=1)
  565. watchdog = _object(payload["watchdog"], "watchdog")
  566. _keys(
  567. watchdog,
  568. {"timeout_seconds", "tick_us", "tick_clks", "timeout_ticks", "enable_after_startup_complete", "target"},
  569. "watchdog",
  570. )
  571. _integer(watchdog["timeout_seconds"], "watchdog.timeout_seconds", minimum=1)
  572. _integer(watchdog["tick_us"], "watchdog.tick_us", minimum=1)
  573. _integer(watchdog["tick_clks"], "watchdog.tick_clks", minimum=1)
  574. _require(watchdog["tick_clks"] == device["clock_hz"] * watchdog["tick_us"] // 1_000_000, "watchdog tick clock mismatch")
  575. _integer(watchdog["timeout_ticks"], "watchdog.timeout_ticks", minimum=1)
  576. _require(watchdog["timeout_ticks"] == watchdog["timeout_seconds"] * 1_000_000 // watchdog["tick_us"], "watchdog tick count mismatch")
  577. _require(watchdog["timeout_seconds"] == 30, "watchdog timeout_seconds must be 30")
  578. _require(watchdog["timeout_ticks"] == 60000, "watchdog timeout_ticks must be 60000")
  579. _require(watchdog["enable_after_startup_complete"] is True, "watchdog must enable after startup complete")
  580. target = _object(watchdog["target"], "watchdog.target")
  581. _keys(target, {"ptc", "fan"}, "watchdog.target")
  582. _require(target == {"ptc": 0, "fan": 10}, "watchdog target mismatch")
  583. def load_project(path: Path) -> dict[str, Any]:
  584. project_path = Path(path)
  585. payload = json.loads(project_path.read_text(encoding="utf-8"))
  586. _require(isinstance(payload, dict), "project root must be an object")
  587. schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
  588. errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda error: list(error.absolute_path))
  589. if errors:
  590. location = ".".join(str(part) for part in errors[0].absolute_path) or "project"
  591. raise ValueError(f"project schema violation at {location}: {errors[0].message}")
  592. _validate_project(payload)
  593. return payload
  594. def _active_interface(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]:
  595. outputs = project["outputs"]
  596. pins = project["pins"]
  597. motors = project["motors"]
  598. interface = (
  599. ("sys_clk", project["device"]["clock_ball"]),
  600. ("host_uart_rx", pins["host_uart_rx"]),
  601. ("host_uart_tx", pins["host_uart_tx"]),
  602. ("temp_scl", pins["temp_scl"]),
  603. ("temp_sda", pins["temp_sda"]),
  604. *tuple((item["signal"], item["ball"]) for item in outputs["ptc_channels"]),
  605. *tuple((item["signal"], item["ball"]) for item in outputs["fan_channels"]),
  606. ("motor_en_n", pins["motor_en_n"]),
  607. ("x_step", motors["mapping"]["x"]["step_ball"]),
  608. ("x_dir", motors["mapping"]["x"]["dir_ball"]),
  609. ("y_step", motors["mapping"]["y"]["step_ball"]),
  610. ("y_dir", motors["mapping"]["y"]["dir_ball"]),
  611. ("z_step", motors["mapping"]["z"]["step_ball"]),
  612. ("z_dir", motors["mapping"]["z"]["dir_ball"]),
  613. *tuple((item["name"], item["ball"]) for item in project["limits"]["channels"]),
  614. )
  615. return interface
  616. def render_adc(project: Mapping[str, Any]) -> tuple[tuple[str, str], ...]:
  617. """Return the ordered active interface as (signal, ball) pairs."""
  618. return _active_interface(project)
  619. def project_summary(path: Path) -> dict[str, Any]:
  620. project = load_project(path)
  621. outputs = project["outputs"]
  622. temperature = project["temperature"]
  623. watchdog = project["watchdog"]
  624. total_channels = outputs["ptc_count"] + outputs["fan_count"]
  625. pwm_period_clks = outputs["pwm_slot_clks"] * total_channels * outputs["pwm_phase_count"]
  626. actual_frequency_hz = project["device"]["clock_hz"] / pwm_period_clks
  627. frequency_error_percent = abs(actual_frequency_hz - outputs["pwm_frequency_hz"]) / outputs["pwm_frequency_hz"] * 100.0
  628. return {
  629. "project_id": project["project_id"],
  630. "profile": project["profile"],
  631. "uart_clks_per_bit": project["uart"]["clks_per_bit"],
  632. "pwm_bits": outputs["pwm_bits"],
  633. "pwm_internal_width": outputs["pwm_internal_width"],
  634. "pwm_max_duty": outputs["pwm_max_duty"],
  635. "pwm_phase_count": outputs["pwm_phase_count"],
  636. "pwm_frequency_hz": outputs["pwm_frequency_hz"],
  637. "pwm_slot_clks": outputs["pwm_slot_clks"],
  638. "pwm_period_clks": pwm_period_clks,
  639. "pwm_period_seconds": round(pwm_period_clks / project["device"]["clock_hz"], 9),
  640. "actual_frequency_hz": round(actual_frequency_hz, 9),
  641. "frequency_error_percent": round(frequency_error_percent, 9),
  642. "ptc_default": outputs["ptc_default"],
  643. "fan_default": outputs["fan_default"],
  644. "ptc_polarity": outputs["ptc_polarity"],
  645. "fan_polarity": outputs["fan_polarity"],
  646. "fan_connector_active_level": outputs["fan_connector_active_level"],
  647. "fan_board_inverts": outputs["fan_board_inverts"],
  648. "set_all_payload_len": project["protocol"]["set_all"]["payload_length"],
  649. "set_all_frame_len": project["protocol"]["set_all"]["payload_length"] + 6,
  650. "temperature_payload_len": temperature["value_count"],
  651. "temperature_frame_len": temperature["value_count"] + 6,
  652. "temperature_addresses": list(temperature["device_addresses"]),
  653. "boot_targets": dict(outputs["boot_targets"]),
  654. "watchdog_timeout_seconds": watchdog["timeout_seconds"],
  655. "watchdog_tick_clks": watchdog["tick_clks"],
  656. "watchdog_timeout_ticks": watchdog["timeout_ticks"],
  657. "watchdog_target": dict(watchdog["target"]),
  658. }
  659. def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
  660. path.parent.mkdir(parents=True, exist_ok=True)
  661. path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  662. def _crc16_ccitt_false(data: bytes) -> int:
  663. crc = 0xFFFF
  664. for value in data:
  665. crc ^= value << 8
  666. for _ in range(8):
  667. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  668. return crc
  669. def _frame_hex(frame_type: int, payload: bytes) -> str:
  670. body = bytes((frame_type, len(payload))) + payload
  671. crc = _crc16_ccitt_false(body)
  672. return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper()
  673. def _render_params(project: Mapping[str, Any]) -> str:
  674. outputs = project["outputs"]
  675. motors = project["motors"]
  676. positioning = motors["positioning"]
  677. limits = project["limits"]
  678. startup = limits["startup"]
  679. temperature = project["temperature"]
  680. uart = project["uart"]
  681. watchdog = project["watchdog"]
  682. protocol = project["protocol"]
  683. commands = protocol["commands"]
  684. axis_count = motors["count"]
  685. _require(motors["dir_setup_cycles"] % watchdog["tick_clks"] == 0, "motor direction setup is not an integral tick count")
  686. motor_dir_setup_ticks = motors["dir_setup_cycles"] // watchdog["tick_clks"]
  687. frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000
  688. startup_dir_bit = motors["close_dir_value"]
  689. startup_dir_mask = f"{axis_count}'b" + (str(startup_dir_bit) * axis_count)
  690. limit_active_high_mask = _axis_mask_literal(limits["limit_active_high"], axis_count)
  691. dir_close_level_mask = _axis_mask_literal(motors["dir_close_level"], axis_count)
  692. close_limit_is_ls_mask = _axis_mask_literal(limits["close_limit_is_ls"], axis_count)
  693. endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"]
  694. lines = [
  695. "// Generated from project.json. Do not edit.",
  696. f"`define P4_AXIS_COUNT {axis_count}",
  697. f"`define P4_LIMIT_COUNT {limits['limit_count']}",
  698. f"`define P4_RUNTIME_LIMIT_USE {1 if limits['runtime_use'] else 0}",
  699. f"`define P4_LIMIT_ACTIVE_HIGH_MASK {limit_active_high_mask}",
  700. f"`define P4_DIR_CLOSE_LEVEL_MASK {dir_close_level_mask}",
  701. f"`define P4_CLOSE_LIMIT_IS_LS_MASK {close_limit_is_ls_mask}",
  702. f"`define P4_CLOCK_HZ {project['device']['clock_hz']}",
  703. f"`define P4_UART_BAUD {uart['baud']}",
  704. f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}",
  705. f"`define P4_PTC_COUNT {outputs['ptc_count']}",
  706. f"`define P4_FAN_COUNT {outputs['fan_count']}",
  707. f"`define P4_OUTPUT_CHANNEL_COUNT {outputs['ptc_count'] + outputs['fan_count']}",
  708. f"`define P4_PWM_PROTOCOL_WIDTH {outputs['pwm_bits']}",
  709. f"`define P4_PWM_INTERNAL_WIDTH {outputs['pwm_internal_width']}",
  710. f"`define P4_PWM_MAX_DUTY {outputs['pwm_max_duty']}",
  711. f"`define P4_PWM_PHASE_COUNT {outputs['pwm_phase_count']}",
  712. f"`define P4_PWM_FREQUENCY_HZ {outputs['pwm_frequency_hz']}",
  713. f"`define P4_PWM_SLOT_CLKS {outputs['pwm_slot_clks']}",
  714. f"`define P4_CMD_SET_ALL 8'h{commands['set_all']:02X}",
  715. f"`define P4_CMD_GET_TEMPERATURE 8'h{commands['get_temperature']:02X}",
  716. f"`define P4_CMD_GET_MOTOR_STATUS 8'h{commands['get_motor_status']:02X}",
  717. f"`define P4_CMD_TEMPERATURE_DATA 8'h{commands['temperature_data']:02X}",
  718. f"`define P4_CMD_MOTOR_STATUS_DATA 8'h{commands['motor_status_data']:02X}",
  719. f"`define P4_RSP_TEMPERATURE 8'h{commands['temperature_data']:02X}",
  720. f"`define P4_RSP_MOTOR_STATUS 8'h{commands['motor_status_data']:02X}",
  721. f"`define P4_SET_ALL_PAYLOAD_LENGTH {protocol['set_all']['payload_length']}",
  722. f"`define P4_CHAMBER_PTC_COUNT {outputs['chamber_ptc_count']}",
  723. f"`define P4_SET_ALL_FAN_OFFSET {protocol['set_all']['fan_offset']}",
  724. f"`define P4_SET_ALL_CHAMBER_PTC_OFFSET {protocol['set_all']['chamber_ptc_offset']}",
  725. f"`define P4_SET_ALL_Z_DOOR_OFFSET {protocol['set_all']['z_door_offset']}",
  726. f"`define P4_SET_ALL_EXHAUST_X_OFFSET {protocol['set_all']['exhaust_x_offset']}",
  727. f"`define P4_SET_ALL_EXHAUST_Y_OFFSET {protocol['set_all']['exhaust_y_offset']}",
  728. f"`define P4_DOOR_PERCENT_MIN {positioning['percent_min']}",
  729. f"`define P4_DOOR_PERCENT_MAX {positioning['percent_max']}",
  730. f"`define P4_OPEN_ENDPOINT_PERCENT {positioning['open_endpoint_percent']}",
  731. f"`define P4_CLOSE_ENDPOINT_PERCENT {positioning['close_endpoint_percent']}",
  732. f"`define P4_MID_PERCENT_MIN {positioning['mid_percent_min']}",
  733. f"`define P4_MID_PERCENT_MAX {positioning['mid_percent_max']}",
  734. f"`define P4_MOTOR_STATUS_PAYLOAD_LENGTH {protocol['motor_status_data']['payload_length']}",
  735. f"`define P4_MOTOR_STATUS_FRAME_LENGTH {protocol['motor_status_data']['frame_length']}",
  736. f"`define P4_MOTOR_OPEN_DIR 1'b{motors['open_dir_value']}",
  737. f"`define P4_MOTOR_CLOSE_DIR 1'b{motors['close_dir_value']}",
  738. f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}",
  739. f"`define P4_MOTOR_STEP_RATE_HZ {motors['step_rate_hz']}",
  740. f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}",
  741. f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
  742. f"`define P4_MOTOR_DIR_SETUP_TICKS {motor_dir_setup_ticks}",
  743. f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}",
  744. f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}",
  745. f"`define P4_TEMPERATURE_FRAME_LENGTH {temperature['value_count'] + 6}",
  746. f"`define P4_TEMP_MAX_CELSIUS {temperature['maximum_celsius']}",
  747. f"`define P4_PTC_ACTIVE_HIGH {1 if outputs['ptc_polarity'] == 'active_high' else 0}",
  748. f"`define P4_FAN_ACTIVE_HIGH {1 if outputs['fan_polarity'] == 'active_high' else 0}",
  749. f"`define P4_PTC_DEFAULT_TARGET 8'h{outputs['ptc_default']:02X}",
  750. f"`define P4_FAN_DEFAULT_TARGET 8'h{outputs['fan_default']:02X}",
  751. f"`define P4_WATCHDOG_TIMEOUT_SECONDS {watchdog['timeout_seconds']}",
  752. f"`define P4_WATCHDOG_TICK_US {watchdog['tick_us']}",
  753. f"`define P4_WATCHDOG_TICK_CLKS {watchdog['tick_clks']}",
  754. f"`define P4_WATCHDOG_TIMEOUT_TICKS {watchdog['timeout_ticks']}",
  755. f"`define P4_WATCHDOG_ENABLE_AFTER_STARTUP {1 if watchdog['enable_after_startup_complete'] else 0}",
  756. f"`define P4_WATCHDOG_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}",
  757. f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}",
  758. f"`define P4_STARTUP_ENABLED {1 if startup['enabled'] else 0}",
  759. f"`define P4_STARTUP_DIR_MASK {startup_dir_mask}",
  760. f"`define P4_CAL_MAX_STEPS {startup['max_steps']}",
  761. f"`define P4_CAL_MIN_TRAVEL {startup['min_travel_steps']}",
  762. f"`define P4_ENDPOINT_GUARD_EXTRA {positioning['endpoint_guard_extra_steps']}",
  763. f"`define P4_ENDPOINT_GUARD_MAX {endpoint_guard_max}",
  764. f"`define P4_STARTUP_STEP_RATE_HZ {startup['step_rate_hz']}",
  765. f"`define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH {1 if motors['enable_n']['policy'] == 'permanent_high' else 0}",
  766. "`define P4_STATE_CAL_SEEK_CLOSE 8'd0",
  767. "`define P4_STATE_CAL_MEASURE_OPEN 8'd1",
  768. "`define P4_STATE_IDLE 8'd2",
  769. "`define P4_STATE_MOVE_OPEN 8'd3",
  770. "`define P4_STATE_MOVE_CLOSE 8'd4",
  771. "`define P4_STATE_WAIT_REPLAN 8'd5",
  772. "`define P4_STATE_FAULT 8'd6",
  773. "`define P4_FAULT_NONE 8'd0",
  774. "`define P4_FAULT_BOTH_LIMITS_ACTIVE 8'd1",
  775. "`define P4_FAULT_CAL_CLOSE_TIMEOUT 8'd2",
  776. "`define P4_FAULT_CAL_OPEN_TIMEOUT 8'd3",
  777. "`define P4_FAULT_INVALID_ZERO_OR_TINY_TRAVEL 8'd4",
  778. "`define P4_FAULT_ENDPOINT_TIMEOUT 8'd5",
  779. ]
  780. lines.extend(
  781. f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}"
  782. for index, address in enumerate(temperature["device_addresses"])
  783. )
  784. lines.extend(
  785. f"`define P4_TEMP_REGISTER_{index} 8'h{register:02X}"
  786. for index, register in enumerate(temperature["registers"])
  787. )
  788. lines.append("")
  789. return "\n".join(lines)
  790. def render_adc_text(project: Mapping[str, Any]) -> str:
  791. lines = [
  792. "# Generated from project.json. Do not edit.",
  793. "# Active interface only; reserved board loads are intentionally absent.",
  794. ]
  795. active_interface = list(render_adc(project))
  796. for signal, ball in active_interface:
  797. lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}")
  798. return "\n".join(lines) + "\n"
  799. def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
  800. project = load_project(project_path)
  801. output = Path(output_root) / "generated"
  802. output.mkdir(parents=True, exist_ok=True)
  803. params_name = f"{project['project_id'].replace('-', '_')}_params.vh"
  804. (output / params_name).write_text(
  805. _render_params(project), encoding="ascii", newline="\n"
  806. )
  807. summary = project_summary(project_path)
  808. positioning = project["motors"]["positioning"]
  809. motor_status_layout = {
  810. "byte0_global": {
  811. "bit0_2": "calibrated_mask_xyz",
  812. "bit3_5": "fault_mask_xyz",
  813. "bit6": "startup_complete",
  814. "bit7": "watchdog_tripped",
  815. },
  816. "per_axis_bytes": 10,
  817. "axis_order": ["x", "y", "z"],
  818. "axis_fields": [
  819. "state",
  820. "flags",
  821. "requested_percent",
  822. "current_position_le16",
  823. "target_position_le16",
  824. "travel_steps_le16",
  825. "fault_code",
  826. ],
  827. "states": {
  828. "CAL_SEEK_CLOSE": 0,
  829. "CAL_MEASURE_OPEN": 1,
  830. "IDLE": 2,
  831. "MOVE_OPEN": 3,
  832. "MOVE_CLOSE": 4,
  833. "WAIT_REPLAN": 5,
  834. "FAULT": 6,
  835. },
  836. "flags": {
  837. "open_limit": 0,
  838. "close_limit": 1,
  839. "calibrated": 2,
  840. "moving": 3,
  841. "endpoint_mode": 4,
  842. "target_valid": 5,
  843. "replan_pending": 6,
  844. "reserved": 7,
  845. },
  846. "fault_codes": {
  847. "NONE": 0,
  848. "BOTH_LIMITS_ACTIVE": 1,
  849. "CAL_CLOSE_TIMEOUT": 2,
  850. "CAL_OPEN_TIMEOUT": 3,
  851. "INVALID_ZERO_OR_TINY_TRAVEL": 4,
  852. "ENDPOINT_TIMEOUT": 5,
  853. },
  854. }
  855. contract = {
  856. "schema": "prod2u-simple-host-contract-v1",
  857. "project_id": project["project_id"],
  858. "profile": project["profile"],
  859. "axis_count": project["motors"]["count"],
  860. "limit_count": project["limits"]["limit_count"],
  861. "runtime_limit_use": project["limits"]["runtime_use"],
  862. "uart": project["uart"],
  863. "protocol": project["protocol"],
  864. "commands": {
  865. "set_all": {
  866. "type": "0x01",
  867. "payload_length": summary["set_all_payload_len"],
  868. "response": "none",
  869. "duty_range": [0, 100],
  870. "door_percent_range": [positioning["percent_min"], positioning["percent_max"]],
  871. "door_percent_semantics": {
  872. "0": "full_open_endpoint",
  873. "1_to_99": "mid_percent_close",
  874. "100": "full_close_endpoint",
  875. "all_zero_frame": "fan_ptc_zero_and_all_doors_full_open_not_heartbeat",
  876. "0x65": "rejected_out_of_range",
  877. },
  878. "field_order": [
  879. "fan_chamber_1",
  880. "fan_chamber_2",
  881. "fan_chamber_3",
  882. "fan_chamber_4",
  883. "ptc_chamber_1",
  884. "ptc_chamber_2",
  885. "ptc_chamber_3",
  886. "ptc_chamber_4",
  887. "door_z_percent",
  888. "door_x_percent",
  889. "door_y_percent",
  890. ],
  891. },
  892. "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
  893. "get_motor_status": {"type": "0x03", "payload_length": 0, "response": "MOTOR_STATUS_DATA"},
  894. "temperature_data": {
  895. "type": "0x82",
  896. "payload_length": summary["temperature_payload_len"],
  897. "frame_length": summary["temperature_frame_len"],
  898. },
  899. "motor_status_data": {
  900. "type": "0x83",
  901. "payload_length": project["protocol"]["motor_status_data"]["payload_length"],
  902. "frame_length": project["protocol"]["motor_status_data"]["frame_length"],
  903. "layout": motor_status_layout,
  904. },
  905. },
  906. "outputs": project["outputs"],
  907. "motors": project["motors"],
  908. "limits": project["limits"],
  909. "temperature": project["temperature"],
  910. "watchdog": project["watchdog"],
  911. }
  912. _write_json(output / "host-contract.json", contract)
  913. _write_json(output / "project-summary.json", summary)
  914. # Representative status: startup_complete + all calibrated, idle at open, travel=1000.
  915. status_axis = bytes((0x02, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE8, 0x03, 0x00))
  916. status_payload = bytes((0x47,)) + status_axis * 3
  917. _write_json(
  918. output / "golden-vectors.json",
  919. {
  920. "set_all_all_zero_full_open": _frame_hex(0x01, bytes(11)),
  921. "set_all_doors_0_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 0, 0, 0))),
  922. "set_all_doors_50_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 50, 50, 50))),
  923. "set_all_doors_100_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 100, 100, 100))),
  924. "set_all_door_0x65_rejected": "65",
  925. "set_all_legacy_14_rejected": "0E",
  926. "get_temperature": _frame_hex(0x02, b""),
  927. "get_motor_status": _frame_hex(0x03, b""),
  928. "motor_status_data_example": _frame_hex(0x83, status_payload),
  929. "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * project["temperature"]["value_count"])),
  930. "notes": {
  931. "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.",
  932. "set_all_door_0x65_rejected": "Door percent 0x65 (101) is out of 0..100 and must be rejected.",
  933. "get_motor_status": "Exact request frame A55A03005C48.",
  934. },
  935. },
  936. )
  937. source_payload = {
  938. "schema": "prod2u-simple-source-manifest-template-v1",
  939. "project_id": project["project_id"],
  940. "sources": list(_load_source_closure()),
  941. "generated_from": "project.json",
  942. "contract": {
  943. "uart": project["uart"],
  944. "protocol": project["protocol"],
  945. "set_all_payload_length": summary["set_all_payload_len"],
  946. "temperature_frame_length": summary["temperature_frame_len"],
  947. "axis_count": project["motors"]["count"],
  948. "limit_count": project["limits"]["limit_count"],
  949. "runtime_limit_use": project["limits"]["runtime_use"],
  950. },
  951. "active_interface": [
  952. {"signal": signal, "ball": ball}
  953. for signal, ball in render_adc(project)
  954. ],
  955. }
  956. _write_json(output / "td-source-manifest.json", source_payload)
  957. (output / f"{project['project_id'].replace('-', '_')}.adc").write_text(
  958. render_adc_text(project), encoding="ascii", newline="\n"
  959. )
  960. return summary
  961. def main() -> int:
  962. parser = argparse.ArgumentParser()
  963. parser.add_argument("project", type=Path)
  964. parser.add_argument("output", type=Path)
  965. args = parser.parse_args()
  966. generate_project(args.project, args.output)
  967. return 0
  968. if __name__ == "__main__":
  969. raise SystemExit(main())