prod2u_p4_normal_v3_model.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. #!/usr/bin/env python3
  2. """Independent binary921-v3 model, replay, fuzz, and source detector.
  3. This verification-only oracle intentionally does not import the production
  4. protocol helper or any RTL-derived implementation. It models externally
  5. visible Profile 4 Normal behavior from the wire contract.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import ast
  10. import json
  11. import random
  12. import re
  13. from dataclasses import asdict, dataclass
  14. from pathlib import Path
  15. from typing import Iterable, Sequence
  16. ROOT = Path(__file__).resolve().parents[1]
  17. PROFILE_ID = "prod2u-p4-normal-actuator-binary921-v3"
  18. RAW_STEP_POLICY = "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP"
  19. FAST_PATH_POLICY = "RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT"
  20. SAME_AXIS_HOST_RULE = "HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION"
  21. SAME_AXIS_VIOLATION_POLICY = "LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED"
  22. COMPLETION_POLICY = "NONE_HOST_TRACKS_TIME"
  23. PARALLEL_POLICY = "TWO_INDEPENDENT_PARALLEL_EXECUTORS"
  24. MAGIC = b"\xA5\x5A"
  25. VERSION = 0x02
  26. PROFILE = 0x04
  27. FRAME_HOST_CMD = 0x05
  28. FRAME_HOST_BATCH = 0x07
  29. FRAME_MOTION_CMD = 0x11
  30. FRAME_MOTION_STATUS = 0x12
  31. CMD_GET_STATUS = 0x24
  32. CMD_DISABLE = 0x26
  33. CMD_SET_SNAPSHOT = 0x2A
  34. MOTION_JOG = 0x35
  35. MOTION_MARK_CLOSED = 0x36
  36. MOTION_GET_STATUS = 0x37
  37. STATUS_OK = 0x00
  38. STATUS_UNSUPPORTED = 0x01
  39. STATUS_BAD_FLAGS = 0x02
  40. STATUS_BAD_LENGTH = 0x03
  41. STATUS_BAD_VALUE = 0x05
  42. STATUS_PARTIAL = 0x16
  43. PTC_COUNT = 24
  44. FAN_COUNT = 4
  45. AXIS_COUNT = 3
  46. UNKNOWN_POSITION = 0xFF
  47. WATCHDOG_TIMEOUT_MS = 5000
  48. DIR_SETUP_MS = 1
  49. SPEED_STEP_MS = (1, 1, 1, 1)
  50. SAFE_PTC = (0,) * PTC_COUNT
  51. SAFE_FAN = (30,) * FAN_COUNT
  52. SAFE_SOLENOID = 0
  53. AXIS_UNCALIBRATED = "uncalibrated"
  54. AXIS_CLOSED = "closed"
  55. AXIS_OPENING = "opening"
  56. AXIS_OPEN = "open"
  57. AXIS_CLOSING = "closing"
  58. AXIS_INTERMEDIATE = "intermediate"
  59. LEGACY_P4_ASSET_PATHS = (
  60. "src/rtl/prod2u_p4_host_rx.v",
  61. "src/rtl/prod2u_p4_tx_scheduler.v",
  62. "src/rtl/prod2u_fan_tach_capture8.v",
  63. "src/rtl/prod2u_fan_pwm_bank.v",
  64. "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
  65. "src/top/prod2u_fan_tach_binary921_v2_normal_top.v",
  66. "src/top/prod2u_fan_tach_binary921_v2_trace_top.v",
  67. "tests/sim/prod2u_p4_host_rx_tb.v",
  68. "tests/sim/prod2u_p4_tx_scheduler_tb.v",
  69. "tests/sim/prod2u_fan_tach_capture8_tb.v",
  70. "tests/sim/prod2u_fan_pwm_bank_tb.v",
  71. "tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v",
  72. "tests/formal/prod2u_fan_data_path.sby",
  73. "tests/formal/prod2u_fan_data_path_formal.v",
  74. "constraints/prod2u_fan_tach_binary921_v2.adc",
  75. "td/prod2u_fan_tach_binary921_v2_normal.prj",
  76. "td/prod2u_fan_tach_binary921_v2_trace.prj",
  77. "td/syn/prod2u_fan_tach_binary921_v2_normal.tcl",
  78. "td/syn/prod2u_fan_tach_binary921_v2_trace.tcl",
  79. "td/phy/prod2u_fan_tach_binary921_v2_normal.tcl",
  80. "td/phy/prod2u_fan_tach_binary921_v2_trace.tcl",
  81. "tools/package_prod2u_p4.ps1",
  82. "tools/prod2u_p4_collector.py",
  83. "tools/prod2u_p4_campaign.py",
  84. "tools/prod2u_p4_validate.py",
  85. "docs/prod2u-p4-start-here.zh-CN.md",
  86. "docs/prod2u-p4-program-sram-runbook.zh-CN.md",
  87. "schemas/prod2u_p4_campaign.schema.json",
  88. "schemas/prod2u_p4_evidence.schema.json",
  89. "schemas/prod2u_p4_final_gate.schema.json",
  90. "schemas/prod2u_p4_qualification.schema.json",
  91. "schemas/prod2u_p4_td_build_receipt.schema.json",
  92. "tests/unit/test_prod2u_p4_cli_campaign.py",
  93. "tests/unit/test_prod2u_p4_cli_identity.py",
  94. "tests/unit/test_prod2u_p4_evidence_binding.py",
  95. "tests/unit/test_prod2u_p4_integration.py",
  96. "tests/unit/test_prod2u_p4_package.py",
  97. "tests/unit/test_prod2u_p4_protocol.py",
  98. "tests/unit/test_prod2u_p4_qualification.py",
  99. "tests/unit/test_prod2u_p4_validate_contract.py",
  100. )
  101. class ModelFrameError(ValueError):
  102. def __init__(self, message: str, *, status: int = STATUS_BAD_VALUE) -> None:
  103. super().__init__(message)
  104. self.status = status
  105. class HostContractViolation(ValueError):
  106. """Input excluded by the trusted-host contract, not a modeled device reply."""
  107. @dataclass(frozen=True)
  108. class PinSample:
  109. time_us: int
  110. en_n: int
  111. direction: tuple[int, int, int]
  112. step: tuple[int, int, int]
  113. @dataclass(frozen=True)
  114. class TraceViolation:
  115. kind: str
  116. axis: int
  117. time_us: int
  118. @dataclass(frozen=True)
  119. class MechanicalTraceReport:
  120. positions: tuple[int, int, int]
  121. step_counts: tuple[int, int, int]
  122. lost_step_counts: tuple[int, int, int]
  123. uncertain_step_counts: tuple[int, int, int]
  124. limit_raw_mask: int
  125. violations: tuple[TraceViolation, ...]
  126. @dataclass(frozen=True)
  127. class MechanicalDifference:
  128. matches: bool
  129. mismatches: tuple[str, ...]
  130. class MechanicalPlant:
  131. """Pin-level plant independent of controller or RTL internal state.
  132. The plant owns the hidden mechanical close direction and physical position.
  133. Its only motion inputs are the externally visible shared EN_N plus per-axis
  134. DIR and STEP pins.
  135. """
  136. def __init__(
  137. self,
  138. *,
  139. positions: Sequence[int],
  140. close_dirs: Sequence[int],
  141. dir_setup_us: int = 1000,
  142. min_step_high_us: int = 0,
  143. min_step_low_us: int = 0,
  144. limit_modes: Sequence[str] = ("normal", "normal"),
  145. limit_assert_delay_us: Sequence[int] = (0, 0),
  146. limit_bounce_us: Sequence[int] = (0, 0),
  147. limit_bounce_period_us: int = 100,
  148. swap_xy_limits: bool = False,
  149. lost_step_every: Sequence[int] = (0, 0, 0),
  150. ) -> None:
  151. if len(positions) != AXIS_COUNT or len(close_dirs) != AXIS_COUNT:
  152. raise ValueError("positions and close_dirs require exactly three axes")
  153. if any(value < 0 for value in positions):
  154. raise ValueError("positions must be non-negative")
  155. if any(value not in (0, 1) for value in close_dirs):
  156. raise ValueError("close_dirs must contain only zero or one")
  157. if len(limit_modes) != 2 or any(
  158. mode not in ("normal", "stuck_low", "stuck_high") for mode in limit_modes
  159. ):
  160. raise ValueError("limit_modes must contain two supported modes")
  161. if len(limit_assert_delay_us) != 2 or len(limit_bounce_us) != 2:
  162. raise ValueError("limit timing values require X and Y entries")
  163. if len(lost_step_every) != AXIS_COUNT or any(value < 0 for value in lost_step_every):
  164. raise ValueError("lost_step_every requires three non-negative values")
  165. if min(dir_setup_us, min_step_high_us, min_step_low_us, limit_bounce_period_us) < 0:
  166. raise ValueError("timing values must be non-negative")
  167. if limit_bounce_period_us == 0:
  168. raise ValueError("limit_bounce_period_us must be positive")
  169. self._positions = list(positions)
  170. self._close_dirs = tuple(close_dirs)
  171. self._dir_setup_us = dir_setup_us
  172. self._min_step_high_us = min_step_high_us
  173. self._min_step_low_us = min_step_low_us
  174. self._limit_modes = tuple(limit_modes)
  175. self._limit_assert_delay_us = tuple(limit_assert_delay_us)
  176. self._limit_bounce_us = tuple(limit_bounce_us)
  177. self._limit_bounce_period_us = limit_bounce_period_us
  178. self._swap_xy_limits = swap_xy_limits
  179. self._lost_step_every = tuple(lost_step_every)
  180. self._step_counts = [0, 0, 0]
  181. self._lost_step_counts = [0, 0, 0]
  182. self._uncertain_step_counts = [0, 0, 0]
  183. self._violations: list[TraceViolation] = []
  184. self._last_sample: PinSample | None = None
  185. self._last_dir_change_us = [0, 0, 0]
  186. self._step_rise_us: list[int | None] = [None, None, None]
  187. self._pending_step_valid = [False, False, False]
  188. self._pending_step_dir = [0, 0, 0]
  189. self._last_step_fall_us: list[int | None] = [None, None, None]
  190. self._contact_time_us: list[int | None] = [
  191. 0 if self._positions[index] == 0 else None for index in range(2)
  192. ]
  193. self._last_time_us = 0
  194. @property
  195. def positions(self) -> tuple[int, int, int]:
  196. return tuple(self._positions) # type: ignore[return-value]
  197. @property
  198. def step_counts(self) -> tuple[int, int, int]:
  199. return tuple(self._step_counts) # type: ignore[return-value]
  200. @property
  201. def uncertain_step_counts(self) -> tuple[int, int, int]:
  202. return tuple(self._uncertain_step_counts) # type: ignore[return-value]
  203. @property
  204. def lost_step_counts(self) -> tuple[int, int, int]:
  205. return tuple(self._lost_step_counts) # type: ignore[return-value]
  206. @property
  207. def violations(self) -> tuple[TraceViolation, ...]:
  208. return tuple(self._violations)
  209. def _record(self, kind: str, axis: int, time_us: int) -> None:
  210. item = TraceViolation(kind=kind, axis=axis, time_us=time_us)
  211. if item not in self._violations:
  212. self._violations.append(item)
  213. def observe(self, sample: PinSample) -> int:
  214. if sample.time_us < self._last_time_us:
  215. raise ValueError("pin samples must be monotonic")
  216. if sample.en_n not in (0, 1):
  217. raise ValueError("en_n must be zero or one")
  218. if len(sample.direction) != AXIS_COUNT or len(sample.step) != AXIS_COUNT:
  219. raise ValueError("direction and step require exactly three axes")
  220. if any(value not in (0, 1) for value in (*sample.direction, *sample.step)):
  221. raise ValueError("direction and step values must be binary")
  222. previous = self._last_sample
  223. if previous is None:
  224. self._last_dir_change_us = [sample.time_us] * AXIS_COUNT
  225. previous_direction = sample.direction
  226. previous_step = (0, 0, 0)
  227. previous_en_n = 1
  228. else:
  229. previous_direction = previous.direction
  230. previous_step = previous.step
  231. previous_en_n = previous.en_n
  232. for axis in range(AXIS_COUNT):
  233. if sample.direction[axis] != previous_direction[axis]:
  234. if previous_step[axis] or sample.step[axis]:
  235. self._record("dir_changed_while_step_high", axis, sample.time_us)
  236. self._pending_step_valid[axis] = False
  237. self._last_dir_change_us[axis] = sample.time_us
  238. rising = not previous_step[axis] and bool(sample.step[axis])
  239. falling = bool(previous_step[axis]) and not sample.step[axis]
  240. truncated = (
  241. not previous_en_n
  242. and sample.en_n
  243. and bool(previous_step[axis] or sample.step[axis])
  244. )
  245. if truncated:
  246. self._record("step_truncated", axis, sample.time_us)
  247. self._pending_step_valid[axis] = False
  248. if rising:
  249. valid = True
  250. if sample.en_n:
  251. self._record("step_while_disabled", axis, sample.time_us)
  252. valid = False
  253. if sample.time_us - self._last_dir_change_us[axis] < self._dir_setup_us:
  254. self._record("dir_setup", axis, sample.time_us)
  255. valid = False
  256. last_fall = self._last_step_fall_us[axis]
  257. if last_fall is not None and sample.time_us - last_fall < self._min_step_low_us:
  258. self._record("step_low_width", axis, sample.time_us)
  259. valid = False
  260. self._step_rise_us[axis] = sample.time_us
  261. self._pending_step_valid[axis] = valid
  262. self._pending_step_dir[axis] = sample.direction[axis]
  263. if falling:
  264. rise = self._step_rise_us[axis]
  265. if rise is not None and sample.time_us - rise < self._min_step_high_us:
  266. self._record("step_high_width", axis, sample.time_us)
  267. self._pending_step_valid[axis] = False
  268. if rise is not None and self._pending_step_valid[axis]:
  269. self._step_counts[axis] += 1
  270. drop_every = self._lost_step_every[axis]
  271. if drop_every and self._step_counts[axis] % drop_every == 0:
  272. self._lost_step_counts[axis] += 1
  273. else:
  274. if self._pending_step_dir[axis] == self._close_dirs[axis]:
  275. self._positions[axis] = max(0, self._positions[axis] - 1)
  276. else:
  277. self._positions[axis] += 1
  278. if axis < 2:
  279. if self._positions[axis] == 0 and self._contact_time_us[axis] is None:
  280. self._contact_time_us[axis] = sample.time_us
  281. elif self._positions[axis] > 0:
  282. self._contact_time_us[axis] = None
  283. elif rise is not None:
  284. self._uncertain_step_counts[axis] += 1
  285. self._step_rise_us[axis] = None
  286. self._pending_step_valid[axis] = False
  287. self._last_step_fall_us[axis] = sample.time_us
  288. self._last_sample = sample
  289. self._last_time_us = sample.time_us
  290. return self.read_limit_raw_mask(sample.time_us)
  291. def _limit_value(self, axis: int, time_us: int) -> int:
  292. mode = self._limit_modes[axis]
  293. if mode == "stuck_low":
  294. return 0
  295. if mode == "stuck_high":
  296. return 1
  297. if self._positions[axis] != 0:
  298. return 0
  299. contact = self._contact_time_us[axis]
  300. if contact is None:
  301. return 0
  302. elapsed = max(0, time_us - contact)
  303. delay = self._limit_assert_delay_us[axis]
  304. if elapsed < delay:
  305. return 0
  306. bounce_elapsed = elapsed - delay
  307. bounce_window = self._limit_bounce_us[axis]
  308. if bounce_elapsed < bounce_window:
  309. return int((bounce_elapsed // self._limit_bounce_period_us) % 2 == 0)
  310. return 1
  311. def read_limit_raw_mask(self, time_us: int | None = None) -> int:
  312. now = self._last_time_us if time_us is None else time_us
  313. values = [self._limit_value(0, now), self._limit_value(1, now)]
  314. if self._swap_xy_limits:
  315. values.reverse()
  316. return values[0] | (values[1] << 1)
  317. def replay_mechanical_trace(
  318. plant: MechanicalPlant,
  319. samples: Iterable[PinSample],
  320. ) -> MechanicalTraceReport:
  321. limit_raw_mask = plant.read_limit_raw_mask(0)
  322. for sample in samples:
  323. limit_raw_mask = plant.observe(sample)
  324. return MechanicalTraceReport(
  325. positions=plant.positions,
  326. step_counts=plant.step_counts,
  327. lost_step_counts=plant.lost_step_counts,
  328. uncertain_step_counts=plant.uncertain_step_counts,
  329. limit_raw_mask=limit_raw_mask,
  330. violations=plant.violations,
  331. )
  332. def compare_mechanical_reports(
  333. reference: MechanicalTraceReport,
  334. candidate: MechanicalTraceReport,
  335. ) -> MechanicalDifference:
  336. mismatches = tuple(
  337. name
  338. for name in (
  339. "positions",
  340. "step_counts",
  341. "lost_step_counts",
  342. "uncertain_step_counts",
  343. "limit_raw_mask",
  344. "violations",
  345. )
  346. if getattr(reference, name) != getattr(candidate, name)
  347. )
  348. return MechanicalDifference(matches=not mismatches, mismatches=mismatches)
  349. def compare_pin_traces(
  350. *,
  351. reference_plant: MechanicalPlant,
  352. candidate_plant: MechanicalPlant,
  353. reference_samples: Iterable[PinSample],
  354. candidate_samples: Iterable[PinSample],
  355. ) -> MechanicalDifference:
  356. return compare_mechanical_reports(
  357. replay_mechanical_trace(reference_plant, reference_samples),
  358. replay_mechanical_trace(candidate_plant, candidate_samples),
  359. )
  360. @dataclass
  361. class AxisState:
  362. state: str = AXIS_UNCALIBRATED
  363. position_valid: bool = False
  364. busy: bool = False
  365. current: int = UNKNOWN_POSITION
  366. target: int = UNKNOWN_POSITION
  367. fault: bool = False
  368. move_kind: str = "idle"
  369. raw_dir: int | None = None
  370. speed_code: int | None = None
  371. remaining_steps: int = 0
  372. drive_active: bool = False
  373. step_phase: str = "idle"
  374. pending_jog: tuple[int, int, int] | None = None
  375. steps_executed: int = 0
  376. step_elapsed_ms: int = 0
  377. dir_setup_remaining_ms: int = 0
  378. @dataclass(frozen=True)
  379. class ModelResult:
  380. accepted: bool
  381. command: int
  382. status: int
  383. detail: int
  384. state_hash16: int
  385. response_type: int = 0
  386. result_flags: int = 0
  387. response: bytes | None = None
  388. reason: str = ""
  389. def crc16_ccitt_false(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
  390. crc = initial & 0xFFFF
  391. for byte in bytes(data):
  392. crc ^= byte << 8
  393. for _ in range(8):
  394. if crc & 0x8000:
  395. crc = ((crc << 1) ^ 0x1021) & 0xFFFF
  396. else:
  397. crc = (crc << 1) & 0xFFFF
  398. return crc
  399. def _byte_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  400. result = tuple(values)
  401. if len(result) != count:
  402. raise ValueError(f"{label} requires exactly {count} values")
  403. for index, value in enumerate(result):
  404. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
  405. raise ValueError(f"{label}[{index}] must fit in one byte")
  406. return result
  407. def _percent_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  408. result = _byte_values(values, count=count, label=label)
  409. for index, value in enumerate(result):
  410. if value > 100:
  411. raise ValueError(f"{label}[{index}] must be from 0 to 100")
  412. return result
  413. def _binary_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  414. result = _byte_values(values, count=count, label=label)
  415. for index, value in enumerate(result):
  416. if value not in (0, 100):
  417. raise ValueError(f"{label}[{index}] must be 0 or 100")
  418. return result
  419. def state_hash16(ptc_percent: Iterable[int], fan_percent: Iterable[int], solenoid: int) -> int:
  420. ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
  421. fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
  422. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  423. return crc16_ccitt_false(bytes(ptc + fan + (checked_solenoid,)))
  424. def _freeze_state(value: object) -> object:
  425. if isinstance(value, dict):
  426. return tuple(
  427. (key, _freeze_state(item))
  428. for key, item in sorted(value.items())
  429. )
  430. if isinstance(value, (list, tuple)):
  431. return tuple(_freeze_state(item) for item in value)
  432. return value
  433. def encode_standard_frame(frame_type: int, payload: bytes | bytearray | Iterable[int]) -> bytes:
  434. payload_bytes = bytes(payload)
  435. if not 0 <= frame_type <= 0xFF:
  436. raise ValueError("frame_type must fit in one byte")
  437. if len(payload_bytes) > 0xFF:
  438. raise ValueError("payload is too long")
  439. body = bytes((VERSION, PROFILE, frame_type))
  440. body += b"\x00" * 8
  441. body += bytes((len(payload_bytes),)) + payload_bytes
  442. return MAGIC + body + crc16_ccitt_false(body).to_bytes(2, "little")
  443. def encode_snapshot_frame(
  444. *,
  445. ptc_percent: Iterable[int],
  446. fan_percent: Iterable[int],
  447. solenoid: int,
  448. xyz: Iterable[int],
  449. ) -> bytes:
  450. ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
  451. fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
  452. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  453. checked_xyz = _byte_values(xyz, count=AXIS_COUNT, label="XYZ")
  454. payload = bytes((CMD_SET_SNAPSHOT, 0, *ptc, *fan, checked_solenoid, *checked_xyz))
  455. return encode_standard_frame(FRAME_HOST_BATCH, payload)
  456. def encode_motion_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
  457. payload_bytes = bytes(payload)
  458. if len(payload_bytes) != 8:
  459. raise ValueError("motion payload must contain exactly eight bytes")
  460. return encode_standard_frame(FRAME_MOTION_CMD, payload_bytes)
  461. def encode_host_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
  462. payload_bytes = bytes(payload)
  463. if len(payload_bytes) != 4:
  464. raise ValueError("host command payload must contain exactly four bytes")
  465. return encode_standard_frame(FRAME_HOST_CMD, payload_bytes)
  466. def _decode_standard_frame(frame: bytes | bytearray) -> tuple[int, bytes]:
  467. raw = bytes(frame)
  468. if len(raw) < 16:
  469. raise ModelFrameError("frame is truncated", status=STATUS_BAD_LENGTH)
  470. if raw[:2] != MAGIC:
  471. raise ModelFrameError("bad frame magic")
  472. if raw[2] != VERSION or raw[3] != PROFILE:
  473. raise ModelFrameError("bad frame identity")
  474. if raw[5:13] != b"\x00" * 8:
  475. raise ModelFrameError("seq and timestamp must be zero")
  476. payload_length = raw[13]
  477. expected_length = 16 + payload_length
  478. if len(raw) != expected_length:
  479. raise ModelFrameError("frame length mismatch", status=STATUS_BAD_LENGTH)
  480. expected_crc = crc16_ccitt_false(raw[2:-2])
  481. actual_crc = int.from_bytes(raw[-2:], "little")
  482. if actual_crc != expected_crc:
  483. raise ModelFrameError("frame CRC mismatch")
  484. return raw[4], raw[14:-2]
  485. GOLDEN_VECTORS = {
  486. "enable": bytes.fromhex(
  487. "a55a0204070000000000000000222a00"
  488. "000000000000000000000000000000000000000000000000"
  489. "1e1e1e1e00000000d6df"
  490. ),
  491. "jog_x": bytes.fromhex("a55a020411000000000000000008350001000100000086c3"),
  492. "jog_y": bytes.fromhex("a55a0204110000000000000000083501000001000000473e"),
  493. "mark_x": bytes.fromhex("a55a0204110000000000000000083600010000000000477d"),
  494. "mark_y": bytes.fromhex("a55a02041100000000000000000836010000000000008680"),
  495. "open": bytes.fromhex(
  496. "a55a0204070000000000000000222a00"
  497. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  498. "46464646646464642c75"
  499. ),
  500. "close": bytes.fromhex(
  501. "a55a0204070000000000000000222a00"
  502. "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
  503. "4646464600000000684a"
  504. ),
  505. "disable": bytes.fromhex("a55a02040500000000000000000426000000c4ae"),
  506. }
  507. class NormalV3Model:
  508. def __init__(self) -> None:
  509. self.ptc_percent = SAFE_PTC
  510. self.fan_percent = SAFE_FAN
  511. self.solenoid = SAFE_SOLENOID
  512. self.axes = [AxisState() for _ in range(AXIS_COUNT)]
  513. self.disabled = True
  514. self.watchdog_timeout = False
  515. self.watchdog_armed = False
  516. self.watchdog_elapsed_ms = 0
  517. @property
  518. def state_hash16(self) -> int:
  519. return state_hash16(self.ptc_percent, self.fan_percent, self.solenoid)
  520. @property
  521. def busy_mask(self) -> int:
  522. return 0
  523. @property
  524. def active_mask(self) -> int:
  525. return sum(
  526. (1 << index)
  527. for index, axis in enumerate(self.axes[:2])
  528. if axis.drive_active
  529. )
  530. @property
  531. def position_valid_mask(self) -> int:
  532. return 0
  533. @property
  534. def fault_mask(self) -> int:
  535. return 0
  536. def state_fingerprint(self) -> tuple[object, ...]:
  537. frozen = _freeze_state(self.state_payload())
  538. if not isinstance(frozen, tuple):
  539. raise AssertionError("state payload did not freeze to a tuple")
  540. return frozen
  541. def state_payload(self) -> dict[str, object]:
  542. return {
  543. "ptc_percent": list(self.ptc_percent),
  544. "fan_percent": list(self.fan_percent),
  545. "solenoid": self.solenoid,
  546. "state_hash16": self.state_hash16,
  547. "disabled": self.disabled,
  548. "watchdog_timeout": self.watchdog_timeout,
  549. "watchdog_armed": self.watchdog_armed,
  550. "watchdog_elapsed_ms": self.watchdog_elapsed_ms,
  551. "position_valid_mask": self.position_valid_mask,
  552. "busy_mask": self.busy_mask,
  553. "active_mask": self.active_mask,
  554. "fault_mask": self.fault_mask,
  555. "axes": [asdict(axis) for axis in self.axes],
  556. }
  557. @staticmethod
  558. def _set_xy_state(axis: AxisState, state: str) -> None:
  559. axis.state = state
  560. axis.fault = False
  561. axis.position_valid = False
  562. axis.current = UNKNOWN_POSITION
  563. axis.target = UNKNOWN_POSITION
  564. if state not in (
  565. AXIS_UNCALIBRATED,
  566. AXIS_CLOSED,
  567. AXIS_OPENING,
  568. AXIS_OPEN,
  569. AXIS_CLOSING,
  570. AXIS_INTERMEDIATE,
  571. ):
  572. raise ValueError(f"unsupported XY axis state: {state}")
  573. @staticmethod
  574. def _clear_motion(axis: AxisState) -> None:
  575. axis.busy = False
  576. axis.drive_active = False
  577. axis.step_phase = "idle"
  578. axis.pending_jog = None
  579. axis.move_kind = "idle"
  580. axis.remaining_steps = 0
  581. axis.steps_executed = 0
  582. axis.step_elapsed_ms = 0
  583. axis.dir_setup_remaining_ms = 0
  584. def _result(
  585. self,
  586. *,
  587. accepted: bool,
  588. command: int,
  589. status: int,
  590. detail: int = 0,
  591. response_type: int = 0,
  592. result_flags: int = 0,
  593. response: bytes | None = None,
  594. reason: str = "",
  595. ) -> ModelResult:
  596. return ModelResult(
  597. accepted=accepted,
  598. command=command,
  599. status=status,
  600. detail=detail,
  601. state_hash16=self.state_hash16,
  602. response_type=response_type,
  603. result_flags=result_flags,
  604. response=response,
  605. reason=reason,
  606. )
  607. def _arm_watchdog(self) -> None:
  608. self.disabled = False
  609. self.watchdog_timeout = False
  610. self.watchdog_armed = True
  611. self.watchdog_elapsed_ms = 0
  612. def _refresh_watchdog(self) -> None:
  613. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  614. self.watchdog_elapsed_ms = 0
  615. def advance_time(self, elapsed_ms: int) -> None:
  616. """Advance wall-clock time, including complete modeled STEP cycles."""
  617. if elapsed_ms < 0:
  618. raise ValueError("elapsed_ms must be non-negative")
  619. remaining_ms = elapsed_ms
  620. while remaining_ms > 0:
  621. delta_ms = remaining_ms
  622. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  623. delta_ms = min(
  624. delta_ms,
  625. WATCHDOG_TIMEOUT_MS - self.watchdog_elapsed_ms,
  626. )
  627. accumulating_axes: list[int] = []
  628. for axis_index, axis in enumerate(self.axes[:2]):
  629. if not axis.drive_active or axis.remaining_steps <= 0:
  630. continue
  631. if axis.dir_setup_remaining_ms > 0:
  632. delta_ms = min(delta_ms, axis.dir_setup_remaining_ms)
  633. continue
  634. accumulating_axes.append(axis_index)
  635. speed_code = axis.speed_code if axis.speed_code is not None else 3
  636. step_due_ms = SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms
  637. delta_ms = min(delta_ms, step_due_ms)
  638. self._advance_control_time(delta_ms)
  639. remaining_ms -= delta_ms
  640. for axis_index in accumulating_axes:
  641. axis = self.axes[axis_index]
  642. if axis.drive_active and axis.dir_setup_remaining_ms == 0:
  643. axis.step_elapsed_ms += delta_ms
  644. for axis_index, axis in enumerate(self.axes[:2]):
  645. if (
  646. not axis.drive_active
  647. or axis.dir_setup_remaining_ms > 0
  648. or axis.remaining_steps <= 0
  649. ):
  650. continue
  651. speed_code = axis.speed_code if axis.speed_code is not None else 3
  652. if axis.step_elapsed_ms < SPEED_STEP_MS[speed_code]:
  653. continue
  654. if axis.step_phase == "idle":
  655. self._commit_axis_step(axis_index)
  656. else:
  657. self.finish_axis_step(axis_index)
  658. def _advance_control_time(self, elapsed_ms: int) -> None:
  659. if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
  660. if self.watchdog_elapsed_ms + elapsed_ms >= WATCHDOG_TIMEOUT_MS:
  661. self.watchdog_expire()
  662. else:
  663. self.watchdog_elapsed_ms += elapsed_ms
  664. for axis_index, axis in enumerate(self.axes[:2]):
  665. if axis.dir_setup_remaining_ms <= 0:
  666. continue
  667. axis.dir_setup_remaining_ms = max(
  668. 0,
  669. axis.dir_setup_remaining_ms - elapsed_ms,
  670. )
  671. if axis.dir_setup_remaining_ms == 0 and axis.drive_active:
  672. self._complete_dir_setup(axis_index)
  673. def _complete_dir_setup(self, axis_index: int) -> None:
  674. axis = self.axes[axis_index]
  675. if not axis.drive_active:
  676. return
  677. axis.drive_active = True
  678. def _safe_outputs(self) -> None:
  679. self.ptc_percent = SAFE_PTC
  680. self.fan_percent = SAFE_FAN
  681. self.solenoid = SAFE_SOLENOID
  682. def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
  683. self._safe_outputs()
  684. self.disabled = disabled
  685. self.watchdog_timeout = watchdog_timeout
  686. self.watchdog_armed = False
  687. self.watchdog_elapsed_ms = 0
  688. def disable(self) -> None:
  689. self._force_safe(disabled=True, watchdog_timeout=False)
  690. def watchdog_expire(self) -> None:
  691. if self.watchdog_armed and not self.disabled:
  692. self._force_safe(disabled=True, watchdog_timeout=True)
  693. def apply_frame(
  694. self,
  695. frame: bytes | bytearray,
  696. ) -> ModelResult:
  697. before = self.state_fingerprint()
  698. try:
  699. frame_type, payload = _decode_standard_frame(frame)
  700. if frame_type == FRAME_HOST_BATCH:
  701. result = self._apply_snapshot(payload)
  702. elif frame_type == FRAME_HOST_CMD:
  703. result = self._apply_host(payload)
  704. elif frame_type == FRAME_MOTION_CMD:
  705. result = self._apply_motion(payload)
  706. else:
  707. result = self._result(
  708. accepted=False,
  709. command=payload[0] if payload else 0,
  710. status=STATUS_UNSUPPORTED,
  711. reason="unsupported input frame type",
  712. )
  713. except ModelFrameError as exc:
  714. result = self._result(
  715. accepted=False,
  716. command=0,
  717. status=exc.status,
  718. reason=str(exc),
  719. )
  720. except HostContractViolation:
  721. raise
  722. except ValueError as exc:
  723. result = self._result(
  724. accepted=False,
  725. command=0,
  726. status=STATUS_BAD_VALUE,
  727. reason=str(exc),
  728. )
  729. if not result.accepted and self.state_fingerprint() != before:
  730. raise AssertionError("rejected frame changed modeled state")
  731. return result
  732. def _apply_snapshot(
  733. self,
  734. payload: bytes,
  735. ) -> ModelResult:
  736. command = payload[0] if payload else 0
  737. if len(payload) != 34:
  738. raise ModelFrameError("snapshot payload length must be 34", status=STATUS_BAD_LENGTH)
  739. if payload[0] != CMD_SET_SNAPSHOT:
  740. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  741. if payload[1] != 0:
  742. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  743. ptc = tuple(payload[2:26])
  744. fan = tuple(payload[26:30])
  745. solenoid = payload[30]
  746. xyz = tuple(payload[31:34])
  747. try:
  748. checked_ptc = _percent_values(ptc, count=PTC_COUNT, label="PTC")
  749. checked_fan = _percent_values(fan, count=FAN_COUNT, label="FAN")
  750. checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
  751. except ValueError as exc:
  752. return self._result(
  753. accepted=False,
  754. command=command,
  755. status=STATUS_BAD_VALUE,
  756. reason=str(exc),
  757. )
  758. self.ptc_percent = checked_ptc
  759. self.fan_percent = checked_fan
  760. self.solenoid = checked_solenoid
  761. self._arm_watchdog()
  762. return self._result(
  763. accepted=True,
  764. command=command,
  765. status=STATUS_OK,
  766. detail=0,
  767. result_flags=0x01,
  768. )
  769. def _apply_host(self, payload: bytes) -> ModelResult:
  770. command = payload[0] if payload else 0
  771. if len(payload) != 4:
  772. raise ModelFrameError("host payload length must be four", status=STATUS_BAD_LENGTH)
  773. if payload[3] != 0:
  774. return self._result(accepted=False, command=command, status=STATUS_BAD_FLAGS)
  775. if payload[1:3] != b"\x00\x00":
  776. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  777. if command == CMD_GET_STATUS:
  778. detail = int(self.disabled) | (int(self.watchdog_timeout) << 1)
  779. return self._result(accepted=True, command=command, status=STATUS_OK, detail=detail)
  780. if command == CMD_DISABLE:
  781. self.disable()
  782. return self._result(accepted=True, command=command, status=STATUS_OK, detail=1)
  783. return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
  784. def _apply_motion(
  785. self,
  786. payload: bytes,
  787. ) -> ModelResult:
  788. command = payload[0] if payload else 0
  789. if len(payload) != 8:
  790. raise ModelFrameError("motion payload length must be eight", status=STATUS_BAD_LENGTH)
  791. if command == MOTION_JOG:
  792. return self._apply_jog(payload)
  793. if command == MOTION_MARK_CLOSED:
  794. return self._result(
  795. accepted=False,
  796. command=command,
  797. status=STATUS_UNSUPPORTED,
  798. reason="MARK_CLOSED is retired",
  799. )
  800. if command == MOTION_GET_STATUS:
  801. if payload[1:] != b"\x00" * 7:
  802. return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
  803. self._refresh_watchdog()
  804. return self._result(
  805. accepted=True,
  806. command=command,
  807. status=STATUS_OK,
  808. response_type=FRAME_MOTION_STATUS,
  809. result_flags=0x08,
  810. response=self.motor_status_payload(),
  811. )
  812. return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
  813. def _apply_jog(
  814. self,
  815. payload: bytes,
  816. ) -> ModelResult:
  817. axis_index = payload[1]
  818. raw_dir = payload[2]
  819. speed_code = payload[3]
  820. steps = int.from_bytes(payload[4:6], "little")
  821. if steps == 0:
  822. raise HostContractViolation(
  823. f"{RAW_STEP_POLICY}: steps=0 violates the trusted-host precondition"
  824. )
  825. if (
  826. axis_index not in (0, 1)
  827. or raw_dir not in (0, 1)
  828. or speed_code >= 4
  829. or payload[6:] != b"\x00\x00"
  830. ):
  831. return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BAD_VALUE)
  832. axis = self.axes[axis_index]
  833. self._set_xy_state(axis, AXIS_INTERMEDIATE)
  834. self._load_force_jog(
  835. axis,
  836. raw_dir=raw_dir,
  837. speed_code=speed_code,
  838. steps=steps,
  839. )
  840. axis.dir_setup_remaining_ms = 0
  841. self.begin_axis_step(axis_index)
  842. return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
  843. def _load_force_jog(
  844. self,
  845. axis: AxisState,
  846. *,
  847. raw_dir: int,
  848. speed_code: int,
  849. steps: int,
  850. ) -> None:
  851. axis.busy = False
  852. axis.drive_active = True
  853. axis.step_phase = "idle"
  854. axis.pending_jog = None
  855. axis.move_kind = "jog"
  856. axis.raw_dir = raw_dir
  857. axis.speed_code = speed_code
  858. axis.remaining_steps = steps
  859. axis.steps_executed = 0
  860. axis.step_elapsed_ms = 0
  861. axis.dir_setup_remaining_ms = DIR_SETUP_MS
  862. def _complete_motion_segment(self, axis_index: int) -> None:
  863. axis = self.axes[axis_index]
  864. if axis_index not in (0, 1) or axis.move_kind != "jog":
  865. raise AssertionError("only X/Y JOG can complete motor motion")
  866. self._set_xy_state(axis, AXIS_INTERMEDIATE)
  867. self._clear_motion(axis)
  868. def _prepare_axis_event(self, axis_index: int) -> tuple[int, str] | None:
  869. axis = self.axes[axis_index]
  870. while axis.drive_active and axis.remaining_steps <= 0:
  871. self._complete_motion_segment(axis_index)
  872. if not axis.drive_active:
  873. return None
  874. if axis.dir_setup_remaining_ms > 0:
  875. return axis.dir_setup_remaining_ms, "setup"
  876. if not axis.drive_active or axis.remaining_steps <= 0:
  877. return None
  878. speed_code = axis.speed_code if axis.speed_code is not None else 3
  879. return SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms, "step"
  880. def _commit_axis_step(self, axis_index: int) -> None:
  881. self.begin_axis_step(axis_index)
  882. self.finish_axis_step(axis_index)
  883. def begin_axis_step(self, axis_index: int) -> None:
  884. if axis_index not in (0, 1):
  885. raise ValueError("only X and Y execute motion")
  886. axis = self.axes[axis_index]
  887. if (
  888. not axis.drive_active
  889. or axis.dir_setup_remaining_ms > 0
  890. or axis.remaining_steps <= 0
  891. or axis.step_phase != "idle"
  892. ):
  893. raise ValueError("axis has no complete step ready to commit")
  894. axis.step_phase = "high"
  895. axis.busy = False
  896. def lower_axis_step(self, axis_index: int) -> None:
  897. if axis_index not in (0, 1):
  898. raise ValueError("only X and Y execute motion")
  899. axis = self.axes[axis_index]
  900. if not axis.drive_active or axis.step_phase != "high":
  901. raise ValueError("axis has no high step phase to lower")
  902. axis.step_phase = "low"
  903. def finish_axis_step(self, axis_index: int) -> None:
  904. if axis_index not in (0, 1):
  905. raise ValueError("only X and Y execute motion")
  906. axis = self.axes[axis_index]
  907. if not axis.drive_active or axis.step_phase not in ("high", "low"):
  908. raise ValueError("axis has no started step to finish")
  909. axis.step_phase = "low"
  910. axis.remaining_steps -= 1
  911. axis.steps_executed += 1
  912. axis.step_elapsed_ms = 0
  913. pending = axis.pending_jog
  914. axis.pending_jog = None
  915. axis.step_phase = "idle"
  916. if pending is not None:
  917. axis.busy = False
  918. raw_dir, speed_code, steps = pending
  919. self._load_force_jog(
  920. axis,
  921. raw_dir=raw_dir,
  922. speed_code=speed_code,
  923. steps=steps,
  924. )
  925. elif axis.drive_active and axis.remaining_steps == 0:
  926. self._complete_motion_segment(axis_index)
  927. def execute_parallel_steps(self, counts: Sequence[int]) -> tuple[int, int, int]:
  928. if len(counts) != AXIS_COUNT or any(count < 0 for count in counts):
  929. raise ValueError("counts require three non-negative axis values")
  930. if counts[2] != 0:
  931. raise ValueError("Z is protocol-only and cannot execute steps")
  932. remaining = list(counts)
  933. executed = [0, 0, 0]
  934. due_ms: list[int | None] = [None, None, None]
  935. due_kind: list[str | None] = [None, None, None]
  936. if any(remaining):
  937. omitted_active = [
  938. axis_index
  939. for axis_index, axis in enumerate(self.axes)
  940. if axis.drive_active
  941. and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
  942. and remaining[axis_index] == 0
  943. ]
  944. if omitted_active:
  945. raise ValueError(
  946. "counts must include every concurrently active axis: "
  947. + ",".join(map(str, omitted_active))
  948. )
  949. while any(remaining):
  950. for axis_index in range(AXIS_COUNT):
  951. if remaining[axis_index] and due_ms[axis_index] is None:
  952. event = self._prepare_axis_event(axis_index)
  953. if event is not None:
  954. due_ms[axis_index], due_kind[axis_index] = event
  955. active_due = [value for value in due_ms if value is not None]
  956. if not active_due:
  957. break
  958. elapsed_ms = min(active_due)
  959. self._advance_control_time(elapsed_ms)
  960. for axis_index in range(AXIS_COUNT):
  961. if due_ms[axis_index] is not None:
  962. due_ms[axis_index] -= elapsed_ms
  963. for axis_index in range(AXIS_COUNT):
  964. if due_ms[axis_index] != 0:
  965. continue
  966. if due_kind[axis_index] == "setup":
  967. if self.axes[axis_index].dir_setup_remaining_ms != 0:
  968. raise AssertionError("DIR setup event completed early")
  969. elif due_kind[axis_index] == "step":
  970. self._commit_axis_step(axis_index)
  971. executed[axis_index] += 1
  972. remaining[axis_index] -= 1
  973. else:
  974. raise AssertionError("scheduled axis event has no kind")
  975. due_ms[axis_index] = None
  976. due_kind[axis_index] = None
  977. if any(remaining):
  978. frozen = [
  979. axis_index
  980. for axis_index, axis in enumerate(self.axes)
  981. if axis.drive_active
  982. and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
  983. and remaining[axis_index] == 0
  984. ]
  985. if frozen:
  986. raise ValueError(
  987. "requested counts would freeze active axes: "
  988. + ",".join(map(str, frozen))
  989. )
  990. return tuple(executed) # type: ignore[return-value]
  991. def execute_axis_steps(self, axis_index: int, count: int) -> int:
  992. if axis_index not in (0, 1):
  993. raise ValueError("only X and Y execute motion")
  994. if count < 0:
  995. raise ValueError("count must be non-negative")
  996. counts = [0, 0, 0]
  997. counts[axis_index] = count
  998. return self.execute_parallel_steps(counts)[axis_index]
  999. def complete_axis(
  1000. self,
  1001. axis_index: int,
  1002. ) -> None:
  1003. if axis_index not in (0, 1):
  1004. raise ValueError("only X and Y execute motion")
  1005. axis = self.axes[axis_index]
  1006. if not axis.drive_active:
  1007. raise ValueError("axis is not active")
  1008. self.execute_axis_steps(axis_index, axis.remaining_steps)
  1009. def motor_status_payload(self) -> bytes:
  1010. flags = 0x02
  1011. flags |= int(self.disabled) << 2
  1012. flags |= int(self.watchdog_timeout) << 3
  1013. return bytes((
  1014. flags,
  1015. 0,
  1016. 0,
  1017. UNKNOWN_POSITION,
  1018. UNKNOWN_POSITION,
  1019. UNKNOWN_POSITION,
  1020. UNKNOWN_POSITION,
  1021. UNKNOWN_POSITION,
  1022. UNKNOWN_POSITION,
  1023. 0,
  1024. ))
  1025. def feed_stream(
  1026. self,
  1027. data: bytes | bytearray,
  1028. ) -> list[ModelResult]:
  1029. raw = bytes(data)
  1030. accepted: list[ModelResult] = []
  1031. offset = 0
  1032. while True:
  1033. start = raw.find(MAGIC, offset)
  1034. if start < 0:
  1035. break
  1036. if len(raw) - start < 16:
  1037. break
  1038. end = start + 16 + raw[start + 13]
  1039. if end > len(raw):
  1040. offset = start + 1
  1041. continue
  1042. result = self.apply_frame(raw[start:end])
  1043. if result.accepted:
  1044. accepted.append(result)
  1045. offset = end if result.accepted else start + 1
  1046. return accepted
  1047. def _verify_golden_encoders() -> list[str]:
  1048. failures: list[str] = []
  1049. generated = {
  1050. "enable": encode_snapshot_frame(
  1051. ptc_percent=(0,) * 24,
  1052. fan_percent=(30,) * 4,
  1053. solenoid=0,
  1054. xyz=(0, 0, 0),
  1055. ),
  1056. "jog_x": encode_motion_frame(bytes((MOTION_JOG, 0, 1, 0, 1, 0, 0, 0))),
  1057. "jog_y": encode_motion_frame(bytes((MOTION_JOG, 1, 0, 0, 1, 0, 0, 0))),
  1058. "mark_x": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 0, 1, 0, 0, 0, 0, 0))),
  1059. "mark_y": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 1, 0, 0, 0, 0, 0, 0))),
  1060. "open": encode_snapshot_frame(
  1061. ptc_percent=(10,) * 24,
  1062. fan_percent=(70,) * 4,
  1063. solenoid=100,
  1064. xyz=(100, 100, 100),
  1065. ),
  1066. "close": encode_snapshot_frame(
  1067. ptc_percent=(10,) * 24,
  1068. fan_percent=(70,) * 4,
  1069. solenoid=0,
  1070. xyz=(0, 0, 0),
  1071. ),
  1072. "disable": encode_host_frame(bytes((CMD_DISABLE, 0, 0, 0))),
  1073. }
  1074. for name, value in generated.items():
  1075. if value != GOLDEN_VECTORS[name]:
  1076. failures.append(name)
  1077. return failures
  1078. def run_replay() -> dict[str, object]:
  1079. checks: list[dict[str, object]] = []
  1080. golden_failures = _verify_golden_encoders()
  1081. checks.append({"name": "fixed_golden_vectors", "status": "pass" if not golden_failures else "fail", "failures": golden_failures})
  1082. subject = NormalV3Model()
  1083. enable = subject.apply_frame(GOLDEN_VECTORS["enable"])
  1084. checks.append({
  1085. "name": "snapshot_xyz_has_no_motor_effect",
  1086. "status": "pass"
  1087. if enable.accepted and subject.active_mask == 0 and subject.busy_mask == 0
  1088. else "fail",
  1089. })
  1090. before_mark = subject.state_fingerprint()
  1091. mark = subject.apply_frame(GOLDEN_VECTORS["mark_x"])
  1092. checks.append({
  1093. "name": "mark_closed_tombstone_unsupported",
  1094. "status": "pass"
  1095. if not mark.accepted
  1096. and mark.status == STATUS_UNSUPPORTED
  1097. and subject.state_fingerprint() == before_mark
  1098. else "fail",
  1099. })
  1100. opened = subject.apply_frame(GOLDEN_VECTORS["open"])
  1101. checks.append({
  1102. "name": "legacy_open_fields_are_ignored",
  1103. "status": "pass"
  1104. if opened.accepted
  1105. and subject.active_mask == 0
  1106. and all(axis.current == UNKNOWN_POSITION for axis in subject.axes[:2])
  1107. else "fail",
  1108. })
  1109. force_jog = encode_motion_frame(
  1110. bytes((MOTION_JOG, 0, 1, 3, 0xFF, 0xFF, 0, 0))
  1111. )
  1112. jog_subject = NormalV3Model()
  1113. jog = jog_subject.apply_frame(force_jog)
  1114. checks.append({
  1115. "name": "jog_preserves_u16_and_acks_on_first_step",
  1116. "status": "pass"
  1117. if jog.accepted
  1118. and jog_subject.axes[0].remaining_steps == 0xFFFF
  1119. and jog_subject.axes[0].step_phase == "high"
  1120. and jog_subject.axes[0].current == UNKNOWN_POSITION
  1121. and jog_subject.active_mask == 1
  1122. and jog_subject.busy_mask == 0
  1123. and not jog_subject.watchdog_armed
  1124. else "fail",
  1125. })
  1126. before_motion = (
  1127. jog_subject.axes[0].drive_active,
  1128. jog_subject.axes[0].raw_dir,
  1129. jog_subject.axes[0].remaining_steps,
  1130. jog_subject.axes[0].step_phase,
  1131. )
  1132. jog_subject.disabled = False
  1133. jog_subject.watchdog_armed = True
  1134. jog_subject.watchdog_expire()
  1135. checks.append({
  1136. "name": "watchdog_safes_outputs_without_motor_effect",
  1137. "status": "pass"
  1138. if before_motion
  1139. == (
  1140. jog_subject.axes[0].drive_active,
  1141. jog_subject.axes[0].raw_dir,
  1142. jog_subject.axes[0].remaining_steps,
  1143. jog_subject.axes[0].step_phase,
  1144. )
  1145. else "fail",
  1146. })
  1147. before_unknown = subject.state_fingerprint()
  1148. unknown = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
  1149. checks.append({
  1150. "name": "temperature_tombstone_unsupported",
  1151. "status": "pass" if not unknown.accepted and unknown.status == STATUS_UNSUPPORTED and subject.state_fingerprint() == before_unknown else "fail",
  1152. })
  1153. final = jog_subject.state_payload()
  1154. motion_status = jog_subject.motor_status_payload()
  1155. final_ok = (
  1156. final["ptc_percent"] == [0] * 24
  1157. and final["fan_percent"] == [30] * 4
  1158. and final["solenoid"] == 0
  1159. and final["active_mask"] == 1
  1160. and final["busy_mask"] == 0
  1161. and final["axes"][0]["current"] == UNKNOWN_POSITION
  1162. and final["watchdog_timeout"] is True
  1163. and motion_status[0] & 0x02
  1164. and motion_status[1:] == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
  1165. )
  1166. checks.append({"name": "constant_motion_status", "status": "pass" if final_ok else "fail"})
  1167. status = "pass" if all(check["status"] == "pass" for check in checks) else "fail"
  1168. return {
  1169. "status": status,
  1170. "verification_layer": "binary921_v3_replay",
  1171. "vector_set": "binary921-v3-golden-v1",
  1172. "golden_vector_count": len(GOLDEN_VECTORS),
  1173. "checks": checks,
  1174. "final_state": final,
  1175. "authority_boundary": "Deterministic offline contract replay only; no RTL or hardware is accessed.",
  1176. }
  1177. def run_model() -> dict[str, object]:
  1178. subject = NormalV3Model()
  1179. initial = subject.state_fingerprint()
  1180. bad = bytearray(GOLDEN_VECTORS["open"])
  1181. bad[-1] ^= 1
  1182. rejected = subject.apply_frame(bytes(bad))
  1183. rejected_atomically = not rejected.accepted and subject.state_fingerprint() == initial
  1184. valid = subject.apply_frame(GOLDEN_VECTORS["open"])
  1185. jog_subject = NormalV3Model()
  1186. jog = jog_subject.apply_frame(GOLDEN_VECTORS["jog_x"])
  1187. checks = {
  1188. "canonical_crc": crc16_ccitt_false(b"123456789") == 0x29B1,
  1189. "initial_safe_hash": state_hash16(SAFE_PTC, SAFE_FAN, SAFE_SOLENOID) == 0xE177,
  1190. "bad_crc_rejected_atomically": rejected_atomically,
  1191. "valid_snapshot_committed_without_motor": valid.accepted and subject.ptc_percent == (10,) * 24,
  1192. "snapshot_xyz_ignored": valid.status == STATUS_OK and valid.detail == 0,
  1193. "jog_first_step_ack": (
  1194. jog.accepted
  1195. and jog_subject.active_mask == 1
  1196. and jog_subject.axes[0].step_phase == "high"
  1197. and jog_subject.axes[0].remaining_steps == 1
  1198. and not jog_subject.watchdog_armed
  1199. and jog_subject.busy_mask == 0
  1200. ),
  1201. "status_fields_constant": (
  1202. valid.status == STATUS_OK
  1203. and jog_subject.motor_status_payload()[1:]
  1204. == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
  1205. ),
  1206. }
  1207. return {
  1208. "status": "pass" if all(checks.values()) else "fail",
  1209. "verification_layer": "binary921_v3_model",
  1210. "checks": checks,
  1211. "authority_boundary": "Independent offline state model only; no RTL or hardware is accessed.",
  1212. }
  1213. def _repair_crc(frame: bytes) -> bytes:
  1214. return frame[:-2] + crc16_ccitt_false(frame[2:-2]).to_bytes(2, "little")
  1215. def run_fuzz(*, seed: int = 921003, iterations: int = 600) -> dict[str, object]:
  1216. if iterations < 9:
  1217. raise ValueError("iterations must be at least nine")
  1218. rng = random.Random(seed)
  1219. categories = (
  1220. "frame",
  1221. "crc",
  1222. "length",
  1223. "percent",
  1224. "solenoid",
  1225. "xyz",
  1226. "motion",
  1227. "host_unknown",
  1228. "stream_noise",
  1229. )
  1230. counts = {category: 0 for category in categories}
  1231. unexpected_accepts = 0
  1232. unexpected_rejections = 0
  1233. atomicity_violations = 0
  1234. stream_resync_failures = 0
  1235. for index in range(iterations):
  1236. category = categories[index % len(categories)]
  1237. counts[category] += 1
  1238. subject = NormalV3Model()
  1239. subject.apply_frame(GOLDEN_VECTORS["enable"])
  1240. before = subject.state_fingerprint()
  1241. candidate = bytearray(GOLDEN_VECTORS["open"])
  1242. result: ModelResult | None = None
  1243. expected_accept = False
  1244. if category == "frame":
  1245. variant = rng.randrange(6)
  1246. if variant == 0:
  1247. candidate[0] ^= 1
  1248. elif variant == 1:
  1249. candidate[2] = 3
  1250. candidate = bytearray(_repair_crc(bytes(candidate)))
  1251. elif variant == 2:
  1252. candidate[3] = 5
  1253. candidate = bytearray(_repair_crc(bytes(candidate)))
  1254. elif variant == 3:
  1255. candidate[4] = 0x08
  1256. candidate = bytearray(_repair_crc(bytes(candidate)))
  1257. elif variant == 4:
  1258. candidate[5 + rng.randrange(4)] = 1
  1259. candidate = bytearray(_repair_crc(bytes(candidate)))
  1260. else:
  1261. candidate[9 + rng.randrange(4)] = 1
  1262. candidate = bytearray(_repair_crc(bytes(candidate)))
  1263. result = subject.apply_frame(bytes(candidate))
  1264. elif category == "crc":
  1265. candidate[-rng.choice((1, 2))] ^= 1 << rng.randrange(8)
  1266. result = subject.apply_frame(bytes(candidate))
  1267. elif category == "length":
  1268. candidate[13] = rng.choice(tuple(value for value in range(256) if value != 34))
  1269. candidate = bytearray(_repair_crc(bytes(candidate)))
  1270. result = subject.apply_frame(bytes(candidate))
  1271. elif category == "percent":
  1272. candidate[16 + rng.randrange(28)] = rng.randrange(101, 256)
  1273. candidate = bytearray(_repair_crc(bytes(candidate)))
  1274. result = subject.apply_frame(bytes(candidate))
  1275. elif category == "solenoid":
  1276. candidate[44] = rng.randrange(1, 100)
  1277. candidate = bytearray(_repair_crc(bytes(candidate)))
  1278. result = subject.apply_frame(bytes(candidate))
  1279. elif category == "xyz":
  1280. candidate[45 + rng.randrange(3)] = rng.randrange(1, 100)
  1281. candidate = bytearray(_repair_crc(bytes(candidate)))
  1282. result = subject.apply_frame(bytes(candidate))
  1283. expected_accept = True
  1284. elif category == "motion":
  1285. variant = rng.randrange(6)
  1286. payload = bytearray((MOTION_JOG, 0, 0, 0, 1, 0, 0, 0))
  1287. if variant == 0:
  1288. payload[1] = 3
  1289. elif variant == 1:
  1290. payload[2] = 2
  1291. elif variant == 2:
  1292. payload[3] = 4
  1293. elif variant == 3:
  1294. payload[4:6] = b"\x00\x00"
  1295. elif variant == 4:
  1296. payload[6] = 1
  1297. else:
  1298. payload[7] = 1
  1299. if variant == 3:
  1300. try:
  1301. subject.apply_frame(encode_motion_frame(payload))
  1302. except HostContractViolation:
  1303. if subject.state_fingerprint() != before:
  1304. atomicity_violations += 1
  1305. else:
  1306. result = subject.apply_frame(encode_motion_frame(payload))
  1307. elif category == "host_unknown":
  1308. result = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
  1309. else:
  1310. noise = b"\xA5\x00\xA5" + bytes(rng.randrange(256) for _ in range(rng.randrange(1, 96)))
  1311. bad_frame = bytearray(GOLDEN_VECTORS["open"])
  1312. bad_frame[-1] ^= 1
  1313. accepted = subject.feed_stream(noise + bytes(bad_frame) + GOLDEN_VECTORS["enable"])
  1314. if len(accepted) != 1 or accepted[0].command != CMD_SET_SNAPSHOT:
  1315. stream_resync_failures += 1
  1316. if result is not None and result.accepted and not expected_accept:
  1317. unexpected_accepts += 1
  1318. if result is not None and not result.accepted and expected_accept:
  1319. unexpected_rejections += 1
  1320. if (
  1321. result is not None
  1322. and not expected_accept
  1323. and subject.state_fingerprint() != before
  1324. ):
  1325. atomicity_violations += 1
  1326. return {
  1327. "status": "pass"
  1328. if unexpected_accepts == 0
  1329. and unexpected_rejections == 0
  1330. and atomicity_violations == 0
  1331. and stream_resync_failures == 0
  1332. else "fail",
  1333. "verification_layer": "binary921_v3_fuzz",
  1334. "seed": seed,
  1335. "iterations": iterations,
  1336. "category_counts": counts,
  1337. "unexpected_accepts": unexpected_accepts,
  1338. "unexpected_rejections": unexpected_rejections,
  1339. "atomicity_violations": atomicity_violations,
  1340. "stream_resync_failures": stream_resync_failures,
  1341. "authority_boundary": "Deterministic malformed-frame fuzzing only; no UART or hardware is accessed.",
  1342. }
  1343. def _extract_production_sources(harness_path: Path) -> list[str]:
  1344. try:
  1345. module = ast.parse(harness_path.read_text(encoding="utf-8-sig"), filename=str(harness_path))
  1346. except (OSError, UnicodeError, SyntaxError) as exc:
  1347. raise ValueError(f"unable to parse production source registry: {exc}") from exc
  1348. for node in module.body:
  1349. if isinstance(node, ast.Assign):
  1350. for target in node.targets:
  1351. if isinstance(target, ast.Name) and target.id == "PROD2U_P4_NORMAL_V3_SOURCES":
  1352. value = ast.literal_eval(node.value)
  1353. if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
  1354. raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES must be a literal string list")
  1355. return value
  1356. if isinstance(node, ast.FunctionDef) and node.name == "active_rtl_sources":
  1357. project_root = harness_path.resolve().parents[1]
  1358. paths = sorted((project_root / "src" / "rtl").glob("*.v"))
  1359. paths.append(project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v")
  1360. return [
  1361. path.relative_to(project_root).as_posix()
  1362. for path in paths
  1363. if path.is_file()
  1364. ]
  1365. raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES is missing")
  1366. def run_detector(root: Path | str = ROOT) -> dict[str, object]:
  1367. project_root = Path(root).resolve()
  1368. failures: list[str] = []
  1369. try:
  1370. sources = _extract_production_sources(project_root / "tools" / "prod2u_p4_harness.py")
  1371. except ValueError as exc:
  1372. sources = []
  1373. failures.append(str(exc))
  1374. forbidden_name_tokens = ("tach", "telemetry", "single_channel", "old_motion")
  1375. forbidden_source_hits = [
  1376. source for source in sources if any(token in source.casefold() for token in forbidden_name_tokens)
  1377. ]
  1378. missing_sources = [source for source in sources if not (project_root / source).is_file()]
  1379. legacy_asset_hits = sorted(
  1380. path for path in LEGACY_P4_ASSET_PATHS if (project_root / path).is_file()
  1381. )
  1382. semantic_patterns = {
  1383. "tach_or_telemetry": re.compile(r"\bFAN_(?:TACH|TELEMETRY)\b|\bTACH_CAPTURE\b", re.IGNORECASE),
  1384. "single_channel": re.compile(r"\b(?:CMD_)?SET_(?:PTC|FAN)\b|\bSINGLE_CHANNEL\b", re.IGNORECASE),
  1385. "old_motion": re.compile(r"\b(?:MOTION|CMD|OPCODE)[A-Z0-9_]*\s*=\s*8'h3[0-4]\b", re.IGNORECASE),
  1386. "ready_semantics": re.compile(r"\b(?:FT|FRAME_TYPE|TYPE|CMD)_READY\b|\bREADY_FRAME\b|\bCAPABILITY_BROADCAST\b", re.IGNORECASE),
  1387. "runtime_build_identity": re.compile(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", re.IGNORECASE),
  1388. }
  1389. forbidden_semantic_hits: list[dict[str, str]] = []
  1390. for source in sources:
  1391. path = project_root / source
  1392. if not path.is_file():
  1393. continue
  1394. try:
  1395. text = path.read_text(encoding="utf-8-sig")
  1396. except (OSError, UnicodeError) as exc:
  1397. failures.append(f"unable to read {source}: {exc}")
  1398. continue
  1399. for semantic, pattern in semantic_patterns.items():
  1400. if pattern.search(text):
  1401. forbidden_semantic_hits.append({"source": source, "semantic": semantic})
  1402. top_path = project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v"
  1403. try:
  1404. top_text = top_path.read_text(encoding="utf-8-sig")
  1405. except (OSError, UnicodeError) as exc:
  1406. top_text = ""
  1407. failures.append(f"unable to read v3 top: {exc}")
  1408. guards = {
  1409. "runtime_build_identity_absent": not bool(
  1410. re.search(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", top_text, re.IGNORECASE)
  1411. ),
  1412. "solenoid_polarity_default_explicit": bool(
  1413. re.search(
  1414. r"parameter\s+integer\s+SOLENOID_ACTIVE_HIGH\s*=\s*[01]",
  1415. top_text,
  1416. re.IGNORECASE,
  1417. )
  1418. ),
  1419. "solenoid_polarity_elaboration_block": "g_solenoid_polarity_must_be_confirmed" in top_text and "prod2u_p4_solenoid_polarity_must_be_confirmed" in top_text,
  1420. }
  1421. missing_guards = [name for name, present in guards.items() if not present]
  1422. if forbidden_source_hits:
  1423. failures.append("forbidden source names are present")
  1424. if forbidden_semantic_hits:
  1425. failures.append("forbidden v2 semantics are present")
  1426. if missing_sources:
  1427. failures.append("production sources are missing")
  1428. if missing_guards:
  1429. failures.append("top-level identity or polarity guards are missing")
  1430. if legacy_asset_hits:
  1431. failures.append("legacy Profile 4 v2 assets are still present")
  1432. if len(sources) != len(set(sources)):
  1433. failures.append("production source list contains duplicates")
  1434. return {
  1435. "status": "pass" if not failures else "fail",
  1436. "verification_layer": "binary921_v3_detector",
  1437. "production_source_count": len(sources),
  1438. "production_sources": sources,
  1439. "forbidden_source_hits": forbidden_source_hits,
  1440. "forbidden_semantic_hits": forbidden_semantic_hits,
  1441. "missing_sources": missing_sources,
  1442. "legacy_asset_hits": legacy_asset_hits,
  1443. "guards": guards,
  1444. "missing_guards": missing_guards,
  1445. "failures": failures,
  1446. "authority_boundary": "Static production-source and elaboration-guard inspection only; no build or hardware is accessed.",
  1447. }
  1448. def run_selftest(root: Path | str = ROOT) -> dict[str, object]:
  1449. reports = {
  1450. "model": run_model(),
  1451. "replay": run_replay(),
  1452. "fuzz": run_fuzz(seed=921003, iterations=60),
  1453. "detector": run_detector(root),
  1454. }
  1455. layers = {name: report["status"] for name, report in reports.items()}
  1456. return {
  1457. "status": "pass" if all(status == "pass" for status in layers.values()) else "fail",
  1458. "profile": PROFILE_ID,
  1459. "hardware_opened": False,
  1460. "layers": layers,
  1461. "reports": reports,
  1462. "authority_boundary": "Offline selftest only; it does not enumerate or open serial, JTAG, or other hardware.",
  1463. }
  1464. def _build_parser() -> argparse.ArgumentParser:
  1465. parser = argparse.ArgumentParser(description=__doc__)
  1466. subparsers = parser.add_subparsers(dest="command", required=True)
  1467. for name in ("model", "replay"):
  1468. child = subparsers.add_parser(name)
  1469. child.add_argument("--json", action="store_true")
  1470. fuzz = subparsers.add_parser("fuzz")
  1471. fuzz.add_argument("--seed", type=int, default=921003)
  1472. fuzz.add_argument("--iterations", type=int, default=600)
  1473. fuzz.add_argument("--json", action="store_true")
  1474. detector = subparsers.add_parser("detector")
  1475. detector.add_argument("--root", type=Path, default=ROOT)
  1476. detector.add_argument("--json", action="store_true")
  1477. selftest = subparsers.add_parser("selftest")
  1478. selftest.add_argument("--root", type=Path, default=ROOT)
  1479. selftest.add_argument("--json", action="store_true")
  1480. return parser
  1481. def main(argv: Sequence[str] | None = None) -> int:
  1482. args = _build_parser().parse_args(argv)
  1483. if args.command == "model":
  1484. report = run_model()
  1485. elif args.command == "replay":
  1486. report = run_replay()
  1487. elif args.command == "fuzz":
  1488. report = run_fuzz(seed=args.seed, iterations=args.iterations)
  1489. elif args.command == "detector":
  1490. report = run_detector(args.root)
  1491. else:
  1492. report = run_selftest(args.root)
  1493. print(json.dumps(report, indent=2, sort_keys=True))
  1494. return 0 if report.get("status") == "pass" else 1
  1495. if __name__ == "__main__":
  1496. raise SystemExit(main())