generate_project.py 54 KB

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