Quick Start
A telemetry protocol, from definition to receiver
A device sends frames over a serial line or a socket. Each has a sync word, a timestamp, a byte of packed status bits, a list of fixed-point temperatures, and a CRC-32.
Define the format
from dataclasses import field
from datetime import UTC, datetime
from enum import IntEnum
from typing import Annotated
from binal import (
CRC32,
Array,
BinaryModel,
BitModel,
Bits,
Checksum,
Const,
CountOf,
FixedPoint,
Range,
Timestamp,
UInt8,
UInt16,
UInt32,
UInt64,
)
class Mode(IntEnum):
IDLE = 0
RUNNING = 1
FAULT = 2
class Status(BitModel, bit_order="msb"):
mode: Annotated[Mode, Bits(2)]
calibrated: Annotated[bool, Bits(1)]
battery: Annotated[int, Bits(5)]
class Reading(BinaryModel, byte_order="little"):
sensor: UInt8
celsius: Annotated[float, FixedPoint(16, 8), Range(-40.0, 125.0)]
class Frame(BinaryModel, byte_order="little"):
sync: Annotated[UInt16, Const(0xA55A)] = field(init=False)
time: Annotated[datetime, Timestamp(UInt64, "ms")]
status: Status
count: Annotated[UInt8, CountOf("readings")] = field(init=False)
readings: Annotated[list[Reading], Array("count")]
crc: Annotated[
UInt32, Checksum(CRC32, fields=("sync", "time", "status", "count", "readings"))
] = field(init=False) The annotation is the format; the attribute is an ordinary Python value.
time is a datetime, status.mode an enum member, and celsius a
float, and a type checker sees them as such.
Encode and decode
The sync word, the count, and the CRC take no argument. Encoding computes them.
frame = Frame(
time=datetime(2026, 1, 1, 8, 0, tzinfo=UTC),
status=Status(mode=Mode.RUNNING, calibrated=True, battery=28),
readings=[Reading(1, 21.5), Reading(2, -3.25)],
)
data = frame.encode()
data[:12].hex(" ") # '5a a5 00 1c 92 78 9b 01 00 00 7c 02'
frame.count # 2
assert Frame.decode(data) == frame Refuse bad data
Decoding verifies everything the model states, and an error names the field and the byte.
from binal import DecodeError, ValidationError
damaged = bytearray(data)
damaged[12] ^= 0x01
try:
Frame.decode(damaged)
except DecodeError as error:
print(error.path, error.offset) # Frame.crc 18
try:
Reading(1, 300.0)
except ValidationError as error:
print(error.path, error.expected) # Reading.celsius value between -40.0 and 125.0 Receive frames as they arrive
A socket delivers pieces, not frames. A parser keeps what is incomplete until the rest arrives.
parser = Frame.incremental_parser()
parser.feed(data[:10]) # []: not a whole frame yet
parser.feed(data[10:] + data[:5]) # [Frame(...)]: one, and the start of the next
parser.feed(data[5:]) # [Frame(...)]
parser.close() # None: nothing is left over The same model reads and writes files, streams, and asyncio streams;
see I/O.
See the layout
for item in frame.layout().fields:
print(item.byte_offset, item.byte_size, item.name)
# 0 2 sync
# 2 8 time
# 10 1 status
# 11 1 count
# 12 6 readings
# 18 4 crc Next
- Binary Models explains the constructor, derived fields, and byte order.
- Modeling covers unions, conditions, references, and compressed data.
- The overview lists everything by what your format needs.