| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583 |
- #!/usr/bin/env python3
- """Prod2U Profile4 binary921 v2 wire protocol helpers.
- The module is intentionally free of serial I/O and clocks. Callers provide
- timestamps to the pure timeout-state functions so the same behavior can be
- used by collectors, replay tools, and deterministic tests.
- All multi-byte fields are little-endian. Payload layouts are:
- * HOST_CMD (4): cmd:u8, channel:u8, value:u8, flags:u8.
- * HOST_ACK (8): ok:u8, cmd:u8, status:u8, detail:u8, state_hash:u16,
- response_type:u8, result_flags:u8. The envelope seq is the request seq.
- * READY (12): build_id:u32, variant:u8, startup_reason:u8, startup_seq:u8,
- reserved:u8=0, capability_flags:u32.
- * STATUS_RESPONSE (24): status:u8, last_command_status:u8, flags:u8,
- variant:u8, command_count:u16, reserved:u16=0,
- watchdog_ticks_remaining:u32, tach_snapshot_seq:u32,
- trace_drop_count:u32, parser_error_count:u32.
- * FAN_TELEMETRY (28): snapshot_seq:u32, window_ticks:u32,
- overflow_mask:u8, fan_install_mask:u8, reserved:u16=0,
- edge_counts[8]:u16. RPM is not carried on wire.
- """
- from __future__ import annotations
- from dataclasses import dataclass, replace
- from enum import IntEnum
- from typing import Iterable
- 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
- READY_PAYLOAD_LEN = 12
- STATUS_RESPONSE_PAYLOAD_LEN = 24
- FAN_TELEMETRY_PAYLOAD_LEN = 28
- FAN_CHANNEL_COUNT = 8
- COMMAND_TIMEOUT_US = 2_000
- class P4FrameError(ValueError):
- """Raised when a Profile4 frame cannot be decoded safely."""
- class FrameType(IntEnum):
- READY = 0x01
- HOST_CMD = 0x05
- HOST_ACK = 0x06
- FAN_TELEMETRY = 0x0D
- STATUS_RESPONSE = 0x0E
- TRACE_SNAPSHOT = 0x0F
- class CommandId(IntEnum):
- SET_PTC = 0x20
- SET_FAN = 0x21
- GET_SENSOR = 0x22
- GET_MAP = 0x23
- GET_STATUS = 0x24
- SET_PID_REQUESTED = 0x25
- DISABLE = 0x26
- GET_FAN_TELEMETRY = 0x27
- class StatusCode(IntEnum):
- OK = 0x00
- UNSUPPORTED_IN_PROFILE = 0x01
- BAD_FLAGS = 0x02
- BAD_LENGTH = 0x03
- BAD_CHANNEL = 0x04
- BAD_VALUE = 0x05
- SEQ_CONFLICT = 0x06
- SEQ_JUMP = 0x07
- QUEUE_FULL = 0x08
- class TimeoutPhase(IntEnum):
- IDLE = 0
- PENDING = 1
- ACKED = 2
- TIMED_OUT = 3
- @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
- status: StatusCode
- detail: int
- state_hash16: int
- response_type: FrameType | int
- result_flags: int
- request_seq: int | None
- @dataclass(frozen=True)
- class Ready:
- build_id: int
- variant: int
- startup_reason: int
- startup_seq: int
- capability_flags: int
- @dataclass(frozen=True)
- class Status:
- status: StatusCode
- last_command_status: StatusCode
- flags: int
- variant: int
- command_count: int
- watchdog_ticks_remaining: int
- tach_snapshot_seq: int
- trace_drop_count: int
- parser_error_count: int
- @dataclass(frozen=True)
- class RpmEstimate:
- window_edges: int
- rpm: int
- calibrated: bool = False
- calibration_status: str = "uncalibrated"
- @dataclass(frozen=True)
- class FanTelemetry:
- snapshot_seq: int
- window_ticks: int
- overflow_mask: int
- fan_install_mask: int
- edge_counts: tuple[int, ...]
- rpm: tuple[int, ...]
- calibrated: bool = False
- calibration_status: str = "uncalibrated"
- @dataclass(frozen=True)
- class CommandTimeoutState:
- phase: TimeoutPhase = TimeoutPhase.IDLE
- request_seq: int | None = None
- started_at_us: int | None = None
- deadline_us: int | None = None
- completed_at_us: int | None = None
- 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 v2")
- try:
- typed_frame = FrameType(int(frame_type))
- except (TypeError, ValueError) as exc:
- raise ValueError(f"unknown Profile4 frame type: {frame_type}") from exc
- seq = _u32(seq, "seq")
- timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
- 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:
- raise P4FrameError("short Profile4 frame")
- if raw[:2] != MAGIC:
- raise P4FrameError("bad Profile4 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}")
- try:
- frame_type = FrameType(raw[4])
- except ValueError as exc:
- raise P4FrameError(f"unknown Profile4 frame type 0x{raw[4]:02x}") from exc
- return P4Frame(
- version=raw[2],
- profile_id=raw[3],
- frame_type=frame_type,
- seq=int.from_bytes(raw[5:9], "little"),
- timestamp_tick=int.from_bytes(raw[9:13], "little"),
- payload=raw[14:-2],
- crc16=actual_crc,
- raw=raw,
- )
- def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
- """Decode all valid frames, skipping noise and corrupt complete frames."""
- 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 build_host_command(
- *,
- seq: int,
- 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 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(
- *,
- seq: int,
- ok: bool,
- command: CommandId | int,
- status: StatusCode | int,
- detail: int = 0,
- state_hash16: int = 0,
- response_type: FrameType | int = 0,
- result_flags: int = 0,
- timestamp_tick: int = 0,
- ) -> bytes:
- command = CommandId(int(command))
- status = StatusCode(int(status))
- if not isinstance(ok, bool):
- raise ValueError("ok must be a bool")
- payload = bytes([int(ok), int(command), int(status), _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(payload[1])
- status = StatusCode(payload[2])
- except ValueError as exc:
- raise ValueError("HOST_ACK contains an unknown command or 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 encode_ready(
- *,
- seq: int,
- timestamp_tick: int,
- build_id: int,
- variant: int,
- startup_reason: int,
- startup_seq: int,
- capability_flags: int,
- ) -> bytes:
- if variant not in (0, 1):
- raise ValueError("variant must be 0 (normal) or 1 (trace)")
- payload = _u32(build_id, "build_id").to_bytes(4, "little")
- payload += bytes([_u8(variant, "variant")])
- payload += bytes([_u8(startup_reason, "startup_reason")])
- payload += bytes([_u8(startup_seq, "startup_seq"), 0])
- payload += _u32(capability_flags, "capability_flags").to_bytes(4, "little")
- return encode_frame(frame_type=FrameType.READY, seq=seq, timestamp_tick=timestamp_tick, payload=payload)
- def decode_ready(value: P4Frame | bytes | bytearray) -> Ready:
- payload = _payload(value, FrameType.READY, READY_PAYLOAD_LEN, "twelve bytes")
- if payload[7] != 0:
- raise ValueError("READY reserved byte must be zero")
- if payload[4] not in (0, 1):
- raise ValueError("READY variant must be 0 (normal) or 1 (trace)")
- return Ready(
- build_id=int.from_bytes(payload[0:4], "little"),
- variant=payload[4],
- startup_reason=payload[5],
- startup_seq=payload[6],
- capability_flags=int.from_bytes(payload[8:12], "little"),
- )
- def encode_status(
- *,
- seq: int,
- timestamp_tick: int,
- status: StatusCode | int,
- last_command_status: StatusCode | int = StatusCode.OK,
- flags: int = 0,
- variant: int = 0,
- command_count: int = 0,
- watchdog_ticks_remaining: int = 0,
- tach_snapshot_seq: int = 0,
- trace_drop_count: int = 0,
- parser_error_count: int = 0,
- ) -> bytes:
- status = StatusCode(int(status))
- last_command_status = StatusCode(int(last_command_status))
- if variant not in (0, 1):
- raise ValueError("variant must be 0 (normal) or 1 (trace)")
- payload = bytes(
- [
- int(status),
- int(last_command_status),
- _u8(flags, "flags"),
- _u8(variant, "variant"),
- ]
- )
- payload += _u16(command_count, "command_count").to_bytes(2, "little")
- payload += b"\x00\x00"
- payload += _u32(watchdog_ticks_remaining, "watchdog_ticks_remaining").to_bytes(4, "little")
- payload += _u32(tach_snapshot_seq, "tach_snapshot_seq").to_bytes(4, "little")
- payload += _u32(trace_drop_count, "trace_drop_count").to_bytes(4, "little")
- payload += _u32(parser_error_count, "parser_error_count").to_bytes(4, "little")
- return encode_frame(
- frame_type=FrameType.STATUS_RESPONSE,
- seq=seq,
- timestamp_tick=timestamp_tick,
- payload=payload,
- )
- def decode_status(value: P4Frame | bytes | bytearray) -> Status:
- payload = _payload(
- value,
- FrameType.STATUS_RESPONSE,
- STATUS_RESPONSE_PAYLOAD_LEN,
- "twenty-four bytes",
- )
- try:
- status = StatusCode(payload[0])
- last_command_status = StatusCode(payload[1])
- except ValueError as exc:
- raise ValueError("STATUS contains an unknown status code") from exc
- if payload[6:8] != b"\x00\x00":
- raise ValueError("STATUS_RESPONSE reserved bytes must be zero")
- if payload[3] not in (0, 1):
- raise ValueError("STATUS_RESPONSE variant must be 0 (normal) or 1 (trace)")
- return Status(
- status=status,
- last_command_status=last_command_status,
- flags=payload[2],
- variant=payload[3],
- command_count=int.from_bytes(payload[4:6], "little"),
- watchdog_ticks_remaining=int.from_bytes(payload[8:12], "little"),
- tach_snapshot_seq=int.from_bytes(payload[12:16], "little"),
- trace_drop_count=int.from_bytes(payload[16:20], "little"),
- parser_error_count=int.from_bytes(payload[20:24], "little"),
- )
- def rpm_from_edges(window_edges: int) -> RpmEstimate:
- edges = _u16(window_edges, "edges")
- return RpmEstimate(window_edges=edges, rpm=edges * 30)
- def encode_fan_telemetry(
- *,
- seq: int,
- timestamp_tick: int,
- snapshot_seq: int,
- window_ticks: int,
- overflow_mask: int,
- fan_install_mask: int,
- edge_counts: Iterable[int],
- ) -> bytes:
- edges = tuple(edge_counts)
- if len(edges) != FAN_CHANNEL_COUNT:
- raise ValueError("FAN_TELEMETRY requires exactly eight edge counts")
- checked_edges = tuple(_u16(edge, f"edge_counts[{index}]") for index, edge in enumerate(edges))
- payload = _u32(snapshot_seq, "snapshot_seq").to_bytes(4, "little")
- payload += _u32(window_ticks, "window_ticks").to_bytes(4, "little")
- payload += bytes([_u8(overflow_mask, "overflow_mask")])
- payload += bytes([_u8(fan_install_mask, "fan_install_mask")])
- payload += b"\x00\x00"
- payload += b"".join(edge.to_bytes(2, "little") for edge in checked_edges)
- return encode_frame(
- frame_type=FrameType.FAN_TELEMETRY,
- seq=seq,
- timestamp_tick=timestamp_tick,
- payload=payload,
- )
- def decode_fan_telemetry(value: P4Frame | bytes | bytearray) -> FanTelemetry:
- payload = _payload(
- value,
- FrameType.FAN_TELEMETRY,
- FAN_TELEMETRY_PAYLOAD_LEN,
- "twenty-eight bytes",
- )
- if payload[10:12] != b"\x00\x00":
- raise ValueError("FAN_TELEMETRY reserved bytes must be zero")
- edge_counts = tuple(
- int.from_bytes(payload[offset : offset + 2], "little")
- for offset in range(12, FAN_TELEMETRY_PAYLOAD_LEN, 2)
- )
- return FanTelemetry(
- snapshot_seq=int.from_bytes(payload[0:4], "little"),
- window_ticks=int.from_bytes(payload[4:8], "little"),
- overflow_mask=payload[8],
- fan_install_mask=payload[9],
- edge_counts=edge_counts,
- rpm=tuple(edge * 30 for edge in edge_counts),
- )
- def start_timeout(
- state: CommandTimeoutState,
- *,
- request_seq: int,
- now_us: int,
- timeout_us: int = COMMAND_TIMEOUT_US,
- ) -> CommandTimeoutState:
- del state
- request_seq = _u32(request_seq, "request_seq")
- now_us = _nonnegative_time(now_us, "now_us")
- timeout_us = _nonnegative_time(timeout_us, "timeout_us")
- if timeout_us == 0:
- raise ValueError("timeout_us must be positive")
- return CommandTimeoutState(
- phase=TimeoutPhase.PENDING,
- request_seq=request_seq,
- started_at_us=now_us,
- deadline_us=now_us + timeout_us,
- )
- def poll_timeout(state: CommandTimeoutState, *, now_us: int) -> CommandTimeoutState:
- now_us = _nonnegative_time(now_us, "now_us")
- if state.phase != TimeoutPhase.PENDING:
- return state
- if state.deadline_us is None:
- raise ValueError("pending timeout state has no deadline")
- if now_us < state.deadline_us:
- return state
- return replace(state, phase=TimeoutPhase.TIMED_OUT, completed_at_us=now_us)
- def observe_ack(state: CommandTimeoutState, *, request_seq: int, now_us: int) -> CommandTimeoutState:
- request_seq = _u32(request_seq, "request_seq")
- now_us = _nonnegative_time(now_us, "now_us")
- checked = poll_timeout(state, now_us=now_us)
- if checked.phase != TimeoutPhase.PENDING or checked.request_seq != request_seq:
- return checked
- return replace(checked, phase=TimeoutPhase.ACKED, completed_at_us=now_us)
- def _nonnegative_time(value: int, name: str) -> int:
- if isinstance(value, bool) or not isinstance(value, int) or value < 0:
- raise ValueError(f"{name} must be a non-negative integer")
- return value
|