prod2u_p4_protocol.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. #!/usr/bin/env python3
  2. """Prod2U Profile 4 Normal-only binary921-v3 wire protocol helpers.
  3. The standard envelope carries BOOT_BUILD_ID, HOST_CMD, HOST_ACK,
  4. HOST_BATCH_CMD, MOTION_CMD, and MOTION_STATUS. The compact 61-byte
  5. temperature response intentionally omits seq, timestamp, and payload length.
  6. All multi-byte integers and CRC fields are little-endian on the UART wire.
  7. """
  8. from __future__ import annotations
  9. from dataclasses import dataclass
  10. from enum import IntEnum
  11. from typing import Iterable
  12. PROTOCOL_ID = "binary921-v3"
  13. MAGIC = b"\xA5\x5A"
  14. VERSION = 2
  15. PROFILE_ID = 4
  16. CAPABILITY_FLAGS = 0x00001FAF
  17. HEADER_LEN = 14
  18. CRC_LEN = 2
  19. MAX_PAYLOAD_LEN = 255
  20. HOST_CMD_PAYLOAD_LEN = 4
  21. HOST_ACK_PAYLOAD_LEN = 8
  22. BOOT_BUILD_ID_PAYLOAD_LEN = 8
  23. OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34
  24. MOTION_COMMAND_PAYLOAD_LEN = 8
  25. MOTION_STATUS_PAYLOAD_LEN = 10
  26. TEMPERATURE_CHANNEL_COUNT = 27
  27. TEMPERATURE_RESPONSE_LEN = 61
  28. PTC_CHANNEL_COUNT = 24
  29. FAN_CHANNEL_COUNT = 4
  30. class P4FrameError(ValueError):
  31. """Raised when a Profile4 frame cannot be decoded safely."""
  32. class FrameType(IntEnum):
  33. BOOT_BUILD_ID = 0x04
  34. HOST_CMD = 0x05
  35. HOST_ACK = 0x06
  36. HOST_BATCH_CMD = 0x07
  37. MOTION_CMD = 0x11
  38. MOTION_STATUS = 0x12
  39. TEMPERATURE_RESPONSE = 0x29
  40. class CommandId(IntEnum):
  41. GET_STATUS = 0x24
  42. DISABLE = 0x26
  43. GET_AUX_TEMP_ALL = 0x29
  44. SET_OUTPUT_SNAPSHOT = 0x2A
  45. class MotionOpcode(IntEnum):
  46. JOG = 0x35
  47. MARK_CLOSED = 0x36
  48. GET_MOTOR_STATUS = 0x37
  49. class StatusCode(IntEnum):
  50. OK = 0x00
  51. UNSUPPORTED_IN_PROFILE = 0x01
  52. BAD_FLAGS = 0x02
  53. BAD_LENGTH = 0x03
  54. BAD_VALUE = 0x05
  55. BUSY = 0x09
  56. PARTIAL = 0x16
  57. @dataclass(frozen=True)
  58. class P4Frame:
  59. version: int
  60. profile_id: int
  61. frame_type: FrameType
  62. seq: int
  63. timestamp_tick: int
  64. payload: bytes
  65. crc16: int
  66. raw: bytes
  67. @dataclass(frozen=True)
  68. class HostCommand:
  69. command: CommandId
  70. channel: int
  71. value: int
  72. flags: int
  73. @dataclass(frozen=True)
  74. class HostAck:
  75. ok: bool
  76. command: CommandId
  77. status: StatusCode
  78. detail: int
  79. state_hash16: int
  80. response_type: FrameType | int
  81. result_flags: int
  82. request_seq: int | None
  83. @dataclass(frozen=True)
  84. class BootBuildId:
  85. build_id: int
  86. capability_flags: int
  87. @dataclass(frozen=True)
  88. class OutputSnapshot:
  89. ptc_percent: tuple[int, ...]
  90. fan_percent: tuple[int, ...]
  91. solenoid: int
  92. xyz: tuple[int, int, int]
  93. state_hash16: int
  94. @dataclass(frozen=True)
  95. class MotionCommand:
  96. opcode: MotionOpcode
  97. axis: int
  98. raw_dir: int
  99. speed_code: int
  100. steps: int
  101. @dataclass(frozen=True)
  102. class MotionStatus:
  103. flags: int
  104. position_valid_mask: int
  105. busy_mask: int
  106. current_xyz: tuple[int, int, int]
  107. target_xyz: tuple[int, int, int]
  108. fault_mask: int
  109. @dataclass(frozen=True)
  110. class TemperatureResponse:
  111. raw_u16: tuple[int, ...]
  112. celsius: tuple[float | None, ...]
  113. def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
  114. """Return CRC-16/CCITT-FALSE for *data*."""
  115. crc = initial & 0xFFFF
  116. for byte in bytes(data):
  117. crc ^= byte << 8
  118. for _ in range(8):
  119. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  120. return crc
  121. def _u8(value: int, name: str) -> int:
  122. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
  123. raise ValueError(f"{name} must fit in one byte")
  124. return value
  125. def _u16(value: int, name: str) -> int:
  126. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF:
  127. raise ValueError(f"{name} must fit in 16 bits")
  128. return value
  129. def _u32(value: int, name: str) -> int:
  130. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF:
  131. raise ValueError(f"{name} must fit in 32 bits")
  132. return value
  133. def encode_frame(
  134. *,
  135. frame_type: FrameType | int,
  136. seq: int,
  137. timestamp_tick: int,
  138. payload: bytes | bytearray | Iterable[int],
  139. ) -> bytes:
  140. payload_bytes = bytes(payload)
  141. if len(payload_bytes) > MAX_PAYLOAD_LEN:
  142. raise ValueError("payload too long for binary921-v3")
  143. try:
  144. typed_frame = FrameType(int(frame_type))
  145. except (TypeError, ValueError) as exc:
  146. raise ValueError(f"unknown Profile4 frame type: {frame_type}") from exc
  147. seq = _u32(seq, "seq")
  148. timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
  149. if seq != 0:
  150. raise ValueError("binary921-v3 seq must be zero")
  151. if timestamp_tick != 0:
  152. raise ValueError("binary921-v3 timestamp must be zero")
  153. body = bytes([VERSION, PROFILE_ID, int(typed_frame)])
  154. body += seq.to_bytes(4, "little")
  155. body += timestamp_tick.to_bytes(4, "little")
  156. body += bytes([len(payload_bytes)]) + payload_bytes
  157. return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
  158. def decode_frame(frame: bytes | bytearray) -> P4Frame:
  159. raw = bytes(frame)
  160. if len(raw) < HEADER_LEN:
  161. raise P4FrameError("short Profile4 frame")
  162. if raw[:2] != MAGIC:
  163. raise P4FrameError("bad Profile4 magic")
  164. if raw[2] != VERSION:
  165. raise P4FrameError(f"unsupported binary921 version {raw[2]}")
  166. if raw[3] != PROFILE_ID:
  167. raise P4FrameError(f"unexpected binary921 profile {raw[3]}")
  168. payload_len = raw[13]
  169. expected_len = HEADER_LEN + payload_len + CRC_LEN
  170. if len(raw) != expected_len:
  171. raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
  172. expected_crc = crc16_ccitt(raw[2:-2])
  173. actual_crc = int.from_bytes(raw[-2:], "little")
  174. if actual_crc != expected_crc:
  175. raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
  176. if raw[5:9] != b"\x00\x00\x00\x00":
  177. raise P4FrameError("binary921-v3 seq must be zero")
  178. if raw[9:13] != b"\x00\x00\x00\x00":
  179. raise P4FrameError("binary921-v3 timestamp must be zero")
  180. try:
  181. frame_type = FrameType(raw[4])
  182. except ValueError as exc:
  183. raise P4FrameError(f"unknown Profile4 frame type 0x{raw[4]:02x}") from exc
  184. return P4Frame(
  185. version=raw[2],
  186. profile_id=raw[3],
  187. frame_type=frame_type,
  188. seq=int.from_bytes(raw[5:9], "little"),
  189. timestamp_tick=int.from_bytes(raw[9:13], "little"),
  190. payload=raw[14:-2],
  191. crc16=actual_crc,
  192. raw=raw,
  193. )
  194. def build_boot_build_id(*, build_id: int, capability_flags: int = CAPABILITY_FLAGS) -> bytes:
  195. payload = _u32(build_id, "build_id").to_bytes(4, "little")
  196. payload += _u32(capability_flags, "capability_flags").to_bytes(4, "little")
  197. return encode_frame(
  198. frame_type=FrameType.BOOT_BUILD_ID,
  199. seq=0,
  200. timestamp_tick=0,
  201. payload=payload,
  202. )
  203. def decode_boot_build_id(value: P4Frame | bytes | bytearray) -> BootBuildId:
  204. payload = _payload(value, FrameType.BOOT_BUILD_ID, BOOT_BUILD_ID_PAYLOAD_LEN, "eight bytes")
  205. return BootBuildId(
  206. build_id=int.from_bytes(payload[0:4], "little"),
  207. capability_flags=int.from_bytes(payload[4:8], "little"),
  208. )
  209. def _percent_tuple(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  210. result = tuple(values)
  211. if len(result) != count:
  212. raise ValueError(f"snapshot requires exactly {count} {label} values")
  213. for index, value in enumerate(result):
  214. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:
  215. raise ValueError(f"{label}[{index}] must be an integer from 0 to 100")
  216. return result
  217. def _binary_output(value: int, label: str) -> int:
  218. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 100):
  219. raise ValueError(f"{label} must be 0 or 100")
  220. return value
  221. def state_hash16(
  222. *,
  223. ptc_percent: Iterable[int],
  224. fan_percent: Iterable[int],
  225. solenoid: int,
  226. ) -> int:
  227. ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
  228. fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
  229. checked_solenoid = _binary_output(solenoid, "solenoid")
  230. return crc16_ccitt(bytes(ptc + fan + (checked_solenoid,)))
  231. def build_output_snapshot(
  232. *,
  233. ptc_percent: Iterable[int],
  234. fan_percent: Iterable[int],
  235. solenoid: int,
  236. xyz: Iterable[int],
  237. ) -> bytes:
  238. ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
  239. fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
  240. checked_solenoid = _binary_output(solenoid, "solenoid")
  241. xyz_values = tuple(xyz)
  242. if len(xyz_values) != 3:
  243. raise ValueError("snapshot requires exactly 3 XYZ values")
  244. checked_xyz = tuple(_binary_output(value, "XYZ") for value in xyz_values)
  245. payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0))
  246. payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz)
  247. return encode_frame(
  248. frame_type=FrameType.HOST_BATCH_CMD,
  249. seq=0,
  250. timestamp_tick=0,
  251. payload=payload,
  252. )
  253. def decode_output_snapshot(value: P4Frame | bytes | bytearray) -> OutputSnapshot:
  254. payload = _payload(
  255. value,
  256. FrameType.HOST_BATCH_CMD,
  257. OUTPUT_SNAPSHOT_PAYLOAD_LEN,
  258. "thirty-four bytes",
  259. )
  260. if payload[0] != CommandId.SET_OUTPUT_SNAPSHOT:
  261. raise ValueError("HOST_BATCH_CMD command must be SET_OUTPUT_SNAPSHOT")
  262. if payload[1] != 0:
  263. raise ValueError("SET_OUTPUT_SNAPSHOT flags must be zero")
  264. ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC")
  265. fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN")
  266. solenoid = _binary_output(payload[30], "solenoid")
  267. xyz_values = tuple(_binary_output(value, "XYZ") for value in payload[31:34])
  268. return OutputSnapshot(
  269. ptc_percent=ptc,
  270. fan_percent=fan,
  271. solenoid=solenoid,
  272. xyz=(xyz_values[0], xyz_values[1], xyz_values[2]),
  273. state_hash16=state_hash16(ptc_percent=ptc, fan_percent=fan, solenoid=solenoid),
  274. )
  275. def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
  276. """Decode all valid frames, skipping noise and corrupt complete frames."""
  277. buf = bytes(data)
  278. frames: list[P4Frame] = []
  279. offset = 0
  280. while True:
  281. magic_at = buf.find(MAGIC, offset)
  282. if magic_at < 0:
  283. remaining = buf[offset:]
  284. return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b""
  285. if len(buf) - magic_at < HEADER_LEN + CRC_LEN:
  286. return frames, buf[magic_at:]
  287. end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN
  288. if end > len(buf):
  289. next_magic = buf.find(MAGIC, magic_at + 1)
  290. if next_magic < 0:
  291. return frames, buf[magic_at:]
  292. offset = next_magic
  293. continue
  294. try:
  295. frames.append(decode_frame(buf[magic_at:end]))
  296. offset = end
  297. except P4FrameError:
  298. offset = magic_at + 1
  299. def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes:
  300. if isinstance(value, P4Frame):
  301. if value.frame_type != frame_type:
  302. raise ValueError(f"expected {frame_type.name} frame")
  303. payload = value.payload
  304. else:
  305. payload = bytes(value)
  306. if len(payload) != length:
  307. raise ValueError(f"{frame_type.name} payload must be exactly {words}")
  308. return payload
  309. def build_host_command(
  310. *,
  311. seq: int = 0,
  312. command: CommandId | int,
  313. channel: int = 0,
  314. value: int = 0,
  315. flags: int = 0,
  316. timestamp_tick: int = 0,
  317. ) -> bytes:
  318. try:
  319. command = CommandId(int(command))
  320. except (TypeError, ValueError) as exc:
  321. raise ValueError(f"unknown Profile4 command: {command}") from exc
  322. payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")])
  323. return encode_frame(
  324. frame_type=FrameType.HOST_CMD,
  325. seq=seq,
  326. timestamp_tick=timestamp_tick,
  327. payload=payload,
  328. )
  329. def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand:
  330. payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes")
  331. try:
  332. command = CommandId(payload[0])
  333. except ValueError as exc:
  334. raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc
  335. return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3])
  336. def build_host_ack(
  337. *,
  338. ok: bool,
  339. command: CommandId | MotionOpcode | int,
  340. status: StatusCode | int,
  341. seq: int = 0,
  342. detail: int = 0,
  343. state_hash16: int = 0,
  344. response_type: FrameType | int = 0,
  345. result_flags: int = 0,
  346. timestamp_tick: int = 0,
  347. ) -> bytes:
  348. command_value = _u8(int(command), "command")
  349. status = StatusCode(int(status))
  350. if not isinstance(ok, bool):
  351. raise ValueError("ok must be a bool")
  352. payload = bytes([int(ok), command_value, int(status), _u8(detail, "detail")])
  353. payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little")
  354. payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")])
  355. return encode_frame(
  356. frame_type=FrameType.HOST_ACK,
  357. seq=seq,
  358. timestamp_tick=timestamp_tick,
  359. payload=payload,
  360. )
  361. def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck:
  362. request_seq = value.seq if isinstance(value, P4Frame) else None
  363. payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes")
  364. if payload[0] not in (0, 1):
  365. raise ValueError("HOST_ACK ok must be 0 or 1")
  366. try:
  367. command: CommandId | MotionOpcode | int = CommandId(payload[1])
  368. except ValueError:
  369. try:
  370. command = MotionOpcode(payload[1])
  371. except ValueError:
  372. command = payload[1]
  373. try:
  374. status = StatusCode(payload[2])
  375. except ValueError as exc:
  376. raise ValueError("HOST_ACK contains an unknown status") from exc
  377. try:
  378. response_type: FrameType | int = FrameType(payload[6])
  379. except ValueError:
  380. response_type = payload[6]
  381. return HostAck(
  382. ok=payload[0] == 1,
  383. command=command,
  384. status=status,
  385. detail=payload[3],
  386. state_hash16=int.from_bytes(payload[4:6], "little"),
  387. response_type=response_type,
  388. result_flags=payload[7],
  389. request_seq=request_seq,
  390. )
  391. def build_temperature_request() -> bytes:
  392. return build_host_command(command=CommandId.GET_AUX_TEMP_ALL)
  393. def _axis(value: int) -> int:
  394. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1, 2):
  395. raise ValueError("axis must be 0, 1, or 2")
  396. return value
  397. def _bit(value: int, label: str) -> int:
  398. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1):
  399. raise ValueError(f"{label} must be 0 or 1")
  400. return value
  401. def build_motor_jog(*, axis: int, raw_dir: int, speed_code: int, steps: int) -> bytes:
  402. checked_axis = _axis(axis)
  403. checked_dir = _bit(raw_dir, "raw_dir")
  404. if isinstance(speed_code, bool) or not isinstance(speed_code, int) or speed_code not in range(4):
  405. raise ValueError("speed_code must be from 0 to 3")
  406. if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= 160:
  407. raise ValueError("steps must be from 1 to 160")
  408. payload = bytes((MotionOpcode.JOG, checked_axis, checked_dir, speed_code))
  409. payload += steps.to_bytes(2, "little") + b"\x00\x00"
  410. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  411. def build_mark_closed(*, close_dir: int) -> bytes:
  412. payload = bytes((MotionOpcode.MARK_CLOSED, 2, _bit(close_dir, "close_dir"))) + b"\x00" * 5
  413. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  414. def build_get_motor_status() -> bytes:
  415. payload = bytes((MotionOpcode.GET_MOTOR_STATUS,)) + b"\x00" * 7
  416. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  417. def decode_motion_command(value: P4Frame | bytes | bytearray) -> MotionCommand:
  418. payload = _payload(value, FrameType.MOTION_CMD, MOTION_COMMAND_PAYLOAD_LEN, "eight bytes")
  419. try:
  420. opcode = MotionOpcode(payload[0])
  421. except ValueError as exc:
  422. raise ValueError(f"unknown motion opcode 0x{payload[0]:02x}") from exc
  423. if opcode == MotionOpcode.JOG:
  424. if payload[6:8] != b"\x00\x00":
  425. raise ValueError("JOG reserved bytes must be zero")
  426. axis = _axis(payload[1])
  427. raw_dir = _bit(payload[2], "raw_dir")
  428. speed_code = payload[3]
  429. steps = int.from_bytes(payload[4:6], "little")
  430. if speed_code not in range(4):
  431. raise ValueError("speed_code must be from 0 to 3")
  432. if not 1 <= steps <= 160:
  433. raise ValueError("steps must be from 1 to 160")
  434. return MotionCommand(opcode, axis, raw_dir, speed_code, steps)
  435. if opcode == MotionOpcode.MARK_CLOSED:
  436. if payload[1] != 2:
  437. raise ValueError("MARK_CLOSED axis must be Z")
  438. if payload[3:8] != b"\x00" * 5:
  439. raise ValueError("MARK_CLOSED reserved bytes must be zero")
  440. return MotionCommand(opcode, 2, _bit(payload[2], "close_dir"), 0, 0)
  441. if payload[1:8] != b"\x00" * 7:
  442. raise ValueError("GET_MOTOR_STATUS reserved bytes must be zero")
  443. return MotionCommand(opcode, 0, 0, 0, 0)
  444. def _position_triplet(values: Iterable[int], label: str) -> tuple[int, int, int]:
  445. result = tuple(values)
  446. if len(result) != 3:
  447. raise ValueError(f"{label} must contain exactly three values")
  448. for value in result:
  449. if value not in (0, 100, 0xFE, 0xFF):
  450. raise ValueError(f"{label} values must be 0, 100, 254, or 255")
  451. return result[0], result[1], result[2]
  452. def build_motion_status(
  453. *,
  454. flags: int,
  455. position_valid_mask: int,
  456. busy_mask: int,
  457. current_xyz: Iterable[int],
  458. target_xyz: Iterable[int],
  459. fault_mask: int,
  460. ) -> bytes:
  461. current = _position_triplet(current_xyz, "current_xyz")
  462. target = _position_triplet(target_xyz, "target_xyz")
  463. for name, value in (
  464. ("position_valid_mask", position_valid_mask),
  465. ("busy_mask", busy_mask),
  466. ("fault_mask", fault_mask),
  467. ):
  468. if isinstance(value, bool) or not isinstance(value, int) or value & ~0x07:
  469. raise ValueError(f"{name} must use only XYZ bits")
  470. payload = bytes(
  471. (
  472. _u8(flags, "flags"),
  473. position_valid_mask,
  474. busy_mask,
  475. *current,
  476. *target,
  477. fault_mask,
  478. )
  479. )
  480. return encode_frame(frame_type=FrameType.MOTION_STATUS, seq=0, timestamp_tick=0, payload=payload)
  481. def decode_motion_status(value: P4Frame | bytes | bytearray) -> MotionStatus:
  482. payload = _payload(value, FrameType.MOTION_STATUS, MOTION_STATUS_PAYLOAD_LEN, "ten bytes")
  483. if payload[0] & 0xF0:
  484. raise ValueError("motion status flags contain reserved bits")
  485. current = _position_triplet(payload[3:6], "current_xyz")
  486. target = _position_triplet(payload[6:9], "target_xyz")
  487. for name, item in (
  488. ("position_valid_mask", payload[1]),
  489. ("busy_mask", payload[2]),
  490. ("fault_mask", payload[9]),
  491. ):
  492. if item & ~0x07:
  493. raise ValueError(f"{name} must use only XYZ bits")
  494. return MotionStatus(payload[0], payload[1], payload[2], current, target, payload[9])
  495. def build_temperature_response(raw_u16: Iterable[int]) -> bytes:
  496. raw = tuple(raw_u16)
  497. if len(raw) != TEMPERATURE_CHANNEL_COUNT:
  498. raise ValueError("temperature response requires exactly 27 raw values")
  499. checked = tuple(_u16(value, f"raw_u16[{index}]") for index, value in enumerate(raw))
  500. body = bytes((VERSION, PROFILE_ID, FrameType.TEMPERATURE_RESPONSE))
  501. body += b"".join(value.to_bytes(2, "little") for value in checked)
  502. return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
  503. def decode_temperature_response(value: bytes | bytearray) -> TemperatureResponse:
  504. raw = bytes(value)
  505. if len(raw) != TEMPERATURE_RESPONSE_LEN:
  506. raise P4FrameError(f"temperature response length must be {TEMPERATURE_RESPONSE_LEN}")
  507. if raw[:2] != MAGIC:
  508. raise P4FrameError("bad temperature response magic")
  509. if raw[2:5] != bytes((VERSION, PROFILE_ID, FrameType.TEMPERATURE_RESPONSE)):
  510. raise P4FrameError("bad temperature response identity")
  511. expected_crc = crc16_ccitt(raw[2:59])
  512. actual_crc = int.from_bytes(raw[59:61], "little")
  513. if actual_crc != expected_crc:
  514. raise P4FrameError(f"temperature response crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
  515. words = tuple(int.from_bytes(raw[offset : offset + 2], "little") for offset in range(5, 59, 2))
  516. celsius: list[float | None] = []
  517. for word in words:
  518. if word == 0xFFFF:
  519. celsius.append(None)
  520. else:
  521. signed = word - 0x10000 if word & 0x8000 else word
  522. celsius.append(signed / 128.0)
  523. return TemperatureResponse(raw_u16=words, celsius=tuple(celsius))