prod2u_p4_cli.py 27 KB

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