| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653 |
- #!/usr/bin/env python3
- """Independent binary921-v3 model, replay, fuzz, and source detector.
- This verification-only oracle intentionally does not import the production
- protocol helper or any RTL-derived implementation. It models externally
- visible Profile 4 Normal behavior from the wire contract.
- """
- from __future__ import annotations
- import argparse
- import ast
- import json
- import random
- import re
- from dataclasses import asdict, dataclass
- from pathlib import Path
- from typing import Iterable, Sequence
- ROOT = Path(__file__).resolve().parents[1]
- PROFILE_ID = "prod2u-p4-normal-actuator-binary921-v3"
- RAW_STEP_POLICY = "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP"
- FAST_PATH_POLICY = "RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT"
- SAME_AXIS_HOST_RULE = "HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION"
- SAME_AXIS_VIOLATION_POLICY = "LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED"
- COMPLETION_POLICY = "NONE_HOST_TRACKS_TIME"
- PARALLEL_POLICY = "TWO_INDEPENDENT_PARALLEL_EXECUTORS"
- MAGIC = b"\xA5\x5A"
- VERSION = 0x02
- PROFILE = 0x04
- FRAME_HOST_CMD = 0x05
- FRAME_HOST_BATCH = 0x07
- FRAME_MOTION_CMD = 0x11
- FRAME_MOTION_STATUS = 0x12
- CMD_GET_STATUS = 0x24
- CMD_DISABLE = 0x26
- CMD_SET_SNAPSHOT = 0x2A
- MOTION_JOG = 0x35
- MOTION_MARK_CLOSED = 0x36
- MOTION_GET_STATUS = 0x37
- STATUS_OK = 0x00
- STATUS_UNSUPPORTED = 0x01
- STATUS_BAD_FLAGS = 0x02
- STATUS_BAD_LENGTH = 0x03
- STATUS_BAD_VALUE = 0x05
- STATUS_PARTIAL = 0x16
- PTC_COUNT = 24
- FAN_COUNT = 4
- AXIS_COUNT = 3
- UNKNOWN_POSITION = 0xFF
- WATCHDOG_TIMEOUT_MS = 5000
- DIR_SETUP_MS = 1
- SPEED_STEP_MS = (1, 1, 1, 1)
- SAFE_PTC = (0,) * PTC_COUNT
- SAFE_FAN = (30,) * FAN_COUNT
- SAFE_SOLENOID = 0
- AXIS_UNCALIBRATED = "uncalibrated"
- AXIS_CLOSED = "closed"
- AXIS_OPENING = "opening"
- AXIS_OPEN = "open"
- AXIS_CLOSING = "closing"
- AXIS_INTERMEDIATE = "intermediate"
- LEGACY_P4_ASSET_PATHS = (
- "src/rtl/prod2u_p4_host_rx.v",
- "src/rtl/prod2u_p4_tx_scheduler.v",
- "src/rtl/prod2u_fan_tach_capture8.v",
- "src/rtl/prod2u_fan_pwm_bank.v",
- "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
- "src/top/prod2u_fan_tach_binary921_v2_normal_top.v",
- "src/top/prod2u_fan_tach_binary921_v2_trace_top.v",
- "tests/sim/prod2u_p4_host_rx_tb.v",
- "tests/sim/prod2u_p4_tx_scheduler_tb.v",
- "tests/sim/prod2u_fan_tach_capture8_tb.v",
- "tests/sim/prod2u_fan_pwm_bank_tb.v",
- "tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v",
- "tests/formal/prod2u_fan_data_path.sby",
- "tests/formal/prod2u_fan_data_path_formal.v",
- "constraints/prod2u_fan_tach_binary921_v2.adc",
- "td/prod2u_fan_tach_binary921_v2_normal.prj",
- "td/prod2u_fan_tach_binary921_v2_trace.prj",
- "td/syn/prod2u_fan_tach_binary921_v2_normal.tcl",
- "td/syn/prod2u_fan_tach_binary921_v2_trace.tcl",
- "td/phy/prod2u_fan_tach_binary921_v2_normal.tcl",
- "td/phy/prod2u_fan_tach_binary921_v2_trace.tcl",
- "tools/package_prod2u_p4.ps1",
- "tools/prod2u_p4_collector.py",
- "tools/prod2u_p4_campaign.py",
- "tools/prod2u_p4_validate.py",
- "docs/prod2u-p4-start-here.zh-CN.md",
- "docs/prod2u-p4-program-sram-runbook.zh-CN.md",
- "schemas/prod2u_p4_campaign.schema.json",
- "schemas/prod2u_p4_evidence.schema.json",
- "schemas/prod2u_p4_final_gate.schema.json",
- "schemas/prod2u_p4_qualification.schema.json",
- "schemas/prod2u_p4_td_build_receipt.schema.json",
- "tests/unit/test_prod2u_p4_cli_campaign.py",
- "tests/unit/test_prod2u_p4_cli_identity.py",
- "tests/unit/test_prod2u_p4_evidence_binding.py",
- "tests/unit/test_prod2u_p4_integration.py",
- "tests/unit/test_prod2u_p4_package.py",
- "tests/unit/test_prod2u_p4_protocol.py",
- "tests/unit/test_prod2u_p4_qualification.py",
- "tests/unit/test_prod2u_p4_validate_contract.py",
- )
- class ModelFrameError(ValueError):
- def __init__(self, message: str, *, status: int = STATUS_BAD_VALUE) -> None:
- super().__init__(message)
- self.status = status
- class HostContractViolation(ValueError):
- """Input excluded by the trusted-host contract, not a modeled device reply."""
- @dataclass(frozen=True)
- class PinSample:
- time_us: int
- en_n: int
- direction: tuple[int, int, int]
- step: tuple[int, int, int]
- @dataclass(frozen=True)
- class TraceViolation:
- kind: str
- axis: int
- time_us: int
- @dataclass(frozen=True)
- class MechanicalTraceReport:
- positions: tuple[int, int, int]
- step_counts: tuple[int, int, int]
- lost_step_counts: tuple[int, int, int]
- uncertain_step_counts: tuple[int, int, int]
- limit_raw_mask: int
- violations: tuple[TraceViolation, ...]
- @dataclass(frozen=True)
- class MechanicalDifference:
- matches: bool
- mismatches: tuple[str, ...]
- class MechanicalPlant:
- """Pin-level plant independent of controller or RTL internal state.
- The plant owns the hidden mechanical close direction and physical position.
- Its only motion inputs are the externally visible shared EN_N plus per-axis
- DIR and STEP pins.
- """
- def __init__(
- self,
- *,
- positions: Sequence[int],
- close_dirs: Sequence[int],
- dir_setup_us: int = 1000,
- min_step_high_us: int = 0,
- min_step_low_us: int = 0,
- limit_modes: Sequence[str] = ("normal", "normal"),
- limit_assert_delay_us: Sequence[int] = (0, 0),
- limit_bounce_us: Sequence[int] = (0, 0),
- limit_bounce_period_us: int = 100,
- swap_xy_limits: bool = False,
- lost_step_every: Sequence[int] = (0, 0, 0),
- ) -> None:
- if len(positions) != AXIS_COUNT or len(close_dirs) != AXIS_COUNT:
- raise ValueError("positions and close_dirs require exactly three axes")
- if any(value < 0 for value in positions):
- raise ValueError("positions must be non-negative")
- if any(value not in (0, 1) for value in close_dirs):
- raise ValueError("close_dirs must contain only zero or one")
- if len(limit_modes) != 2 or any(
- mode not in ("normal", "stuck_low", "stuck_high") for mode in limit_modes
- ):
- raise ValueError("limit_modes must contain two supported modes")
- if len(limit_assert_delay_us) != 2 or len(limit_bounce_us) != 2:
- raise ValueError("limit timing values require X and Y entries")
- if len(lost_step_every) != AXIS_COUNT or any(value < 0 for value in lost_step_every):
- raise ValueError("lost_step_every requires three non-negative values")
- if min(dir_setup_us, min_step_high_us, min_step_low_us, limit_bounce_period_us) < 0:
- raise ValueError("timing values must be non-negative")
- if limit_bounce_period_us == 0:
- raise ValueError("limit_bounce_period_us must be positive")
- self._positions = list(positions)
- self._close_dirs = tuple(close_dirs)
- self._dir_setup_us = dir_setup_us
- self._min_step_high_us = min_step_high_us
- self._min_step_low_us = min_step_low_us
- self._limit_modes = tuple(limit_modes)
- self._limit_assert_delay_us = tuple(limit_assert_delay_us)
- self._limit_bounce_us = tuple(limit_bounce_us)
- self._limit_bounce_period_us = limit_bounce_period_us
- self._swap_xy_limits = swap_xy_limits
- self._lost_step_every = tuple(lost_step_every)
- self._step_counts = [0, 0, 0]
- self._lost_step_counts = [0, 0, 0]
- self._uncertain_step_counts = [0, 0, 0]
- self._violations: list[TraceViolation] = []
- self._last_sample: PinSample | None = None
- self._last_dir_change_us = [0, 0, 0]
- self._step_rise_us: list[int | None] = [None, None, None]
- self._pending_step_valid = [False, False, False]
- self._pending_step_dir = [0, 0, 0]
- self._last_step_fall_us: list[int | None] = [None, None, None]
- self._contact_time_us: list[int | None] = [
- 0 if self._positions[index] == 0 else None for index in range(2)
- ]
- self._last_time_us = 0
- @property
- def positions(self) -> tuple[int, int, int]:
- return tuple(self._positions) # type: ignore[return-value]
- @property
- def step_counts(self) -> tuple[int, int, int]:
- return tuple(self._step_counts) # type: ignore[return-value]
- @property
- def uncertain_step_counts(self) -> tuple[int, int, int]:
- return tuple(self._uncertain_step_counts) # type: ignore[return-value]
- @property
- def lost_step_counts(self) -> tuple[int, int, int]:
- return tuple(self._lost_step_counts) # type: ignore[return-value]
- @property
- def violations(self) -> tuple[TraceViolation, ...]:
- return tuple(self._violations)
- def _record(self, kind: str, axis: int, time_us: int) -> None:
- item = TraceViolation(kind=kind, axis=axis, time_us=time_us)
- if item not in self._violations:
- self._violations.append(item)
- def observe(self, sample: PinSample) -> int:
- if sample.time_us < self._last_time_us:
- raise ValueError("pin samples must be monotonic")
- if sample.en_n not in (0, 1):
- raise ValueError("en_n must be zero or one")
- if len(sample.direction) != AXIS_COUNT or len(sample.step) != AXIS_COUNT:
- raise ValueError("direction and step require exactly three axes")
- if any(value not in (0, 1) for value in (*sample.direction, *sample.step)):
- raise ValueError("direction and step values must be binary")
- previous = self._last_sample
- if previous is None:
- self._last_dir_change_us = [sample.time_us] * AXIS_COUNT
- previous_direction = sample.direction
- previous_step = (0, 0, 0)
- previous_en_n = 1
- else:
- previous_direction = previous.direction
- previous_step = previous.step
- previous_en_n = previous.en_n
- for axis in range(AXIS_COUNT):
- if sample.direction[axis] != previous_direction[axis]:
- if previous_step[axis] or sample.step[axis]:
- self._record("dir_changed_while_step_high", axis, sample.time_us)
- self._pending_step_valid[axis] = False
- self._last_dir_change_us[axis] = sample.time_us
- rising = not previous_step[axis] and bool(sample.step[axis])
- falling = bool(previous_step[axis]) and not sample.step[axis]
- truncated = (
- not previous_en_n
- and sample.en_n
- and bool(previous_step[axis] or sample.step[axis])
- )
- if truncated:
- self._record("step_truncated", axis, sample.time_us)
- self._pending_step_valid[axis] = False
- if rising:
- valid = True
- if sample.en_n:
- self._record("step_while_disabled", axis, sample.time_us)
- valid = False
- if sample.time_us - self._last_dir_change_us[axis] < self._dir_setup_us:
- self._record("dir_setup", axis, sample.time_us)
- valid = False
- last_fall = self._last_step_fall_us[axis]
- if last_fall is not None and sample.time_us - last_fall < self._min_step_low_us:
- self._record("step_low_width", axis, sample.time_us)
- valid = False
- self._step_rise_us[axis] = sample.time_us
- self._pending_step_valid[axis] = valid
- self._pending_step_dir[axis] = sample.direction[axis]
- if falling:
- rise = self._step_rise_us[axis]
- if rise is not None and sample.time_us - rise < self._min_step_high_us:
- self._record("step_high_width", axis, sample.time_us)
- self._pending_step_valid[axis] = False
- if rise is not None and self._pending_step_valid[axis]:
- self._step_counts[axis] += 1
- drop_every = self._lost_step_every[axis]
- if drop_every and self._step_counts[axis] % drop_every == 0:
- self._lost_step_counts[axis] += 1
- else:
- if self._pending_step_dir[axis] == self._close_dirs[axis]:
- self._positions[axis] = max(0, self._positions[axis] - 1)
- else:
- self._positions[axis] += 1
- if axis < 2:
- if self._positions[axis] == 0 and self._contact_time_us[axis] is None:
- self._contact_time_us[axis] = sample.time_us
- elif self._positions[axis] > 0:
- self._contact_time_us[axis] = None
- elif rise is not None:
- self._uncertain_step_counts[axis] += 1
- self._step_rise_us[axis] = None
- self._pending_step_valid[axis] = False
- self._last_step_fall_us[axis] = sample.time_us
- self._last_sample = sample
- self._last_time_us = sample.time_us
- return self.read_limit_raw_mask(sample.time_us)
- def _limit_value(self, axis: int, time_us: int) -> int:
- mode = self._limit_modes[axis]
- if mode == "stuck_low":
- return 0
- if mode == "stuck_high":
- return 1
- if self._positions[axis] != 0:
- return 0
- contact = self._contact_time_us[axis]
- if contact is None:
- return 0
- elapsed = max(0, time_us - contact)
- delay = self._limit_assert_delay_us[axis]
- if elapsed < delay:
- return 0
- bounce_elapsed = elapsed - delay
- bounce_window = self._limit_bounce_us[axis]
- if bounce_elapsed < bounce_window:
- return int((bounce_elapsed // self._limit_bounce_period_us) % 2 == 0)
- return 1
- def read_limit_raw_mask(self, time_us: int | None = None) -> int:
- now = self._last_time_us if time_us is None else time_us
- values = [self._limit_value(0, now), self._limit_value(1, now)]
- if self._swap_xy_limits:
- values.reverse()
- return values[0] | (values[1] << 1)
- def replay_mechanical_trace(
- plant: MechanicalPlant,
- samples: Iterable[PinSample],
- ) -> MechanicalTraceReport:
- limit_raw_mask = plant.read_limit_raw_mask(0)
- for sample in samples:
- limit_raw_mask = plant.observe(sample)
- return MechanicalTraceReport(
- positions=plant.positions,
- step_counts=plant.step_counts,
- lost_step_counts=plant.lost_step_counts,
- uncertain_step_counts=plant.uncertain_step_counts,
- limit_raw_mask=limit_raw_mask,
- violations=plant.violations,
- )
- def compare_mechanical_reports(
- reference: MechanicalTraceReport,
- candidate: MechanicalTraceReport,
- ) -> MechanicalDifference:
- mismatches = tuple(
- name
- for name in (
- "positions",
- "step_counts",
- "lost_step_counts",
- "uncertain_step_counts",
- "limit_raw_mask",
- "violations",
- )
- if getattr(reference, name) != getattr(candidate, name)
- )
- return MechanicalDifference(matches=not mismatches, mismatches=mismatches)
- def compare_pin_traces(
- *,
- reference_plant: MechanicalPlant,
- candidate_plant: MechanicalPlant,
- reference_samples: Iterable[PinSample],
- candidate_samples: Iterable[PinSample],
- ) -> MechanicalDifference:
- return compare_mechanical_reports(
- replay_mechanical_trace(reference_plant, reference_samples),
- replay_mechanical_trace(candidate_plant, candidate_samples),
- )
- @dataclass
- class AxisState:
- state: str = AXIS_UNCALIBRATED
- position_valid: bool = False
- busy: bool = False
- current: int = UNKNOWN_POSITION
- target: int = UNKNOWN_POSITION
- fault: bool = False
- move_kind: str = "idle"
- raw_dir: int | None = None
- speed_code: int | None = None
- remaining_steps: int = 0
- drive_active: bool = False
- step_phase: str = "idle"
- pending_jog: tuple[int, int, int] | None = None
- steps_executed: int = 0
- step_elapsed_ms: int = 0
- dir_setup_remaining_ms: int = 0
- @dataclass(frozen=True)
- class ModelResult:
- accepted: bool
- command: int
- status: int
- detail: int
- state_hash16: int
- response_type: int = 0
- result_flags: int = 0
- response: bytes | None = None
- reason: str = ""
- def crc16_ccitt_false(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
- crc = initial & 0xFFFF
- for byte in bytes(data):
- crc ^= byte << 8
- for _ in range(8):
- if crc & 0x8000:
- crc = ((crc << 1) ^ 0x1021) & 0xFFFF
- else:
- crc = (crc << 1) & 0xFFFF
- return crc
- def _byte_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
- result = tuple(values)
- if len(result) != count:
- raise ValueError(f"{label} requires exactly {count} values")
- for index, value in enumerate(result):
- if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
- raise ValueError(f"{label}[{index}] must fit in one byte")
- return result
- def _percent_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
- result = _byte_values(values, count=count, label=label)
- for index, value in enumerate(result):
- if value > 100:
- raise ValueError(f"{label}[{index}] must be from 0 to 100")
- return result
- def _binary_values(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
- result = _byte_values(values, count=count, label=label)
- for index, value in enumerate(result):
- if value not in (0, 100):
- raise ValueError(f"{label}[{index}] must be 0 or 100")
- return result
- def state_hash16(ptc_percent: Iterable[int], fan_percent: Iterable[int], solenoid: int) -> int:
- ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
- fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
- checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
- return crc16_ccitt_false(bytes(ptc + fan + (checked_solenoid,)))
- def _freeze_state(value: object) -> object:
- if isinstance(value, dict):
- return tuple(
- (key, _freeze_state(item))
- for key, item in sorted(value.items())
- )
- if isinstance(value, (list, tuple)):
- return tuple(_freeze_state(item) for item in value)
- return value
- def encode_standard_frame(frame_type: int, payload: bytes | bytearray | Iterable[int]) -> bytes:
- payload_bytes = bytes(payload)
- if not 0 <= frame_type <= 0xFF:
- raise ValueError("frame_type must fit in one byte")
- if len(payload_bytes) > 0xFF:
- raise ValueError("payload is too long")
- body = bytes((VERSION, PROFILE, frame_type))
- body += b"\x00" * 8
- body += bytes((len(payload_bytes),)) + payload_bytes
- return MAGIC + body + crc16_ccitt_false(body).to_bytes(2, "little")
- def encode_snapshot_frame(
- *,
- ptc_percent: Iterable[int],
- fan_percent: Iterable[int],
- solenoid: int,
- xyz: Iterable[int],
- ) -> bytes:
- ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
- fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
- checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
- checked_xyz = _byte_values(xyz, count=AXIS_COUNT, label="XYZ")
- payload = bytes((CMD_SET_SNAPSHOT, 0, *ptc, *fan, checked_solenoid, *checked_xyz))
- return encode_standard_frame(FRAME_HOST_BATCH, payload)
- def encode_motion_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
- payload_bytes = bytes(payload)
- if len(payload_bytes) != 8:
- raise ValueError("motion payload must contain exactly eight bytes")
- return encode_standard_frame(FRAME_MOTION_CMD, payload_bytes)
- def encode_host_frame(payload: bytes | bytearray | Iterable[int]) -> bytes:
- payload_bytes = bytes(payload)
- if len(payload_bytes) != 4:
- raise ValueError("host command payload must contain exactly four bytes")
- return encode_standard_frame(FRAME_HOST_CMD, payload_bytes)
- def _decode_standard_frame(frame: bytes | bytearray) -> tuple[int, bytes]:
- raw = bytes(frame)
- if len(raw) < 16:
- raise ModelFrameError("frame is truncated", status=STATUS_BAD_LENGTH)
- if raw[:2] != MAGIC:
- raise ModelFrameError("bad frame magic")
- if raw[2] != VERSION or raw[3] != PROFILE:
- raise ModelFrameError("bad frame identity")
- if raw[5:13] != b"\x00" * 8:
- raise ModelFrameError("seq and timestamp must be zero")
- payload_length = raw[13]
- expected_length = 16 + payload_length
- if len(raw) != expected_length:
- raise ModelFrameError("frame length mismatch", status=STATUS_BAD_LENGTH)
- expected_crc = crc16_ccitt_false(raw[2:-2])
- actual_crc = int.from_bytes(raw[-2:], "little")
- if actual_crc != expected_crc:
- raise ModelFrameError("frame CRC mismatch")
- return raw[4], raw[14:-2]
- GOLDEN_VECTORS = {
- "enable": bytes.fromhex(
- "a55a0204070000000000000000222a00"
- "000000000000000000000000000000000000000000000000"
- "1e1e1e1e00000000d6df"
- ),
- "jog_x": bytes.fromhex("a55a020411000000000000000008350001000100000086c3"),
- "jog_y": bytes.fromhex("a55a0204110000000000000000083501000001000000473e"),
- "mark_x": bytes.fromhex("a55a0204110000000000000000083600010000000000477d"),
- "mark_y": bytes.fromhex("a55a02041100000000000000000836010000000000008680"),
- "open": bytes.fromhex(
- "a55a0204070000000000000000222a00"
- "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
- "46464646646464642c75"
- ),
- "close": bytes.fromhex(
- "a55a0204070000000000000000222a00"
- "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
- "4646464600000000684a"
- ),
- "disable": bytes.fromhex("a55a02040500000000000000000426000000c4ae"),
- }
- class NormalV3Model:
- def __init__(self) -> None:
- self.ptc_percent = SAFE_PTC
- self.fan_percent = SAFE_FAN
- self.solenoid = SAFE_SOLENOID
- self.axes = [AxisState() for _ in range(AXIS_COUNT)]
- self.disabled = True
- self.watchdog_timeout = False
- self.watchdog_armed = False
- self.watchdog_elapsed_ms = 0
- @property
- def state_hash16(self) -> int:
- return state_hash16(self.ptc_percent, self.fan_percent, self.solenoid)
- @property
- def busy_mask(self) -> int:
- return 0
- @property
- def active_mask(self) -> int:
- return sum(
- (1 << index)
- for index, axis in enumerate(self.axes[:2])
- if axis.drive_active
- )
- @property
- def position_valid_mask(self) -> int:
- return 0
- @property
- def fault_mask(self) -> int:
- return 0
- def state_fingerprint(self) -> tuple[object, ...]:
- frozen = _freeze_state(self.state_payload())
- if not isinstance(frozen, tuple):
- raise AssertionError("state payload did not freeze to a tuple")
- return frozen
- def state_payload(self) -> dict[str, object]:
- return {
- "ptc_percent": list(self.ptc_percent),
- "fan_percent": list(self.fan_percent),
- "solenoid": self.solenoid,
- "state_hash16": self.state_hash16,
- "disabled": self.disabled,
- "watchdog_timeout": self.watchdog_timeout,
- "watchdog_armed": self.watchdog_armed,
- "watchdog_elapsed_ms": self.watchdog_elapsed_ms,
- "position_valid_mask": self.position_valid_mask,
- "busy_mask": self.busy_mask,
- "active_mask": self.active_mask,
- "fault_mask": self.fault_mask,
- "axes": [asdict(axis) for axis in self.axes],
- }
- @staticmethod
- def _set_xy_state(axis: AxisState, state: str) -> None:
- axis.state = state
- axis.fault = False
- axis.position_valid = False
- axis.current = UNKNOWN_POSITION
- axis.target = UNKNOWN_POSITION
- if state not in (
- AXIS_UNCALIBRATED,
- AXIS_CLOSED,
- AXIS_OPENING,
- AXIS_OPEN,
- AXIS_CLOSING,
- AXIS_INTERMEDIATE,
- ):
- raise ValueError(f"unsupported XY axis state: {state}")
- @staticmethod
- def _clear_motion(axis: AxisState) -> None:
- axis.busy = False
- axis.drive_active = False
- axis.step_phase = "idle"
- axis.pending_jog = None
- axis.move_kind = "idle"
- axis.remaining_steps = 0
- axis.steps_executed = 0
- axis.step_elapsed_ms = 0
- axis.dir_setup_remaining_ms = 0
- def _result(
- self,
- *,
- accepted: bool,
- command: int,
- status: int,
- detail: int = 0,
- response_type: int = 0,
- result_flags: int = 0,
- response: bytes | None = None,
- reason: str = "",
- ) -> ModelResult:
- return ModelResult(
- accepted=accepted,
- command=command,
- status=status,
- detail=detail,
- state_hash16=self.state_hash16,
- response_type=response_type,
- result_flags=result_flags,
- response=response,
- reason=reason,
- )
- def _arm_watchdog(self) -> None:
- self.disabled = False
- self.watchdog_timeout = False
- self.watchdog_armed = True
- self.watchdog_elapsed_ms = 0
- def _refresh_watchdog(self) -> None:
- if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
- self.watchdog_elapsed_ms = 0
- def advance_time(self, elapsed_ms: int) -> None:
- """Advance wall-clock time, including complete modeled STEP cycles."""
- if elapsed_ms < 0:
- raise ValueError("elapsed_ms must be non-negative")
- remaining_ms = elapsed_ms
- while remaining_ms > 0:
- delta_ms = remaining_ms
- if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
- delta_ms = min(
- delta_ms,
- WATCHDOG_TIMEOUT_MS - self.watchdog_elapsed_ms,
- )
- accumulating_axes: list[int] = []
- for axis_index, axis in enumerate(self.axes[:2]):
- if not axis.drive_active or axis.remaining_steps <= 0:
- continue
- if axis.dir_setup_remaining_ms > 0:
- delta_ms = min(delta_ms, axis.dir_setup_remaining_ms)
- continue
- accumulating_axes.append(axis_index)
- speed_code = axis.speed_code if axis.speed_code is not None else 3
- step_due_ms = SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms
- delta_ms = min(delta_ms, step_due_ms)
- self._advance_control_time(delta_ms)
- remaining_ms -= delta_ms
- for axis_index in accumulating_axes:
- axis = self.axes[axis_index]
- if axis.drive_active and axis.dir_setup_remaining_ms == 0:
- axis.step_elapsed_ms += delta_ms
- for axis_index, axis in enumerate(self.axes[:2]):
- if (
- not axis.drive_active
- or axis.dir_setup_remaining_ms > 0
- or axis.remaining_steps <= 0
- ):
- continue
- speed_code = axis.speed_code if axis.speed_code is not None else 3
- if axis.step_elapsed_ms < SPEED_STEP_MS[speed_code]:
- continue
- if axis.step_phase == "idle":
- self._commit_axis_step(axis_index)
- else:
- self.finish_axis_step(axis_index)
- def _advance_control_time(self, elapsed_ms: int) -> None:
- if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
- if self.watchdog_elapsed_ms + elapsed_ms >= WATCHDOG_TIMEOUT_MS:
- self.watchdog_expire()
- else:
- self.watchdog_elapsed_ms += elapsed_ms
- for axis_index, axis in enumerate(self.axes[:2]):
- if axis.dir_setup_remaining_ms <= 0:
- continue
- axis.dir_setup_remaining_ms = max(
- 0,
- axis.dir_setup_remaining_ms - elapsed_ms,
- )
- if axis.dir_setup_remaining_ms == 0 and axis.drive_active:
- self._complete_dir_setup(axis_index)
- def _complete_dir_setup(self, axis_index: int) -> None:
- axis = self.axes[axis_index]
- if not axis.drive_active:
- return
- axis.drive_active = True
- def _safe_outputs(self) -> None:
- self.ptc_percent = SAFE_PTC
- self.fan_percent = SAFE_FAN
- self.solenoid = SAFE_SOLENOID
- def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
- self._safe_outputs()
- self.disabled = disabled
- self.watchdog_timeout = watchdog_timeout
- self.watchdog_armed = False
- self.watchdog_elapsed_ms = 0
- def disable(self) -> None:
- self._force_safe(disabled=True, watchdog_timeout=False)
- def watchdog_expire(self) -> None:
- if self.watchdog_armed and not self.disabled:
- self._force_safe(disabled=True, watchdog_timeout=True)
- def apply_frame(
- self,
- frame: bytes | bytearray,
- ) -> ModelResult:
- before = self.state_fingerprint()
- try:
- frame_type, payload = _decode_standard_frame(frame)
- if frame_type == FRAME_HOST_BATCH:
- result = self._apply_snapshot(payload)
- elif frame_type == FRAME_HOST_CMD:
- result = self._apply_host(payload)
- elif frame_type == FRAME_MOTION_CMD:
- result = self._apply_motion(payload)
- else:
- result = self._result(
- accepted=False,
- command=payload[0] if payload else 0,
- status=STATUS_UNSUPPORTED,
- reason="unsupported input frame type",
- )
- except ModelFrameError as exc:
- result = self._result(
- accepted=False,
- command=0,
- status=exc.status,
- reason=str(exc),
- )
- except HostContractViolation:
- raise
- except ValueError as exc:
- result = self._result(
- accepted=False,
- command=0,
- status=STATUS_BAD_VALUE,
- reason=str(exc),
- )
- if not result.accepted and self.state_fingerprint() != before:
- raise AssertionError("rejected frame changed modeled state")
- return result
- def _apply_snapshot(
- self,
- payload: bytes,
- ) -> ModelResult:
- command = payload[0] if payload else 0
- if len(payload) != 34:
- raise ModelFrameError("snapshot payload length must be 34", status=STATUS_BAD_LENGTH)
- if payload[0] != CMD_SET_SNAPSHOT:
- return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
- if payload[1] != 0:
- return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
- ptc = tuple(payload[2:26])
- fan = tuple(payload[26:30])
- solenoid = payload[30]
- xyz = tuple(payload[31:34])
- try:
- checked_ptc = _percent_values(ptc, count=PTC_COUNT, label="PTC")
- checked_fan = _percent_values(fan, count=FAN_COUNT, label="FAN")
- checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
- except ValueError as exc:
- return self._result(
- accepted=False,
- command=command,
- status=STATUS_BAD_VALUE,
- reason=str(exc),
- )
- self.ptc_percent = checked_ptc
- self.fan_percent = checked_fan
- self.solenoid = checked_solenoid
- self._arm_watchdog()
- return self._result(
- accepted=True,
- command=command,
- status=STATUS_OK,
- detail=0,
- result_flags=0x01,
- )
- def _apply_host(self, payload: bytes) -> ModelResult:
- command = payload[0] if payload else 0
- if len(payload) != 4:
- raise ModelFrameError("host payload length must be four", status=STATUS_BAD_LENGTH)
- if payload[3] != 0:
- return self._result(accepted=False, command=command, status=STATUS_BAD_FLAGS)
- if payload[1:3] != b"\x00\x00":
- return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
- if command == CMD_GET_STATUS:
- detail = int(self.disabled) | (int(self.watchdog_timeout) << 1)
- return self._result(accepted=True, command=command, status=STATUS_OK, detail=detail)
- if command == CMD_DISABLE:
- self.disable()
- return self._result(accepted=True, command=command, status=STATUS_OK, detail=1)
- return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
- def _apply_motion(
- self,
- payload: bytes,
- ) -> ModelResult:
- command = payload[0] if payload else 0
- if len(payload) != 8:
- raise ModelFrameError("motion payload length must be eight", status=STATUS_BAD_LENGTH)
- if command == MOTION_JOG:
- return self._apply_jog(payload)
- if command == MOTION_MARK_CLOSED:
- return self._result(
- accepted=False,
- command=command,
- status=STATUS_UNSUPPORTED,
- reason="MARK_CLOSED is retired",
- )
- if command == MOTION_GET_STATUS:
- if payload[1:] != b"\x00" * 7:
- return self._result(accepted=False, command=command, status=STATUS_BAD_VALUE)
- self._refresh_watchdog()
- return self._result(
- accepted=True,
- command=command,
- status=STATUS_OK,
- response_type=FRAME_MOTION_STATUS,
- result_flags=0x08,
- response=self.motor_status_payload(),
- )
- return self._result(accepted=False, command=command, status=STATUS_UNSUPPORTED)
- def _apply_jog(
- self,
- payload: bytes,
- ) -> ModelResult:
- axis_index = payload[1]
- raw_dir = payload[2]
- speed_code = payload[3]
- steps = int.from_bytes(payload[4:6], "little")
- if steps == 0:
- raise HostContractViolation(
- f"{RAW_STEP_POLICY}: steps=0 violates the trusted-host precondition"
- )
- if (
- axis_index not in (0, 1)
- or raw_dir not in (0, 1)
- or speed_code >= 4
- or payload[6:] != b"\x00\x00"
- ):
- return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BAD_VALUE)
- axis = self.axes[axis_index]
- self._set_xy_state(axis, AXIS_INTERMEDIATE)
- self._load_force_jog(
- axis,
- raw_dir=raw_dir,
- speed_code=speed_code,
- steps=steps,
- )
- axis.dir_setup_remaining_ms = 0
- self.begin_axis_step(axis_index)
- return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
- def _load_force_jog(
- self,
- axis: AxisState,
- *,
- raw_dir: int,
- speed_code: int,
- steps: int,
- ) -> None:
- axis.busy = False
- axis.drive_active = True
- axis.step_phase = "idle"
- axis.pending_jog = None
- axis.move_kind = "jog"
- axis.raw_dir = raw_dir
- axis.speed_code = speed_code
- axis.remaining_steps = steps
- axis.steps_executed = 0
- axis.step_elapsed_ms = 0
- axis.dir_setup_remaining_ms = DIR_SETUP_MS
- def _complete_motion_segment(self, axis_index: int) -> None:
- axis = self.axes[axis_index]
- if axis_index not in (0, 1) or axis.move_kind != "jog":
- raise AssertionError("only X/Y JOG can complete motor motion")
- self._set_xy_state(axis, AXIS_INTERMEDIATE)
- self._clear_motion(axis)
- def _prepare_axis_event(self, axis_index: int) -> tuple[int, str] | None:
- axis = self.axes[axis_index]
- while axis.drive_active and axis.remaining_steps <= 0:
- self._complete_motion_segment(axis_index)
- if not axis.drive_active:
- return None
- if axis.dir_setup_remaining_ms > 0:
- return axis.dir_setup_remaining_ms, "setup"
- if not axis.drive_active or axis.remaining_steps <= 0:
- return None
- speed_code = axis.speed_code if axis.speed_code is not None else 3
- return SPEED_STEP_MS[speed_code] - axis.step_elapsed_ms, "step"
- def _commit_axis_step(self, axis_index: int) -> None:
- self.begin_axis_step(axis_index)
- self.finish_axis_step(axis_index)
- def begin_axis_step(self, axis_index: int) -> None:
- if axis_index not in (0, 1):
- raise ValueError("only X and Y execute motion")
- axis = self.axes[axis_index]
- if (
- not axis.drive_active
- or axis.dir_setup_remaining_ms > 0
- or axis.remaining_steps <= 0
- or axis.step_phase != "idle"
- ):
- raise ValueError("axis has no complete step ready to commit")
- axis.step_phase = "high"
- axis.busy = False
- def lower_axis_step(self, axis_index: int) -> None:
- if axis_index not in (0, 1):
- raise ValueError("only X and Y execute motion")
- axis = self.axes[axis_index]
- if not axis.drive_active or axis.step_phase != "high":
- raise ValueError("axis has no high step phase to lower")
- axis.step_phase = "low"
- def finish_axis_step(self, axis_index: int) -> None:
- if axis_index not in (0, 1):
- raise ValueError("only X and Y execute motion")
- axis = self.axes[axis_index]
- if not axis.drive_active or axis.step_phase not in ("high", "low"):
- raise ValueError("axis has no started step to finish")
- axis.step_phase = "low"
- axis.remaining_steps -= 1
- axis.steps_executed += 1
- axis.step_elapsed_ms = 0
- pending = axis.pending_jog
- axis.pending_jog = None
- axis.step_phase = "idle"
- if pending is not None:
- axis.busy = False
- raw_dir, speed_code, steps = pending
- self._load_force_jog(
- axis,
- raw_dir=raw_dir,
- speed_code=speed_code,
- steps=steps,
- )
- elif axis.drive_active and axis.remaining_steps == 0:
- self._complete_motion_segment(axis_index)
- def execute_parallel_steps(self, counts: Sequence[int]) -> tuple[int, int, int]:
- if len(counts) != AXIS_COUNT or any(count < 0 for count in counts):
- raise ValueError("counts require three non-negative axis values")
- if counts[2] != 0:
- raise ValueError("Z is protocol-only and cannot execute steps")
- remaining = list(counts)
- executed = [0, 0, 0]
- due_ms: list[int | None] = [None, None, None]
- due_kind: list[str | None] = [None, None, None]
- if any(remaining):
- omitted_active = [
- axis_index
- for axis_index, axis in enumerate(self.axes)
- if axis.drive_active
- and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
- and remaining[axis_index] == 0
- ]
- if omitted_active:
- raise ValueError(
- "counts must include every concurrently active axis: "
- + ",".join(map(str, omitted_active))
- )
- while any(remaining):
- for axis_index in range(AXIS_COUNT):
- if remaining[axis_index] and due_ms[axis_index] is None:
- event = self._prepare_axis_event(axis_index)
- if event is not None:
- due_ms[axis_index], due_kind[axis_index] = event
- active_due = [value for value in due_ms if value is not None]
- if not active_due:
- break
- elapsed_ms = min(active_due)
- self._advance_control_time(elapsed_ms)
- for axis_index in range(AXIS_COUNT):
- if due_ms[axis_index] is not None:
- due_ms[axis_index] -= elapsed_ms
- for axis_index in range(AXIS_COUNT):
- if due_ms[axis_index] != 0:
- continue
- if due_kind[axis_index] == "setup":
- if self.axes[axis_index].dir_setup_remaining_ms != 0:
- raise AssertionError("DIR setup event completed early")
- elif due_kind[axis_index] == "step":
- self._commit_axis_step(axis_index)
- executed[axis_index] += 1
- remaining[axis_index] -= 1
- else:
- raise AssertionError("scheduled axis event has no kind")
- due_ms[axis_index] = None
- due_kind[axis_index] = None
- if any(remaining):
- frozen = [
- axis_index
- for axis_index, axis in enumerate(self.axes)
- if axis.drive_active
- and (axis.drive_active or axis.dir_setup_remaining_ms > 0)
- and remaining[axis_index] == 0
- ]
- if frozen:
- raise ValueError(
- "requested counts would freeze active axes: "
- + ",".join(map(str, frozen))
- )
- return tuple(executed) # type: ignore[return-value]
- def execute_axis_steps(self, axis_index: int, count: int) -> int:
- if axis_index not in (0, 1):
- raise ValueError("only X and Y execute motion")
- if count < 0:
- raise ValueError("count must be non-negative")
- counts = [0, 0, 0]
- counts[axis_index] = count
- return self.execute_parallel_steps(counts)[axis_index]
- def complete_axis(
- self,
- axis_index: int,
- ) -> None:
- if axis_index not in (0, 1):
- raise ValueError("only X and Y execute motion")
- axis = self.axes[axis_index]
- if not axis.drive_active:
- raise ValueError("axis is not active")
- self.execute_axis_steps(axis_index, axis.remaining_steps)
- def motor_status_payload(self) -> bytes:
- flags = 0x02
- flags |= int(self.disabled) << 2
- flags |= int(self.watchdog_timeout) << 3
- return bytes((
- flags,
- 0,
- 0,
- UNKNOWN_POSITION,
- UNKNOWN_POSITION,
- UNKNOWN_POSITION,
- UNKNOWN_POSITION,
- UNKNOWN_POSITION,
- UNKNOWN_POSITION,
- 0,
- ))
- def feed_stream(
- self,
- data: bytes | bytearray,
- ) -> list[ModelResult]:
- raw = bytes(data)
- accepted: list[ModelResult] = []
- offset = 0
- while True:
- start = raw.find(MAGIC, offset)
- if start < 0:
- break
- if len(raw) - start < 16:
- break
- end = start + 16 + raw[start + 13]
- if end > len(raw):
- offset = start + 1
- continue
- result = self.apply_frame(raw[start:end])
- if result.accepted:
- accepted.append(result)
- offset = end if result.accepted else start + 1
- return accepted
- def _verify_golden_encoders() -> list[str]:
- failures: list[str] = []
- generated = {
- "enable": encode_snapshot_frame(
- ptc_percent=(0,) * 24,
- fan_percent=(30,) * 4,
- solenoid=0,
- xyz=(0, 0, 0),
- ),
- "jog_x": encode_motion_frame(bytes((MOTION_JOG, 0, 1, 0, 1, 0, 0, 0))),
- "jog_y": encode_motion_frame(bytes((MOTION_JOG, 1, 0, 0, 1, 0, 0, 0))),
- "mark_x": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 0, 1, 0, 0, 0, 0, 0))),
- "mark_y": encode_motion_frame(bytes((MOTION_MARK_CLOSED, 1, 0, 0, 0, 0, 0, 0))),
- "open": encode_snapshot_frame(
- ptc_percent=(10,) * 24,
- fan_percent=(70,) * 4,
- solenoid=100,
- xyz=(100, 100, 100),
- ),
- "close": encode_snapshot_frame(
- ptc_percent=(10,) * 24,
- fan_percent=(70,) * 4,
- solenoid=0,
- xyz=(0, 0, 0),
- ),
- "disable": encode_host_frame(bytes((CMD_DISABLE, 0, 0, 0))),
- }
- for name, value in generated.items():
- if value != GOLDEN_VECTORS[name]:
- failures.append(name)
- return failures
- def run_replay() -> dict[str, object]:
- checks: list[dict[str, object]] = []
- golden_failures = _verify_golden_encoders()
- checks.append({"name": "fixed_golden_vectors", "status": "pass" if not golden_failures else "fail", "failures": golden_failures})
- subject = NormalV3Model()
- enable = subject.apply_frame(GOLDEN_VECTORS["enable"])
- checks.append({
- "name": "snapshot_xyz_has_no_motor_effect",
- "status": "pass"
- if enable.accepted and subject.active_mask == 0 and subject.busy_mask == 0
- else "fail",
- })
- before_mark = subject.state_fingerprint()
- mark = subject.apply_frame(GOLDEN_VECTORS["mark_x"])
- checks.append({
- "name": "mark_closed_tombstone_unsupported",
- "status": "pass"
- if not mark.accepted
- and mark.status == STATUS_UNSUPPORTED
- and subject.state_fingerprint() == before_mark
- else "fail",
- })
- opened = subject.apply_frame(GOLDEN_VECTORS["open"])
- checks.append({
- "name": "legacy_open_fields_are_ignored",
- "status": "pass"
- if opened.accepted
- and subject.active_mask == 0
- and all(axis.current == UNKNOWN_POSITION for axis in subject.axes[:2])
- else "fail",
- })
- force_jog = encode_motion_frame(
- bytes((MOTION_JOG, 0, 1, 3, 0xFF, 0xFF, 0, 0))
- )
- jog_subject = NormalV3Model()
- jog = jog_subject.apply_frame(force_jog)
- checks.append({
- "name": "jog_preserves_u16_and_acks_on_first_step",
- "status": "pass"
- if jog.accepted
- and jog_subject.axes[0].remaining_steps == 0xFFFF
- and jog_subject.axes[0].step_phase == "high"
- and jog_subject.axes[0].current == UNKNOWN_POSITION
- and jog_subject.active_mask == 1
- and jog_subject.busy_mask == 0
- and not jog_subject.watchdog_armed
- else "fail",
- })
- before_motion = (
- jog_subject.axes[0].drive_active,
- jog_subject.axes[0].raw_dir,
- jog_subject.axes[0].remaining_steps,
- jog_subject.axes[0].step_phase,
- )
- jog_subject.disabled = False
- jog_subject.watchdog_armed = True
- jog_subject.watchdog_expire()
- checks.append({
- "name": "watchdog_safes_outputs_without_motor_effect",
- "status": "pass"
- if before_motion
- == (
- jog_subject.axes[0].drive_active,
- jog_subject.axes[0].raw_dir,
- jog_subject.axes[0].remaining_steps,
- jog_subject.axes[0].step_phase,
- )
- else "fail",
- })
- before_unknown = subject.state_fingerprint()
- unknown = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
- checks.append({
- "name": "temperature_tombstone_unsupported",
- "status": "pass" if not unknown.accepted and unknown.status == STATUS_UNSUPPORTED and subject.state_fingerprint() == before_unknown else "fail",
- })
- final = jog_subject.state_payload()
- motion_status = jog_subject.motor_status_payload()
- final_ok = (
- final["ptc_percent"] == [0] * 24
- and final["fan_percent"] == [30] * 4
- and final["solenoid"] == 0
- and final["active_mask"] == 1
- and final["busy_mask"] == 0
- and final["axes"][0]["current"] == UNKNOWN_POSITION
- and final["watchdog_timeout"] is True
- and motion_status[0] & 0x02
- and motion_status[1:] == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
- )
- checks.append({"name": "constant_motion_status", "status": "pass" if final_ok else "fail"})
- status = "pass" if all(check["status"] == "pass" for check in checks) else "fail"
- return {
- "status": status,
- "verification_layer": "binary921_v3_replay",
- "vector_set": "binary921-v3-golden-v1",
- "golden_vector_count": len(GOLDEN_VECTORS),
- "checks": checks,
- "final_state": final,
- "authority_boundary": "Deterministic offline contract replay only; no RTL or hardware is accessed.",
- }
- def run_model() -> dict[str, object]:
- subject = NormalV3Model()
- initial = subject.state_fingerprint()
- bad = bytearray(GOLDEN_VECTORS["open"])
- bad[-1] ^= 1
- rejected = subject.apply_frame(bytes(bad))
- rejected_atomically = not rejected.accepted and subject.state_fingerprint() == initial
- valid = subject.apply_frame(GOLDEN_VECTORS["open"])
- jog_subject = NormalV3Model()
- jog = jog_subject.apply_frame(GOLDEN_VECTORS["jog_x"])
- checks = {
- "canonical_crc": crc16_ccitt_false(b"123456789") == 0x29B1,
- "initial_safe_hash": state_hash16(SAFE_PTC, SAFE_FAN, SAFE_SOLENOID) == 0xE177,
- "bad_crc_rejected_atomically": rejected_atomically,
- "valid_snapshot_committed_without_motor": valid.accepted and subject.ptc_percent == (10,) * 24,
- "snapshot_xyz_ignored": valid.status == STATUS_OK and valid.detail == 0,
- "jog_first_step_ack": (
- jog.accepted
- and jog_subject.active_mask == 1
- and jog_subject.axes[0].step_phase == "high"
- and jog_subject.axes[0].remaining_steps == 1
- and not jog_subject.watchdog_armed
- and jog_subject.busy_mask == 0
- ),
- "status_fields_constant": (
- valid.status == STATUS_OK
- and jog_subject.motor_status_payload()[1:]
- == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
- ),
- }
- return {
- "status": "pass" if all(checks.values()) else "fail",
- "verification_layer": "binary921_v3_model",
- "checks": checks,
- "authority_boundary": "Independent offline state model only; no RTL or hardware is accessed.",
- }
- def _repair_crc(frame: bytes) -> bytes:
- return frame[:-2] + crc16_ccitt_false(frame[2:-2]).to_bytes(2, "little")
- def run_fuzz(*, seed: int = 921003, iterations: int = 600) -> dict[str, object]:
- if iterations < 9:
- raise ValueError("iterations must be at least nine")
- rng = random.Random(seed)
- categories = (
- "frame",
- "crc",
- "length",
- "percent",
- "solenoid",
- "xyz",
- "motion",
- "host_unknown",
- "stream_noise",
- )
- counts = {category: 0 for category in categories}
- unexpected_accepts = 0
- unexpected_rejections = 0
- atomicity_violations = 0
- stream_resync_failures = 0
- for index in range(iterations):
- category = categories[index % len(categories)]
- counts[category] += 1
- subject = NormalV3Model()
- subject.apply_frame(GOLDEN_VECTORS["enable"])
- before = subject.state_fingerprint()
- candidate = bytearray(GOLDEN_VECTORS["open"])
- result: ModelResult | None = None
- expected_accept = False
- if category == "frame":
- variant = rng.randrange(6)
- if variant == 0:
- candidate[0] ^= 1
- elif variant == 1:
- candidate[2] = 3
- candidate = bytearray(_repair_crc(bytes(candidate)))
- elif variant == 2:
- candidate[3] = 5
- candidate = bytearray(_repair_crc(bytes(candidate)))
- elif variant == 3:
- candidate[4] = 0x08
- candidate = bytearray(_repair_crc(bytes(candidate)))
- elif variant == 4:
- candidate[5 + rng.randrange(4)] = 1
- candidate = bytearray(_repair_crc(bytes(candidate)))
- else:
- candidate[9 + rng.randrange(4)] = 1
- candidate = bytearray(_repair_crc(bytes(candidate)))
- result = subject.apply_frame(bytes(candidate))
- elif category == "crc":
- candidate[-rng.choice((1, 2))] ^= 1 << rng.randrange(8)
- result = subject.apply_frame(bytes(candidate))
- elif category == "length":
- candidate[13] = rng.choice(tuple(value for value in range(256) if value != 34))
- candidate = bytearray(_repair_crc(bytes(candidate)))
- result = subject.apply_frame(bytes(candidate))
- elif category == "percent":
- candidate[16 + rng.randrange(28)] = rng.randrange(101, 256)
- candidate = bytearray(_repair_crc(bytes(candidate)))
- result = subject.apply_frame(bytes(candidate))
- elif category == "solenoid":
- candidate[44] = rng.randrange(1, 100)
- candidate = bytearray(_repair_crc(bytes(candidate)))
- result = subject.apply_frame(bytes(candidate))
- elif category == "xyz":
- candidate[45 + rng.randrange(3)] = rng.randrange(1, 100)
- candidate = bytearray(_repair_crc(bytes(candidate)))
- result = subject.apply_frame(bytes(candidate))
- expected_accept = True
- elif category == "motion":
- variant = rng.randrange(6)
- payload = bytearray((MOTION_JOG, 0, 0, 0, 1, 0, 0, 0))
- if variant == 0:
- payload[1] = 3
- elif variant == 1:
- payload[2] = 2
- elif variant == 2:
- payload[3] = 4
- elif variant == 3:
- payload[4:6] = b"\x00\x00"
- elif variant == 4:
- payload[6] = 1
- else:
- payload[7] = 1
- if variant == 3:
- try:
- subject.apply_frame(encode_motion_frame(payload))
- except HostContractViolation:
- if subject.state_fingerprint() != before:
- atomicity_violations += 1
- else:
- result = subject.apply_frame(encode_motion_frame(payload))
- elif category == "host_unknown":
- result = subject.apply_frame(encode_host_frame(bytes((0x29, 0, 0, 0))))
- else:
- noise = b"\xA5\x00\xA5" + bytes(rng.randrange(256) for _ in range(rng.randrange(1, 96)))
- bad_frame = bytearray(GOLDEN_VECTORS["open"])
- bad_frame[-1] ^= 1
- accepted = subject.feed_stream(noise + bytes(bad_frame) + GOLDEN_VECTORS["enable"])
- if len(accepted) != 1 or accepted[0].command != CMD_SET_SNAPSHOT:
- stream_resync_failures += 1
- if result is not None and result.accepted and not expected_accept:
- unexpected_accepts += 1
- if result is not None and not result.accepted and expected_accept:
- unexpected_rejections += 1
- if (
- result is not None
- and not expected_accept
- and subject.state_fingerprint() != before
- ):
- atomicity_violations += 1
- return {
- "status": "pass"
- if unexpected_accepts == 0
- and unexpected_rejections == 0
- and atomicity_violations == 0
- and stream_resync_failures == 0
- else "fail",
- "verification_layer": "binary921_v3_fuzz",
- "seed": seed,
- "iterations": iterations,
- "category_counts": counts,
- "unexpected_accepts": unexpected_accepts,
- "unexpected_rejections": unexpected_rejections,
- "atomicity_violations": atomicity_violations,
- "stream_resync_failures": stream_resync_failures,
- "authority_boundary": "Deterministic malformed-frame fuzzing only; no UART or hardware is accessed.",
- }
- def _extract_production_sources(harness_path: Path) -> list[str]:
- try:
- module = ast.parse(harness_path.read_text(encoding="utf-8-sig"), filename=str(harness_path))
- except (OSError, UnicodeError, SyntaxError) as exc:
- raise ValueError(f"unable to parse production source registry: {exc}") from exc
- for node in module.body:
- if isinstance(node, ast.Assign):
- for target in node.targets:
- if isinstance(target, ast.Name) and target.id == "PROD2U_P4_NORMAL_V3_SOURCES":
- value = ast.literal_eval(node.value)
- if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
- raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES must be a literal string list")
- return value
- if isinstance(node, ast.FunctionDef) and node.name == "active_rtl_sources":
- project_root = harness_path.resolve().parents[1]
- paths = sorted((project_root / "src" / "rtl").glob("*.v"))
- paths.append(project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v")
- return [
- path.relative_to(project_root).as_posix()
- for path in paths
- if path.is_file()
- ]
- raise ValueError("PROD2U_P4_NORMAL_V3_SOURCES is missing")
- def run_detector(root: Path | str = ROOT) -> dict[str, object]:
- project_root = Path(root).resolve()
- failures: list[str] = []
- try:
- sources = _extract_production_sources(project_root / "tools" / "prod2u_p4_harness.py")
- except ValueError as exc:
- sources = []
- failures.append(str(exc))
- forbidden_name_tokens = ("tach", "telemetry", "single_channel", "old_motion")
- forbidden_source_hits = [
- source for source in sources if any(token in source.casefold() for token in forbidden_name_tokens)
- ]
- missing_sources = [source for source in sources if not (project_root / source).is_file()]
- legacy_asset_hits = sorted(
- path for path in LEGACY_P4_ASSET_PATHS if (project_root / path).is_file()
- )
- semantic_patterns = {
- "tach_or_telemetry": re.compile(r"\bFAN_(?:TACH|TELEMETRY)\b|\bTACH_CAPTURE\b", re.IGNORECASE),
- "single_channel": re.compile(r"\b(?:CMD_)?SET_(?:PTC|FAN)\b|\bSINGLE_CHANNEL\b", re.IGNORECASE),
- "old_motion": re.compile(r"\b(?:MOTION|CMD|OPCODE)[A-Z0-9_]*\s*=\s*8'h3[0-4]\b", re.IGNORECASE),
- "ready_semantics": re.compile(r"\b(?:FT|FRAME_TYPE|TYPE|CMD)_READY\b|\bREADY_FRAME\b|\bCAPABILITY_BROADCAST\b", re.IGNORECASE),
- "runtime_build_identity": re.compile(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", re.IGNORECASE),
- }
- forbidden_semantic_hits: list[dict[str, str]] = []
- for source in sources:
- path = project_root / source
- if not path.is_file():
- continue
- try:
- text = path.read_text(encoding="utf-8-sig")
- except (OSError, UnicodeError) as exc:
- failures.append(f"unable to read {source}: {exc}")
- continue
- for semantic, pattern in semantic_patterns.items():
- if pattern.search(text):
- forbidden_semantic_hits.append({"source": source, "semantic": semantic})
- top_path = project_root / "src" / "top" / "prod2u_p4_normal_v3_top.v"
- try:
- top_text = top_path.read_text(encoding="utf-8-sig")
- except (OSError, UnicodeError) as exc:
- top_text = ""
- failures.append(f"unable to read v3 top: {exc}")
- guards = {
- "runtime_build_identity_absent": not bool(
- re.search(r"\bBUILD_ID\b|\bBOOT_BUILD_ID\b", top_text, re.IGNORECASE)
- ),
- "solenoid_polarity_default_explicit": bool(
- re.search(
- r"parameter\s+integer\s+SOLENOID_ACTIVE_HIGH\s*=\s*[01]",
- top_text,
- re.IGNORECASE,
- )
- ),
- "solenoid_polarity_elaboration_block": "g_solenoid_polarity_must_be_confirmed" in top_text and "prod2u_p4_solenoid_polarity_must_be_confirmed" in top_text,
- }
- missing_guards = [name for name, present in guards.items() if not present]
- if forbidden_source_hits:
- failures.append("forbidden source names are present")
- if forbidden_semantic_hits:
- failures.append("forbidden v2 semantics are present")
- if missing_sources:
- failures.append("production sources are missing")
- if missing_guards:
- failures.append("top-level identity or polarity guards are missing")
- if legacy_asset_hits:
- failures.append("legacy Profile 4 v2 assets are still present")
- if len(sources) != len(set(sources)):
- failures.append("production source list contains duplicates")
- return {
- "status": "pass" if not failures else "fail",
- "verification_layer": "binary921_v3_detector",
- "production_source_count": len(sources),
- "production_sources": sources,
- "forbidden_source_hits": forbidden_source_hits,
- "forbidden_semantic_hits": forbidden_semantic_hits,
- "missing_sources": missing_sources,
- "legacy_asset_hits": legacy_asset_hits,
- "guards": guards,
- "missing_guards": missing_guards,
- "failures": failures,
- "authority_boundary": "Static production-source and elaboration-guard inspection only; no build or hardware is accessed.",
- }
- def run_selftest(root: Path | str = ROOT) -> dict[str, object]:
- reports = {
- "model": run_model(),
- "replay": run_replay(),
- "fuzz": run_fuzz(seed=921003, iterations=60),
- "detector": run_detector(root),
- }
- layers = {name: report["status"] for name, report in reports.items()}
- return {
- "status": "pass" if all(status == "pass" for status in layers.values()) else "fail",
- "profile": PROFILE_ID,
- "hardware_opened": False,
- "layers": layers,
- "reports": reports,
- "authority_boundary": "Offline selftest only; it does not enumerate or open serial, JTAG, or other hardware.",
- }
- def _build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- subparsers = parser.add_subparsers(dest="command", required=True)
- for name in ("model", "replay"):
- child = subparsers.add_parser(name)
- child.add_argument("--json", action="store_true")
- fuzz = subparsers.add_parser("fuzz")
- fuzz.add_argument("--seed", type=int, default=921003)
- fuzz.add_argument("--iterations", type=int, default=600)
- fuzz.add_argument("--json", action="store_true")
- detector = subparsers.add_parser("detector")
- detector.add_argument("--root", type=Path, default=ROOT)
- detector.add_argument("--json", action="store_true")
- selftest = subparsers.add_parser("selftest")
- selftest.add_argument("--root", type=Path, default=ROOT)
- selftest.add_argument("--json", action="store_true")
- return parser
- def main(argv: Sequence[str] | None = None) -> int:
- args = _build_parser().parse_args(argv)
- if args.command == "model":
- report = run_model()
- elif args.command == "replay":
- report = run_replay()
- elif args.command == "fuzz":
- report = run_fuzz(seed=args.seed, iterations=args.iterations)
- elif args.command == "detector":
- report = run_detector(args.root)
- else:
- report = run_selftest(args.root)
- print(json.dumps(report, indent=2, sort_keys=True))
- return 0 if report.get("status") == "pass" else 1
- if __name__ == "__main__":
- raise SystemExit(main())
|