
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 | raw candidate = version:u8 | payload_length:u8 | payload:0..64 bytes | CRC:4 bytes |
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.
| Event | Receiver action | What permits collection again? |
|---|---|---|
| Process starts or reconnects midstream | Discard the initial fragment | A received zero delimiter |
| Nonzero byte after a boundary | Start or extend the candidate | Already collecting within the bound |
| Candidate would exceed 71 encoded bytes | Clear it, count overflow, enter discard state | A received zero delimiter |
| Assembly deadline expires | Clear it, count expiry, enter discard state | A received zero delimiter |
| Delimiter closes an invalid candidate | Count the validation failure and clear it | That delimiter already establishes a new boundary |
| Delimiter closes a valid candidate | Emit its payload and clear it | Collect the following candidate |
| Repeated delimiters | Ignore empty candidates | Remain 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 | from collections import Counter |
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.
