binary921.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. #!/usr/bin/env python3
  2. """J6 binary921 host/debug frame helpers.
  3. The CPLD emits and accepts compact binary frames so the expensive ASCII
  4. formatting stays in the PC-side harness.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import re
  10. import sys
  11. from dataclasses import dataclass
  12. from enum import IntEnum
  13. from pathlib import Path
  14. from typing import Iterable
  15. MAGIC = b"\xA5\x5A"
  16. VERSION = 1
  17. HEADER_LEN = 14
  18. CRC_LEN = 2
  19. MAX_PAYLOAD_LEN = 255
  20. PROFILE_NAME_TO_ID = {
  21. "debug-photo-bmc-replay-binary921": 1,
  22. "formal-uart1-bmc-replay-binary921": 2,
  23. "production-two-uart-bmc-replay-binary921": 3,
  24. "prod2u-bmc-replay-binary921": 3,
  25. }
  26. PROFILE_ID_TO_NAME = {
  27. 1: "debug-photo-bmc-replay-binary921",
  28. 2: "formal-uart1-bmc-replay-binary921",
  29. 3: "production-two-uart-bmc-replay-binary921",
  30. }
  31. BUILD_ID_RE = re.compile(r"^[0-9A-Fa-f]{8}$")
  32. class Binary921FrameError(ValueError):
  33. """Raised when a binary921 frame cannot be decoded safely."""
  34. class FrameType(IntEnum):
  35. READY = 0x01
  36. BMC_POLL = 0x02
  37. BMC_PAYLOAD = 0x03
  38. SENSOR_CACHE = 0x04
  39. HOST_CMD = 0x05
  40. HOST_ACK = 0x06
  41. PWM_STATE = 0x07
  42. PID_STATE = 0x08
  43. TIMEOUT_STATE = 0x09
  44. PIN_PROFILE = 0x0A
  45. MODULE_SNAPSHOT = 0x0B
  46. ERROR_COUNTERS = 0x0C
  47. class CommandId(IntEnum):
  48. SET_PTC = 0x20
  49. SET_FAN = 0x21
  50. GET_SENSOR = 0x22
  51. GET_MAP = 0x23
  52. GET_STATUS = 0x24
  53. SET_PID_REQUESTED = 0x25
  54. DISABLE = 0x26
  55. def profile_id_for_name(profile: str) -> int:
  56. try:
  57. return PROFILE_NAME_TO_ID[profile]
  58. except KeyError as exc:
  59. raise ValueError(f"unknown binary921 profile: {profile}") from exc
  60. def profile_name_for_id(profile_id: int) -> str:
  61. try:
  62. return PROFILE_ID_TO_NAME[int(profile_id)]
  63. except KeyError as exc:
  64. raise ValueError(f"unknown binary921 profile id: {profile_id}") from exc
  65. def format_build_id(build_id: int | str) -> str:
  66. """Return a binary921 32-bit build ID as canonical uppercase JSON text."""
  67. if isinstance(build_id, bool):
  68. raise ValueError("build_id must be a 32-bit integer or eight hex digits")
  69. if isinstance(build_id, int):
  70. if build_id < 0 or build_id > 0xFFFFFFFF:
  71. raise ValueError("build_id must fit in 32 bits")
  72. return f"{build_id:08X}"
  73. if isinstance(build_id, str):
  74. value = build_id.strip()
  75. if BUILD_ID_RE.fullmatch(value):
  76. return value.upper()
  77. raise ValueError("build_id must be a 32-bit integer or eight hex digits")
  78. @dataclass(frozen=True)
  79. class Binary921Frame:
  80. version: int
  81. profile_id: int
  82. frame_type: int
  83. seq: int
  84. timestamp_tick: int
  85. payload: bytes
  86. crc16: int
  87. raw: bytes
  88. def crc16_ccitt(data: bytes, *, initial: int = 0xFFFF) -> int:
  89. crc = initial & 0xFFFF
  90. for byte in data:
  91. crc ^= byte << 8
  92. for _ in range(8):
  93. if crc & 0x8000:
  94. crc = ((crc << 1) ^ 0x1021) & 0xFFFF
  95. else:
  96. crc = (crc << 1) & 0xFFFF
  97. return crc & 0xFFFF
  98. def _le_u32(value: int) -> bytes:
  99. if value < 0 or value > 0xFFFFFFFF:
  100. raise ValueError("u32 value out of range")
  101. return value.to_bytes(4, "little")
  102. def encode_frame(
  103. *,
  104. profile_id: int,
  105. frame_type: int,
  106. seq: int,
  107. timestamp_tick: int,
  108. payload: bytes | bytearray | Iterable[int],
  109. ) -> bytes:
  110. payload_bytes = bytes(payload)
  111. if profile_id < 0 or profile_id > 0xFF:
  112. raise ValueError("profile_id must fit in one byte")
  113. if int(frame_type) < 0 or int(frame_type) > 0xFF:
  114. raise ValueError("frame_type must fit in one byte")
  115. if len(payload_bytes) > MAX_PAYLOAD_LEN:
  116. raise ValueError("payload too long for binary921 v1")
  117. body = bytes(
  118. [
  119. VERSION,
  120. profile_id & 0xFF,
  121. int(frame_type) & 0xFF,
  122. ]
  123. )
  124. body += _le_u32(seq)
  125. body += _le_u32(timestamp_tick)
  126. body += bytes([len(payload_bytes)])
  127. body += payload_bytes
  128. crc = crc16_ccitt(body)
  129. return MAGIC + body + crc.to_bytes(2, "little")
  130. def decode_frame(frame: bytes | bytearray) -> Binary921Frame:
  131. raw = bytes(frame)
  132. if len(raw) < HEADER_LEN + CRC_LEN:
  133. raise Binary921FrameError("short binary921 frame")
  134. if raw[:2] != MAGIC:
  135. raise Binary921FrameError("bad binary921 magic")
  136. payload_len = raw[13]
  137. expected_len = HEADER_LEN + payload_len + CRC_LEN
  138. if len(raw) != expected_len:
  139. raise Binary921FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
  140. body = raw[2:-2]
  141. expected_crc = crc16_ccitt(body)
  142. actual_crc = int.from_bytes(raw[-2:], "little")
  143. if actual_crc != expected_crc:
  144. raise Binary921FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
  145. version = raw[2]
  146. if version != VERSION:
  147. raise Binary921FrameError(f"unsupported binary921 version {version}")
  148. return Binary921Frame(
  149. version=version,
  150. profile_id=raw[3],
  151. frame_type=raw[4],
  152. seq=int.from_bytes(raw[5:9], "little"),
  153. timestamp_tick=int.from_bytes(raw[9:13], "little"),
  154. payload=raw[14 : 14 + payload_len],
  155. crc16=actual_crc,
  156. raw=raw,
  157. )
  158. def decode_stream(data: bytes | bytearray) -> tuple[list[Binary921Frame], bytes]:
  159. buf = bytes(data)
  160. frames: list[Binary921Frame] = []
  161. offset = 0
  162. while True:
  163. magic_at = buf.find(MAGIC, offset)
  164. if magic_at < 0:
  165. tail = buf[-1:] if buf.endswith(MAGIC[:1]) else b""
  166. return frames, tail
  167. if magic_at + HEADER_LEN + CRC_LEN > len(buf):
  168. return frames, buf[magic_at:]
  169. payload_len = buf[magic_at + 13]
  170. end = magic_at + HEADER_LEN + payload_len + CRC_LEN
  171. if end > len(buf):
  172. return frames, buf[magic_at:]
  173. candidate = buf[magic_at:end]
  174. try:
  175. frames.append(decode_frame(candidate))
  176. offset = end
  177. except Binary921FrameError:
  178. offset = magic_at + 1
  179. def build_host_command(
  180. *,
  181. seq: int,
  182. command: int,
  183. channel: int | None = None,
  184. percent: int | None = None,
  185. profile_id: int = 1,
  186. timestamp_tick: int = 0,
  187. ) -> bytes:
  188. command_id = CommandId(int(command))
  189. if command_id == CommandId.SET_PTC:
  190. if channel is None or channel < 1 or channel > 24:
  191. raise ValueError("PTC channel must be 1..24")
  192. if percent is None or percent < 0 or percent > 100:
  193. raise ValueError("percent must be 0..100")
  194. payload = bytes([command_id, channel, percent])
  195. elif command_id == CommandId.SET_FAN:
  196. if channel is None or channel < 1 or channel > 4:
  197. raise ValueError("FAN channel must be 1..4")
  198. if percent is None or percent < 0 or percent > 100:
  199. raise ValueError("percent must be 0..100")
  200. payload = bytes([command_id, channel, percent])
  201. elif command_id == CommandId.SET_PID_REQUESTED:
  202. if percent not in (0, 1):
  203. raise ValueError("SET_PID_REQUESTED uses percent as enabled flag 0/1")
  204. payload = bytes([command_id, percent])
  205. else:
  206. payload = bytes([command_id])
  207. return encode_frame(
  208. profile_id=profile_id,
  209. frame_type=FrameType.HOST_CMD,
  210. seq=seq,
  211. timestamp_tick=timestamp_tick,
  212. payload=payload,
  213. )
  214. def _enum_name(enum_cls: type[IntEnum], value: int) -> str:
  215. try:
  216. return enum_cls(value).name
  217. except ValueError:
  218. return f"UNKNOWN_0x{value:02X}"
  219. def decode_payload(frame: Binary921Frame) -> dict[str, object]:
  220. payload = frame.payload
  221. if frame.frame_type == FrameType.READY:
  222. decoded: dict[str, object] = {"kind": "ready"}
  223. if len(payload) >= 1:
  224. decoded["profile_id_payload"] = payload[0]
  225. if len(payload) >= 5:
  226. decoded["build_id"] = format_build_id(int.from_bytes(payload[1:5], "little"))
  227. decoded["startup_epoch"] = frame.seq
  228. decoded["startup_tick"] = frame.timestamp_tick
  229. if len(payload) >= 6:
  230. decoded["por_reason"] = payload[5]
  231. if len(payload) >= 7:
  232. decoded["announcement_seq"] = payload[6]
  233. return decoded
  234. if frame.frame_type == FrameType.HOST_CMD:
  235. if len(payload) < 1:
  236. return {"kind": "host_cmd", "error": "missing_cmd_id"}
  237. command_id = payload[0]
  238. decoded = {"kind": "host_cmd", "cmd": _enum_name(CommandId, command_id), "cmd_id": command_id}
  239. if command_id == int(CommandId.SET_PID_REQUESTED):
  240. if len(payload) < 2:
  241. decoded["error"] = "missing_enabled_flag"
  242. elif payload[1] not in (0, 1):
  243. decoded["error"] = "invalid_enabled_flag"
  244. decoded["enabled_raw"] = payload[1]
  245. else:
  246. decoded["enabled"] = payload[1] == 1
  247. return decoded
  248. if len(payload) >= 2:
  249. decoded["channel"] = payload[1]
  250. if len(payload) >= 3:
  251. decoded["percent"] = payload[2]
  252. return decoded
  253. if frame.frame_type == FrameType.HOST_ACK:
  254. if len(payload) < 6:
  255. return {"kind": "host_ack", "error": "short_payload", "payload_len": len(payload)}
  256. command_id = payload[1]
  257. return {
  258. "kind": "host_ack",
  259. "ok": payload[0] == 1,
  260. "cmd": _enum_name(CommandId, command_id),
  261. "cmd_id": command_id,
  262. "status_code": payload[2],
  263. "applied_state_hash": int.from_bytes(payload[4:6], "little"),
  264. }
  265. if frame.frame_type == FrameType.BMC_PAYLOAD:
  266. return {
  267. "kind": "bmc_payload",
  268. "payload_len_reported": payload[0] if len(payload) >= 1 else None,
  269. "payload_count": payload[1] if len(payload) >= 2 else None,
  270. "bmc_frame_seq": int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else None,
  271. "first_byte": payload[4] if len(payload) >= 5 else None,
  272. "last_byte": payload[5] if len(payload) >= 6 else None,
  273. "checksum": int.from_bytes(payload[6:8], "little") if len(payload) >= 8 else None,
  274. }
  275. if frame.frame_type == FrameType.SENSOR_CACHE:
  276. return {
  277. "kind": "sensor_cache",
  278. "profile_id_payload": payload[0] if len(payload) >= 1 else None,
  279. "bmc_frame_seq": int.from_bytes(payload[1:3], "little") if len(payload) >= 3 else None,
  280. "missing_mask": int.from_bytes(payload[3:6], "little") if len(payload) >= 6 else None,
  281. "valid_count": payload[6] if len(payload) >= 7 else None,
  282. "missing_count": payload[7] if len(payload) >= 8 else None,
  283. }
  284. if frame.frame_type == FrameType.ERROR_COUNTERS:
  285. return {"kind": "error_counters", "payload_len": len(payload)}
  286. if frame.frame_type == FrameType.MODULE_SNAPSHOT:
  287. decoded = {"kind": "module_snapshot", "payload_len": len(payload)}
  288. if len(payload) >= 20:
  289. decoded.update(
  290. {
  291. "profile_id_payload": payload[0],
  292. "host_err_count": payload[1],
  293. "command_count_seen": int.from_bytes(payload[2:4], "little"),
  294. "bmc_payload_first": payload[4],
  295. "bmc_payload_last": payload[5],
  296. "bmc_payload_checksum": int.from_bytes(payload[6:8], "little"),
  297. "last_cmd_id": payload[8],
  298. "last_cmd": _enum_name(CommandId, payload[8]),
  299. "last_cmd_ch": payload[9],
  300. "last_cmd_pct": payload[10],
  301. "last_status_code": payload[11],
  302. "pid_requested": payload[12] != 0,
  303. "timeout_active": payload[13] != 0,
  304. "valid_count": payload[14],
  305. "missing_count": payload[15],
  306. "ptc01_percent": payload[16],
  307. "ptc24_percent": payload[17],
  308. "fan01_percent": payload[18],
  309. "fan04_percent": payload[19],
  310. }
  311. )
  312. if len(payload) >= 21:
  313. decoded["fan_fg_mask"] = payload[20]
  314. if len(payload) >= 22:
  315. decoded["fan_install_mask"] = payload[21] & 0x0F
  316. return decoded
  317. return {"kind": _enum_name(FrameType, frame.frame_type).lower(), "payload_len": len(payload)}
  318. def frame_to_dict(frame: Binary921Frame) -> dict[str, object]:
  319. return {
  320. "version": frame.version,
  321. "profile_id": frame.profile_id,
  322. "frame_type": frame.frame_type,
  323. "frame_type_name": _enum_name(FrameType, frame.frame_type),
  324. "seq": frame.seq,
  325. "timestamp_tick": frame.timestamp_tick,
  326. "payload_hex": frame.payload.hex(),
  327. "crc16": f"{frame.crc16:04x}",
  328. "decoded": decode_payload(frame),
  329. }
  330. def cmd_decode(args: argparse.Namespace) -> int:
  331. data = Path(args.input).read_bytes()
  332. frames, remainder = decode_stream(data)
  333. payload = {
  334. "schema": "binary921-decode-v1",
  335. "status": "pass" if frames and not remainder else "blocked_incomplete_or_empty",
  336. "frames": [frame_to_dict(frame) for frame in frames],
  337. "remainder_hex": remainder.hex(),
  338. }
  339. print(json.dumps(payload, indent=2))
  340. return 0 if payload["status"] == "pass" else 1
  341. def build_parser() -> argparse.ArgumentParser:
  342. parser = argparse.ArgumentParser(description=__doc__)
  343. sub = parser.add_subparsers(dest="command", required=True)
  344. decode = sub.add_parser("decode")
  345. decode.add_argument("--input", required=True)
  346. decode.set_defaults(func=cmd_decode)
  347. return parser
  348. def main(argv: list[str] | None = None) -> int:
  349. parser = build_parser()
  350. args = parser.parse_args(argv)
  351. return int(args.func(args))
  352. if __name__ == "__main__":
  353. raise SystemExit(main(sys.argv[1:]))