| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992 |
- #!/usr/bin/env python3
- """Normal-only host tooling for Prod2U Profile 4 binary921-v3."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import queue
- import re
- import subprocess
- import sys
- import threading
- import time
- from dataclasses import dataclass
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any, Callable, Mapping
- from prod2u_programmer import execute_program_sram
- from prod2u_p4_normal_v3_build import validate_build_info, verify_bitstream
- from prod2u_p4_normal_v3_receipts import replay_serial_transcript_events, validate_session_receipt
- from prod2u_p4_protocol import (
- CRC_LEN,
- HEADER_LEN,
- MAGIC,
- CAPABILITY_FLAGS,
- BootBuildId,
- CommandId,
- FrameType,
- HostAck,
- MotionStatus,
- P4Frame,
- P4FrameError,
- StatusCode,
- build_get_motor_status,
- build_host_command,
- build_mark_closed,
- build_motor_jog,
- build_output_snapshot,
- decode_boot_build_id,
- decode_frame,
- decode_host_ack,
- decode_motion_status,
- state_hash16,
- )
- from prod2u_p4_trace import (
- AxisStopReason,
- AxisTraceSource,
- CompletedCommand,
- EpochTraceEvidence,
- TraceEvent,
- TraceEventType,
- TraceHostPolicy,
- TracePolicyError,
- decode_axis_trace_event,
- decode_epoch_trace_event,
- decode_limit_trace_event,
- decode_overflow_trace_event,
- decode_trace_frame,
- encode_trace_frame,
- )
- PROFILE = "prod2u-p4-normal-actuator-trace-binary921-v3"
- PROFILE_ID = 4
- PROTOCOL_VERSION = 2
- PORT = "COM5"
- BAUD = 921600
- DEFAULT_TD_ROOT = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412")
- BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
- BOARD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
- COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
- SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
- HARDWARE_QUALIFIED_AXES = (0, 1)
- SAFE_STATE_HASH16 = state_hash16(
- ptc_percent=(0,) * 24,
- fan_percent=(30,) * 4,
- solenoid=0,
- )
- POST_FAULT_DRAIN_BYTE_LIMIT = 8192
- POST_FAULT_DRAIN_FRAME_LIMIT = 64
- POST_FAULT_DRAIN_SECONDS = 0.050
- @dataclass(frozen=True)
- class CommandResult:
- ack: HostAck
- raw_response: bytes
- frames: tuple[P4Frame, ...]
- command_result_trace: TraceEvent
- @dataclass(frozen=True)
- class MotorStatusResult:
- ack: HostAck
- status: MotionStatus
- raw_response: bytes
- class _PumpCall:
- def __init__(
- self,
- action: Callable[[], Any],
- *,
- pre_dispatch_quiet: bool,
- activate_parser: bool,
- ) -> None:
- self.action = action
- self.pre_dispatch_quiet = pre_dispatch_quiet
- self.activate_parser = activate_parser
- self.done = threading.Event()
- self.result: Any = None
- self.error: BaseException | None = None
- def open_com5(serial_factory: Callable[[], Any] | None = None) -> Any:
- if serial_factory is None:
- try:
- import serial # type: ignore
- except ImportError as exc:
- raise RuntimeError("pyserial is required for live Profile 4 operation") from exc
- serial_factory = serial.Serial
- endpoint = serial_factory()
- endpoint.port = PORT
- endpoint.baudrate = BAUD
- endpoint.bytesize = 8
- endpoint.parity = "N"
- endpoint.stopbits = 1
- endpoint.timeout = 0
- endpoint.write_timeout = 1
- endpoint.dtr = False
- endpoint.rts = False
- if not getattr(endpoint, "is_open", False):
- endpoint.open()
- endpoint.dtr = False
- endpoint.rts = False
- return endpoint
- class NormalSession:
- """One-outstanding-command COM5 session with one DISABLE fallback."""
- def __init__(
- self,
- endpoint: Any,
- *,
- timeout_seconds: float = 0.25,
- quiet_window_seconds: float = 0.010,
- max_quiet_drain_seconds: float = 0.050,
- monotonic: Callable[[], float] = time.monotonic,
- sleep: Callable[[float], None] = time.sleep,
- expected_build_id: int | None = None,
- expected_capability_flags: int | None = None,
- ) -> None:
- if timeout_seconds <= 0:
- raise ValueError("timeout_seconds must be positive")
- if quiet_window_seconds <= 0:
- raise ValueError("quiet_window_seconds must be positive")
- if max_quiet_drain_seconds < quiet_window_seconds:
- raise ValueError("max_quiet_drain_seconds must cover the quiet window")
- for name, value in (
- ("expected_build_id", expected_build_id),
- ("expected_capability_flags", expected_capability_flags),
- ):
- if value is not None and (
- isinstance(value, bool)
- or not isinstance(value, int)
- or not 0 <= value <= 0xFFFFFFFF
- ):
- raise ValueError(f"{name} must be a 32-bit integer or None")
- self.endpoint = endpoint
- self.timeout_seconds = timeout_seconds
- self.quiet_window_seconds = quiet_window_seconds
- self.max_quiet_drain_seconds = max_quiet_drain_seconds
- self.disable_attempted = False
- self._command_lock = threading.Lock()
- self._state_lock = threading.RLock()
- self._fail_lock = threading.Lock()
- self._rx_buffer = bytearray()
- self._rx_journal = bytearray()
- self._last_exchange: dict[str, Any] | None = None
- self._best_effort_disable_exchange: dict[str, Any] | None = None
- self._trace_policy = TraceHostPolicy()
- self._post_fault_trace_events: list[TraceEvent] = []
- self._post_fault_drain_attempted = False
- self._terminated = False
- self._startup_preamble_state = "inactive"
- self._startup_boot_seen = False
- self._startup_epoch_seen = False
- self.expected_build_id = expected_build_id
- self.expected_capability_flags = expected_capability_flags
- self.startup_boot_identity: BootBuildId | None = None
- self.startup_epoch: EpochTraceEvidence | None = None
- self._monotonic = monotonic
- self._sleep = sleep
- self._pump_calls: queue.Queue[_PumpCall | None] = queue.Queue(maxsize=1)
- self._pump_thread: threading.Thread | None = None
- self._pump_thread_id: int | None = None
- self._pump_stop = threading.Event()
- self._pump_started = threading.Event()
- self._pump_persistent = False
- self._pump_capture_only = False
- self._pump_error: BaseException | None = None
- self._idle_partial_since: float | None = None
- self._idle_frames: list[P4Frame] = []
- self._idle_raw = bytearray()
- @property
- def rx_journal(self) -> bytes:
- with self._state_lock:
- return bytes(self._rx_journal)
- @property
- def trace_events(self) -> list[TraceEvent]:
- with self._state_lock:
- return [
- *self._trace_policy.trace_events,
- *self._post_fault_trace_events,
- ]
- @property
- def last_exchange(self) -> dict[str, Any] | None:
- with self._state_lock:
- return None if self._last_exchange is None else dict(self._last_exchange)
- @property
- def best_effort_disable_exchange(self) -> dict[str, Any] | None:
- with self._state_lock:
- return (
- None
- if self._best_effort_disable_exchange is None
- else dict(self._best_effort_disable_exchange)
- )
- @property
- def reader_running(self) -> bool:
- thread = self._pump_thread
- return thread is not None and thread.is_alive()
- @property
- def reader_thread_id(self) -> int | None:
- return self._pump_thread_id
- @property
- def reader_error(self) -> BaseException | None:
- return self._pump_error
- def start_reader(
- self,
- *,
- persistent: bool = True,
- capture_only: bool = False,
- allow_startup_preamble: bool = False,
- ) -> None:
- if self.reader_running:
- if persistent:
- self._pump_persistent = True
- if capture_only:
- self._pump_capture_only = True
- return
- if allow_startup_preamble:
- self._begin_startup_preamble(
- expected_command=CommandId.DISABLE,
- allow_boot_preamble=True,
- )
- self._pump_stop.clear()
- self._pump_started.clear()
- self._pump_calls = queue.Queue(maxsize=1)
- self._pump_persistent = persistent
- self._pump_capture_only = capture_only
- self._pump_error = None
- self._idle_partial_since = None
- self._pump_thread = threading.Thread(
- target=self._pump_loop,
- name="prod2u-p4-uart-pump",
- daemon=True,
- )
- self._pump_thread.start()
- if not self._pump_started.wait(1.0):
- raise RuntimeError("UART pump did not start within its bound")
- def stop_reader(self) -> None:
- thread = self._pump_thread
- if thread is None:
- return
- self._pump_stop.set()
- thread.join(timeout=max(1.0, self.timeout_seconds + self.max_quiet_drain_seconds + 0.5))
- if thread.is_alive():
- raise RuntimeError("UART pump did not stop within its bounded join")
- self._pump_thread = None
- self._pump_thread_id = None
- self._pump_persistent = False
- self._pump_capture_only = False
- self._pump_started.clear()
- def _store_idle_frames(self, frames: tuple[P4Frame, ...]) -> None:
- with self._state_lock:
- self._idle_frames.extend(frames)
- for frame in frames:
- self._idle_raw.extend(frame.raw)
- def _pump_capture_once(self) -> None:
- chunk = self._read_endpoint(256)
- if chunk:
- self._rx_buffer.extend(chunk)
- return
- self._pump_stop.wait(0.0005)
- def _capture_available_on_pump(self) -> None:
- captured = 0
- while True:
- chunk = self._read_endpoint(256)
- if not chunk:
- return
- self._rx_buffer.extend(chunk)
- captured += len(chunk)
- if captured >= 8192:
- return
- def _pump_idle_once(self) -> None:
- chunk = self._read_endpoint(256)
- if chunk:
- self._rx_buffer.extend(chunk)
- if self._idle_partial_since is None:
- self._idle_partial_since = self._monotonic()
- frames: list[P4Frame] = []
- while True:
- frame = self._pop_frame()
- if frame is None:
- break
- frames.append(frame)
- self._consume_passive_trace_frame(frame, expected_command=-1)
- if frames:
- self._store_idle_frames(tuple(frames))
- if self._rx_buffer:
- if self._idle_partial_since is None:
- self._idle_partial_since = self._monotonic()
- elif self._monotonic() - self._idle_partial_since >= self.max_quiet_drain_seconds:
- self._fail(
- -1,
- "idle UART stream ended with a truncated frame",
- drain_overflow_evidence=False,
- )
- else:
- self._idle_partial_since = None
- if not chunk:
- self._pump_stop.wait(0.0005)
- def _record_background_failure(self, exc: BaseException, *, capture_only: bool) -> None:
- if capture_only:
- self._pump_error = exc
- return
- if self._terminated:
- self._pump_error = exc
- return
- try:
- self._fail(-1, f"UART pump failure: {type(exc).__name__}:{exc}")
- except BaseException as fatal:
- self._pump_error = fatal
- def _pump_loop(self) -> None:
- self._pump_thread_id = threading.get_ident()
- self._pump_started.set()
- try:
- while not self._pump_stop.is_set():
- try:
- call = self._pump_calls.get_nowait()
- except queue.Empty:
- call = None
- if call is not None:
- if self._terminated:
- call.error = RuntimeError("Profile 4 session is terminated")
- call.done.set()
- break
- try:
- if self._pump_capture_only and call.activate_parser:
- self._pump_capture_only = False
- if call.pre_dispatch_quiet:
- self._store_idle_frames(
- self._drain_trace_quiet_window(
- expected_command=-1,
- maximum_seconds=self.max_quiet_drain_seconds,
- )
- )
- call.result = call.action()
- except BaseException as exc:
- call.error = exc
- finally:
- call.done.set()
- if not self._pump_persistent or self._terminated:
- break
- continue
- if not self._pump_persistent:
- self._pump_stop.wait(0.0005)
- continue
- if self._terminated:
- break
- capture_only = self._pump_capture_only
- try:
- if capture_only:
- self._pump_capture_once()
- else:
- self._pump_idle_once()
- except BaseException as exc:
- self._record_background_failure(exc, capture_only=capture_only)
- break
- finally:
- self._pump_started.set()
- def _run_on_pump(
- self,
- action: Callable[[], Any],
- *,
- pre_dispatch_quiet: bool,
- activate_parser: bool = True,
- ) -> Any:
- started_here = not self.reader_running
- if started_here:
- self.start_reader(persistent=False)
- call = _PumpCall(
- action,
- pre_dispatch_quiet=pre_dispatch_quiet,
- activate_parser=activate_parser,
- )
- try:
- try:
- self._pump_calls.put_nowait(call)
- except queue.Full as exc:
- raise RuntimeError("UART pump already has a queued operation") from exc
- wait_seconds = max(
- 2.0,
- self.timeout_seconds + self.max_quiet_drain_seconds + 1.0,
- )
- if not call.done.wait(wait_seconds):
- raise TimeoutError("UART pump operation did not complete within its bound")
- if call.error is not None:
- raise call.error
- return call.result
- finally:
- if started_here:
- self.stop_reader()
- def close(self) -> None:
- try:
- self.stop_reader()
- finally:
- self.endpoint.close()
- def _finish_exchange(
- self,
- *,
- request: bytes,
- response_prefix: bytes,
- journal_start: int,
- command: object,
- ) -> None:
- with self._state_lock:
- response = response_prefix + bytes(self._rx_journal[journal_start:])
- self._last_exchange = {
- "request_hex": request.hex(),
- "response_hex": response.hex(),
- "command": command,
- }
- def _read_endpoint(self, size: int = 256) -> bytes:
- chunk = bytes(self.endpoint.read(size))
- if chunk:
- with self._state_lock:
- self._rx_journal.extend(chunk)
- return chunk
- def _write_once(self, frame: bytes) -> None:
- written = self.endpoint.write(frame)
- if written != len(frame):
- raise IOError(f"short serial write: {written}/{len(frame)}")
- def _attempt_disable(self) -> None:
- with self._fail_lock:
- if self.disable_attempted:
- return
- self.disable_attempted = True
- request = build_host_command(command=CommandId.DISABLE)
- with self._state_lock:
- self._best_effort_disable_exchange = {
- "request_hex": request.hex(),
- "response_hex": "",
- "command": "DISABLE",
- }
- try:
- self._write_once(request)
- except Exception:
- pass
- def _drain_post_fault_overflow_evidence(self, expected_event_seq: int) -> None:
- if self._post_fault_drain_attempted:
- return
- self._post_fault_drain_attempted = True
- with self._state_lock:
- existing = list(self._trace_policy.trace_events)
- if any(event.event_type == TraceEventType.OVERFLOW for event in existing):
- return
- hard_deadline = self._monotonic() + min(
- self.max_quiet_drain_seconds,
- POST_FAULT_DRAIN_SECONDS,
- )
- quiet_deadline = self._monotonic() + self.quiet_window_seconds
- bytes_seen = len(self._rx_buffer)
- frames_seen = 0
- while (
- self._monotonic() < hard_deadline
- and bytes_seen <= POST_FAULT_DRAIN_BYTE_LIMIT
- and frames_seen < POST_FAULT_DRAIN_FRAME_LIMIT
- ):
- try:
- frame = self._pop_frame()
- except P4FrameError:
- self._rx_buffer.clear()
- return
- if frame is not None:
- frames_seen += 1
- if frame.frame_type != FrameType.TRACE_EVENT:
- continue
- try:
- event = decode_trace_frame(frame.raw)
- overflow = decode_overflow_trace_event(event)
- except ValueError:
- continue
- if overflow.first_lost_event_seq != expected_event_seq:
- continue
- with self._state_lock:
- known_sequences = {
- item.event_seq
- for item in (
- *self._trace_policy.trace_events,
- *self._post_fault_trace_events,
- )
- }
- if event.event_seq not in known_sequences:
- self._post_fault_trace_events.append(event)
- return
- now = self._monotonic()
- if now >= quiet_deadline:
- return
- remaining = POST_FAULT_DRAIN_BYTE_LIMIT - bytes_seen
- if remaining <= 0:
- return
- chunk = self._read_endpoint(min(256, remaining))
- if chunk:
- bytes_seen += len(chunk)
- self._rx_buffer.extend(chunk)
- quiet_deadline = self._monotonic() + self.quiet_window_seconds
- continue
- self._sleep(0.0005)
- def _fail(
- self,
- expected_command: CommandId | int,
- message: str,
- *,
- drain_overflow_evidence: bool = True,
- ) -> None:
- with self._state_lock:
- expected_event_seq = self._trace_policy.expected_event_seq
- self._terminated = True
- if int(expected_command) == int(CommandId.DISABLE):
- self.disable_attempted = True
- else:
- self._attempt_disable()
- if drain_overflow_evidence:
- self._drain_post_fault_overflow_evidence(expected_event_seq)
- self._rx_buffer.clear()
- raise RuntimeError(message)
- def _pop_frame(self) -> P4Frame | None:
- if not self._rx_buffer:
- return None
- magic_at = self._rx_buffer.find(MAGIC)
- if magic_at < 0:
- if self._rx_buffer == MAGIC[:1]:
- return None
- raise P4FrameError("non-frame bytes before Profile 4 magic")
- if magic_at:
- raise P4FrameError("non-frame bytes before Profile 4 magic")
- if len(self._rx_buffer) < HEADER_LEN + CRC_LEN:
- return None
- frame_len = HEADER_LEN + self._rx_buffer[13] + CRC_LEN
- if len(self._rx_buffer) < frame_len:
- return None
- raw = bytes(self._rx_buffer[:frame_len])
- del self._rx_buffer[:frame_len]
- return decode_frame(raw)
- def collect_available(self) -> bytes:
- """Collect every byte currently available without parsing or discarding partial frames."""
- if self._pump_thread is not None:
- raise RuntimeError("UART pump owns serial reads while the reader is running")
- raw = bytearray()
- while True:
- chunk = self._read_endpoint(256)
- if not chunk:
- break
- raw.extend(chunk)
- self._rx_buffer.extend(chunk)
- return bytes(raw)
- def drain_unparsed(self, *, timeout_seconds: float) -> bytes:
- """Quarantine pre-session bytes while keeping the same physical UART reader."""
- if self._pump_thread is not None:
- raise RuntimeError("UART pump owns serial reads while the reader is running")
- deadline = self._monotonic() + timeout_seconds
- while self._monotonic() < deadline:
- if not self.collect_available():
- self._sleep(0.001)
- raw = bytes(self._rx_buffer)
- self._rx_buffer.clear()
- return raw
- @staticmethod
- def _trace_failure_message(exc: TracePolicyError) -> str:
- message = str(exc)
- if "HOST_ACK arrived before COMMAND_RESULT" in message:
- return "COMMAND_RESULT must arrive before HOST_ACK"
- if "COMMAND_RESULT request identity mismatch" in message:
- return "COMMAND_RESULT request frame type or CRC mismatch"
- return message
- def _consume_passive_trace_frame(
- self,
- frame: P4Frame,
- *,
- expected_command: CommandId | int,
- ) -> None:
- if frame.frame_type == FrameType.BOOT_BUILD_ID:
- if self._startup_preamble_state != "open":
- self._fail(expected_command, "BOOT_BUILD_ID outside startup preamble")
- self._observe_startup_boot(
- expected_command=expected_command,
- allow_boot_preamble=True,
- command_result_seen=False,
- frame=frame,
- )
- return
- if frame.frame_type != FrameType.TRACE_EVENT:
- self._fail(expected_command, "unexpected response frame after command completion")
- self._guard_startup_trace_frame(frame, expected_command=expected_command)
- try:
- with self._state_lock:
- observed = self._trace_policy.observe_wire(frame.raw)
- except TracePolicyError as exc:
- self._fail(expected_command, self._trace_failure_message(exc))
- event = decode_trace_frame(frame.raw)
- self._observe_startup_trace(event, expected_command=expected_command)
- if observed != event or event != self.trace_events[-1]:
- self._fail(expected_command, "Trace decoder and host policy disagree")
- def _drain_trace_quiet_window(
- self,
- *,
- expected_command: CommandId | int,
- maximum_seconds: float,
- ) -> tuple[P4Frame, ...]:
- if maximum_seconds <= 0:
- raise ValueError("maximum_seconds must be positive")
- started = self._monotonic()
- hard_deadline = started + maximum_seconds
- quiet_deadline = started + self.quiet_window_seconds
- frames: list[P4Frame] = []
- newly_read_bytes = 0
- while True:
- try:
- frame = self._pop_frame()
- except P4FrameError as exc:
- self._fail(expected_command, f"malformed Profile 4 frame: {exc}")
- if frame is not None:
- frames.append(frame)
- self._consume_passive_trace_frame(
- frame,
- expected_command=expected_command,
- )
- continue
- now = self._monotonic()
- if now >= hard_deadline:
- if self._rx_buffer:
- self._fail(
- expected_command,
- "quiet-window drain ended with a truncated frame",
- drain_overflow_evidence=False,
- )
- if quiet_deadline > now:
- self._fail(
- expected_command,
- "UART quiet window did not settle before its hard deadline",
- drain_overflow_evidence=False,
- )
- return tuple(frames)
- chunk = self._read_endpoint(256)
- if chunk:
- newly_read_bytes += len(chunk)
- if newly_read_bytes > 8192:
- self._fail(
- expected_command,
- "UART quiet-window byte budget exceeded",
- drain_overflow_evidence=False,
- )
- self._rx_buffer.extend(chunk)
- quiet_deadline = self._monotonic() + self.quiet_window_seconds
- continue
- if now >= quiet_deadline:
- if self._rx_buffer:
- self._sleep(0.0005)
- continue
- return tuple(frames)
- self._sleep(0.0005)
- def _begin_startup_preamble(
- self,
- *,
- expected_command: CommandId | int,
- allow_boot_preamble: bool,
- ) -> None:
- if not allow_boot_preamble:
- return
- if self._startup_preamble_state == "closed":
- self._fail(expected_command, "startup BOOT/EPOCH preamble may occur only once")
- if self._startup_preamble_state == "inactive":
- self._startup_preamble_state = "open"
- def _observe_startup_boot(
- self,
- *,
- expected_command: CommandId | int,
- allow_boot_preamble: bool,
- command_result_seen: bool,
- frame: P4Frame,
- ) -> bool:
- if not allow_boot_preamble and self._startup_preamble_state == "inactive":
- return False
- if not allow_boot_preamble or self._startup_preamble_state != "open":
- self._fail(expected_command, "BOOT_BUILD_ID outside startup preamble")
- if self._startup_boot_seen:
- self._fail(expected_command, "duplicate BOOT_BUILD_ID in startup preamble")
- if self._startup_epoch_seen or command_result_seen:
- self._fail(expected_command, "BOOT_BUILD_ID must precede EPOCH")
- try:
- identity = decode_boot_build_id(frame)
- except ValueError as exc:
- self._fail(expected_command, f"malformed BOOT_BUILD_ID: {exc}")
- self.startup_boot_identity = identity
- if (
- self.expected_build_id is not None
- and identity.build_id != self.expected_build_id
- ) or (
- self.expected_capability_flags is not None
- and identity.capability_flags != self.expected_capability_flags
- ):
- self._fail(expected_command, "startup BOOT identity mismatch")
- self._startup_boot_seen = True
- return True
- def _observe_startup_trace(
- self,
- event: TraceEvent,
- *,
- expected_command: CommandId | int,
- ) -> None:
- if (
- event.event_type == TraceEventType.EPOCH
- and self._startup_preamble_state != "open"
- ):
- self._fail(expected_command, "EPOCH outside startup preamble")
- if self._startup_preamble_state != "open":
- return
- if event.event_type == TraceEventType.EPOCH:
- if not self._startup_boot_seen:
- self._fail(expected_command, "BOOT_BUILD_ID must precede EPOCH")
- if self._startup_epoch_seen:
- self._fail(expected_command, "duplicate EPOCH in startup preamble")
- if event.event_seq != 1:
- self._fail(expected_command, "startup EPOCH must use event_seq 1")
- epoch = decode_epoch_trace_event(event)
- boot = self.startup_boot_identity
- if boot is None or (
- epoch.build_id != boot.build_id
- or epoch.capability_flags != boot.capability_flags
- ):
- self._fail(expected_command, "startup BOOT/EPOCH identity mismatch")
- if (
- self.expected_build_id is not None
- and epoch.build_id != self.expected_build_id
- ) or (
- self.expected_capability_flags is not None
- and epoch.capability_flags != self.expected_capability_flags
- ):
- self._fail(expected_command, "startup EPOCH identity mismatch")
- self.startup_epoch = epoch
- self._startup_epoch_seen = True
- return
- if not self._startup_epoch_seen:
- self._fail(expected_command, "EPOCH must precede startup Trace backlog")
- def _guard_startup_trace_frame(
- self,
- frame: P4Frame,
- *,
- expected_command: CommandId | int,
- ) -> None:
- if (
- frame.frame_type == FrameType.TRACE_EVENT
- and self._startup_preamble_state != "open"
- and len(frame.payload) >= 5
- and frame.payload[4] == int(TraceEventType.EPOCH)
- ):
- self._fail(expected_command, "EPOCH outside startup preamble")
- def _read_command_frames(
- self,
- *,
- expected_command: CommandId | int,
- expected_followup: FrameType | None,
- allow_boot_preamble: bool,
- ) -> tuple[tuple[P4Frame, ...], bytes, CompletedCommand]:
- deadline = self._monotonic() + self.timeout_seconds
- frames: list[P4Frame] = []
- completed: CompletedCommand | None = None
- command_result_seen = False
- self._begin_startup_preamble(
- expected_command=expected_command,
- allow_boot_preamble=allow_boot_preamble,
- )
- while self._monotonic() < deadline:
- frame = self._pop_frame()
- if frame is None:
- chunk = self._read_endpoint(256)
- if chunk:
- self._rx_buffer.extend(chunk)
- continue
- self._sleep(0.0005)
- continue
- frames.append(frame)
- if frame.frame_type == FrameType.BOOT_BUILD_ID:
- if self._observe_startup_boot(
- expected_command=expected_command,
- allow_boot_preamble=allow_boot_preamble,
- command_result_seen=command_result_seen,
- frame=frame,
- ):
- continue
- self._guard_startup_trace_frame(
- frame,
- expected_command=expected_command,
- )
- try:
- with self._state_lock:
- observed = self._trace_policy.observe_wire(frame.raw)
- except TracePolicyError as exc:
- self._fail(expected_command, self._trace_failure_message(exc))
- if frame.frame_type == FrameType.TRACE_EVENT:
- event = decode_trace_frame(frame.raw)
- self._observe_startup_trace(event, expected_command=expected_command)
- if event.event_type == TraceEventType.COMMAND_RESULT:
- if self._startup_preamble_state == "open" and not (
- self._startup_boot_seen and self._startup_epoch_seen
- ):
- self._fail(
- expected_command,
- "startup BOOT/EPOCH must precede first COMMAND_RESULT",
- )
- command_result_seen = True
- if event != self.trace_events[-1]:
- self._fail(expected_command, "Trace decoder and host policy disagree")
- if isinstance(observed, CompletedCommand):
- completed = observed
- followup_seen = expected_followup is None or any(
- item.frame_type == expected_followup for item in frames
- )
- if completed is not None and followup_seen:
- if self._startup_preamble_state == "open":
- if not (self._startup_boot_seen and self._startup_epoch_seen):
- self._fail(expected_command, "startup BOOT/EPOCH preamble incomplete")
- self._startup_preamble_state = "closed"
- frames.extend(
- self._drain_trace_quiet_window(
- expected_command=expected_command,
- maximum_seconds=self.max_quiet_drain_seconds,
- )
- )
- return tuple(frames), b"".join(item.raw for item in frames), completed
- raise TimeoutError("Profile 4 ACK timeout without automatic retry")
- def observe_passive_bytes(self, raw: bytes | bytearray) -> tuple[P4Frame, ...]:
- """Consume a complete BOOT/Trace epoch before the first host command."""
- if self._pump_thread is not None:
- raise RuntimeError("UART pump owns passive frame parsing while the reader is running")
- if self._terminated:
- raise RuntimeError("Profile 4 session is terminated")
- data = bytes(raw)
- frames: list[P4Frame] = []
- offset = 0
- while offset < len(data):
- if data[offset : offset + len(MAGIC)] != MAGIC:
- self._fail(-1, "passive UART epoch contains non-frame bytes")
- if len(data) - offset < HEADER_LEN + CRC_LEN:
- self._fail(-1, "passive UART epoch contains a truncated frame")
- end = offset + HEADER_LEN + data[offset + 13] + CRC_LEN
- if end > len(data):
- self._fail(-1, "passive UART epoch contains a truncated frame")
- try:
- frame = decode_frame(data[offset:end])
- except P4FrameError as exc:
- self._fail(-1, f"malformed passive Profile 4 frame: {exc}")
- offset = end
- frames.append(frame)
- if frame.frame_type == FrameType.BOOT_BUILD_ID:
- self._fail(-1, "BOOT_BUILD_ID outside startup preamble")
- if frame.frame_type != FrameType.TRACE_EVENT:
- self._fail(-1, "passive UART epoch contains a non-Trace response")
- self._guard_startup_trace_frame(frame, expected_command=-1)
- try:
- with self._state_lock:
- observed = self._trace_policy.observe_wire(frame.raw)
- except TracePolicyError as exc:
- self._fail(-1, self._trace_failure_message(exc))
- event = decode_trace_frame(frame.raw)
- self._observe_startup_trace(event, expected_command=-1)
- if observed != event or event != self.trace_events[-1]:
- self._fail(-1, "Trace decoder and host policy disagree")
- return tuple(frames)
- def read_passive_frames(self, *, timeout_seconds: float) -> tuple[tuple[P4Frame, ...], bytes]:
- """Drain a bounded quiet window, accepting only continuous asynchronous Trace."""
- if self._terminated:
- raise RuntimeError("Profile 4 session is terminated")
- if not self._command_lock.acquire(blocking=False):
- raise RuntimeError("one outstanding command is already active")
- try:
- return self._run_on_pump(
- lambda: self._read_passive_frames_on_pump(timeout_seconds=timeout_seconds),
- pre_dispatch_quiet=False,
- )
- finally:
- self._command_lock.release()
- def _read_passive_frames_on_pump(
- self,
- *,
- timeout_seconds: float,
- ) -> tuple[tuple[P4Frame, ...], bytes]:
- with self._state_lock:
- frames = list(self._idle_frames)
- raw = bytearray(self._idle_raw)
- self._idle_frames.clear()
- self._idle_raw.clear()
- self._last_exchange = None
- drained = self._drain_trace_quiet_window(
- expected_command=-1,
- maximum_seconds=timeout_seconds,
- )
- frames.extend(drained)
- for frame in drained:
- raw.extend(frame.raw)
- with self._state_lock:
- self._last_exchange = {
- "request_hex": "",
- "response_hex": bytes(raw).hex(),
- "command": "PASSIVE_RX_DRAIN",
- }
- return tuple(frames), bytes(raw)
- def _command_on_pump(
- self,
- request: bytes,
- *,
- expected_command: CommandId | int,
- expected_followup: FrameType | None,
- allowed_statuses: tuple[StatusCode, ...],
- expected_detail: int | None,
- expected_state_hash16: int | None,
- required_result_flags: int,
- allowed_result_flags: int,
- allow_boot_preamble: bool,
- followup_decoder: Callable[[P4Frame], Any] | None,
- followup_name: str,
- ) -> tuple[CommandResult, Any]:
- response_prefix = bytes(self._rx_buffer)
- with self._state_lock:
- journal_start = len(self._rx_journal)
- self._last_exchange = None
- try:
- try:
- with self._state_lock:
- self._trace_policy.begin_command(
- request,
- expected_followup=expected_followup,
- )
- except TracePolicyError as exc:
- self._fail(expected_command, self._trace_failure_message(exc))
- try:
- self._write_once(request)
- except Exception:
- self._terminated = True
- if int(expected_command) == int(CommandId.DISABLE):
- self.disable_attempted = True
- else:
- self._attempt_disable()
- raise
- try:
- frames, raw, completed = self._read_command_frames(
- expected_command=expected_command,
- expected_followup=expected_followup,
- allow_boot_preamble=allow_boot_preamble,
- )
- except TimeoutError:
- self._terminated = True
- if int(expected_command) == int(CommandId.DISABLE):
- self.disable_attempted = True
- else:
- self._attempt_disable()
- raise
- except P4FrameError as exc:
- self._fail(expected_command, f"malformed Profile 4 frame: {exc}")
- ack_frames = [frame for frame in frames if frame.frame_type == FrameType.HOST_ACK]
- if len(ack_frames) != 1:
- self._fail(expected_command, "expected exactly one HOST_ACK")
- try:
- ack = decode_host_ack(ack_frames[0])
- except ValueError as exc:
- self._fail(expected_command, f"malformed HOST_ACK: {exc}")
- if int(ack.command) != int(expected_command):
- self._fail(expected_command, "HOST_ACK command mismatch")
- if not ack.ok or ack.status not in allowed_statuses:
- self._fail(
- expected_command,
- f"HOST_ACK rejected command with status 0x{int(ack.status):02x}",
- )
- expected_response_type = int(expected_followup) if expected_followup is not None else 0
- if int(ack.response_type) != expected_response_type:
- self._fail(expected_command, "HOST_ACK response type mismatch")
- if expected_detail is not None and ack.detail != expected_detail:
- self._fail(expected_command, "HOST_ACK detail mismatch")
- if expected_state_hash16 is not None and ack.state_hash16 != expected_state_hash16:
- self._fail(expected_command, "HOST_ACK state hash mismatch")
- if ack.result_flags & ~allowed_result_flags:
- self._fail(expected_command, "HOST_ACK contains unexpected result flags")
- if (ack.result_flags & required_result_flags) != required_result_flags:
- self._fail(expected_command, "HOST_ACK is missing required result flags")
- decoded_followup: Any = None
- if expected_followup is not None:
- followups = [frame for frame in frames if frame.frame_type == expected_followup]
- if len(followups) != 1:
- self._fail(expected_command, "HOST_ACK follow-up type mismatch")
- if followup_decoder is not None:
- try:
- decoded_followup = followup_decoder(followups[0])
- except ValueError as exc:
- self._fail(expected_command, f"malformed {followup_name}: {exc}")
- result = CommandResult(
- ack=ack,
- raw_response=raw,
- frames=frames,
- command_result_trace=completed.command_result_trace,
- )
- return result, decoded_followup
- finally:
- self._finish_exchange(
- request=bytes(request),
- response_prefix=response_prefix,
- journal_start=journal_start,
- command=int(expected_command),
- )
- def _run_command_transaction(
- self,
- request: bytes,
- *,
- expected_command: CommandId | int,
- expected_followup: FrameType | None,
- allowed_statuses: tuple[StatusCode, ...],
- expected_detail: int | None,
- expected_state_hash16: int | None,
- required_result_flags: int,
- allowed_result_flags: int,
- allow_boot_preamble: bool,
- followup_decoder: Callable[[P4Frame], Any] | None = None,
- followup_name: str = "follow-up",
- ) -> tuple[CommandResult, Any]:
- if self._terminated:
- raise RuntimeError("Profile 4 session is terminated")
- if not self._command_lock.acquire(blocking=False):
- raise RuntimeError("one outstanding command is already active")
- try:
- return self._run_on_pump(
- lambda: self._command_on_pump(
- request,
- expected_command=expected_command,
- expected_followup=expected_followup,
- allowed_statuses=allowed_statuses,
- expected_detail=expected_detail,
- expected_state_hash16=expected_state_hash16,
- required_result_flags=required_result_flags,
- allowed_result_flags=allowed_result_flags,
- allow_boot_preamble=allow_boot_preamble,
- followup_decoder=followup_decoder,
- followup_name=followup_name,
- ),
- pre_dispatch_quiet=not allow_boot_preamble,
- )
- finally:
- self._command_lock.release()
- def command(
- self,
- request: bytes,
- *,
- expected_command: CommandId | int,
- expected_followup: FrameType | None = None,
- allowed_statuses: tuple[StatusCode, ...] = (StatusCode.OK, StatusCode.PARTIAL),
- expected_detail: int | None = None,
- expected_state_hash16: int | None = None,
- required_result_flags: int = 0,
- allowed_result_flags: int = 0,
- allow_boot_preamble: bool = False,
- ) -> CommandResult:
- if required_result_flags & ~allowed_result_flags:
- raise ValueError("required result flags must be included in allowed result flags")
- result, _ = self._run_command_transaction(
- request,
- expected_command=expected_command,
- expected_followup=expected_followup,
- allowed_statuses=allowed_statuses,
- expected_detail=expected_detail,
- expected_state_hash16=expected_state_hash16,
- required_result_flags=required_result_flags,
- allowed_result_flags=allowed_result_flags,
- allow_boot_preamble=allow_boot_preamble,
- )
- return result
- def motor_status(self) -> MotorStatusResult:
- result, status = self._run_command_transaction(
- build_get_motor_status(),
- expected_command=0x37,
- expected_followup=FrameType.MOTION_STATUS,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0,
- expected_state_hash16=None,
- required_result_flags=0x08,
- allowed_result_flags=0x08,
- allow_boot_preamble=False,
- followup_decoder=decode_motion_status,
- followup_name="MOTION_STATUS",
- )
- return MotorStatusResult(
- ack=result.ack,
- status=status,
- raw_response=result.raw_response,
- )
- def _bounded_int(minimum: int, maximum: int) -> Callable[[str], int]:
- def parse(value: str) -> int:
- try:
- parsed = int(value, 10)
- except ValueError as exc:
- raise argparse.ArgumentTypeError("must be an integer") from exc
- if not minimum <= parsed <= maximum:
- raise argparse.ArgumentTypeError(f"must be from {minimum} to {maximum}")
- return parsed
- return parse
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- sub = parser.add_subparsers(dest="command", required=True)
- sub.add_parser("selftest")
- sub.add_parser("preflight")
- snapshot = sub.add_parser(
- "set-all-outputs",
- description=(
- "Sets synchronous outputs and always sends X/Y/Z motor targets; X/Y default 0 "
- "requests CLOSED and may start motion, while Z 0/100 is an accepted no-op."
- ),
- )
- snapshot.add_argument("--ptc", type=_bounded_int(0, 100), default=0)
- snapshot.add_argument("--fan", type=_bounded_int(0, 100), default=30)
- snapshot.add_argument("--solenoid", type=_bounded_int(0, 100), choices=(0, 100), default=0)
- snapshot.add_argument("--x", type=_bounded_int(0, 100), choices=(0, 100), default=0)
- snapshot.add_argument("--y", type=_bounded_int(0, 100), choices=(0, 100), default=0)
- snapshot.add_argument("--z", type=_bounded_int(0, 100), choices=(0, 100), default=0)
- jog = sub.add_parser("jog")
- jog.add_argument("--axis", type=_bounded_int(0, 2), required=True)
- jog.add_argument("--raw-dir", type=_bounded_int(0, 1), required=True)
- jog.add_argument("--speed-code", type=_bounded_int(0, 3), required=True)
- jog.add_argument("--steps", type=_bounded_int(1, 65535), required=True)
- mark = sub.add_parser("mark-closed")
- mark.add_argument("--axis", type=_bounded_int(0, 1), required=True)
- mark.add_argument("--close-dir", type=_bounded_int(0, 1), required=True)
- sub.add_parser("get-status")
- sub.add_parser("motor-status")
- sub.add_parser("disable")
- gate = sub.add_parser("normal-actuator-trace-gate")
- gate.add_argument("--bitstream", type=Path, required=True)
- gate.add_argument("--build-info", type=Path, required=True)
- gate.add_argument("--td-receipt", type=Path, required=True)
- gate.add_argument("--package-info", type=Path, required=True)
- gate.add_argument("--output-dir", type=Path, required=True)
- gate.add_argument("--board-id", required=True)
- gate.add_argument("--confirm-ptc-load-disabled", action="store_true")
- gate.add_argument("--confirm-mechanical-travel-safe", action="store_true")
- gate.add_argument("--confirm-p5-active-high-closes-intake", action="store_true")
- gate.add_argument("--confirm-ls1-x-closed-high", action="store_true")
- gate.add_argument("--confirm-ls2-y-closed-high", action="store_true")
- gate.add_argument("--x-close-dir", type=_bounded_int(0, 1), required=True)
- gate.add_argument("--y-close-dir", type=_bounded_int(0, 1), required=True)
- gate.add_argument("--td-root", type=Path, default=DEFAULT_TD_ROOT)
- gate.add_argument("--run-id", default="prod2u-p4-normal-v3-gate")
- return parser
- def _selftest() -> dict[str, Any]:
- snapshot = build_output_snapshot(
- ptc_percent=(0,) * 24,
- fan_percent=(30,) * 4,
- solenoid=0,
- xyz=(0, 0, 0),
- )
- return {
- "schema": "prod2u-p4-normal-v3-selftest-v1",
- "status": "pass" if len(snapshot) == 50 else "fail",
- "profile": PROFILE,
- "profile_id": PROFILE_ID,
- "protocol_version": PROTOCOL_VERSION,
- "baud": BAUD,
- "port": PORT,
- "hardware_opened": False,
- "program_sram_attempted": False,
- }
- def hardware_stage_plan() -> dict[str, Any]:
- return {
- "stages": [
- "preflight",
- "program_sram",
- "initial_disable",
- "boot_identity",
- "baseline_status",
- "direction_mapping",
- "limit_jog",
- "open_to_close",
- "standard_motion",
- "xy_partial",
- "watchdog",
- "trace_integrity",
- "register_checkpoint",
- "final_disable",
- ]
- }
- def enumerate_hardware_candidates(
- *,
- runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
- ) -> dict[str, Any]:
- """Enumerate COM and AL-Link candidates without opening either interface."""
- script = r"""
- $ErrorActionPreference = 'Stop'
- $cimSerialPorts = @()
- try {
- $cimSerialPorts = @(
- Get-CimInstance Win32_SerialPort |
- Sort-Object DeviceID |
- ForEach-Object {
- [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
- }
- )
- } catch {}
- $pnpSerialPorts = @()
- try {
- if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) {
- $pnpSerialPorts = @(
- Get-PnpDevice -Class Ports -PresentOnly -ErrorAction Stop |
- Sort-Object InstanceId |
- ForEach-Object {
- [ordered]@{ name = [string]$_.FriendlyName; device_id = [string]$_.InstanceId }
- }
- )
- }
- } catch {}
- $dotNetSerialPorts = @()
- try {
- $dotNetSerialPorts = @(
- [System.IO.Ports.SerialPort]::GetPortNames() |
- Sort-Object |
- ForEach-Object {
- [ordered]@{ name = [string]$_; device_id = [string]$_ }
- }
- )
- } catch {}
- $serialPorts = @($cimSerialPorts) + @($pnpSerialPorts) + @($dotNetSerialPorts)
- $pnpDevices = @()
- try {
- $pnpDevices = @(
- Get-CimInstance Win32_PnPEntity |
- Where-Object { ([string]$_.Name) -match '(?i)AL[- ]?Link|Anlogic' } |
- Sort-Object DeviceID |
- ForEach-Object {
- [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
- }
- )
- } catch {}
- [ordered]@{ serial_ports = @($serialPorts); pnp_devices = @($pnpDevices) } |
- ConvertTo-Json -Compress -Depth 4
- """.strip()
- try:
- completed = runner(
- ["powershell.exe", "-NoProfile", "-Command", script],
- capture_output=True,
- text=True,
- check=False,
- timeout=20,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- return {
- "status": "blocked_hardware_enumeration_failed",
- "opened_com": False,
- "opened_jtag": False,
- "serial_ports": [],
- "pnp_devices": [],
- "error": str(exc),
- }
- if completed.returncode != 0:
- return {
- "status": "blocked_hardware_enumeration_failed",
- "opened_com": False,
- "opened_jtag": False,
- "serial_ports": [],
- "pnp_devices": [],
- "error": f"PowerShell enumeration exited {completed.returncode}",
- }
- try:
- payload = json.loads(completed.stdout)
- except (TypeError, json.JSONDecodeError) as exc:
- return {
- "status": "blocked_hardware_enumeration_failed",
- "opened_com": False,
- "opened_jtag": False,
- "serial_ports": [],
- "pnp_devices": [],
- "error": f"invalid enumeration JSON: {exc}",
- }
- def records(name: str) -> list[dict[str, str]]:
- raw = payload.get(name, []) if isinstance(payload, dict) else []
- if isinstance(raw, dict):
- raw = [raw]
- if not isinstance(raw, list):
- return []
- return [
- {"name": str(item.get("name", "")), "device_id": str(item.get("device_id", ""))}
- for item in raw
- if isinstance(item, dict)
- ]
- serial_ports = records("serial_ports")
- serial_key_order: list[tuple[str, ...]] = []
- best_serial_record: dict[tuple[str, ...], dict[str, str]] = {}
- def serial_record_score(record: dict[str, str]) -> tuple[int, int, int]:
- name = record["name"].strip()
- device_id = record["device_id"].strip()
- generic_name = re.fullmatch(r"COM[0-9]+", name, re.IGNORECASE) is not None
- generic_device = re.fullmatch(r"COM[0-9]+", device_id, re.IGNORECASE) is not None
- return (
- 0 if generic_device else 1,
- 0 if generic_name else 1,
- len(name) + len(device_id),
- )
- for record in serial_ports:
- combined = f"{record['name']} {record['device_id']}"
- match = re.search(r"(?<![A-Z0-9])COM([0-9]+)(?![0-9])", combined.upper())
- key = ("com", str(int(match.group(1)))) if match else (
- "record",
- record["name"].casefold(),
- record["device_id"].casefold(),
- )
- if key not in best_serial_record:
- serial_key_order.append(key)
- best_serial_record[key] = record
- elif serial_record_score(record) > serial_record_score(best_serial_record[key]):
- best_serial_record[key] = record
- deduplicated_serial_ports = [best_serial_record[key] for key in serial_key_order]
- return {
- "status": "pass",
- "opened_com": False,
- "opened_jtag": False,
- "dtr_rts_toggled": False,
- "serial_ports": deduplicated_serial_ports,
- "pnp_devices": records("pnp_devices"),
- }
- def _record_text(record: Any) -> str:
- if not isinstance(record, dict):
- return ""
- return " ".join(str(record.get(field, "")) for field in ("name", "device_id"))
- def run_preflight(
- *,
- enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
- ) -> dict[str, Any]:
- try:
- enumeration = enumerator()
- except Exception as exc:
- enumeration = {
- "status": "blocked_hardware_enumeration_failed",
- "opened_com": False,
- "opened_jtag": False,
- "serial_ports": [],
- "pnp_devices": [],
- "error": str(exc),
- }
- serial_ports = enumeration.get("serial_ports", []) if isinstance(enumeration, dict) else []
- pnp_devices = enumeration.get("pnp_devices", []) if isinstance(enumeration, dict) else []
- if not isinstance(serial_ports, list):
- serial_ports = []
- if not isinstance(pnp_devices, list):
- pnp_devices = []
- com5_present = any(
- re.search(r"(?<![A-Z0-9])COM5(?![0-9])", _record_text(record).upper())
- for record in serial_ports
- )
- al_link_present = any(
- any(
- marker in re.sub(r"[^a-z0-9]", "", _record_text(record).casefold())
- for marker in ("allink", "anlogic")
- )
- for record in pnp_devices
- )
- opened_com = enumeration.get("opened_com") is True
- opened_jtag = enumeration.get("opened_jtag") is True
- dtr_rts_toggled = enumeration.get("dtr_rts_toggled") is True
- failures: list[str] = []
- if enumeration.get("status") != "pass":
- failures.append("hardware_enumeration_failed")
- if opened_com:
- failures.append("enumerator_opened_com")
- if opened_jtag:
- failures.append("enumerator_opened_jtag")
- if dtr_rts_toggled:
- failures.append("enumerator_toggled_dtr_rts")
- if not com5_present:
- failures.append("com5_not_found")
- if not al_link_present:
- failures.append("al_link_not_found")
- return {
- "schema": "prod2u-p4-normal-v3-preflight-v2",
- "status": "pass" if not failures else "blocked_hardware_not_ready",
- "serial": {
- "port": PORT,
- "baud": BAUD,
- "format": "8N1",
- "com5_present": com5_present,
- "ports": serial_ports,
- "opened": opened_com,
- "dtr_rts_toggled": dtr_rts_toggled,
- },
- "jtag": {
- "adapter": "AL-Link",
- "speed_hz": 200000,
- "al_link_present": al_link_present,
- "devices": pnp_devices,
- "opened": opened_jtag,
- },
- "hardware_opened": opened_com or opened_jtag,
- "program_sram_attempted": False,
- "failures": sorted(set(failures)),
- }
- def _program_input_failures(
- args: argparse.Namespace,
- ) -> tuple[list[str], dict[str, Any] | None]:
- failures: list[str] = []
- bitstream = Path(args.bitstream)
- build_info_path = Path(args.build_info)
- build_info: dict[str, Any] | None = None
- try:
- payload = json.loads(build_info_path.read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError):
- failures.append("build_info_unreadable")
- else:
- if not isinstance(payload, dict):
- failures.append("build_info_not_object")
- else:
- build_info = payload
- failures.extend(validate_build_info(build_info)["failures"])
- failures.extend(verify_bitstream(bitstream=bitstream, build_info=build_info)["failures"])
- output_dir = Path(args.output_dir)
- if output_dir.exists() and (not output_dir.is_dir() or any(output_dir.iterdir())):
- failures.append("output_dir_not_empty")
- if not str(getattr(args, "run_id", "")).strip():
- failures.append("run_id_missing")
- if not BOARD_ID_RE.fullmatch(str(getattr(args, "board_id", ""))):
- failures.append("board_id_invalid")
- return sorted(set(failures)), build_info
- def _sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with Path(path).open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def _load_json_object(path: Path, *, label: str, failures: list[str]) -> dict[str, Any] | None:
- try:
- payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError):
- failures.append(f"{label}_unreadable")
- return None
- if not isinstance(payload, dict):
- failures.append(f"{label}_not_object")
- return None
- return payload
- def _gate_evidence_input_failures(
- args: argparse.Namespace,
- *,
- build_info: Mapping[str, Any] | None,
- ) -> tuple[list[str], dict[str, Any] | None, dict[str, Any] | None]:
- failures: list[str] = []
- td_path = Path(args.td_receipt)
- package_path = Path(args.package_info)
- td = _load_json_object(td_path, label="td_receipt", failures=failures)
- package = _load_json_object(package_path, label="package_info", failures=failures)
- if build_info is None or td is None or package is None:
- return sorted(set(failures)), package, td
- if set(package) != {
- "schema",
- "profile",
- "commit",
- "build_id",
- "build_info_sha256",
- "bitstream_sha256",
- "td_receipt_sha256",
- "file_sha256",
- }:
- failures.append("package_info_fields_mismatch")
- if package.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v1":
- failures.append("package_info_schema_mismatch")
- if package.get("profile") != PROFILE:
- failures.append("package_profile_mismatch")
- commit = package.get("commit")
- if not isinstance(commit, str) or not COMMIT_RE.fullmatch(commit):
- failures.append("package_commit_invalid")
- if package.get("build_id") != build_info.get("build_id"):
- failures.append("package_build_id_mismatch")
- if package.get("build_info_sha256") != _sha256_file(Path(args.build_info)):
- failures.append("package_build_info_sha256_mismatch")
- if package.get("bitstream_sha256") != build_info.get("bitstream_sha256"):
- failures.append("package_bitstream_sha256_mismatch")
- if package.get("td_receipt_sha256") != _sha256_file(td_path):
- failures.append("package_td_receipt_sha256_mismatch")
- if td.get("status") != "pass":
- failures.append("td_receipt_not_pass")
- if td.get("commit") != commit:
- failures.append("td_receipt_commit_mismatch")
- if td.get("build_id") != build_info.get("build_id"):
- failures.append("td_receipt_build_id_mismatch")
- if td.get("bitstream_sha256") != build_info.get("bitstream_sha256"):
- failures.append("td_receipt_bitstream_sha256_mismatch")
- file_sha256 = package.get("file_sha256")
- if not isinstance(file_sha256, dict) or any(
- not isinstance(relative, str)
- or not isinstance(digest, str)
- or not SHA256_RE.fullmatch(digest)
- for relative, digest in (file_sha256.items() if isinstance(file_sha256, dict) else ())
- ):
- failures.append("package_file_sha256_invalid")
- else:
- root = package_path.resolve().parent
- observed: dict[str, str] = {}
- for path in sorted(candidate for candidate in root.rglob("*") if candidate.is_file()):
- if path.resolve() == package_path.resolve():
- continue
- relative = path.resolve().relative_to(root).as_posix()
- observed[relative] = _sha256_file(path)
- if set(file_sha256) != set(observed):
- failures.append("package_file_sha256_paths_mismatch")
- for relative in sorted(set(file_sha256) & set(observed)):
- if file_sha256[relative] != observed[relative]:
- failures.append(f"package_file_sha256_mismatch:{relative}")
- for label, path in (
- ("bitstream", Path(args.bitstream)),
- ("build_info", Path(args.build_info)),
- ("td_receipt", td_path),
- ):
- if not path.is_file():
- failures.append(f"package_{label}_missing")
- continue
- try:
- relative = path.resolve().relative_to(root).as_posix()
- except ValueError:
- failures.append(f"package_{label}_outside_root")
- else:
- if file_sha256.get(relative) != _sha256_file(path):
- failures.append(f"package_{label}_not_bound")
- return sorted(set(failures)), package, td
- def _program_receipt_failures(
- receipt: Any,
- *,
- build_id: str,
- expected_sha256: str,
- ) -> list[str]:
- if not isinstance(receipt, dict):
- return ["programmer_receipt_not_object"]
- failures: list[str] = []
- request = receipt.get("request") if isinstance(receipt.get("request"), dict) else {}
- execution = receipt.get("execution") if isinstance(receipt.get("execution"), dict) else {}
- safety = receipt.get("safety") if isinstance(receipt.get("safety"), dict) else {}
- bitstream = receipt.get("bitstream") if isinstance(receipt.get("bitstream"), dict) else {}
- expected_request = {
- "operation": "PROGRAM_SRAM",
- "target_chip": "EF2L45",
- "cable_index": 0,
- "speed_code": 2,
- "speed_hz": 200000,
- "attempt_limit": 1,
- "power_cycle_allowed": False,
- }
- for field, expected in expected_request.items():
- if request.get(field) != expected:
- failures.append(f"programmer_request_mismatch:{field}")
- expected_execution = {
- "attempt_count": 1,
- "retry_count": 0,
- "power_cycle_count": 0,
- "command_execution_attempted": True,
- }
- for field, expected in expected_execution.items():
- if execution.get(field) != expected:
- failures.append(f"programmer_execution_mismatch:{field}")
- for field in (
- "flash_attempted",
- "programs_nonvolatile",
- "power_cycle_attempted",
- "driver_install_attempted",
- "toggles_dtr_rts",
- ):
- if safety.get(field) is not False:
- failures.append(f"programmer_safety_not_false:{field}")
- if str(bitstream.get("build_id", "")).upper() != build_id:
- failures.append("programmer_build_id_mismatch")
- if str(bitstream.get("sha256", "")).casefold() != expected_sha256:
- failures.append("programmer_bitstream_sha256_mismatch")
- if receipt.get("status") != "pass":
- failures.append("programmer_receipt_not_pass")
- return sorted(set(failures))
- PROGRAMMER_METADATA_CONTRACT: dict[str, object] = {
- "operation": "PROGRAM_SRAM",
- "speed_hz": 200000,
- "program_sram_attempted": True,
- "attempt_count": 1,
- "retry_count": 0,
- "flash_attempted": False,
- }
- def _program_receipt_metadata(receipt: object) -> dict[str, object]:
- if not isinstance(receipt, Mapping):
- return {field: None for field in PROGRAMMER_METADATA_CONTRACT}
- request = receipt.get("request") if isinstance(receipt.get("request"), Mapping) else {}
- execution = receipt.get("execution") if isinstance(receipt.get("execution"), Mapping) else {}
- safety = receipt.get("safety") if isinstance(receipt.get("safety"), Mapping) else {}
- return {
- "operation": request.get("operation"),
- "speed_hz": request.get("speed_hz"),
- "program_sram_attempted": execution.get("command_execution_attempted"),
- "attempt_count": execution.get("attempt_count"),
- "retry_count": execution.get("retry_count"),
- "flash_attempted": safety.get("flash_attempted"),
- }
- def _programmer_metadata_failures(result: Mapping[str, Any]) -> list[str]:
- failures: list[str] = []
- for field, expected in PROGRAMMER_METADATA_CONTRACT.items():
- observed = result.get(field)
- if type(observed) is not type(expected) or observed != expected:
- failures.append(f"programmer_metadata_mismatch:{field}")
- return failures
- def run_program_only(
- args: argparse.Namespace,
- *,
- programmer: Callable[..., dict[str, Any]] = execute_program_sram,
- ) -> dict[str, Any]:
- """Validate build-info and invoke PROGRAM_SRAM exactly once without COM5."""
- failures, build_info = _program_input_failures(args)
- if failures:
- return {
- "schema": "prod2u-p4-normal-v3-program-only-v2",
- "status": "fail_preflight",
- "failures": failures,
- "program_sram_attempted": False,
- "attempt_count": 0,
- "retry_count": 0,
- "serial_opened": False,
- "flash_attempted": False,
- }
- assert build_info is not None
- build_id = str(build_info["build_id"])
- expected_sha256 = str(build_info["bitstream_sha256"])
- try:
- receipt = programmer(
- source_bitstream=Path(args.bitstream),
- expected_bitstream_sha256=expected_sha256,
- build_id=build_id,
- output_dir=Path(args.output_dir),
- td_root=Path(args.td_root),
- run_id=str(args.run_id),
- )
- except Exception as exc:
- return {
- "schema": "prod2u-p4-normal-v3-program-only-v2",
- "status": "fail_programmer_exception",
- "error_type": type(exc).__name__,
- "error": str(exc),
- "failures": ["programmer_exception"],
- "program_sram_attempted": True,
- "attempt_count": 1,
- "retry_count": 0,
- "serial_opened": False,
- "flash_attempted": False,
- "build_id": build_id,
- "bitstream_sha256": expected_sha256,
- }
- failures = _program_receipt_failures(
- receipt,
- build_id=build_id,
- expected_sha256=expected_sha256,
- )
- safety = receipt.get("safety") if isinstance(receipt, dict) and isinstance(receipt.get("safety"), dict) else {}
- metadata = _program_receipt_metadata(receipt)
- failures = sorted(set(failures + _programmer_metadata_failures(metadata)))
- return {
- "schema": "prod2u-p4-normal-v3-program-only-v2",
- "status": "pass" if not failures else "fail_programmer_contract",
- "failures": failures,
- **metadata,
- "serial_opened": False,
- "programs_nonvolatile": safety.get("programs_nonvolatile") is not False,
- "build_id": build_id,
- "bitstream_sha256": expected_sha256,
- }
- def _console_operator_observer(stage: str, context: dict[str, Any]) -> dict[str, Any]:
- if not sys.stdin.isatty():
- return {"status": "fail", "stage": stage, "reason": "operator_console_not_interactive"}
- print(json.dumps({"operator_observation_required": stage, "context": context}, ensure_ascii=False))
- answer = input(f"观察完成后输入 CONFIRM {stage}: ").strip()
- confirmations: dict[str, bool] = {}
- for field in context.get("required_confirmations", []):
- field_answer = input(f"输入 CONFIRM {stage} {field}: ").strip()
- confirmations[str(field)] = field_answer == f"CONFIRM {stage} {field}"
- return {
- "status": "pass" if answer == f"CONFIRM {stage}" else "fail",
- "stage": stage,
- "observed_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
- "confirmations": confirmations,
- }
- def _confirm_operator_observation(
- observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
- observations: list[dict[str, Any]],
- *,
- stage: str,
- context: dict[str, Any],
- required_confirmations: tuple[str, ...] = (),
- ) -> dict[str, Any]:
- if observer is None:
- raise RuntimeError(f"operator observer missing for {stage}")
- observer_context = {**context, "required_confirmations": list(required_confirmations)}
- response = observer(stage, observer_context)
- if not isinstance(response, Mapping) or response.get("status") != "pass" or response.get("stage") != stage:
- raise RuntimeError(f"operator observation rejected for {stage}")
- observed_at = response.get("observed_at")
- if not isinstance(observed_at, str) or not observed_at.endswith("Z"):
- raise RuntimeError(f"operator observation timestamp invalid for {stage}")
- confirmations = response.get("confirmations") if isinstance(response.get("confirmations"), Mapping) else {}
- for field in required_confirmations:
- if confirmations.get(field) is not True:
- raise RuntimeError(f"operator confirmation missing for {stage}:{field}")
- recorded = {
- "stage": stage,
- "context": observer_context,
- "observed_at": observed_at,
- "confirmations": {str(key): value is True for key, value in confirmations.items()},
- }
- observations.append(recorded)
- return recorded
- def _confirm_operator_observation_from_disabled(
- session: NormalSession,
- events: list[dict[str, Any]],
- observations: list[dict[str, Any]],
- *,
- observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
- stage: str,
- context: dict[str, Any],
- required_confirmations: tuple[str, ...] = (),
- ) -> dict[str, Any]:
- _gate_safe_disable(session, events, phase=f"{stage}-pre-observation-disable")
- try:
- return _confirm_operator_observation(
- observer,
- observations,
- stage=stage,
- context=context,
- required_confirmations=required_confirmations,
- )
- except BaseException:
- session.disable_attempted = True
- raise
- def _gate_result(
- *,
- status: str,
- args: argparse.Namespace,
- failures: list[str],
- hardware_enumerated: bool,
- serial_opened: bool,
- program_sram_attempted: object,
- attempt_count: object,
- retry_count: object,
- flash_attempted: object = False,
- operation: object = None,
- speed_hz: object = None,
- ) -> dict[str, Any]:
- return {
- "schema": "prod2u-p4-normal-v3-gate-launch-v2",
- "status": status,
- "profile": PROFILE,
- "bitstream": str(Path(args.bitstream)),
- "output_dir": str(Path(args.output_dir)),
- "failures": list(dict.fromkeys(failures)),
- "hardware_enumerated": hardware_enumerated,
- "serial_opened": serial_opened,
- "program_sram_attempted": program_sram_attempted,
- "operation": operation,
- "speed_hz": speed_hz,
- "attempt_count": attempt_count,
- "retry_count": retry_count,
- "flash_attempted": flash_attempted,
- "authority_boundary": (
- "The gate performs at most one PROGRAM_SRAM attempt and never programs flash. "
- "Trace, motion, watchdog and final DISABLE evidence are required for acceptance."
- ),
- }
- def _build_hardware_session_receipt(
- *,
- board_id: str,
- commit: str,
- build_id: str,
- artifacts: Mapping[str, Any],
- programmer_metadata: Mapping[str, Any],
- trace: Mapping[str, Any],
- wire_order: Mapping[str, Any],
- axes: Mapping[str, Any],
- partial: Mapping[str, Any],
- watchdog: Mapping[str, Any],
- stages: list[Mapping[str, Any]],
- final_disable: Mapping[str, Any],
- status: str = "pass",
- failures: list[str] | None = None,
- ) -> dict[str, Any]:
- receipt = {
- "schema": "prod2u-p4-normal-v3-actuator-trace-hardware-session-v1",
- "status": status,
- "profile": PROFILE,
- "board_id": board_id,
- "commit": commit,
- "build_id": build_id,
- "artifacts": dict(artifacts),
- "serial": {"port": PORT, "baud": BAUD, "format": "8N1"},
- "jtag": {
- field: programmer_metadata[field]
- for field in PROGRAMMER_METADATA_CONTRACT
- },
- "trace": dict(trace),
- "wire_order": dict(wire_order),
- "axes": {str(key): dict(value) for key, value in axes.items()},
- "partial": dict(partial),
- "watchdog": dict(watchdog),
- "counterparty": {
- "kind": "prod2u-p4-normal-v3-board",
- "board_id": board_id,
- "uart_endpoint": PORT,
- "jtag_adapter": "AL-Link",
- },
- "stages": [dict(stage) for stage in stages],
- "final_disable": dict(final_disable),
- "prohibited_actions": {
- "flash_attempted": programmer_metadata["flash_attempted"],
- "driver_install_attempted": False,
- "ptc_heating_attempted": False,
- "retired_sensor_action_attempted": False,
- "z_motion_attempted": False,
- "limit_fault_injection_attempted": False,
- "automatic_retry_attempted": False,
- "second_program_sram_attempted": False,
- },
- "authority_boundary": (
- "This receipt proves one controlled SRAM session and the observed Normal v3 digital control "
- "path only; it does not prove mechanics, external wiring, thermal behavior, or service life."
- ),
- }
- if status == "fail":
- receipt["failures"] = list(dict.fromkeys(failures or ["unspecified_hardware_session_failure"]))
- return receipt
- def _write_json_artifact(path: Path, payload: Any) -> str:
- Path(path).write_text(
- json.dumps(payload, indent=2, ensure_ascii=False, default=lambda value: int(value)) + "\n",
- encoding="utf-8",
- newline="\n",
- )
- return _sha256_file(Path(path))
- def _trace_event_row(event: TraceEvent) -> dict[str, Any]:
- return {
- "event_seq": event.event_seq,
- "event_type": event.event_type.name,
- "source": event.source,
- "meta": event.meta,
- "data": event.data,
- "state_hash16": event.state_hash16,
- }
- def _trace_receipt_summary(events: list[TraceEvent]) -> dict[str, Any]:
- continuous = bool(events)
- for previous, current in zip(events, events[1:]):
- expected = 1 if previous.event_seq == 0xFFFFFFFF else previous.event_seq + 1
- if current.event_seq != expected:
- continuous = False
- break
- overflow = any(event.event_type == TraceEventType.OVERFLOW for event in events)
- epoch = any(event.event_type == TraceEventType.EPOCH for event in events)
- command_result = any(event.event_type == TraceEventType.COMMAND_RESULT for event in events)
- return {
- "status": "pass" if continuous and not overflow and epoch and command_result else "fail",
- "first_event_seq": events[0].event_seq if events else None,
- "last_event_seq": events[-1].event_seq if events else None,
- "event_count": len(events),
- "continuous_event_seq": continuous,
- "overflow_observed": overflow,
- "command_result_before_ack": command_result,
- "epoch_observed": epoch,
- "layout_versions": {
- "EPOCH": 1,
- "CORE_STATE": 1,
- "AXIS_STATE": 1,
- "LIMIT_STATE": 1,
- "SAFETY_STATE": 1,
- "OVERFLOW": 1,
- },
- }
- def _open_to_close_trace_pair(
- events: list[TraceEvent],
- *,
- expected_source: AxisTraceSource,
- close_dir: int,
- ) -> list[tuple[TraceEvent, Any]]:
- decoded = [
- (event, decode_axis_trace_event(event))
- for event in events
- if event.event_type == TraceEventType.AXIS_STATE
- and event.source == int(expected_source)
- ]
- reversals = [
- (index, event, evidence)
- for index, (event, evidence) in enumerate(decoded)
- if evidence.stop_reason == AxisStopReason.REVERSED_TO_CLOSE
- ]
- if len(reversals) != 1:
- raise ValueError(
- f"{expected_source.name} open-to-close requires exactly one REVERSED_TO_CLOSE terminal"
- )
- reverse_index, reverse_event, reverse_evidence = reversals[0]
- finals = [
- (event, evidence)
- for event, evidence in decoded[reverse_index + 1 :]
- if evidence.stop_reason == AxisStopReason.LIMIT_CONFIRMED
- and evidence.axis_state == 1
- ]
- if len(finals) != 1:
- raise ValueError(
- f"{expected_source.name} open-to-close requires exactly one final CLOSED/LIMIT_CONFIRMED terminal"
- )
- final_event, final_evidence = finals[0]
- if (
- reverse_evidence.axis_state != 4
- or reverse_evidence.move_kind != 1
- or not reverse_evidence.close_dir_valid
- or reverse_evidence.close_dir != close_dir
- or reverse_evidence.requested_dir == close_dir
- ):
- raise ValueError(f"{expected_source.name} REVERSED_TO_CLOSE direction/state evidence is invalid")
- if (
- final_evidence.move_kind != 1
- or not final_evidence.close_dir_valid
- or final_evidence.close_dir != close_dir
- or final_evidence.requested_dir != close_dir
- or final_evidence.live_dir != close_dir
- ):
- raise ValueError(f"{expected_source.name} final close direction/state evidence is invalid")
- return [(reverse_event, reverse_evidence), (final_event, final_evidence)]
- def _axis_evidence_from_trace(
- events: list[TraceEvent],
- *,
- axis_label: str,
- close_dir: int,
- checks: Mapping[str, bool],
- open_to_close_events: list[TraceEvent],
- ) -> dict[str, Any]:
- try:
- expected_source = AxisTraceSource[axis_label]
- except KeyError as exc:
- raise ValueError(f"unsupported axis label: {axis_label}") from exc
- if close_dir not in {0, 1}:
- raise ValueError("close_dir must be 0 or 1")
- expected_checks = {"mark_closed", "jog_away", "jog_to_limit", "standard_open_close"}
- if set(checks) != expected_checks or any(not isinstance(value, bool) for value in checks.values()):
- raise ValueError("axis checks must contain the four non-derived motion checks")
- open_to_close = _open_to_close_trace_pair(
- open_to_close_events,
- expected_source=expected_source,
- close_dir=close_dir,
- )
- decoded = [
- (event, decode_axis_trace_event(event))
- for event in events
- if event.event_type == TraceEventType.AXIS_STATE and event.source == int(expected_source)
- ]
- final_index = next(
- (
- index
- for index in range(len(decoded) - 1, -1, -1)
- if decoded[index][1].axis_state == 1
- and decoded[index][1].stop_reason == AxisStopReason.LIMIT_CONFIRMED
- ),
- None,
- )
- if final_index is None:
- raise ValueError(f"{axis_label} has no terminal CLOSED/LIMIT_CONFIRMED Trace evidence")
- selected = [decoded[final_index]]
- final_evidence = selected[-1][1]
- if final_evidence.recovery_segment:
- primary_index = next(
- (
- index
- for index in range(final_index - 1, -1, -1)
- if not decoded[index][1].recovery_segment
- ),
- None,
- )
- if primary_index is None:
- raise ValueError(f"{axis_label} recovery Trace is missing its primary segment")
- selected.insert(0, decoded[primary_index])
- final_evidence = selected[-1][1]
- if any(
- evidence.move_kind != 1
- or not evidence.close_dir_valid
- or evidence.close_dir != close_dir
- or evidence.requested_dir != close_dir
- or evidence.live_dir != close_dir
- for _, evidence in selected
- ):
- raise ValueError(f"{axis_label} standard CLOSE terminal evidence is invalid")
- if len(selected) == 1:
- if final_evidence.recovery_segment:
- raise ValueError(f"{axis_label} standard CLOSE recovery evidence is incomplete")
- else:
- primary_evidence = selected[0][1]
- if (
- len(selected) != 2
- or primary_evidence.recovery_segment
- or primary_evidence.stop_reason != AxisStopReason.REQUEST_COMPLETE
- or primary_evidence.axis_state != 6
- or not final_evidence.recovery_segment
- ):
- raise ValueError(f"{axis_label} standard CLOSE recovery evidence is invalid")
- primary = next((evidence for _, evidence in selected if not evidence.recovery_segment), None)
- requested_steps = primary.requested_steps if primary is not None else final_evidence.requested_steps
- emitted_steps = sum(evidence.completed_steps for _, evidence in selected)
- recovery_steps = sum(
- evidence.completed_steps for _, evidence in selected if evidence.recovery_segment
- )
- axis_states = (
- "UNCALIBRATED",
- "CLOSED",
- "OPENING",
- "OPEN",
- "CLOSING",
- "INTERMEDIATE",
- "RECOVERY",
- "LOCKED_FAULT",
- )
- return {
- "status": "pass",
- "axis": axis_label,
- "close_dir": close_dir,
- "limit_open_volts": 0.0,
- "limit_closed_volts": 3.3,
- "limit_active_high": True,
- "requested_steps": requested_steps,
- "emitted_steps": emitted_steps,
- "recovery_steps": recovery_steps,
- "stop_reason": final_evidence.stop_reason.name.lower(),
- "final_state": axis_states[final_evidence.axis_state],
- "trace_event_seqs": [evidence.event_seq for _, evidence in selected],
- "trace_frames_hex": [encode_trace_frame(event).hex() for event, _ in selected],
- "distance_steps": final_evidence.distance_steps,
- "distance_valid": final_evidence.distance_valid,
- "distance_saturated": final_evidence.distance_saturated,
- "layout_version": 1,
- "open_to_close_trace_event_seqs": [
- evidence.event_seq for _, evidence in open_to_close
- ],
- "open_to_close_trace_frames_hex": [
- encode_trace_frame(event).hex() for event, _ in open_to_close
- ],
- "checks": {**dict(checks), "open_to_close": len(open_to_close) == 2},
- }
- def _finalize_hardware_session_receipt(
- *,
- output_dir: Path,
- board_id: str,
- commit: str,
- build_id: str,
- build_info_path: Path,
- bitstream_path: Path,
- td_receipt_path: Path,
- programmer_metadata: Mapping[str, Any],
- serial_events: list[Mapping[str, Any]],
- trace_events: list[TraceEvent],
- register_checkpoint: Mapping[str, Any],
- axes: Mapping[str, Any],
- partial: Mapping[str, Any],
- watchdog: Mapping[str, Any],
- stages: list[Mapping[str, Any]],
- final_disable: Mapping[str, Any],
- ) -> dict[str, Any]:
- output_dir = Path(output_dir)
- serial_path = output_dir / "serial-transcript.json"
- trace_path = output_dir / "trace-events.json"
- register_path = output_dir / "register-checkpoint.json"
- serial_payload = {"events": [dict(row) for row in serial_events]}
- serial_sha256 = _write_json_artifact(serial_path, serial_payload)
- wire_replay = replay_serial_transcript_events(
- serial_payload["events"],
- require_startup_epoch=True,
- )
- if wire_replay.get("status") != "pass":
- raise ValueError(f"serial transcript replay failed: {wire_replay.get('failures', [])}")
- wire_order = {
- key: wire_replay[key]
- for key in (
- "status",
- "command_count",
- "trace_event_count",
- "first_event_seq",
- "last_event_seq",
- "commands",
- )
- }
- wire_order["serial_transcript_sha256"] = serial_sha256
- trace_sha256 = _write_json_artifact(
- trace_path,
- {"events": [_trace_event_row(event) for event in trace_events]},
- )
- register_sha256 = _write_json_artifact(register_path, dict(register_checkpoint))
- trace_summary = _trace_receipt_summary(trace_events)
- trace_summary["command_result_before_ack"] = wire_order["status"] == "pass"
- receipt = _build_hardware_session_receipt(
- board_id=board_id,
- commit=commit,
- build_id=build_id,
- artifacts={
- "build_info_sha256": _sha256_file(Path(build_info_path)),
- "bitstream_sha256": _sha256_file(Path(bitstream_path)),
- "td_receipt_sha256": _sha256_file(Path(td_receipt_path)),
- "serial_transcript_sha256": serial_sha256,
- "trace_sha256": trace_sha256,
- "register_checkpoint_sha256": register_sha256,
- },
- programmer_metadata=programmer_metadata,
- trace=trace_summary,
- wire_order=wire_order,
- axes=axes,
- partial=partial,
- watchdog=watchdog,
- stages=stages,
- final_disable=final_disable,
- )
- receipt_path = output_dir / "hardware-session-receipt.json"
- candidate_path = output_dir / "hardware-session-receipt.candidate.json"
- _write_json_artifact(candidate_path, receipt)
- validation = validate_session_receipt(candidate_path)
- if validation.get("status") != "pass":
- candidate_path.unlink(missing_ok=True)
- raise ValueError(f"hardware session receipt invalid: {validation.get('failures', [])}")
- candidate_path.replace(receipt_path)
- return receipt
- def _not_run_axis_evidence(axis: str, close_dir: int | None) -> dict[str, Any]:
- return {
- "status": "not_run",
- "axis": axis,
- "close_dir": close_dir,
- "limit_open_volts": None,
- "limit_closed_volts": None,
- "limit_active_high": True,
- "requested_steps": 0,
- "emitted_steps": 0,
- "recovery_steps": 0,
- "stop_reason": "not_run",
- "final_state": "UNKNOWN",
- "trace_event_seqs": [],
- "trace_frames_hex": [],
- "distance_steps": 0,
- "distance_valid": False,
- "distance_saturated": False,
- "layout_version": 1,
- "open_to_close_trace_event_seqs": [],
- "open_to_close_trace_frames_hex": [],
- "checks": {
- "mark_closed": False,
- "jog_away": False,
- "jog_to_limit": False,
- "standard_open_close": False,
- "open_to_close": False,
- },
- }
- def _append_last_exchange(
- events: list[dict[str, Any]],
- session: NormalSession,
- *,
- phase: str,
- ) -> None:
- exchange = session.last_exchange
- if exchange is None or (
- not exchange.get("request_hex") and not exchange.get("response_hex")
- ):
- return
- if any(
- row.get("request_hex") == exchange.get("request_hex")
- and row.get("response_hex") == exchange.get("response_hex")
- for row in events
- ):
- return
- events.append({"phase": phase, **exchange})
- def _append_best_effort_disable(
- events: list[dict[str, Any]],
- session: NormalSession,
- *,
- phase: str,
- ) -> None:
- exchange = session.best_effort_disable_exchange
- if exchange is None:
- return
- if any(
- row.get("request_hex") == exchange.get("request_hex")
- and row.get("response_hex") == exchange.get("response_hex")
- for row in events
- ):
- return
- events.append({"phase": phase, **exchange})
- def _complete_failure_stages(
- stages: list[Mapping[str, Any]],
- *,
- reason: str,
- ) -> list[dict[str, Any]]:
- completed = [dict(stage) for stage in stages]
- names = {str(stage.get("name")) for stage in completed}
- failure_assigned = any(stage.get("status") == "fail" for stage in completed)
- for name in hardware_stage_plan()["stages"]:
- if name in names:
- continue
- if not failure_assigned:
- completed.append(_stage(name, status="fail", reason=reason))
- failure_assigned = True
- else:
- completed.append(_stage(name, status="not_run", reason="blocked_by_prior_failure"))
- return completed
- def _finalize_failed_hardware_session_receipt(
- *,
- output_dir: Path,
- board_id: str,
- commit: str,
- build_id: str,
- build_info_path: Path,
- bitstream_path: Path,
- td_receipt_path: Path,
- programmer_metadata: Mapping[str, Any],
- serial_events: list[Mapping[str, Any]],
- rx_journal: bytes,
- trace_events: list[TraceEvent],
- stages: list[Mapping[str, Any]],
- failure_reasons: list[str],
- final_disable: Mapping[str, Any],
- x_close_dir: int | None,
- y_close_dir: int | None,
- ) -> dict[str, Any]:
- output_dir = Path(output_dir)
- serial_path = output_dir / "serial-transcript.json"
- trace_path = output_dir / "trace-events.json"
- register_path = output_dir / "register-checkpoint.json"
- serial_payload = {
- "events": [dict(row) for row in serial_events],
- "rx_journal_hex": bytes(rx_journal).hex(),
- "rx_byte_count": len(rx_journal),
- }
- serial_sha256 = _write_json_artifact(serial_path, serial_payload)
- wire_replay = replay_serial_transcript_events(
- serial_payload["events"],
- require_startup_epoch=True,
- expected_build_id=int(build_id, 16),
- expected_capability_flags=CAPABILITY_FLAGS,
- )
- declared_failures = list(
- dict.fromkeys(
- [*failure_reasons, *[str(value) for value in wire_replay.get("failures", [])]]
- )
- )
- wire_order = {
- key: wire_replay[key]
- for key in (
- "status",
- "command_count",
- "trace_event_count",
- "first_event_seq",
- "last_event_seq",
- "commands",
- )
- }
- wire_order["serial_transcript_sha256"] = serial_sha256
- trace_sha256 = _write_json_artifact(
- trace_path,
- {"events": [_trace_event_row(event) for event in trace_events]},
- )
- register_sha256 = _write_json_artifact(
- register_path,
- {
- "status": "not_run",
- "reason": "host_uart_failure",
- "last_rx_byte_count": len(rx_journal),
- },
- )
- trace_summary = _trace_receipt_summary(trace_events)
- trace_summary["command_result_before_ack"] = wire_replay.get("status") == "pass"
- receipt = _build_hardware_session_receipt(
- board_id=board_id,
- commit=commit,
- build_id=build_id,
- artifacts={
- "build_info_sha256": _sha256_file(Path(build_info_path)),
- "bitstream_sha256": _sha256_file(Path(bitstream_path)),
- "td_receipt_sha256": _sha256_file(Path(td_receipt_path)),
- "serial_transcript_sha256": serial_sha256,
- "trace_sha256": trace_sha256,
- "register_checkpoint_sha256": register_sha256,
- },
- programmer_metadata=programmer_metadata,
- trace=trace_summary,
- wire_order=wire_order,
- axes={
- "x": _not_run_axis_evidence("X", x_close_dir),
- "y": _not_run_axis_evidence("Y", y_close_dir),
- },
- partial={"status": "not_run", "scenarios": []},
- watchdog={"status": "not_run", "timeout_ms": 5000, "timeline": []},
- stages=stages,
- final_disable=final_disable,
- status="fail",
- failures=declared_failures,
- )
- receipt_path = output_dir / "hardware-session-receipt.json"
- candidate_path = output_dir / "hardware-session-receipt.candidate.json"
- _write_json_artifact(candidate_path, receipt)
- validation = validate_session_receipt(candidate_path)
- if validation.get("status") != "pass":
- candidate_path.unlink(missing_ok=True)
- raise ValueError(
- f"hardware session failure receipt invalid: {validation.get('failures', [])}"
- )
- candidate_path.replace(receipt_path)
- return receipt
- def _stage(name: str, *, status: str = "pass", **details: Any) -> dict[str, Any]:
- row: dict[str, Any] = {"name": name, "status": status}
- if details:
- row["details"] = details
- return row
- def _gate_safe_disable(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- allow_boot_preamble: bool = False,
- ) -> CommandResult:
- request = build_host_command(command=CommandId.DISABLE)
- result = session.command(
- request,
- expected_command=CommandId.DISABLE,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0x01,
- expected_state_hash16=SAFE_STATE_HASH16,
- allow_boot_preamble=allow_boot_preamble,
- )
- events.append(
- {
- "phase": phase,
- "request_hex": request.hex(),
- "response_hex": result.raw_response.hex(),
- "command": "DISABLE",
- }
- )
- return result
- def _gate_status(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- ) -> CommandResult:
- request = build_host_command(command=CommandId.GET_STATUS)
- result = session.command(
- request,
- expected_command=CommandId.GET_STATUS,
- allowed_statuses=(StatusCode.OK,),
- allowed_result_flags=0,
- )
- if result.ack.detail & ~0x03:
- session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
- events.append(
- {
- "phase": phase,
- "request_hex": request.hex(),
- "response_hex": result.raw_response.hex(),
- "command": "GET_STATUS",
- "detail": result.ack.detail,
- "state_hash16": result.ack.state_hash16,
- }
- )
- return result
- def _gate_motor_status(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- ) -> MotorStatusResult:
- result = session.motor_status()
- events.append(
- {
- "phase": phase,
- "request_hex": build_get_motor_status().hex(),
- "response_hex": result.raw_response.hex(),
- "command": "GET_MOTOR_STATUS",
- "flags": result.status.flags,
- "busy_mask": result.status.busy_mask,
- "position_valid_mask": result.status.position_valid_mask,
- "current_xyz": list(result.status.current_xyz),
- "target_xyz": list(result.status.target_xyz),
- "fault_mask": result.status.fault_mask,
- }
- )
- return result
- def _gate_snapshot(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- solenoid: int,
- xyz: tuple[int, int, int],
- ) -> CommandResult:
- request = build_output_snapshot(
- ptc_percent=(0,) * 24,
- fan_percent=(30,) * 4,
- solenoid=solenoid,
- xyz=xyz,
- )
- expected_hash = state_hash16(
- ptc_percent=(0,) * 24,
- fan_percent=(30,) * 4,
- solenoid=solenoid,
- )
- result = session.command(
- request,
- expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
- expected_state_hash16=expected_hash,
- required_result_flags=0x01,
- allowed_result_flags=0x0F,
- )
- if result.ack.detail & 0xC0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
- busy_mask = result.ack.detail & 0x07
- invalid_mask = (result.ack.detail >> 3) & 0x07
- if busy_mask & invalid_mask:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
- if result.ack.status == StatusCode.OK and result.ack.detail != 0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
- if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK missing skip detail")
- accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
- expected_flags = 0x01 | (accepted_or_noop_mask << 1)
- if result.ack.result_flags != expected_flags:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
- events.append(
- {
- "phase": phase,
- "request_hex": request.hex(),
- "response_hex": result.raw_response.hex(),
- "command": "SET_OUTPUT_SNAPSHOT",
- "status": result.ack.status.name,
- "detail": result.ack.detail,
- "result_flags": result.ack.result_flags,
- "state_hash16": result.ack.state_hash16,
- }
- )
- return result
- def _gate_jog(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- axis: int,
- raw_dir: int,
- speed_code: int,
- steps: int,
- ) -> CommandResult:
- request = build_motor_jog(
- axis=axis,
- raw_dir=raw_dir,
- speed_code=speed_code,
- steps=steps,
- )
- result = session.command(
- request,
- expected_command=0x35,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0,
- )
- events.append(
- {
- "phase": phase,
- "request_hex": request.hex(),
- "response_hex": result.raw_response.hex(),
- "command": "JOG",
- "axis": axis,
- "raw_dir": raw_dir,
- "speed_code": speed_code,
- "steps": steps,
- }
- )
- return result
- def _gate_mark_closed(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- axis: int,
- close_dir: int,
- ) -> CommandResult:
- request = build_mark_closed(axis=axis, close_dir=close_dir)
- result = session.command(
- request,
- expected_command=0x36,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0,
- )
- events.append(
- {
- "phase": f"mark-closed-{axis}",
- "request_hex": request.hex(),
- "response_hex": result.raw_response.hex(),
- "command": "MARK_CLOSED",
- "axis": axis,
- "close_dir": close_dir,
- }
- )
- return result
- def _wait_for_idle(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- phase: str,
- sleep: Callable[[float], None],
- max_polls: int = 100,
- ) -> MotorStatusResult:
- for index in range(max_polls):
- result = _gate_motor_status(session, events, phase=f"{phase}-poll-{index}")
- if result.status.busy_mask == 0:
- return result
- sleep(0.1)
- raise TimeoutError(f"motor status remained busy during {phase}")
- def _latest_axis_limit_state(events: list[TraceEvent], *, axis: int) -> dict[str, bool] | None:
- if axis not in {0, 1}:
- raise ValueError("limit Trace is available only for X/Y")
- for event in reversed(events):
- if event.event_type != TraceEventType.LIMIT_STATE:
- continue
- try:
- decoded = decode_limit_trace_event(event)
- except ValueError as exc:
- raise RuntimeError(f"malformed combined LIMIT_STATE Trace: {exc}") from exc
- return {
- "fast": decoded.x_fast if axis == 0 else decoded.y_fast,
- "active": decoded.x_active if axis == 0 else decoded.y_active,
- "ready": decoded.x_ready if axis == 0 else decoded.y_ready,
- }
- return None
- def _calibrate_axis_until_limit(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- axis: int,
- raw_dir: int,
- sleep: Callable[[float], None],
- confirm_startup_high: Callable[[int, int], None] | None = None,
- ) -> MotorStatusResult:
- _gate_motor_status(session, events, phase=f"calibrate-{axis}-startup")
- limit_state = _latest_axis_limit_state(list(session.trace_events), axis=axis)
- for poll in range(100):
- if (
- limit_state is not None
- and limit_state["ready"]
- and limit_state["fast"] == limit_state["active"]
- ):
- break
- sleep(0.001)
- _gate_motor_status(session, events, phase=f"calibrate-{axis}-limit-ready-{poll}")
- limit_state = _latest_axis_limit_state(list(session.trace_events), axis=axis)
- if (
- limit_state is None
- or not limit_state["ready"]
- or limit_state["fast"] != limit_state["active"]
- ):
- raise RuntimeError(f"axis {axis} limit filter did not reach a stable confirmed level")
- if limit_state["active"]:
- if confirm_startup_high is None:
- raise RuntimeError(f"axis {axis} startup-high requires operator confirmation")
- confirm_startup_high(axis, raw_dir)
- _gate_mark_closed(session, events, axis=axis, close_dir=raw_dir)
- marked = _gate_motor_status(session, events, phase=f"calibrate-{axis}-startup-marked")
- if (
- marked.status.busy_mask != 0
- or not (marked.status.position_valid_mask & (1 << axis))
- or marked.status.current_xyz[axis] != 0
- ):
- raise RuntimeError(f"axis {axis} startup-high MARK_CLOSED did not establish CLOSED")
- return marked
- for segment in range(40):
- _gate_jog(
- session,
- events,
- phase=f"calibrate-{axis}-{segment}",
- axis=axis,
- raw_dir=raw_dir,
- speed_code=0,
- steps=80,
- )
- state = _wait_for_idle(
- session,
- events,
- phase=f"calibrate-{axis}-{segment}",
- sleep=sleep,
- )
- if state.status.position_valid_mask & (1 << axis):
- _gate_mark_closed(session, events, axis=axis, close_dir=raw_dir)
- marked = _gate_motor_status(session, events, phase=f"calibrate-{axis}-marked")
- if marked.status.busy_mask != 0 or marked.status.current_xyz[axis] != 0:
- raise RuntimeError(f"axis {axis} MARK_CLOSED did not preserve CLOSED")
- return marked
- raise RuntimeError(f"axis {axis} did not reach its limit within 3200 steps")
- def _run_xy_calibration_then_jog(
- session: NormalSession,
- events: list[dict[str, Any]],
- stages: list[dict[str, Any]],
- observations: list[dict[str, Any]],
- *,
- x_close_dir: int,
- y_close_dir: int,
- sleep: Callable[[float], None],
- operator_observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
- ) -> None:
- start = len(events)
- def confirm_startup_high(axis: int, close_dir: int) -> None:
- axis_label = "X" if axis == 0 else "Y"
- _confirm_operator_observation_from_disabled(
- session,
- events,
- observations,
- observer=operator_observer,
- stage=f"startup_high_mark_closed_{axis_label.lower()}",
- context={
- "axis": axis_label,
- "close_dir": close_dir,
- "limit_ready": True,
- "limit_active": True,
- "limit_closed_volts": 3.3,
- },
- required_confirmations=("limit_closed_high", "close_direction"),
- )
- _calibrate_axis_until_limit(
- session,
- events,
- axis=0,
- raw_dir=x_close_dir,
- sleep=sleep,
- confirm_startup_high=confirm_startup_high,
- )
- _calibrate_axis_until_limit(
- session,
- events,
- axis=1,
- raw_dir=y_close_dir,
- sleep=sleep,
- confirm_startup_high=confirm_startup_high,
- )
- calibrated = _gate_motor_status(session, events, phase="calibration-status")
- if (
- calibrated.status.position_valid_mask != 0x03
- or calibrated.status.busy_mask != 0
- or calibrated.status.current_xyz != (0, 0, 0xFF)
- ):
- raise RuntimeError("XY calibration did not establish both closed positions")
- stages.append(_stage("direction_mapping", events=_events_since(events, start)))
- start = len(events)
- for axis, close_dir, name in (
- (0, x_close_dir, "x_jog_motion"),
- (1, y_close_dir, "y_jog_motion"),
- ):
- _gate_jog(
- session,
- events,
- phase=f"jog-{axis}",
- axis=axis,
- raw_dir=1 - close_dir,
- speed_code=2,
- steps=20,
- )
- _wait_for_idle(session, events, phase=f"jog-{axis}", sleep=sleep)
- _confirm_operator_observation_from_disabled(
- session,
- events,
- observations,
- observer=operator_observer,
- stage=name,
- context={"axis": axis, "speed_step_per_s": 100, "steps": 20},
- )
- _calibrate_axis_until_limit(
- session,
- events,
- axis=axis,
- raw_dir=close_dir,
- sleep=sleep,
- )
- recalibrated = _gate_motor_status(session, events, phase="post-jog-calibration-status")
- if (
- recalibrated.status.position_valid_mask != 0x03
- or recalibrated.status.busy_mask != 0
- or recalibrated.status.current_xyz != (0, 0, 0xFF)
- ):
- raise RuntimeError("XY jog verification did not return both axes to closed positions")
- stages.append(_stage("limit_jog", events=_events_since(events, start)))
- def _run_xy_partial_scenarios(
- session: NormalSession,
- events: list[dict[str, Any]],
- stages: list[dict[str, Any]],
- *,
- sleep: Callable[[float], None],
- ) -> list[dict[str, str]]:
- start = len(events)
- def snapshot(
- phase: str,
- xyz: tuple[int, int, int],
- expected_status: StatusCode,
- expected_detail: int,
- ) -> None:
- result = _gate_snapshot(session, events, phase=phase, solenoid=0, xyz=xyz)
- if result.ack.status != expected_status or result.ack.detail != expected_detail:
- raise RuntimeError(f"{phase} did not return expected per-axis result")
- snapshot("partial-y-open", (0, 100, 0), StatusCode.OK, 0x00)
- y_open = _wait_for_idle(session, events, phase="partial-y-open", sleep=sleep)
- if y_open.status.current_xyz != (0, 100, 0xFF):
- raise RuntimeError("Y did not reach OPEN for X-accepted/Y-busy PARTIAL scenario")
- snapshot("partial-y-close", (0, 0, 0), StatusCode.OK, 0x00)
- snapshot("partial-accept-x-busy-y", (100, 100, 0), StatusCode.PARTIAL, 0x02)
- first = _gate_motor_status(session, events, phase="partial-accept-x-busy-y-status")
- if first.status.busy_mask != 0x03 or first.status.target_xyz != (100, 0, 0xFF):
- raise RuntimeError("X-accepted/Y-busy PARTIAL changed the wrong targets")
- first_idle = _wait_for_idle(
- session,
- events,
- phase="partial-accept-x-busy-y",
- sleep=sleep,
- )
- if first_idle.status.current_xyz != (100, 0, 0xFF):
- raise RuntimeError("X-accepted/Y-busy PARTIAL did not finish at the expected endpoints")
- snapshot("partial-x-close", (0, 0, 0), StatusCode.OK, 0x00)
- snapshot("partial-accept-y-busy-x", (100, 100, 0), StatusCode.PARTIAL, 0x01)
- second = _gate_motor_status(session, events, phase="partial-accept-y-busy-x-status")
- if second.status.busy_mask != 0x03 or second.status.target_xyz != (0, 100, 0xFF):
- raise RuntimeError("Y-accepted/X-busy PARTIAL changed the wrong targets")
- second_idle = _wait_for_idle(
- session,
- events,
- phase="partial-accept-y-busy-x",
- sleep=sleep,
- )
- if second_idle.status.current_xyz != (0, 100, 0xFF):
- raise RuntimeError("Y-accepted/X-busy PARTIAL did not finish at the expected endpoints")
- snapshot("partial-restore-close", (0, 0, 0), StatusCode.OK, 0x00)
- restored = _wait_for_idle(session, events, phase="partial-restore-close", sleep=sleep)
- if restored.status.current_xyz != (0, 0, 0xFF):
- raise RuntimeError("XY PARTIAL scenarios did not restore both axes to CLOSED")
- scenarios = [
- {"accepted_axis": "X", "busy_axis": "Y", "result": "PARTIAL"},
- {"accepted_axis": "Y", "busy_axis": "X", "result": "PARTIAL"},
- ]
- stages.append(_stage("xy_partial", events=_events_since(events, start), scenarios=scenarios))
- return scenarios
- def _start_watchdog_motion(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- y_close_dir: int,
- ) -> MotorStatusResult:
- _gate_jog(
- session,
- events,
- phase="watchdog-start",
- axis=1,
- raw_dir=1 - int(y_close_dir),
- speed_code=0,
- steps=160,
- )
- started = _gate_motor_status(session, events, phase="watchdog-start-status")
- if not (started.status.busy_mask & 0x02):
- raise RuntimeError("watchdog Y motion did not enter busy state")
- return started
- def _run_solenoid_pulse(
- session: NormalSession,
- events: list[dict[str, Any]],
- *,
- sleep: Callable[[float], None],
- ) -> list[CommandResult]:
- results = [
- _gate_snapshot(session, events, phase="solenoid-off-1", solenoid=0, xyz=(0, 0, 0))
- ]
- results.append(
- _gate_snapshot(session, events, phase="solenoid-on", solenoid=100, xyz=(0, 0, 0))
- )
- try:
- sleep(0.25)
- finally:
- results.append(
- _gate_snapshot(session, events, phase="solenoid-off-2", solenoid=0, xyz=(0, 0, 0))
- )
- return results
- def _run_program_with_uart_collection(
- session: NormalSession,
- *,
- programmer: Callable[[argparse.Namespace], dict[str, Any]],
- program_args: argparse.Namespace,
- ) -> dict[str, Any]:
- """Capture UART bytes with the session pump while PROGRAM_SRAM runs once."""
- result: dict[str, Any] = {}
- failure: list[BaseException] = []
- session.start_reader(
- persistent=True,
- capture_only=True,
- allow_startup_preamble=True,
- )
- def run_programmer() -> None:
- try:
- value = programmer(program_args)
- if not isinstance(value, dict):
- raise TypeError("PROGRAM_SRAM runner must return an object")
- result.update(value)
- except BaseException as exc: # Preserve the programmer's original exception in the caller.
- failure.append(exc)
- worker = threading.Thread(
- target=run_programmer,
- name="prod2u-program-sram",
- daemon=True,
- )
- worker.start()
- while worker.is_alive():
- worker.join(timeout=0.001)
- if failure:
- raise failure[0]
- if session.reader_error is not None:
- raise RuntimeError(
- f"UART capture reader failed: {type(session.reader_error).__name__}:"
- f"{session.reader_error}"
- )
- session._run_on_pump(
- session._capture_available_on_pump,
- pre_dispatch_quiet=False,
- activate_parser=False,
- )
- if session.reader_error is not None:
- raise RuntimeError(
- f"UART capture reader failed: {type(session.reader_error).__name__}:"
- f"{session.reader_error}"
- )
- return result
- def _program_failure_disable(session: NormalSession) -> dict[str, Any]:
- events: list[dict[str, Any]] = []
- try:
- result = _gate_safe_disable(
- session,
- events,
- phase="program-failure-disable",
- allow_boot_preamble=True,
- )
- return {
- "attempted": True,
- "confirmed": True,
- "state_hash16": result.ack.state_hash16,
- "events": events,
- }
- except Exception as exc:
- _append_last_exchange(events, session, phase="program-failure-disable")
- _append_best_effort_disable(events, session, phase="program-failure-disable")
- return {
- "attempted": True,
- "confirmed": False,
- "error": f"{type(exc).__name__}:{exc}",
- "events": events,
- }
- def _publish_program_failure_receipt(
- *,
- args: argparse.Namespace,
- output_dir: Path,
- commit: str,
- build_id: str,
- session: NormalSession,
- stages: list[dict[str, Any]],
- serial_events: list[dict[str, Any]],
- programmer_metadata: Mapping[str, Any],
- failure_disable: Mapping[str, Any],
- failure_reasons: list[str],
- ) -> dict[str, Any]:
- for row in failure_disable.get("events", []):
- if isinstance(row, Mapping):
- serial_events.append(dict(row))
- attempted = programmer_metadata.get("attempt_count") == 1
- failure_stages = list(stages)
- failure_stages.append(
- _stage(
- "program_sram",
- status="fail" if attempted else "not_run",
- **dict(programmer_metadata),
- )
- )
- failure_stages.append(
- _stage(
- "initial_disable",
- status="pass" if failure_disable.get("confirmed") is True else "fail",
- events=[dict(row) for row in failure_disable.get("events", []) if isinstance(row, Mapping)],
- )
- )
- failure_stages = _complete_failure_stages(
- failure_stages,
- reason=";".join(failure_reasons),
- )
- confirmed = failure_disable.get("confirmed") is True
- state_hash = failure_disable.get("state_hash16")
- final_disable = {
- "attempted": failure_disable.get("attempted") is True,
- "acknowledged": confirmed,
- "state_hash16": f"{int(state_hash):04X}" if confirmed and isinstance(state_hash, int) else "0000",
- "ptc_percent": 0,
- "fan_percent": [30, 30, 30, 30],
- "solenoid_percent": 0,
- "step_all_low": False,
- "en_n_high": False,
- }
- return _finalize_failed_hardware_session_receipt(
- output_dir=output_dir,
- board_id=str(args.board_id),
- commit=commit,
- build_id=build_id,
- build_info_path=Path(args.build_info),
- bitstream_path=Path(args.bitstream),
- td_receipt_path=Path(args.td_receipt),
- programmer_metadata=programmer_metadata,
- serial_events=serial_events,
- rx_journal=session.rx_journal,
- trace_events=list(session.trace_events),
- stages=failure_stages,
- failure_reasons=failure_reasons,
- final_disable=final_disable,
- x_close_dir=int(args.x_close_dir),
- y_close_dir=int(args.y_close_dir),
- )
- def _gate_preflight_failures(args: argparse.Namespace) -> list[str]:
- required = {
- "confirm_ptc_load_disabled": "ptc_load_not_disabled",
- "confirm_mechanical_travel_safe": "mechanical_travel_not_confirmed",
- "confirm_p5_active_high_closes_intake": "p5_polarity_not_confirmed",
- "confirm_ls1_x_closed_high": "ls1_x_closed_high_not_confirmed",
- "confirm_ls2_y_closed_high": "ls2_y_closed_high_not_confirmed",
- }
- failures = [failure for field, failure in required.items() if getattr(args, field, False) is not True]
- for axis in ("x", "y"):
- value = getattr(args, f"{axis}_close_dir", None)
- if isinstance(value, bool) or value not in (0, 1):
- failures.append(f"{axis}_close_dir_invalid")
- return sorted(set(failures))
- def _events_since(events: list[dict[str, Any]], start: int) -> list[dict[str, Any]]:
- return [dict(event) for event in events[start:]]
- def run_normal_actuator_trace_gate(
- args: argparse.Namespace,
- *,
- enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
- program_runner: Callable[..., dict[str, Any]] = run_program_only,
- endpoint_factory: Callable[[], Any] = open_com5,
- sleep: Callable[[float], None] = time.sleep,
- monotonic: Callable[[], float] = time.monotonic,
- operator_observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None = _console_operator_observer,
- ) -> dict[str, Any]:
- """Run one Normal v3 SRAM hardware session with strict Trace evidence."""
- input_failures, build_info = _program_input_failures(args)
- evidence_failures, package_info, _ = _gate_evidence_input_failures(
- args,
- build_info=build_info,
- )
- input_failures.extend(evidence_failures)
- input_failures.extend(_gate_preflight_failures(args))
- if operator_observer is None or (
- operator_observer is _console_operator_observer and not sys.stdin.isatty()
- ):
- input_failures.append("operator_observer_unavailable")
- input_failures = sorted(set(input_failures))
- if input_failures:
- return _gate_result(
- status="fail_preflight",
- args=args,
- failures=input_failures,
- hardware_enumerated=False,
- serial_opened=False,
- program_sram_attempted=False,
- attempt_count=0,
- retry_count=0,
- )
- assert build_info is not None
- assert package_info is not None
- build_id = str(build_info["build_id"])
- bitstream_sha256 = str(build_info["bitstream_sha256"])
- commit = str(package_info["commit"])
- plan = hardware_stage_plan()
- preflight = run_preflight(enumerator=enumerator)
- if preflight.get("status") != "pass":
- return _gate_result(
- status="fail_preflight",
- args=args,
- failures=[str(value) for value in preflight.get("failures", ["hardware_preflight_failed"])],
- hardware_enumerated=True,
- serial_opened=False,
- program_sram_attempted=False,
- attempt_count=0,
- retry_count=0,
- )
- output_dir = Path(args.output_dir)
- output_dir.mkdir(parents=True, exist_ok=False)
- stages: list[dict[str, Any]] = [
- _stage(
- "preflight",
- com5_present=True,
- al_link_present=True,
- ptc_load_disabled=True,
- mechanical_travel_safe=True,
- p5_active_high_closes_intake=True,
- ls1_x_closed_high=True,
- ls2_y_closed_high=True,
- z_hardware="not_connected_protocol_reserved",
- planned_stages=plan["stages"],
- )
- ]
- try:
- endpoint = endpoint_factory()
- except Exception as exc:
- return _gate_result(
- status="fail_com5_open",
- args=args,
- failures=[f"{type(exc).__name__}:{exc}"],
- hardware_enumerated=True,
- serial_opened=False,
- program_sram_attempted=False,
- attempt_count=0,
- retry_count=0,
- )
- session = NormalSession(
- endpoint,
- monotonic=monotonic,
- sleep=sleep,
- expected_build_id=int(build_id, 16),
- expected_capability_flags=CAPABILITY_FLAGS,
- )
- preprogram_uart_noise = session.drain_unparsed(timeout_seconds=0.1)
- events: list[dict[str, Any]] = []
- if preprogram_uart_noise:
- events.append(
- {
- "phase": "preprogram-rx-drain",
- "request_hex": "",
- "response_hex": preprogram_uart_noise.hex(),
- "command": "PASSIVE_RX_DRAIN",
- }
- )
- program_args = argparse.Namespace(
- bitstream=Path(args.bitstream),
- build_info=Path(args.build_info),
- output_dir=output_dir / "program-sram",
- td_root=Path(getattr(args, "td_root", DEFAULT_TD_ROOT)),
- run_id=str(getattr(args, "run_id", "prod2u-p4-normal-v3-gate")),
- board_id=str(args.board_id),
- )
- try:
- program_result = _run_program_with_uart_collection(
- session,
- programmer=program_runner,
- program_args=program_args,
- )
- except Exception as exc:
- failure_disable = _program_failure_disable(session)
- programmer_metadata = {
- "operation": "PROGRAM_SRAM",
- "speed_hz": 200000,
- "program_sram_attempted": True,
- "attempt_count": 1,
- "retry_count": 0,
- "flash_attempted": False,
- }
- failure_text = f"{type(exc).__name__}:{exc}"
- try:
- failure_receipt = _publish_program_failure_receipt(
- args=args,
- output_dir=output_dir,
- commit=commit,
- build_id=build_id,
- session=session,
- stages=stages,
- serial_events=events,
- programmer_metadata=programmer_metadata,
- failure_disable=failure_disable,
- failure_reasons=[failure_text],
- )
- finally:
- try:
- session.close()
- except Exception:
- pass
- return {
- **_gate_result(
- status="fail_program_sram",
- args=args,
- failures=[failure_text],
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=True,
- attempt_count=1,
- retry_count=0,
- ),
- "program_failure_disable": failure_disable,
- "hardware_session_receipt": failure_receipt,
- "receipt": str(output_dir / "hardware-session-receipt.json"),
- }
- program_status = str(program_result.get("status", "fail_programmer_contract"))
- programmer_metadata = {
- field: program_result.get(field)
- for field in PROGRAMMER_METADATA_CONTRACT
- }
- operation = programmer_metadata["operation"]
- speed_hz = programmer_metadata["speed_hz"]
- attempt_count = programmer_metadata["attempt_count"]
- retry_count = programmer_metadata["retry_count"]
- attempted_value = program_result.get("program_sram_attempted")
- attempted = attempted_value is True
- may_have_attempted = attempted_value is not False or (
- type(attempt_count) is int and attempt_count > 0
- )
- metadata_failures = (
- _programmer_metadata_failures(program_result)
- if program_status == "pass"
- else []
- )
- if metadata_failures:
- failure_disable = _program_failure_disable(session)
- try:
- session.close()
- except Exception:
- pass
- return {
- **_gate_result(
- status="fail_programmer_contract",
- args=args,
- failures=metadata_failures,
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=programmer_metadata["program_sram_attempted"],
- operation=operation,
- speed_hz=speed_hz,
- attempt_count=attempt_count,
- retry_count=retry_count,
- flash_attempted=programmer_metadata["flash_attempted"],
- ),
- "program_failure_disable": failure_disable,
- }
- if program_status != "pass":
- failure_disable = (
- _program_failure_disable(session)
- if may_have_attempted
- else {"attempted": False, "confirmed": False, "reason": "program_sram_not_attempted"}
- )
- try:
- session.close()
- except Exception:
- pass
- failures = [str(value) for value in program_result.get("failures", [])]
- if not failures:
- failures = [f"program_result_status:{program_status}"]
- failure_receipt = None
- if may_have_attempted:
- failure_metadata = {
- "operation": "PROGRAM_SRAM",
- "speed_hz": 200000,
- "program_sram_attempted": True,
- "attempt_count": 1,
- "retry_count": 0,
- "flash_attempted": False,
- }
- failure_receipt = _publish_program_failure_receipt(
- args=args,
- output_dir=output_dir,
- commit=commit,
- build_id=build_id,
- session=session,
- stages=stages,
- serial_events=events,
- programmer_metadata=failure_metadata,
- failure_disable=failure_disable,
- failure_reasons=failures,
- )
- return {
- **_gate_result(
- status="fail_program_sram",
- args=args,
- failures=failures,
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=may_have_attempted,
- operation=operation,
- speed_hz=speed_hz,
- attempt_count=attempt_count,
- retry_count=retry_count,
- flash_attempted=programmer_metadata["flash_attempted"],
- ),
- "program_failure_disable": failure_disable,
- "hardware_session_receipt": failure_receipt,
- **(
- {"receipt": str(output_dir / "hardware-session-receipt.json")}
- if failure_receipt is not None
- else {}
- ),
- }
- stages.append(
- _stage(
- "program_sram",
- **programmer_metadata,
- )
- )
- observations: list[dict[str, Any]] = []
- final_disable_confirmed = False
- watchdog_evidence: dict[str, Any] = {
- "status": "not_run",
- "timeout_ms": 5000,
- "timeline": [],
- }
- partial_scenarios: list[dict[str, str]] = []
- open_to_close_trace_events: list[TraceEvent] = []
- try:
- start = len(events)
- initial_disable = _gate_safe_disable(
- session,
- events,
- phase="initial-disable",
- allow_boot_preamble=True,
- )
- stages.append(_stage("initial_disable", events=_events_since(events, start)))
- boot_frames = [
- frame for frame in initial_disable.frames if frame.frame_type == FrameType.BOOT_BUILD_ID
- ]
- if len(boot_frames) != 1:
- raise RuntimeError("expected exactly one BOOT_BUILD_ID after PROGRAM_SRAM")
- boot = decode_boot_build_id(boot_frames[0])
- if boot.build_id != int(build_id, 16) or boot.capability_flags != CAPABILITY_FLAGS:
- raise RuntimeError("BOOT_BUILD_ID identity mismatch")
- stages.append(
- _stage(
- "boot_identity",
- build_id=build_id,
- capability=CAPABILITY_FLAGS,
- announcement_count=1,
- )
- )
- start = len(events)
- baseline = _gate_status(session, events, phase="baseline-status")
- if not (baseline.ack.detail & 0x01) or baseline.ack.detail & 0x02:
- raise RuntimeError("baseline GET_STATUS did not report DISABLE safe state")
- if baseline.ack.state_hash16 != SAFE_STATE_HASH16:
- raise RuntimeError("baseline safe state hash mismatch")
- stages.append(_stage("baseline_status", events=_events_since(events, start)))
- _run_xy_calibration_then_jog(
- session,
- events,
- stages,
- observations,
- x_close_dir=int(args.x_close_dir),
- y_close_dir=int(args.y_close_dir),
- sleep=sleep,
- operator_observer=operator_observer,
- )
- start = len(events)
- open_ack = _gate_snapshot(
- session,
- events,
- phase="open-xy",
- solenoid=0,
- xyz=(100, 100, 0),
- )
- if open_ack.ack.status != StatusCode.OK or open_ack.ack.detail != 0:
- raise RuntimeError("XY open did not accept protocol-reserved Z as a no-op")
- busy_status = _gate_motor_status(session, events, phase="open-busy")
- if (
- busy_status.status.busy_mask != 0x03
- or busy_status.status.position_valid_mask != 0x03
- or busy_status.status.current_xyz[:2] != (0xFE, 0xFE)
- or busy_status.status.target_xyz != (100, 100, 0xFF)
- ):
- raise RuntimeError("XY open did not start both connected axes")
- partial_ack = _gate_snapshot(
- session,
- events,
- phase="busy-idempotent-open",
- solenoid=0,
- xyz=(100, 100, 0),
- )
- if partial_ack.ack.status != StatusCode.OK or partial_ack.ack.detail != 0:
- raise RuntimeError("idempotent XY OPEN did not keep Z as an accepted no-op")
- after_partial = _gate_motor_status(session, events, phase="busy-idempotent-open-status")
- if after_partial.status.busy_mask != 0x03 or after_partial.status.target_xyz != (100, 100, 0xFF):
- raise RuntimeError("idempotent XY OPEN changed active motion")
- stages.append(
- _stage(
- "idempotent_motion",
- events=[event for event in _events_since(events, start) if event["phase"].startswith("busy-idempotent")],
- )
- )
- reverse_start = len(events)
- reverse_trace_start = len(session.trace_events)
- reverse_ack = _gate_snapshot(
- session,
- events,
- phase="opening-reverse-close",
- solenoid=0,
- xyz=(0, 0, 0),
- )
- if reverse_ack.ack.status != StatusCode.OK or reverse_ack.ack.detail != 0:
- raise RuntimeError("OPENING-to-CLOSE did not accept both connected axes")
- reversing = _gate_motor_status(session, events, phase="opening-reverse-close-status")
- if reversing.status.busy_mask != 0x03 or reversing.status.target_xyz != (0, 0, 0xFF):
- raise RuntimeError("OPENING-to-CLOSE did not preserve a closing target")
- reversed_closed = _wait_for_idle(
- session,
- events,
- phase="opening-reverse-close",
- sleep=sleep,
- )
- if reversed_closed.status.current_xyz != (0, 0, 0xFF):
- raise RuntimeError("OPENING-to-CLOSE did not return both axes to CLOSED")
- open_to_close_trace_events = list(session.trace_events[reverse_trace_start:])
- stages.append(_stage("open_to_close", events=_events_since(events, reverse_start)))
- partial_scenarios = _run_xy_partial_scenarios(
- session,
- events,
- stages,
- sleep=sleep,
- )
- standard_start = len(events)
- standard_open_ack = _gate_snapshot(
- session,
- events,
- phase="standard-open-xy",
- solenoid=0,
- xyz=(100, 100, 0),
- )
- if standard_open_ack.ack.status != StatusCode.OK or standard_open_ack.ack.detail != 0:
- raise RuntimeError("standard XY open did not keep Z as an accepted no-op")
- opened = _wait_for_idle(session, events, phase="standard-open-xy", sleep=sleep)
- if opened.status.current_xyz != (100, 100, 0xFF):
- raise RuntimeError("XY open did not complete")
- close_ack = _gate_snapshot(
- session,
- events,
- phase="close-xy",
- solenoid=0,
- xyz=(0, 0, 0),
- )
- if close_ack.ack.status != StatusCode.OK or close_ack.ack.detail != 0:
- raise RuntimeError("XY close did not keep Z as an accepted no-op")
- rejected_open_ack = _gate_snapshot(
- session,
- events,
- phase="closing-reject-open",
- solenoid=0,
- xyz=(100, 100, 0),
- )
- if rejected_open_ack.ack.status != StatusCode.PARTIAL or rejected_open_ack.ack.detail != 0x03:
- raise RuntimeError("CLOSING-to-OPEN did not report both XY axes busy")
- after_rejected_open = _gate_motor_status(session, events, phase="closing-reject-open-status")
- if (
- after_rejected_open.status.busy_mask != 0x03
- or after_rejected_open.status.current_xyz[:2] != (0xFE, 0xFE)
- or after_rejected_open.status.target_xyz != (0, 0, 0xFF)
- ):
- raise RuntimeError("rejected CLOSING-to-OPEN changed active XY close motion")
- closed = _wait_for_idle(session, events, phase="close-xy", sleep=sleep)
- if closed.status.current_xyz != (0, 0, 0xFF):
- raise RuntimeError("XY close did not complete")
- _confirm_operator_observation_from_disabled(
- session,
- events,
- observations,
- observer=operator_observer,
- stage="xy_open_close",
- context={"open_target": [100, 100, 0], "closed_position": [0, 0, 255]},
- )
- stages.append(_stage("standard_motion", events=_events_since(events, standard_start)))
- start = len(events)
- _start_watchdog_motion(
- session,
- events,
- y_close_dir=int(args.y_close_dir),
- )
- for event in events[start:]:
- if event.get("phase") in {"watchdog-start", "watchdog-start-status"}:
- event["elapsed_ms"] = 0
- before_watchdog = monotonic()
- sleep(1.0)
- refreshed = _gate_motor_status(session, events, phase="watchdog-refresh")
- refresh_ms = int(round((monotonic() - before_watchdog) * 1000))
- events[-1]["elapsed_ms"] = refresh_ms
- if not (refreshed.status.busy_mask & 0x02):
- raise RuntimeError("watchdog refresh did not observe active Y motion")
- sleep(5.1)
- elapsed_ms = int(round((monotonic() - before_watchdog) * 1000))
- watchdog_motor = _gate_motor_status(session, events, phase="watchdog-status")
- watchdog_ack = _gate_status(session, events, phase="watchdog-get-status")
- for event in events[start:]:
- if event.get("phase") in {"watchdog-status", "watchdog-get-status"}:
- event["elapsed_ms"] = elapsed_ms
- if (
- elapsed_ms < 4900
- or not (watchdog_motor.status.position_valid_mask & 0x02)
- or watchdog_motor.status.current_xyz[1] != 0xFE
- or (watchdog_motor.status.flags & 0x0E) != 0x0C
- or not (watchdog_ack.ack.detail & 0x02)
- or watchdog_ack.ack.state_hash16 != SAFE_STATE_HASH16
- ):
- raise RuntimeError("watchdog safe-state verification failed")
- _confirm_operator_observation_from_disabled(
- session,
- events,
- observations,
- observer=operator_observer,
- stage="watchdog_safe_state",
- context={"observed_delay_ms": elapsed_ms},
- required_confirmations=("step_all_low", "en_n_high"),
- )
- stages.append(
- _stage("watchdog", events=_events_since(events, start), observed_delay_ms=elapsed_ms)
- )
- watchdog_evidence = {
- "status": "pass",
- "timeout_ms": 5000,
- "timeline": [
- {"event": "armed", "elapsed_ms": 0},
- {"event": "motor_status_refresh", "elapsed_ms": refresh_ms},
- {"event": "expired", "elapsed_ms": elapsed_ms},
- {"event": "safe_state_confirmed", "elapsed_ms": elapsed_ms},
- ],
- }
- start = len(events)
- final_disable = _gate_safe_disable(session, events, phase="final-disable")
- final_motor = _gate_motor_status(session, events, phase="final-motor-status")
- if (
- final_disable.ack.state_hash16 != SAFE_STATE_HASH16
- or final_motor.status.busy_mask != 0
- or not (final_motor.status.flags & 0x04)
- ):
- raise RuntimeError("final DISABLE safe state verification failed")
- final_disable_confirmed = True
- _confirm_operator_observation(
- operator_observer,
- observations,
- stage="final_disable_safe_state",
- context={"state_hash16": final_disable.ack.state_hash16},
- required_confirmations=("step_all_low", "en_n_high"),
- )
- final_quiet_frames, final_quiet_raw = session.read_passive_frames(
- timeout_seconds=session.max_quiet_drain_seconds
- )
- if final_quiet_raw:
- events.append(
- {
- "phase": "final-quiet-drain",
- "request_hex": "",
- "response_hex": final_quiet_raw.hex(),
- "command": "PASSIVE_TRACE_DRAIN",
- }
- )
- stages.append(
- _stage(
- "final_disable",
- events=_events_since(events, start),
- operator_observations=observations,
- )
- )
- except BaseException as exc:
- exchange = session.last_exchange or {}
- if not exchange.get("request_hex"):
- failed_phase = "final-quiet-drain"
- elif not any(row.get("request_hex") for row in events) and int(
- exchange.get("command", -1)
- ) == int(CommandId.DISABLE):
- failed_phase = "initial-disable"
- else:
- failed_phase = "failed-command"
- _append_last_exchange(events, session, phase=failed_phase)
- _append_best_effort_disable(events, session, phase="exception-disable")
- if not final_disable_confirmed and not session.disable_attempted:
- try:
- _gate_safe_disable(session, events, phase="exception-disable")
- except Exception as disable_exc:
- _append_last_exchange(events, session, phase="exception-disable")
- events.append(
- {
- "phase": "exception-disable",
- "error": f"{type(disable_exc).__name__}:{disable_exc}",
- }
- )
- failure_text = f"{type(exc).__name__}:{exc}"
- failure_stages = _complete_failure_stages(stages, reason=failure_text)
- failure_receipt: dict[str, Any] | None = None
- try:
- failure_receipt = _finalize_failed_hardware_session_receipt(
- output_dir=output_dir,
- board_id=str(args.board_id),
- commit=commit,
- build_id=build_id,
- build_info_path=Path(args.build_info),
- bitstream_path=Path(args.bitstream),
- td_receipt_path=Path(args.td_receipt),
- programmer_metadata=programmer_metadata,
- serial_events=events,
- rx_journal=session.rx_journal,
- trace_events=list(session.trace_events),
- stages=failure_stages,
- failure_reasons=[failure_text],
- final_disable={
- "attempted": True,
- "acknowledged": False,
- "state_hash16": "0000",
- "ptc_percent": 0,
- "fan_percent": [30, 30, 30, 30],
- "solenoid_percent": 0,
- "step_all_low": False,
- "en_n_high": False,
- },
- x_close_dir=int(args.x_close_dir),
- y_close_dir=int(args.y_close_dir),
- )
- except Exception as receipt_exc:
- failure_text = (
- f"{failure_text};failure_receipt:{type(receipt_exc).__name__}:{receipt_exc}"
- )
- try:
- session.close()
- except Exception:
- pass
- return {
- **_gate_result(
- status="fail_host_uart_gate",
- args=args,
- failures=[failure_text],
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=attempted,
- operation=operation,
- speed_hz=speed_hz,
- attempt_count=attempt_count,
- retry_count=retry_count,
- flash_attempted=programmer_metadata["flash_attempted"],
- ),
- "stages": failure_stages,
- "serial_events": events,
- "hardware_session_receipt": failure_receipt,
- }
- finally:
- try:
- session.close()
- except Exception:
- pass
- trace_summary = _trace_receipt_summary(list(session.trace_events))
- stages.append(
- _stage(
- "trace_integrity",
- status=str(trace_summary["status"]),
- **{key: value for key, value in trace_summary.items() if key != "status"},
- )
- )
- register_checkpoint = {
- "baseline": {
- "detail": baseline.ack.detail,
- "state_hash16": f"{baseline.ack.state_hash16:04X}",
- },
- "final_disable": {
- "detail": final_disable.ack.detail,
- "state_hash16": f"{final_disable.ack.state_hash16:04X}",
- },
- "final_motor": {
- "flags": final_motor.status.flags,
- "position_valid_mask": final_motor.status.position_valid_mask,
- "busy_mask": final_motor.status.busy_mask,
- "current_xyz": list(final_motor.status.current_xyz),
- "target_xyz": list(final_motor.status.target_xyz),
- "fault_mask": final_motor.status.fault_mask,
- },
- }
- stages.append(_stage("register_checkpoint", checkpoint=register_checkpoint))
- partial = {
- "status": "pass",
- "scenarios": partial_scenarios,
- }
- final_disable_evidence = {
- "attempted": True,
- "acknowledged": final_disable_confirmed,
- "state_hash16": f"{final_disable.ack.state_hash16:04X}",
- "ptc_percent": 0,
- "fan_percent": [30, 30, 30, 30],
- "solenoid_percent": 0,
- "step_all_low": True,
- "en_n_high": True,
- }
- try:
- axis_checks = {
- "mark_closed": True,
- "jog_away": True,
- "jog_to_limit": True,
- "standard_open_close": True,
- }
- axes = {
- "x": _axis_evidence_from_trace(
- list(session.trace_events),
- axis_label="X",
- close_dir=int(args.x_close_dir),
- checks=axis_checks,
- open_to_close_events=open_to_close_trace_events,
- ),
- "y": _axis_evidence_from_trace(
- list(session.trace_events),
- axis_label="Y",
- close_dir=int(args.y_close_dir),
- checks=axis_checks,
- open_to_close_events=open_to_close_trace_events,
- ),
- }
- receipt = _finalize_hardware_session_receipt(
- output_dir=output_dir,
- board_id=str(args.board_id),
- commit=commit,
- build_id=build_id,
- build_info_path=Path(args.build_info),
- bitstream_path=Path(args.bitstream),
- td_receipt_path=Path(args.td_receipt),
- programmer_metadata=programmer_metadata,
- serial_events=events,
- trace_events=list(session.trace_events),
- register_checkpoint=register_checkpoint,
- axes=axes,
- partial=partial,
- watchdog=watchdog_evidence,
- stages=stages,
- final_disable=final_disable_evidence,
- )
- except (OSError, TypeError, ValueError) as exc:
- return {
- **_gate_result(
- status="fail_gate_receipt",
- args=args,
- failures=[f"{type(exc).__name__}:{exc}"],
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=programmer_metadata["program_sram_attempted"],
- operation=operation,
- speed_hz=speed_hz,
- attempt_count=attempt_count,
- retry_count=retry_count,
- flash_attempted=programmer_metadata["flash_attempted"],
- ),
- "stages": stages,
- }
- receipt_path = output_dir / "hardware-session-receipt.json"
- return {
- **_gate_result(
- status="pass",
- args=args,
- failures=[],
- hardware_enumerated=True,
- serial_opened=True,
- program_sram_attempted=programmer_metadata["program_sram_attempted"],
- operation=operation,
- speed_hz=speed_hz,
- attempt_count=attempt_count,
- retry_count=retry_count,
- flash_attempted=programmer_metadata["flash_attempted"],
- ),
- "commit": commit,
- "build_id": build_id,
- "bitstream_sha256": bitstream_sha256,
- "artifacts": dict(receipt["artifacts"]),
- "receipt": str(receipt_path),
- }
- def _live_request(args: argparse.Namespace, endpoint: Any) -> dict[str, Any]:
- session = NormalSession(endpoint)
- if args.command == "set-all-outputs":
- request = build_output_snapshot(
- ptc_percent=(args.ptc,) * 24,
- fan_percent=(args.fan,) * 4,
- solenoid=args.solenoid,
- xyz=(args.x, args.y, args.z),
- )
- expected_hash = state_hash16(
- ptc_percent=(args.ptc,) * 24,
- fan_percent=(args.fan,) * 4,
- solenoid=args.solenoid,
- )
- result = session.command(
- request,
- expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
- expected_state_hash16=expected_hash,
- required_result_flags=0x01,
- allowed_result_flags=0x0F,
- )
- if result.ack.detail & 0xC0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
- if result.ack.status == StatusCode.OK and result.ack.detail != 0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
- if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK is missing skip detail")
- busy_mask = result.ack.detail & 0x07
- invalid_mask = (result.ack.detail >> 3) & 0x07
- if busy_mask & invalid_mask:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
- accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
- expected_result_flags = 0x01 | (accepted_or_noop_mask << 1)
- if result.ack.result_flags != expected_result_flags:
- session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
- return {"status": "pass", "ack": result.ack.__dict__}
- if args.command == "jog":
- request = build_motor_jog(
- axis=args.axis,
- raw_dir=args.raw_dir,
- speed_code=args.speed_code,
- steps=args.steps,
- )
- result = session.command(
- request,
- expected_command=0x35,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0,
- )
- return {"status": "pass", "ack": result.ack.__dict__}
- if args.command == "mark-closed":
- result = session.command(
- build_mark_closed(axis=args.axis, close_dir=args.close_dir),
- expected_command=0x36,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0,
- )
- return {"status": "pass", "ack": result.ack.__dict__}
- if args.command == "get-status":
- result = session.command(
- build_host_command(command=CommandId.GET_STATUS),
- expected_command=CommandId.GET_STATUS,
- allowed_statuses=(StatusCode.OK,),
- allowed_result_flags=0,
- )
- if result.ack.detail & ~0x03:
- session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
- return {
- "status": "pass",
- "ack": result.ack.__dict__,
- "disabled": bool(result.ack.detail & 0x01),
- "watchdog_timeout": bool(result.ack.detail & 0x02),
- }
- if args.command == "motor-status":
- result = session.motor_status()
- return {
- "status": "pass",
- "ack": result.ack.__dict__,
- "motor_status": result.status.__dict__,
- }
- if args.command == "disable":
- result = session.command(
- build_host_command(command=CommandId.DISABLE),
- expected_command=CommandId.DISABLE,
- allowed_statuses=(StatusCode.OK,),
- expected_detail=0x01,
- expected_state_hash16=SAFE_STATE_HASH16,
- )
- return {"status": "pass", "ack": result.ack.__dict__}
- raise RuntimeError(f"unsupported live command: {args.command}")
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- if args.command == "selftest":
- result = _selftest()
- elif args.command == "preflight":
- result = run_preflight()
- elif args.command == "normal-actuator-trace-gate":
- result = run_normal_actuator_trace_gate(args)
- elif args.command in {
- "set-all-outputs",
- "jog",
- "mark-closed",
- "get-status",
- "motor-status",
- "disable",
- }:
- result = {
- "status": "fail_unsafe_trace_reattach",
- "reason": (
- "one-shot live commands cannot safely reattach to the continuous Trace "
- "event sequence; use normal-actuator-trace-gate"
- ),
- }
- else:
- raise AssertionError(f"unhandled command: {args.command}")
- print(json.dumps(result, indent=2, default=lambda value: int(value), ensure_ascii=False))
- return 0 if result.get("status") == "pass" else 1
- if __name__ == "__main__":
- raise SystemExit(main())
|