#!/usr/bin/env python3 """Minimal ACK-only host tooling for Prod2U Profile 4 binary921-v3.""" from __future__ import annotations import argparse import json import re import subprocess import threading import time from dataclasses import dataclass from pathlib import Path from typing import Any, Callable from prod2u_p4_protocol import ( CRC_LEN, HEADER_LEN, MAGIC, CommandId, FrameType, HostAck, MotionOpcode, MotionStatus, P4Frame, P4FrameError, StatusCode, build_get_motor_status, build_host_command, build_motor_jog, build_output_snapshot, decode_frame, decode_host_ack, decode_motion_status, state_hash16, ) PROFILE = "prod2u-p4-normal-actuator-binary921-v3" PROFILE_ID = 4 PROTOCOL_VERSION = 2 PORT = "COM5" BAUD = 921600 SAFE_STATE_HASH16 = state_hash16( ptc_percent=(0,) * 24, fan_percent=(30,) * 4, solenoid=0, ) @dataclass(frozen=True) class CommandResult: ack: HostAck raw_response: bytes frames: tuple[P4Frame, ...] @dataclass(frozen=True) class MotorStatusResult: ack: HostAck status: MotionStatus raw_response: bytes 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 UART 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, ) -> 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") 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._terminated = False self._command_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._monotonic = monotonic self._sleep = sleep @property def rx_journal(self) -> bytes: return bytes(self._rx_journal) @property def last_exchange(self) -> dict[str, Any] | None: return None if self._last_exchange is None else dict(self._last_exchange) @property def best_effort_disable_exchange(self) -> dict[str, Any] | None: return ( None if self._best_effort_disable_exchange is None else dict(self._best_effort_disable_exchange) ) def close(self) -> None: close = getattr(self.endpoint, "close", None) if callable(close): close() def _write_exact(self, data: bytes) -> None: written = self.endpoint.write(data) if written != len(data): raise IOError(f"short serial write: expected {len(data)}, got {written}") def _read_frame(self, *, deadline: float) -> P4Frame: while self._monotonic() < deadline: if len(self._rx_buffer) >= HEADER_LEN + CRC_LEN: if self._rx_buffer[:2] != MAGIC: raise RuntimeError("unexpected bytes before Profile 4 response") frame_length = HEADER_LEN + self._rx_buffer[13] + CRC_LEN if len(self._rx_buffer) >= frame_length: raw = bytes(self._rx_buffer[:frame_length]) del self._rx_buffer[:frame_length] try: return decode_frame(raw) except P4FrameError as exc: raise RuntimeError(f"invalid Profile 4 response: {exc}") from exc chunk = bytes(self.endpoint.read(256)) if chunk: self._rx_buffer.extend(chunk) self._rx_journal.extend(chunk) continue self._sleep(0.0005) raise TimeoutError("ACK timeout") def _attempt_disable(self) -> None: if self.disable_attempted: return self.disable_attempted = True request = build_host_command(command=CommandId.DISABLE) try: self._write_exact(request) self._best_effort_disable_exchange = {"request_hex": request.hex()} except Exception as exc: # pragma: no cover - best effort only self._best_effort_disable_exchange = { "request_hex": request.hex(), "error": str(exc), } def _require_quiet_tail(self) -> None: if self._rx_buffer: raise RuntimeError("unexpected bytes after completed response") started = self._monotonic() quiet_deadline = started + self.quiet_window_seconds hard_deadline = started + self.max_quiet_drain_seconds while self._monotonic() < quiet_deadline and self._monotonic() < hard_deadline: chunk = bytes(self.endpoint.read(256)) if chunk: self._rx_journal.extend(chunk) raise RuntimeError("unexpected bytes after completed response") self._sleep(0.0005) def _fail(self, expected_command: CommandId | int, message: str) -> None: self._terminated = True if int(expected_command) == int(CommandId.DISABLE): self.disable_attempted = True else: self._attempt_disable() self._rx_buffer.clear() raise RuntimeError(message) def collect_available(self) -> bytes: collected = bytearray() while True: chunk = bytes(self.endpoint.read(256)) if not chunk: break collected.extend(chunk) self._rx_journal.extend(chunk) return bytes(collected) def drain_unparsed(self, *, timeout_seconds: float | None = None) -> bytes: duration = self.quiet_window_seconds if timeout_seconds is None else timeout_seconds if duration < 0: raise ValueError("timeout_seconds must be non-negative") deadline = self._monotonic() + duration collected = bytearray(self._rx_buffer) self._rx_buffer.clear() while self._monotonic() < deadline: chunk = bytes(self.endpoint.read(256)) if chunk: collected.extend(chunk) self._rx_journal.extend(chunk) deadline = self._monotonic() + self.quiet_window_seconds else: self._sleep(0.0005) return bytes(collected) @staticmethod def _validate_ack( ack: HostAck, *, expected_command: CommandId | MotionOpcode | int, allowed_statuses: tuple[StatusCode, ...], expected_detail: int | None, expected_state_hash16: int | None, expected_response_type: FrameType | int, required_result_flags: int, allowed_result_flags: int, ) -> None: if int(ack.command) != int(expected_command): raise RuntimeError("ACK command mismatch") if ack.status not in allowed_statuses: raise RuntimeError(f"unexpected ACK status: {ack.status.name}") expected_ok = ack.status in (StatusCode.OK, StatusCode.PARTIAL) if ack.ok != expected_ok: raise RuntimeError("ACK ok/status mismatch") if expected_detail is not None and ack.detail != expected_detail: raise RuntimeError("ACK detail mismatch") if expected_state_hash16 is not None and ack.state_hash16 != expected_state_hash16: raise RuntimeError("ACK state hash mismatch") if int(ack.response_type) != int(expected_response_type): raise RuntimeError("ACK response type mismatch") if ack.result_flags & ~allowed_result_flags: raise RuntimeError("ACK contains disallowed result flags") if ack.result_flags & required_result_flags != required_result_flags: raise RuntimeError("ACK is missing required result flags") def _begin(self) -> None: if self._terminated: raise RuntimeError("session is terminated") if not self._command_lock.acquire(blocking=False): raise RuntimeError("only one outstanding command is allowed") def _abort(self, expected_command: CommandId | MotionOpcode | int) -> None: self._terminated = True if int(expected_command) == int(CommandId.DISABLE): self.disable_attempted = True else: self._attempt_disable() def command( self, request: bytes, *, expected_command: CommandId | MotionOpcode | int, 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 = 0xFF, ) -> CommandResult: self._begin() try: try: self._write_exact(request) frame = self._read_frame(deadline=self._monotonic() + self.timeout_seconds) if frame.frame_type != FrameType.HOST_ACK: raise RuntimeError("first response must be HOST_ACK") try: ack = decode_host_ack(frame) except ValueError as exc: raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc self._validate_ack( ack, expected_command=expected_command, allowed_statuses=allowed_statuses, expected_detail=expected_detail, expected_state_hash16=expected_state_hash16, expected_response_type=0, required_result_flags=required_result_flags, allowed_result_flags=allowed_result_flags, ) self._require_quiet_tail() result = CommandResult(ack=ack, raw_response=frame.raw, frames=(frame,)) self._last_exchange = { "request_hex": request.hex(), "response_hex": frame.raw.hex(), } return result except BaseException: self._abort(expected_command) raise finally: self._command_lock.release() def motor_status(self) -> MotorStatusResult: request = build_get_motor_status() expected_command = MotionOpcode.GET_MOTOR_STATUS self._begin() try: try: self._write_exact(request) deadline = self._monotonic() + self.timeout_seconds ack_frame = self._read_frame(deadline=deadline) if ack_frame.frame_type != FrameType.HOST_ACK: raise RuntimeError("first response must be HOST_ACK") try: ack = decode_host_ack(ack_frame) except ValueError as exc: raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc self._validate_ack( ack, expected_command=expected_command, allowed_statuses=(StatusCode.OK,), expected_detail=0, expected_state_hash16=None, expected_response_type=FrameType.MOTION_STATUS, required_result_flags=0x08, allowed_result_flags=0x08, ) status_frame = self._read_frame(deadline=deadline) if status_frame.frame_type != FrameType.MOTION_STATUS: raise RuntimeError("HOST_ACK must be followed by MOTION_STATUS") try: status = decode_motion_status(status_frame) except ValueError as exc: raise RuntimeError(f"malformed MOTION_STATUS: {exc}") from exc self._require_quiet_tail() raw = ack_frame.raw + status_frame.raw self._last_exchange = { "request_hex": request.hex(), "response_hex": raw.hex(), } return MotorStatusResult(ack=ack, status=status, raw_response=raw) except BaseException: self._abort(expected_command) raise finally: self._command_lock.release() 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 PTC, fan, and solenoid. Legacy X/Y/Z bytes remain on the wire but " "accept any byte value and have no motor effect." ), ) 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, 255), default=0) snapshot.add_argument("--y", type=_bounded_int(0, 255), default=0) snapshot.add_argument("--z", type=_bounded_int(0, 255), default=0) jog = sub.add_parser( "jog", description=( "The only motor-driving command. Executes the full 1..65535 step field " "at fixed 1000 step/s; speed_code is validated then ignored. ACK follows " "the first emitted STEP." ), ) jog.add_argument("--axis", type=_bounded_int(0, 1), 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) sub.add_parser("get-status") sub.add_parser("motor-status") sub.add_parser("disable") 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), ) jog = build_motor_jog(axis=1, raw_dir=1, speed_code=3, steps=65535) return { "schema": "prod2u-p4-normal-v3-selftest-v2", "status": "pass" if len(snapshot) == 50 and len(jog) == 24 else "fail", "profile": PROFILE, "profile_id": PROFILE_ID, "protocol_version": PROTOCOL_VERSION, "baud": BAUD, "port": PORT, "jog_request_steps_max": 65535, "jog_executed_steps": "requested_u16_without_cap", "jog_effective_step_rate_hz": 1000, "jog_ack_semantics": "FIRST_STEP_EMITTED", "hardware_opened": False, "program_sram_attempted": False, } 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") key_order: list[tuple[str, ...]] = [] best: dict[tuple[str, ...], dict[str, str]] = {} def 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"(? score(best[key]): best[key] = record return { "status": "pass", "opened_com": False, "opened_jtag": False, "dtr_rts_toggled": False, "serial_ports": [best[key] for key in key_order], "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"(? 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), ) requested_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=requested_hash, allowed_statuses=(StatusCode.OK,), expected_detail=0, required_result_flags=0x01, allowed_result_flags=0x01, ) return {"status": "pass", "ack": result.ack.__dict__} if args.command == "jog": result = session.command( build_motor_jog( axis=args.axis, raw_dir=args.raw_dir, speed_code=args.speed_code, steps=args.steps, ), expected_command=MotionOpcode.JOG, allowed_statuses=(StatusCode.OK,), expected_detail=0, allowed_result_flags=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, allowed_result_flags=0, ) 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() else: endpoint = open_com5() try: result = _live_request(args, endpoint) finally: endpoint.close() 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())