#!/usr/bin/env python3 """Reference model for the Prod2U door-percent SET_ALL / status contract. Reads ``projects/prod2u-door-temp/project.json`` when present, but stays resilient if another agent is mid-edit: door fields are always percent 0..100, and frame types ``0x03`` / ``0x83`` are always accepted even when ``project.json`` still lists the legacy jog-only command table. """ from __future__ import annotations from dataclasses import dataclass from enum import IntEnum, IntFlag import json from pathlib import Path from typing import Iterable, Sequence _PROJECT_PATH = Path(__file__).resolve().parents[1] / "projects" / "prod2u-door-temp" / "project.json" try: _PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): _PROJECT = {} _OUTPUTS = _PROJECT.get("outputs", {}) _PROTOCOL = _PROJECT.get("protocol", {}) _SET_ALL = _PROTOCOL.get("set_all", {}) _CRC = _PROTOCOL.get("crc", {}) _COMMANDS = _PROTOCOL.get("commands", {}) _TEMPERATURE = _PROJECT.get("temperature", {}) FRAME_HEADER = bytes.fromhex(_PROTOCOL.get("header_hex", "A55A")) CHAMBER_PTC_COUNT = int(_OUTPUTS.get("chamber_ptc_count", _SET_ALL.get("chamber_ptc_count", 4))) FAN_COUNT = len(_OUTPUTS.get("fan_channels", [0, 1, 2, 3])) or 4 TEMPERATURE_COUNT = int(_TEMPERATURE.get("value_count", 27)) SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("payload_length", 11)) LEGACY_SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("legacy_payload_length_rejected", 14)) DUTY_MIN = int(_SET_ALL.get("duty_min", 0)) DUTY_MAX = int(_SET_ALL.get("duty_max", 100)) DOOR_PERCENT_MIN = 0 DOOR_PERCENT_MAX = 100 MOTOR_STATUS_PAYLOAD_LENGTH = 31 MOTOR_STATUS_FRAME_LENGTH = MOTOR_STATUS_PAYLOAD_LENGTH + 6 AXIS_STATUS_BYTES = 10 CRC_POLYNOMIAL = int(_CRC.get("polynomial", 4129)) CRC_INITIAL = int(_CRC.get("initial", 65535)) # Golden GET_MOTOR_STATUS request (empty payload). GET_MOTOR_STATUS_GOLDEN = bytes.fromhex("A55A03005C48") class FrameType(IntEnum): SET_ALL = int(_COMMANDS.get("set_all", 0x01)) GET_TEMPERATURE = int(_COMMANDS.get("get_temperature", 0x02)) GET_MOTOR_STATUS = int(_COMMANDS.get("get_motor_status", 0x03)) TEMPERATURE_DATA = int(_COMMANDS.get("temperature_data", 0x82)) MOTOR_STATUS_DATA = int(_COMMANDS.get("motor_status_data", 0x83)) class AxisState(IntEnum): CAL_SEEK_CLOSE = 0 CAL_MEASURE_OPEN = 1 IDLE = 2 MOVE_OPEN = 3 MOVE_CLOSE = 4 WAIT_REPLAN = 5 FAULT = 6 class AxisFlags(IntFlag): OPEN_LIMIT = 0x01 CLOSE_LIMIT = 0x02 CALIBRATED = 0x04 MOVING = 0x08 ENDPOINT_MODE = 0x10 TARGET_VALID = 0x20 REPLAN_PENDING = 0x40 RESERVED = 0x80 class FaultCode(IntEnum): NONE = 0 BOTH_LIMITS_ACTIVE = 1 CAL_CLOSE_TIMEOUT = 2 CAL_OPEN_TIMEOUT = 3 INVALID_ZERO_OR_TINY_TRAVEL = 4 ENDPOINT_TIMEOUT = 5 class GlobalStatusBits(IntFlag): X_CALIBRATED = 0x01 Y_CALIBRATED = 0x02 Z_CALIBRATED = 0x04 X_FAULT = 0x08 Y_FAULT = 0x10 Z_FAULT = 0x20 STARTUP_COMPLETE = 0x40 WATCHDOG_TRIPPED = 0x80 class ProtocolError(ValueError): """Raised when a frame violates the frozen protocol contract.""" @dataclass(frozen=True) class Frame: frame_type: FrameType payload: bytes @dataclass(frozen=True) class AxisMotorStatus: state: AxisState flags: AxisFlags requested_percent: int current_position: int target_position: int travel_steps: int fault_code: FaultCode @dataclass(frozen=True) class MotorStatus: global_status: GlobalStatusBits x: AxisMotorStatus y: AxisMotorStatus z: AxisMotorStatus @property def startup_complete(self) -> bool: return bool(self.global_status & GlobalStatusBits.STARTUP_COMPLETE) @property def watchdog_tripped(self) -> bool: return bool(self.global_status & GlobalStatusBits.WATCHDOG_TRIPPED) def mid_target(travel: int, percent: int) -> int: """Half-up mid-position clamp; same contract as ``door_percent_planner_ref``.""" if not isinstance(travel, int) or not isinstance(percent, int): raise ValueError("travel and percent must be integers") if travel < 2: raise ValueError("travel must be >= 2 for mid targets") if not 1 <= percent <= 99: raise ValueError("mid percent must be in the range 1..99") return max(1, min(travel - 1, (travel * percent + 50) // 100)) def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int: crc = CRC_INITIAL for value in data: crc ^= (int(value) & 0xFF) << 8 for _ in range(8): crc = ((crc << 1) ^ CRC_POLYNOMIAL) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def _coerce_type(value: int | FrameType) -> FrameType: try: return FrameType(int(value)) except (TypeError, ValueError) as exc: raise ProtocolError(f"unsupported frame type: {value!r}") from exc def _expected_length(frame_type: FrameType) -> int: return { FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH, FrameType.GET_TEMPERATURE: 0, FrameType.GET_MOTOR_STATUS: 0, FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT, FrameType.MOTOR_STATUS_DATA: MOTOR_STATUS_PAYLOAD_LENGTH, }[frame_type] def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray | Sequence[int]) -> bytes: kind = _coerce_type(frame_type) body = bytes(payload) expected = _expected_length(kind) if len(body) != expected: raise ProtocolError(f"{kind.name} payload must be {expected} bytes") crc = crc16_ccitt_false(bytes((int(kind), len(body))) + body) return FRAME_HEADER + bytes((int(kind), len(body))) + body + crc.to_bytes(2, "little") def decode_frame(raw: bytes | bytearray) -> Frame: packet = bytes(raw) if len(packet) < 6 or packet[:2] != FRAME_HEADER: raise ProtocolError("invalid frame header or length") try: kind = FrameType(packet[2]) except ValueError as exc: raise ProtocolError(f"unsupported frame type: 0x{packet[2]:02X}") from exc payload_length = packet[3] if len(packet) != payload_length + 6: raise ProtocolError("frame length mismatch") payload = packet[4 : 4 + payload_length] expected = _expected_length(kind) if payload_length != expected: raise ProtocolError(f"{kind.name} payload must be {expected} bytes") actual_crc = int.from_bytes(packet[-2:], "little") expected_crc = crc16_ccitt_false(packet[2:-2]) if actual_crc != expected_crc: raise ProtocolError("CRC mismatch") return Frame(kind, payload) def _checked_duty_bytes(values: Iterable[int], count: int, name: str) -> bytes: items = tuple(values) if len(items) != count: raise ValueError(f"{name} must contain {count} bytes") if any(not isinstance(value, int) or not DUTY_MIN <= value <= DUTY_MAX for value in items): raise ValueError(f"{name} values must be in the range {DUTY_MIN}..{DUTY_MAX}") return bytes(items) def _checked_temperature_bytes(values: Iterable[int]) -> bytes: items = tuple(values) if len(items) != TEMPERATURE_COUNT: raise ValueError(f"temperature must contain {TEMPERATURE_COUNT} bytes") if any(not isinstance(value, int) or not 0 <= value <= 0xFF for value in items): raise ValueError("temperature values must be in the range 0..255") return bytes(items) def _checked_door_percent(value: int, name: str) -> int: if not isinstance(value, int) or not DOOR_PERCENT_MIN <= value <= DOOR_PERCENT_MAX: raise ValueError(f"{name} must be in the range {DOOR_PERCENT_MIN}..{DOOR_PERCENT_MAX}") return value def build_set_all( fan: Iterable[int], chamber_ptc: Iterable[int], z_percent: int, x_percent: int, y_percent: int, ) -> bytes: z_percent = _checked_door_percent(z_percent, "z_percent") x_percent = _checked_door_percent(x_percent, "x_percent") y_percent = _checked_door_percent(y_percent, "y_percent") payload = _checked_duty_bytes(fan, FAN_COUNT, "fan") payload += _checked_duty_bytes(chamber_ptc, CHAMBER_PTC_COUNT, "chamber ptc") payload += bytes((z_percent, x_percent, y_percent)) return encode_frame(FrameType.SET_ALL, payload) def build_get_temperature() -> bytes: return encode_frame(FrameType.GET_TEMPERATURE, b"") def build_get_motor_status() -> bytes: frame = encode_frame(FrameType.GET_MOTOR_STATUS, b"") if frame != GET_MOTOR_STATUS_GOLDEN: raise ProtocolError( f"GET_MOTOR_STATUS golden mismatch: got {frame.hex(' ').upper()}, " f"expected {GET_MOTOR_STATUS_GOLDEN.hex(' ').upper()}" ) return frame def build_temperature_data(values: Iterable[int]) -> bytes: return encode_frame(FrameType.TEMPERATURE_DATA, _checked_temperature_bytes(values)) def decode_temperature_data(frame: Frame) -> tuple[int, ...]: if frame.frame_type is not FrameType.TEMPERATURE_DATA: raise ProtocolError("frame is not TEMPERATURE_DATA") return tuple(frame.payload) def _u16_le(payload: bytes, offset: int) -> int: return int.from_bytes(payload[offset : offset + 2], "little") def _parse_axis_status(raw: bytes) -> AxisMotorStatus: if len(raw) != AXIS_STATUS_BYTES: raise ProtocolError(f"axis status must be {AXIS_STATUS_BYTES} bytes") try: state = AxisState(raw[0]) except ValueError as exc: raise ProtocolError(f"unsupported axis state: 0x{raw[0]:02X}") from exc flags = AxisFlags(raw[1]) if flags & AxisFlags.RESERVED: raise ProtocolError("axis flags reserved bit must be 0") requested = raw[2] if not DOOR_PERCENT_MIN <= requested <= DOOR_PERCENT_MAX: raise ProtocolError(f"requested_percent out of range: {requested}") try: fault = FaultCode(raw[9]) except ValueError as exc: raise ProtocolError(f"unsupported fault_code: 0x{raw[9]:02X}") from exc return AxisMotorStatus( state=state, flags=flags, requested_percent=requested, current_position=_u16_le(raw, 3), target_position=_u16_le(raw, 5), travel_steps=_u16_le(raw, 7), fault_code=fault, ) def decode_motor_status_data(frame: Frame | bytes | bytearray) -> MotorStatus: if isinstance(frame, (bytes, bytearray)): frame = decode_frame(frame) if frame.frame_type is not FrameType.MOTOR_STATUS_DATA: raise ProtocolError("frame is not MOTOR_STATUS_DATA") payload = frame.payload if len(payload) != MOTOR_STATUS_PAYLOAD_LENGTH: raise ProtocolError(f"MOTOR_STATUS_DATA payload must be {MOTOR_STATUS_PAYLOAD_LENGTH} bytes") return MotorStatus( global_status=GlobalStatusBits(payload[0]), x=_parse_axis_status(payload[1:11]), y=_parse_axis_status(payload[11:21]), z=_parse_axis_status(payload[21:31]), ) def build_motor_status_data( global_status: int, x: AxisMotorStatus | Sequence[int] | bytes, y: AxisMotorStatus | Sequence[int] | bytes, z: AxisMotorStatus | Sequence[int] | bytes, ) -> bytes: """Encode a 31-byte MOTOR_STATUS_DATA frame (host/sim helper).""" def _axis_bytes(axis: AxisMotorStatus | Sequence[int] | bytes) -> bytes: if isinstance(axis, AxisMotorStatus): if axis.flags & AxisFlags.RESERVED: raise ValueError("axis flags reserved bit must be 0") return bytes( ( int(axis.state) & 0xFF, int(axis.flags) & 0xFF, int(axis.requested_percent) & 0xFF, ) ) + int(axis.current_position).to_bytes(2, "little") + int(axis.target_position).to_bytes( 2, "little" ) + int(axis.travel_steps).to_bytes(2, "little") + bytes((int(axis.fault_code) & 0xFF,)) raw = bytes(axis) if len(raw) != AXIS_STATUS_BYTES: raise ValueError(f"axis status must be {AXIS_STATUS_BYTES} bytes") return raw payload = bytes((int(global_status) & 0xFF,)) + _axis_bytes(x) + _axis_bytes(y) + _axis_bytes(z) return encode_frame(FrameType.MOTOR_STATUS_DATA, payload) SET_ALL_6400_PAYLOAD_LENGTH = 32 PTC_6400_COUNT = 24 FAN_6400_COUNT = 8 def encode_frame_raw(frame_type: int, payload: bytes | bytearray | Sequence[int]) -> bytes: """Shared A5 5A / CRC-16/CCITT-FALSE encoder without project length tables.""" body = bytes(payload) crc = crc16_ccitt_false(bytes((int(frame_type) & 0xFF, len(body))) + body) return FRAME_HEADER + bytes((int(frame_type) & 0xFF, len(body))) + body + crc.to_bytes(2, "little") def build_set_all_6400(ptc: Iterable[int], fan: Iterable[int]) -> bytes: """6400 SET_ALL: 24 PTC then 8 FAN, chamber-major intake/exhaust.""" payload = _checked_duty_bytes(ptc, PTC_6400_COUNT, "ptc") payload += _checked_duty_bytes(fan, FAN_6400_COUNT, "fan") if len(payload) != SET_ALL_6400_PAYLOAD_LENGTH: raise ValueError("6400 SET_ALL payload must be 32 bytes") return encode_frame_raw(int(FrameType.SET_ALL), payload) encode_frame_untyped = encode_frame_raw