prod2u_p4_protocol.py 20 KB

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