| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699 |
- #!/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_TEMPERATURE_SHORT = 0x10
- FRAME_MOTION_CMD = 0x11
- FRAME_MOTION_STATUS = 0x12
- CMD_GET_STATUS = 0x24
- CMD_DISABLE = 0x26
- CMD_GET_TEMPERATURES = 0x28
- 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_TEMPERATURE_BUS_ERROR = 0x0A
- 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
- TEMPERATURE_COUNT = 27
- DEFAULT_TEMPERATURE_VALUES = (0xFF,) * TEMPERATURE_COUNT
- 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_temperature_response(values: bytes | bytearray | Iterable[int]) -> bytes:
- payload = bytes(
- _byte_values(values, count=TEMPERATURE_COUNT, label="temperature")
- )
- body = bytes(
- (VERSION, PROFILE, FRAME_TEMPERATURE_SHORT, TEMPERATURE_COUNT)
- ) + payload
- 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,
- *,
- temperature_values: Iterable[int] = DEFAULT_TEMPERATURE_VALUES,
- powerup_ready: bool = True,
- temperature_bus_error: bool = False,
- ) -> 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
- self.temperature_values = _byte_values(
- temperature_values,
- count=TEMPERATURE_COUNT,
- label="temperature",
- )
- self.powerup_ready = bool(powerup_ready)
- self.temperature_bus_error = bool(temperature_bus_error)
- @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)
- if command == CMD_GET_TEMPERATURES:
- if not self.powerup_ready:
- values = DEFAULT_TEMPERATURE_VALUES
- elif self.temperature_bus_error:
- return self._result(
- accepted=False,
- command=command,
- status=STATUS_TEMPERATURE_BUS_ERROR,
- )
- else:
- values = self.temperature_values
- return self._result(
- accepted=True,
- command=command,
- status=STATUS_OK,
- response_type=FRAME_TEMPERATURE_SHORT,
- response=encode_temperature_response(values),
- )
- 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())
|