prod2u_p4_protocol.py 19 KB

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