generate_project.py 53 KB

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