prod2u_p4_normal_v3_model.py 66 KB

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