| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- #!/usr/bin/env python3
- """Reference model for the frozen Prod2U door-temperature frame contract."""
- from __future__ import annotations
- from dataclasses import dataclass
- from enum import IntEnum
- import json
- from pathlib import Path
- from typing import Iterable, Sequence
- _PROJECT_PATH = Path(__file__).resolve().parents[1] / "projects" / "prod2u-door-temp" / "project.json"
- _PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8"))
- _OUTPUTS = _PROJECT["outputs"]
- _PROTOCOL = _PROJECT["protocol"]
- _SET_ALL = _PROTOCOL["set_all"]
- _CRC = _PROTOCOL["crc"]
- _COMMANDS = _PROTOCOL["commands"]
- FRAME_HEADER = bytes.fromhex(_PROTOCOL["header_hex"])
- PTC_COUNT = len(_OUTPUTS["ptc_channels"])
- FAN_COUNT = len(_OUTPUTS["fan_channels"])
- TEMPERATURE_COUNT = _PROJECT["temperature"]["value_count"]
- SET_ALL_PAYLOAD_LENGTH = _SET_ALL["payload_length"]
- DUTY_MIN = _SET_ALL["duty_min"]
- DUTY_MAX = _SET_ALL["duty_max"]
- MOTOR_COMMANDS = tuple(_SET_ALL["motor_values"])
- HEARTBEAT_MOTOR_COMMAND = _SET_ALL["heartbeat"][0]
- CRC_POLYNOMIAL = _CRC["polynomial"]
- CRC_INITIAL = _CRC["initial"]
- class FrameType(IntEnum):
- SET_ALL = _COMMANDS["set_all"]
- GET_TEMPERATURE = _COMMANDS["get_temperature"]
- TEMPERATURE_DATA = _COMMANDS["temperature_data"]
- class ProtocolError(ValueError):
- """Raised when a frame violates the frozen protocol contract."""
- @dataclass(frozen=True)
- class Frame:
- frame_type: FrameType
- payload: bytes
- 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.TEMPERATURE_DATA: TEMPERATURE_COUNT,
- }[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_motor_command(value: int, name: str) -> int:
- if value not in MOTOR_COMMANDS:
- raise ValueError(f"{name} must be one of {MOTOR_COMMANDS}")
- return value
- def build_set_all(ptc: Iterable[int], fan: Iterable[int], x_command: int, y_command: int) -> bytes:
- x_command = _checked_motor_command(x_command, "x motor command")
- y_command = _checked_motor_command(y_command, "y motor command")
- payload = _checked_duty_bytes(ptc, PTC_COUNT, "ptc")
- payload += _checked_duty_bytes(fan, FAN_COUNT, "fan")
- return encode_frame(FrameType.SET_ALL, payload + bytes((x_command, y_command)))
- def build_get_temperature() -> bytes:
- return encode_frame(FrameType.GET_TEMPERATURE, b"")
- 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)
|