Skip to content

Link

Link transform: data bits <-> packets: framing (HDLC, byte stuffing) and integrity checks (CRC, composite, checksum), defined in config/crc, config/frame and config/header/link. Decoding refuses channel bits: decode them first (or rp.code.Uncoded() for no FEC)

A link header decodes packets too: a header inside a frame's payload ({"link": "frame"} then {"link": "header"}, the frame step's frame and frame_bits driving the header's frame and length) strips a frame's own header and reads it.

Packets that cross frames (rpps.link.packets, {"link": "packets"}): a stream of packets in fixed frames' data fields, cut back out by a pointer (CCSDS first header pointer, DVB-S2 SYNCD) and each packet's length, per channel.

Captures (rpps.link.capture): a profile's messages as packets of a link type (config/linktype), for Wireshark and interfaces (rpps.source.PcapSink, rpps.source.Tun), each rule with its inverse for transmitting.

Modules:

Name Description
bytestuff
capture

Captures: decoded frames as packets of a link type, for Wireshark (rpps.source.PcapSink) or an interface (rpps.source.Tun)

check

Composite checks: a check field built from CRCs over transformed views of the message

checksum

Checksums that are not CRCs: sums, ones' complement (Internet), Fletcher, Adler, XOR (LRC)

crc
encap

Encapsulation parent classes

fields

Fields: what a frame's bits say, as a definition (link headers, frame payloads, a profile step's messages)

gse

Generic Stream Encapsulation (ETSI TS 102 606-1): PDUs in the data fields of DVB-S2 BBFRAMEs

hdlc
header

Link headers: fields, a CRC, and the payload they announce (rpps.profile.control)

kernels

Batch kernels of the link operators: HeaderDecode of a framed header (rpps.parallel)

packets

Packets that cross frames: a stream of packets carried in the data fields of fixed frames, cut back into packets

serial

Link definitions, one resource each: config/crc, config/frame, config/header/link; rp.link.load("crc/crc32_mpeg2")

bytestuff

Classes:

Name Description
bytestuff

Byte-stuffed framing (SLIP, KISS, asynchronous PPP): a flag byte between frames, and an escape byte before any

bytestuff

bytestuff(log, flag=192, escape=219, escapes=None, xor=None, escaped=None, fcs=None, refin=False, min_bytes=1)

Bases: _code

Byte-stuffed framing (SLIP, KISS, asynchronous PPP): a flag byte between frames, and an escape byte before any flag or escape byte inside one, defined by config (see config/frame)

flag: the frame delimiter (SLIP / KISS 0xC0, PPP 0x7E). escape: the escape byte (0xDB, 0x7D). escapes: {byte: what follows the escape for it} (SLIP: {0xC0: 0xDC, 0xDB: 0xDD}); or xor: the escaped byte is the byte XOR this (PPP 0x20), for the bytes in escaped (flag and escape when not given). fcs: a crc (or checksum) appended to each frame, or None. refin: bytes sent least significant bit first (a UART); the bit stream is in bytes from its first bit. min_bytes: shortest frame (with the FCS) kept.

The same interface as hdlc: encode(frames) the bits of a list of byte frames; frames_at(bits) every frame between flags as (index of its opening flag's first bit, payload, fcs ok) and the aborts (an escape before a byte it doesn't escape); decode_stream(bits, held) for a stream cut anywhere.

Methods:

Name Description
frame

The bytes of one frame: flag, the stuffed payload and FCS, flag

frames_at

Frames as (index of the opening flag in bits, payload bytes, fcs ok, the FCS bytes received: b"" without an

consumed

How many of these bits are done with: whole bytes up to the last flag (a frame may be open there), or all whole

decode_stream

Decode held (what the last call kept) and bits together: (data bits of the good frames, what to hold).

Source code in src/rpps/link/bytestuff.py
def __init__(self, log, flag=0xC0, escape=0xDB, escapes=None, xor=None, escaped=None, fcs=None, refin=False, min_bytes=1):
    super().__init__(log, None, 1, 1)
    self.flag, self.escape, self.fcs, self.refin, self.min_bytes = flag, escape, fcs, refin, min_bytes
    if xor is not None:
        esc = escaped if escaped is not None else (flag, escape)
        self.escapes = {int(b): int(b) ^ xor for b in esc}
    else:
        self.escapes = {int(k): int(v) for k, v in (escapes or {flag: flag ^ 0x20, escape: escape ^ 0x20}).items()}
    self.unescape = {v: k for k, v in self.escapes.items()}
    if self.flag not in self.escapes or self.escape not in self.escapes:
        raise ValueError("byte stuffing: the flag and the escape byte must both be escaped")
frame
frame(payload)

The bytes of one frame: flag, the stuffed payload and FCS, flag

Source code in src/rpps/link/bytestuff.py
def frame(self, payload):
    """The bytes of one frame: flag, the stuffed payload and FCS, flag"""
    body = bytes(payload)
    if self.fcs is not None:
        body += self.fcs.to_bytes(self.fcs.compute(body))
    out = bytearray([self.flag])
    for b in body:
        if b in self.escapes:
            out += bytes([self.escape, self.escapes[b]])
        else:
            out.append(b)
    out.append(self.flag)
    return bytes(out)
frames_at
frames_at(bits)

Frames as (index of the opening flag in bits, payload bytes, fcs ok, the FCS bytes received: b"" without an FCS), and the number of aborted frames

Source code in src/rpps/link/bytestuff.py
def frames_at(self, bits):
    """Frames as (index of the opening flag in `bits`, payload bytes, fcs ok, the FCS bytes received: b"" without an
    FCS), and the number of aborted frames"""
    b = np.asarray(bits, dtype=np.uint8)
    raw = self._bytes(b[:len(b)//8*8])
    flags = self._flags(raw)
    frames, aborts = [], 0
    for s, e in zip(flags[:-1], flags[1:]):
        if e - s <= 1:
            continue # Back-to-back flags: idle
        body, out, bad, esc = raw[s + 1:e], bytearray(), False, False
        for x in body:
            if esc:
                if x not in self.unescape:
                    bad = True
                    break
                out.append(self.unescape[x])
                esc = False
            elif x == self.escape:
                esc = True
            else:
                out.append(x)
        if bad or esc:
            aborts += 1
            continue
        if len(out) < self.min_bytes:
            continue
        if self.fcs is None:
            frames.append((int(s)*8, bytes(out), True, b""))
            continue
        n = self.fcs.width//8
        if len(out) <= n:
            aborts += 1
            continue
        ok = self.fcs.to_bytes(self.fcs.compute(bytes(out[:-n]))) == bytes(out[-n:])
        frames.append((int(s)*8, bytes(out[:-n]), ok, bytes(out[-n:])))
    return frames, aborts
consumed
consumed(bits)

How many of these bits are done with: whole bytes up to the last flag (a frame may be open there), or all whole bytes when there is no flag (nothing can start one) or the frame after it has run too long

Source code in src/rpps/link/bytestuff.py
def consumed(self, bits):
    """How many of these bits are done with: whole bytes up to the last flag (a frame may be open there), or all whole
    bytes when there is no flag (nothing can start one) or the frame after it has run too long"""
    n = len(bits)//8
    flags = self._flags(self._bytes(np.asarray(bits, dtype=np.uint8)[:n*8]))
    if not len(flags) or n - int(flags[-1]) > self.MAX_FRAME_BYTES:
        return n*8
    return int(flags[-1])*8
decode_stream
decode_stream(bits, held, frames=None)

Decode held (what the last call kept) and bits together: (data bits of the good frames, what to hold). frames: a list to append every frame found to, as frames_at gives them (index in held + bits)

Source code in src/rpps/link/bytestuff.py
def decode_stream(self, bits, held, frames=None):
    """Decode `held` (what the last call kept) and `bits` together: (data bits of the good frames, what to hold).
    frames: a list to append every frame found to, as `frames_at` gives them (index in held + bits)"""
    buf = np.concatenate((np.asarray(held, dtype=np.uint8), np.asarray(bits, dtype=np.uint8)))
    used = self.consumed(buf)
    part = buf[:used + 8] # the flag at `used` closes the frames before it
    out = self.decode(part) if used else np.zeros(0, bool)
    if frames is not None and used:
        frames += self.frames_at(part)[0]
    return out, buf[used:]

capture

Captures: decoded frames as packets of a link type, for Wireshark (rpps.source.PcapSink) or an interface (rpps.source.Tun)

A profile's messages (rpps.profile.message) hold what each step decoded; a capture says how a kind of message becomes the bytes a link type expects, and back again on transmit. Profiles say it in "capture", one rule a message kind:

"capture": {"pdu": {"linktype": "ble_ll_phdr",                       a config/linktype definition (or "find", below)
                    "include": ["header", "payload", "fcs"],          the message's parts, in order (Message.parts)
                    "transform": [{"prefix": "0x8E89BED6", "bytes": 4, "order": "little"},
                                  {"header": "ble_phdr", "channel": "channel"}],
                    "drop": "type == 3",                               messages left out (an expression over fields)
                    "fields": ["type.name", "length"]},               fields named in the packet's comment (true: all)
            "frame": false}                                           a kind not captured

A kind without a rule goes out as Wireshark's exported PDU (upper_pdu) to its "data" dissector, so it is still seen.

Parts. A step that knows more of its frame than the payload emits the whole frame with where each part is (a link header: header, payload, FCS; an HDLC frame: payload, FCS). include takes them in order; without it the payload alone.

Transforms, applied in order, each with an inverse for transmit (unpacket):

Transform Receive Transmit
{"bit_order": "lsb"} each byte's bits reversed the same
{"prefix": v, "bytes": n, "order": "big"} n bytes of v (a constant, a field, an expression) before taken off (a field name: its value read back)
{"suffix": v, "bytes": n, "order": "big"} after taken off
{"strip": {"head": n, "tail": m}, "fill": 0} n bytes off the front, m off the end (expressions) put back, fill
{"set": {"at": i, "value": v}, "was": w} byte i set to v (a restored sync byte) set to w, when given
{"fcs": "<crc definition>", "order": "big"} a check over the bytes so far, appended checked and taken off
{"header": "radiotap" \| "ble_phdr", ...} a pseudo-header built from the message (below) taken off
{"restore": "ppp_acfc_pfc"} a named repair an expression can't make (below) its inverse

Expressions see the message's fields (a group's as group.field), the profile's parameters, and size (the bytes so far).

Pseudo-headers. radiotap (802.11): flags (FCS at the end when fcs is true), rate (an expression in 500 kb/s units), channel (MHz; the message's frequency when not given), 2.4 GHz CCK. ble_phdr (LINKTYPE_BLUETOOTH_LE_LL_WITH_PHDR): the RF channel (0..39), dewhitened, the CRC checked and its verdict (the message's crc_ok).

Restores. ppp_acfc_pfc: puts back the address and control bytes (0xFF 0x03) a peer left out (ACFC), and widens a one-byte protocol field (PFC) to two (RFC 1661 6.5, 6.6); transmitting, nothing to undo (uncompressed is always valid).

Finding a link type in a frame ("linktype": "find", "find": {"in": ["ethernet", "ipv4", "ipv6"], "max": 64}): a frame with a header nobody describes, then a frame of a known link type. Each offset from min to max is tried against the link types' signature (fields, a valid expression over them and size, a check over bytes that comes out zero, and next: what follows by a field, an EtherType's IPv4); the first offset with the best score wins (1: the fields are valid; 2: and the check holds; one more for each layer inside that scores too), at least score. The bytes before it are left out, and the packet takes that link type. Only where a frame starts is found: nothing above the link layer is read. No match: the frame goes out whole, as exported PDU data, and is counted.

Exported PDU (upper_pdu): tags then the payload. The rule's dissector names Wireshark's dissector ("lte_rrc.bcch_dl_sch"); the protocol column says the profile and kind, the info column the check and fields.

Classes:

Name Description
LinkType

A link type (config/linktype): its pcap number (dlt), the Linux ARPHRD a TUN takes for it (arphrd, proto:

Packet

One captured frame: its link type and bytes, and what it was (from its message)

Capture

One message kind's capture rule (see module): packet(message) the Packet (None: dropped), unpacket(bytes) the

Captures

A profile's capture rules, by message kind ("capture" in a profile; see module). packet(message): its Packet,

Functions:

Name Description
linktype

A link type by name: linktype("ieee802_15_4") (config/linktype)

convert

A packet of link type src as one of link type dst, where one is the other with transforms (a link type's

by_dlt

The link type of a pcap link type number (None: not one of config/linktype)

linktypes

Every link type's name

find

(offset, LinkType) where a frame of one of these link types starts in data: the best score, the first offset

exported_pdu

Wireshark's exported PDU (LINKTYPE_WIRESHARK_UPPER_PDU): tags (dissector, protocol and info columns), the end tag,

unexported_pdu

(dissector, payload) of an exported PDU

LinkType

LinkType(name, dlt, arphrd=None, proto=None, dissector=None, fcs=None, signature=None, **kw)

A link type (config/linktype): its pcap number (dlt), the Linux ARPHRD a TUN takes for it (arphrd, proto: the EtherType a TUN's packet information says), Wireshark's dissector, what it says of an FCS, and a signature

Methods:

Name Description
score

How well data starts a frame of this link type: 0 not at all, 1 its fields are valid, 2 and its check holds;

Source code in src/rpps/link/capture.py
def __init__(self, name, dlt, arphrd=None, proto=None, dissector=None, fcs=None, signature=None, **kw):
    self.name, self.dlt = name, int(dlt)
    self.made_from = {k: list(v) for k, v in (kw.pop("from", None) or {}).items()} # {other link type: transforms}
    if kw:
        raise ConfigError(f"linktype {name}: unknown keys {sorted(kw)}")
    self.arphrd = None if arphrd is None else int(arphrd)
    self.proto = None if proto is None else (int(proto, 0) if isinstance(proto, str) else int(proto))
    self.dissector, self.fcs = dissector, fcs
    self.signature = self._plain = None
    if signature:
        from .fields import Schema
        sig = dict(signature)
        check = sig.get("check")
        nxt = sig.get("next")
        self._plain = None # Plain unsigned fields of fixed size: read as integers (fast), else through the schema
        if all(set(f) <= {"name", "bits", "comment"} and isinstance(f.get("bits"), int) for f in sig["fields"]):
            at, plain = 0, []
            for fl in sig["fields"]:
                plain.append((fl["name"], at, fl["bits"]))
                at += fl["bits"]
            self._plain = (plain, (at + 7)//8)
        self.signature = (Schema(sig["fields"], "msb", f"linktype {name} signature"), sig["valid"], int(sig.get("min", 1)),
                          None if check is None else (_check(check["crc"]), check.get("bytes")),
                          None if nxt is None else (nxt["field"], nxt["at"], {int(k, 0): v for k, v in nxt["linktypes"].items()}))
score
score(data, bits=None)

How well data starts a frame of this link type: 0 not at all, 1 its fields are valid, 2 and its check holds; with a next (what follows, by a field: an EtherType), one more than what follows scores, when it scores. bits: data unpacked already (MSB first), at least as far as the signature reads

Source code in src/rpps/link/capture.py
def score(self, data, bits=None):
    """How well `data` starts a frame of this link type: 0 not at all, 1 its fields are valid, 2 and its check holds;
    with a `next` (what follows, by a field: an EtherType), one more than what follows scores, when it scores.
    bits: `data` unpacked already (MSB first), at least as far as the signature reads"""
    if self.signature is None:
        return 0
    schema, valid, least, check, nxt = self.signature
    if len(data) < least:
        return 0
    if self._plain is not None:
        plain, nbytes = self._plain
        if len(data) < nbytes:
            return 0
        word, total = int.from_bytes(bytes(data[:nbytes]), "big"), 8*nbytes
        values = {name: (word >> (total - at - n)) & ((1 << n) - 1) for name, at, n in plain}
        values["size"] = len(data)
    else:
        from .fields import Short
        need = schema.fixed_bits or 8*64
        if bits is None:
            bits = np.unpackbits(np.frombuffer(bytes(data[:(need + 7)//8]), np.uint8)).astype(bool)
        try:
            fields = schema.parse(bits[:need])[0]
        except (Short, ValueError, ConfigError):
            return 0
        values = {**_flat(fields), "size": len(data)}
    if not _config.evaluate(valid, values, f"linktype {self.name}"):
        return 0
    if nxt is not None:
        field, at, kinds = nxt
        inner = kinds.get(values.get(field))
        s = linktype(inner).score(memoryview(data)[int(at):], None if bits is None else bits[8*int(at):]) if inner else 0
        if s:
            return 1 + s
    if check is None:
        return 1
    crc, n = check
    n = len(data) if n is None else int(_config.evaluate(n, values, f"linktype {self.name}"))
    return 2 if 0 < n <= len(data) and crc.compute(bytes(data[:n])) == 0 else 1

Packet

Packet(linktype, data, profile='', kind='', check=None, crc_ok=None, sample=0, time=None, freq=None, quality=None, fields=None)

One captured frame: its link type and bytes, and what it was (from its message)

linktype: a LinkType; data: the bytes as the link type has them. profile, kind, check, crc_ok, sample, time, freq, quality: the message's; fields: the fields the rule names; comment(): one line of them, for a capture's comment

Source code in src/rpps/link/capture.py
def __init__(self, linktype, data, profile="", kind="", check=None, crc_ok=None, sample=0, time=None, freq=None,
             quality=None, fields=None):
    self.linktype, self.data = linktype, bytes(data)
    self.profile, self.kind, self.check, self.crc_ok = profile, kind, check, crc_ok
    self.sample, self.time, self.freq, self.quality = sample, time, freq, quality
    self.fields = dict(fields or {})

Capture

Capture(spec, where='capture', params=None)

One message kind's capture rule (see module): packet(message) the Packet (None: dropped), unpacket(bytes) the payload bytes and fields to transmit

Methods:

Name Description
packet

The message as a Packet of this rule's link type; None when drop says so

forward

The transforms applied to bytes alone (no message: no pseudo-headers, fields or parameters)

unpacket

(bytes, fields) for transmitting a packet of this rule's link type: the transforms undone in reverse (a prefix

Source code in src/rpps/link/capture.py
def __init__(self, spec, where="capture", params=None):
    spec = dict(spec)
    bad = set(spec) - set(RULE_KEYS)
    if bad:
        raise ConfigError(f"{where}: unknown keys {sorted(bad)}; a capture rule takes {list(RULE_KEYS)}")
    self.where, self.params = where, dict(params or {})
    name = spec.get("linktype", "upper_pdu")
    self.find = None
    if name == "find":
        f = dict(spec.get("find") or {})
        if not f.get("in"):
            raise ConfigError(f"{where}: \"linktype\": \"find\" needs \"find\": {{\"in\": [link types], \"max\": bytes}}")
        self.find = ([linktype(n) for n in f["in"]], int(f.get("min", 0)), int(f.get("max", 64)), int(f.get("score", 1)))
        self.linktype = None
    else:
        self.linktype = linktype(name)
    self.dissector = spec.get("dissector") or (self.linktype.dissector if self.linktype is not None else None)
    if self.linktype is not None and self.linktype.name == "upper_pdu" and not spec.get("dissector"):
        self.dissector = "data"
    self.include = list(spec.get("include") or ["payload"])
    bad = [p for p in self.include if p not in PARTS]
    if bad:
        raise ConfigError(f"{where}: include takes {list(PARTS)}, not {bad}")
    self.transform = [dict(t) for t in spec.get("transform", [])]
    for t in self.transform:
        kind = [k for k in t if k in TRANSFORMS]
        if len(kind) != 1:
            raise ConfigError(f"{where}: a transform is one of {list(TRANSFORMS)}, got {t}")
        if kind[0] == "header" and t["header"] not in HEADERS:
            raise ConfigError(f"{where}: no pseudo-header {t['header']!r}; have {sorted(HEADERS)}")
        if kind[0] == "restore" and t["restore"] not in RESTORES:
            raise ConfigError(f"{where}: no restore {t['restore']!r}; have {sorted(RESTORES)}")
        if kind[0] == "fcs":
            t["_crc"] = _check(t["fcs"])
    self.drop = spec.get("drop")
    self.fields = spec.get("fields", True)
    self.undetected = 0 # Frames "find" found no link type in
packet
packet(msg)

The message as a Packet of this rule's link type; None when drop says so

Source code in src/rpps/link/capture.py
def packet(self, msg):
    """The message as a Packet of this rule's link type; None when `drop` says so"""
    values = self.values(msg)
    if self.drop is not None and _config.evaluate(self.drop, values, self.where):
        return None
    data = self._bytes(msg)
    for t in self.transform:
        values["size"] = len(data)
        data = self._forward(t, data, msg, values)
    lt, dissector = self.linktype, self.dissector
    if self.find is not None:
        kinds, lo, hi, least = self.find
        off, lt = find(data, [k.name for k in kinds], lo, hi, least)
        if lt is None:
            self.undetected += 1
            lt, dissector = linktype("upper_pdu"), "data"
        else:
            data = data[off:]
    p = Packet(lt, data, msg.profile, msg.kind, msg.check, msg.crc_ok, msg.sample, msg.time, msg.freq, msg.quality,
               self._fields(msg))
    if lt.name == "upper_pdu":
        p.data = exported_pdu(data, dissector or "data", f"{msg.profile} {msg.kind}", _info(p))
    return p
forward
forward(data)

The transforms applied to bytes alone (no message: no pseudo-headers, fields or parameters)

Source code in src/rpps/link/capture.py
def forward(self, data):
    """The transforms applied to bytes alone (no message: no pseudo-headers, fields or parameters)"""
    data = bytes(data)
    for t in self.transform:
        data = self._forward(t, data, None, {**self.params, "size": len(data)})
    return data
unpacket
unpacket(data)

(bytes, fields) for transmitting a packet of this rule's link type: the transforms undone in reverse (a prefix named by a field gives that field). The bytes are the included parts, in order (the profile's Encoder splits them)

Source code in src/rpps/link/capture.py
def unpacket(self, data):
    """(bytes, fields) for transmitting a packet of this rule's link type: the transforms undone in reverse (a prefix
    named by a field gives that field). The bytes are the included parts, in order (the profile's Encoder splits them)"""
    data, fields = bytes(data), {}
    if self.linktype is not None and self.linktype.name == "upper_pdu":
        data = unexported_pdu(data)[1]
    values = dict(self.params)
    for t in reversed(self.transform):
        data = self._inverse(t, data, values, fields)
    return data, fields

Captures

Captures(spec=None, where='capture', params=None)

A profile's capture rules, by message kind ("capture" in a profile; see module). packet(message): its Packet, None for a kind not captured or a message dropped. A kind without a rule: exported PDU data

Methods:

Name Description
rule

The rule for a kind (False: not captured)

linktypes

The link types the rules give, by kind (None: found per frame)

Source code in src/rpps/link/capture.py
def __init__(self, spec=None, where="capture", params=None):
    spec = dict(spec or {})
    self.where, self.params = where, dict(params or {})
    self.rules = {k: (False if v is False else Capture(v, f"{where} {k!r}", self.params)) for k, v in spec.items()}
    self._default = None
rule
rule(kind)

The rule for a kind (False: not captured)

Source code in src/rpps/link/capture.py
def rule(self, kind):
    """The rule for a kind (False: not captured)"""
    r = self.rules.get(kind)
    if r is None:
        if self._default is None:
            self._default = Capture({"linktype": "upper_pdu"}, f"{self.where} (default)", self.params)
        return self._default
    return r
linktypes
linktypes()

The link types the rules give, by kind (None: found per frame)

Source code in src/rpps/link/capture.py
def linktypes(self):
    """The link types the rules give, by kind (None: found per frame)"""
    return {k: (None if r is False else r.linktype) for k, r in self.rules.items()}

linktype

linktype(name)

A link type by name: linktype("ieee802_15_4") (config/linktype)

Source code in src/rpps/link/capture.py
def linktype(name):
    """A link type by name: `linktype("ieee802_15_4")` (config/linktype)"""
    if isinstance(name, LinkType):
        return name
    lt = _LINKTYPES.get(name)
    if lt is None:
        lt = _LINKTYPES[name] = _config.load("linktype", name)
    return lt

convert

convert(data, src, dst)

A packet of link type src as one of link type dst, where one is the other with transforms (a link type's "from": {other: [transforms]}, as a capture rule's: 802.15.4 with FCS is 802.15.4 without, its FCS appended; AX.25 with its KISS byte is AX.25 with a 0 before). ValueError where neither says how (or a check to take off fails)

Source code in src/rpps/link/capture.py
def convert(data, src, dst):
    """A packet of link type `src` as one of link type `dst`, where one is the other with transforms (a link type's
    "from": {other: [transforms]}, as a capture rule's: 802.15.4 with FCS is 802.15.4 without, its FCS appended; AX.25
    with its KISS byte is AX.25 with a 0 before). ValueError where neither says how (or a check to take off fails)"""
    src, dst = linktype(src), linktype(dst)
    if src.name == dst.name:
        return bytes(data)
    if src.name in dst.made_from:
        return Capture({"linktype": dst.name, "transform": dst.made_from[src.name]}).forward(data)
    if dst.name in src.made_from:
        return Capture({"linktype": src.name, "transform": src.made_from[dst.name]}).unpacket(data)[0]
    raise ValueError(f"no conversion between link types {src.name} and {dst.name} (a link type's \"from\" says one)")

by_dlt

by_dlt(dlt)

The link type of a pcap link type number (None: not one of config/linktype)

Source code in src/rpps/link/capture.py
def by_dlt(dlt):
    """The link type of a pcap link type number (None: not one of config/linktype)"""
    return next((linktype(n) for n in linktypes() if linktype(n).dlt == int(dlt)), None)

linktypes

linktypes()

Every link type's name

Source code in src/rpps/link/capture.py
def linktypes():
    """Every link type's name"""
    return sorted(n for ns in _config.ls("linktype").values() for n in ns)

find

find(data, names, lo=0, hi=64, least=1)

(offset, LinkType) where a frame of one of these link types starts in data: the best score, the first offset of it, from lo to hi; (None, None) when none scores least

Source code in src/rpps/link/capture.py
def find(data, names, lo=0, hi=64, least=1):
    """(offset, LinkType) where a frame of one of these link types starts in `data`: the best score, the first offset
    of it, from `lo` to `hi`; (None, None) when none scores `least`"""
    kinds = [linktype(n) for n in names]
    data = bytes(data)
    allbits = None
    if any(lt._plain is None and lt.signature is not None for lt in kinds): # (unpacked once, for the schemas)
        allbits = np.unpackbits(np.frombuffer(data[:int(hi) + 128], np.uint8)).astype(bool)
    best = (0, None, None)
    view = memoryview(data)
    for off in range(int(lo), min(int(hi), len(data) - 1) + 1):
        for lt in kinds:
            s = lt.score(view[off:], None if allbits is None else allbits[8*off:])
            if s > best[0]:
                best = (s, off, lt)
    return (best[1], best[2]) if best[0] >= least else (None, None)

exported_pdu

exported_pdu(payload, dissector, protocol=None, info=None)

Wireshark's exported PDU (LINKTYPE_WIRESHARK_UPPER_PDU): tags (dissector, protocol and info columns), the end tag, then the payload. Each tag: its type and length (16 bits, big endian), the value padded with zeros to 4 bytes

Source code in src/rpps/link/capture.py
def exported_pdu(payload, dissector, protocol=None, info=None):
    """Wireshark's exported PDU (LINKTYPE_WIRESHARK_UPPER_PDU): tags (dissector, protocol and info columns), the end tag,
    then the payload. Each tag: its type and length (16 bits, big endian), the value padded with zeros to 4 bytes"""
    def tag(t, text):
        v = text.encode()
        v += bytes(-len(v) % 4)
        return t.to_bytes(2, "big") + len(v).to_bytes(2, "big") + v
    out = tag(EXP_PDU_TAG_DISSECTOR_NAME, dissector)
    if protocol:
        out += tag(EXP_PDU_TAG_COL_PROT_TEXT, protocol)
    if info:
        out += tag(EXP_PDU_TAG_COL_INFO_TEXT, info)
    return out + bytes(4) + bytes(payload)

unexported_pdu

unexported_pdu(data)

(dissector, payload) of an exported PDU

Source code in src/rpps/link/capture.py
def unexported_pdu(data):
    """(dissector, payload) of an exported PDU"""
    i, name = 0, None
    while i + 4 <= len(data):
        t, n = int.from_bytes(data[i:i + 2], "big"), int.from_bytes(data[i + 2:i + 4], "big")
        if t == 0:
            return name, bytes(data[i + 4:])
        if t == EXP_PDU_TAG_DISSECTOR_NAME:
            name = bytes(data[i + 4:i + 4 + n]).rstrip(b"\x00").decode()
        i += 4 + n
    raise ValueError("exported PDU: no end tag")

check

Composite checks: a check field built from CRCs over transformed views of the message

{"base": "crc", "type": "composite",
 "parts": [{"crc": "crc8_smbus"},                                   CRC-8 of the message
           {"crc": "crc8_smbus", "input": ["nibble_swap"]}],        CRC-8 of the message with each byte's nibbles swapped
 "combine": "concat",                                               the field: the parts' fields in order (or "xor")
 "check": "0x...."}                                                 optional: compute(b"123456789"), verified on load

A part is a crc definition (crc, a config/crc name) with optional input transforms, applied in order to the message bytes before its register runs, and output transforms on its value. A transform is a name or {"op": name, ...args}:

nibble_swap                 each byte's two nibbles swapped
reverse_bits                each byte's bits reversed
reverse_bytes               the bytes in reverse order
invert                      every bit inverted
{"op": "xor", "value": ...} XORed with a byte, or a list of bytes repeated over the message
{"op": "skip", "n": 2}      the message without its first n bytes
{"op": "take", "n": 4}      the first n bytes (a negative n: all but the last -n)

outputs: reflect (the value's bits reversed over the part's width), invert (all ones XORed on).

register(name) adds a transform from Python, fn(data: np.ndarray[uint8], **args) -> np.ndarray[uint8], which a definition then names. A composite has the crc interface (width, compute, compute_bits, field, syndrome, encode, decode), so it goes wherever a CRC does: an HDLC frame's fcs, a link header's crc or fcs. Each part's field is sent the way its own CRC sends it; for xor the first part's conventions apply and every part has its width.

Classes:

Name Description
Part

One CRC over a transformed view of the message

composite

A check from several CRC parts, concatenated or XORed (see the module docstring)

Functions:

Name Description
register

Register a byte transform a composite check's parts can name in "input": fn(data uint8 array, **args) -> uint8 array

Part

Part(crc, inputs=(), outputs=(), name='composite')

One CRC over a transformed view of the message

Source code in src/rpps/link/check.py
def __init__(self, crc, inputs=(), outputs=(), name="composite"):
    self.crc = crc
    self.inputs = [_op(s, name) for s in inputs]
    for o in outputs:
        if o not in OUTPUTS:
            raise ConfigError(f"{name}: output {o!r} is one of {OUTPUTS}")
    self.outputs = list(outputs)
    self.width = crc.width

composite

composite(log, parts, combine='concat', check=None, name='composite')

Bases: _code

A check from several CRC parts, concatenated or XORed (see the module docstring)

Methods:

Name Description
compute

The check of bytes: each part's CRC of its view, combined

compute_bits

The check of a bit stream, in the order sent

field

The check field of message bits, as sent after them

Source code in src/rpps/link/check.py
def __init__(self, log, parts, combine="concat", check=None, name="composite"):
    super().__init__(log, None, 1, 1)
    if not parts:
        raise ConfigError(f"{name}: a composite check needs parts")
    if combine not in ("concat", "xor"):
        raise ConfigError(f"{name}: combine is concat or xor, not {combine!r}")
    if combine == "xor" and len({p.width for p in parts}) > 1:
        raise ConfigError(f"{name}: xor combines parts of one width, have {[p.width for p in parts]}")
    self.parts, self.combine = parts, combine
    self.width = sum(p.width for p in parts) if combine == "concat" else parts[0].width
    self.mask = (1 << self.width) - 1
    self.check = check
    if check is not None and self.compute(b"123456789") != check:
        raise ValueError(f"{name}: composite check fails its check value: {self.compute(b'123456789'):#x} != {check:#x}")
compute
compute(data)

The check of bytes: each part's CRC of its view, combined

Source code in src/rpps/link/check.py
def compute(self, data):
    """The check of bytes: each part's CRC of its view, combined"""
    return self._join([p.compute(data) for p in self.parts])
compute_bits
compute_bits(bits)

The check of a bit stream, in the order sent

Source code in src/rpps/link/check.py
def compute_bits(self, bits):
    """The check of a bit stream, in the order sent"""
    return self._join([p.compute_bits(bits) for p in self.parts])
field
field(bits, mask=0)

The check field of message bits, as sent after them

Source code in src/rpps/link/check.py
def field(self, bits, mask=0):
    """The check field of message bits, as sent after them"""
    return self.to_bits(self.compute_bits(bits) ^ mask)

register

register(name)

Register a byte transform a composite check's parts can name in "input": fn(data uint8 array, **args) -> uint8 array

Source code in src/rpps/link/check.py
def register(name):
    """Register a byte transform a composite check's parts can name in "input": fn(data uint8 array, **args) -> uint8 array"""
    def deco(fn):
        TRANSFORMS[name] = fn
        return fn
    return deco

checksum

Checksums that are not CRCs: sums, ones' complement (Internet), Fletcher, Adler, XOR (LRC)

{"base": "crc", "type": "checksum", "algorithm": "internet",   sum | internet | fletcher | adler | xor
 "width": 16,                                                   bits of the value (sum, xor: 8, 16 or 32)
 "word": 16, "endian": "big",                                   sum, xor: the message read as words of this many bits
 "negate": false,                                               sum: the two's complement of the sum (Intel HEX, NMEA's
                                                                is xor) so that message + checksum sums to 0
 "xorout": "0x0",                                               XORed onto the value
 "refin": false,                                                the bytes are sent least significant bit first
 "order": "big",                                                the value's bytes as sent after the message
 "check": "0x...."}                                             optional: compute(b"123456789"), verified on load

internet  RFC 1071: the ones' complement of the ones' complement sum of big-endian 16-bit words (a last odd byte
          padded with a zero)
fletcher  width 16: two sums of bytes mod 255 (value sum2 << 8 | sum1); width 32: of 16-bit words (`endian`) mod 65535
adler     Adler-32 (zlib): sums of bytes mod 65521, value s2 << 16 | s1

It has the crc interface (width, compute, compute_bits, to_bytes, to_bits, field, syndrome, encode, decode), so it goes wherever a CRC does: an HDLC or byte-stuffed frame's fcs, a link header's crc or fcs, a composite check's part.

Classes:

Name Description
checksum

checksum

checksum(log, algorithm='sum', width=8, word=8, endian='big', negate=False, xorout=0, refin=False, order='big', check=None, name='checksum')

Bases: _code

Methods:

Name Description
compute

The checksum of bytes

compute_bits

The checksum of a bit stream in the order sent: whole bytes, each least significant bit first with refin

Source code in src/rpps/link/checksum.py
def __init__(self, log, algorithm="sum", width=8, word=8, endian="big", negate=False, xorout=0, refin=False,
             order="big", check=None, name="checksum"):
    super().__init__(log, None, 1, 1)
    if algorithm not in ALGORITHMS:
        raise ConfigError(f"{name}: algorithm is one of {ALGORITHMS}, not {algorithm!r}")
    if algorithm == "internet":
        width, word = 16, 16
    elif algorithm == "adler":
        width = 32
    elif algorithm == "fletcher" and width not in (16, 32):
        raise ConfigError(f"{name}: Fletcher is 16 or 32 bits wide, not {width}")
    if algorithm in ("sum", "xor") and (width not in (8, 16, 32) or word not in (8, 16, 32)):
        raise ConfigError(f"{name}: width and word are 8, 16 or 32 bits")
    if endian not in ("big", "little") or order not in ("big", "little"):
        raise ConfigError(f"{name}: endian and order are big or little")
    self.algorithm, self.width, self.word, self.endian, self.negate = algorithm, width, word, endian, negate
    self.xorout, self.refin, self.order = xorout, refin, order
    self.mask = (1 << width) - 1
    self.check = check
    if check is not None and self.compute(b"123456789") != check:
        raise ValueError(f"{name}: checksum fails its check value: {self.compute(b'123456789'):#x} != {check:#x}")
compute
compute(data)

The checksum of bytes

Source code in src/rpps/link/checksum.py
def compute(self, data):
    """The checksum of bytes"""
    data = bytes(data)
    a = self.algorithm
    if a == "sum":
        v = sum(self._words(data, self.word)) & self.mask
        v = (-v) & self.mask if self.negate else v
    elif a == "xor":
        v = 0
        for w in self._words(data, self.word):
            v ^= w
        v &= self.mask
    elif a == "internet":
        s = sum(int.from_bytes(data[i:i + 2].ljust(2, b"\0"), "big") for i in range(0, len(data), 2))
        while s >> 16:
            s = (s & 0xFFFF) + (s >> 16)
        v = ~s & 0xFFFF
    elif a == "fletcher":
        half, mod = (8, 255) if self.width == 16 else (16, 65535)
        s1 = s2 = 0
        for w in (data if half == 8 else self._words(data, 16)):
            s1 = (s1 + w) % mod
            s2 = (s2 + s1) % mod
        v = s2 << half | s1
    else: # adler
        s1, s2 = 1, 0
        for b in data:
            s1 = (s1 + b) % 65521
            s2 = (s2 + s1) % 65521
        v = s2 << 16 | s1
    return (v ^ self.xorout) & self.mask
compute_bits
compute_bits(bits)

The checksum of a bit stream in the order sent: whole bytes, each least significant bit first with refin

Source code in src/rpps/link/checksum.py
def compute_bits(self, bits):
    """The checksum of a bit stream in the order sent: whole bytes, each least significant bit first with `refin`"""
    bits = np.asarray(bits, dtype=np.uint8).reshape(-1)
    if len(bits) % 8:
        raise ValueError(f"{len(bits)} bits: a checksum is over whole bytes")
    return self.compute(np.packbits(bits, bitorder="little" if self.refin else "big").tobytes())

crc

Classes:

Name Description
crc

Parametrised CRC (Rocksoft model: width, poly, init, refin, refout, xorout), any width from 1 to 64

crc

crc(log, width=16, poly=4129, init=0, refin=False, refout=False, xorout=0, check=None)

Bases: _code

Parametrised CRC (Rocksoft model: width, poly, init, refin, refout, xorout), any width from 1 to 64

Two views of the same register

compute(data) bytes / a uint8 array, as the catalogues define it: with refin each byte goes in least significant bit first. compute(b"123456789") is the catalogue's check value. compute_bits(bits) a bit stream of any length, fed in the order given (the order it is sent). refin is then already in the order of the bits; refout and xorout apply as usual, so compute(data) == compute_bits(np.unpackbits(data, bitorder="little" if refin else "big")).

encode(bits) appends the CRC to a message of any length and decode(bits) strips it (status=True: [0] if it checked out, [-1] if not). Both work on the bit stream as sent: the CRC follows the message bits the way the register would shift it out, most significant bit first, or least significant first when refout is set (HDLC's FCS, BLE). A received frame passes when the CRC over the message equals the CRC field.

mask: XORed onto the CRC value by encode / decode / syndrome, for standards that overlay something on it (LTE's antenna port mask or RNTI, the Mode S address). syndrome(bits) is the received CRC field XOR the computed one: 0 for a good frame, the overlay (or an error pattern) otherwise.

Methods:

Name Description
compute

CRC of bytes (catalogue convention: refin feeds each byte least significant bit first)

compute_bits

CRC of a bit stream of any length, bits fed in the order given

to_bytes

The CRC as bytes, the way catalogue protocols append it to byte data (little-endian when refout)

to_bits

The CRC field as sent after the message bits

from_bits

Value of a received CRC field (inverse of to_bits)

field

The CRC field of message bits, as it is sent after them (bools, width of them)

encode

Message bits followed by their CRC field

syndrome

Received CRC field XOR the CRC of the message (and mask): 0 when the frame checks out

Source code in src/rpps/link/crc.py
def __init__(self, log, width=16, poly=0x1021, init=0, refin=False, refout=False, xorout=0, check=None):
    super().__init__(log, None, 1, 1)
    if not 1 <= width <= 64:
        raise ValueError(f"CRC width {width}: need 1 to 64 bits")
    self.width, self.poly, self.init = width, poly, init
    self.refin, self.refout, self.xorout = refin, refout, xorout
    self.mask = (1 << width) - 1
    self.check = check
    self.table = self._table() if width >= 8 else None
    if check is not None and self.compute(b"123456789") != check:
        raise ValueError(f"CRC definition fails its check value: {self.compute(b'123456789'):#x} != {check:#x}")
compute
compute(data)

CRC of bytes (catalogue convention: refin feeds each byte least significant bit first)

Source code in src/rpps/link/crc.py
def compute(self, data):
    """CRC of bytes (catalogue convention: `refin` feeds each byte least significant bit first)"""
    data = np.frombuffer(bytes(data), np.uint8)
    if self.refin:
        data = _REV8[data]
    return self._finish(self._feed_bytes(self.init, data))
compute_bits
compute_bits(bits)

CRC of a bit stream of any length, bits fed in the order given

Source code in src/rpps/link/crc.py
def compute_bits(self, bits):
    """CRC of a bit stream of any length, bits fed in the order given"""
    bits = np.asarray(bits, dtype=np.uint8).reshape(-1)
    whole = len(bits)//8*8
    c = self._feed_bytes(self.init, np.packbits(bits[:whole]))
    return self._finish(self._feed_bits(c, bits[whole:]))
to_bytes
to_bytes(value)

The CRC as bytes, the way catalogue protocols append it to byte data (little-endian when refout)

Source code in src/rpps/link/crc.py
def to_bytes(self, value):
    """The CRC as bytes, the way catalogue protocols append it to byte data (little-endian when refout)"""
    n = -(-self.width//8)
    return value.to_bytes(n, "little" if self.refout else "big")
to_bits
to_bits(value)

The CRC field as sent after the message bits

Source code in src/rpps/link/crc.py
def to_bits(self, value):
    """The CRC field as sent after the message bits"""
    order = np.arange(self.width) if self.refout else np.arange(self.width - 1, -1, -1)
    return ((int(value) >> order) & 1).astype(bool)
from_bits
from_bits(bits)

Value of a received CRC field (inverse of to_bits)

Source code in src/rpps/link/crc.py
def from_bits(self, bits):
    """Value of a received CRC field (inverse of to_bits)"""
    bits = np.asarray(bits, dtype=np.uint8)
    order = np.arange(self.width) if self.refout else np.arange(self.width - 1, -1, -1)
    return int(sum(int(b) << int(i) for b, i in zip(bits, order)))
field
field(bits, mask=0)

The CRC field of message bits, as it is sent after them (bools, width of them)

Source code in src/rpps/link/crc.py
def field(self, bits, mask=0):
    """The CRC field of message bits, as it is sent after them (bools, `width` of them)"""
    return self.to_bits(self.compute_bits(bits) ^ mask)
encode
encode(bits, mask=0)

Message bits followed by their CRC field

Source code in src/rpps/link/crc.py
def encode(self, bits, mask=0):
    """Message bits followed by their CRC field"""
    bits = np.asarray(bits).astype(bool).reshape(-1)
    return np.concatenate((bits, self.field(bits, mask)))
syndrome
syndrome(bits, mask=0)

Received CRC field XOR the CRC of the message (and mask): 0 when the frame checks out

Source code in src/rpps/link/crc.py
def syndrome(self, bits, mask=0):
    """Received CRC field XOR the CRC of the message (and `mask`): 0 when the frame checks out"""
    msg, field = self._split(bits)
    return self.from_bits(field) ^ self.compute_bits(msg) ^ mask

encap

Encapsulation parent classes

Classes:

Name Description
Encap

Parent of framing / integrity-check definitions: the link transform, data bits <-> packets

CRC

CRC defined by config: width, poly, init, refin, refout, xorout (hex strings or ints), check value; or a composite

Frame

Framing (HDLC: bit stuffing; bytes: byte stuffing, SLIP / KISS / PPP) defined by config; the FCS is another config,

Encap

Encap(e_impl, d_impl)

Bases: Coding

Parent of framing / integrity-check definitions: the link transform, data bits <-> packets

Methods:

Name Description
load

Load from json: the type picks CRC or HDLC

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
load staticmethod
load(name: str, obj: dict)

Load from json: the type picks CRC or HDLC

Source code in src/rpps/link/encap.py
@staticmethod
def load(name: str, obj: dict):
    """Load from json: the `type` picks CRC or HDLC"""
    t = obj.get("type")
    if t in ("crc", "composite", "checksum"):
        return CRC.load(name, obj)
    if t in ("hdlc", "bytes"):
        return Frame.load(name, obj)
    raise ConfigError(f"Unknown encapsulation type {t!r} in {name}: have crc, composite, checksum, hdlc, bytes")

CRC

CRC(e_impl, d_impl)

Bases: Encap

CRC defined by config: width, poly, init, refin, refout, xorout (hex strings or ints), check value; or a composite check (type "composite": CRC parts over transformed views of the message, rpps.link.check)

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl

Frame

Frame(e_impl, d_impl)

Bases: Encap

Framing (HDLC: bit stuffing; bytes: byte stuffing, SLIP / KISS / PPP) defined by config; the FCS is another config, fcs, from config/crc

As an operator: packet * frame gives one frame's bits (flags, stuffing, FCS) per call; bits / frame the payload bits of the frames whose FCS checks out, however the stream is cut (an open frame waits for its closing flag in the next block)

Receiving, each good frame's payload starts with a publication, {"frame": where the frame starts, "frame_bits": its payload's bits}, at its place in the output, and an anchor there: a step after it (a link header that strips the frame's own header, {"link": "header"} driven by "frame" and "length": "frame_bits") reads frame by frame. Every frame's message carries the whole frame as received, payload then FCS (Message.frame, parts)

Methods:

Name Description
decode

bits / frame: the good frames' payloads; every frame, good or not, also emitted as a message from its opening

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
decode
decode(data)

bits / frame: the good frames' payloads; every frame, good or not, also emitted as a message from its opening flag (rpps.profile.message: bytes, crc_ok the FCS's verdict)

Source code in src/rpps/link/encap.py
def decode(self, data):
    """`bits / frame`: the good frames' payloads; every frame, good or not, also emitted as a message from its opening
    flag (rpps.profile.message: bytes, crc_ok the FCS's verdict)"""
    out = super().decode(data)
    from ..base.control import emit, publish, anchor
    n_out = 0 # Where each good frame's payload starts in the output (they come out in order)
    for s, p, ok, fcs in out.ctx.pop((self, "frames"), []):
        bits = np.unpackbits(np.frombuffer(p, np.uint8)).astype(bool)
        at = data.meta.pos + s
        fields = {"bytes": len(p)}
        if ok and self.payload_schema is not None: # What the payload says ("payload_fields": rpps.link.fields)
            from .fields import Short
            try:
                fields["payload"] = self.payload_schema.parse(bits)[0]
            except (Short, ValueError, ConfigError):
                pass
        whole = np.unpackbits(np.frombuffer(p + fcs, np.uint8)).astype(bool)
        parts = {"payload": (0, len(bits))}
        if fcs:
            parts["fcs"] = (len(bits), 8*len(fcs))
        emit(data.meta, self, None, fields, bits, bool(ok), at, frame=whole, parts=parts)
        if ok:
            publish(data.meta, self, {"frame": at, "frame_bits": len(bits)}, at=at, out=n_out, group=at)
            anchor(data.meta, self, at, n_out)
            n_out += len(bits)
    return out

fields

Fields: what a frame's bits say, as a definition (link headers, frame payloads, a profile step's messages)

A schema is a list of fields, read in order from the bits (most significant bit first unless order says otherwise):

{"name": "length", "bits": 8}                              an unsigned integer
{"name": "alt", "bits": 12, "signed": true,                two's complement; value = raw*scale + offset
 "scale": 25, "offset": -1000}
{"name": "type", "bits": 4, "order": "lsb",                bits least significant first; `enum` adds "type.name"
 "enum": {"0": "ADV_IND", "2": "ADV_NONCONN_IND"}}
{"name": "data", "type": "bytes", "bytes": "length - 1"}   bytes (a count or an expression over the fields before, or
                                                           "*": the group's whole bytes left; on build, the value's);
                                                           "reverse": true for an address sent low octet first
{"name": "call", "type": "text", "bytes": 6, "shift": 1}   ASCII, each byte shifted right `shift` bits (AX.25), stripped;
                                                           "encoding": "dvb": EN 300 468 annex A (a table byte first)
{"name": "freq", "type": "bcd", "bits": 32, "scale": 10}   BCD digits, then scale/offset; "mjd": a date ("2026-11-26"),
                                                           "time": BCD pairs ("12:34:56", 16 bits "12:34")
{"name": "pid", "bits": 8, "if": "(control & 1) == 0"}     only if the expression holds over the fields before (per
                                                           frame; a definition's "when" is decided at load, by params)
{"name": "pcr", "from": 48, "bits": 33}                    at a bit position (from the start of the schema or group)
{"name": "ads", "fields": [...], "repeat": "*"}             a group: a dict; repeated: a list. repeat: a count, an
{"name": "addr", "fields": [...], "until": "ext == 1"}      expression, or "*" (until the bits end); until: after each
                                                           element, stop when its fields make the expression true
{"name": "fmt", "fields": [...], "bytes": "fmt_length"}     a sized group: exactly that many bytes (the rest skipped;
                                                           padded with zeros on build); with "repeat": "*" a list
                                                           filling them (its bytes are there for len() on build)
{"name": "descs", "group": "descriptor", ...}              the definition's "groups": {"descriptor": [...]} as fields
{"name": "stuff", "align": 8}                              stuffing bits to a multiple of 8 from the group's start
{"name": "count", "bits": 8, "tx": "len(items) - 1"}       on build, when not given: from the group's values (its lists
                                                           and a sized group's bytes are there for len())

Expressions are the definitions' (rpps._config.evaluate) over the fields read so far (a group's own first, then its parents') and left, the bits not yet read. A field's bits may be an expression too.

parse(bits) gives (values, bits used) and raises Short when the bits end before the schema does (a header waiting for the rest of its bits); build(values) gives the bits (transmit), fields not given taken from their "tx", else their "default", else 0; an enum field may be given by name ("mod.name": "psk/qpsk"), a uint by its bits (a sequence of 0/1).

Classes:

Name Description
Short

The bits ended before the schema did

Schema

Functions:

Name Description
mjd_date

A Modified Julian Date as an ISO date (EN 300 468 annex C)

mjd_of

The Modified Julian Date of an ISO date

dvb_text

A DVB string (EN 300 468 annex A): a first byte below 0x20 names its table (latin-1 stands in for ISO 6937, the

dvb_bytes

A DVB string's bytes: as they are when printable ASCII, else UTF-8 after its table byte (0x15)

Short

Bases: Exception

The bits ended before the schema did

Schema

Schema(fields, order='msb', name='fields', groups=None)

Methods:

Name Description
parse

(values, bits used) of the schema read from bits; raises Short when they end first

build

The bits of these values (see the module for fields not given); scope: values expressions may name too

Attributes:

Name Type Description
top

The names of the top-level fields

fixed_bits

Bits of the schema when every field has a fixed size and none is conditional or repeated, else None

Source code in src/rpps/link/fields.py
def __init__(self, fields, order="msb", name="fields", groups=None):
    self.name, self.order = name, order
    if order not in ("msb", "lsb"):
        raise ConfigError(f"{name}: order is msb or lsb, not {order!r}")
    self.fields = _expand([dict(f) for f in fields], dict(groups or {}), name, ())
    for f in self._all(self.fields):
        bad = set(f) - KEYS
        if "name" not in f or bad:
            raise ConfigError(f"{name}: a field needs a name and takes {sorted(KEYS)}; got {f}")
        if "align" in f:
            if set(f) - {"name", "align", "if", "comment"} or not isinstance(f["align"], int) or f["align"] < 1:
                raise ConfigError(f"{name}: field {f['name']}: an align field takes a whole number of bits (and if)")
            continue
        if "fields" in f and "bytes" in f and ("until" in f or f.get("repeat", "*") != "*"):
            raise ConfigError(f"{name}: field {f['name']}: a sized group (bytes) repeats only as \"*\" (to fill them)")
        kind = f.get("type", "uint")
        if kind not in BITS_KINDS + ("bytes", "text"):
            raise ConfigError(f"{name}: field {f['name']}: type is {', '.join(BITS_KINDS)}, bytes or text, not {kind!r}")
        if "fields" not in f and kind in BITS_KINDS and "bits" not in f:
            raise ConfigError(f"{name}: field {f['name']} needs 'bits'")
        if kind in ("time", "mjd") and ("scale" in f or "offset" in f or "enum" in f):
            raise ConfigError(f"{name}: field {f['name']} ({kind}) takes no scale, offset or enum")
        if f.get("encoding", "ascii") not in ("ascii", "dvb") or ("encoding" in f and kind != "text"):
            raise ConfigError(f"{name}: field {f['name']}: encoding (ascii or dvb) is a text field's")
        if kind not in BITS_KINDS and "bytes" not in f and "fields" not in f:
            raise ConfigError(f"{name}: field {f['name']} ({kind}) needs 'bytes'")
        if f.get("order", order) not in ("msb", "lsb"):
            raise ConfigError(f"{name}: field {f['name']}: order is msb or lsb")
top property
top

The names of the top-level fields

fixed_bits property
fixed_bits

Bits of the schema when every field has a fixed size and none is conditional or repeated, else None

parse
parse(bits, scope=None)

(values, bits used) of the schema read from bits; raises Short when they end first

Source code in src/rpps/link/fields.py
def parse(self, bits, scope=None):
    """(values, bits used) of the schema read from `bits`; raises Short when they end first"""
    b = np.asarray(bits).astype(bool).reshape(-1)
    vals, used = self._group(self.fields, b, 0, dict(scope or {}))
    return vals, used
build
build(values, scope=None)

The bits of these values (see the module for fields not given); scope: values expressions may name too

Source code in src/rpps/link/fields.py
def build(self, values, scope=None):
    """The bits of these values (see the module for fields not given); scope: values expressions may name too"""
    out = []
    self._build(self.fields, dict(values or {}), dict(scope or {}), out)
    return np.concatenate(out).astype(bool) if out else np.zeros(0, bool)

mjd_date

mjd_date(mjd)

A Modified Julian Date as an ISO date (EN 300 468 annex C)

Source code in src/rpps/link/fields.py
def mjd_date(mjd):
    """A Modified Julian Date as an ISO date (EN 300 468 annex C)"""
    import datetime
    return (datetime.date(1858, 11, 17) + datetime.timedelta(days=int(mjd))).isoformat()

mjd_of

mjd_of(date)

The Modified Julian Date of an ISO date

Source code in src/rpps/link/fields.py
def mjd_of(date):
    """The Modified Julian Date of an ISO date"""
    import datetime
    return (datetime.date.fromisoformat(date) - datetime.date(1858, 11, 17)).days

dvb_text

dvb_text(data)

A DVB string (EN 300 468 annex A): a first byte below 0x20 names its table (latin-1 stands in for ISO 6937, the default); emphasis codes go, 0x8A is a line break

Source code in src/rpps/link/fields.py
def dvb_text(data):
    """A DVB string (EN 300 468 annex A): a first byte below 0x20 names its table (latin-1 stands in for ISO 6937, the
    default); emphasis codes go, 0x8A is a line break"""
    data = bytes(data)
    if not data:
        return ""
    b0, codec = data[0], "latin-1"
    if 1 <= b0 <= 0x0B:
        codec, data = f"iso8859_{b0 + 4}", data[1:]
    elif b0 == 0x10 and len(data) >= 3:
        codec, data = f"iso8859_{data[2]}", data[3:]
    elif b0 == 0x11:
        return data[1:].decode("utf-16-be", "replace")
    elif b0 == 0x15:
        return data[1:].decode("utf-8", "replace")
    elif b0 < 0x20:
        data = data[1:]
    data = bytes(c for c in data.replace(b"\x8a", b"\n") if not 0x80 <= c <= 0x9F)
    try:
        return data.decode(codec, "replace")
    except LookupError:
        return data.decode("latin-1")

dvb_bytes

dvb_bytes(text)

A DVB string's bytes: as they are when printable ASCII, else UTF-8 after its table byte (0x15)

Source code in src/rpps/link/fields.py
def dvb_bytes(text):
    """A DVB string's bytes: as they are when printable ASCII, else UTF-8 after its table byte (0x15)"""
    if all(0x20 <= ord(c) < 0x7F for c in text):
        return text.encode("ascii")
    return b"\x15" + text.encode("utf-8")

gse

Generic Stream Encapsulation (ETSI TS 102 606-1): PDUs in the data fields of DVB-S2 BBFRAMEs

{"link": "gse", "protocols": [130]}        receive: the PDUs of those protocol types, each a frame of its own

A data field holds GSE packets one after the other, then padding (a packet header of zeros) to its end; a packet never crosses into the next data field, so a PDU too long for what is left is sent in fragments (Start, End indicators; a fragment id), the first saying the PDU's total length, the last carrying a CRC-32 (MPEG-2) over the whole of it.

S E LT GSE_Length(12) [Frag_ID(8)] [Total_Length(16)] [Protocol_Type(16) Label(6 | 3 | 0 bytes)] data [CRC_32]

Receiving takes the data fields as a frame each (its start where a profile's BBHEADER says one starts: the step's frame control); every whole PDU is a message (kind "gse": protocol, label, length, its bytes), a fragmented one whose CRC fails a failed message. The PDUs of the protocols asked for (all: none given) come out, each published as a frame of its own ({"frame": k, "protocol", "pdu_bits"}) so the steps after (a table's header) read each by itself. Protocol types below 0x0600 are taken as the PDU's own type, not an extension header (DVB-RCS2's NCR 0x0081 and lower layer signalling 0x0082 are used so); extension headers are not read.

Transmitting a stream of data fields is pack(pdus, size): the PDUs fragmented across data fields of size bytes, each padded to its end (what a profile's BBHEADER then frames).

Classes:

Name Description
GSE

Functions:

Name Description
pack

Data fields of size bytes carrying the PDUs [(protocol type, payload bytes) or (protocol, payload, label

GSE

GSE(protocols=None, name='gse')

Bases: Pipe

Source code in src/rpps/link/gse.py
def __init__(self, protocols=None, name="gse"):
    self.protocols = None if protocols is None else {int(p) for p in protocols}
    self.name = name
    self._start = True

pack

pack(pdus, size, frag_ids=None)

Data fields of size bytes carrying the PDUs [(protocol type, payload bytes) or (protocol, payload, label bytes)] in GSE packets: whole where they fit, else fragmented (the first fragment as long as the field allows, the rest in the next fields), every field padded with zeros

Source code in src/rpps/link/gse.py
def pack(pdus, size, frag_ids=None):
    """Data fields of `size` bytes carrying the PDUs [(protocol type, payload bytes) or (protocol, payload, label
    bytes)] in GSE packets: whole where they fit, else fragmented (the first fragment as long as the field allows, the
    rest in the next fields), every field padded with zeros"""
    fields, cur = [], bytearray()
    def room():
        return size - len(cur)
    def close():
        nonlocal cur
        fields.append(bytes(cur) + bytes(size - len(cur)))
        cur = bytearray()
    fid = 0
    for item in pdus:
        proto, data = int(item[0]), bytes(item[1])
        label = bytes(item[2]) if len(item) > 2 and item[2] is not None else b""
        lt = {6: 0, 3: 1, 0: 2}.get(len(label))
        if lt is None:
            raise ValueError("gse.pack: a label is 6, 3 or 0 bytes")
        head = proto.to_bytes(2, "big") + label
        whole = 2 + len(head) + len(data)
        if whole > 4097:
            raise ValueError("gse.pack: a PDU over 4095 bytes needs a fragmenting packet of its own; not supported")
        if room() < 2 + len(head) + 1: # (no room for this packet's header and a byte: the next field)
            close()
        if whole <= room(): # Whole: S=1 E=1
            cur += (0xC000 | (lt << 12) | (len(head) + len(data))).to_bytes(2, "big") + head + data
            continue
        # Fragmented: total length over protocol, label and data; CRC-32 over total length, them and the data
        total = (len(head) + len(data)).to_bytes(2, "big")
        crc = _crc32(total + head + data).to_bytes(4, "big")
        body = head + data + crc # (the bytes the fragments carry after the first's frag id and total length)
        first = True
        frag = frag_ids[fid % len(frag_ids)] if frag_ids else fid % 256
        fid += 1
        while body:
            over = 2 + 1 + (2 if first else 0) # GSE header, frag id, total length (the first)
            if room() < over + 1:
                close()
            n = min(len(body), room() - over)
            last = n == len(body)
            s, e = (1 if first else 0), (1 if last else 0)
            if first and last: # (it fits after all: the packet is whole)
                raise AssertionError("gse.pack")
            ltv = lt if first else 3
            length = 1 + (2 if first else 0) + n
            cur += ((s << 15) | (e << 14) | (ltv << 12) | length).to_bytes(2, "big") + bytes([frag]) \
                   + (total if first else b"") + body[:n]
            body, first = body[n:], False
            if body:
                close()
    if cur or not fields:
        close()
    return fields

hdlc

Classes:

Name Description
hdlc

HDLC framing: flags, bit stuffing and an FCS, defined by config (see config/frame)

hdlc

hdlc(log, fcs, flag=126, stuff=5, nrzi=False, min_bytes=4)

Bases: _code

HDLC framing: flags, bit stuffing and an FCS, defined by config (see config/frame)

fcs: a crc instance. flag: the flag byte (0x7E). stuff: ones before a zero is inserted (5) nrzi: line coding (a 0 is a transition, a 1 is no change). Bytes go out least significant bit first. min_bytes: shortest frame (including the FCS) accepted.

encode(frames) takes a list of bytes. decode(bits) returns the frames whose FCS checks out (status=True: also 0 or -1 per frame found, by its FCS); deframe(bits) gives every frame with its FCS verdict, and the aborts.

Methods:

Name Description
frame

Bits of one frame: flag, stuffed payload + FCS, flag

deframe

Frames as (payload bytes, fcs ok) in the bit stream, and the number of aborted frames

frames_at

Frames as (index of the opening flag in bits, payload bytes, fcs ok, the FCS bytes received), and the number of

consumed

How many of these bits are done with: up to the last flag (a frame may be open there), or all but a flag's

decode_stream

Decode held (what the last call kept) and bits together: (data bits of the good frames, what to hold).

Source code in src/rpps/link/hdlc.py
def __init__(self, log, fcs, flag=0x7E, stuff=5, nrzi=False, min_bytes=4):
    super().__init__(log, None, 1, 1)
    self.fcs, self.flag, self.stuff, self.nrzi, self.min_bytes = fcs, flag, stuff, nrzi, min_bytes
    self.flag_bits = self._lsb(bytes([flag]))
frame
frame(payload)

Bits of one frame: flag, stuffed payload + FCS, flag

Source code in src/rpps/link/hdlc.py
def frame(self, payload):
    """Bits of one frame: flag, stuffed payload + FCS, flag"""
    body = bytes(payload)
    body += self.fcs.to_bytes(self.fcs.compute(body))
    return np.concatenate((self.flag_bits, self._stuffed(self._lsb(body)), self.flag_bits))
deframe
deframe(bits)

Frames as (payload bytes, fcs ok) in the bit stream, and the number of aborted frames

Source code in src/rpps/link/hdlc.py
def deframe(self, bits):
    """Frames as (payload bytes, fcs ok) in the bit stream, and the number of aborted frames"""
    frames, aborts = self.frames_at(bits)
    return [(p, ok) for _, p, ok, _ in frames], aborts
frames_at
frames_at(bits)

Frames as (index of the opening flag in bits, payload bytes, fcs ok, the FCS bytes received), and the number of aborted frames

Source code in src/rpps/link/hdlc.py
def frames_at(self, bits):
    """Frames as (index of the opening flag in `bits`, payload bytes, fcs ok, the FCS bytes received), and the number of
    aborted frames"""
    b = np.asarray(bits, dtype=np.uint8)
    if self.nrzi:
        b = np.concatenate(([0], (b[1:] == b[:-1]).astype(np.uint8)))
    # Flags: 01111110 patterns (LSB first: the flag byte's bits in transmission order)
    n = len(self.flag_bits)
    starts = bitops.find(b, self.flag_bits)
    spans = [(int(s), int(e)) for s, e in zip(starts[:-1], starts[1:]) if e - s > n] # (adjacent flags: idle)
    status, raws = bitops.unstuff(b, [s + n for s, _ in spans], [e for _, e in spans], self.stuff)
    frames, aborts = [], 0
    n_fcs = self.fcs.width // 8
    for (s, _), st, raw in zip(spans, status, raws):
        if st: # more than `stuff` ones inside, or not whole bytes
            aborts += 1
            continue
        if len(raw) < self.min_bytes:
            continue
        ok = self.fcs.to_bytes(self.fcs.compute(raw[:-n_fcs])) == raw[-n_fcs:]
        frames.append((s, raw[:-n_fcs], ok, raw[-n_fcs:]))
    return frames, aborts
consumed
consumed(bits)

How many of these bits are done with: up to the last flag (a frame may be open there), or all but a flag's worth when nothing can start one. The rest waits for the next block, so a frame cut by a block boundary is whole

Source code in src/rpps/link/hdlc.py
def consumed(self, bits):
    """How many of these bits are done with: up to the last flag (a frame may be open there), or all but a flag's
    worth when nothing can start one. The rest waits for the next block, so a frame cut by a block boundary is whole"""
    b = np.asarray(bits, dtype=np.uint8)
    if self.nrzi:
        b = np.concatenate(([0], (b[1:] == b[:-1]).astype(np.uint8)))
    n = len(self.flag_bits)
    if len(b) < n:
        return 0
    starts = bitops.find(b, self.flag_bits)
    if not len(starts):
        return max(0, len(b) - (n - 1) - (1 if self.nrzi else 0))
    last = int(starts[-1])
    if len(b) - last > self.MAX_FRAME_BITS:
        return max(0, len(b) - (n - 1) - (1 if self.nrzi else 0))
    return max(0, last - (1 if self.nrzi else 0)) # (NRZI: the bit before the flag is its reference)
decode_stream
decode_stream(bits, held, frames=None)

Decode held (what the last call kept) and bits together: (data bits of the good frames, what to hold). frames: a list to append every frame found to, as frames_at gives them (index in held + bits)

Source code in src/rpps/link/hdlc.py
def decode_stream(self, bits, held, frames=None):
    """Decode `held` (what the last call kept) and `bits` together: (data bits of the good frames, what to hold).
    frames: a list to append every frame found to, as `frames_at` gives them (index in held + bits)"""
    buf = np.concatenate((np.asarray(held, dtype=np.uint8), np.asarray(bits, dtype=np.uint8)))
    used = self.consumed(buf)
    part = buf[:used + len(self.flag_bits) + (1 if self.nrzi else 0)]
    out = self.decode(part) if used else np.zeros(0, bool)
    if frames is not None and used:
        frames += self.frames_at(part)[0]
    # Frames between the flags before `used` are out; the flag at `used` opens the next one (decode found no frame after it)
    return out, buf[used:]

header

Link headers: fields, a CRC, and the payload they announce (rpps.profile.control)

A definition, config/header/link/.json, rp.link.load("header/ieee80211b_plcp"):

{"base": "header", "type": "link", "comment": "...", "ref": "...",
 "order": "lsb",                                      field bits sent least ("lsb") or most ("msb") significant first
 "payload_fields": [...],                             what the payload says, for its message (rpps.link.fields), read
                                                      with the header's fields in scope: Message.fields["payload"]
 "payload_order": "lsb",                              the payload's bytes sent least significant bit first (BLE, 802.11);
                                                      out (and in, transmitting) come bytes most significant bit first,
                                                      as everywhere else. Default "msb": the payload as sent
 "fields": [{"name": "signal", "bits": 8},               (a schema: rpps.link.fields; conditional, repeated and
                                                      expression-sized fields make a header read as it comes)
            {"name": "length", "bits": 16,
             "tx": "(bits*10 + signal - 1)//signal"},   transmit: its value from the payload's bits and the other
            ...],                                         fields (an expression, as "expr" takes, worked out per frame);
                                                          else the controlled value, its "default", or 0
 "crc": "crc16_genibus",                              a crc definition over the field bits, sent after them
 "fcs": "crc24_ble",                                  a crc definition over header and payload, sent after the payload;
                                                      {"crc": ..., "if": "ssi == 1"}: only on frames whose fields say so
 "payload": "length*signal//10",                      receive: payload bits after the header, from the fields (and
                                                      `length`, a framed header's frame length: "length - 48 - 32*ocf")
 "preamble": {"ones": 128, "word": "0xF3A0", "bits": 16},   transmit: sent before the header (in `order`)
 "framed": true,                                      frames of `length` bits (a controlled parameter: DVB-S2 Kbch),
                                                      the payload padded to fill them
 "length": 96}                                        framed: the frame length until a control sets one (fixed blocks)

Receiving, each frame starts where a profile applies a change (a delimiter before it publishes frame starts), or, framed, length bits after the last. The header's fields, with "bits" (the payload's length), are published from the payload's first bit for the payload's length, and {"frame_bits": header + payload} from the frame's first bit (rp.base.control.publish), so a profile can drive the rate of the payload and the length of the frame. A header whose CRC fails is counted, and its frame dropped; so is a frame whose FCS fails (fcs_failed). Out come the payloads. Every frame is also emitted as a message (rpps.profile.message) from its first bit: its fields, its payload, and crc_ok (the FCS's verdict, else the header CRC's, else None); a failed one too (crc_ok False, the fields as far as they were read). select ({field: value}) keeps only the frames whose fields have those values: the others are used up, counted (skipped), and neither given nor published (one of a DVB-S2 multistream's input streams by its ISI). Transmitting, a frame starts at each change a profile applies: its fields are the controlled values; framed, its payload is length minus the header, else everything until the next frame start (one frame per call). The fields are published from the payload's first bit, and {"frame_bits": the frame's bits} from the frame's first bit after the preamble, so the steps after the header can restart per frame (a whitening sequence, a sync marker) where a profile's controls say so.

Classes:

Name Description
Header

Header

Header(name, fields, order='msb', crc=None, payload=None, preamble=None, framed=False, fcs=None, payload_order='msb', payload_fields=None, groups=None)

Bases: Pipe

Methods:

Name Description
control

A frame starts here (receive and transmit); length: its bits, framed; fields: transmit values

kernel

The batch decoder of a framed header of fixed size with a known frame length, its payload as sent, no FCS and no

need

The header's bits, CRC included, as far as these first bits of it say (more once more of it is read)

parse

(fields, CRC ok) of a header's bits

payload_values

What payload_fields reads of a payload (bytes most significant bit first), the header's fields in scope;

build

A header's bits for these field values

payload_bits

The payload's bits: the payload expression over the fields (and length, a framed header's frame length)

frame_fcs

The FCS bits this frame carries (fcs with an "if": only some frames do)

Source code in src/rpps/link/header.py
def __init__(self, name, fields, order="msb", crc=None, payload=None, preamble=None, framed=False, fcs=None,
             payload_order="msb", payload_fields=None, groups=None):
    from .fields import Schema
    self.name = name
    if payload_order not in ("msb", "lsb"):
        raise ConfigError(f"header {name}: payload_order is msb or lsb, not {payload_order!r}")
    self.payload_lsb = payload_order == "lsb"
    self.schema = Schema(fields, order, f"header {name}", groups) # (rpps.link.fields: optional, repeated, sized by expression)
    self.fields = self.schema.fields
    self.payload_schema = None if not payload_fields else Schema(payload_fields, "msb", f"header {name} payload", groups)
    self.order = order
    self.crc = None if crc is None else _crc(crc)
    self.fcs_if = None # An expression over the fields: the frames that carry the FCS (None: all)
    if isinstance(fcs, dict):
        if set(fcs) - {"crc", "if"} or "crc" not in fcs:
            raise ConfigError(f"header {name}: fcs is a crc name or {{\"crc\": ..., \"if\": ...}}, not {fcs}")
        if framed:
            raise ConfigError(f"header {name}: a framed header's FCS is on every frame")
        fcs, self.fcs_if = fcs["crc"], fcs.get("if")
    self.fcs = None if fcs is None else _crc(fcs)
    self.fcs_bits = 0 if self.fcs is None else self.fcs.width
    self.check_name = fcs or crc # The check behind a message's crc_ok (Message.check)
    self.payload = payload
    self.framed = bool(framed)
    self.crc_bits = self.crc.width if self.crc is not None else 0
    self.field_bits = self.schema.fixed_bits # None: the header's size follows its fields (read as they come)
    self.header_bits = None if self.field_bits is None else self.field_bits + self.crc_bits
    if framed and self.header_bits is None:
        raise ConfigError(f"header {name}: a framed header has fields of fixed size")
    self.preamble = np.zeros(0, dtype=bool) if not preamble else np.concatenate((
        np.ones(int(preamble.get("ones", 0)), dtype=bool),
        self._value_bits(preamble["word"], int(preamble["bits"])) if "word" in preamble else np.zeros(0, bool)))
    self.values = {f["name"]: f.get("default", 0) for f in self.fields}
    self.length = None
    self.select = None # {field: value}: the frames kept (see the module)
    self._start = True
    self.CONTROLS = {"frame": "live", "length": "live", **{f["name"]: "live" for f in self.fields}}
control
control(frame=None, length=None, **fields)

A frame starts here (receive and transmit); length: its bits, framed; fields: transmit values

Source code in src/rpps/link/header.py
def control(self, frame=None, length=None, **fields):
    """A frame starts here (receive and transmit); length: its bits, framed; fields: transmit values"""
    unknown = set(fields) - set(self.values)
    if unknown:
        raise ConfigError(f"header {self.name}: no field {sorted(unknown)}")
    if length is not None:
        self.length = int(length)
    self.values = {**self.values, **{k: v for k, v in fields.items() if v is not None}}
    self._start = True
kernel
kernel(params, how)

The batch decoder of a framed header of fixed size with a known frame length, its payload as sent, no FCS and no select (rpps.link.kernels.HeaderDecode); None otherwise (the frames go through the operator one at a time)

Source code in src/rpps/link/header.py
def kernel(self, params, how):
    """The batch decoder of a framed header of fixed size with a known frame length, its payload as sent, no FCS and no
    `select` (rpps.link.kernels.HeaderDecode); None otherwise (the frames go through the operator one at a time)"""
    if how != "/":
        return None
    if params:
        self.control(**params)
    if not (self.framed and self.length and self.header_bits is not None and self.fcs is None and not self.select
            and not self.payload_lsb):
        return None
    from .kernels import HeaderDecode
    return HeaderDecode(self, self.length)
need
need(bits)

The header's bits, CRC included, as far as these first bits of it say (more once more of it is read)

Source code in src/rpps/link/header.py
def need(self, bits):
    """The header's bits, CRC included, as far as these first bits of it say (more once more of it is read)"""
    if self.header_bits is not None:
        return self.header_bits
    from .fields import Short
    try:
        return self.schema.parse(bits)[1] + self.crc_bits
    except Short as e:
        return e.args[0] + self.crc_bits
parse
parse(bits)

(fields, CRC ok) of a header's bits

Source code in src/rpps/link/header.py
def parse(self, bits):
    """(fields, CRC ok) of a header's bits"""
    bits = np.asarray(bits).astype(bool)
    out, i = self.schema.parse(bits)
    ok = True
    if self.crc is not None:
        ok = self.crc.from_bits(bits[i:i + self.crc.width]) == self.crc.compute_bits(bits[:i])
    return out, ok
payload_values
payload_values(payload, fields=None)

What payload_fields reads of a payload (bytes most significant bit first), the header's fields in scope; None when it doesn't fit

Source code in src/rpps/link/header.py
def payload_values(self, payload, fields=None):
    """What `payload_fields` reads of a payload (bytes most significant bit first), the header's `fields` in scope;
    None when it doesn't fit"""
    if self.payload_schema is None or payload is None:
        return None
    from .fields import Short
    try:
        return self.payload_schema.parse(payload, {k: v for k, v in (fields or {}).items() if not isinstance(v, (list, dict))})[0]
    except (Short, ValueError, ConfigError):
        return None
build
build(values)

A header's bits for these field values

Source code in src/rpps/link/header.py
def build(self, values):
    """A header's bits for these field values"""
    bits = self.schema.build(values)
    if self.crc is not None:
        bits = np.concatenate((bits, self.crc.field(bits)))
    return bits
payload_bits
payload_bits(fields)

The payload's bits: the payload expression over the fields (and length, a framed header's frame length)

Source code in src/rpps/link/header.py
def payload_bits(self, fields):
    """The payload's bits: the `payload` expression over the fields (and `length`, a framed header's frame length)"""
    if self.payload is None:
        return None
    scope = {**fields, "length": self.length} if self.length is not None else fields
    return int(_config.evaluate(self.payload, scope, f"header {self.name}"))
frame_fcs
frame_fcs(fields)

The FCS bits this frame carries (fcs with an "if": only some frames do)

Source code in src/rpps/link/header.py
def frame_fcs(self, fields):
    """The FCS bits this frame carries (`fcs` with an "if": only some frames do)"""
    if self.fcs is None or (self.fcs_if is not None and not _config.evaluate(
            self.fcs_if, {k: v for k, v in fields.items() if not isinstance(v, (list, dict))}, f"header {self.name}")):
        return 0
    return self.fcs_bits

kernels

Batch kernels of the link operators: HeaderDecode of a framed header (rpps.parallel)

Checked row for row against the operator run frame by frame (tests/unit/parallel/test_batch_kernels.py). The header bits of each row come to the host (a few bytes) to be read; the payloads are cut on whichever xp the batch is on

Classes:

Name Description
HeaderDecode

A framed header (rpps.link.header.Header) of fixed size, one frame a row: its fields and CRC read, and the payload

HeaderDecode

HeaderDecode(op, length)

Bases: Kernel

A framed header (rpps.link.header.Header) of fixed size, one frame a row: its fields and CRC read, and the payload they announce given (payload, at most the frame's length less the header). A row whose header fails its CRC is dropped (the operator gives it no payload, and a message with crc_ok False); one shorter than its header gives nothing, as the operator does. Rows of one batch give payloads of one length (as LoopKernel asks)

Source code in src/rpps/link/kernels.py
def __init__(self, op, length):
    self.op, self.length = op, int(length)
    self.name = f"header:{op.name}"

packets

Packets that cross frames: a stream of packets carried in the data fields of fixed frames, cut back into packets

{"link": "packets", "id": "space", "params": ["fhp", "vcid", "vc_count"],          what a header before it gives
 "frame_fields": [...],                         read at the start of each frame's data (in band: a pointer byte)
 "active": "1",                                  frames that carry packets at all (others are passed over)
 "starts": "fhp != 2047",                        a packet starts in this frame (else it only continues one)
 "pointer": "8*fhp",                             where, in bits from the data's start (after the frame_fields)
 "idle_frame": "fhp == 2046",                    a frame of idle data only
 "channel": "vcid", "count": "vc_count", "modulo": 256,    streams kept apart, and their frame counts
 "fields": [...],                                the packet's header (rpps.link.fields)
 "length": "8*(length + 7)",                     its whole length in bits, from those fields
 "idle": "apid == 2047",                         idle packets: used up, not given
 "end": "table_id == 255",                       filler: the rest of the frame is not packets
 "carried_check": {"crc": "crc8_dvbs2", "bits": 8, "restore": "0x47"},
 "keep": "8*188",                                the packet's first bits given; the rest of it is its trailer
 "trailer": [...],                               fields read there and taken off (DVB-S2's ISSY and DNP)
 "insert": {"count": "dnp", "bits": 1504,         packets put back before it: `count` of them, each `head` then
            "head": "0x471FFF10", "fill": 255},   `fill` bytes to `bits` (the null packets DVB-S2 deleted)
 "defaults": {"upl": 1504},                      values of the params before any control (transmit: all there is)
                                                 (a list of numbers too: `pid in more`)
 "tx": {"syncd": "pointer if start else 65535"}} transmit: the fields published at each frame's start

A header step before it (a transfer frame's, a BBHEADER, a transport packet's) drives it from each frame's data: the profile's controls give it frame (a frame starts here), length (the data's bits; bits of a header) and the params it names. Each frame's data is taken whole, then cut: what comes before the pointer finishes the packet the last frame of its channel left open; from the pointer, packets follow one another, each length long, the last one left open for the next frame. A frame lost (its channel's count skips: modulo), or a packet whose end doesn't meet the pointer, drops only the packets that crossed it (est[id]: "lost", "misaligned"); the stream picks up again at the next pointer. A pointer the open packet does end at is counted est[id]["aligned"]: the packets' own lengths meeting the frames' pointers is the layer's check (random data's lengths run past them), which blind identification reads to tell a packet layer that is there from one that isn't (rpps.analysis.signal_profile). Bits left before a pointer that are fewer than a header are filler (no packet fits there). A packet's length of zero or over max bits (default 65536*8) is taken as lost sync.

Every packet is a message (kind: the step's id) with its header's fields and the channel, its frame the whole packet (parts: header, payload); good packets come out, one after another, each published as a frame of its own ({"frame", "packet_bits"}) for a step after it.

Trailer and inserted packets (DVB-S2 null-packet deletion, EN 302 307-1 annex D.3): a user packet length long carries more than the packet it stands for (an ISSY field, the DNP byte). Once checked, its first keep bits are the packet; the trailer fields are read from the rest (into its message's fields) and taken off. insert then puts count packets back before it (the null packets deleted since the last one: bits long, head then fill bytes); they are given and published as frames like the others, but are not messages (counted: est[id]["inserted"]).

Carried check (DVB-S2 TS mode, EN 302 307-1 5.1.4): a packet's first bits are a check over the packet before (all of it but those first bits): each packet is given once the next has said whether it was good, its first bits then set to restore (the sync byte 0x47 the check stood in for). The last packet of a stream is given unchecked.

Transmitting packs a stream of packets back to back into the frames' data fields. A frame starts at each control (length: its data field's bits, the profile's framer giving it); at each start the tx fields are worked out and published for the header step after it to build that frame with: over the params (defaults), pointer (bits from the data field's start to the first packet starting in it), start (1 when one does, else 0) and frame (the frames so far). A carried check is made (each packet's first bits the check of the one before; the first packet's zeros). The packets' lengths come from their own header (fields, length); a frame start is published once the first packet starting at or after it is seen, so the output from a frame start may wait up to a packet. Not transmitted: frame_fields (a pointer in the data field), a trailer of any bits (ISSY, null-packet deletion), channels of their own; the step refuses them.

Shipped: ccsds/tm_packets (space packets out of TM transfer frames by their first header pointer), dvbs2/ts (transport stream packets out of BBFRAMEs in TS mode by SYNCD and UPL, null packets deleted put back; transmitted too), dvbs2/mpe and dvbs2/ule (sections and SNDUs out of the transport packets of one PID, by the pointer field). A profile's capture rule then sends them on.

Classes:

Name Description
Packets

Packets cut from frames' data fields (see module)

Packets

Packets(spec, name='packets')

Bases: Pipe

Packets cut from frames' data fields (see module)

Source code in src/rpps/link/packets.py
def __init__(self, spec, name="packets"):
    spec = dict(spec)
    bad = set(spec) - KEYS
    if bad:
        raise ConfigError(f"link packets {name}: unknown keys {sorted(bad)}; it takes {sorted(KEYS)}")
    self.name = name
    self.params = list(spec.get("params", []))
    self.CONTROLS = {"frame": "live", "length": "live", **{p: "live" for p in self.params}}
    self.frame_fields = Schema(spec["frame_fields"], "msb", f"packets {name} frame_fields") if spec.get("frame_fields") else None
    self.active, self.starts = spec.get("active"), spec.get("starts", "1")
    if "pointer" not in spec or "length" not in spec:
        raise ConfigError(f"link packets {name}: needs \"pointer\" and \"length\"")
    self.pointer, self.length = spec["pointer"], spec["length"]
    self.idle_frame, self.channel, self.count = spec.get("idle_frame"), spec.get("channel"), spec.get("count")
    self.modulo = int(spec.get("modulo", 0)) or None
    self.fields = Schema(spec.get("fields", []), "msb", f"packets {name} fields")
    self.header_bits = self.fields.fixed_bits
    if self.header_bits is None:
        raise ConfigError(f"link packets {name}: a packet's header has fields of fixed size")
    self.idle, self.end = spec.get("idle"), spec.get("end")
    self.max = int(spec.get("max", 8*65536))
    cc = spec.get("carried_check")
    self.carried = None
    if cc:
        from .serial import load
        self.carried = (load(f"crc/{cc['crc']}").encoder, int(cc["bits"]),
                        None if cc.get("restore") is None else _config.evaluate(str(cc["restore"]), {}, name))
        self.check_name = cc["crc"]
    else:
        self.check_name = None
    self.keep = spec.get("keep")
    self.trailer = Schema(spec["trailer"], "msb", f"packets {name} trailer") if spec.get("trailer") else None
    ins = spec.get("insert")
    self.insert = None
    if ins:
        bad = set(ins) - {"count", "bits", "head", "fill"}
        if bad or "count" not in ins or "bits" not in ins:
            raise ConfigError(f"link packets {name}: insert takes count, bits, head and fill (needs count and bits), not {sorted(bad)}")
        nbits, head = int(ins["bits"]), str(ins.get("head", "0x"))
        hb = 4*(len(head) - 2) if head.lower().startswith("0x") else 0
        hv = int(head, 16) if hb else 0
        fill = int(ins.get("fill", 0))
        pkt = np.concatenate((((hv >> np.arange(hb - 1, -1, -1)) & 1).astype(bool),
                              np.tile(((fill >> np.arange(7, -1, -1)) & 1).astype(bool), max(0, nbits - hb)//8 + 1)))[:nbits]
        self.insert = (ins["count"], pkt)
    defaults = dict(spec.get("defaults", {}))
    if set(defaults) - set(self.params):
        raise ConfigError(f"link packets {name}: defaults {sorted(set(defaults) - set(self.params))} are not params ({self.params})")
    self.defaults = {p: tuple(int(x) for x in v) if isinstance(v, (list, tuple)) else int(v)
                     for p, v in ((p, defaults.get(p, 0)) for p in self.params)} # (a list: for `in`)
    self.tx = dict(spec.get("tx", {}))
    self.values = dict(self.defaults)
    self.frame_len = None
    self._start = False

serial

Link definitions, one resource each: config/crc, config/frame, config/header/link; rp.link.load("crc/crc32_mpeg2")

crc {"base": "crc", "type": "crc", "width": 16, "poly": "0x1021", "init": "0x0", "xorout": "0x0", "refin": false, "refout": false, the reveng catalogue fields (numbers or hex strings) "check": "0x29b1"} optional: the CRC of b"123456789", verified on load width is 1 to 64 bits; encode / decode / syndrome work on bit streams of any length (see crc) {"base": "crc", "type": "composite", a check from CRC parts over transformed views of the message "parts": [{"crc": "crc8_smbus"}, {"crc": "crc8_smbus", "input": ["nibble_swap"]}], "combine": "concat"} (or "xor"); goes wherever a crc does (see rpps.link.check) {"base": "crc", "type": "checksum", a sum, ones' complement (Internet), Fletcher, Adler or XOR checksum "algorithm": "internet", ...} (see rpps.link.checksum); goes wherever a crc does frame {"base": "frame", "type": "hdlc", "flag": "0x7E", "stuff": 5, "nrzi": false, "fcs": "crc16_x25", the name of a crc definition "min_bytes": 4} {"base": "frame", "type": "bytes", byte stuffing (SLIP, KISS, asynchronous PPP; see bytestuff) "flag": "0xC0", "escape": "0xDB", "escapes": {"0xC0": "0xDC", "0xDB": "0xDD"}, what follows the escape for each byte, or "xor": "0x20" for "fcs": null, "refin": false} the bytes in "escaped"; an optional fcs; refin: LSB first header {"base": "header", "type": "link", "fields": [...], "crc": ..., "payload": "..."} fields, CRC and payload length of a frame's header, driven and published through a profile (see rpps.link.header)

Functions:

Name Description
root

Directory holding the encapsulation definitions

ls

List available definitions: {category: [names]}

load

Load a link definition by "/": load("crc/crc32_mpeg2"), load("frame/hdlc"), load("header/ble_adv")

root

root() -> Path

Directory holding the encapsulation definitions

Source code in src/rpps/link/serial.py
def root() -> Path:
    """Directory holding the encapsulation definitions"""
    return _config.find_config("crc")

ls

ls(path=None, blind=False)

List available definitions: {category: [names]}

blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)

Source code in src/rpps/link/serial.py
def ls(path=None, blind=False):
    """List available definitions: {category: [names]}

    blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)"""
    return {k: sorted(n for names in _config.ls(k, path, blind=blind).items() if k != "header" or names[0] == "link" for n in names[1])
            for k in KINDS}

load

load(ref: str, path=None, **params)

Load a link definition by "/": load("crc/crc32_mpeg2"), load("frame/hdlc"), load("header/ble_adv") (config//.json; a link header is config/header/link/.json), or below path. kind: crc | frame | header. A bare name works while one definition of the three kinds has it

Source code in src/rpps/link/serial.py
def load(ref: str, path=None, **params):
    """Load a link definition by "<kind>/<name>": `load("crc/crc32_mpeg2")`, `load("frame/hdlc")`, `load("header/ble_adv")`
    (config/<kind>/<name>.json; a link header is config/header/link/<name>.json), or below `path`. kind: crc | frame | header.
    A bare name works while one definition of the three kinds has it"""
    ref = str(ref).strip("/")
    kind, _, rest = ref.partition("/")
    kinds = [kind] if kind in KINDS and rest else list(KINDS)
    rest = rest if kind in KINDS and rest else ref
    hits = [(k, *_config.locate(k, rest, "link" if k == "header" else None, path)) for k in kinds]
    hits = [h for h in hits if h[1] is not None]
    if len(hits) > 1:
        raise ConfigError(f"{ref} is ambiguous: {[f'{k}/{rest}' for k, _, _ in hits]}")
    if not hits:
        raise FileNotFoundError(f"{ref}: no link definition (give <kind>/<name>, kind one of {KINDS}), have {ls(path)}")
    k, file, parts = hits[0]
    obj = _config.resolve(_config.read(file), params, f"{k}/{rest}")
    return _config.load_obj(k, parts[-1], obj)