prod2u_p4_protocol.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #!/usr/bin/env python3
  2. """Prod2U Profile4 binary921 v2 wire protocol helpers.
  3. The module is intentionally free of serial I/O and clocks. Callers provide
  4. timestamps to the pure timeout-state functions so the same behavior can be
  5. used by collectors, replay tools, and deterministic tests.
  6. All multi-byte fields are little-endian. Payload layouts are:
  7. * HOST_CMD (4): cmd:u8, channel:u8, value:u8, flags:u8.
  8. * HOST_ACK (8): ok:u8, cmd:u8, status:u8, detail:u8, state_hash:u16,
  9. response_type:u8, result_flags:u8. The envelope seq is the request seq.
  10. * READY (12): build_id:u32, variant:u8, startup_reason:u8, startup_seq:u8,
  11. reserved:u8=0, capability_flags:u32.
  12. * STATUS_RESPONSE (24): status:u8, last_command_status:u8, flags:u8,
  13. variant:u8, command_count:u16, reserved:u16=0,
  14. watchdog_ticks_remaining:u32, tach_snapshot_seq:u32,
  15. trace_drop_count:u32, parser_error_count:u32.
  16. * FAN_TELEMETRY (28): snapshot_seq:u32, window_ticks:u32,
  17. overflow_mask:u8, fan_install_mask:u8, reserved:u16=0,
  18. edge_counts[8]:u16. RPM is not carried on wire.
  19. """
  20. from __future__ import annotations
  21. from dataclasses import dataclass, replace
  22. from enum import IntEnum
  23. from typing import Iterable
  24. MAGIC = b"\xA5\x5A"
  25. VERSION = 2
  26. PROFILE_ID = 4
  27. HEADER_LEN = 14
  28. CRC_LEN = 2
  29. MAX_PAYLOAD_LEN = 255
  30. HOST_CMD_PAYLOAD_LEN = 4
  31. HOST_ACK_PAYLOAD_LEN = 8
  32. READY_PAYLOAD_LEN = 12
  33. STATUS_RESPONSE_PAYLOAD_LEN = 24
  34. FAN_TELEMETRY_PAYLOAD_LEN = 28
  35. FAN_CHANNEL_COUNT = 8
  36. COMMAND_TIMEOUT_US = 2_000
  37. class P4FrameError(ValueError):
  38. """Raised when a Profile4 frame cannot be decoded safely."""
  39. class FrameType(IntEnum):
  40. READY = 0x01
  41. HOST_CMD = 0x05
  42. HOST_ACK = 0x06
  43. FAN_TELEMETRY = 0x0D
  44. STATUS_RESPONSE = 0x0E
  45. TRACE_SNAPSHOT = 0x0F
  46. class CommandId(IntEnum):
  47. SET_PTC = 0x20
  48. SET_FAN = 0x21
  49. GET_SENSOR = 0x22
  50. GET_MAP = 0x23
  51. GET_STATUS = 0x24
  52. SET_PID_REQUESTED = 0x25
  53. DISABLE = 0x26
  54. GET_FAN_TELEMETRY = 0x27
  55. class StatusCode(IntEnum):
  56. OK = 0x00
  57. UNSUPPORTED_IN_PROFILE = 0x01
  58. BAD_FLAGS = 0x02
  59. BAD_LENGTH = 0x03
  60. BAD_CHANNEL = 0x04
  61. BAD_VALUE = 0x05
  62. SEQ_CONFLICT = 0x06
  63. SEQ_JUMP = 0x07
  64. QUEUE_FULL = 0x08
  65. class TimeoutPhase(IntEnum):
  66. IDLE = 0
  67. PENDING = 1
  68. ACKED = 2
  69. TIMED_OUT = 3
  70. @dataclass(frozen=True)
  71. class P4Frame:
  72. version: int
  73. profile_id: int
  74. frame_type: FrameType
  75. seq: int
  76. timestamp_tick: int
  77. payload: bytes
  78. crc16: int
  79. raw: bytes
  80. @dataclass(frozen=True)
  81. class HostCommand:
  82. command: CommandId
  83. channel: int
  84. value: int
  85. flags: int
  86. @dataclass(frozen=True)
  87. class HostAck:
  88. ok: bool
  89. command: CommandId
  90. status: StatusCode
  91. detail: int
  92. state_hash16: int
  93. response_type: FrameType | int
  94. result_flags: int
  95. request_seq: int | None
  96. @dataclass(frozen=True)
  97. class Ready:
  98. build_id: int
  99. variant: int
  100. startup_reason: int
  101. startup_seq: int
  102. capability_flags: int
  103. @dataclass(frozen=True)
  104. class Status:
  105. status: StatusCode
  106. last_command_status: StatusCode
  107. flags: int
  108. variant: int
  109. command_count: int
  110. watchdog_ticks_remaining: int
  111. tach_snapshot_seq: int
  112. trace_drop_count: int
  113. parser_error_count: int
  114. @dataclass(frozen=True)
  115. class RpmEstimate:
  116. window_edges: int
  117. rpm: int
  118. calibrated: bool = False
  119. calibration_status: str = "uncalibrated"
  120. @dataclass(frozen=True)
  121. class FanTelemetry:
  122. snapshot_seq: int
  123. window_ticks: int
  124. overflow_mask: int
  125. fan_install_mask: int
  126. edge_counts: tuple[int, ...]
  127. rpm: tuple[int, ...]
  128. calibrated: bool = False
  129. calibration_status: str = "uncalibrated"
  130. @dataclass(frozen=True)
  131. class CommandTimeoutState:
  132. phase: TimeoutPhase = TimeoutPhase.IDLE
  133. request_seq: int | None = None
  134. started_at_us: int | None = None
  135. deadline_us: int | None = None
  136. completed_at_us: int | None = None
  137. def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
  138. """Return CRC-16/CCITT-FALSE for *data*."""
  139. crc = initial & 0xFFFF
  140. for byte in bytes(data):
  141. crc ^= byte << 8
  142. for _ in range(8):
  143. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  144. return crc
  145. def _u8(value: int, name: str) -> int:
  146. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
  147. raise ValueError(f"{name} must fit in one byte")
  148. return value
  149. def _u16(value: int, name: str) -> int:
  150. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF:
  151. raise ValueError(f"{name} must fit in 16 bits")
  152. return value
  153. def _u32(value: int, name: str) -> int:
  154. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF:
  155. raise ValueError(f"{name} must fit in 32 bits")
  156. return value
  157. def encode_frame(
  158. *,
  159. frame_type: FrameType | int,
  160. seq: int,
  161. timestamp_tick: int,
  162. payload: bytes | bytearray | Iterable[int],
  163. ) -> bytes:
  164. payload_bytes = bytes(payload)
  165. if len(payload_bytes) > MAX_PAYLOAD_LEN:
  166. raise ValueError("payload too long for binary921 v2")
  167. try:
  168. typed_frame = FrameType(int(frame_type))
  169. except (TypeError, ValueError) as exc:
  170. raise ValueError(f"unknown Profile4 frame type: {frame_type}") from exc
  171. seq = _u32(seq, "seq")
  172. timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
  173. body = bytes([VERSION, PROFILE_ID, int(typed_frame)])
  174. body += seq.to_bytes(4, "little")
  175. body += timestamp_tick.to_bytes(4, "little")
  176. body += bytes([len(payload_bytes)]) + payload_bytes
  177. return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
  178. def decode_frame(frame: bytes | bytearray) -> P4Frame:
  179. raw = bytes(frame)
  180. if len(raw) < HEADER_LEN:
  181. raise P4FrameError("short Profile4 frame")
  182. if raw[:2] != MAGIC:
  183. raise P4FrameError("bad Profile4 magic")
  184. if raw[2] != VERSION:
  185. raise P4FrameError(f"unsupported binary921 version {raw[2]}")
  186. if raw[3] != PROFILE_ID:
  187. raise P4FrameError(f"unexpected binary921 profile {raw[3]}")
  188. payload_len = raw[13]
  189. expected_len = HEADER_LEN + payload_len + CRC_LEN
  190. if len(raw) != expected_len:
  191. raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
  192. expected_crc = crc16_ccitt(raw[2:-2])
  193. actual_crc = int.from_bytes(raw[-2:], "little")
  194. if actual_crc != expected_crc:
  195. raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
  196. try:
  197. frame_type = FrameType(raw[4])
  198. except ValueError as exc:
  199. raise P4FrameError(f"unknown Profile4 frame type 0x{raw[4]:02x}") from exc
  200. return P4Frame(
  201. version=raw[2],
  202. profile_id=raw[3],
  203. frame_type=frame_type,
  204. seq=int.from_bytes(raw[5:9], "little"),
  205. timestamp_tick=int.from_bytes(raw[9:13], "little"),
  206. payload=raw[14:-2],
  207. crc16=actual_crc,
  208. raw=raw,
  209. )
  210. def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
  211. """Decode all valid frames, skipping noise and corrupt complete frames."""
  212. buf = bytes(data)
  213. frames: list[P4Frame] = []
  214. offset = 0
  215. while True:
  216. magic_at = buf.find(MAGIC, offset)
  217. if magic_at < 0:
  218. remaining = buf[offset:]
  219. return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b""
  220. if len(buf) - magic_at < HEADER_LEN + CRC_LEN:
  221. return frames, buf[magic_at:]
  222. end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN
  223. if end > len(buf):
  224. next_magic = buf.find(MAGIC, magic_at + 1)
  225. if next_magic < 0:
  226. return frames, buf[magic_at:]
  227. offset = next_magic
  228. continue
  229. try:
  230. frames.append(decode_frame(buf[magic_at:end]))
  231. offset = end
  232. except P4FrameError:
  233. offset = magic_at + 1
  234. def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes:
  235. if isinstance(value, P4Frame):
  236. if value.frame_type != frame_type:
  237. raise ValueError(f"expected {frame_type.name} frame")
  238. payload = value.payload
  239. else:
  240. payload = bytes(value)
  241. if len(payload) != length:
  242. raise ValueError(f"{frame_type.name} payload must be exactly {words}")
  243. return payload
  244. def build_host_command(
  245. *,
  246. seq: int,
  247. command: CommandId | int,
  248. channel: int = 0,
  249. value: int = 0,
  250. flags: int = 0,
  251. timestamp_tick: int = 0,
  252. ) -> bytes:
  253. try:
  254. command = CommandId(int(command))
  255. except (TypeError, ValueError) as exc:
  256. raise ValueError(f"unknown Profile4 command: {command}") from exc
  257. payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")])
  258. return encode_frame(
  259. frame_type=FrameType.HOST_CMD,
  260. seq=seq,
  261. timestamp_tick=timestamp_tick,
  262. payload=payload,
  263. )
  264. def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand:
  265. payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes")
  266. try:
  267. command = CommandId(payload[0])
  268. except ValueError as exc:
  269. raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc
  270. return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3])
  271. def build_host_ack(
  272. *,
  273. seq: int,
  274. ok: bool,
  275. command: CommandId | int,
  276. status: StatusCode | int,
  277. detail: int = 0,
  278. state_hash16: int = 0,
  279. response_type: FrameType | int = 0,
  280. result_flags: int = 0,
  281. timestamp_tick: int = 0,
  282. ) -> bytes:
  283. command = CommandId(int(command))
  284. status = StatusCode(int(status))
  285. if not isinstance(ok, bool):
  286. raise ValueError("ok must be a bool")
  287. payload = bytes([int(ok), int(command), int(status), _u8(detail, "detail")])
  288. payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little")
  289. payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")])
  290. return encode_frame(
  291. frame_type=FrameType.HOST_ACK,
  292. seq=seq,
  293. timestamp_tick=timestamp_tick,
  294. payload=payload,
  295. )
  296. def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck:
  297. request_seq = value.seq if isinstance(value, P4Frame) else None
  298. payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes")
  299. if payload[0] not in (0, 1):
  300. raise ValueError("HOST_ACK ok must be 0 or 1")
  301. try:
  302. command = CommandId(payload[1])
  303. status = StatusCode(payload[2])
  304. except ValueError as exc:
  305. raise ValueError("HOST_ACK contains an unknown command or status") from exc
  306. try:
  307. response_type: FrameType | int = FrameType(payload[6])
  308. except ValueError:
  309. response_type = payload[6]
  310. return HostAck(
  311. ok=payload[0] == 1,
  312. command=command,
  313. status=status,
  314. detail=payload[3],
  315. state_hash16=int.from_bytes(payload[4:6], "little"),
  316. response_type=response_type,
  317. result_flags=payload[7],
  318. request_seq=request_seq,
  319. )
  320. def encode_ready(
  321. *,
  322. seq: int,
  323. timestamp_tick: int,
  324. build_id: int,
  325. variant: int,
  326. startup_reason: int,
  327. startup_seq: int,
  328. capability_flags: int,
  329. ) -> bytes:
  330. if variant not in (0, 1):
  331. raise ValueError("variant must be 0 (normal) or 1 (trace)")
  332. payload = _u32(build_id, "build_id").to_bytes(4, "little")
  333. payload += bytes([_u8(variant, "variant")])
  334. payload += bytes([_u8(startup_reason, "startup_reason")])
  335. payload += bytes([_u8(startup_seq, "startup_seq"), 0])
  336. payload += _u32(capability_flags, "capability_flags").to_bytes(4, "little")
  337. return encode_frame(frame_type=FrameType.READY, seq=seq, timestamp_tick=timestamp_tick, payload=payload)
  338. def decode_ready(value: P4Frame | bytes | bytearray) -> Ready:
  339. payload = _payload(value, FrameType.READY, READY_PAYLOAD_LEN, "twelve bytes")
  340. if payload[7] != 0:
  341. raise ValueError("READY reserved byte must be zero")
  342. if payload[4] not in (0, 1):
  343. raise ValueError("READY variant must be 0 (normal) or 1 (trace)")
  344. return Ready(
  345. build_id=int.from_bytes(payload[0:4], "little"),
  346. variant=payload[4],
  347. startup_reason=payload[5],
  348. startup_seq=payload[6],
  349. capability_flags=int.from_bytes(payload[8:12], "little"),
  350. )
  351. def encode_status(
  352. *,
  353. seq: int,
  354. timestamp_tick: int,
  355. status: StatusCode | int,
  356. last_command_status: StatusCode | int = StatusCode.OK,
  357. flags: int = 0,
  358. variant: int = 0,
  359. command_count: int = 0,
  360. watchdog_ticks_remaining: int = 0,
  361. tach_snapshot_seq: int = 0,
  362. trace_drop_count: int = 0,
  363. parser_error_count: int = 0,
  364. ) -> bytes:
  365. status = StatusCode(int(status))
  366. last_command_status = StatusCode(int(last_command_status))
  367. if variant not in (0, 1):
  368. raise ValueError("variant must be 0 (normal) or 1 (trace)")
  369. payload = bytes(
  370. [
  371. int(status),
  372. int(last_command_status),
  373. _u8(flags, "flags"),
  374. _u8(variant, "variant"),
  375. ]
  376. )
  377. payload += _u16(command_count, "command_count").to_bytes(2, "little")
  378. payload += b"\x00\x00"
  379. payload += _u32(watchdog_ticks_remaining, "watchdog_ticks_remaining").to_bytes(4, "little")
  380. payload += _u32(tach_snapshot_seq, "tach_snapshot_seq").to_bytes(4, "little")
  381. payload += _u32(trace_drop_count, "trace_drop_count").to_bytes(4, "little")
  382. payload += _u32(parser_error_count, "parser_error_count").to_bytes(4, "little")
  383. return encode_frame(
  384. frame_type=FrameType.STATUS_RESPONSE,
  385. seq=seq,
  386. timestamp_tick=timestamp_tick,
  387. payload=payload,
  388. )
  389. def decode_status(value: P4Frame | bytes | bytearray) -> Status:
  390. payload = _payload(
  391. value,
  392. FrameType.STATUS_RESPONSE,
  393. STATUS_RESPONSE_PAYLOAD_LEN,
  394. "twenty-four bytes",
  395. )
  396. try:
  397. status = StatusCode(payload[0])
  398. last_command_status = StatusCode(payload[1])
  399. except ValueError as exc:
  400. raise ValueError("STATUS contains an unknown status code") from exc
  401. if payload[6:8] != b"\x00\x00":
  402. raise ValueError("STATUS_RESPONSE reserved bytes must be zero")
  403. if payload[3] not in (0, 1):
  404. raise ValueError("STATUS_RESPONSE variant must be 0 (normal) or 1 (trace)")
  405. return Status(
  406. status=status,
  407. last_command_status=last_command_status,
  408. flags=payload[2],
  409. variant=payload[3],
  410. command_count=int.from_bytes(payload[4:6], "little"),
  411. watchdog_ticks_remaining=int.from_bytes(payload[8:12], "little"),
  412. tach_snapshot_seq=int.from_bytes(payload[12:16], "little"),
  413. trace_drop_count=int.from_bytes(payload[16:20], "little"),
  414. parser_error_count=int.from_bytes(payload[20:24], "little"),
  415. )
  416. def rpm_from_edges(window_edges: int) -> RpmEstimate:
  417. edges = _u16(window_edges, "edges")
  418. return RpmEstimate(window_edges=edges, rpm=edges * 30)
  419. def encode_fan_telemetry(
  420. *,
  421. seq: int,
  422. timestamp_tick: int,
  423. snapshot_seq: int,
  424. window_ticks: int,
  425. overflow_mask: int,
  426. fan_install_mask: int,
  427. edge_counts: Iterable[int],
  428. ) -> bytes:
  429. edges = tuple(edge_counts)
  430. if len(edges) != FAN_CHANNEL_COUNT:
  431. raise ValueError("FAN_TELEMETRY requires exactly eight edge counts")
  432. checked_edges = tuple(_u16(edge, f"edge_counts[{index}]") for index, edge in enumerate(edges))
  433. payload = _u32(snapshot_seq, "snapshot_seq").to_bytes(4, "little")
  434. payload += _u32(window_ticks, "window_ticks").to_bytes(4, "little")
  435. payload += bytes([_u8(overflow_mask, "overflow_mask")])
  436. payload += bytes([_u8(fan_install_mask, "fan_install_mask")])
  437. payload += b"\x00\x00"
  438. payload += b"".join(edge.to_bytes(2, "little") for edge in checked_edges)
  439. return encode_frame(
  440. frame_type=FrameType.FAN_TELEMETRY,
  441. seq=seq,
  442. timestamp_tick=timestamp_tick,
  443. payload=payload,
  444. )
  445. def decode_fan_telemetry(value: P4Frame | bytes | bytearray) -> FanTelemetry:
  446. payload = _payload(
  447. value,
  448. FrameType.FAN_TELEMETRY,
  449. FAN_TELEMETRY_PAYLOAD_LEN,
  450. "twenty-eight bytes",
  451. )
  452. if payload[10:12] != b"\x00\x00":
  453. raise ValueError("FAN_TELEMETRY reserved bytes must be zero")
  454. edge_counts = tuple(
  455. int.from_bytes(payload[offset : offset + 2], "little")
  456. for offset in range(12, FAN_TELEMETRY_PAYLOAD_LEN, 2)
  457. )
  458. return FanTelemetry(
  459. snapshot_seq=int.from_bytes(payload[0:4], "little"),
  460. window_ticks=int.from_bytes(payload[4:8], "little"),
  461. overflow_mask=payload[8],
  462. fan_install_mask=payload[9],
  463. edge_counts=edge_counts,
  464. rpm=tuple(edge * 30 for edge in edge_counts),
  465. )
  466. def start_timeout(
  467. state: CommandTimeoutState,
  468. *,
  469. request_seq: int,
  470. now_us: int,
  471. timeout_us: int = COMMAND_TIMEOUT_US,
  472. ) -> CommandTimeoutState:
  473. del state
  474. request_seq = _u32(request_seq, "request_seq")
  475. now_us = _nonnegative_time(now_us, "now_us")
  476. timeout_us = _nonnegative_time(timeout_us, "timeout_us")
  477. if timeout_us == 0:
  478. raise ValueError("timeout_us must be positive")
  479. return CommandTimeoutState(
  480. phase=TimeoutPhase.PENDING,
  481. request_seq=request_seq,
  482. started_at_us=now_us,
  483. deadline_us=now_us + timeout_us,
  484. )
  485. def poll_timeout(state: CommandTimeoutState, *, now_us: int) -> CommandTimeoutState:
  486. now_us = _nonnegative_time(now_us, "now_us")
  487. if state.phase != TimeoutPhase.PENDING:
  488. return state
  489. if state.deadline_us is None:
  490. raise ValueError("pending timeout state has no deadline")
  491. if now_us < state.deadline_us:
  492. return state
  493. return replace(state, phase=TimeoutPhase.TIMED_OUT, completed_at_us=now_us)
  494. def observe_ack(state: CommandTimeoutState, *, request_seq: int, now_us: int) -> CommandTimeoutState:
  495. request_seq = _u32(request_seq, "request_seq")
  496. now_us = _nonnegative_time(now_us, "now_us")
  497. checked = poll_timeout(state, now_us=now_us)
  498. if checked.phase != TimeoutPhase.PENDING or checked.request_seq != request_seq:
  499. return checked
  500. return replace(checked, phase=TimeoutPhase.ACKED, completed_at_us=now_us)
  501. def _nonnegative_time(value: int, name: str) -> int:
  502. if isinstance(value, bool) or not isinstance(value, int) or value < 0:
  503. raise ValueError(f"{name} must be a non-negative integer")
  504. return value