generate_project.py 55 KB

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