#!/usr/bin/env python3 """Prod2U Profile 4 Normal binary921-v3 wire protocol helpers. Host request frame types and payload layouts are intentionally frozen. The temperature command is the sole exception on the response side: it returns a compact 35-byte frame instead of a normal 14-byte-header Binary921 frame. """ from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing import Iterable PROTOCOL_ID = "binary921-v3" MAGIC = b"\xA5\x5A" VERSION = 2 PROFILE_ID = 4 HEADER_LEN = 14 CRC_LEN = 2 MAX_PAYLOAD_LEN = 255 HOST_CMD_PAYLOAD_LEN = 4 HOST_ACK_PAYLOAD_LEN = 8 OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34 MOTION_COMMAND_PAYLOAD_LEN = 8 MOTION_STATUS_PAYLOAD_LEN = 10 PTC_CHANNEL_COUNT = 24 FAN_CHANNEL_COUNT = 4 TEMPERATURE_VALUE_COUNT = 27 TEMPERATURE_RESPONSE_TYPE = 0x10 TEMPERATURE_RESPONSE_LEN = 6 + TEMPERATURE_VALUE_COUNT + CRC_LEN class P4FrameError(ValueError): """Raised when a Profile 4 frame cannot be decoded safely.""" class FrameType(IntEnum): HOST_CMD = 0x05 HOST_ACK = 0x06 HOST_BATCH_CMD = 0x07 MOTION_CMD = 0x11 MOTION_STATUS = 0x12 class CommandId(IntEnum): GET_STATUS = 0x24 DISABLE = 0x26 GET_TEMPERATURES = 0x28 SET_OUTPUT_SNAPSHOT = 0x2A class MotionOpcode(IntEnum): JOG = 0x35 MARK_CLOSED = 0x36 GET_MOTOR_STATUS = 0x37 class StatusCode(IntEnum): OK = 0x00 UNSUPPORTED_IN_PROFILE = 0x01 BAD_FLAGS = 0x02 BAD_LENGTH = 0x03 BAD_VALUE = 0x05 BUSY = 0x09 TEMPERATURE_BUS_ERROR = 0x0A PARTIAL = 0x16 @dataclass(frozen=True) class P4Frame: version: int profile_id: int frame_type: FrameType seq: int timestamp_tick: int payload: bytes crc16: int raw: bytes @dataclass(frozen=True) class HostCommand: command: CommandId channel: int value: int flags: int @dataclass(frozen=True) class HostAck: ok: bool command: CommandId | MotionOpcode | int status: StatusCode detail: int state_hash16: int response_type: FrameType | int result_flags: int request_seq: int | None @dataclass(frozen=True) class OutputSnapshot: ptc_percent: tuple[int, ...] fan_percent: tuple[int, ...] solenoid: int xyz: tuple[int, int, int] state_hash16: int @dataclass(frozen=True) class MotionCommand: opcode: MotionOpcode axis: int raw_dir: int speed_code: int steps: int @dataclass(frozen=True) class MotionStatus: flags: int position_valid_mask: int busy_mask: int current_xyz: tuple[int, int, int] target_xyz: tuple[int, int, int] fault_mask: int def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int: """Return CRC-16/CCITT-FALSE for *data*.""" crc = initial & 0xFFFF for byte in bytes(data): crc ^= byte << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def _u8(value: int, name: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF: raise ValueError(f"{name} must fit in one byte") return value def _u16(value: int, name: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF: raise ValueError(f"{name} must fit in 16 bits") return value def _u32(value: int, name: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF: raise ValueError(f"{name} must fit in 32 bits") return value def encode_frame( *, frame_type: FrameType | int, seq: int, timestamp_tick: int, payload: bytes | bytearray | Iterable[int], ) -> bytes: payload_bytes = bytes(payload) if len(payload_bytes) > MAX_PAYLOAD_LEN: raise ValueError("payload too long for binary921-v3") try: typed_frame = FrameType(int(frame_type)) except (TypeError, ValueError) as exc: raise ValueError(f"unknown Profile 4 frame type: {frame_type}") from exc seq = _u32(seq, "seq") timestamp_tick = _u32(timestamp_tick, "timestamp_tick") if seq != 0: raise ValueError("binary921-v3 seq must be zero") if timestamp_tick != 0: raise ValueError("binary921-v3 timestamp must be zero") body = bytes([VERSION, PROFILE_ID, int(typed_frame)]) body += seq.to_bytes(4, "little") body += timestamp_tick.to_bytes(4, "little") body += bytes([len(payload_bytes)]) + payload_bytes return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little") def decode_frame(frame: bytes | bytearray) -> P4Frame: raw = bytes(frame) if len(raw) < HEADER_LEN + CRC_LEN: raise P4FrameError("short Profile 4 frame") if raw[:2] != MAGIC: raise P4FrameError("bad Profile 4 magic") if raw[2] != VERSION: raise P4FrameError(f"unsupported binary921 version {raw[2]}") if raw[3] != PROFILE_ID: raise P4FrameError(f"unexpected binary921 profile {raw[3]}") payload_len = raw[13] expected_len = HEADER_LEN + payload_len + CRC_LEN if len(raw) != expected_len: raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}") expected_crc = crc16_ccitt(raw[2:-2]) actual_crc = int.from_bytes(raw[-2:], "little") if actual_crc != expected_crc: raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}") if raw[5:9] != b"\x00\x00\x00\x00": raise P4FrameError("binary921-v3 seq must be zero") if raw[9:13] != b"\x00\x00\x00\x00": raise P4FrameError("binary921-v3 timestamp must be zero") try: frame_type = FrameType(raw[4]) except ValueError as exc: raise P4FrameError(f"unknown Profile 4 frame type 0x{raw[4]:02x}") from exc return P4Frame( version=raw[2], profile_id=raw[3], frame_type=frame_type, seq=0, timestamp_tick=0, payload=raw[14:-2], crc16=actual_crc, raw=raw, ) def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]: """Decode complete valid frames while preserving a possible partial tail.""" buf = bytes(data) frames: list[P4Frame] = [] offset = 0 while True: magic_at = buf.find(MAGIC, offset) if magic_at < 0: remaining = buf[offset:] return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b"" if len(buf) - magic_at < HEADER_LEN + CRC_LEN: return frames, buf[magic_at:] end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN if end > len(buf): next_magic = buf.find(MAGIC, magic_at + 1) if next_magic < 0: return frames, buf[magic_at:] offset = next_magic continue try: frames.append(decode_frame(buf[magic_at:end])) offset = end except P4FrameError: offset = magic_at + 1 def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes: if isinstance(value, P4Frame): if value.frame_type != frame_type: raise ValueError(f"expected {frame_type.name} frame") payload = value.payload else: payload = bytes(value) if len(payload) != length: raise ValueError(f"{frame_type.name} payload must be exactly {words}") return payload def _percent_tuple(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]: result = tuple(values) if len(result) != count: raise ValueError(f"snapshot requires exactly {count} {label} values") for index, value in enumerate(result): if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100: raise ValueError(f"{label}[{index}] must be an integer from 0 to 100") return result def _binary_output(value: int, label: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 100): raise ValueError(f"{label} must be 0 or 100") return value def state_hash16( *, ptc_percent: Iterable[int], fan_percent: Iterable[int], solenoid: int, ) -> int: """Hash the currently applied PTC, fan, and solenoid values.""" ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC") fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN") checked_solenoid = _binary_output(solenoid, "solenoid") return crc16_ccitt(bytes(ptc + fan + (checked_solenoid,))) def build_output_snapshot( *, ptc_percent: Iterable[int], fan_percent: Iterable[int], solenoid: int, xyz: Iterable[int], ) -> bytes: ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC") fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN") checked_solenoid = _binary_output(solenoid, "solenoid") xyz_values = tuple(xyz) if len(xyz_values) != 3: raise ValueError("snapshot requires exactly 3 XYZ values") checked_xyz = tuple(_u8(value, "XYZ") for value in xyz_values) payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0)) payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz) return encode_frame( frame_type=FrameType.HOST_BATCH_CMD, seq=0, timestamp_tick=0, payload=payload, ) def decode_output_snapshot(value: P4Frame | bytes | bytearray) -> OutputSnapshot: payload = _payload(value, FrameType.HOST_BATCH_CMD, OUTPUT_SNAPSHOT_PAYLOAD_LEN, "thirty-four bytes") if payload[0] != CommandId.SET_OUTPUT_SNAPSHOT: raise ValueError("HOST_BATCH_CMD command must be SET_OUTPUT_SNAPSHOT") if payload[1] != 0: raise ValueError("SET_OUTPUT_SNAPSHOT flags must be zero") ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC") fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN") solenoid = _binary_output(payload[30], "solenoid") xyz_values = tuple(payload[31:34]) return OutputSnapshot( ptc_percent=ptc, fan_percent=fan, solenoid=solenoid, xyz=(xyz_values[0], xyz_values[1], xyz_values[2]), state_hash16=state_hash16(ptc_percent=ptc, fan_percent=fan, solenoid=solenoid), ) def build_host_command( *, seq: int = 0, command: CommandId | int, channel: int = 0, value: int = 0, flags: int = 0, timestamp_tick: int = 0, ) -> bytes: try: command = CommandId(int(command)) except (TypeError, ValueError) as exc: raise ValueError(f"unknown Profile4 command: {command}") from exc payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")]) return encode_frame( frame_type=FrameType.HOST_CMD, seq=seq, timestamp_tick=timestamp_tick, payload=payload, ) def build_get_temperatures() -> bytes: """Build the exact HOST_CMD request for one on-demand temperature read.""" return build_host_command(command=CommandId.GET_TEMPERATURES) def build_temperature_response(values: bytes | bytearray | Iterable[int]) -> bytes: """Build the compact 35-byte temperature response used by command 0x28.""" try: payload = bytes(values) except (TypeError, ValueError) as exc: raise ValueError("temperature response values must be bytes") from exc if len(payload) != TEMPERATURE_VALUE_COUNT: raise ValueError("temperature response requires exactly 27 values") body = bytes( [VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT] ) + payload return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little") def decode_temperature_response(frame: bytes | bytearray) -> bytes: """Decode the compact 35-byte temperature response used by command 0x28.""" raw = bytes(frame) if len(raw) != TEMPERATURE_RESPONSE_LEN: raise P4FrameError( f"temperature response length mismatch: expected " f"{TEMPERATURE_RESPONSE_LEN}, got {len(raw)}" ) expected_prefix = bytes( [*MAGIC, VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT] ) if raw[:6] != expected_prefix: raise P4FrameError("bad compact temperature response header") expected_crc = crc16_ccitt(raw[2:-2]) actual_crc = int.from_bytes(raw[-2:], "little") if actual_crc != expected_crc: raise P4FrameError( f"temperature response crc mismatch: expected 0x{expected_crc:04x}, " f"got 0x{actual_crc:04x}" ) return raw[6:-2] def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand: payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes") try: command = CommandId(payload[0]) except ValueError as exc: raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3]) def build_host_ack( *, ok: bool, command: CommandId | MotionOpcode | int, status: StatusCode | int, seq: int = 0, detail: int = 0, state_hash16: int = 0, response_type: FrameType | int = 0, result_flags: int = 0, timestamp_tick: int = 0, ) -> bytes: command_value = _u8(int(command), "command") status_value = StatusCode(int(status)) if not isinstance(ok, bool): raise ValueError("ok must be a bool") payload = bytes([int(ok), command_value, int(status_value), _u8(detail, "detail")]) payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little") payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")]) return encode_frame( frame_type=FrameType.HOST_ACK, seq=seq, timestamp_tick=timestamp_tick, payload=payload, ) def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck: request_seq = value.seq if isinstance(value, P4Frame) else None payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes") if payload[0] not in (0, 1): raise ValueError("HOST_ACK ok must be 0 or 1") try: command: CommandId | MotionOpcode | int = CommandId(payload[1]) except ValueError: try: command = MotionOpcode(payload[1]) except ValueError: command = payload[1] try: status = StatusCode(payload[2]) except ValueError as exc: raise ValueError("HOST_ACK contains an unknown status") from exc try: response_type: FrameType | int = FrameType(payload[6]) except ValueError: response_type = payload[6] return HostAck( ok=payload[0] == 1, command=command, status=status, detail=payload[3], state_hash16=int.from_bytes(payload[4:6], "little"), response_type=response_type, result_flags=payload[7], request_seq=request_seq, ) def _axis(value: int) -> int: if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1, 2): raise ValueError("axis must be 0, 1, or 2") return value def _bit(value: int, label: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1): raise ValueError(f"{label} must be 0 or 1") return value def build_motor_jog(*, axis: int, raw_dir: int, speed_code: int, steps: int) -> bytes: checked_axis = _axis(axis) checked_dir = _bit(raw_dir, "raw_dir") if isinstance(speed_code, bool) or not isinstance(speed_code, int) or speed_code not in range(4): raise ValueError("speed_code must be from 0 to 3") if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= 0xFFFF: raise ValueError("steps must be from 1 to 65535") payload = bytes((MotionOpcode.JOG, checked_axis, checked_dir, speed_code)) payload += steps.to_bytes(2, "little") + b"\x00\x00" return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload) def build_mark_closed(*, axis: int, close_dir: int) -> bytes: """Build the frozen legacy request; compliant firmware rejects it.""" checked_axis = _axis(axis) if checked_axis == 2: raise ValueError("MARK_CLOSED axis must be X or Y") payload = bytes((MotionOpcode.MARK_CLOSED, checked_axis, _bit(close_dir, "close_dir"))) + b"\x00" * 5 return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload) def build_get_motor_status() -> bytes: payload = bytes((MotionOpcode.GET_MOTOR_STATUS,)) + b"\x00" * 7 return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload) def decode_motion_command(value: P4Frame | bytes | bytearray) -> MotionCommand: payload = _payload(value, FrameType.MOTION_CMD, MOTION_COMMAND_PAYLOAD_LEN, "eight bytes") try: opcode = MotionOpcode(payload[0]) except ValueError as exc: raise ValueError(f"unknown motion opcode 0x{payload[0]:02x}") from exc if opcode == MotionOpcode.JOG: if payload[6:8] != b"\x00\x00": raise ValueError("JOG reserved bytes must be zero") axis = _axis(payload[1]) raw_dir = _bit(payload[2], "raw_dir") speed_code = payload[3] steps = int.from_bytes(payload[4:6], "little") if speed_code not in range(4): raise ValueError("speed_code must be from 0 to 3") if not 1 <= steps <= 0xFFFF: raise ValueError("steps must be from 1 to 65535") return MotionCommand(opcode, axis, raw_dir, speed_code, steps) if opcode == MotionOpcode.MARK_CLOSED: if payload[1] not in (0, 1): raise ValueError("MARK_CLOSED axis must be X or Y") if payload[3:8] != b"\x00" * 5: raise ValueError("MARK_CLOSED reserved bytes must be zero") return MotionCommand(opcode, payload[1], _bit(payload[2], "close_dir"), 0, 0) if payload[1:8] != b"\x00" * 7: raise ValueError("GET_MOTOR_STATUS reserved bytes must be zero") return MotionCommand(opcode, 0, 0, 0, 0) def _position_triplet(values: Iterable[int], label: str) -> tuple[int, int, int]: result = tuple(values) if len(result) != 3: raise ValueError(f"{label} must contain exactly three values") for value in result: if value not in (0, 100, 0xFE, 0xFF): raise ValueError(f"{label} values must be 0, 100, 254, or 255") return result[0], result[1], result[2] def _validate_motion_status_contract( *, flags: int, position_valid_mask: int, busy_mask: int, current_xyz: tuple[int, int, int], target_xyz: tuple[int, int, int], fault_mask: int, ) -> None: if position_valid_mask != 0 or busy_mask != 0 or fault_mask != 0: raise ValueError("MOTION_STATUS valid, busy, and fault fields must be zero") if current_xyz != (0xFF, 0xFF, 0xFF) or target_xyz != (0xFF, 0xFF, 0xFF): raise ValueError("MOTION_STATUS current and target must remain unknown") if flags & 0x01: raise ValueError("MOTION_STATUS any_busy must be zero") if not flags & 0x02: raise ValueError("MOTION_STATUS en_active must be one") if flags & 0x08 and not flags & 0x04: raise ValueError("MOTION_STATUS watchdog_timeout requires disabled") def build_motion_status( *, flags: int, position_valid_mask: int, busy_mask: int, current_xyz: Iterable[int], target_xyz: Iterable[int], fault_mask: int, ) -> bytes: current = _position_triplet(current_xyz, "current_xyz") target = _position_triplet(target_xyz, "target_xyz") for name, value in ( ("position_valid_mask", position_valid_mask), ("busy_mask", busy_mask), ("fault_mask", fault_mask), ): if isinstance(value, bool) or not isinstance(value, int) or value & ~0x07: raise ValueError(f"{name} must use only XYZ bits") checked_flags = _u8(flags, "flags") if checked_flags & 0xF0: raise ValueError("motion status flags contain reserved bits") _validate_motion_status_contract( flags=checked_flags, position_valid_mask=position_valid_mask, busy_mask=busy_mask, current_xyz=current, target_xyz=target, fault_mask=fault_mask, ) payload = bytes((checked_flags, position_valid_mask, busy_mask, *current, *target, fault_mask)) return encode_frame(frame_type=FrameType.MOTION_STATUS, seq=0, timestamp_tick=0, payload=payload) def decode_motion_status(value: P4Frame | bytes | bytearray) -> MotionStatus: payload = _payload(value, FrameType.MOTION_STATUS, MOTION_STATUS_PAYLOAD_LEN, "ten bytes") flags = payload[0] if flags & 0xF0: raise ValueError("motion status flags contain reserved bits") position_valid_mask = payload[1] busy_mask = payload[2] fault_mask = payload[9] for name, field in ( ("position_valid_mask", position_valid_mask), ("busy_mask", busy_mask), ("fault_mask", fault_mask), ): if field & ~0x07: raise ValueError(f"{name} must use only XYZ bits") current = _position_triplet(payload[3:6], "current_xyz") target = _position_triplet(payload[6:9], "target_xyz") _validate_motion_status_contract( flags=flags, position_valid_mask=position_valid_mask, busy_mask=busy_mask, current_xyz=current, target_xyz=target, fault_mask=fault_mask, ) return MotionStatus( flags=flags, position_valid_mask=position_valid_mask, busy_mask=busy_mask, current_xyz=current, target_xyz=target, fault_mask=fault_mask, )