| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- #!/usr/bin/env python3
- """Reference model for the frozen 115200 Prod2U frame contract."""
- from __future__ import annotations
- from dataclasses import dataclass
- from enum import IntEnum
- from typing import Iterable, Sequence
- FRAME_HEADER = b"\xA5\x5A"
- PTC_COUNT = 24
- FAN_COUNT = 4
- TEMPERATURE_COUNT = 27
- SET_ALL_PAYLOAD_LENGTH = PTC_COUNT + FAN_COUNT + 2
- class FrameType(IntEnum):
- SET_ALL = 0x01
- GET_TEMPERATURE = 0x02
- TEMPERATURE_DATA = 0x82
- 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 = 0xFFFF
- for value in data:
- crc ^= (int(value) & 0xFF) << 8
- for _ in range(8):
- crc = ((crc << 1) ^ 0x1021) & 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_bytes(values: Iterable[int], count: int, name: str) -> bytes:
- body = bytes(values)
- if len(body) != count:
- raise ValueError(f"{name} must contain {count} bytes")
- return body
- def build_set_all(ptc: Iterable[int], fan: Iterable[int], inlet_dir: int, outlet_dir: int) -> bytes:
- if inlet_dir not in (0, 1) or outlet_dir not in (0, 1):
- raise ValueError("motor directions must be 0 or 1")
- payload = _checked_bytes(ptc, PTC_COUNT, "ptc")
- payload += _checked_bytes(fan, FAN_COUNT, "fan")
- return encode_frame(FrameType.SET_ALL, payload + bytes((inlet_dir, outlet_dir)))
- 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_bytes(values, TEMPERATURE_COUNT, "temperature"))
- 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)
|