#!/usr/bin/env python3 """J6 binary921 host/debug frame helpers. The CPLD emits and accepts compact binary frames so the expensive ASCII formatting stays in the PC-side harness. """ from __future__ import annotations import argparse import json import re import sys from dataclasses import dataclass from enum import IntEnum from pathlib import Path from typing import Iterable MAGIC = b"\xA5\x5A" VERSION = 1 HEADER_LEN = 14 CRC_LEN = 2 MAX_PAYLOAD_LEN = 255 PROFILE_NAME_TO_ID = { "debug-photo-bmc-replay-binary921": 1, "formal-uart1-bmc-replay-binary921": 2, "production-two-uart-bmc-replay-binary921": 3, "prod2u-bmc-replay-binary921": 3, } PROFILE_ID_TO_NAME = { 1: "debug-photo-bmc-replay-binary921", 2: "formal-uart1-bmc-replay-binary921", 3: "production-two-uart-bmc-replay-binary921", } BUILD_ID_RE = re.compile(r"^[0-9A-Fa-f]{8}$") class Binary921FrameError(ValueError): """Raised when a binary921 frame cannot be decoded safely.""" class FrameType(IntEnum): READY = 0x01 BMC_POLL = 0x02 BMC_PAYLOAD = 0x03 SENSOR_CACHE = 0x04 HOST_CMD = 0x05 HOST_ACK = 0x06 PWM_STATE = 0x07 PID_STATE = 0x08 TIMEOUT_STATE = 0x09 PIN_PROFILE = 0x0A MODULE_SNAPSHOT = 0x0B ERROR_COUNTERS = 0x0C class CommandId(IntEnum): SET_PTC = 0x20 SET_FAN = 0x21 GET_SENSOR = 0x22 GET_MAP = 0x23 GET_STATUS = 0x24 SET_PID_REQUESTED = 0x25 DISABLE = 0x26 def profile_id_for_name(profile: str) -> int: try: return PROFILE_NAME_TO_ID[profile] except KeyError as exc: raise ValueError(f"unknown binary921 profile: {profile}") from exc def profile_name_for_id(profile_id: int) -> str: try: return PROFILE_ID_TO_NAME[int(profile_id)] except KeyError as exc: raise ValueError(f"unknown binary921 profile id: {profile_id}") from exc def format_build_id(build_id: int | str) -> str: """Return a binary921 32-bit build ID as canonical uppercase JSON text.""" if isinstance(build_id, bool): raise ValueError("build_id must be a 32-bit integer or eight hex digits") if isinstance(build_id, int): if build_id < 0 or build_id > 0xFFFFFFFF: raise ValueError("build_id must fit in 32 bits") return f"{build_id:08X}" if isinstance(build_id, str): value = build_id.strip() if BUILD_ID_RE.fullmatch(value): return value.upper() raise ValueError("build_id must be a 32-bit integer or eight hex digits") @dataclass(frozen=True) class Binary921Frame: version: int profile_id: int frame_type: int seq: int timestamp_tick: int payload: bytes crc16: int raw: bytes def crc16_ccitt(data: bytes, *, initial: int = 0xFFFF) -> int: crc = initial & 0xFFFF for byte in data: crc ^= byte << 8 for _ in range(8): if crc & 0x8000: crc = ((crc << 1) ^ 0x1021) & 0xFFFF else: crc = (crc << 1) & 0xFFFF return crc & 0xFFFF def _le_u32(value: int) -> bytes: if value < 0 or value > 0xFFFFFFFF: raise ValueError("u32 value out of range") return value.to_bytes(4, "little") def encode_frame( *, profile_id: int, frame_type: int, seq: int, timestamp_tick: int, payload: bytes | bytearray | Iterable[int], ) -> bytes: payload_bytes = bytes(payload) if profile_id < 0 or profile_id > 0xFF: raise ValueError("profile_id must fit in one byte") if int(frame_type) < 0 or int(frame_type) > 0xFF: raise ValueError("frame_type must fit in one byte") if len(payload_bytes) > MAX_PAYLOAD_LEN: raise ValueError("payload too long for binary921 v1") body = bytes( [ VERSION, profile_id & 0xFF, int(frame_type) & 0xFF, ] ) body += _le_u32(seq) body += _le_u32(timestamp_tick) body += bytes([len(payload_bytes)]) body += payload_bytes crc = crc16_ccitt(body) return MAGIC + body + crc.to_bytes(2, "little") def decode_frame(frame: bytes | bytearray) -> Binary921Frame: raw = bytes(frame) if len(raw) < HEADER_LEN + CRC_LEN: raise Binary921FrameError("short binary921 frame") if raw[:2] != MAGIC: raise Binary921FrameError("bad binary921 magic") payload_len = raw[13] expected_len = HEADER_LEN + payload_len + CRC_LEN if len(raw) != expected_len: raise Binary921FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}") body = raw[2:-2] expected_crc = crc16_ccitt(body) actual_crc = int.from_bytes(raw[-2:], "little") if actual_crc != expected_crc: raise Binary921FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}") version = raw[2] if version != VERSION: raise Binary921FrameError(f"unsupported binary921 version {version}") return Binary921Frame( version=version, profile_id=raw[3], frame_type=raw[4], seq=int.from_bytes(raw[5:9], "little"), timestamp_tick=int.from_bytes(raw[9:13], "little"), payload=raw[14 : 14 + payload_len], crc16=actual_crc, raw=raw, ) def decode_stream(data: bytes | bytearray) -> tuple[list[Binary921Frame], bytes]: buf = bytes(data) frames: list[Binary921Frame] = [] offset = 0 while True: magic_at = buf.find(MAGIC, offset) if magic_at < 0: tail = buf[-1:] if buf.endswith(MAGIC[:1]) else b"" return frames, tail if magic_at + HEADER_LEN + CRC_LEN > len(buf): return frames, buf[magic_at:] payload_len = buf[magic_at + 13] end = magic_at + HEADER_LEN + payload_len + CRC_LEN if end > len(buf): return frames, buf[magic_at:] candidate = buf[magic_at:end] try: frames.append(decode_frame(candidate)) offset = end except Binary921FrameError: offset = magic_at + 1 def build_host_command( *, seq: int, command: int, channel: int | None = None, percent: int | None = None, profile_id: int = 1, timestamp_tick: int = 0, ) -> bytes: command_id = CommandId(int(command)) if command_id == CommandId.SET_PTC: if channel is None or channel < 1 or channel > 24: raise ValueError("PTC channel must be 1..24") if percent is None or percent < 0 or percent > 100: raise ValueError("percent must be 0..100") payload = bytes([command_id, channel, percent]) elif command_id == CommandId.SET_FAN: if channel is None or channel < 1 or channel > 4: raise ValueError("FAN channel must be 1..4") if percent is None or percent < 0 or percent > 100: raise ValueError("percent must be 0..100") payload = bytes([command_id, channel, percent]) elif command_id == CommandId.SET_PID_REQUESTED: if percent not in (0, 1): raise ValueError("SET_PID_REQUESTED uses percent as enabled flag 0/1") payload = bytes([command_id, percent]) else: payload = bytes([command_id]) return encode_frame( profile_id=profile_id, frame_type=FrameType.HOST_CMD, seq=seq, timestamp_tick=timestamp_tick, payload=payload, ) def _enum_name(enum_cls: type[IntEnum], value: int) -> str: try: return enum_cls(value).name except ValueError: return f"UNKNOWN_0x{value:02X}" def decode_payload(frame: Binary921Frame) -> dict[str, object]: payload = frame.payload if frame.frame_type == FrameType.READY: decoded: dict[str, object] = {"kind": "ready"} if len(payload) >= 1: decoded["profile_id_payload"] = payload[0] if len(payload) >= 5: decoded["build_id"] = format_build_id(int.from_bytes(payload[1:5], "little")) decoded["startup_epoch"] = frame.seq decoded["startup_tick"] = frame.timestamp_tick if len(payload) >= 6: decoded["por_reason"] = payload[5] if len(payload) >= 7: decoded["announcement_seq"] = payload[6] return decoded if frame.frame_type == FrameType.HOST_CMD: if len(payload) < 1: return {"kind": "host_cmd", "error": "missing_cmd_id"} command_id = payload[0] decoded = {"kind": "host_cmd", "cmd": _enum_name(CommandId, command_id), "cmd_id": command_id} if command_id == int(CommandId.SET_PID_REQUESTED): if len(payload) < 2: decoded["error"] = "missing_enabled_flag" elif payload[1] not in (0, 1): decoded["error"] = "invalid_enabled_flag" decoded["enabled_raw"] = payload[1] else: decoded["enabled"] = payload[1] == 1 return decoded if len(payload) >= 2: decoded["channel"] = payload[1] if len(payload) >= 3: decoded["percent"] = payload[2] return decoded if frame.frame_type == FrameType.HOST_ACK: if len(payload) < 6: return {"kind": "host_ack", "error": "short_payload", "payload_len": len(payload)} command_id = payload[1] return { "kind": "host_ack", "ok": payload[0] == 1, "cmd": _enum_name(CommandId, command_id), "cmd_id": command_id, "status_code": payload[2], "applied_state_hash": int.from_bytes(payload[4:6], "little"), } if frame.frame_type == FrameType.BMC_PAYLOAD: return { "kind": "bmc_payload", "payload_len_reported": payload[0] if len(payload) >= 1 else None, "payload_count": payload[1] if len(payload) >= 2 else None, "bmc_frame_seq": int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else None, "first_byte": payload[4] if len(payload) >= 5 else None, "last_byte": payload[5] if len(payload) >= 6 else None, "checksum": int.from_bytes(payload[6:8], "little") if len(payload) >= 8 else None, } if frame.frame_type == FrameType.SENSOR_CACHE: return { "kind": "sensor_cache", "profile_id_payload": payload[0] if len(payload) >= 1 else None, "bmc_frame_seq": int.from_bytes(payload[1:3], "little") if len(payload) >= 3 else None, "missing_mask": int.from_bytes(payload[3:6], "little") if len(payload) >= 6 else None, "valid_count": payload[6] if len(payload) >= 7 else None, "missing_count": payload[7] if len(payload) >= 8 else None, } if frame.frame_type == FrameType.ERROR_COUNTERS: return {"kind": "error_counters", "payload_len": len(payload)} if frame.frame_type == FrameType.MODULE_SNAPSHOT: decoded = {"kind": "module_snapshot", "payload_len": len(payload)} if len(payload) >= 20: decoded.update( { "profile_id_payload": payload[0], "host_err_count": payload[1], "command_count_seen": int.from_bytes(payload[2:4], "little"), "bmc_payload_first": payload[4], "bmc_payload_last": payload[5], "bmc_payload_checksum": int.from_bytes(payload[6:8], "little"), "last_cmd_id": payload[8], "last_cmd": _enum_name(CommandId, payload[8]), "last_cmd_ch": payload[9], "last_cmd_pct": payload[10], "last_status_code": payload[11], "pid_requested": payload[12] != 0, "timeout_active": payload[13] != 0, "valid_count": payload[14], "missing_count": payload[15], "ptc01_percent": payload[16], "ptc24_percent": payload[17], "fan01_percent": payload[18], "fan04_percent": payload[19], } ) if len(payload) >= 21: decoded["fan_fg_mask"] = payload[20] if len(payload) >= 22: decoded["fan_install_mask"] = payload[21] & 0x0F return decoded return {"kind": _enum_name(FrameType, frame.frame_type).lower(), "payload_len": len(payload)} def frame_to_dict(frame: Binary921Frame) -> dict[str, object]: return { "version": frame.version, "profile_id": frame.profile_id, "frame_type": frame.frame_type, "frame_type_name": _enum_name(FrameType, frame.frame_type), "seq": frame.seq, "timestamp_tick": frame.timestamp_tick, "payload_hex": frame.payload.hex(), "crc16": f"{frame.crc16:04x}", "decoded": decode_payload(frame), } def cmd_decode(args: argparse.Namespace) -> int: data = Path(args.input).read_bytes() frames, remainder = decode_stream(data) payload = { "schema": "binary921-decode-v1", "status": "pass" if frames and not remainder else "blocked_incomplete_or_empty", "frames": [frame_to_dict(frame) for frame in frames], "remainder_hex": remainder.hex(), } print(json.dumps(payload, indent=2)) return 0 if payload["status"] == "pass" else 1 def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) decode = sub.add_parser("decode") decode.add_argument("--input", required=True) decode.set_defaults(func=cmd_decode) return parser def main(argv: list[str] | None = None) -> int: parser = build_parser() args = parser.parse_args(argv) return int(args.func(args)) if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))