Skip to content

Source

rpps.source

Signal sources and sinks: files, radios and memory (on pysdrlib), sockets, SigMF recordings, WAV, channels in shared memory (ShmSink; received with Device("shm@...")); and packets: pcapng for Wireshark, live or in a file (PcapSink, read back with Pcap), and a Linux TUN/TAP interface both ways (Tun)

Modules:

Name Description
formats

Sample file formats, as pysdrlib names them: a complex format is named by the bits of its I (or Q) alone, as in SigMF

net

Samples from the network: raw IQ over UDP or TCP, in any pysdrlib format

pcap

Packets to Wireshark: pcapng written to a file, a FIFO, stdout or a Windows named pipe, live (PcapSink); and read back

shm

Channels in shared memory: one process channelizes, others receive their channel (pysdrlib's shm streams)

sigmf

SigMF recordings: the samples and what they were recorded with (sigmf.org, the core namespace)

source

Sources and sinks of signal blocks

transmit

Transmitting with a radio: blocks of samples out of a pysdrlib device (DeviceSink)

tun

A Linux TUN/TAP interface, both ways: decoded packets onto it, packets written to it out to transmit

wav

WAV files in and out (the stdlib wave module: no dependency)

formats

Sample file formats, as pysdrlib names them: a complex format is named by the bits of its I (or Q) alone, as in SigMF

ci8t ci16t ci32t   complex two's complement integers (8, 16 and 32 bit I and Q)
cf16 cf32 cf64     complex floats (cf32 is two float32: numpy's complex64; cf64 is complex128)
i8t.. ui8.. f32..  real samples

rp.source.formats.ls() lists them.

Functions:

Name Description
pysdrlib

The pysdrlib module, refused (ImportError) when it is older than NEED

ls

The format names pysdrlib knows

get

A pysdrlib Formats member from its name (or a member)

pysdrlib

pysdrlib()

The pysdrlib module, refused (ImportError) when it is older than NEED

Source code in src/rpps/source/formats.py
def pysdrlib():
    """The pysdrlib module, refused (ImportError) when it is older than NEED"""
    import pysdrlib as lib
    have = tuple(int(p) for p in lib.__version__.split(".")[:2] if p.isdigit())
    if have < NEED:
        raise ImportError(f"rpps needs pysdrlib >= {'.'.join(map(str, NEED))}, this is {lib.__version__} ({lib.__file__}): "
                          f"its format names differ, so samples would be misread. pip install -U pysdrlib")
    return lib

ls

ls()

The format names pysdrlib knows

Source code in src/rpps/source/formats.py
def ls():
    """The format names pysdrlib knows"""
    return pysdrlib().Formats.ls()

get

get(fmt)

A pysdrlib Formats member from its name (or a member)

Source code in src/rpps/source/formats.py
def get(fmt):
    """A pysdrlib Formats member from its name (or a member)"""
    Formats = pysdrlib().Formats
    if isinstance(fmt, Formats):
        return fmt
    try:
        return Formats[fmt]
    except KeyError:
        raise ValueError(f"Unknown format {fmt!r}, have {ls()}") from None

net

Samples from the network: raw IQ over UDP or TCP, in any pysdrlib format

src = rp.source.Socket("cf32", "udp://0.0.0.0:5004", Fs=2e6, cf=100e6)       # listen for datagrams
src = rp.source.Socket("cui8", "tcp://10.0.0.5:1234", Fs=2.4e6)             # connect and read a byte stream
for out in src(16384) + rx:
    ...

The bytes are cut into whole samples whatever the datagrams or reads hold (a sample split across two keeps its first part until the rest comes), so the blocks are the same however the network delivers them. TCP ends when the far side closes (the last block flushes the stream); UDP when timeout seconds pass with nothing received (None: never).

Classes:

Name Description
Socket

Raw samples from url: udp://host:port (bound and listened on) or tcp://host:port (connected to)

Socket

Socket(fmt, url, Fs=1.0, cf=0.0, sps=0.0, scale=True, timeout=None, chunk=1 << 16)

Bases: Source

Raw samples from url: udp://host:port (bound and listened on) or tcp://host:port (connected to)

fmt: pysdrlib format of the samples; scale: integer formats become floats in [-1, 1), as File's do. timeout: seconds of silence that end a UDP stream (None: wait for ever); a TCP stream ends when it is closed

Methods:

Name Description
decode

Whole samples of raw bytes (as an array) and the bytes left over

Source code in src/rpps/source/net.py
def __init__(self, fmt, url, Fs=1.0, cf=0.0, sps=0.0, scale=True, timeout=None, chunk=1 << 16):
    super().__init__(Fs, cf, sps)
    u = urlparse(url)
    if u.scheme not in ("udp", "tcp") or u.port is None:
        raise ValueError(f"Socket: {url!r} is not udp://host:port or tcp://host:port")
    self.url, self.proto, self.addr = url, u.scheme, (u.hostname or "0.0.0.0", u.port)
    self.fmt = fmts.get(fmt)
    self.scale = (1.0/self.fmt.full_scale) if (scale and self.fmt.integer) else 1.0
    self.timeout, self.chunk = timeout, int(chunk)
decode
decode(raw)

Whole samples of raw bytes (as an array) and the bytes left over

Source code in src/rpps/source/net.py
def decode(self, raw):
    """Whole samples of `raw` bytes (as an array) and the bytes left over"""
    size = self.fmt.bytes
    n = len(raw)//size
    x = self.fmt.read(io.BytesIO(raw[:n*size]), n) if n else np.zeros(0, np.complex64)
    x = np.asarray(x)
    return (x*self.scale if self.scale != 1.0 else x), raw[n*size:]

pcap

Packets to Wireshark: pcapng written to a file, a FIFO, stdout or a Windows named pipe, live (PcapSink); and read back (Pcap)

rx, caps = p.rx(), p.capture                                    # a profile's capture rules (rpps.link.capture)
with rp.source.PcapSink("-") as sink:                            # rpps rx ... --pcap - | wireshark -k -i -
    for block in src(65536):
        rx(block)
        caps.packets(rx.take_messages()) >> sink                 # (a list of Packets: each written)

Targets: a path (a file, or a FIFO made with mkfifo: opening waits for Wireshark), "-" for stdout, a file object, or "pipe:" on Windows: a named pipe server, \\.\pipe\<name>, that waits for wireshark -k -i \\.\pipe\<name>. Every packet is flushed as it is written, so a live view keeps up.

Each (profile, kind, link type) is an interface of its own (named rpps:<profile>:<kind>, described with its link type and frequency), so Wireshark's interface column and filters tell them apart. Each packet's comment says what it was (frame.comment contains "FAILED"): profile and kind, the check and its verdict, frequency, quality, sample, fields; a failed check also sets the packet's CRC-error flag (frame.packet_flags_crc_error == 1).

rpps: every packet wrapped in RPPS's own header on LINKTYPE_USER0, which tools/wireshark/rpps.lua shows as fields to filter on (rpps.crc_ok == 0, rpps.profile == "ble/adv", rpps.field.type) before handing the packet to its link type's dissector. clock: "message" stamps a packet with its message's time (the source's, else seconds from the start of the stream), "wall" with the time it is written.

Classes:

Name Description
PcapSink

Write packets (rpps.link.capture.Packet) as pcapng: packets >> sink, packet >> sink, sink.write(...)

Record

A packet read from a capture: dlt (its link type's number), data, time (seconds), comment, flags, interface

Pcap

Packets of a pcapng or pcap capture, in order: for rec in rp.source.Pcap(path) (Records). source: a path, bytes,

Functions:

Name Description
rpps_header

RPPS's header for a Packet: TLVs (type 1 byte, length 2 bytes big endian), then the packet's bytes

PcapSink

PcapSink(target, rpps=False, clock='message')

Write packets (rpps.link.capture.Packet) as pcapng: packets >> sink, packet >> sink, sink.write(...)

target: a path or FIFO, "-" (stdout), a file object, or "pipe:" (a Windows named pipe; see module). rpps: wrap every packet in RPPS's header (LINKTYPE_USER0, for tools/wireshark/rpps.lua). clock: "message" or "wall". count: packets written; per: {interface name: packets}

Methods:

Name Description
write

Write a Packet or an iterable of them (None items skipped); returns the sink

Source code in src/rpps/source/pcap.py
def __init__(self, target, rpps=False, clock="message"):
    if clock not in ("message", "wall"):
        raise ValueError(f"PcapSink: clock is \"message\" or \"wall\", not {clock!r}")
    self.rpps, self.clock = bool(rpps), clock
    self._own = True
    if hasattr(target, "write"):
        self.f, self._own = target, False
    elif target == "-":
        self.f, self._own = sys.stdout.buffer, False
    elif isinstance(target, str) and target.startswith("pipe:"):
        self.f = _windows_pipe(target[5:])
    else:
        self.f = open(Path(target), "wb", buffering=0)
    self.target = target
    self._ifs = {} # (profile, kind, dlt) -> interface id
    self.count, self.per = 0, {}
    self._put(shb())
write
write(packets)

Write a Packet or an iterable of them (None items skipped); returns the sink

Source code in src/rpps/source/pcap.py
def write(self, packets):
    """Write a Packet or an iterable of them (None items skipped); returns the sink"""
    from ..link.capture import Packet
    for p in ([packets] if isinstance(packets, Packet) else packets):
        if p is None:
            continue
        data, dlt = (rpps_header(p), USER0) if self.rpps else (p.data, p.linktype.dlt)
        i = self._interface(p, dlt)
        t = _time.time() if self.clock == "wall" or p.time is None else p.time
        flags = FLAG_INBOUND | (FLAG_CRC_ERROR if p.crc_ok is False else 0)
        self._put(epb(i, t, data, p.comment(), flags))
        self.count += 1
        self.per[f"rpps:{p.profile}:{p.kind}"] += 1
    return self

Record

Record(dlt, data, time, comment=None, flags=0, interface=0)

A packet read from a capture: dlt (its link type's number), data, time (seconds), comment, flags, interface

Source code in src/rpps/source/pcap.py
def __init__(self, dlt, data, time, comment=None, flags=0, interface=0):
    self.dlt, self.data, self.time, self.comment, self.flags, self.interface = dlt, data, time, comment, flags, interface

Pcap

Pcap(source)

Packets of a pcapng or pcap capture, in order: for rec in rp.source.Pcap(path) (Records). source: a path, bytes, or a file object. A FIFO is read as it is written. interfaces: [(dlt, name)] of a pcapng's interfaces seen so far

Source code in src/rpps/source/pcap.py
def __init__(self, source):
    self.source = source
    self.interfaces = []

rpps_header

rpps_header(p)

RPPS's header for a Packet: TLVs (type 1 byte, length 2 bytes big endian), then the packet's bytes

Source code in src/rpps/source/pcap.py
def rpps_header(p):
    """RPPS's header for a Packet: TLVs (type 1 byte, length 2 bytes big endian), then the packet's bytes"""
    from ..link.capture import _quality, _text
    def tlv(t, v):
        return struct.pack(">BH", t, len(v)) + v
    out = tlv(T_PROFILE, p.profile.encode()) + tlv(T_KIND, str(p.kind).encode())
    if p.check:
        out += tlv(T_CHECK, p.check.encode())
    out += tlv(T_CRC_OK, bytes([{True: 1, False: 0, None: 2}[p.crc_ok]]))
    out += tlv(T_SAMPLE, struct.pack(">q", int(p.sample)))
    if p.time is not None:
        out += tlv(T_TIME, struct.pack(">d", float(p.time)))
    if p.freq:
        out += tlv(T_FREQ, struct.pack(">d", float(p.freq)))
    q = _quality(p.quality)
    if q is not None:
        out += tlv(T_QUALITY, struct.pack(">d", q))
    out += tlv(T_DLT, struct.pack(">H", p.linktype.dlt))
    if p.linktype.dissector:
        out += tlv(T_DISSECTOR, p.linktype.dissector.encode())
    if p.fields:
        out += tlv(T_FIELDS, json.dumps({k: _text(v) for k, v in p.fields.items()}).encode())
    return RPPS_MAGIC + struct.pack(">BH", RPPS_VERSION, 7 + len(out)) + out + p.data

shm

Channels in shared memory: one process channelizes, others receive their channel (pysdrlib's shm streams)

wide = rp.source.Device("hackrf", cf=915e6, Fs=20e6)(65536)
wide + rp.signal.filters.Channelizer(8) >> rp.source.ShmSink([f"ch{k}" for k in range(8)])   # one process
for blk in rp.source.Device("shm@rpps.ch3")(8192) + rx: ...                                     # any other

A process that runs several demodulators does the wideband work once and publishes each channel; each demodulator is a process of its own, receiving at its own pace (the GIL is not shared, a crash is its own). Any number of receivers can take one channel: a decoder and a live view (pyspecan) alike, and pysdrlib.find() lists them.

The streams, their rings and manifests are pysdrlib's (pysdrlib.shm.ShmStream, which owns the format): a channel is received as a pysdrlib device, rp.source.Device("shm@<namespace>.<name>"), with positions true to time (a gap upstream is a gap there, a receiver that falls behind counts what it missed in stream.dropped), a retune starting the stream over, and the end of the publisher ending the blocks.

Classes:

Name Description
ShmSink

Publish blocks to shared memory, for other processes: block >> sink, blocks >> sink

ShmSink

ShmSink(name, namespace='rpps', capacity=None, labels=None, profile=None, bw=None, directory=None)

Publish blocks to shared memory, for other processes: block >> sink, blocks >> sink

name: the channel's name, or one per column of a channelized block (Channelizer output, (time, M)): column k is the channel centred on cf + k Fs (above half the channels, the negative frequencies), at the block's rate. Each is published as <namespace>.<name> (namespace None: the bare name). capacity: samples a ring holds (None: pysdrlib's default, a second); a receiver more than that behind is moved on. labels: {name: text} for a view; profile: the profile that decodes these, if any; bw: a channel's usable width [Hz] (None: its rate; a critically sampled channelizer's flat passband is a little under it). directory: where the manifests go (pysdrlib's default: $PYSDRLIB_SHM_DIR). Close it (or use with) to end the streams.

A block's meta.pos is where it goes in its stream, so a gap upstream stays a gap. A change of rate or centre, or a stream that starts over, is a retune: a new generation, which receivers follow.

Source code in src/rpps/source/shm.py
def __init__(self, name, namespace="rpps", capacity=None, labels=None, profile=None, bw=None, directory=None):
    self.names = [name] if isinstance(name, str) else list(name)
    self.full = {n: f"{namespace}.{n}" if namespace else n for n in self.names}
    self.capacity, self.labels, self.profile, self.bw, self.dir = capacity, dict(labels or {}), profile, bw, directory
    self._out = {} # name -> [ShmStream, (Fs, cf), pos of the generation's first sample, the Stream's gen]
    self.count = 0

sigmf

SigMF recordings: the samples and what they were recorded with (sigmf.org, the core namespace)

src = rp.source.SigMF("capture.sigmf-meta")          # or the .sigmf-data path: Fs, cf and the format from the metadata
for out in src(65536) + rx: ...
src.annotations                                        # [{"core:sample_start": ..., "core:label": ...}, ...]

with rp.source.SigMFSink("out", Fs=2e6, cf=915e6, datatype="cf32_le") as sink:
    blocks >> sink                                     # out.sigmf-data, and out.sigmf-meta when it is closed

Datatypes: complex or real, float (f32, f64) or integer (i8, i16, i32, u8, u16, u32), little or big endian ("cf32_le", "ci16_be", "ri8"). Integers are scaled to [-1, 1) as File's are. Blocks start at the recording's core:sample_start of its first capture; a capture's core:frequency sets cf (the first; later captures are listed in captures). numpy and json only: no sigmf package needed. How the radio received (pysdrlib's pysdrlib:rx: the chain and its LO, whether it inverts, the reference) is the source's context (see rp.source.Source: an inverting chain is undone as the samples are read).

Classes:

Name Description
SigMF

A SigMF recording (the -meta or -data path, or their stem): Fs, cf and the datatype from its metadata

SigMFSink

Blocks written as a SigMF recording: path.sigmf-data as they come, path.sigmf-meta when closed

Functions:

Name Description
dtype_of

numpy dtype of the real components, and whether samples are complex, from a SigMF core:datatype

SigMF

SigMF(path, sps=0.0, scale=True, correct=True)

Bases: Source

A SigMF recording (the -meta or -data path, or their stem): Fs, cf and the datatype from its metadata

The data file stays memory mapped until close() (or the end of a with block): close it before the file is deleted or overwritten, which Windows refuses while it is mapped

Methods:

Name Description
close

Unmap the data file. Windows can't delete or replace a file while it is mapped; reading again maps it again

Attributes:

Name Type Description
data

The recording's raw values, memory mapped (mapped again if the source was closed)

Source code in src/rpps/source/sigmf.py
def __init__(self, path, sps=0.0, scale=True, correct=True):
    self.meta_path, self.data_path = _paths(path)
    self.meta = json.loads(self.meta_path.read_text())
    g = self.meta.get("global", {})
    self.captures = self.meta.get("captures", [])
    self.annotations = self.meta.get("annotations", [])
    first = self.captures[0] if self.captures else {}
    super().__init__(float(g.get("core:sample_rate", 1.0)), float(first.get("core:frequency", 0.0)), sps,
                     context=_context(g), correct=correct)
    self.datatype = g["core:datatype"]
    self.dtype, self.complex = dtype_of(self.datatype)
    self.scale = (1.0/float(2**(8*self.dtype.itemsize - 1))) if (scale and self.dtype.kind in "iu") else 1.0
    self.start = int(first.get("core:sample_start", 0))
    self._map = None
    self.open()
data property
data

The recording's raw values, memory mapped (mapped again if the source was closed)

close
close()

Unmap the data file. Windows can't delete or replace a file while it is mapped; reading again maps it again

Source code in src/rpps/source/sigmf.py
def close(self):
    """Unmap the data file. Windows can't delete or replace a file while it is mapped; reading again maps it again"""
    self._map = None # The blocks are copies, so this was the only reference

SigMFSink

SigMFSink(path, Fs=None, cf=None, datatype='cf32_le', description=None, annotations=(), context=None)

Blocks written as a SigMF recording: path.sigmf-data as they come, path.sigmf-meta when closed

datatype: the SigMF core:datatype written ("cf32_le" default; integer types are scaled from [-1, 1) and clipped). Fs, cf: the recording's; else the first block's. annotations: added to the metadata. context: how the samples were received (a pysdrlib RxContext, kept as pysdrlib:rx); else the first block's stream's (stream.rx), marked undone when its source conjugated them

Source code in src/rpps/source/sigmf.py
def __init__(self, path, Fs=None, cf=None, datatype="cf32_le", description=None, annotations=(), context=None):
    self.meta_path, self.data_path = _paths(path)
    self.datatype, self.Fs, self.cf, self.description = datatype, Fs, cf, description
    self.context = context
    self.dtype, self.complex = dtype_of(datatype)
    self.annotations = list(annotations)
    self.count = 0
    self._f = open(self.data_path, "wb")

dtype_of

dtype_of(datatype)

numpy dtype of the real components, and whether samples are complex, from a SigMF core:datatype

Source code in src/rpps/source/sigmf.py
def dtype_of(datatype):
    """numpy dtype of the real components, and whether samples are complex, from a SigMF core:datatype"""
    d = datatype.lower()
    cplx = d.startswith("c")
    if not (cplx or d.startswith("r")):
        raise ValueError(f"SigMF datatype {datatype!r}: starts with c (complex) or r (real)")
    body, _, endian = d[1:].partition("_")
    kind, bits = body[0], int(body[1:])
    if kind not in "fiu" or bits not in (8, 16, 32, 64) or (kind == "f" and bits not in (32, 64)):
        raise ValueError(f"SigMF datatype {datatype!r}: not a supported type")
    order = "<" if endian in ("", "le") else ">" if endian == "be" else None
    if order is None:
        raise ValueError(f"SigMF datatype {datatype!r}: endianness le or be")
    return np.dtype(f"{order}{kind}{bits//8}"), cplx

source

Sources and sinks of signal blocks

src = rp.source.File("ci16t", "capture.cs16", Fs=2e6, cf=100e6)
for out in src(4096) + (lpf + dec):          # blocks flow through the pipeline, its state carried along
    ...
src(4096) + (lpf + dec) >> rp.source.Sink("cf32", "out.iq")   # or straight into a sink

Threads: .threaded() puts everything before it in its own thread, and .pipelined(pipe) gives every stage of a pipeline its own, connected by bounded queues. Stages overlap where they release the GIL (numpy, the rpps._native kernels), and a radio is drained while the stages work:

src(16384).threaded(drop=True).pipelined(agc + timing + carrier) >> sink

Classes:

Name Description
Blocks

Blocks of a stream. The operators apply to every block as it is produced, with state carried between them

Source

Parent of the things that produce blocks. Call it with a block length for the blocks

File

Samples from a file, in blocks (a short last block is delivered, flushing the stream)

Memory

Samples held in memory, in blocks (a short last block flushes the stream): what was captured from a device, for

Device

Samples from a pysdrlib device (RTL-SDR, HackRF, ..., "sim", or "remote"): blocks until the loop is left. A device

Sink

Write blocks to a file with pysdrlib's FileSink: block >> sink or blocks >> sink

Blocks

Blocks(gen)

Blocks of a stream. The operators apply to every block as it is produced, with state carried between them

blocks + stage      # DSP stage or pipeline (also blocks * pipe, blocks / pipe)
blocks >> sink      # write every block; returns the sink
blocks.threaded()   # everything so far runs in a thread of its own
blocks.pipelined(a + b + c) # a, b and c each in a thread of their own

A stage that splits a block (rp.sync.Burst: a list of bursts) gives its pieces one by one: what follows runs on each.

Methods:

Name Description
threaded

Run everything before this point (the source, the stages applied so far) in its own thread

pipelined

blocks + pipe, with every top-level stage of the pipe in its own thread (and the source in another). A

collect

All the output joined into one array

Source code in src/rpps/source/source.py
def __init__(self, gen):
    self._gen = gen
threaded
threaded(depth=8, drop=False)

Run everything before this point (the source, the stages applied so far) in its own thread

depth: blocks the queue to the next thread holds. drop: when the queue is full, discard the block and count it in stream.dropped (source samples) instead of waiting. Use for a radio, which overruns anyway when it isn't read; the stream then has gaps: the stages carry on, and the positions of what follows count the block (meta.pos stays true to time). An exception in the thread is raised where the blocks are read; leaving the loop stops the thread (and closes the source).

Source code in src/rpps/source/source.py
def threaded(self, depth=8, drop=False):
    """Run everything before this point (the source, the stages applied so far) in its own thread

    depth: blocks the queue to the next thread holds.
    drop: when the queue is full, discard the block and count it in `stream.dropped` (source samples) instead of
        waiting. Use for a radio, which overruns anyway when it isn't read; the stream then has gaps: the stages
        carry on, and the positions of what follows count the block (`meta.pos` stays true to time).
    An exception in the thread is raised where the blocks are read; leaving the loop stops the thread (and
    closes the source).
    """
    return Blocks(_threaded(self._gen, depth, drop, "rpps-blocks"))
pipelined
pipelined(pipe, depth=4)

blocks + pipe, with every top-level stage of the pipe in its own thread (and the source in another). A profile's receiver that branches runs its trunk in one and its branches in another (pipelined_parts)

Source code in src/rpps/source/source.py
def pipelined(self, pipe, depth=4):
    """blocks + pipe, with every top-level stage of the pipe in its own thread (and the source in another). A
    profile's receiver that branches runs its trunk in one and its branches in another (`pipelined_parts`)"""
    items = pipe.items if isinstance(pipe, base.Pipeline) else (pipe,)
    b = self.threaded(depth)
    for it in items:
        parts = it.pipelined_parts() if hasattr(it, "pipelined_parts") else (it,)
        for part in parts:
            b = (b + part).threaded(depth)
    return b
collect
collect()

All the output joined into one array

Source code in src/rpps/source/source.py
def collect(self):
    """All the output joined into one array"""
    try:
        parts = [np.asarray(b.data) for b in self._gen]
    finally:
        _close(self._gen)
    return np.concatenate(parts) if parts else np.zeros(0, dtype=np.complex64)

Source

Source(Fs=1.0, cf=0.0, sps=0.0, ppm=0.0, context=None, correct=True)

Parent of the things that produce blocks. Call it with a block length for the blocks

REP: the representation its blocks are (SAMPLES; a demodulator's ring of timed symbols is SYMBOLS), and APPLIED the sync it has done already ({"timing"}): profile.rx(source=src) skips the steps before and those (rpps.base, Contracts). ppm: how far the radio's reference is off (+15: its clock runs 15 ppm fast). The sample rate and the tuned frequency both come from it, so blocks carry Fs and cf times (1 + ppm 1e-6): what was actually sampled, and where. context: how the samples were received (a pysdrlib RxContext: Device.get_rx_context(), a SigMF recording's pysdrlib:rx; give one for a file that doesn't say), kept as stream.rx. A chain whose LO is above the signal (context.inverted: mirrored, and not undone by whoever wrote the samples) mirrors the spectrum: with correct (the default) the samples are conjugated here, every block and peek, so cf + f is over the air at f (conjugated; stream.rx_conjugated: put right, here or before). An inversion found later (rp.sync.Inversion) is then the transmitter's or a transponder's, not ours.

Methods:

Name Description
set_context

How the samples are received (see the class): a new one when the radio retunes or the chain changes

restart

Start the stream over: the stages that ran on it forget their state

peek

The first count samples as an array (not a block), without using them up: a File keeps its place

Attributes:

Name Type Description
conjugated

The samples come conjugated, putting right a chain that inverts the spectrum

Source code in src/rpps/source/source.py
def __init__(self, Fs=1.0, cf=0.0, sps=0.0, ppm=0.0, context=None, correct=True):
    self.Fs, self.cf, self.sps, self.ppm = Fs, cf, sps, ppm
    self.stream = Stream(Fs) # Shared by every block this source makes
    self.correct = bool(correct)
    self.set_context(context)
conjugated property
conjugated

The samples come conjugated, putting right a chain that inverts the spectrum

set_context
set_context(context)

How the samples are received (see the class): a new one when the radio retunes or the chain changes

Source code in src/rpps/source/source.py
def set_context(self, context):
    """How the samples are received (see the class): a new one when the radio retunes or the chain changes"""
    self.context = context
    self.stream.rx, self.stream.rx_conjugated = context, self.conjugated or bool(getattr(context, "undone", False))
restart
restart()

Start the stream over: the stages that ran on it forget their state

Source code in src/rpps/source/source.py
def restart(self):
    """Start the stream over: the stages that ran on it forget their state"""
    self.stream.restart()
peek
peek(count)

The first count samples as an array (not a block), without using them up: a File keeps its place

Source code in src/rpps/source/source.py
def peek(self, count):
    """The first `count` samples as an array (not a block), without using them up: a File keeps its place"""
    raise StreamError(f"{type(self).__name__} can't peek")

File

File(fmt, path, Fs=1.0, cf=0.0, sps=0.0, scale=True, context=None, correct=True)

Bases: Source

Samples from a file, in blocks (a short last block is delivered, flushing the stream)

fmt: pysdrlib format name (see rp.source.formats.ls()) Fs, cf, sps: what the capture was recorded with scale: integer formats become floats in [-1, 1), as a device's samples are context, correct: how it was received (a pysdrlib RxContext) and whether to undo an inverting chain (see Source)

Methods:

Name Description
peek

count samples from sample start (fewer near the end) as an array, leaving the read position where it was

read

The next count samples as an array (not a block)

Attributes:

Name Type Description
percent

Fraction of the file read [0, 1]

Source code in src/rpps/source/source.py
def __init__(self, fmt, path, Fs=1.0, cf=0.0, sps=0.0, scale=True, context=None, correct=True):
    super().__init__(Fs, cf, sps, context=context, correct=correct)
    self.fmt = fmts.get(fmt)
    pysdrlib = fmts.pysdrlib()
    self._f = pysdrlib.File(path, self.fmt.name, scale=scale)
    self.path = self._f.get_path()
percent property
percent

Fraction of the file read [0, 1]

peek
peek(count, start=0)

count samples from sample start (fewer near the end) as an array, leaving the read position where it was

Source code in src/rpps/source/source.py
def peek(self, count, start=0):
    """`count` samples from sample `start` (fewer near the end) as an array, leaving the read position where it was"""
    pos, was_open = self._f.cur_samp, self._f.f is not None
    self._f.seek(start)
    try:
        self.open()
        return self._writable(self._sense(self._f.next(int(count), partial=True)))
    finally:
        self._f.seek(pos)
        if not was_open:
            self.close()
read
read(count)

The next count samples as an array (not a block)

Source code in src/rpps/source/source.py
def read(self, count):
    """The next `count` samples as an array (not a block)"""
    self.open()
    return self._writable(self._sense(self._f.next(int(count))))

Memory

Memory(samples, Fs=1.0, cf=0.0, sps=0.0, context=None, correct=True)

Bases: Source

Samples held in memory, in blocks (a short last block flushes the stream): what was captured from a device, for analysis that runs slower than the device does (Memory.capture), or an array made some other way

Methods:

Name Description
peek

count samples from sample start (fewer near the end), as an array

capture

The next count samples of a source (a Device), held: blocks as they come, then nothing more is read. The

Source code in src/rpps/source/source.py
def __init__(self, samples, Fs=1.0, cf=0.0, sps=0.0, context=None, correct=True):
    super().__init__(Fs, cf, sps, context=context, correct=correct)
    self.samples = np.asarray(samples)
peek
peek(count, start=0)

count samples from sample start (fewer near the end), as an array

Source code in src/rpps/source/source.py
def peek(self, count, start=0):
    """`count` samples from sample `start` (fewer near the end), as an array"""
    return self._sense(self.samples[int(start):int(start) + int(count)].copy())
capture classmethod
capture(source, count, block=2 ** 16, skip=0)

The next count samples of a source (a Device), held: blocks as they come, then nothing more is read. The rate and centre are what the source settled on; dropped samples during the capture are in .dropped. skip: samples to read and throw away first (a radio just tuned can still deliver the old frequency for a while)

Source code in src/rpps/source/source.py
@classmethod
def capture(cls, source, count, block=2**16, skip=0):
    """The next `count` samples of a source (a Device), held: blocks as they come, then nothing more is read. The
    rate and centre are what the source settled on; dropped samples during the capture are in `.dropped`.
    skip: samples to read and throw away first (a radio just tuned can still deliver the old frequency for a while)"""
    out, n, thrown = [], 0, 0
    for blk in source(block):
        if thrown < skip:
            thrown += len(blk)
            continue
        out.append(np.asarray(blk.data))
        n += len(out[-1])
        if n >= count:
            break
    ctx = source.context
    if source.conjugated: # (its blocks came the right way round: the context says so)
        import dataclasses
        ctx = dataclasses.replace(ctx, undone=True)
    mem = cls(np.concatenate(out)[:count] if out else np.zeros(0, np.complex64), source.Fs, source.cf, source.sps,
              context=ctx, correct=source.correct)
    mem.dropped = int(getattr(source.stream, "dropped", 0))
    return mem

Device

Device(device, cf=None, Fs=None, rx_gain=None, sps=0.0, correct=True, **open_args)

Bases: Source

Samples from a pysdrlib device (RTL-SDR, HackRF, ..., "sim", or "remote"): blocks until the loop is left. A device that is open already (pysdrlib.connect gives one) stays open; one this opens is closed when the blocks end

for blk in rp.source.Device("hackrf", cf=100e6, Fs=10e6)(8192) + rx: ...

Positions and time come from the radio: samples it lost (an overrun) are counted in meta.pos, so a block after a gap starts further on and the stages carry the gap into theirs (one inside a block shows at the next block), and stream.dropped adds them up. The radio's get_rx_context() (its chain, reference, gains) is stream.rx; a chain that inverts the spectrum is undone here unless correct=False (see Source). stream.t0 is the radio's clock (hw_time) where it timestamps its samples, else the host's time.monotonic() at the first sample, so meta.time_of(k) dates any item.

When the device's frequency or rate changes while it streams (a "freq" / "rate" event: another program retuned it, a shared-memory publisher retuned), the block is cut there and the stream starts over (restart) at the new setting, positions counting from the change. When the device is lost (unplugged, a publisher that stopped: pysdrlib's err.Lost), the blocks end, the last one flushing, and lost says why.

device: a pysdrlib driver name ("hackrf"), a target string ("hackrf@SERIAL", "shm@rpps.ch3", "radiohost/hackrf-0": opened here by pysdrlib.open, closed by close() or when it is lost), or a device you made (rp.source.Device(pysdrlib.device("sim", realtime=False))). rx_gain: the receive gain as a fraction 0-1 of the device's range (the same on any radio), or a {stage: fraction} dict

Methods:

Name Description
peek

The first count samples from the device, as an array. A device can't rewind: these are not in the blocks

close

Close a device this opened from a target string (one opened by name is closed when its blocks end)

Source code in src/rpps/source/source.py
def __init__(self, device, cf=None, Fs=None, rx_gain=None, sps=0.0, correct=True, **open_args):
    """device: a pysdrlib driver name ("hackrf"), a target string ("hackrf@SERIAL", "shm@rpps.ch3",
    "radiohost/hackrf-0": opened here by `pysdrlib.open`, closed by `close()` or when it is lost), or a device you made
    (rp.source.Device(pysdrlib.device("sim", realtime=False))). rx_gain: the receive gain as a fraction 0-1 of the
    device's range (the same on any radio), or a {stage: fraction} dict"""
    self._opened, self.lost = False, None
    if isinstance(device, str):
        pysdrlib = fmts.pysdrlib()
        if "@" in device or "/" in device:
            device, open_args, self._opened = pysdrlib.open(device, **open_args), {}, True
        else:
            device = pysdrlib.device(device)
    self.sdr = device
    self.rx_gain = rx_gain
    self._open_args = open_args
    super().__init__(Fs if Fs is not None else self.sdr.get_rx_sample_rate(), cf if cf is not None else self.sdr.get_rx_freq(), sps,
                     correct=correct) # (the context once the radio is set up: `_samples`)
peek
peek(count)

The first count samples from the device, as an array. A device can't rewind: these are not in the blocks that follow (rp.analysis.survey keeps them in Survey.head)

Source code in src/rpps/source/source.py
def peek(self, count):
    """The first `count` samples from the device, as an array. A device can't rewind: these are not in the blocks
    that follow (rp.analysis.survey keeps them in Survey.head)"""
    for blk in self._samples(count):
        return np.asarray(blk.data)
close
close()

Close a device this opened from a target string (one opened by name is closed when its blocks end)

Source code in src/rpps/source/source.py
def close(self):
    """Close a device this opened from a target string (one opened by name is closed when its blocks end)"""
    if self._opened and self.sdr.state["open"]:
        self.sdr.close()

Sink

Sink(fmt, path, scale=True, append=False, clip=True)

Write blocks to a file with pysdrlib's FileSink: block >> sink or blocks >> sink

The file is opened when the sink is made. Use it as a context manager (or close()) to finish the file. scale: samples in [-1, 1) are stored at the format's full scale (FileSink's scale, the inverse of File's) clip: saturate what is out of range instead of failing (FileSink counts it in clipped and warns when closed)

Attributes:

Name Type Description
clipped

Samples that were saturated

Source code in src/rpps/source/source.py
def __init__(self, fmt, path, scale=True, append=False, clip=True):
    self.fmt = fmts.get(fmt)
    pysdrlib = fmts.pysdrlib()
    self._sink = pysdrlib.FileSink(path, self.fmt.name, append=append, open=True, clip=clip, scale=scale)
clipped property
clipped

Samples that were saturated

transmit

Transmitting with a radio: blocks of samples out of a pysdrlib device (DeviceSink)

with rp.source.DeviceSink("hackrf", cf=433.92e6, Fs=2e6, tx_gain=0.3) as radio:
    enc.packet(pkt) >> radio                          # rp.profile.Encoder: a packet's samples

The device starts transmitting when the sink is made and stops when it is closed; write queues samples (complex, full scale +-1) and blocks while the device's queue is full. A block's rate must be the sink's (be explicit: resample first, or make the sink at the block's rate). Receive with rp.source.Device.

Classes:

Name Description
DeviceSink

Transmit blocks with a pysdrlib device: block >> sink, blocks >> sink

DeviceSink

DeviceSink(device, cf=None, Fs=None, tx_gain=None, channel=0, scale=1.0, **open_args)

Transmit blocks with a pysdrlib device: block >> sink, blocks >> sink

device: a pysdrlib driver name ("hackrf"), a target string ("hackrf@SERIAL", "radiohost/hackrf-0": opened here, closed by close()), or a device you made (left open). cf, Fs: the transmit frequency and rate (None: the device's own). tx_gain: the transmit gain as a fraction 0-1 of the device's range. channel: the transmit channel. scale: multiplies the samples (headroom: clipping at +-1 is the radio's). count: samples queued

Methods:

Name Description
write

Queue a block (rp.Data at the sink's rate, or an array) for transmission; returns the sink

Source code in src/rpps/source/transmit.py
def __init__(self, device, cf=None, Fs=None, tx_gain=None, channel=0, scale=1.0, **open_args):
    self._opened = False
    if isinstance(device, str):
        pysdrlib = fmts.pysdrlib()
        if "@" in device or "/" in device:
            device, open_args, self._opened = pysdrlib.open(device, **open_args), {}, True
        else:
            device = pysdrlib.device(device)
    self.sdr, self.channel, self.scale = device, channel, float(scale)
    if not self.sdr.state["open"]:
        self.sdr.open(**open_args)
        self._opened = True
    caps = getattr(self.sdr, "caps", None) # (what the device can do as opened: a sim made with transmit=True can)
    if not (caps.channels.get("tx") if caps is not None else getattr(self.sdr, "CAN_TRANSMIT", True)):
        name = getattr(type(self.sdr), "NAME", type(self.sdr).__name__)
        self.close()
        raise ValueError(f"DeviceSink: {name} can't transmit")
    if cf is not None:
        self.sdr.set_tx_freq(cf, channel=channel)
    if Fs is not None:
        self.sdr.set_tx_sample_rate(Fs, channel=channel)
    if tx_gain is not None:
        self.sdr.set_tx_gain(tx_gain, channel=channel)
    self.cf, self.Fs = self.sdr.get_tx_freq(channel=channel), self.sdr.get_tx_sample_rate(channel=channel)
    self.sdr.start_tx([channel])
    self.count = 0
write
write(data)

Queue a block (rp.Data at the sink's rate, or an array) for transmission; returns the sink

Source code in src/rpps/source/transmit.py
def write(self, data):
    """Queue a block (rp.Data at the sink's rate, or an array) for transmission; returns the sink"""
    if isinstance(data, base.data._Data):
        Fs = data.meta.Fs
        if Fs and self.Fs and abs(Fs - self.Fs) > 1e-6*self.Fs:
            raise ValueError(f"DeviceSink: a block at {Fs:g} Hz, the device transmits at {self.Fs:g} Hz (resample first)")
        data = data.data
    x = np.asarray(data, dtype=np.complex64)
    if self.scale != 1.0:
        x = x*np.float32(self.scale)
    if len(x):
        self.sdr.write(x, channel=self.channel)
        self.count += len(x)
    return self

tun

A Linux TUN/TAP interface, both ways: decoded packets onto it, packets written to it out to transmit

tun = rp.source.Tun("rpps0")                                       # raw IP (a TUN): IPv4 and IPv6 packets
tun = rp.source.Tun("rpps1", linktype="ieee802_15_4_nofcs")        # a TUN of another link type (TUNSETLINK)
tun = rp.source.Tun("rpps2", mode="tap")                           # Ethernet frames (a TAP)
p.capture.packets(rx.take_messages()) >> tun                         # receive: each packet of its link type
for pkt in tun.packets(timeout=1.0): ...                             # transmit: what the system sends on it

Wireshark (or tcpdump) on the interface sees the packets as the system does, of the interface's link type. A TUN is raw IP; on Linux it can take another link type (Linux's ARPHRD: 802.11, 802.11 with radiotap, 802.15.4 without FCS, AX.25 with its KISS byte), set while the interface is down, and then each packet carries packet information (its protocol, the link type's proto) since the kernel takes a TUN's packets without it for IP only. A TAP is Ethernet. A packet of a link type that is the interface's with transforms (config/linktype "from": 802.15.4 with its FCS on an 802.15.4 interface, which has none; AX.25 on Linux's AX.25 with its KISS byte) is converted; other packets are not written (counted in skipped): a pcapng stream (rpps.source.PcapSink) carries any link type, and what each packet was.

Making the interface needs CAP_NET_ADMIN once; a persistent interface owned by the user is opened without it:

sudo ip tuntap add dev rpps0 mode tun user $USER        # (mode tap for a TAP)
sudo ip link set rpps0 up                               # (after the link type is set: Tun sets it while it is down)

up: bring the interface up when opened (True: or fail; None: try, and leave it to ip link set up without the right to). Linux only: on Windows and macOS use a pcapng pipe (PcapSink("pipe:<name>"), a FIFO, or stdout).

Classes:

Name Description
Tun

A TUN or TAP interface (see module). name: the interface; mode: "tun" or "tap"; linktype: a TUN's link type

Tun

Tun(name, mode='tun', linktype=None, up=None)

A TUN or TAP interface (see module). name: the interface; mode: "tun" or "tap"; linktype: a TUN's link type (config/linktype: "raw" by default; one with an arphrd), a TAP's is "ethernet". count: packets written; skipped: packets of another link type, by its name

Methods:

Name Description
set_up

Bring the interface up (or down); needs CAP_NET_ADMIN

write

Write a Packet (rpps.link.capture), bytes (of the interface's link type), or an iterable of them; returns self

packets

The packets the system sends on the interface, as bytes of its link type, until timeout seconds pass with none

Source code in src/rpps/source/tun.py
def __init__(self, name, mode="tun", linktype=None, up=None):
    if not sys.platform.startswith("linux"):
        raise OSError("Tun: TUN/TAP interfaces are Linux's here; write a pcapng stream instead "
                      "(rp.source.PcapSink(\"pipe:<name>\") on Windows, a FIFO or \"-\" elsewhere)")
    from ..link.capture import linktype as _linktype
    if mode not in ("tun", "tap"):
        raise ConfigError(f"Tun {name}: mode is \"tun\" or \"tap\", not {mode!r}")
    lt = _linktype(linktype or ("raw" if mode == "tun" else "ethernet"))
    if mode == "tap" and lt.name != "ethernet":
        raise ConfigError(f"Tun {name}: a TAP carries Ethernet frames, not {lt.name} (make a TUN of that link type)")
    if mode == "tun" and lt.name not in RAW_IP and (lt.arphrd is None or lt.proto is None):
        raise ConfigError(f"Tun {name}: Linux has no interface type for {lt.name}; a TUN takes raw IP or one of the link "
                          "types with an `arphrd` and a `proto` (config/linktype); write a pcapng stream for the rest")
    self.name, self.mode, self.linktype = name, mode, lt
    self.pi = mode == "tun" and lt.name not in RAW_IP # (packet information: the protocol of a non-IP packet)
    flags = (IFF_TUN if mode == "tun" else IFF_TAP) | (0 if self.pi else IFF_NO_PI)
    self.fd = os.open("/dev/net/tun", os.O_RDWR)
    try:
        import fcntl
        fcntl.ioctl(self.fd, TUNSETIFF, struct.pack("16sH", name.encode(), flags))
        if self.pi:
            try:
                fcntl.ioctl(self.fd, TUNSETLINK, lt.arphrd)
            except OSError as e:
                if e.errno == errno.EBUSY:
                    raise OSError(f"Tun {name}: its link type is set while it is down: ip link set {name} down") from e
                raise
    except BaseException:
        os.close(self.fd)
        raise
    self.count, self.skipped = 0, {}
    if up is not False:
        try:
            self.set_up(True)
        except PermissionError:
            if up:
                raise
            from ..logger import Logger
            Logger().Child("Tun").warn(f"{name}: not brought up (no CAP_NET_ADMIN): sudo ip link set {name} up")
set_up
set_up(on=True)

Bring the interface up (or down); needs CAP_NET_ADMIN

Source code in src/rpps/source/tun.py
def set_up(self, on=True):
    """Bring the interface up (or down); needs CAP_NET_ADMIN"""
    import fcntl
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        req = struct.pack("16sH", self.name.encode(), 0)
        got = struct.unpack("16sH", fcntl.ioctl(s, SIOCGIFFLAGS, req + bytes(22))[:18])[1]
        new = (got | IFF_UP) if on else (got & ~IFF_UP)
        fcntl.ioctl(s, SIOCSIFFLAGS, struct.pack("16sH", self.name.encode(), new) + bytes(22))
write
write(packets)

Write a Packet (rpps.link.capture), bytes (of the interface's link type), or an iterable of them; returns self

Source code in src/rpps/source/tun.py
def write(self, packets):
    """Write a Packet (rpps.link.capture), bytes (of the interface's link type), or an iterable of them; returns self"""
    from ..link.capture import Packet, convert
    items = [packets] if isinstance(packets, (Packet, bytes, bytearray)) else packets
    for p in items:
        if p is None:
            continue
        if isinstance(p, Packet):
            data = p.data
            if not self._carries(p.linktype):
                try: # A link type that is this one with transforms (802.15.4 with its FCS): converted
                    data = convert(data, p.linktype, self.linktype)
                except ValueError:
                    self.skipped[p.linktype.name] = self.skipped.get(p.linktype.name, 0) + 1
                    continue
        else:
            data = bytes(p)
        if self.pi:
            data = struct.pack("!HH", 0, self.linktype.proto) + data
        os.write(self.fd, data)
        self.count += 1
    return self
packets
packets(timeout=None)

The packets the system sends on the interface, as bytes of its link type, until timeout seconds pass with none (None: for ever) or it is closed

Source code in src/rpps/source/tun.py
def packets(self, timeout=None):
    """The packets the system sends on the interface, as bytes of its link type, until `timeout` seconds pass with none
    (None: for ever) or it is closed"""
    while self.fd is not None:
        r, _, _ = select.select([self.fd], [], [], timeout)
        if not r:
            return
        try:
            data = os.read(self.fd, 1 << 16)
        except OSError as e:
            if e.errno in (errno.EBADF, errno.EIO):
                return
            raise
        yield data[4:] if self.pi else data

wav

WAV files in and out (the stdlib wave module: no dependency)

rp.source.write_wav("out.wav", audio, 48000, peak=0.8) # an array at once, scaled so its peak is 0.8 of full scale blocks + demod >> rp.source.WavSink("out.wav") # a stream, at the blocks' own rate for blk in rp.source.Wav("sdr.wav", iq=True)(4096): ... # in: 8/16/32-bit PCM; a 2-channel IQ recording as samples

Classes:

Name Description
WavSink

A 16-bit WAV file written block by block: block >> sink or blocks >> sink. Samples in [-1, 1) (clipped).

Wav

A PCM WAV file as a source, scaled to [-1, 1): one channel gives real samples (audio); two give I and Q

Functions:

Name Description
write_wav

Write audio (frames, or (frames, channels)) as a 16-bit WAV at rate Hz. peak: normalise to that fraction of full scale

WavSink

WavSink(path, rate=None, channels=1)

A 16-bit WAV file written block by block: block >> sink or blocks >> sink. Samples in [-1, 1) (clipped). rate: Hz, else the first block's Fs. channels: 1, or 2 for blocks of (frames, 2). Close it (or use with) to finish

Source code in src/rpps/source/wav.py
def __init__(self, path, rate=None, channels=1):
    self.path, self.rate, self.channels = str(path), rate, int(channels)
    self.count = 0
    self._w = None

Wav

Wav(path, iq=None, cf=0.0)

Bases: Source

A PCM WAV file as a source, scaled to [-1, 1): one channel gives real samples (audio); two give I and Q (iq=True: an SDR's IQ recording) or, with iq=False, the first channel. Fs is the file's rate

Source code in src/rpps/source/wav.py
def __init__(self, path, iq=None, cf=0.0):
    self.path = str(path)
    with wave.open(self.path, "rb") as w:
        self.channels, self.width, rate, self.frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
    if self.width not in (1, 2, 4):
        raise ValueError(f"{path}: {8*self.width}-bit samples (8, 16 or 32-bit PCM)")
    self.iq = self.channels == 2 if iq is None else bool(iq)
    if self.iq and self.channels != 2:
        raise ValueError(f"{path}: IQ needs 2 channels, it has {self.channels}")
    super().__init__(float(rate), cf)

write_wav

write_wav(path, x, rate, peak=None)

Write audio (frames, or (frames, channels)) as a 16-bit WAV at rate Hz. peak: normalise to that fraction of full scale

Source code in src/rpps/source/wav.py
def write_wav(path, x, rate, peak=None):
    """Write audio (frames, or (frames, channels)) as a 16-bit WAV at `rate` Hz. peak: normalise to that fraction of full scale"""
    y = _pcm(x, peak)
    with wave.open(str(path), "wb") as w:
        w.setnchannels(1 if y.ndim == 1 else y.shape[1])
        w.setsampwidth(2)
        w.setframerate(int(round(rate)))
        w.writeframes(y.tobytes())
    return len(y)