跳到正文
DEV Community· UNITED UAV Official·· 45 分鐘前AI 評分43

UVH PNP 原型專案的獨立測試工具:如何用 Python 測試串流 SLIP 解碼器

UVH PNP bench tooling: test a streaming SLIP decoder in Python

AI 導讀

UVH PNP 原型專案的教學以 Python 建立獨立測試工具,使用合成位元組測試串流 SLIP 解碼器,並指出工具不連接硬件,也不代表平台介面或機載功能。解碼器須跨讀取區塊保留狀態,並確保相同有序位元組在不同分塊方式下產生相同訊息;範例設定候選資料上限為 256 bytes、單次 feed 上限為 4,096 bytes。

正文

A byte reader does not promise to return one application message per read. It may deliver half an escape sequence, several complete messages, or the end of one message followed by the beginning of another. A decoder that treats each returned chunk as a packet can appear correct with a convenient test fixture and fail as soon as buffering changes.

This tutorial builds independent bench tooling for a proposed prototype project using the UNITED UAV UVH PNP platform. UNITED UAV publishes this article and the linked listing. The modular aircraft supplies the project context. SLIP is an educational framing choice for this software exercise, not a claimed UVH PNP interface, onboard function or supplied payload protocol. The implementation connects to no hardware and uses synthetic bytes throughout.

UVH PNP fixed-wing VTOL platform shown in the UNITED UAV product catalog

Separate the stream from the messages

An input chunk is a transport observation: these bytes became available together. A message boundary is a protocol decision. The two can coincide during a demonstration without having any contractual relationship. Increasing a read buffer, changing a timeout or processing a saved capture with different block sizes should not change the decoded messages.

The useful invariant is therefore partition independence. Given identical ordered bytes and identical decoder configuration, feeding them in one allowed chunk or several allowed chunks must produce the same ordered payloads. Empty reads inserted between chunks should also preserve that result. This says nothing about missing or reordered bytes; those are changes to the stream itself.

Keep one decoder instance per continuous stream. Sharing an instance between independent connections would combine their partial candidates. Likewise, silently carrying an unfinished candidate into a replacement connection invents continuity that the capture does not establish. Create a new decoder when the surrounding application establishes a new stream identity.

Declare a small application profile

RFC 1055 documents SLIP's END byte, escape byte and two escape substitutions. The example uses hexadecimal C0 for END and DB for ESC, with DC and DD as their escaped forms. The RFC also discusses sending a leading END. Here every generated candidate has both leading and trailing boundaries.

Our receiver adds explicit application choices: discard the initial unbounded prefix, ignore empty candidates, accept only the two declared escape substitutions, and reject a malformed candidate through its next boundary. These are the rules of this strict bench profile. They should not be presented as the only possible behavior of every existing SLIP implementation.

The profile also caps a decoded candidate at 256 bytes and a single feed call at 4,096 bytes by default. Those are illustrative software limits, not UVH PNP payload capacities or a universal SLIP maximum. An actual interface agreement must supply its own permitted message sizes and transport behavior.

Make state survive a read boundary

The receiver needs to remember its current decoded candidate, whether an escape is pending, and whether it is discarding bytes. A pending escape is ordinary incomplete state when a read ends. It becomes an error only when subsequent input contradicts the declared grammar or a surrounding connection policy closes the attempt.

A raw END is handled before escape translation. That ordering lets a boundary terminate a candidate whose final byte was an unfinished escape. The candidate is rejected, its prefix is cleared, and the same boundary returns the receiver to an accepting state. It does not emit a packet containing a truncated prefix.

Once a candidate is rejected, ordinary following bytes must not become a new candidate immediately. The discard state lasts until a boundary arrives. Without that state, the suffix of an oversized or malformed message could be emitted later as a plausible independent payload, hiding the original error.

Use one original incremental implementation

END, ESC, ESC_END, ESC_ESC = 0xC0, 0xDB, 0xDC, 0xDD


def slip_encode(payload):
    if type(payload) is not bytes or not payload:
        raise ValueError("payload must be nonempty bytes")
    escaped = payload.replace(bytes([ESC]), bytes([ESC, ESC_ESC]))
    escaped = escaped.replace(bytes([END]), bytes([ESC, ESC_END]))
    return bytes([END]) + escaped + bytes([END])


class SlipDecoder:
    def __init__(self, max_frame=256, max_chunk=4096):
        for limit in (max_frame, max_chunk):
            if type(limit) is not int or limit < 1:
                raise ValueError("limits must be positive integers")
        self.max_frame = max_frame
        self.max_chunk = max_chunk
        self.rejected = 0
        self._frame = bytearray()
        self._escaped = False
        self._discard = True  # Wait for the first boundary.

    def _reject(self):
        self.rejected += 1
        self._frame.clear()
        self._escaped = False
        self._discard = True

    def feed(self, chunk):
        if type(chunk) is not bytes or len(chunk) > self.max_chunk:
            raise ValueError("chunk must be bytes within max_chunk")
        frames = []
        for value in chunk:
            if value == END:
                if not self._discard:
                    if self._escaped:
                        self.rejected += 1
                    elif self._frame:
                        frames.append(bytes(self._frame))
                self._frame.clear()
                self._escaped = False
                self._discard = False
                continue
            if self._discard:
                continue
            if self._escaped:
                self._escaped = False
                if value == ESC_END:
                    value = END
                elif value == ESC_ESC:
                    value = ESC
                else:
                    self._reject()
                    continue
            elif value == ESC:
                self._escaped = True
                continue
            if len(self._frame) >= self.max_frame:
                self._reject()
                continue
            self._frame.append(value)
        return frames

The public feed method takes an immutable bytes object. Its type and chunk-size checks run before the loop, so rejecting an invalid call does not partially consume that call's contents. The caller can distinguish an API misuse from a malformed candidate already observed inside an otherwise valid byte stream.

The encoder is a test helper for nonempty payloads. The receiver ignores empty delimiter intervals, so allowing the helper to promise round trips for an empty application message would be misleading. If an actual protocol needs meaningful empty messages, define a different profile and corresponding tests rather than guessing whether an empty interval was a separator or a message.

The implementation uses a mutable bytearray for the candidate and copies accepted data into bytes before returning it. Python's binary-sequence documentation describes those types. The copy gives the recipient an independent result; clearing the working buffer for the next candidate cannot alter a packet already returned.

Read a split escape as incomplete input

Consider a chunk ending immediately after DB. The receiver records that an escape is pending and returns no result for that unfinished candidate. If the next chunk starts with DC, it appends a literal C0 to the candidate. Chunk boundaries have not entered the protocol grammar at all.

Now change the next byte to an unsupported escape value. Our profile rejects the whole candidate and discards the remaining suffix until END. It does not preserve the valid-looking prefix, substitute a guessed byte, or resume accepting halfway through the suffix. That explicit outcome is easier to audit than a partial result whose origin has been lost.

An empty read between the escape and its continuation changes neither case. It is not a delimiter. A transport timeout may give the application a reason to record a stalled connection, but feeding an empty bytes object does not grant permission to complete the unfinished candidate.

Exercise fragmentation and recovery

payloads = [b"\x01\xc0\xdb\x02", b"second"]
wire = b"".join(slip_encode(p) for p in payloads)
decoder = SlipDecoder()
received = []
for value in wire:
    received.extend(decoder.feed(bytes([value])))
assert received == payloads

decoder = SlipDecoder(max_frame=8)
bad = b"\xc0bad\xdb\x00suffix\xc0"
assert decoder.feed(bad + slip_encode(b"ok")) == [b"ok"]
assert decoder.rejected == 1

decoder = SlipDecoder()
partial = slip_encode(b"unfinished")
assert decoder.feed(partial[:-1]) == []
assert decoder.feed(partial[-1:]) == [b"unfinished"]

The first exercise deliberately uses one-byte reads, including boundaries inside both escape pairs. The second injects an invalid escape followed by a printable suffix. Only the subsequent independently bounded candidate is returned. The rejection count provides evidence that the earlier candidate was discarded.

The final exercise withholds the closing boundary. No payload appears until that boundary arrives. This makes a useful distinction during debugging: a candidate can be syntactically valid so far and still be incomplete. Returning it early because a read happened to stop there would violate the stream model.

Keep the synthetic encoder and a literal expected wire vector in the tests. A matching encoder and decoder can share the same mistake, so a round trip alone is weak evidence. For the four-byte payload in the example, the literal wire hex is c001dbdcdbdd02c0. That independent fixture checks the mapping itself.

Reject overflow without publishing a truncated packet

The size check occurs before appending the next decoded byte. A candidate exactly at its configured limit is accepted if a boundary follows. If another decoded byte arrives first, the complete candidate is rejected and the buffer is cleared. No shortened payload is returned to the application.

Check the decoded size rather than confusing it with encoded input length. A reserved data byte takes an escape pair on the wire. For a payload of n bytes, this helper's worst-case encoded length is twice n plus the two boundaries. That arithmetic helps size a test capture or read loop; it is not a throughput measurement.

A long stream without a boundary cannot make this candidate buffer grow indefinitely. After overflow, the receiver discards further data until synchronization returns. The caller still needs an overall connection deadline or cancellation policy: bounded buffering does not prevent an unproductive stream from consuming processing time forever.

Bound a call as well as the pending candidate

Limiting only the unfinished candidate leaves another source of allocation. One huge input chunk could contain many tiny complete packets, and returning all of them in one list could produce a large result even though every individual candidate is small. This API therefore also bounds each accepted input chunk.

The reference returns a list for clarity. An integration handling larger captures can feed bounded blocks and drain the returned packets before requesting another block. If it adopts a callback or queue instead, it needs an explicit backpressure policy. Dropping accepted packets from a full queue should not masquerade as a parser rejection.

The decoder's candidate storage is bounded by its configured frame limit. Returned packets belong to the caller, while counters and application queues have their own lifetime. Keep those resource responsibilities separate when measuring the full tool rather than attaching a whole-system memory guarantee to one buffer check.

Test against a different style of oracle

For short captures, an independent batch oracle can split a fully bounded stream at raw delimiters, then validate each isolated candidate with an index-based escape decoder. That implementation has a different structure from the incremental state machine. Comparing their accepted payloads and rejection counts is more informative than running the same loop twice.

Generate short byte strings from an alphabet containing ordinary data, END, ESC and both substitution values. Add a final boundary so the oracle can classify the final candidate. For every generated stream, try every two-chunk split and insert an empty read at the split. The accepted outputs and counted candidate rejections should match.

This test deliberately includes malformed streams, not just correctly encoded payloads. It exercises initial noise, empty intervals, dangling escapes, invalid substitutions and small frame limits. Separate round-trip fixtures should cover all 256 byte values and a payload containing the complete byte range, including cuts through escaped data.

Preserve what a rejection count actually means

The counter records candidates rejected after the receiver has synchronized. It is not a count of all missing messages, corrupted bytes or transport failures. Startup bytes discarded before the first boundary have no established candidate identity. A lost delimiter can also change how several transmitted messages appear to the receiver.

Do not infer an error rate from the counter without a separately justified denominator. The number of feed calls depends on buffering, and the number of emitted payloads excludes rejected or never-completed candidates. Neither is automatically the number of messages the sender attempted to transmit.

For a bench investigation, preserve the raw capture and the read-chunk sequence or byte offsets needed to reproduce the observation. Keep application validation failures separate from framing rejections. A correctly delimited payload with an unsupported message version is a different result from a candidate whose escape grammar was malformed.

Keep framing separate from measurement validation

SLIP framing does not supply a checksum, sender authentication or application schema. A byte can change into another ordinary byte while the candidate remains grammatically acceptable. Strict escape handling detects particular malformed representations; it does not establish the correctness of all accepted bytes.

After framing, a separately specified payload decoder must check its own length, type, version, units and integrity fields where the actual interface defines them. Preserve those checks as independent outcomes. Receiving a complete byte sequence is not evidence that a sensor is calibrated, a timestamp is accurate or a measurement belongs to the intended job.

This layered interpretation also helps when proposing a different framing scheme. Keep the payload contract and its tests distinguishable from the stream decoder. Otherwise, a change intended to improve framing can silently alter numeric interpretation, while a successful packet counter conceals the semantic regression.

Define what happens when a connection ends

An unfinished candidate remains unfinished at end of input. The reference feed method does not invent an EOF packet or silently append a boundary. The application should record that the capture or connection ended with pending data and retain the relevant bytes under its diagnostic policy.

If a connection is replaced, start a new decoder and identify the new capture separately. Do not attach a new connection's prefix to the previous connection's partial buffer. That may create a valid-looking combined candidate even though the two byte sequences were never part of one continuous session.

A timeout-based abandonment policy can be added outside this reference. It needs its own definition of elapsed time, connection identity and logging behavior. For example, deciding to abandon a partial candidate should create a diagnostic event rather than incrementing a vaguely named success counter or pretending the candidate was complete.

Ask for the actual payload interface before adapting the tool

For a UVH PNP prototype proposal, request the intended configuration and documented interface before connecting any software. Relevant details include electrical signaling, byte encoding, actual message framing, maximum sizes, reconnect behavior and ownership of timestamps or sequence numbers. The product listing's modular context does not determine those fields.

Use a representative interface capture to test a bench tool only after those facts are agreed. A useful demonstration includes arbitrary read splits, multiple messages in one read, malformed input, an oversized candidate and recovery at a later boundary. Compare the same capture under different chunk partitions to expose accidental read-size dependencies.

The deliverable is a decoder with declared acceptance and discard behavior, supported by reproducible synthetic tests and later by the proposed interface's own fixtures. That gives a developer a concrete boundary to inspect when a prototype's logs look plausible but its messages change when buffering changes.

Written with AI assistance; the implementation and examples are offline synthetic exercises.

來源:DEV Community · dev.to