#!/usr/bin/env python3 """Offline packet/page examples, not a flasher. No network or Bluetooth code. Run python3 protocol_examples.py --self-test for independent literal fixtures. Functions accept explicit sequences; no live request allocator is provided. """ import argparse import struct ESCAPES = {0x8D: b"\xAB\x05", 0xD8: b"\xAB\x50", 0xAB: b"\xAB\x23"} UNESCAPES = {5: 0x8D, 0x50: 0xD8, 0x23: 0xAB} AUDIO_COMPLETION = bytes.fromhex("8D 00 1E 07 00 DA D8") FINISH_SUCCESS = bytes.fromhex("8D 00 1D 09 FF 01 D9 D8") def encode_untargeted(device, command, sequence, payload=b"", flags=0x0A): if flags & ~0x0F or not isinstance(payload, bytes) or len(payload) > 4096: raise ValueError("This example only supports bounded untargeted packets") body = bytes((flags, device, command, sequence)) + payload body += bytes((~sum(body) & 255,)) return b"\x8D" + b"".join(ESCAPES.get(b, bytes((b,))) for b in body) + b"\xD8" def decode_untargeted(frame): if not 7 <= len(frame) <= 8204 or frame[0] != 0x8D or frame[-1] != 0xD8: raise ValueError("Invalid frame boundary/length") body, escaped = bytearray(), False for byte in frame[1:-1]: if escaped: if byte not in UNESCAPES: raise ValueError("Unknown escape") body.append(UNESCAPES[byte]); escaped = False elif byte == 0xAB: escaped = True elif byte in (0x8D, 0xD8): raise ValueError("Unescaped delimiter") else: body.append(byte) if escaped or not 5 <= len(body) <= 4101 or body[0] & ~0x0F or sum(body) & 255 != 255: raise ValueError("Invalid body/checksum or unsupported routed packet") return {"flags": body[0], "device": body[1], "command": body[2], "sequence": body[3], "payload": bytes(body[4:-1])} def st_pages(image): if len(image) != 262144: raise ValueError("Reference ST image must be exactly 262144 bytes") for offset in range(0, len(image), 2048): page = image[offset:offset + 2048] if page != b"\xFF" * 2048: address = 0x80 + offset // 2048 yield address, struct.pack(">H", address) + page def dfu_application_sizes(byte_count): if not 0 < byte_count <= 0xFFFFFFFF: raise ValueError("Invalid application size") return struct.pack("