Field-tested notes on robotics safety, ROS 2, embedded AI, AI agents, SaaS architecture and the practical systems that connect software to real-world outcomes.

UART Packet Recovery for Robots: Bound the Parser, Then Resynchronize

Edge computer and robot microcontroller connected to a serial packet diagnostic display

A serial bridge can pass a loopback test and still fail after its first interrupted packet. The receiver waits for a length that will never arrive, keeps appending bytes after a missing terminator, or interprets the tail of an old message as the beginning of a new one. A faster baud rate fixes none of these failures.

Treat UART input as an arbitrary byte stream. Put a hard limit on each packet candidate, give incomplete candidates an assembly deadline, and define the boundary that ends recovery. After an overflow or deadline, clearing the buffer is only half the operation: the receiver must discard the remaining fragment through the next delimiter before collecting again.

The example below makes that behavior executable. It is a small telemetry framing exercise for a robot’s edge-computer-to-microcontroller link, with synthetic fault tests. It is not a measured UART implementation or a motion-command protocol.

Decide what the receiver is allowed to promise

The electrical setup in the Jetson UART guide gets bytes across a link. Application framing has a different job: decide which consecutive bytes constitute a message that can be decoded.

A call to read(256) is not a packet boundary. It might return a fragment, several packets, or nothing. The pySerial API explicitly allows reads to return fewer bytes when a timeout is configured. Keep parser state across reads; do not interpret a read timeout as proof that a message ended.

For this receiver, acceptance means only that one delimited candidate has a valid encoding, permitted size, matching checksum, supported version and consistent payload length. It does not establish who sent it, when the sensor acquired it, or whether its contents are physically plausible.

First check whether the device already speaks a maintained protocol. Micro XRCE-DDS supplies a stream framing layer with HDLC-style byte stuffing and a CRC. The micro-ROS bridge architecture discusses when that middleware is useful. Preserve an existing protocol’s framing and use its implementation; do not wrap it in this exercise by default.

The useful design question, even with an established library, is precise: after which fault, and after which boundary, may the parser emit another message?

Make the wire-size bound independent of the received length

This teaching format is deliberately small:

1
2
raw candidate = version:u8 | payload_length:u8 | payload:0..64 bytes | CRC:4 bytes
wire packet = COBS(raw candidate) | 0x00

The CRC covers the version, length and payload. It uses Python’s zlib.crc32 with its default initial argument, serialized as four little-endian bytes. The familiar input 123456789 produces 0xcbf43926; include that check value when implementing the other endpoint. Python documents the calculation and its non-cryptographic purpose in the zlib reference.

Consistent Overhead Byte Stuffing, by Cheshire and Baker, removes zero bytes from an encoded candidate so that zero can mark its boundary. Here, the raw candidate is at most 70 bytes. Because that is below 254 bytes, the short-frame encoding adds exactly one byte; the delimiter adds another. The maximum wire packet is therefore 72 bytes. The code intentionally implements only this short-frame subset, not a general-purpose COBS library.

The length field is a consistency check after decoding. It never tells the receiver to allocate memory or wait for an arbitrary number of bytes. The encoded candidate buffer has an independent 71-byte limit.

At an assumed 115,200 baud with 8N1 framing, 72 bytes require 72 × 10 / 115200 = 6.25 ms of uninterrupted serialization. Sending maximum-size packets at 100 Hz consumes 62.5% of one direction’s line capacity before other traffic. These are calculated wire budgets, not measured latency or a timeout recommendation.

An assembly deadline must also allow for the sender’s permitted pauses, transport buffering and the receiver’s scheduling behavior. The example uses 50 ms to exercise the state machine. Qualify a real value through the sensor-to-actuator timing budget; a deadline shorter than permitted delivery delays rejects healthy traffic.

Recovery has a discard state

There are three useful states: waiting for a boundary, collecting a candidate, and idle after a boundary. Waiting and discarding use the same implementation: ignore nonzero bytes until a zero arrives.

EventReceiver actionWhat permits collection again?
Process starts or reconnects midstreamDiscard the initial fragmentA received zero delimiter
Nonzero byte after a boundaryStart or extend the candidateAlready collecting within the bound
Candidate would exceed 71 encoded bytesClear it, count overflow, enter discard stateA received zero delimiter
Assembly deadline expiresClear it, count expiry, enter discard stateA received zero delimiter
Delimiter closes an invalid candidateCount the validation failure and clear itThat delimiter already establishes a new boundary
Delimiter closes a valid candidateEmit its payload and clear itCollect the following candidate
Repeated delimitersIgnore empty candidatesRemain ready

On connection startup, the sender can emit an extra zero before its first packet. Otherwise this conservative receiver sacrifices the first candidate it sees. That is intentional: it cannot know whether the process attached at a true packet start.

A missing delimiter can merge two candidates. The receiver may lose both before the next intact boundary. “Resynchronized” means it can collect a subsequent complete candidate; it does not mean the lost data has been reconstructed. If delimiters never return, it keeps dropping bytes with bounded candidate storage.

The assembly clock starts when the application observes the first byte of a candidate. Later fragments do not refresh it. A peer that dribbles bytes slowly therefore cannot keep one candidate alive indefinitely. However, this clock cannot measure time already spent in a device or kernel queue, and a complete old packet delivered in one read can still pass. Freshness needs a separate timestamp and session contract.

A receiver you can exercise without hardware

Save this as receiver.py and run it with Python 3. It has no third-party dependency. feed() receives a bounded chunk and a monotonic time value. Call it on empty reads too, so inactivity can expire a partial candidate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
from collections import Counter
from zlib import crc32

MAX_PAYLOAD = 64
MAX_RAW = 2 + MAX_PAYLOAD + 4
MAX_ENCODED = MAX_RAW + 1 # This example stays below 254 raw bytes.


def encode(raw):
if len(raw) >= 254:
raise ValueError("short-frame encoder only")
return b"".join(bytes([len(run) + 1]) + run
for run in raw.split(b"\x00"))


def decode(encoded):
if not 1 <= len(encoded) <= MAX_ENCODED or 0 in encoded:
raise ValueError("encoded size or embedded delimiter")
raw = bytearray()
i = 0
while i < len(encoded):
end = i + encoded[i]
if end > len(encoded):
raise ValueError("truncated COBS block")
raw.extend(encoded[i + 1:end])
i = end
if i < len(encoded):
raw.append(0)
return bytes(raw)


def frame(payload):
if len(payload) > MAX_PAYLOAD:
raise ValueError("payload too large")
body = bytes([1, len(payload)]) + payload
return encode(body + crc32(body).to_bytes(4, "little")) + b"\x00"


def validate(encoded):
raw = decode(encoded)
if not 6 <= len(raw) <= MAX_RAW:
raise ValueError("raw size")
body, check = raw[:-4], raw[-4:]
if crc32(body) != int.from_bytes(check, "little"):
raise ValueError("CRC")
if body[0] != 1 or body[1] != len(body) - 2:
raise ValueError("version or length")
return body[2:]


class Receiver:
def __init__(self, deadline=0.050):
self.deadline = deadline
self.buf = bytearray()
self.started = None
self.dropping = True # Startup may be in the middle of a frame.
self.errors = Counter()

def discard(self, reason):
self.errors[reason] += 1
self.buf.clear()
self.started = None
self.dropping = True

def feed(self, chunk, now):
# Caller supplies monotonic seconds, even for an empty read.
if self.started is not None and now - self.started >= self.deadline:
self.discard("deadline")
accepted = []
for byte in chunk:
if byte == 0:
if not self.dropping and self.buf:
try:
accepted.append(validate(bytes(self.buf)))
except ValueError as error:
self.errors[str(error)] += 1
self.buf.clear()
self.started = None
self.dropping = False
elif self.dropping:
continue
elif len(self.buf) == MAX_ENCODED:
self.discard("oversize")
else:
if self.started is None:
self.started = now
self.buf.append(byte)
return accepted


if __name__ == "__main__":
a, b, c = frame(b"A\x00B"), frame(b"second"), frame(b"third")
stream = b"\x00" + a + b
for split in range(len(stream) + 1):
rx = Receiver()
got = rx.feed(stream[:split], 0.0)
got += rx.feed(stream[split:], 0.001)
assert got == [b"A\x00B", b"second"]
rx = Receiver()
# Lost delimiter merges two candidates; the third is recoverable.
assert rx.feed(b"\x00" + a[:-1] + b + c, 0.0) == [b"third"]
rx = Receiver()
assert rx.feed(b"\x00" + a[:3], 0.0) == []
assert rx.feed(b"", 0.050) == []
assert rx.errors["deadline"] == 1
assert rx.feed(a[3:] + b, 0.051) == [b"second"]
rx = Receiver()
assert rx.feed(b"\x00" + b"x" * 1000, 0.0) == []
assert len(rx.buf) == 0 and rx.dropping
assert rx.feed(b"\x00" + c, 0.001) == [b"third"]
print(f"PASS: {len(stream) + 1} read splits; delimiter, deadline, overflow recovery")

The embedded checks print:

1
PASS: 27 read splits; delimiter, deadline, overflow recovery

Use a single owner for this stateful receiver. In a pySerial loop, pass a finite-size read and time.monotonic() to feed(), including when the read returns b"". Keep the read timeout short enough to service the assembly deadline. This checks expiry when the application runs; it does not guarantee a deadline under an indefinitely stalled process. Recreate the receiver after disconnect or reconnect so that a partial candidate cannot survive into another connection.

Only the candidate buffer is bounded here. The serial driver’s queue, the size of each feed() input, its returned payload list and the downstream telemetry queue need their own limits. For a high-rate robot, count errors without printing a line for every malformed packet; synchronous logging can become the next source of receive starvation.

Test the first accepted packet after the fault

A useful parser test must check recovery as well as rejection. Append known valid packets after the damaged bytes and verify what the receiver emits. Otherwise a parser that silently wedges forever can appear to pass every corruption test.

The receiver source and extended fault checks are available as plain Python files. Save both in the same directory, then run python3 test_receiver.py. The latter writes an artifact-review.json receipt alongside the files.

The extended checks passed locally with six hand-worked encoding vectors, 260 payload round trips across lengths 0–64, and a separate bitwise CRC calculation. They also exercised all 86 two-chunk splits of a maximum-size packet followed by a short packet, plus byte-at-a-time delivery.

For one chosen maximum-size wire packet, the fault sweep covered 576 individual bit flips, 72 single-byte deletions and 219 insertions of selected byte values. In those 867 synthetic cases, no unexpected payload was emitted and a later intact packet was recovered. Additional checks covered startup, exact buffer capacity, repeated delimiters, the deadline boundary, slow fragments that must not renew the deadline, and invalid version/length/checksum cases.

These results describe those inputs. They are not an exhaustive proof, an estimate of undetected corruption probability, a hostile-peer security test or a benchmark of an MCU implementation. A CRC can miss errors and can be recomputed by an attacker. Passing it does not authenticate a sender.

On the actual bridge, repeat the failure scenarios while recording both the byte stream and parser counters. Cut transmission partway through a packet; reset each endpoint separately; deliver a burst larger than the application’s normal read size; stall the receiver under CPU load; and saturate the downstream consumer. For each case, record the first accepted packet after the fault, maximum buffered bytes, discard duration and any driver overrun evidence. Compare that behavior with the configured deadline and allowed telemetry loss.

Finally, keep packet acceptance below application authority. A structurally valid telemetry sample can be stale, from a previous boot, or outside a sensor’s range. A structurally valid command can be a duplicate or no longer authorized. Session identity, sequence handling, acquisition time and physical limits belong in the application contract; the robot command-validation layer addresses that next boundary. Recovering a byte stream should restore communication, never implicitly restore permission to move.