prod2u_p4_cli.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. #!/usr/bin/env python3
  2. """Minimal ACK-only host tooling for Prod2U Profile 4 binary921-v3."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import re
  7. import subprocess
  8. import threading
  9. import time
  10. from dataclasses import dataclass
  11. from pathlib import Path
  12. from typing import Any, Callable
  13. from prod2u_p4_protocol import (
  14. CRC_LEN,
  15. HEADER_LEN,
  16. MAGIC,
  17. CommandId,
  18. FrameType,
  19. FORCE_JOG_STEP_CAP,
  20. HostAck,
  21. MotionOpcode,
  22. MotionStatus,
  23. P4Frame,
  24. P4FrameError,
  25. StatusCode,
  26. build_get_motor_status,
  27. build_host_command,
  28. build_motor_jog,
  29. build_output_snapshot,
  30. decode_frame,
  31. decode_host_ack,
  32. decode_motion_status,
  33. state_hash16,
  34. )
  35. PROFILE = "prod2u-p4-normal-actuator-binary921-v3"
  36. PROFILE_ID = 4
  37. PROTOCOL_VERSION = 2
  38. PORT = "COM5"
  39. BAUD = 921600
  40. SAFE_STATE_HASH16 = state_hash16(
  41. ptc_percent=(0,) * 24,
  42. fan_percent=(30,) * 4,
  43. solenoid=0,
  44. )
  45. @dataclass(frozen=True)
  46. class CommandResult:
  47. ack: HostAck
  48. raw_response: bytes
  49. frames: tuple[P4Frame, ...]
  50. @dataclass(frozen=True)
  51. class MotorStatusResult:
  52. ack: HostAck
  53. status: MotionStatus
  54. raw_response: bytes
  55. def open_com5(serial_factory: Callable[[], Any] | None = None) -> Any:
  56. if serial_factory is None:
  57. try:
  58. import serial # type: ignore
  59. except ImportError as exc:
  60. raise RuntimeError("pyserial is required for live Profile 4 operation") from exc
  61. serial_factory = serial.Serial
  62. endpoint = serial_factory()
  63. endpoint.port = PORT
  64. endpoint.baudrate = BAUD
  65. endpoint.bytesize = 8
  66. endpoint.parity = "N"
  67. endpoint.stopbits = 1
  68. endpoint.timeout = 0
  69. endpoint.write_timeout = 1
  70. endpoint.dtr = False
  71. endpoint.rts = False
  72. if not getattr(endpoint, "is_open", False):
  73. endpoint.open()
  74. endpoint.dtr = False
  75. endpoint.rts = False
  76. return endpoint
  77. class NormalSession:
  78. """One-outstanding-command UART session with one DISABLE fallback."""
  79. def __init__(
  80. self,
  81. endpoint: Any,
  82. *,
  83. timeout_seconds: float = 0.25,
  84. quiet_window_seconds: float = 0.010,
  85. max_quiet_drain_seconds: float = 0.050,
  86. monotonic: Callable[[], float] = time.monotonic,
  87. sleep: Callable[[float], None] = time.sleep,
  88. ) -> None:
  89. if timeout_seconds <= 0:
  90. raise ValueError("timeout_seconds must be positive")
  91. if quiet_window_seconds <= 0:
  92. raise ValueError("quiet_window_seconds must be positive")
  93. if max_quiet_drain_seconds < quiet_window_seconds:
  94. raise ValueError("max_quiet_drain_seconds must cover the quiet window")
  95. self.endpoint = endpoint
  96. self.timeout_seconds = timeout_seconds
  97. self.quiet_window_seconds = quiet_window_seconds
  98. self.max_quiet_drain_seconds = max_quiet_drain_seconds
  99. self.disable_attempted = False
  100. self._terminated = False
  101. self._command_lock = threading.Lock()
  102. self._rx_buffer = bytearray()
  103. self._rx_journal = bytearray()
  104. self._last_exchange: dict[str, Any] | None = None
  105. self._best_effort_disable_exchange: dict[str, Any] | None = None
  106. self._monotonic = monotonic
  107. self._sleep = sleep
  108. @property
  109. def rx_journal(self) -> bytes:
  110. return bytes(self._rx_journal)
  111. @property
  112. def last_exchange(self) -> dict[str, Any] | None:
  113. return None if self._last_exchange is None else dict(self._last_exchange)
  114. @property
  115. def best_effort_disable_exchange(self) -> dict[str, Any] | None:
  116. return (
  117. None
  118. if self._best_effort_disable_exchange is None
  119. else dict(self._best_effort_disable_exchange)
  120. )
  121. def close(self) -> None:
  122. close = getattr(self.endpoint, "close", None)
  123. if callable(close):
  124. close()
  125. def _write_exact(self, data: bytes) -> None:
  126. written = self.endpoint.write(data)
  127. if written != len(data):
  128. raise IOError(f"short serial write: expected {len(data)}, got {written}")
  129. def _read_frame(self, *, deadline: float) -> P4Frame:
  130. while self._monotonic() < deadline:
  131. if len(self._rx_buffer) >= HEADER_LEN + CRC_LEN:
  132. if self._rx_buffer[:2] != MAGIC:
  133. raise RuntimeError("unexpected bytes before Profile 4 response")
  134. frame_length = HEADER_LEN + self._rx_buffer[13] + CRC_LEN
  135. if len(self._rx_buffer) >= frame_length:
  136. raw = bytes(self._rx_buffer[:frame_length])
  137. del self._rx_buffer[:frame_length]
  138. try:
  139. return decode_frame(raw)
  140. except P4FrameError as exc:
  141. raise RuntimeError(f"invalid Profile 4 response: {exc}") from exc
  142. chunk = bytes(self.endpoint.read(256))
  143. if chunk:
  144. self._rx_buffer.extend(chunk)
  145. self._rx_journal.extend(chunk)
  146. continue
  147. self._sleep(0.0005)
  148. raise TimeoutError("ACK timeout")
  149. def _attempt_disable(self) -> None:
  150. if self.disable_attempted:
  151. return
  152. self.disable_attempted = True
  153. request = build_host_command(command=CommandId.DISABLE)
  154. try:
  155. self._write_exact(request)
  156. self._best_effort_disable_exchange = {"request_hex": request.hex()}
  157. except Exception as exc: # pragma: no cover - best effort only
  158. self._best_effort_disable_exchange = {
  159. "request_hex": request.hex(),
  160. "error": str(exc),
  161. }
  162. def _require_quiet_tail(self) -> None:
  163. if self._rx_buffer:
  164. raise RuntimeError("unexpected bytes after completed response")
  165. started = self._monotonic()
  166. quiet_deadline = started + self.quiet_window_seconds
  167. hard_deadline = started + self.max_quiet_drain_seconds
  168. while self._monotonic() < quiet_deadline and self._monotonic() < hard_deadline:
  169. chunk = bytes(self.endpoint.read(256))
  170. if chunk:
  171. self._rx_journal.extend(chunk)
  172. raise RuntimeError("unexpected bytes after completed response")
  173. self._sleep(0.0005)
  174. def _fail(self, expected_command: CommandId | int, message: str) -> None:
  175. self._terminated = True
  176. if int(expected_command) == int(CommandId.DISABLE):
  177. self.disable_attempted = True
  178. else:
  179. self._attempt_disable()
  180. self._rx_buffer.clear()
  181. raise RuntimeError(message)
  182. def collect_available(self) -> bytes:
  183. collected = bytearray()
  184. while True:
  185. chunk = bytes(self.endpoint.read(256))
  186. if not chunk:
  187. break
  188. collected.extend(chunk)
  189. self._rx_journal.extend(chunk)
  190. return bytes(collected)
  191. def drain_unparsed(self, *, timeout_seconds: float | None = None) -> bytes:
  192. duration = self.quiet_window_seconds if timeout_seconds is None else timeout_seconds
  193. if duration < 0:
  194. raise ValueError("timeout_seconds must be non-negative")
  195. deadline = self._monotonic() + duration
  196. collected = bytearray(self._rx_buffer)
  197. self._rx_buffer.clear()
  198. while self._monotonic() < deadline:
  199. chunk = bytes(self.endpoint.read(256))
  200. if chunk:
  201. collected.extend(chunk)
  202. self._rx_journal.extend(chunk)
  203. deadline = self._monotonic() + self.quiet_window_seconds
  204. else:
  205. self._sleep(0.0005)
  206. return bytes(collected)
  207. @staticmethod
  208. def _validate_ack(
  209. ack: HostAck,
  210. *,
  211. expected_command: CommandId | MotionOpcode | int,
  212. allowed_statuses: tuple[StatusCode, ...],
  213. expected_detail: int | None,
  214. expected_state_hash16: int | None,
  215. expected_response_type: FrameType | int,
  216. required_result_flags: int,
  217. allowed_result_flags: int,
  218. ) -> None:
  219. if int(ack.command) != int(expected_command):
  220. raise RuntimeError("ACK command mismatch")
  221. if ack.status not in allowed_statuses:
  222. raise RuntimeError(f"unexpected ACK status: {ack.status.name}")
  223. expected_ok = ack.status in (StatusCode.OK, StatusCode.PARTIAL)
  224. if ack.ok != expected_ok:
  225. raise RuntimeError("ACK ok/status mismatch")
  226. if expected_detail is not None and ack.detail != expected_detail:
  227. raise RuntimeError("ACK detail mismatch")
  228. if expected_state_hash16 is not None and ack.state_hash16 != expected_state_hash16:
  229. raise RuntimeError("ACK state hash mismatch")
  230. if int(ack.response_type) != int(expected_response_type):
  231. raise RuntimeError("ACK response type mismatch")
  232. if ack.result_flags & ~allowed_result_flags:
  233. raise RuntimeError("ACK contains disallowed result flags")
  234. if ack.result_flags & required_result_flags != required_result_flags:
  235. raise RuntimeError("ACK is missing required result flags")
  236. def _begin(self) -> None:
  237. if self._terminated:
  238. raise RuntimeError("session is terminated")
  239. if not self._command_lock.acquire(blocking=False):
  240. raise RuntimeError("only one outstanding command is allowed")
  241. def _abort(self, expected_command: CommandId | MotionOpcode | int) -> None:
  242. self._terminated = True
  243. if int(expected_command) == int(CommandId.DISABLE):
  244. self.disable_attempted = True
  245. else:
  246. self._attempt_disable()
  247. def command(
  248. self,
  249. request: bytes,
  250. *,
  251. expected_command: CommandId | MotionOpcode | int,
  252. allowed_statuses: tuple[StatusCode, ...] = (StatusCode.OK, StatusCode.PARTIAL),
  253. expected_detail: int | None = None,
  254. expected_state_hash16: int | None = None,
  255. required_result_flags: int = 0,
  256. allowed_result_flags: int = 0xFF,
  257. ) -> CommandResult:
  258. self._begin()
  259. try:
  260. try:
  261. self._write_exact(request)
  262. frame = self._read_frame(deadline=self._monotonic() + self.timeout_seconds)
  263. if frame.frame_type != FrameType.HOST_ACK:
  264. raise RuntimeError("first response must be HOST_ACK")
  265. try:
  266. ack = decode_host_ack(frame)
  267. except ValueError as exc:
  268. raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc
  269. self._validate_ack(
  270. ack,
  271. expected_command=expected_command,
  272. allowed_statuses=allowed_statuses,
  273. expected_detail=expected_detail,
  274. expected_state_hash16=expected_state_hash16,
  275. expected_response_type=0,
  276. required_result_flags=required_result_flags,
  277. allowed_result_flags=allowed_result_flags,
  278. )
  279. self._require_quiet_tail()
  280. result = CommandResult(ack=ack, raw_response=frame.raw, frames=(frame,))
  281. self._last_exchange = {
  282. "request_hex": request.hex(),
  283. "response_hex": frame.raw.hex(),
  284. }
  285. return result
  286. except BaseException:
  287. self._abort(expected_command)
  288. raise
  289. finally:
  290. self._command_lock.release()
  291. def motor_status(self) -> MotorStatusResult:
  292. request = build_get_motor_status()
  293. expected_command = MotionOpcode.GET_MOTOR_STATUS
  294. self._begin()
  295. try:
  296. try:
  297. self._write_exact(request)
  298. deadline = self._monotonic() + self.timeout_seconds
  299. ack_frame = self._read_frame(deadline=deadline)
  300. if ack_frame.frame_type != FrameType.HOST_ACK:
  301. raise RuntimeError("first response must be HOST_ACK")
  302. try:
  303. ack = decode_host_ack(ack_frame)
  304. except ValueError as exc:
  305. raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc
  306. self._validate_ack(
  307. ack,
  308. expected_command=expected_command,
  309. allowed_statuses=(StatusCode.OK,),
  310. expected_detail=0,
  311. expected_state_hash16=None,
  312. expected_response_type=FrameType.MOTION_STATUS,
  313. required_result_flags=0x08,
  314. allowed_result_flags=0x08,
  315. )
  316. status_frame = self._read_frame(deadline=deadline)
  317. if status_frame.frame_type != FrameType.MOTION_STATUS:
  318. raise RuntimeError("HOST_ACK must be followed by MOTION_STATUS")
  319. try:
  320. status = decode_motion_status(status_frame)
  321. except ValueError as exc:
  322. raise RuntimeError(f"malformed MOTION_STATUS: {exc}") from exc
  323. self._require_quiet_tail()
  324. raw = ack_frame.raw + status_frame.raw
  325. self._last_exchange = {
  326. "request_hex": request.hex(),
  327. "response_hex": raw.hex(),
  328. }
  329. return MotorStatusResult(ack=ack, status=status, raw_response=raw)
  330. except BaseException:
  331. self._abort(expected_command)
  332. raise
  333. finally:
  334. self._command_lock.release()
  335. def _bounded_int(minimum: int, maximum: int) -> Callable[[str], int]:
  336. def parse(value: str) -> int:
  337. try:
  338. parsed = int(value, 10)
  339. except ValueError as exc:
  340. raise argparse.ArgumentTypeError("must be an integer") from exc
  341. if not minimum <= parsed <= maximum:
  342. raise argparse.ArgumentTypeError(f"must be from {minimum} to {maximum}")
  343. return parsed
  344. return parse
  345. def build_parser() -> argparse.ArgumentParser:
  346. parser = argparse.ArgumentParser(description=__doc__)
  347. sub = parser.add_subparsers(dest="command", required=True)
  348. sub.add_parser("selftest")
  349. sub.add_parser("preflight")
  350. snapshot = sub.add_parser(
  351. "set-all-outputs",
  352. description=(
  353. "Sets PTC, fan, solenoid, and X/Y/Z target fields. X/Y targets may start "
  354. "independent 3200-step moves; 0 requests closed, 100 requests open, and Z "
  355. "remains a protocol-only no-op."
  356. ),
  357. )
  358. snapshot.add_argument("--ptc", type=_bounded_int(0, 100), default=0)
  359. snapshot.add_argument("--fan", type=_bounded_int(0, 100), default=30)
  360. snapshot.add_argument("--solenoid", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  361. snapshot.add_argument("--x", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  362. snapshot.add_argument("--y", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  363. snapshot.add_argument("--z", type=_bounded_int(0, 100), choices=(0, 100), default=0)
  364. jog = sub.add_parser("jog")
  365. jog.add_argument("--axis", type=_bounded_int(0, 1), required=True)
  366. jog.add_argument("--raw-dir", type=_bounded_int(0, 1), required=True)
  367. jog.add_argument("--speed-code", type=_bounded_int(0, 3), required=True)
  368. jog.add_argument("--steps", type=_bounded_int(1, 65535), required=True)
  369. sub.add_parser("get-status")
  370. sub.add_parser("motor-status")
  371. sub.add_parser("disable")
  372. return parser
  373. def _selftest() -> dict[str, Any]:
  374. snapshot = build_output_snapshot(
  375. ptc_percent=(0,) * 24,
  376. fan_percent=(30,) * 4,
  377. solenoid=0,
  378. xyz=(0, 0, 0),
  379. )
  380. jog = build_motor_jog(axis=1, raw_dir=1, speed_code=3, steps=65535)
  381. return {
  382. "schema": "prod2u-p4-normal-v3-selftest-v2",
  383. "status": "pass" if len(snapshot) == 50 and len(jog) == 24 else "fail",
  384. "profile": PROFILE,
  385. "profile_id": PROFILE_ID,
  386. "protocol_version": PROTOCOL_VERSION,
  387. "baud": BAUD,
  388. "port": PORT,
  389. "jog_request_steps_max": 65535,
  390. "jog_actual_steps_cap": FORCE_JOG_STEP_CAP,
  391. "hardware_opened": False,
  392. "program_sram_attempted": False,
  393. }
  394. def enumerate_hardware_candidates(
  395. *,
  396. runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
  397. ) -> dict[str, Any]:
  398. """Enumerate COM and AL-Link candidates without opening either interface."""
  399. script = r"""
  400. $ErrorActionPreference = 'Stop'
  401. $cimSerialPorts = @()
  402. try {
  403. $cimSerialPorts = @(
  404. Get-CimInstance Win32_SerialPort |
  405. Sort-Object DeviceID |
  406. ForEach-Object {
  407. [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
  408. }
  409. )
  410. } catch {}
  411. $pnpSerialPorts = @()
  412. try {
  413. if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) {
  414. $pnpSerialPorts = @(
  415. Get-PnpDevice -Class Ports -PresentOnly -ErrorAction Stop |
  416. Sort-Object InstanceId |
  417. ForEach-Object {
  418. [ordered]@{ name = [string]$_.FriendlyName; device_id = [string]$_.InstanceId }
  419. }
  420. )
  421. }
  422. } catch {}
  423. $dotNetSerialPorts = @()
  424. try {
  425. $dotNetSerialPorts = @(
  426. [System.IO.Ports.SerialPort]::GetPortNames() |
  427. Sort-Object |
  428. ForEach-Object {
  429. [ordered]@{ name = [string]$_; device_id = [string]$_ }
  430. }
  431. )
  432. } catch {}
  433. $serialPorts = @($cimSerialPorts) + @($pnpSerialPorts) + @($dotNetSerialPorts)
  434. $pnpDevices = @()
  435. try {
  436. $pnpDevices = @(
  437. Get-CimInstance Win32_PnPEntity |
  438. Where-Object { ([string]$_.Name) -match '(?i)AL[- ]?Link|Anlogic' } |
  439. Sort-Object DeviceID |
  440. ForEach-Object {
  441. [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
  442. }
  443. )
  444. } catch {}
  445. [ordered]@{ serial_ports = @($serialPorts); pnp_devices = @($pnpDevices) } |
  446. ConvertTo-Json -Compress -Depth 4
  447. """.strip()
  448. try:
  449. completed = runner(
  450. ["powershell.exe", "-NoProfile", "-Command", script],
  451. capture_output=True,
  452. text=True,
  453. check=False,
  454. timeout=20,
  455. )
  456. except (OSError, subprocess.TimeoutExpired) as exc:
  457. return {
  458. "status": "blocked_hardware_enumeration_failed",
  459. "opened_com": False,
  460. "opened_jtag": False,
  461. "serial_ports": [],
  462. "pnp_devices": [],
  463. "error": str(exc),
  464. }
  465. if completed.returncode != 0:
  466. return {
  467. "status": "blocked_hardware_enumeration_failed",
  468. "opened_com": False,
  469. "opened_jtag": False,
  470. "serial_ports": [],
  471. "pnp_devices": [],
  472. "error": f"PowerShell enumeration exited {completed.returncode}",
  473. }
  474. try:
  475. payload = json.loads(completed.stdout)
  476. except (TypeError, json.JSONDecodeError) as exc:
  477. return {
  478. "status": "blocked_hardware_enumeration_failed",
  479. "opened_com": False,
  480. "opened_jtag": False,
  481. "serial_ports": [],
  482. "pnp_devices": [],
  483. "error": f"invalid enumeration JSON: {exc}",
  484. }
  485. def records(name: str) -> list[dict[str, str]]:
  486. raw = payload.get(name, []) if isinstance(payload, dict) else []
  487. if isinstance(raw, dict):
  488. raw = [raw]
  489. if not isinstance(raw, list):
  490. return []
  491. return [
  492. {"name": str(item.get("name", "")), "device_id": str(item.get("device_id", ""))}
  493. for item in raw
  494. if isinstance(item, dict)
  495. ]
  496. serial_ports = records("serial_ports")
  497. key_order: list[tuple[str, ...]] = []
  498. best: dict[tuple[str, ...], dict[str, str]] = {}
  499. def score(record: dict[str, str]) -> tuple[int, int, int]:
  500. name = record["name"].strip()
  501. device_id = record["device_id"].strip()
  502. generic_name = re.fullmatch(r"COM[0-9]+", name, re.IGNORECASE) is not None
  503. generic_device = re.fullmatch(r"COM[0-9]+", device_id, re.IGNORECASE) is not None
  504. return (0 if generic_device else 1, 0 if generic_name else 1, len(name) + len(device_id))
  505. for record in serial_ports:
  506. combined = f"{record['name']} {record['device_id']}"
  507. match = re.search(r"(?<![A-Z0-9])COM([0-9]+)(?![0-9])", combined.upper())
  508. key = (
  509. ("com", str(int(match.group(1))))
  510. if match
  511. else ("record", record["name"].casefold(), record["device_id"].casefold())
  512. )
  513. if key not in best:
  514. key_order.append(key)
  515. best[key] = record
  516. elif score(record) > score(best[key]):
  517. best[key] = record
  518. return {
  519. "status": "pass",
  520. "opened_com": False,
  521. "opened_jtag": False,
  522. "dtr_rts_toggled": False,
  523. "serial_ports": [best[key] for key in key_order],
  524. "pnp_devices": records("pnp_devices"),
  525. }
  526. def _record_text(record: Any) -> str:
  527. if not isinstance(record, dict):
  528. return ""
  529. return " ".join(str(record.get(field, "")) for field in ("name", "device_id"))
  530. def run_preflight(
  531. *,
  532. enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
  533. ) -> dict[str, Any]:
  534. try:
  535. enumeration = enumerator()
  536. except Exception as exc:
  537. enumeration = {
  538. "status": "blocked_hardware_enumeration_failed",
  539. "opened_com": False,
  540. "opened_jtag": False,
  541. "serial_ports": [],
  542. "pnp_devices": [],
  543. "error": str(exc),
  544. }
  545. serial_ports = enumeration.get("serial_ports", []) if isinstance(enumeration, dict) else []
  546. pnp_devices = enumeration.get("pnp_devices", []) if isinstance(enumeration, dict) else []
  547. if not isinstance(serial_ports, list):
  548. serial_ports = []
  549. if not isinstance(pnp_devices, list):
  550. pnp_devices = []
  551. com5_present = any(
  552. re.search(r"(?<![A-Z0-9])COM5(?![0-9])", _record_text(record).upper())
  553. for record in serial_ports
  554. )
  555. al_link_present = any(
  556. any(
  557. marker in re.sub(r"[^a-z0-9]", "", _record_text(record).casefold())
  558. for marker in ("allink", "anlogic")
  559. )
  560. for record in pnp_devices
  561. )
  562. opened_com = enumeration.get("opened_com") is True
  563. opened_jtag = enumeration.get("opened_jtag") is True
  564. dtr_rts_toggled = enumeration.get("dtr_rts_toggled") is True
  565. failures: list[str] = []
  566. if enumeration.get("status") != "pass":
  567. failures.append("hardware_enumeration_failed")
  568. if opened_com:
  569. failures.append("enumerator_opened_com")
  570. if opened_jtag:
  571. failures.append("enumerator_opened_jtag")
  572. if dtr_rts_toggled:
  573. failures.append("enumerator_toggled_dtr_rts")
  574. if not com5_present:
  575. failures.append("com5_not_found")
  576. if not al_link_present:
  577. failures.append("al_link_not_found")
  578. return {
  579. "schema": "prod2u-p4-normal-v3-preflight-v2",
  580. "status": "pass" if not failures else "blocked_hardware_not_ready",
  581. "serial": {
  582. "port": PORT,
  583. "baud": BAUD,
  584. "format": "8N1",
  585. "com5_present": com5_present,
  586. "ports": serial_ports,
  587. "opened": opened_com,
  588. "dtr_rts_toggled": dtr_rts_toggled,
  589. },
  590. "jtag": {
  591. "adapter": "AL-Link",
  592. "speed_hz": 200000,
  593. "al_link_present": al_link_present,
  594. "devices": pnp_devices,
  595. "opened": opened_jtag,
  596. },
  597. "hardware_opened": opened_com or opened_jtag,
  598. "program_sram_attempted": False,
  599. "failures": sorted(set(failures)),
  600. }
  601. def _live_request(args: argparse.Namespace, endpoint: Any) -> dict[str, Any]:
  602. session = NormalSession(endpoint)
  603. if args.command == "set-all-outputs":
  604. request = build_output_snapshot(
  605. ptc_percent=(args.ptc,) * 24,
  606. fan_percent=(args.fan,) * 4,
  607. solenoid=args.solenoid,
  608. xyz=(args.x, args.y, args.z),
  609. )
  610. requested_hash = state_hash16(
  611. ptc_percent=(args.ptc,) * 24,
  612. fan_percent=(args.fan,) * 4,
  613. solenoid=args.solenoid,
  614. )
  615. result = session.command(
  616. request,
  617. expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
  618. expected_state_hash16=None,
  619. required_result_flags=0x01,
  620. allowed_result_flags=0x0F,
  621. )
  622. if result.ack.detail & 0x80:
  623. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
  624. if result.ack.status == StatusCode.OK and result.ack.detail != 0:
  625. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
  626. if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
  627. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK is missing skip detail")
  628. busy_mask = result.ack.detail & 0x07
  629. invalid_mask = (result.ack.detail >> 3) & 0x07
  630. solenoid_skipped = bool(result.ack.detail & 0x40)
  631. if busy_mask & invalid_mask:
  632. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
  633. if not solenoid_skipped and result.ack.state_hash16 != requested_hash:
  634. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK state hash does not match applied outputs")
  635. accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
  636. expected_result_flags = 0x01 | (accepted_or_noop_mask << 1)
  637. if result.ack.result_flags != expected_result_flags:
  638. session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
  639. return {"status": "pass", "ack": result.ack.__dict__}
  640. if args.command == "jog":
  641. result = session.command(
  642. build_motor_jog(
  643. axis=args.axis,
  644. raw_dir=args.raw_dir,
  645. speed_code=args.speed_code,
  646. steps=args.steps,
  647. ),
  648. expected_command=MotionOpcode.JOG,
  649. allowed_statuses=(StatusCode.OK,),
  650. expected_detail=0,
  651. allowed_result_flags=0,
  652. )
  653. return {"status": "pass", "ack": result.ack.__dict__}
  654. if args.command == "get-status":
  655. result = session.command(
  656. build_host_command(command=CommandId.GET_STATUS),
  657. expected_command=CommandId.GET_STATUS,
  658. allowed_statuses=(StatusCode.OK,),
  659. allowed_result_flags=0,
  660. )
  661. if result.ack.detail & ~0x03:
  662. session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
  663. return {
  664. "status": "pass",
  665. "ack": result.ack.__dict__,
  666. "disabled": bool(result.ack.detail & 0x01),
  667. "watchdog_timeout": bool(result.ack.detail & 0x02),
  668. }
  669. if args.command == "motor-status":
  670. result = session.motor_status()
  671. return {
  672. "status": "pass",
  673. "ack": result.ack.__dict__,
  674. "motor_status": result.status.__dict__,
  675. }
  676. if args.command == "disable":
  677. result = session.command(
  678. build_host_command(command=CommandId.DISABLE),
  679. expected_command=CommandId.DISABLE,
  680. allowed_statuses=(StatusCode.OK,),
  681. expected_detail=0x01,
  682. expected_state_hash16=SAFE_STATE_HASH16,
  683. allowed_result_flags=0,
  684. )
  685. return {"status": "pass", "ack": result.ack.__dict__}
  686. raise RuntimeError(f"unsupported live command: {args.command}")
  687. def main(argv: list[str] | None = None) -> int:
  688. args = build_parser().parse_args(argv)
  689. if args.command == "selftest":
  690. result = _selftest()
  691. elif args.command == "preflight":
  692. result = run_preflight()
  693. else:
  694. endpoint = open_com5()
  695. try:
  696. result = _live_request(args, endpoint)
  697. finally:
  698. endpoint.close()
  699. print(json.dumps(result, indent=2, default=lambda value: int(value), ensure_ascii=False))
  700. return 0 if result.get("status") == "pass" else 1
  701. if __name__ == "__main__":
  702. raise SystemExit(main())