Skip to content

Remote

pysdrlib.remote

Radios hosted on one machine and used from another, over ZeroMQ (pip install pysdrlib[remote]).

A remote device is a normal pysdrlib.Device (RemoteDevice), so code written for a local radio works unchanged. sdr.caps comes from the hosted device, and every control (set_rx_gain, set_rx_bandwidth, set_setting, a driver's own setters such as set_rx_lna_gain...) is forwarded to it. Channels, transmit, read(meta=True) gaps and stream() work as they do locally, and so do retunes: m.events marks a change inside a block, m.freq is the frequency the block was received at, and set_rx_freq(f, flush=True) skips what came before (viewers see the controller's changes the same way).

How to run a server, connect, find servers, share and relay a radio, and the pysdrlib server/relay/client/discover command line: the Remote radios guide. This page is the reference for what those do.

Finding servers

A server can announce itself on the local network (mDNS / DNS-SD, as _pysdrlib._tcp, with --advertise), so clients find it without being told its address: discover() lists the servers announcing themselves. connect with no address asks every server it finds which of its radios fit, without opening any, and connects to the best:

  • Radios are compared across servers as one server compares its own (see Saying who you are and what you need): what fits need, nearest want, the antenna best for the frequency, one attached before one a client left open. Of equals, a server on this machine wins (samples come through shared memory).
  • Every fitting radio of every server is put in one order, and connect opens exactly the radio it ranked (the open names it, pick=): if someone took it in the meantime, the server says Busy rather than opening its next best in its place, and the next radio in the order is tried, on whichever server it is. A radio that fails to open is passed over the same way; err.NoDevice says why each was left out.
  • discover_timeout= (default 2 s) is how long it listens for servers. A server too old to be asked is tried last, as is one that can open the device type asked for but has none attached (sim, say).
  • The announcement says only where a server is, its protocol and pysdrlib version, and whether it is a server or a relay (pysdrlib relay --advertise). What it has is asked of the server itself, so it is never out of date.
  • A server bound to every interface (0.0.0.0) announces each of its addresses; address is one on a network the client is on, addresses all of them. A server on 127.0.0.1 or ipc:// cannot be advertised (--advertise says so).
  • Servers of another protocol version are left out (--all-versions / all_versions=True shows them).
  • mDNS stays on the local network: a server across a router or a VPN still has to be given by address. Advertising is off unless asked for; it makes a server easier to find, not easier to use (see Security). avahi-browse -rt _pysdrlib._tcp sees the same announcements.

Controllers and viewers

A hosted device has at most one controller and any number of viewers.

Controller Viewer
Receive samples yes yes
get_* calls yes yes
Change settings, start/stop, transmit yes no
  • Connecting to a device type (pysdrlib.connect(addr, "hackrf")) starts a new device and makes you its controller. reuse=True first takes over a hosted one nobody controls (a client that died without closing leaves its device open).
  • Connecting to a hosted device id (pysdrlib.connect(addr, "hackrf-0")) attaches you as a viewer; claim=True also takes control if it is free. (pysdrlib.device("remote", addr, ...) is the same without choosing for you.) sdr.claim() takes control if nobody has it, and sdr.release() gives it back.
  • pysdrlib server --open hackrf hosts a device at startup with no controller until a client claims it.
  • A controller must keep talking to the server (the client sends heartbeats itself). One that is silent for --lease seconds (default 15) loses control: receiving and transmitting stop, the device stays open and can be claimed again. Time the server spends on a request that holds it up (a radio slow to open) counts against nobody.
  • A client that finds it has lost control (a heartbeat or a call is refused) says so in its log and is a viewer from then on: is_controller is False, write raises err.NotController, claim() takes control again if it is free (err.Busy if not), and close() / detach() just disconnect.
  • A new stream (stop_rx, start_rx) reaches every client: viewers start over at index 0, with the channels, frequency and rate it starts at. start_rx while receiving changes nothing, as on a local device. A read of several channels that a restart lands in starts over on the new stream; a read of one may return the end of the old one and the start of the new in one block.
  • A RemoteDevice closed and opened again connects as it was constructed to. An open that fails after the server opened the radio closes it there.

Saying who you are and what you need

A program can tell the server its name and let the server pick the radio, instead of knowing which radios it has:

  • program is shown by pysdrlib client ADDRESS list (and in the server log) next to the radio you control, with the need/want you gave, so someone who finds a radio busy can see who has it. A viewer's or claimant's program is logged.
  • serial and label pick a unit among the radios attached to the server (list shows them under "attached, not open" with their serials). With them, or with need/want, the driver may be left out.
  • need and want are dicts of freq (Hz, or a (low, high) pair that must be tunable without a gap), rate, bandwidth (the analog filter, or the sample rate where there is none), channels and tx. A limit a driver does not declare is taken as met.
  • Radios that do not meet need are never used; err.NoDevice names why each was left out. Of the rest, the one that meets most of want wins, and a radio nobody has open is preferred to taking over one a client left open and uncontrolled. Nothing is tuned for you: granted reports what it can do, then initialize as usual.
  • A radio that runs faster than a rate you need is usable (decimate it yourself) but never preferred: the radio nearest above wins, and a faster one is picked only when nothing runs as fast. granted["rate"] is the rate it will really run at, so check it.
  • freq is always the frequency over the air. If the operator says (pysdrlib server --frontends FILE, JSON or TOML, see pysdrlib.remote.frontends) that an LNB, converter or antenna sits on a radio, the server maps it to the radio's own tuning, set_rx_freq/set_tx_freq take and get_*_freq return the over-the-air frequency, and granted adds if_freq, antenna and inverted (get_rx_inverted(): the spectrum comes mirrored). Among radios that do equally well, the one whose antenna (ANT500: a 20-88 cm 50 ohm whip, best 75 MHz to 1 GHz; add your own with a kind such as lpda or dish, a size in metres and an impedance, all shown by list) is best at the wanted freq comes first; outside its best band it is only less preferred, not refused.
  • Arguments to open() (and init_args / init_kwargs) go to the radio the server opens. A hosted radio that would be taken over is open already: with open() arguments it is passed over, and constructor arguments are not used on it. An open() argument that names another unit than the one chosen (serial, index, addr) is refused.
  • Nothing stops a controller from tuning outside need/want: they are for choosing and for show, not limits.
  • Command line: rx --serial SN --program NAME, or rx --need rate=2e6 --freq 433.92e6 --rate 10e6 (with no type).

Sample format on the wire

By default samples cross the network in the device's own layout (8-bit for a HackRF, ...), which is lossless and several times smaller than complex64. The client always hands you complex64. Choose another format with --wire / --rx-wire (server default or per rx), --tx-wire (for tx), or the wire= / tx_wire= arguments of RemoteDevice:

native (default), complex64 (float32), int8, uint8, int12, int12p (packed), int16

A narrower format than the device's own loses precision; one wider only costs bandwidth.

Sharing a radio between programs on one machine

Run pysdrlib server next to the radio and let each program connect to it: one program controls the radio, any number of others watch (see Controllers and viewers). A program on the server's machine takes the samples from shared memory by default (transport="auto"), so the cost of serving one reader or five is almost the same:

  • The server keeps one ring of complex64 samples per streaming channel (a quarter second at the device's top rate) in shared memory and tells readers when it has written. Each reader has its own place in it: a reader that falls behind loses the samples it was too slow for, and sees that in read(..., meta=True) (m.gaps, m.dropped) like any other loss. It never slows the radio, the server, or another reader.
  • A client starts on the position of the block it first hears of; the one that called start_rx, and any attached when a stream starts, reads from its first sample. When the controller restarts the stream (stop_rx, start_rx) readers move to its new ring and indices start again from 0.
  • A client on another machine, or one that cannot attach the segment, takes blocks over the socket as before, with no setting. transport="zmq" forces that; transport="shm" insists on shared memory (err.NotSupported if there is none). pysdrlib server --no-shm (or Server(shm=False)) doesn't offer it.
  • The server only does the work of a way somebody is using: it writes the ring while a client reads from it, and encodes and sends blocks while one takes them over the socket.
  • Rings live in /dev/shm (named psdr-...) and are removed when the stream is restarted, the device is closed or the server stops. If a very large ring would not fit in /dev/shm the server makes a smaller one, or none (then clients use the socket). A server killed outright can leave psdr-* files there; deleting them is safe when it is not running.

Measured with the simulated radio, with reader processes on the same stream (CPU as a share of one core):

Stream Readers Socket (server + readers) Shared memory (server + readers)
20 MS/s 1 25% 21%
20 MS/s 4 66% 48%
61.44 MS/s 1 35% 29%
61.44 MS/s 4 94% 62%

The server's share is flat in the number of readers with shared memory (13% at 20 MS/s whether one reads or four) where over the socket it grows. What each reader still costs is mostly the array read() allocates and fills; read_into with your own buffer avoids the allocation.

Relaying a radio on another machine to programs here

Several programs on a machine that is not the radio's would each pull their own copy of the stream across the network, and a B210 at 61 MS/s in its native layout is already about 245 MB/s (2 Gb/s) for one. A relay is a server on this machine that hosts the far device: it takes the stream once, and the programs here share it through shared memory.

  • It hosts the device under the far device's own id, and the programs use it like any other hosted device: the same API, the same controller and viewer rules (those of the relay, among the programs on this machine).
  • Control passes through. When the far device is free the relay takes control of it and local control calls reach it. If someone else controls it the relay only watches: programs here can receive but not change anything (NotController). --control yes insists (an error if it is taken), --control no always only watches. --open TYPE opens a new far device instead, which closing the relay closes; otherwise closing it gives control back and the far device carries on.
  • A relay follows the far device: a stream someone else starts or stops there starts or stops here, and a restarted stream starts over for programs here too.
  • The far samples travel in the far device's own layout (8-bit for a HackRF), as to any client, and are shared here as complex64. Transmitting works when the relay has control. The relay adds a hop: its server publishes in batches of about 2 ms, so expect a few milliseconds more than a direct connection (not measured).
  • What goes wrong far away shows here: a device the far server reports stalled, lost or failing, and a far server that has stopped answering (lost), make a local read raise err.StreamStalled or err.Lost, as with a direct connection.
  • It does not reconnect: when the far server stops answering (about two timeouts) pysdrlib relay exits with an error, so a supervisor can restart it. From Python, worker.lost is set and list shows lost. Server.relay(address, device) does the same inside your own server.

What it saves is the network: the far server sends one stream however many programs listen here. On a machine with no network between them (measured with the simulated radio, the far server in its own process) the CPU is about even:

Stream Readers Directly: far server / all Through a relay: far server / relay / all
20 MS/s 4 15% / 49% 12% / 9% / 48%
61.44 MS/s 1 20% / 34% 21% / 16% / 47%
61.44 MS/s 4 31% / 100% 22% / 18% / 86%

So a relay costs a little for one program, and pays for itself from two or three, and mostly in bandwidth.

Monitoring

Each hosted device counts what passes through it. pysdrlib client ADDRESS stats shows it, and Client.metrics() returns it (--json prints the same dict):

  • rx: samples published, blocks and bytes sent on the socket (in the wire format), shared-memory notices, and how many clients subscribe over the socket and over shared memory.
  • device: the radio's own stream counts while it receives: samples delivered, dropped (the server fell behind), missing (the radio didn't deliver at its rate), stalls.
  • tx: samples and blocks transmitted, blocks refused (not from the controller, or not transmitting), and the device's transmit stats.
  • control: calls answered and failed. A relay adds upstream.dropped_blocks: blocks lost between the far server and the relay.

So lost samples can be placed: dropped_blocks on a client (the network or a slow client), device.dropped (the server's host), device.missing (the radio or its USB link). pysdrlib server and pysdrlib relay also log a line per streaming device every --stats-interval seconds (default 60; 0 turns it off): the rate published, subscribers, and what the device dropped or missed since the last line.

Security

There is no authentication or encryption. The controller token only stops two clients from stepping on each other; anyone who can reach the server can list devices, receive samples, and claim any uncontrolled device. The server binds to 127.0.0.1 unless told otherwise. Use --bind tcp://0.0.0.0:5555 only on a network you trust, or tunnel the ports (SSH, a VPN).

What a stranger who reaches the sockets can do is still bounded:

  • A client passes a driver a serial, an index, a UHD radio's addr and a simulated radio's signal, and nothing else: the arguments that name a host (tcpiq's host, listen), a file (file's path and tx_path, shm's directory) or a device string (UHD's args) are the operator's. --open TYPE:KEY=VALUE opens such a device at startup; --allow-arg TYPE:KEY,KEY (Server(client_args=...)) lets clients choose those keys, and then a client can make the server read, write and connect as it says: allow them only to clients you would give a shell.
  • A serial, serial_number or addr a client gives is text with no ,, = or control character, and an index a whole number: a driver may build a device string from them, which they must not be able to add to.
  • A server hosts at most --max-devices (32) devices, refuses a request over 1 MiB (a block to transmit over 4 MiB), and answers a request of the wrong shape with an error. A message that is not a single request frame does not stop it.
  • Each read find_gain makes through a server (count, confirm, skip) is at most 4 Mi samples and waits at most 30 s, and pump, sweep and find are not remote methods.
  • A subscription only counts when it is one of the device's own two topics, and an unsubscribe only when the last subscriber of a topic has gone, so socket_subscribers is "someone is subscribed", not an exact count.
  • Streams in shared memory: the manifest directory is private to the user (0700) and one that another user owns, or anyone can write to, is not believed; a reader refuses a ring whose header the segment cannot hold.

What it cannot stop: anyone who can reach the sockets can still list devices, claim any free one, receive every stream and consume the server's CPU and bandwidth. A slow open (a radio that takes seconds to come up) still holds the C2 thread while it opens.

Layout

File Contents
remote/server.py Server (the C2 socket: lifecycle and ownership) and DeviceWorker (one hosted device's sockets)
remote/client.py Client (discovery) and RemoteDevice (a Device backed by a server)
remote/server.py also has RelayWorker, a device of another server hosted here (Server.relay)
pysdrlib.shm ShmWriter (the server's ring in shared memory) and ShmReader (a client's view of it), in shm/ring.py; the ring is C++ in _native/include/hardware_shm.hpp
remote/discovery.py Advertiser (a server's mDNS announcement) and discover
remote/protocol.py Wire format: message framing, sample block headers, wire formats. The file documents the sockets
remote/cli.py The pysdrlib command

Per hosted device the server runs a control socket (ROUTER), an RX stream (PUB) and a TX stream (PUSH); see remote/protocol.py for the details. Tests are in tests/test_remote.py.

Modules:

Name Description
choose

Choosing a radio by what a program needs, without knowing which radios a server has.

cli

Command line for the remote server, relay and client

client

pysdrlib client: use a device hosted by a pysdrlib server like a local one.

discovery

Finding servers on the local network with mDNS / DNS-SD (needs zeroconf: pip install pysdrlib[remote])

frontends

What sits between each radio of a server and the air: LNBs, converters, antennas

protocol

pysdrlib remote protocol.

server

pysdrlib server: hosts hardware SDRs for remote clients.

choose

Choosing a radio by what a program needs, without knowing which radios a server has.

A client says what it needs (need: below this it is of no use) and what it would like (want):

pysdrlib.connect(addr, program="pyspecan", need={"freq": 433e6, "rate": 2e6}, want={"freq": 433.92e6, "rate": 10e6})

Both are dicts with any of these keys:

freq        Hz over the air to tune to, or a (low, high) pair of Hz the radio has to be able to tune across without a gap
            (through whatever LNB or converter the server says is on the radio: see `Chain`)
rate        samples/s; a radio can run at it or faster (the client decimates), never slower
bandwidth   Hz of spectrum seen (the analog filter where the radio has one, else its sample rate)
channels    how many channels
tx          True if it must be able to transmit

A radio is a candidate when it meets all of need. Of the candidates the one that misses the fewest keys of want, and then comes nearest to it, wins; a radio whose capabilities are unknown comes after every one whose are known. A freq pair means the radio can tune across the whole span (retuning between its ends), not that it sees all of it at once: that is bandwidth. More rate or bandwidth than want asks for is no miss (only a small cost, growing with how much more, so the radio nearest above wins); less is. Of radios that do equally well, the one whose antenna is best at the wanted frequency comes first. What the radio can actually do nearest to want (and need) is reported back as granted: the rate it will really run at, and for a radio behind a converter the frequency it tunes (if_freq), the antenna port and whether the spectrum is inverted.

This module is pure functions of pysdrlib.base.caps.Capabilities: no sockets, no hardware.

Functions:

Name Description
normalize

spec as a clean dict (None -> {}); raises ValueError for a key or value that makes no sense

problems

What of spec the radio described by caps cannot do, as sentences (empty: it meets all of it).

granted

What the radio can do nearest to spec: for each key the value it would give (a frequency pair is the span clipped

score

(keys missed, shortfall) of the radio against spec: how many keys it cannot meet, and how far from them it is as

shortfall

How far the radio is from spec, 0.0 when it meets all of it (see score). Orders radios that all meet need.

known

Whether caps says anything about what the radio tunes or samples. One that does not (a driver that declares nothing,

antenna_off

How far the antenna(s) the radio would use for want are from their best at the wanted frequency: 0.0 when optimal there or

rank

Sort key of a radio that meets need, smallest best: unknown capabilities last, then fewest keys of want missed, then

met

Whether the radio meets all of spec

normalize

normalize(spec, what='need')

spec as a clean dict (None -> {}); raises ValueError for a key or value that makes no sense

Source code in src/pysdrlib/remote/choose.py
def normalize(spec, what="need"):
    """`spec` as a clean dict (None -> {}); raises ValueError for a key or value that makes no sense"""
    if not spec:
        return {}
    if not isinstance(spec, dict):
        raise ValueError(f"{what} is a dict of {', '.join(FIELDS)}, not {type(spec).__name__}")
    out = {}
    for key, value in spec.items():
        if key not in FIELDS:
            raise ValueError(f"{what} has no {key!r} (it takes {', '.join(FIELDS)})")
        if key == "tx":
            out[key] = _bool(what, key, value)
        elif key == "freq" and isinstance(value, (list, tuple)):
            if len(value) != 2:
                raise ValueError(f"{what}['freq'] is a Hz number or a (low, high) pair, not {value!r}")
            lo, hi = _number(what, key, value[0]), _number(what, key, value[1])
            if not 0 <= lo <= hi:
                raise ValueError(f"{what}['freq'] is a Hz number or a (low, high) pair, not {value!r}")
            out[key] = [lo, hi]
        else:
            num = _number(what, key, value)
            if num < 0 or (key == "channels" and num < 1):
                raise ValueError(f"{what}[{key!r}] must be positive, not {value!r}")
            if key == "channels":
                if num != int(num):
                    raise ValueError(f"{what}['channels'] is a whole number, not {value!r}")
                num = int(num)
            out[key] = num
    return out

problems

problems(caps, spec) -> list

What of spec the radio described by caps cannot do, as sentences (empty: it meets all of it). A limit the radio does not declare is taken as met.

Source code in src/pysdrlib/remote/choose.py
def problems(caps, spec) -> list:
    """What of `spec` the radio described by `caps` cannot do, as sentences (empty: it meets all of it).
    A limit the radio does not declare is taken as met."""
    spec = normalize(spec)
    out = []
    if "freq" in spec:
        lo, hi = _span(spec["freq"])
        wanted = _fmt(lo) if lo == hi else f"{_fmt(lo)}-{_fmt(hi)}"
        if not _freq_ok(caps, spec["freq"]):
            out.append(f"cannot tune {wanted} (tunes {_reach_text(caps, 'rx')})")
        if spec.get("tx") and caps.channels.get("tx", 0) and not _freq_ok(caps, spec["freq"], "tx"):
            out.append(f"cannot transmit on {wanted} (transmits {_reach_text(caps, 'tx')})")
    if "rate" in spec and caps.rates and _caps.at_least(caps.rates, spec["rate"]) is None:
        # a faster radio will do (the client decimates), a slower one is of no use
        out.append(f"top sample rate is {_fmt(_widest(caps.rates))}, not {_fmt(spec['rate'])}")
    if "bandwidth" in spec:
        top = _bandwidth_limit(caps)
        if top is not None and spec["bandwidth"] > top:
            out.append(f"sees at most {_fmt(top)}, not {_fmt(spec['bandwidth'])}")
    if "channels" in spec and caps.channels.get("rx", 1) < spec["channels"]:
        out.append(f"has {caps.channels.get('rx', 1)} receive channel(s), not {spec['channels']}")
    if spec.get("tx") and not caps.channels.get("tx", 0):
        out.append("cannot transmit")
    return out

granted

granted(caps, spec) -> dict

What the radio can do nearest to spec: for each key the value it would give (a frequency pair is the span clipped to what it tunes; a rate is the slowest it runs at that is not below the asked one, else its top; a key the radio puts no limit on keeps the asked value). Through a converter the frequency is still over the air, with if_freq (what the radio tunes), antenna and inverted beside it

Source code in src/pysdrlib/remote/choose.py
def granted(caps, spec) -> dict:
    """What the radio can do nearest to `spec`: for each key the value it would give (a frequency pair is the span clipped
    to what it tunes; a rate is the slowest it runs at that is not below the asked one, else its top; a key the radio puts no
    limit on keeps the asked value). Through a converter the frequency is still over the air, with `if_freq` (what the radio
    tunes), `antenna` and `inverted` beside it"""
    spec = normalize(spec)
    out = {}
    for key, value in spec.items():
        if key == "freq":
            out[key], chain = _freq_granted(caps, value)
            if chain is not IDENTITY:
                lo, hi = _span(value)
                out["if_freq"] = chain.to_if(lo) if lo == hi else list(chain.span_to_if(lo, hi))
                out["antenna"] = chain.antenna or chain.port
                out["inverted"] = chain.invert
        elif key == "rate":
            out[key] = (_caps.at_least(caps.rates, value) or _widest(caps.rates)) if caps.rates else value
        elif key == "bandwidth":
            top = _bandwidth_limit(caps)
            out[key] = min(value, top) if top is not None else value
        elif key == "channels":
            out[key] = min(value, caps.channels.get("rx", 1))
        else:
            out[key] = bool(value and caps.channels.get("tx", 0))
    return out

score

score(caps, spec) -> tuple

(keys missed, shortfall) of the radio against spec: how many keys it cannot meet, and how far from them it is as the share of each unmet key (so 1.0 is one key missed entirely), summed. (0, 0.0) meets all of spec. Rate above what was wanted costs a little and is not a miss.

Source code in src/pysdrlib/remote/choose.py
def score(caps, spec) -> tuple:
    """(keys missed, shortfall) of the radio against `spec`: how many keys it cannot meet, and how far from them it is as
    the share of each unmet key (so 1.0 is one key missed entirely), summed. (0, 0.0) meets all of `spec`. Rate above
    what was wanted costs a little and is not a miss."""
    spec = normalize(spec)
    got = granted(caps, spec)
    missed, total = 0, 0.0
    for key, value in spec.items():
        if got[key] == value:
            continue
        a, b = _span(value), _span(got[key])
        if key == "freq":
            scale = max(abs(a[1] - a[0]), abs(a[0]), 1.0)
            cost = min(1.0, (abs(a[0] - b[0]) + abs(a[1] - b[1])) / scale)
        elif key == "tx":
            cost = 1.0
        else:
            cost = min(1.0, abs(a[0] - b[0]) / max(abs(a[0]), 1.0))
            if key == "rate" and b[0] > a[0]:
                total += cost * OVER
                continue
        missed += 1
        total += cost
    return missed, total

shortfall

shortfall(caps, spec) -> float

How far the radio is from spec, 0.0 when it meets all of it (see score). Orders radios that all meet need.

Source code in src/pysdrlib/remote/choose.py
def shortfall(caps, spec) -> float:
    """How far the radio is from `spec`, 0.0 when it meets all of it (see `score`). Orders radios that all meet `need`."""
    return score(caps, spec)[1]

known

known(caps) -> bool

Whether caps says anything about what the radio tunes or samples. One that does not (a driver that declares nothing, or a radio whose capabilities could not be read) meets every limit by default, so it is ranked after those that do.

Source code in src/pysdrlib/remote/choose.py
def known(caps) -> bool:
    """Whether `caps` says anything about what the radio tunes or samples. One that does not (a driver that declares nothing,
    or a radio whose capabilities could not be read) meets every limit by default, so it is ranked after those that do."""
    return caps is not None and bool(caps.freq or caps.rates)

antenna_off

antenna_off(caps, want) -> float

How far the antenna(s) the radio would use for want are from their best at the wanted frequency: 0.0 when optimal there or when nothing says (see Chain.optimal)

Source code in src/pysdrlib/remote/choose.py
def antenna_off(caps, want) -> float:
    """How far the antenna(s) the radio would use for `want` are from their best at the wanted frequency: 0.0 when optimal there or
    when nothing says (see `Chain.optimal`)"""
    want = normalize(want)
    if caps is None or "freq" not in want:
        return 0.0
    off = 0.0
    for direction in ("rx", "tx") if want.get("tx") else ("rx",):
        picked = _pick(caps, direction, want["freq"])
        off += picked[1] if picked else 0.0
    return off

rank

rank(caps, want) -> tuple

Sort key of a radio that meets need, smallest best: unknown capabilities last, then fewest keys of want missed, then nearest, then the antenna nearest its best at the wanted frequency

Source code in src/pysdrlib/remote/choose.py
def rank(caps, want) -> tuple:
    """Sort key of a radio that meets `need`, smallest best: unknown capabilities last, then fewest keys of `want` missed, then
    nearest, then the antenna nearest its best at the wanted frequency"""
    missed, total = score(caps, want) if caps is not None else (0, 0.0)
    return (not known(caps), missed, total, antenna_off(caps, want))

met

met(caps, spec) -> bool

Whether the radio meets all of spec

Source code in src/pysdrlib/remote/choose.py
def met(caps, spec) -> bool:
    """Whether the radio meets all of `spec`"""
    return not problems(caps, spec)

cli

Command line for the remote server, relay and client

pysdrlib server --bind tcp://0.0.0.0:5555 --port-range 6000-6100 --devices <driver1>,<driver2>
pysdrlib client tcp://host:5555 list
pysdrlib client tcp://host:5555 info <driver>-0
pysdrlib client tcp://host:5555 rx <driver> --freq 100e6 --rate 10e6 -o out.cfile -t 5
pysdrlib client tcp://host:5555 rx --serial <serial> --program myapp -o out.cfile -t 5
pysdrlib client tcp://host:5555 rx --need freq=433e6 --need rate=2e6 --freq 433.92e6 --rate 10e6 -o out.cfile -t 5
pysdrlib client tcp://host:5555 watch <driver>-0 -o out.cfile -t 5
pysdrlib client tcp://host:5555 rx <driver> --freq 433.92e6 --rate 2e6 -f ci8 -o capture.sigmf -t 10
pysdrlib client tcp://host:5555 tx <driver> -i out.cfile --freq 915e6 --rate 2e6 --tx-gain 0 --tx-wire int8
pysdrlib client tcp://host:5555 set <driver>-0 rx_freq=101e6 rx_lna_gain=16
pysdrlib relay tcp://host:5555 <driver>-0 --bind tcp://127.0.0.1:5556      # programs here share one connection to it

Recordings are raw complex64 (GNU Radio .cfile) by default; -f picks another format (ci16, ci8, cu8...), and an output ending in .sigmf (or --sigmf) records SigMF, with the rate, frequency, retunes and lost samples in its metadata. Transmit files are raw complex64. --rx-wire / --tx-wire choose the format samples cross the network in (native = the device's own layout).

Functions:

Name Description
add_parsers

Add the server, relay and client commands to the subparsers of the pysdrlib command

build_parser

A parser of just the remote commands, for main here

run_server

pysdrlib server: host devices until Ctrl+C or SIGTERM. Logs to stderr (the journal, under systemd)

run_relay

pysdrlib relay: host a far device here until Ctrl+C, or until the far server stops answering

format_chain

A chain as one line for list: its direction, port, the LO it has and the antenna on it

print_list

Print what the server c (a Client) allows, hosts and has attached, as client ADDRESS list does

run_discover

pysdrlib discover: the servers announcing themselves here, and with --list what each has

print_stats

client stats: one paragraph per hosted device

run_client

pysdrlib client: list, info, stats, rx, watch, set and tx

run

Run the command args names (server, relay or client); errors exit with a message instead of a traceback

main

The remote commands on their own (pysdrlib.cli.main is the whole pysdrlib command)

add_parsers

add_parsers(sub)

Add the server, relay and client commands to the subparsers of the pysdrlib command

Source code in src/pysdrlib/remote/cli.py
def add_parsers(sub):
    """Add the `server`, `relay` and `client` commands to the subparsers of the `pysdrlib` command"""
    s = sub.add_parser("server", help="host the SDRs connected to this machine")
    s.add_argument("--bind", default="tcp://127.0.0.1:5555", help="C2 endpoint (default %(default)s; use tcp://0.0.0.0:5555 to serve the network)")
    s.add_argument("--port-range", type=_port_range, help="LOW-HIGH ports for per-device sockets (default: any free port)")
    s.add_argument("--devices", help="comma separated device types clients may open (default: all)")
    s.add_argument("--open", action="append", default=[], metavar="TYPE[:KEY=VALUE,...]",
                   help="open a device at startup, uncontrolled until a client claims it; KEY=VALUE pairs go to its open() "
                        "(e.g. file:path=cap.sigmf,loop=true or tcpiq:host=10.0.0.5,port=1234); opened by the operator, so not limited as a client's arguments are (repeatable)")
    s.add_argument("--allow-arg", action="append", default=[], metavar="TYPE:KEY[,KEY...]",
                   help="let clients pass these arguments to a driver's constructor and open() (repeatable). By default they may pass a serial, an index, "
                        "a UHD radio's addr and a simulated radio's signal, nothing that names a host or a file: e.g. tcpiq:host,port,sample_format")
    s.add_argument("--max-devices", type=int, default=32, help="devices the server hosts at once (default %(default)s)")
    s.add_argument("--frontends", metavar="FILE", help="JSON (or TOML) file saying what sits between each radio and the air (LNB or converter LO, tx chain, antenna), so clients ask for over-the-air frequencies; see pysdrlib.remote.frontends")
    s.add_argument("--wire", "--rx-wire", dest="wire", default="native", help="default RX wire format: native (device's own sample layout, default), complex64, int8, int16, ...")
    s.add_argument("--lease", type=float, default=15.0, help="seconds a silent controller keeps control, 0 = forever (default %(default)s)")
    s.add_argument("--no-shm", dest="shm", action="store_false", help="don't offer clients on this machine the samples in shared memory")
    s.add_argument("--advertise", action="store_true", help="announce this server on the local network (mDNS) so `pysdrlib discover` finds it; needs a --bind others can reach")
    s.add_argument("--advertise-name", metavar="NAME", help="the name to announce (default: this machine's host name)")
    s.add_argument("--scan-interval", type=float, default=10.0, help="seconds between looks at which radios are attached, logging ones that appear or vanish, 0 = only at startup (default %(default)s)")
    s.add_argument("--uhd-log", metavar="LEVEL", help="how much of UHD's own console log to show: trace, debug, info, warning, error, fatal or off "
                   "(default: warning, or UHD_LOG_CONSOLE_LEVEL if set)")
    s.add_argument("--log-timestamps", action="store_true", help="prefix log lines with a time (default off: journald adds one)")
    s.add_argument("--stats-interval", type=float, default=60.0, metavar="S",
                   help="seconds between log lines per streaming device: rate published, subscribers, drops; 0 = none (default %(default)s)")
    s.add_argument("-v", "--verbose", action="store_true", help="also log debug detail")

    y = sub.add_parser("relay", help="host a device of another server here, so programs on this machine share one connection to it")
    y.add_argument("address", help="the far server's C2 endpoint, e.g. tcp://host:5555")
    y.add_argument("device", nargs="?", help="id of a device it hosts, e.g. hackrf-0 (or use --open)")
    y.add_argument("--open", metavar="TYPE", help="open a new device of this type on the far server instead (the relay controls it)")
    y.add_argument("--control", choices=("auto", "yes", "no"), default="auto",
                   help="take control of the far device: if it is free (auto, default), insist (yes), or only watch it (no)")
    y.add_argument("--name", help="the id the device has here (default: the far device's)")
    y.add_argument("--bind", default="tcp://127.0.0.1:5556", help="where local programs connect (default %(default)s)")
    y.add_argument("--timeout", type=float, default=5.0, help="seconds the far server may take to answer")
    y.add_argument("--stats-interval", type=float, default=60.0, metavar="S", help="seconds between stats log lines; 0 = none (default %(default)s)")
    y.add_argument("--lease", type=float, default=15.0, help="seconds a silent local controller keeps control, 0 = forever (default %(default)s)")
    y.add_argument("--no-shm", dest="shm", action="store_false", help="don't offer programs on this machine the samples in shared memory")
    y.add_argument("-v", "--verbose", action="store_true")
    y.add_argument("--advertise", action="store_true", help="announce this relay on the local network (mDNS) so `pysdrlib discover` finds it; needs a --bind others can reach")
    y.add_argument("--advertise-name", metavar="NAME", help="the name to announce (default: this machine's host name)")

    d = sub.add_parser("discover", help="list the pysdrlib servers announcing themselves on the local network")
    d.add_argument("--timeout", type=float, default=2.0, help="seconds to listen (default %(default)s)")
    d.add_argument("--list", action="store_true", help="also ask each server what it has (as `client ADDRESS list`)")
    d.add_argument("--all-versions", action="store_true", help="also show servers speaking another protocol version")

    c = sub.add_parser("client", help="talk to a pysdrlib server")
    c.add_argument("address", help="server C2 endpoint, e.g. tcp://host:5555")
    c.add_argument("--timeout", type=float, default=5.0)
    cmd = c.add_subparsers(dest="cmd", required=True)

    cmd.add_parser("list", help="device types and hosted devices")

    m = cmd.add_parser("stats", help="what each hosted device has published, to whom, and what was lost")
    m.add_argument("device", nargs="?", help="just this hosted device")
    m.add_argument("--json", action="store_true", help="all of it, as JSON")

    i = cmd.add_parser("info", help="capabilities of a hosted device")
    i.add_argument("device")

    r = cmd.add_parser("rx", help="open a new device, configure it and record")
    r.add_argument("type", nargs="?", help="device type, e.g. hackrf (optional with --serial, --label or --need: any radio that fits)")
    _choose_args(r)
    _record_args(r)
    r.add_argument("--rx-wire", "--wire", dest="rx_wire", help="RX wire format for this device (default: the server's)")
    r.add_argument("--init", action="append", default=[], metavar="KEY=VALUE", help="device constructor argument (repeatable)")
    r.add_argument("--arg", action="append", default=[], metavar="KEY=VALUE",
                   help="argument to the device's open(), e.g. path=cap.sigmf for `file`, host=... for `tcpiq` (repeatable)")
    r.add_argument("--freq", type=_number)
    r.add_argument("--rate", type=_number)
    r.add_argument("--rx-gain", type=_number)
    r.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", help="device specific setter, e.g. rx_lna_gain=16 (repeatable)")

    w = cmd.add_parser("watch", help="record from an already hosted device without controlling it")
    w.add_argument("device")
    _record_args(w)

    st = cmd.add_parser("set", help="change settings on a hosted device (takes control briefly)")
    st.add_argument("device")
    st.add_argument("settings", nargs="+", metavar="KEY=VALUE", help="calls set_<key>(value): rx_freq, tx_freq, rx_sample_rate, rx_gain, rx_lna_gain, ...")

    t = cmd.add_parser("tx", help="open a new device, configure it and transmit a file")
    t.add_argument("type", nargs="?", help="device type, e.g. hackrf (optional with --serial, --label or --need)")
    _choose_args(t)
    t.add_argument("-i", "--input", required=True, help="file of raw complex64 to transmit")
    t.add_argument("--tx-wire", default="native", help="TX wire format: native (device's own sample layout, default), complex64, int8, int16, ...")
    t.add_argument("--freq", type=_number)
    t.add_argument("--rate", type=_number)
    t.add_argument("--tx-gain", type=_number, help="total TX gain in dB (default: the device's)")
    t.add_argument("--loop", action="store_true", help="repeat the file until Ctrl+C")
    t.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", help="device specific setter, e.g. tx_if_gain=0 (repeatable)")
    t.add_argument("--init", action="append", default=[], metavar="KEY=VALUE", help="device constructor argument (repeatable)")
    t.add_argument("--arg", action="append", default=[], metavar="KEY=VALUE", help="argument to the device's open() (repeatable)")

build_parser

build_parser()

A parser of just the remote commands, for main here

Source code in src/pysdrlib/remote/cli.py
def build_parser():
    """A parser of just the remote commands, for `main` here"""
    p = argparse.ArgumentParser(prog="pysdrlib", description="pysdrlib remote server, relay and client")
    add_parsers(p.add_subparsers(dest="mode", required=True))
    return p

run_server

run_server(args)

pysdrlib server: host devices until Ctrl+C or SIGTERM. Logs to stderr (the journal, under systemd)

Source code in src/pysdrlib/remote/cli.py
def run_server(args):
    """`pysdrlib server`: host devices until Ctrl+C or SIGTERM. Logs to stderr (the journal, under systemd)"""
    import logging
    import os
    from .. import logger
    if args.uhd_log:   # UHD reads this when its library loads (the first scan), so set it before then
        os.environ["UHD_LOG_CONSOLE_LEVEL"] = args.uhd_log
    logger.configure(logging.DEBUG if args.verbose else logging.INFO, timestamps=args.log_timestamps)
    try:
        _serve(args, logger.new("remote.cli"))
    finally:
        logger.unconfigure()

run_relay

run_relay(args)

pysdrlib relay: host a far device here until Ctrl+C, or until the far server stops answering

Source code in src/pysdrlib/remote/cli.py
def run_relay(args):
    """`pysdrlib relay`: host a far device here until Ctrl+C, or until the far server stops answering"""
    import logging
    from .. import logger
    if args.verbose:
        logger.configure(logging.DEBUG)
    try:
        _relay(args)
    finally:
        if args.verbose:
            logger.unconfigure()

format_chain

format_chain(chain)

A chain as one line for list: its direction, port, the LO it has and the antenna on it

Source code in src/pysdrlib/remote/cli.py
def format_chain(chain):
    """A chain as one line for `list`: its direction, port, the LO it has and the antenna on it"""
    where = f"{chain['direction']}" + (f" {chain['port']}" if chain.get("port") else "") + \
        (f" (channel {chain['channel']})" if chain.get("channel") is not None else "")
    lo = f", LO {chain['lo'] / 1e6:g} MHz{' (inverted)' if chain.get('invert') else ''}" if chain.get("lo") else ""
    pol = f", {chain['polarization']}" if chain.get("polarization") else ""
    return f"antenna {where}: {format_antenna(chain.get('antenna'))}{lo}{pol}"

print_list

print_list(c)

Print what the server c (a Client) allows, hosts and has attached, as client ADDRESS list does

Source code in src/pysdrlib/remote/cli.py
def print_list(c):
    """Print what the server `c` (a `Client`) allows, hosts and has attached, as `client ADDRESS list` does"""
    print("types:", ", ".join(c.types()) or "(none)")
    res = c._c2.request("list")
    devs = res["devices"]
    for d in devs:
        flags = [k for k, v in d["state"].items() if v and k != "open"]
        who = f" by {d['program']}" if d.get("program") else ""
        print(f"{d['id']:<14} {d['name']:<20} cf={d['cf']:,.0f} Fs={d['Fs']:,.0f} "
              f"{d['wire']:<9} {'controlled' + who if d['controlled'] else 'free'} {' '.join(flags)}")
        for key in ("need", "want"):
            if d.get(key):
                print(f"{'':<14} {key}: {d[key]}")
        for chain in d.get("chains", []):
            print(f"{'':<14} {format_chain(chain)}")
    if not devs:
        print("no devices hosted")
    free = [a for a in res.get("available", []) if not a["hosted"]]
    if free:
        print("attached, not open:")
        for a in free:
            print(f"{'':<14} {a['driver']}: {a['label']}" + (f"  serial {a['serial']}" if a["serial"] else ""))

run_discover

run_discover(args)

pysdrlib discover: the servers announcing themselves here, and with --list what each has

Source code in src/pysdrlib/remote/cli.py
def run_discover(args):
    """`pysdrlib discover`: the servers announcing themselves here, and with --list what each has"""
    from .discovery import discover
    from .client import Client
    from . import protocol
    found = discover(args.timeout, all_versions=args.all_versions)
    if not found:
        print("no servers found (a server must run with --advertise, on this network)")
    for i, s in enumerate(found):
        if args.list and i:
            print()
        other = f" protocol {s['proto']}" if s["proto"] != protocol.VERSION else ""
        print(f"{s['address']:<24} {s['name']} ({s['kind']}, pysdrlib {s['version'] or '?'}{other})")
        for extra in s["addresses"][1:]:
            print(f"{'':<24} also {extra}")
        if args.list:
            try:
                with Client(s["address"], timeout=max(args.timeout, 2.0)) as c:
                    print_list(c)
            except Exception as e:
                print(f"  cannot ask it: {e}")

print_stats

print_stats(metrics)

client stats: one paragraph per hosted device

Source code in src/pysdrlib/remote/cli.py
def print_stats(metrics):
    """`client stats`: one paragraph per hosted device"""
    print(f"server up {metrics['uptime']:.0f}s")
    if not metrics["devices"]:
        print("  no hosted devices")
    for dev_id, m in metrics["devices"].items():
        rx, dev, tx = m["rx"], m["device"] or {}, m["tx"]
        who = f"controlled by {m['program'] or 'a client'}" if m["controlled"] else "uncontrolled"
        print(f"  {dev_id} ({m['type']}, {who}, {'streaming' if m['streaming'] else 'idle'}, up {m['uptime']:.0f}s)")
        print(f"    rx: {rx['samples']:,} samples published, {rx['bytes'] / 1e6:,.1f} MB in {rx['blocks']:,} blocks "
              f"({rx['wire']}); subscribers: {rx['socket_subscribers']} socket, {rx['shm_subscribers']} shm")
        if dev:
            print(f"    device: {dev.get('samples', 0):,} delivered, {dev.get('dropped', 0):,} dropped, "
                  f"{dev.get('missing', 0):,} missing, {dev.get('stalls', 0)} stalls" if "error" not in dev
                  else f"    device: {dev['error']}")
        if "upstream" in m:
            print(f"    upstream: {m['upstream']['id']} of {m['upstream']['address']}, "
                  f"{m['upstream']['dropped_blocks']:,} blocks lost on the way")
        if tx["samples"] or tx["refused"] or tx["device"]:
            print(f"    tx: {tx['samples']:,} samples in {tx['blocks']:,} blocks, {tx['refused']:,} refused"
                  + (f", device {tx['device']}" if tx["device"] else ""))
        print(f"    control: {m['control']['calls']:,} calls, {m['control']['errors']:,} failed")

run_client

run_client(args)

pysdrlib client: list, info, stats, rx, watch, set and tx

Source code in src/pysdrlib/remote/cli.py
def run_client(args):
    """`pysdrlib client`: list, info, stats, rx, watch, set and tx"""
    from .client import Client, RemoteDevice
    if args.cmd == "list":
        with Client(args.address, args.timeout) as c:
            print_list(c)
    elif args.cmd == "stats":
        with Client(args.address, args.timeout) as c:
            metrics = c.metrics(args.device)
        if args.json:
            print(json.dumps(metrics, indent=2))
        else:
            print_stats(metrics)
    elif args.cmd == "info":
        with RemoteDevice(args.address, id=args.device, timeout=args.timeout) as dev:
            print(json.dumps(dev.capabilities, indent=2))
    elif args.cmd == "rx":
        dev = RemoteDevice(args.address, args.type, timeout=args.timeout, wire=args.rx_wire,
                           init_kwargs=dict(_setting(i) for i in args.init),
                           **_choice(args, freq=args.freq, rate=args.rate))
        dev.open(**dict(_setting(a) for a in args.arg))
        with dev:
            dev.initialize(cf=args.freq, Fs=args.rate, rx_gain=args.rx_gain)
            _apply(dev, [_setting(s) for s in args.set])
            print(f"{dev.id}: cf={dev.get_rx_freq():,.0f} Fs={dev.get_rx_sample_rate():,.0f} wire={dev.wire}")
            dev.start_rx()
            try:
                _record(dev, args)
            finally:
                dev.stop_rx()
    elif args.cmd == "watch":
        with RemoteDevice(args.address, id=args.device, timeout=args.timeout) as dev:
            _record(dev, args)
    elif args.cmd == "set":
        with RemoteDevice(args.address, id=args.device, timeout=args.timeout) as dev:
            dev.claim()
            try:
                _apply(dev, [_setting(s) for s in args.settings])
            finally:
                dev.release()
    elif args.cmd == "tx":
        dev = RemoteDevice(args.address, args.type, timeout=args.timeout, tx_wire=args.tx_wire,
                           init_kwargs=dict(_setting(i) for i in args.init),
                           **_choice(args, freq=args.freq, rate=args.rate))
        dev.open(**dict(_setting(a) for a in args.arg))
        with dev:
            dev.initialize(cf=args.freq, Fs=args.rate, tx_gain=args.tx_gain)
            _apply(dev, [_setting(x) for x in args.set])
            print(f"{dev.id}: cf={dev.get_rx_freq():,.0f} Fs={dev.get_rx_sample_rate():,.0f} tx_wire={dev.tx_wire_name}")
            _transmit(dev, args)

run

run(args)

Run the command args names (server, relay or client); errors exit with a message instead of a traceback

Source code in src/pysdrlib/remote/cli.py
def run(args):
    """Run the command `args` names (`server`, `relay` or `client`); errors exit with a message instead of a traceback"""
    try:
        import zmq  # noqa: F401
    except ImportError:
        raise SystemExit("pysdrlib's remote support needs pyzmq: pip install pysdrlib[remote]")
    try:
        {"server": run_server, "relay": run_relay, "client": run_client, "discover": run_discover}[args.mode](args)
    except (TimeoutError, OSError) as e:
        raise SystemExit(f"error: {e}")
    except Exception as e:
        from .. import err
        if isinstance(e, err._Error):
            raise SystemExit(f"error: {e}")
        raise

main

main(argv=None)

The remote commands on their own (pysdrlib.cli.main is the whole pysdrlib command)

Source code in src/pysdrlib/remote/cli.py
def main(argv=None):
    """The remote commands on their own (`pysdrlib.cli.main` is the whole `pysdrlib` command)"""
    run(build_parser().parse_args(argv))

client

pysdrlib client: use a device hosted by a pysdrlib server like a local one.

sdr = pysdrlib.device("remote", "tcp://host:5555", "hackrf")   # a device type: this client controls it
sdr.open()
sdr.initialize(cf=100e6, Fs=10e6)
sdr.start_rx()
samples = sdr.get_samples()

view = pysdrlib.device("remote", "tcp://host:5555", id="hackrf-0")  # an already hosted device: a viewer
view.open()                       # can read samples and `get_*`; view.claim() to take control if it is free

RemoteDevice is a Device, so code written for a local device works unchanged. Any other public method of the hosted device (e.g. its per-stage gain setters) is reachable by name too.

Classes:

Name Description
Client

Talks to a server's C2 socket: discovery. Use RemoteDevice to work with a device.

RemoteDevice

Client

Client(address: str, timeout=DEFAULT_TIMEOUT)

Talks to a server's C2 socket: discovery. Use RemoteDevice to work with a device.

Methods:

Name Description
types

Device types the server can open

list

Devices the server currently hosts

available

Radios attached to the server's machine as of its last scan: dicts with driver, label, serial, index and

metrics

What the server's devices (or the one with id device) have passed since hosted: see Server.metrics

candidates

The server's radios that fit the request, best first, without opening any (see Server.candidates); raises

close

Close the connection

Source code in src/pysdrlib/remote/client.py
def __init__(self, address: str, timeout=DEFAULT_TIMEOUT):
    self.address = address
    self._c2 = _Channel(address, timeout)
    self.info = _hello(self._c2, address)
types
types()

Device types the server can open

Source code in src/pysdrlib/remote/client.py
def types(self):
    """Device types the server can open"""
    return self.info["types"]
list
list()

Devices the server currently hosts

Source code in src/pysdrlib/remote/client.py
def list(self):
    """Devices the server currently hosts"""
    return self._c2.request("list")["devices"]
available
available()

Radios attached to the server's machine as of its last scan: dicts with driver, label, serial, index and hosted (the id of the device that has it open, or None)

Source code in src/pysdrlib/remote/client.py
def available(self):
    """Radios attached to the server's machine as of its last scan: dicts with `driver`, `label`, `serial`, `index` and
    `hosted` (the id of the device that has it open, or None)"""
    return self._c2.request("list").get("available", [])
metrics
metrics(device=None)

What the server's devices (or the one with id device) have passed since hosted: see Server.metrics

Source code in src/pysdrlib/remote/client.py
def metrics(self, device=None):
    """What the server's devices (or the one with id `device`) have passed since hosted: see `Server.metrics`"""
    return self._c2.request("metrics", device=device)
candidates
candidates(device=None, serial=None, label=None, need=None, want=None)

The server's radios that fit the request, best first, without opening any (see Server.candidates); raises err.NoDevice saying why when none do

Source code in src/pysdrlib/remote/client.py
def candidates(self, device=None, serial=None, label=None, need=None, want=None):
    """The server's radios that fit the request, best first, without opening any (see `Server.candidates`); raises
    `err.NoDevice` saying why when none do"""
    return self._c2.request("choose", type=device, serial=serial, label=label, need=need, want=want)["candidates"]
close
close()

Close the connection

Source code in src/pysdrlib/remote/client.py
def close(self):
    """Close the connection"""
    self._c2.close()

RemoteDevice

RemoteDevice(address: str, device=None, *, id=None, timeout=DEFAULT_TIMEOUT, init_args=(), init_kwargs=None, wire=None, tx_wire='native', transport='auto', program=None, serial=None, label=None, need=None, want=None, pick=None)

Bases: Device

address: server C2 endpoint, e.g. tcp://host:5555 device: device type to open on the server (this client becomes its controller) id: id of an already hosted device to attach to (as a viewer) instead program: the name of the program you are running: the server shows it in list and its log, so others can tell who has a radio serial, label: which unit to open: the serial number, or part of the label (pysdrlib client ADDRESS list shows both). With these, device may be left out to take a unit of any driver. need, want: what the program needs (a radio that cannot is not used) and would like: dicts with freq (Hz, or a (low, high) pair), rate, bandwidth, channels, tx. The server opens the best radio that meets need (or takes over a free hosted one); granted says what it can do nearest to want and need. pick: the key of one of Client.candidates: open that radio and no other (err.Busy if it has been taken since). init_args/init_kwargs: passed to the device type's constructor on the server wire: RX wire format to request when opening a device type (default: the server's, normally the device's native layout). See set_wire. tx_wire: wire format the TX stream is sent in: "native" (the device's own layout, lossless: the device quantises to it anyway, and it is several times smaller than complex64), "complex64", "int8", ... See set_tx_wire. transport: how samples reach this client. "auto": from shared memory when the server is on this machine and offers it (any number of clients then read one copy, each at its own pace), else over the socket; "zmq": always over the socket; "shm": shared memory, or err.NotSupported.

Methods:

Name Description
open

Connect to the server. For a device type: opens it on the server (args/kwargs go to the device's open)

close

Disconnect. The controller also closes the device on the server; a viewer just detaches.

detach

Disconnect without closing the hosted device (close closes it, if this client controls it). A controller

claim

Become the controller of an attached device (raises err.Busy if it has one)

release

Give up control (stops RX/TX on the server); stay attached as a viewer

refresh

Update state, CF and Fs from the server (a viewer sees what the controller does)

set_wire

Choose the RX stream's wire format for everyone watching: "native" (the device's own layout,

set_tx_wire

Choose the wire format of the TX stream this client sends (it is the controller's alone, so this is local):

get_rx_context

How the hosted radio receives on this channel (RxContext; see Device.get_rx_context). Raises

get_chains

The hosted radio's chains, from the server's frontends file (caps.chains)

set_chains

A server's chains are the operator's: its frontends file (pysdrlib server --frontends)

get_samples

All samples of the first streaming channel received since the last call. Waits up to timeout seconds

Attributes:

Name Type Description
tx_wire_name

Name of the format TX blocks are sent in right now (with "native" resolved to the device's layout)

caps

The hosted device's capabilities (fetched once per connection)

stats StreamStats

What this client has received of the first channel since start_rx: samples, dropped (lost between the

Source code in src/pysdrlib/remote/client.py
def __init__(self, address: str, device=None, *, id=None, timeout=DEFAULT_TIMEOUT, init_args=(), init_kwargs=None, wire=None, tx_wire="native",
             transport="auto", program=None, serial=None, label=None, need=None, want=None, pick=None):
    """
    address: server C2 endpoint, e.g. tcp://host:5555
    device: device type to open on the server (this client becomes its controller)
    id: id of an already hosted device to attach to (as a viewer) instead
    program: the name of the program you are running: the server shows it in `list` and its log, so others can tell who
          has a radio
    serial, label: which unit to open: the serial number, or part of the label (`pysdrlib client ADDRESS list` shows both).
          With these, `device` may be left out to take a unit of any driver.
    need, want: what the program needs (a radio that cannot is not used) and would like: dicts with `freq` (Hz, or a
          (low, high) pair), `rate`, `bandwidth`, `channels`, `tx`. The server opens the best radio that meets `need`
          (or takes over a free hosted one); `granted` says what it can do nearest to `want` and `need`.
    pick: the `key` of one of `Client.candidates`: open that radio and no other (`err.Busy` if it has been taken since).
    init_args/init_kwargs: passed to the device type's constructor on the server
    wire: RX wire format to request when opening a device type (default: the server's, normally the
          device's native layout). See `set_wire`.
    tx_wire: wire format the TX stream is sent in: "native" (the device's own layout, lossless: the device
          quantises to it anyway, and it is several times smaller than complex64), "complex64", "int8", ...
          See `set_tx_wire`.
    transport: how samples reach this client. "auto": from shared memory when the server is on this machine and
          offers it (any number of clients then read one copy, each at its own pace), else over the socket; "zmq":
          always over the socket; "shm": shared memory, or `err.NotSupported`.
    """
    choosing = any(v is not None for v in (serial, label, need, want, pick))
    if id is not None and (device is not None or choosing):
        raise ValueError("`id` attaches to a hosted device: it takes no `device`, `serial`, `label`, `need` or `want`")
    if id is None and device is None and not choosing:
        raise ValueError("give one of `device` (a type to open), `id` (a hosted device), or `serial`/`label`/`need`/`want` to choose a radio")
    self.program = program
    self.granted = None         # what the radio the server chose can do nearest to `want` (see `need`, `want`)
    self._choice = {k: v for k, v in (("serial", serial), ("label", label), ("need", choose.normalize(need, "need") or None),
                                      ("want", choose.normalize(want, "want") or None), ("pick", pick)) if v is not None}
    self.log = logger.new(f"device.{type(self).__name__}")
    self.device = None
    self.state = {"open": False, "rx": False, "tx": False}
    self._cf = None
    self._Fs = None

    self.address = address
    self.timeout = timeout
    self.type = device
    self.id = id
    self._target = (device, id)   # what each `open` connects to (a closed device opens the same way again)
    self.token = None
    self.capabilities = None
    self.server_version = None  # the server's pysdrlib (its hello)
    self.dropped_blocks = 0     # RX blocks lost between server and here (detected by sequence number)
    self._init = (list(init_args), dict(init_kwargs or {}))
    self._wire = wire
    protocol.wire_format(tx_wire) if tx_wire != "native" else None    # validate now
    self.tx_wire = tx_wire      # format of the TX stream we send ("native": the device's own layout)
    self.wire = None            # format of the RX stream, e.g. "int8" (see `refresh`)
    if transport not in ("auto", "zmq", "shm"):
        raise ValueError(f"transport is 'auto', 'zmq' or 'shm', not {transport!r}")
    self.transport = transport
    self._endpoints = None      # the sockets the server handed out (kept for a later claim)
    self._lost = {}             # channel -> samples lost between the server and here since start_rx
    self._rx_lock = threading.RLock()   # guards the receive state below (see `_rx_synced`)
    self._shm_mode = False      # samples come from shared memory (see `_subscribe`)
    self._rings = {}            # channel -> shm.ShmReader of the stream's ring
    self._retired = collections.deque(maxlen=32)   # names of the rings closed (an old stream's)
    self._pos = {}              # channel -> stream index of the next sample to read from its ring
    self._from_start = False    # read the rings from their first sample: of a stream this client saw (or made) start
    self._streams = 0           # counts the streams seen to start (a relay's server follows it)
    self._gen = None            # the server's number of the stream being received (None: it has not said)
    self._heard = False         # a block or notice has arrived on this connection
    self._stale = None          # blocks dropped so far while those of the last stream may still arrive (None: none may)
    self._closing = False       # `_teardown` is under way: no more reads
    self._host = _host_of(address)
    self._c2 = None
    self._ctrl = None
    self._sub = None
    self._last_seq = None
    self._bufs = {}             # channel -> deque of [index of first sample, samples] received, not yet read
    self._changes_seen = set()  # `seq` of the stream changes applied (see `_apply_change`)
    self._rx_last = {}          # channel -> index after the last sample received
    self._rx_time = None        # time.monotonic() of the last block
    self._idle_since = None     # time.monotonic() a read first found nothing, with no block yet (see `_rx_idle`)
    self._probed = 0.0          # time.monotonic() the server was last asked how the device is
    self.stall_timeout = STALL_TIMEOUT   # seconds without samples before `read` asks the server why; None: never
    self._tx = None             # PUSH socket for TX blocks (the controller's)
    self._tx_lock = threading.Lock()   # a ZeroMQ socket is not closed under a thread that is sending on it
    self._aligning = threading.local()   # this thread's multi-channel read: the stream it is lining up (see `_read_aligned`)
    self._tx_seq = 0
    self._beat = None
    self._beat_stop = threading.Event()
    self._init_generic()
    self._remote_caps = None
tx_wire_name property
tx_wire_name

Name of the format TX blocks are sent in right now (with "native" resolved to the device's layout)

caps property
caps

The hosted device's capabilities (fetched once per connection)

stats property
stats: StreamStats

What this client has received of the first channel since start_rx: samples, dropped (lost between the server and here: blocks the socket dropped, or samples a slow reader was lapped for in shared memory) and age (since the server last wrote). missing and stalls are counted by the server's own device, not here

open
open(*args, **kwargs)

Connect to the server. For a device type: opens it on the server (args/kwargs go to the device's open)

Source code in src/pysdrlib/remote/client.py
def open(self, *args, **kwargs):
    """Connect to the server. For a device type: opens it on the server (args/kwargs go to the device's `open`)"""
    if self.state["open"]:
        self.log.warning("Device is already open!")
        return
    self.type, self.id = self._target
    self.capabilities = None
    self._gen, self._heard, self._stale, self._closing = None, False, None, False
    self._changes_seen.clear()   # (another device numbers its changes from the start again)
    self._drop_received()
    self._c2 = _Channel(self.address, self.timeout)
    try:
        hello = _hello(self._c2, self.address)
        lease, self.server_version = hello["lease"], hello.get("pysdrlib")
        if self.id is None:
            res = self._c2.request("open", type=self.type, args=list(args), kwargs=kwargs,
                                   init_args=self._init[0], init_kwargs=self._init[1], wire=self._wire,
                                   program=self.program, **self._choice)
            self.token = res["token"]
            self.id = res["device"]
            self.type = res.get("type", self.type)
            self.granted = res.get("granted")
        else:
            if args or kwargs:
                raise ValueError("an attached device is already open; open() takes no arguments")
            res = self._c2.request("attach", device=self.id, program=self.program)
        self._endpoints = res["endpoints"]
        self._connect(res["endpoints"])
        self.capabilities = self._ctrl.request("capabilities")
        self._subscribe()
        self.state["open"] = True
        self.refresh()
    except BaseException:
        if self.token and self._target[1] is None:   # opened for us: don't leave it running with nobody to close it
            try:
                self._c2.request("close", device=self.id, token=self.token)
            except Exception as e:
                self.log.warning("could not close %s after failing to connect to it: %s", self.id, e)
        self._teardown()
        self.state.update(open=False, rx=False, tx=False)
        self.type, self.id = self._target
        raise
    if self.token:
        self._start_heartbeat(lease)
close
close()

Disconnect. The controller also closes the device on the server; a viewer just detaches.

Source code in src/pysdrlib/remote/client.py
def close(self):
    """Disconnect. The controller also closes the device on the server; a viewer just detaches."""
    self._ensure_open("close")
    try:
        if self.token:
            try:
                self._c2.request("close", device=self.id, token=self.token)
            except (err.NotController, err.NoDevice) as e:   # it isn't ours to close any more
                self.log.warning("%s was not closed on the server: %s", self.id, e)
    finally:
        self._teardown()
        self.state.update(open=False, rx=False, tx=False)
detach
detach()

Disconnect without closing the hosted device (close closes it, if this client controls it). A controller gives up control first, which stops what it had running, as release does

Source code in src/pysdrlib/remote/client.py
def detach(self):
    """Disconnect without closing the hosted device (`close` closes it, if this client controls it). A controller
    gives up control first, which stops what it had running, as `release` does"""
    self._ensure_open("detach")
    try:
        if self.token:
            self.release()
    finally:
        self._teardown()
        self.state.update(open=False, rx=False, tx=False)
claim
claim()

Become the controller of an attached device (raises err.Busy if it has one)

Source code in src/pysdrlib/remote/client.py
def claim(self):
    """Become the controller of an attached device (raises `err.Busy` if it has one)"""
    self._ensure_open("claim")
    if self._still_controls():
        return
    res = self._c2.request("claim", device=self.id, program=self.program)
    self.token = res["token"]
    self._connect_tx()
    self._start_heartbeat(res["lease"])
release
release()

Give up control (stops RX/TX on the server); stay attached as a viewer

Source code in src/pysdrlib/remote/client.py
def release(self):
    """Give up control (stops RX/TX on the server); stay attached as a viewer"""
    self._ensure_open("release")
    if not self.token:
        return
    token, self.token = self.token, None
    self._beat_stop.set()
    try:
        self._c2.request("release", device=self.id, token=token)
    except (err.NotController, err.NoDevice) as e:   # lost already
        self.log.warning("%s: nothing to release: %s", self.id, e)
    self._close_tx()   # only the controller transmits
    self.refresh()
refresh
refresh()

Update state, CF and Fs from the server (a viewer sees what the controller does)

Source code in src/pysdrlib/remote/client.py
def refresh(self):
    """Update `state`, `CF` and `Fs` from the server (a viewer sees what the controller does)"""
    self._ensure_open("refresh")
    status = self._control().request("status")
    self.state.update(status["state"])
    self._cf = status["cf"]
    self._Fs = status["Fs"]
    self.wire = status["wire"]
    self._rx_channels = tuple(status["rx_channels"])
    self._tx_channels = tuple(status["tx_channels"])
    return status
set_wire
set_wire(fmt='native')

Choose the RX stream's wire format for everyone watching: "native" (the device's own layout, lossless), "complex64", "int8", "int16", ... Narrower than the device's native is lossy. Controller only. Returns the format name.

Source code in src/pysdrlib/remote/client.py
def set_wire(self, fmt="native"):
    """Choose the RX stream's wire format for everyone watching: "native" (the device's own layout,
    lossless), "complex64", "int8", "int16", ... Narrower than the device's native is lossy.
    Controller only. Returns the format name."""
    self._ensure_open("set_wire")
    self.wire = self._control().request("set_wire", format=fmt, token=self.token)
    return self.wire
set_tx_wire
set_tx_wire(fmt='native')

Choose the wire format of the TX stream this client sends (it is the controller's alone, so this is local): "native" (the device's own layout, lossless), "complex64", "int8", "int16", ... Narrower than the device's native is lossy. Returns the format name.

Source code in src/pysdrlib/remote/client.py
def set_tx_wire(self, fmt="native"):
    """Choose the wire format of the TX stream this client sends (it is the controller's alone, so this is local):
    "native" (the device's own layout, lossless), "complex64", "int8", "int16", ... Narrower than the device's
    native is lossy. Returns the format name."""
    if fmt != "native":
        protocol.wire_format(fmt)
    self.tx_wire = fmt
    return self.tx_wire_name
get_rx_context
get_rx_context(channel=0)

How the hosted radio receives on this channel (RxContext; see Device.get_rx_context). Raises err.NotSupported from a server whose pysdrlib is older than 0.5.1

Source code in src/pysdrlib/remote/client.py
def get_rx_context(self, channel=0):
    """How the hosted radio receives on this channel (`RxContext`; see `Device.get_rx_context`). Raises
    `err.NotSupported` from a server whose pysdrlib is older than 0.5.1"""
    return RxContext.from_json(self._call("get_rx_context", channel))
get_chains
get_chains()

The hosted radio's chains, from the server's frontends file (caps.chains)

Source code in src/pysdrlib/remote/client.py
def get_chains(self):
    """The hosted radio's chains, from the server's frontends file (`caps.chains`)"""
    return list(self.caps.chains)
set_chains
set_chains(chains)

A server's chains are the operator's: its frontends file (pysdrlib server --frontends)

Source code in src/pysdrlib/remote/client.py
def set_chains(self, chains):
    """A server's chains are the operator's: its frontends file (`pysdrlib server --frontends`)"""
    raise err.NotSupported("a server's chains are in its frontends file (pysdrlib server --frontends FILE)")
get_samples
get_samples(timeout=0.0) -> np.ndarray

All samples of the first streaming channel received since the last call. Waits up to timeout seconds for the first block. See read for exact counts, several channels and stream metadata

Source code in src/pysdrlib/remote/client.py
@_rx_synced
def get_samples(self, timeout=0.0) -> np.ndarray:
    """All samples of the first streaming channel received since the last call. Waits up to `timeout` seconds
    for the first block. See `read` for exact counts, several channels and stream metadata"""
    self._ensure_open("get_samples")
    channel = self._rx_channels[0]
    if not self._queued(channel):
        self._pull(timeout)
    self._pull(0)
    if self._shm_mode:
        x = self._take_all(channel)
        if len(x):   # handed out: the next `read` follows on, rather than reporting them lost
            self._rx_next[channel] = self._pos[channel]
        return x
    blocks = self._bufs.pop(channel, ())
    if not blocks:
        return np.empty(0, dtype=np.complex64)
    self._rx_next[channel] = blocks[-1][0] + len(blocks[-1][1])
    return blocks[0][1] if len(blocks) == 1 else np.concatenate([x for _, x in blocks])

discovery

Finding servers on the local network with mDNS / DNS-SD (needs zeroconf: pip install pysdrlib[remote])

A server started with advertise=True (pysdrlib server --advertise) announces itself as a _pysdrlib._tcp service; discover() lists the ones that answer. The announcement only says where a server is (and its protocol version): ask it what it has with Client(address).list() as usual. mDNS does not cross routers, so a server on another subnet or over a VPN still has to be given by address.

Classes:

Name Description
NotAdvertisable

The server's endpoint is not one other machines could use (ipc://, loopback, or a host that does not resolve)

Advertiser

Announces a server's C2 endpoint on the local network until stop

Functions:

Name Description
discover

Servers announcing themselves on the local network, after listening for timeout seconds.

rank

Ask each of servers (from discover) for its radios that fit the request, without opening any.

NotAdvertisable

Bases: ValueError

The server's endpoint is not one other machines could use (ipc://, loopback, or a host that does not resolve)

Advertiser

Advertiser(endpoint, name=None, kind='server')

Announces a server's C2 endpoint on the local network until stop

endpoint: the bound C2 endpoint (Server.endpoint). name: the instance name shown by discover (default: the host name, with " relay" for a relay; a name already taken gets a number added). kind: "server" or "relay".

Methods:

Name Description
stop

Withdraw the announcement (clients see the server go at once) and close

Attributes:

Name Type Description
name

The instance name in use (it may differ from the one asked for when that was taken)

Source code in src/pysdrlib/remote/discovery.py
def __init__(self, endpoint, name=None, kind="server"):
    """endpoint: the bound C2 endpoint (`Server.endpoint`). name: the instance name shown by `discover` (default: the
    host name, with " relay" for a relay; a name already taken gets a number added). kind: "server" or "relay"."""
    zc = _zeroconf()
    self.log = logger.new("remote.discovery")
    self.addresses, self.port = _addresses(endpoint)
    from .. import __version__
    name = (name or (_short_host() + (" relay" if kind == "relay" else ""))).replace(".", "-")
    self.info = zc.ServiceInfo(
        SERVICE, f"{name}.{SERVICE}",
        addresses=[socket.inet_aton(a) for a in self.addresses], port=self.port,
        properties={"proto": str(protocol.VERSION), "ver": __version__, "kind": kind},
        server=f"{_short_host()}.local.")
    self._zc = None
name property
name

The instance name in use (it may differ from the one asked for when that was taken)

stop
stop()

Withdraw the announcement (clients see the server go at once) and close

Source code in src/pysdrlib/remote/discovery.py
def stop(self):
    """Withdraw the announcement (clients see the server go at once) and close"""
    if self._zc is not None:
        try:
            self._zc.unregister_service(self.info)
        finally:
            self._zc.close()
            self._zc = None

discover

discover(timeout=2.0, all_versions=False) -> list[dict]

Servers announcing themselves on the local network, after listening for timeout seconds.

Each is a dict: name, address (a C2 endpoint to give Client or pysdrlib.connect: one on a network this machine is on, when there is one), addresses (every endpoint it announced, for a server on several networks), host, kind ("server" or "relay"), proto and version. Servers speaking another protocol version than this pysdrlib are left out unless all_versions.

Source code in src/pysdrlib/remote/discovery.py
def discover(timeout=2.0, all_versions=False) -> list[dict]:
    """Servers announcing themselves on the local network, after listening for `timeout` seconds.

    Each is a dict: `name`, `address` (a C2 endpoint to give `Client` or `pysdrlib.connect`: one on a network this machine
    is on, when there is one), `addresses` (every endpoint it announced, for a server on several networks), `host`, `kind` ("server" or "relay"), `proto` and `version`.
    Servers speaking another protocol version than this pysdrlib are left out unless `all_versions`.
    """
    zc = _zeroconf()
    names = set()

    def changed(zeroconf, service_type, name, state_change):
        if state_change is zc.ServiceStateChange.Added:
            names.add(name)
        elif state_change is zc.ServiceStateChange.Removed:
            names.discard(name)

    found = []
    with zc.Zeroconf(interfaces=zc.InterfaceChoice.All, ip_version=zc.IPVersion.V4Only) as z:
        browser = zc.ServiceBrowser(z, SERVICE, handlers=[changed])
        try:
            time.sleep(timeout)
        finally:
            browser.cancel()
        for name in sorted(names):
            info = z.get_service_info(SERVICE, name, timeout=int(max(timeout, 0.5) * 1000))
            if info is None or not info.port:
                continue
            props = {k.decode(errors="replace"): (v.decode(errors="replace") if v is not None else None)
                     for k, v in info.properties.items()}
            try:
                proto = int(props.get("proto") or 0)
            except ValueError:
                proto = 0
            if proto != protocol.VERSION and not all_versions:
                continue
            addresses = [f"tcp://{a}:{info.port}" for a in _reachable_first(info.parsed_addresses())]
            if not addresses:
                continue
            found.append({"name": name[:-len(SERVICE) - 1], "address": addresses[0], "addresses": addresses,
                          "host": (info.server or "").rstrip("."), "kind": props.get("kind") or "server",
                          "proto": proto, "version": props.get("ver")})
    return found

rank

rank(servers, device=None, serial=None, label=None, need=None, want=None, timeout=5.0)

Ask each of servers (from discover) for its radios that fit the request, without opening any.

-> (choices, hosting, reasons): choices every radio that fits on any server, best first (by choose.rank, then one attached before one a client left open, then one on this machine, which can share samples through shared memory), as dicts of its server and the candidate (from Client.candidates: open it with its key as pick). A server too old to be asked, or that has no device attached but can open one (as a plain connect(address, device) would), is there once with candidate None, after the rest; hosting the servers that host a device whose id is device; reasons why each other server was left out, as text.

Source code in src/pysdrlib/remote/discovery.py
def rank(servers, device=None, serial=None, label=None, need=None, want=None, timeout=5.0):
    """Ask each of `servers` (from `discover`) for its radios that fit the request, without opening any.

    -> (choices, hosting, reasons): `choices` every radio that fits on any server, best first (by `choose.rank`, then one
    attached before one a client left open, then one on this machine, which can share samples through shared memory), as
    dicts of its server and the `candidate` (from `Client.candidates`: open it with its `key` as `pick`). A server too old
    to be asked, or that has no `device` attached but can open one (as a plain `connect(address, device)` would), is there
    once with `candidate` None, after the rest; `hosting` the
    servers that host a device whose id is `device`; `reasons` why each other server was left out, as text.
    """
    from .client import Client
    ranked, hosting, reasons = [], [], []
    for i, server in enumerate(servers):
        where = f"{server['address']} ({server['name']})"
        try:
            with Client(server["address"], timeout) as c:
                if device is not None and device in {d["id"] for d in c.list()}:
                    hosting.append(server)
                    continue
                if device is not None and device not in c.types():
                    reasons.append(f"{where}: cannot open {device!r}")
                    continue
                choosing = any(v is not None for v in (serial, label, need, want))
                try:
                    offered = c.candidates(device, serial, label, need, want)
                except err.RemoteError as e:      # a server from before `choose`: it may still have one
                    if "unknown op" not in str(e):
                        raise
                    offered = [None]
                except err.NoDevice:
                    if choosing or device is None:
                        raise
                    offered = [None]    # none of the type attached, but it can open one (a driver nothing finds, like sim)
        except err.NoDevice as e:
            reasons.append(f"{where}: {e}")
            continue
        except (err._Error, TimeoutError, OSError) as e:
            reasons.append(f"{where}: {type(e).__name__}: {e}")
            continue
        local = _is_local(server["address"])
        for j, cand in enumerate(offered):
            key = (1,) if cand is None else (0, *cand["rank"], cand["kind"] == "hosted")
            ranked.append((key, not local, i, j, {**server, "candidate": cand}))
    ranked.sort(key=lambda r: r[:4])
    return [r[4] for r in ranked], hosting, reasons

frontends

What sits between each radio of a server and the air: LNBs, converters, antennas

An operator describes it once, in a JSON file (TOML also works) given to pysdrlib server --frontends FILE, and clients just ask for the over-the-air frequency they want (see choose, pysdrlib.base.caps.Chain):

{
  "antenna": {                              // antenna standards of your own (ANT500 is built in); usable/optimal: [low, high] Hz
    "MYLPDA": {"optimal": [[430e6, 440e6]],
               "kind": "lpda",                // whip, dipole, biconical, lpda, yagi, dish, horn, discone, patch, helical, loop, or any text
               "size": [0.5, 0.9],            // metres: what the kind measures (boom length for lpda, diameter for dish)
               "impedance": 50}               // ohms
  },
  "radio": [{                               // picked by any of driver, serial and label (a part of it, case ignored); first match wins
    "serial": "0123ABCD",
    "chain": [{
      "direction": "rx",                    // rx or tx
      "port": "RX2",                        // the radio's antenna port it is behind (leave out: any port)
      // "channel": 1,                      // the radio's channel it is on (leave out: any): ports of one name on two channels
      // "polarization": "H",               // what the feed takes in: H, V, RHCP or LHCP (leave out: not said)
      "antenna": "ANT500",
      "lo": 9.75e9,                         // external LO, Hz (leave out: none): the radio tunes RF - lo, as behind an LNB
      // "lo_accuracy": 25e3,               // how well lo is known, Hz (a standard error; a measured LO's)
      "name": "universal LNB"
      // "invert": true                     // the LO is above the signal instead: radio tunes lo - RF, spectrum mirrored
      // "usable": [[10.7e9, 12.75e9]], "optimal": [[11e9, 12e9]]    // override the antenna's
    }]
  }]
}

(Comments and e notation are for reading here: JSON proper has neither, so write 9750000000 and no comments.) The file is read as JSON, unless its name ends in .toml; one that is not valid JSON is tried as TOML, with the same keys ([antenna.MYLPDA], [[radio]], [[radio.chain]]).

Classes:

Name Description
Frontends

The chains each radio has, by what picks the radio out. radios: [({driver/serial/label: text}, [Chain])]

Functions:

Name Description
parse

A Frontends from what json or tomllib read (registers the antennas it defines). Raises ValueError saying what is wrong

load

Read a frontends file: JSON, or TOML when the name ends in .toml or it is not valid JSON. Raises ValueError (with the

Frontends

Frontends(radios=None)

The chains each radio has, by what picks the radio out. radios: [({driver/serial/label: text}, [Chain])]

Methods:

Name Description
chains_for

The chains of the first radio entry that matches this radio ([] when none does)

apply

caps with the chains this radio has (itself, if it has none)

Source code in src/pysdrlib/remote/frontends.py
def __init__(self, radios=None):
    self.radios = list(radios or [])
chains_for
chains_for(driver, serial=None, label=None)

The chains of the first radio entry that matches this radio ([] when none does)

Source code in src/pysdrlib/remote/frontends.py
def chains_for(self, driver, serial=None, label=None):
    """The chains of the first radio entry that matches this radio ([] when none does)"""
    for match, chains in self.radios:
        if "driver" in match and match["driver"] != driver:
            continue
        if "serial" in match and str(serial) != str(match["serial"]):
            continue
        if "label" in match and (label is None or match["label"].lower() not in str(label).lower()):
            continue
        return chains
    return []
apply
apply(caps, driver, serial=None, label=None)

caps with the chains this radio has (itself, if it has none)

Source code in src/pysdrlib/remote/frontends.py
def apply(self, caps, driver, serial=None, label=None):
    """`caps` with the chains this radio has (itself, if it has none)"""
    chains = self.chains_for(driver, serial, label)
    if caps is None or not chains:
        return caps
    out = copy.copy(caps)
    out.chains = list(chains)
    return out

parse

parse(data) -> Frontends

A Frontends from what json or tomllib read (registers the antennas it defines). Raises ValueError saying what is wrong

Source code in src/pysdrlib/remote/frontends.py
def parse(data) -> Frontends:
    """A `Frontends` from what `json` or `tomllib` read (registers the antennas it defines). Raises ValueError saying what is wrong"""
    _check("the file", data, {"antenna", "radio"})
    for name, table in (data.get("antenna") or {}).items():
        _check(f"[antenna.{name}]", table, _ANTENNA_KEYS)
        if "size" in table and "length" in table:
            raise ValueError(f"[antenna.{name}] has both 'size' and its old name 'length': keep one")
        size = table.get("size", table.get("length"))
        try:
            _antennas.register(_antennas.Antenna(
                name, usable=_ranges(f"antenna.{name}.usable", table.get("usable", [])),
                optimal=_ranges(f"antenna.{name}.optimal", table.get("optimal", [])), doc=str(table.get("doc", "")),
                kind=str(table["kind"]) if "kind" in table else None,
                size=tuple(float(v) for v in size) if size is not None else None,
                impedance=float(table["impedance"]) if "impedance" in table else None), replace=True)
        except (TypeError, ValueError) as e:
            raise ValueError(f"[antenna.{name}]: {e}") from None
    radios = []
    for i, radio in enumerate(data.get("radio") or []):
        where = f"[[radio]] #{i + 1}"
        _check(where, radio, _RADIO_KEYS)
        match = {k: str(radio[k]) for k in ("driver", "serial", "label") if k in radio}
        if not match:
            raise ValueError(f"{where} needs a driver, serial or label to say which radio it is")
        chains = []
        for j, c in enumerate(radio.get("chain") or []):
            cwhere = f"{where} chain #{j + 1}"
            _check(cwhere, c, _CHAIN_KEYS)
            if c.get("antenna") and _antennas.find(c["antenna"]) is None:
                _antennas.get(c["antenna"])    # raises, naming the known ones
            try:
                chains.append(_caps.Chain(direction=c.get("direction", "rx"), port=c.get("port"), antenna=c.get("antenna"),
                                          lo=float(c.get("lo", 0.0)), invert=bool(c.get("invert", False)),
                                          lo_accuracy=float(c["lo_accuracy"]) if "lo_accuracy" in c else None,
                                          usable=_ranges(f"{cwhere} usable", c.get("usable", [])),
                                          optimal=_ranges(f"{cwhere} optimal", c.get("optimal", [])), name=str(c.get("name", "")),
                                          channel=c.get("channel"), polarization=c.get("polarization")))
            except ValueError as e:
                raise ValueError(f"{cwhere}: {e}") from None
        radios.append((match, chains))
    return Frontends(radios)

load

load(path) -> Frontends

Read a frontends file: JSON, or TOML when the name ends in .toml or it is not valid JSON. Raises ValueError (with the file's name) when it cannot be read or is wrong

Source code in src/pysdrlib/remote/frontends.py
def load(path) -> Frontends:
    """Read a frontends file: JSON, or TOML when the name ends in `.toml` or it is not valid JSON. Raises ValueError (with the
    file's name) when it cannot be read or is wrong"""
    try:
        with open(path, "rb") as f:
            raw = f.read()
        if str(path).lower().endswith(".toml"):
            data = tomllib.loads(raw.decode())
        else:
            try:
                data = json.loads(raw)
            except ValueError as first:      # not JSON: TOML, and if that is not either, say why it is not JSON (the default)
                try:
                    data = tomllib.loads(raw.decode())
                except (tomllib.TOMLDecodeError, UnicodeDecodeError):
                    raise ValueError(f"not valid JSON ({first}), nor TOML") from None
        return parse(data)
    except (OSError, tomllib.TOMLDecodeError, ValueError, UnicodeDecodeError) as e:
        raise ValueError(f"{path}: {e}") from None

protocol

pysdrlib remote protocol.

Three kinds of socket, all ZeroMQ:

C2 (server -> ROUTER, client -> DEALER)      lifecycle: list / open / attach / claim / release / close / ping
device control (ROUTER <-> DEALER)           one per hosted device: capabilities, state, method calls
device RX stream (PUB -> SUB)                one per hosted device: sample blocks, every channel the device streams
                                             (or, for a client on the same host, notices of blocks in shared memory)
device TX stream (PUSH -> PULL)              one per hosted device: sample blocks to transmit (controller only)

Requests and replies on the C2 and control sockets are single-frame JSON:

request  {"id": int, "op": str, ...op specific}
reply    {"id": int, "ok": true,  "result": ...}
         {"id": int, "ok": false, "error": {"type": str, "msg": str, "reason"?: str}}   (reason: err.NoDevice's)

Sample blocks are 3 frames: [topic, header, payload]. topic is the device id (SUB prefix filter) on the RX stream and the controller's token on the TX stream, header is HEADER (below) and payload is nsamples interleaved I/Q samples in the layout the header describes: a convert.SampleFormat. The header also says which channel the block is and the stream index of its first sample (samples since start_rx), so a client keeps channels apart and aligned, and sees where samples were lost. By default that is the device's own native layout (8-bit for a HackRF, ...), which is lossless and several times smaller than complex64; clients always hand the caller complex64. The same goes for the TX stream: the controller sends blocks in the device's native layout by default (or any other wire format) and the server decodes whatever the header says. The format may change between blocks (the controller can switch it), so it is read from every header.

A client on the same machine as the server can take the samples from shared memory instead (pysdrlib.shm.ring): per streaming channel the server keeps a ring of complex64 samples in a shared-memory segment that any number of clients read, each at its own pace. They subscribe to the topic shm:<device id> rather than the device id, and get a notice for each block published: 3 frames like a block, with FLAG_SHM in the header (channel, index of the first sample, count) and the name of the segment as the payload (empty: the server could not make one, so use the other topic). The server encodes and sends full blocks only while someone subscribes to the device id.

Changes to the stream (a retune, a new gain, a flush) go to both topics as events: FLAG_EVENT in the header and a JSON payload {"seq": n, "events": [[index, kind, value, channel], ...], "discard": index, "gen": g}, published before any sample from after the change. gen numbers the device's streams. A new stream (indices from 0) begins with an event that also has "start": {"channels": [...], "freq": [[channel, Hz], ...], "rate": [[channel, S/s], ...]}, published before its first sample and sent in the reply to the start_rx that made it: a client then drops what it knew of the last stream, ignores changes of an earlier gen, and drops blocks and notices that were still on their way. gen and start are additions to protocol 4: a 0.5.2 client ignores them, and from a 0.5.2 server, which sends neither, a client tells a new stream by its indices going back. A call of start_rx says "keeps_stream": true if the client keeps what it has received when the device is receiving already; for one that doesn't (0.5.2), the server then moves the stream to new rings. The reply to the call that made the change carries it too ("stream"), so the caller has it before its next read. A client applies each seq once, as a local device would, so read(meta=True) reports retunes inside a block and set_rx_freq(..., flush=True) skips what came before. Blocks and notices are numbered separately, each from 0.

Endpoints handed out by the server may contain {host}, which the client replaces with the host it used to reach the C2 socket (so a server bound to 0.0.0.0 doesn't need to know its own address).

Functions:

Name Description
mismatch

Why this side (protocol version, pysdrlib package) and peer ("server" or "client", running protocol

jsonable

json.dumps default: numpy scalars/arrays, a few containers, and objects with a json()

pack

JSON-encode a request or reply message

unpack

Decode a message. Raises err.ProtocolError if it isn't a JSON object

ok

A success reply to request req_id. stream: the change the request made to the receive stream, if any (the

fail

An error reply to request req_id; the client re-raises it as the same pysdrlib error type

raise_error

Raise the exception described by a reply's error

wire_format

Name -> SampleFormat, e.g. "int8".

wire_name

SampleFormat -> its wire name, or its description if it has none

resolve_wire

The format to publish device's samples in: "native" is its own SAMPLE_FORMAT (complex64 if it has none)

pack_block

complex64 samples -> (header bytes, payload buffer) in wire format fmt

pack_notice

-> (header bytes, payload bytes): a block of count samples from stream index index is in the shared-memory

unpack_notice

-> (seq, timestamp, channel, index, count, segment name) of a notice; err.ProtocolError if it isn't one

change

A change to the receive stream (see the module docs): events are (index, kind, value, channel) as Device

pack_event

-> (header bytes, payload bytes): a change on the RX stream. Sent on both topics, ahead of any sample published

is_event

Whether a message on the RX stream is an event (pack_event) rather than samples or a notice

unpack_event

The change an event message carries

unpack_block

-> (seq, timestamp, complex64 samples, channel, index of the first sample or None)

is_readonly

Methods a viewer (no controller token) may call

mismatch

mismatch(version, package, peer_version, peer_package, peer)

Why this side (protocol version, pysdrlib package) and peer ("server" or "client", running protocol peer_version and pysdrlib peer_package) can't talk, naming the one to update; None when they can

Source code in src/pysdrlib/remote/protocol.py
def mismatch(version, package, peer_version, peer_package, peer):
    """Why this side (protocol `version`, pysdrlib `package`) and `peer` ("server" or "client", running protocol
    `peer_version` and pysdrlib `peer_package`) can't talk, naming the one to update; None when they can"""
    if peer_version == version:
        return None
    me = "client" if peer == "server" else "server"
    older = peer if peer_version is None or (isinstance(peer_version, int) and peer_version < version) else me
    return (f"the {peer} runs pysdrlib {peer_package or '(an older version)'} (protocol {peer_version}) and the {me} "
            f"pysdrlib {package} (protocol {version}): update the {older} (pip install -U pysdrlib)")

jsonable

jsonable(obj)

json.dumps default: numpy scalars/arrays, a few containers, and objects with a json()

Source code in src/pysdrlib/remote/protocol.py
def jsonable(obj):
    """json.dumps default: numpy scalars/arrays, a few containers, and objects with a `json()`"""
    if isinstance(obj, np.generic):
        return obj.item()
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    if isinstance(obj, (set, frozenset, tuple)):
        return list(obj)
    if callable(getattr(obj, "json", None)):   # RxContext, caps.Chain...: their own plain form
        return obj.json()
    raise TypeError(f"{type(obj).__name__} is not JSON serializable")

pack

pack(msg: dict) -> bytes

JSON-encode a request or reply message

Source code in src/pysdrlib/remote/protocol.py
def pack(msg: dict) -> bytes:
    """JSON-encode a request or reply message"""
    return json.dumps(msg, default=jsonable, separators=(",", ":")).encode()

unpack

unpack(data: bytes) -> dict

Decode a message. Raises err.ProtocolError if it isn't a JSON object

Source code in src/pysdrlib/remote/protocol.py
def unpack(data: bytes) -> dict:
    """Decode a message. Raises `err.ProtocolError` if it isn't a JSON object"""
    try:
        msg = json.loads(data)
    except ValueError as e:
        raise err.ProtocolError(f"invalid message: {e}") from None
    if not isinstance(msg, dict):
        raise err.ProtocolError("message must be an object")
    return msg

ok

ok(req_id, result=None, stream=None) -> bytes

A success reply to request req_id. stream: the change the request made to the receive stream, if any (the caller applies it before its next read, rather than wait for it on the stream)

Source code in src/pysdrlib/remote/protocol.py
def ok(req_id, result=None, stream=None) -> bytes:
    """A success reply to request `req_id`. stream: the `change` the request made to the receive stream, if any (the
    caller applies it before its next read, rather than wait for it on the stream)"""
    msg = {"id": req_id, "ok": True, "result": result}
    if stream is not None:
        msg["stream"] = stream
    return pack(msg)

fail

fail(req_id, exc: BaseException) -> bytes

An error reply to request req_id; the client re-raises it as the same pysdrlib error type

Source code in src/pysdrlib/remote/protocol.py
def fail(req_id, exc: BaseException) -> bytes:
    """An error reply to request `req_id`; the client re-raises it as the same pysdrlib error type"""
    error = {"type": type(exc).__name__, "msg": str(exc)}
    if getattr(exc, "reason", None) is not None:   # err.NoDevice's
        error["reason"] = exc.reason
    try:
        return pack({"id": req_id, "ok": False, "error": error})
    except (TypeError, ValueError, RecursionError):   # a request id that cannot be sent back
        return pack({"id": None, "ok": False, "error": error})

raise_error

raise_error(error: dict)

Raise the exception described by a reply's error

Source code in src/pysdrlib/remote/protocol.py
def raise_error(error: dict):
    """Raise the exception described by a reply's `error`"""
    cls = _ERRORS.get(error.get("type"), err.RemoteError)
    msg = error.get("msg", "")
    if cls is err.RemoteError and error.get("type"):
        msg = f"{error['type']}: {msg}"
    exc = cls(msg)
    if error.get("reason") is not None:
        exc.reason = error["reason"]
    raise exc

wire_format

wire_format(name: str) -> convert.SampleFormat

Name -> SampleFormat, e.g. "int8".

Source code in src/pysdrlib/remote/protocol.py
def wire_format(name: str) -> convert.SampleFormat:
    """Name -> SampleFormat, e.g. "int8"."""
    try:
        return WIRE_FORMATS[name]
    except KeyError:
        raise ValueError(f"unknown wire format {name!r} (have: native, {', '.join(WIRE_FORMATS)})") from None

wire_name

wire_name(fmt: SampleFormat) -> str

SampleFormat -> its wire name, or its description if it has none

Source code in src/pysdrlib/remote/protocol.py
def wire_name(fmt: convert.SampleFormat) -> str:
    """SampleFormat -> its wire name, or its description if it has none"""
    for name, known in WIRE_FORMATS.items():
        if known == fmt:
            return name
    return str(fmt)

resolve_wire

resolve_wire(name: str, device) -> convert.SampleFormat

The format to publish device's samples in: "native" is its own SAMPLE_FORMAT (complex64 if it has none)

Source code in src/pysdrlib/remote/protocol.py
def resolve_wire(name: str, device) -> convert.SampleFormat:
    """The format to publish `device`'s samples in: "native" is its own SAMPLE_FORMAT (complex64 if it has none)"""
    if name == "native":
        return device.SAMPLE_FORMAT or convert.FLOAT32
    return wire_format(name)

pack_block

pack_block(seq: int, timestamp: float, samples: ndarray, fmt: SampleFormat = convert.FLOAT32, channel=0, index=None)

complex64 samples -> (header bytes, payload buffer) in wire format fmt

Source code in src/pysdrlib/remote/protocol.py
def pack_block(seq: int, timestamp: float, samples: np.ndarray, fmt: convert.SampleFormat = convert.FLOAT32, channel=0,
               index=None):
    """complex64 samples -> (header bytes, payload buffer) in wire format `fmt`"""
    if fmt == convert.FLOAT32:
        payload = np.ascontiguousarray(samples, dtype=COMPLEX64_LE)    # no copy for the usual complex64
    else:
        payload = fmt.from_complex64(samples)
    flags = (FLAG_PACKED if fmt.packed else 0) | (FLAG_BIG_ENDIAN if fmt.byteorder == ">" else 0)
    return HEADER.pack(VERSION, KINDS.index(fmt.kind), fmt.bits, fmt.storage, flags, int(channel), seq, timestamp,
                       len(samples), NO_INDEX if index is None else int(index)), payload

pack_notice

pack_notice(seq: int, timestamp: float, channel: int, index: int, count: int, name: str)

-> (header bytes, payload bytes): a block of count samples from stream index index is in the shared-memory segment name (see the module docs)

Source code in src/pysdrlib/remote/protocol.py
def pack_notice(seq: int, timestamp: float, channel: int, index: int, count: int, name: str):
    """-> (header bytes, payload bytes): a block of `count` samples from stream index `index` is in the shared-memory
    segment `name` (see the module docs)"""
    return HEADER.pack(VERSION, KINDS.index("float"), 32, 32, FLAG_SHM, int(channel), seq, timestamp, count, index), name.encode()

unpack_notice

unpack_notice(header: bytes, payload)

-> (seq, timestamp, channel, index, count, segment name) of a notice; err.ProtocolError if it isn't one

Source code in src/pysdrlib/remote/protocol.py
def unpack_notice(header: bytes, payload):
    """-> (seq, timestamp, channel, index, count, segment name) of a notice; `err.ProtocolError` if it isn't one"""
    if len(header) != HEADER.size:
        raise err.ProtocolError("bad notice header")
    version, _, _, _, flags, channel, seq, timestamp, count, index = HEADER.unpack(header)
    if version != VERSION or not flags & FLAG_SHM:
        raise err.ProtocolError("not a shared-memory notice")
    return seq, timestamp, channel, index, count, bytes(payload).decode()

change

change(seq: int, events, discard: int, gen=None, start=None) -> dict

A change to the receive stream (see the module docs): events are (index, kind, value, channel) as Device records them, discard the stream index before which samples are settling or flushed, seq numbers the changes of a device (a client applies each once: it may get one both in a reply and on the stream). gen: the number of the stream it changes; start: how that stream starts, in the first change of one (see the module docs)

Source code in src/pysdrlib/remote/protocol.py
def change(seq: int, events, discard: int, gen=None, start=None) -> dict:
    """A change to the receive stream (see the module docs): `events` are (index, kind, value, channel) as `Device`
    records them, `discard` the stream index before which samples are settling or flushed, `seq` numbers the changes of
    a device (a client applies each once: it may get one both in a reply and on the stream). gen: the number of the stream
    it changes; start: how that stream starts, in the first change of one (see the module docs)"""
    out = {"seq": int(seq), "events": [list(e) for e in events], "discard": int(discard)}
    if gen is not None:
        out["gen"] = int(gen)
    if start is not None:
        out["start"] = start
    return out

pack_event

pack_event(timestamp: float, change: dict)

-> (header bytes, payload bytes): a change on the RX stream. Sent on both topics, ahead of any sample published after it

Source code in src/pysdrlib/remote/protocol.py
def pack_event(timestamp: float, change: dict):
    """-> (header bytes, payload bytes): a `change` on the RX stream. Sent on both topics, ahead of any sample published
    after it"""
    return HEADER.pack(VERSION, KINDS.index("float"), 32, 32, FLAG_EVENT, 0, change["seq"], timestamp, 0,
                       change["discard"]), pack(change)

is_event

is_event(header: bytes) -> bool

Whether a message on the RX stream is an event (pack_event) rather than samples or a notice

Source code in src/pysdrlib/remote/protocol.py
def is_event(header: bytes) -> bool:
    """Whether a message on the RX stream is an event (`pack_event`) rather than samples or a notice"""
    return len(header) == HEADER.size and bool(header[4] & FLAG_EVENT)

unpack_event

unpack_event(payload) -> dict

The change an event message carries

Source code in src/pysdrlib/remote/protocol.py
def unpack_event(payload) -> dict:
    """The `change` an event message carries"""
    return unpack(bytes(payload))

unpack_block

unpack_block(header: bytes, payload)

-> (seq, timestamp, complex64 samples, channel, index of the first sample or None)

Source code in src/pysdrlib/remote/protocol.py
def unpack_block(header: bytes, payload):
    """-> (seq, timestamp, complex64 samples, channel, index of the first sample or None)"""
    if len(header) != HEADER.size:
        raise err.ProtocolError("bad block header")
    version, kind, bits, storage, flags, channel, seq, timestamp, n, index = HEADER.unpack(header)
    if version != VERSION:
        raise err.ProtocolError(f"a block of protocol {version}; this pysdrlib speaks {VERSION}: run the same "
                                "pysdrlib version on the server and the client")
    if kind >= len(KINDS):
        raise err.ProtocolError(f"unsupported block (format kind {kind})")
    try:
        fmt = convert.SampleFormat(KINDS[kind], bits, storage, bool(flags & FLAG_PACKED),
                                   ">" if flags & FLAG_BIG_ENDIAN else "<")
    except ValueError as e:
        raise err.ProtocolError(f"unsupported block format: {e}") from None
    if memoryview(payload).nbytes != n * fmt.bytes_per_sample:
        raise err.ProtocolError("block length mismatch")
    if fmt == convert.FLOAT32:
        samples = np.frombuffer(payload, dtype=COMPLEX64_LE).astype(np.complex64, copy=False)
    else:
        samples = fmt.to_complex64(payload)
    return seq, timestamp, samples, channel, None if index == NO_INDEX else index

is_readonly

is_readonly(method: str) -> bool

Methods a viewer (no controller token) may call

Source code in src/pysdrlib/remote/protocol.py
def is_readonly(method: str) -> bool:
    """Methods a viewer (no controller token) may call"""
    return method.startswith(("get_", "split_"))

server

pysdrlib server: hosts hardware SDRs for remote clients.

server = Server("tcp://0.0.0.0:5555", port_range=(6000, 6100))
server.serve_forever()          # or server.start() ... server.stop()

The C2 socket (the address given to Server) manages lifecycle and ownership. Every hosted device gets its own control socket and RX stream socket on separate ports, each served by its own threads, so a slow call on one device never blocks another. See protocol for the wire format.

Ownership: a device has at most one controller (the holder of its token) and any number of viewers. Viewers may subscribe to RX and call get_* methods. A controller that stops talking to the server for lease seconds loses control (RX/TX are stopped, the device stays open and can be claimed).

Samples reach clients two ways. A client on another machine subscribes to the device's id and gets blocks of samples over the socket. One on this machine can take them from shared memory instead (see shm), which costs the server one copy of each block however many clients there are: it keeps a ring per streaming channel and tells subscribers when it has written. The server only does the work of a way someone is using.

Classes:

Name Description
DeviceWorker

One hosted device: its control socket, RX stream socket, and ownership state

RelayWorker

A device hosted by another server, hosted here: a relay

Server

DeviceWorker

DeviceWorker(server: Server, dev_id: str, dtype: str, device, wire='native', shm=True, shm_samples=None)

One hosted device: its control socket, RX stream socket, and ownership state

Methods:

Name Description
claim

Make a new controller token the owner. Raises err.Busy if the device already has a controller

is_controller

Whether token is the current controller's

touch

Note that the controller is still there (renews its lease)

release

Drop the controller; stop streaming since nobody is left to manage it.

serial

The serial number of the radio, when the driver or the scan told us it

status

What list shows clients: id, type, name, state, frequency, sample rate, wire format and whether it is controlled.

metrics

What has passed through since the device was hosted: samples published (to how many subscribers, over the

close

Stop serving and close the hardware

Source code in src/pysdrlib/remote/server.py
def __init__(self, server: "Server", dev_id: str, dtype: str, device, wire="native", shm=True, shm_samples=None):
    self.id = dev_id
    self.type = dtype
    self.device = device
    self.log = logger.new(f"remote.worker.{dev_id}")
    self.lock = threading.RLock()           # serializes calls into the device
    self.health = "ok"                      # of its receive stream: "ok", "stalled", "lost" or "failing" (in `list`)
    self._owner_lock = threading.Lock()     # guards who controls it (never held while calling the device)
    self._last_status = None                # what `status` last saw, shown while the device is busy
    self.token = None                       # controller token, None if uncontrolled
    self.last_seen = time.monotonic()
    self.streaming = threading.Event()
    self._stop = threading.Event()
    self._seq = 0                           # numbers the blocks sent (a client sees a gap as blocks lost) ...
    self._notice_seq = 0                    # ... and, apart, the shared-memory notices
    self._sent_discard = 0                  # the device's flush point last sent to clients (see `_take_changes`)
    self._change_seq = 0                    # numbers the stream changes
    self._changes = []                      # ... taken from the device, not yet published (guarded by `lock`)
    self._starting = None                   # how a new stream starts, until a change has said so (see `_new_stream`)
    self._device_streams = getattr(device, "_streams", 0)   # streams a relay's upstream has seen start
    self._reply_stream = None               # the change the request being answered made (control thread only)
    self.wire = protocol.resolve_wire(wire, device)    # format RX blocks are published in

    self.shm_enabled = bool(shm)            # offer clients on this machine the samples in shared memory
    self._shm_samples = shm_samples         # ring capacity in samples (default: SHM_SECONDS at the device's top rate)
    self._rings = {}                        # channel -> shm.ShmWriter of the current stream
    self._stream_gen = 0                    # numbers the streams (see `_new_stream`): a new one gets new rings
    self._ring_gen = -1
    self._ring_failed = False
    self._renew_rings = False               # a client needs the stream's rings again, under new names (see `_call`)
    self._ends = {}                         # channel -> index after the last sample read of this stream
    self._subs = {}                         # topic -> subscribers, from the RX socket's subscription messages
    self._topic = dev_id.encode()
    self._shm_topic = protocol.SHM_PREFIX + self._topic

    self.tx_refused = 0                     # TX blocks dropped: not from the controller, or not transmitting
    self.hosted_at = time.monotonic()
    self.counters = dict.fromkeys(          # what passed through, since hosted (see `metrics`)
        ("rx_samples", "rx_blocks", "rx_bytes", "shm_notices", "tx_samples", "tx_blocks", "calls", "errors"), 0)
    self.ctrl = server._socket(zmq.ROUTER)
    self.rx = server._socket(zmq.XPUB)      # a PUB that also says who subscribed to what
    # VERBOSE, not VERBOSER: the socket then reports every subscribe, and an unsubscribe only when the last subscriber of
    # a topic goes. (VERBOSER reports them all, so anyone could cut off a real subscriber with a forged unsubscribe.)
    self.rx.setsockopt(zmq.XPUB_VERBOSE, 1)
    self.rx.setsockopt(zmq.SNDHWM, 64)
    self.rx.setsockopt(zmq.MAXMSGSIZE, MAX_SUBSCRIPTION_BYTES)   # all it is sent are subscriptions
    self.ctrl.setsockopt(zmq.MAXMSGSIZE, MAX_REQUEST_BYTES)
    self.tx = server._socket(zmq.PULL)
    self.tx.setsockopt(zmq.RCVHWM, 8)       # little queued here: a full device queue holds the sender back
    self.tx.setsockopt(zmq.MAXMSGSIZE, MAX_TX_BLOCK_BYTES)
    self.endpoints = {
        "ctrl": server._bind(self.ctrl, f"{dev_id}.ctrl"),
        "rx": server._bind(self.rx, f"{dev_id}.rx"),
        "tx": server._bind(self.tx, f"{dev_id}.tx"),
    }
    self.capabilities = self._capabilities()
    self._threads = [
        threading.Thread(target=self._control_loop, name=f"pysdrlib-{dev_id}-ctrl", daemon=True),
        threading.Thread(target=self._pump_loop, name=f"pysdrlib-{dev_id}-rx", daemon=True),
        threading.Thread(target=self._tx_loop, name=f"pysdrlib-{dev_id}-tx", daemon=True),
    ]
    for t in self._threads:
        t.start()
claim
claim(program=None) -> str

Make a new controller token the owner. Raises err.Busy if the device already has a controller

Source code in src/pysdrlib/remote/server.py
def claim(self, program=None) -> str:
    """Make a new controller token the owner. Raises `err.Busy` if the device already has a controller"""
    with self._owner_lock:
        if self.token is not None:
            raise err.Busy(f"{self.id} already has a controller" + (f" ({self.program})" if self.program else ""))
        self.program = program
        self.token = secrets.token_hex(16)
        self.last_seen = time.monotonic()
        return self.token
is_controller
is_controller(token) -> bool

Whether token is the current controller's

Source code in src/pysdrlib/remote/server.py
def is_controller(self, token) -> bool:
    """Whether `token` is the current controller's"""
    return self.token is not None and isinstance(token, str) and hmac.compare_digest(self.token, token)
touch
touch()

Note that the controller is still there (renews its lease)

Source code in src/pysdrlib/remote/server.py
def touch(self):
    """Note that the controller is still there (renews its lease)"""
    self.last_seen = time.monotonic()
release
release(wait=True)

Drop the controller; stop streaming since nobody is left to manage it. wait=False: stop it in the background, so a radio slow to stop holds up nobody (the C2 thread answers everyone). A controller that claims the radio before that happens keeps its stream.

Source code in src/pysdrlib/remote/server.py
def release(self, wait=True):
    """Drop the controller; stop streaming since nobody is left to manage it.
    wait=False: stop it in the background, so a radio slow to stop holds up nobody (the C2 thread answers everyone).
    A controller that claims the radio before that happens keeps its stream."""
    with self._owner_lock:
        self.token = None
        self.program = self.need = self.want = None
    if wait:
        self._stop_streams()
    else:
        threading.Thread(target=self._stop_streams, args=(True,), name=f"pysdrlib-{self.id}-release", daemon=True).start()
serial
serial()

The serial number of the radio, when the driver or the scan told us it

Source code in src/pysdrlib/remote/server.py
def serial(self):
    """The serial number of the radio, when the driver or the scan told us it"""
    if self.unit is not None and self.unit.serial:
        return self.unit.serial
    try:
        return self.device.caps.info.get("serial")
    except Exception:
        return None
status
status()

What list shows clients: id, type, name, state, frequency, sample rate, wire format and whether it is controlled. While a call into the device is under way (a slow stop_rx...), the last status seen, with busy set

Source code in src/pysdrlib/remote/server.py
def status(self):
    """What `list` shows clients: id, type, name, state, frequency, sample rate, wire format and whether it is controlled.
    While a call into the device is under way (a slow stop_rx...), the last status seen, with `busy` set"""
    owner = {"controlled": self.token is not None, "program": self.program, "need": self.need, "want": self.want,
             "health": self.health}
    if not self.lock.acquire(timeout=STATUS_WAIT):
        last = self._last_status or {   # never seen yet: what can be read without the device (its cached settings)
            "id": self.id, "type": self.type, "name": type(self.device).NAME, "state": dict(self.device.state),
            "cf": self.device.get_rx_freq(), "Fs": self.device.get_rx_sample_rate(), "serial": None,
            "wire": protocol.wire_name(self.wire), "rx_channels": [0], "tx_channels": [0], "chains": []}
        return {**last, **owner, "busy": True}
    try:
        self._last_status = {
            "id": self.id, "type": self.type, "name": type(self.device).NAME,
            "state": dict(self.device.state),
            "cf": self.device.get_rx_freq(), "Fs": self.device.get_rx_sample_rate(),
            **owner,
            "serial": self.serial(),
            "wire": protocol.wire_name(self.wire),
            "rx_channels": list(getattr(self.device, "rx_channels", (0,))),
            "tx_channels": list(getattr(self.device, "tx_channels", (0,))),
            "chains": [{"direction": c.direction, "port": c.port, "channel": c.channel, "name": c.name, "lo": c.lo,
                        "invert": c.invert, "polarization": c.polarization, "antenna": c.describe()} for c in self.device.caps.chains],
        }
        return dict(self._last_status)
    finally:
        self.lock.release()
metrics
metrics()

What has passed through since the device was hosted: samples published (to how many subscribers, over the socket and in shared memory), what the device itself dropped or missed, what was transmitted, control calls. For a dashboard, or to tell a network problem (dropped_blocks on a client) from a radio's (device.dropped)

Source code in src/pysdrlib/remote/server.py
def metrics(self):
    """What has passed through since the device was hosted: samples published (to how many subscribers, over the
    socket and in shared memory), what the device itself dropped or missed, what was transmitted, control calls.
    For a dashboard, or to tell a network problem (dropped_blocks on a client) from a radio's (device.dropped)"""
    c = dict(self.counters)
    device = None
    if self.lock.acquire(timeout=STATUS_WAIT):   # the device's own counts, between calls into it
        try:
            if self.device.state.get("rx") and hasattr(self.device, "stats"):
                st = self.device.stats
                device = {"samples": st.samples, "dropped": st.dropped, "missing": st.missing, "stalls": st.stalls}
            tx = self.device.get_tx_stats() if self.device.state.get("tx") else None
        except Exception as e:   # a failing device: the counters still help
            device, tx = {"error": str(e)}, None
        finally:
            self.lock.release()
    else:
        tx = None
    return {
        "id": self.id, "type": self.type, "uptime": time.monotonic() - self.hosted_at,
        "streaming": self.streaming.is_set(), "controlled": self.token is not None, "program": self.program,
        "rx": {"samples": c["rx_samples"], "blocks": c["rx_blocks"], "bytes": c["rx_bytes"],
               "shm_notices": c["shm_notices"], "wire": protocol.wire_name(self.wire),
               "socket_subscribers": self._subs.get(self._topic, 0),
               "shm_subscribers": self._subs.get(self._shm_topic, 0)},
        "device": device,
        "tx": {"samples": c["tx_samples"], "blocks": c["tx_blocks"], "refused": self.tx_refused, "device": tx},
        "control": {"calls": c["calls"], "errors": c["errors"]},
    }
close
close()

Stop serving and close the hardware

Source code in src/pysdrlib/remote/server.py
def close(self):
    """Stop serving and close the hardware"""
    self._stop.set()
    self.streaming.clear()
    for t in self._threads:
        t.join(5.0)
        if t.is_alive():
            self.log.warning("%s: %s did not stop within 5 s", self.id, t.name)
    self._destroy_rings()
    self.ctrl.close(0)
    self.rx.close(0)
    self.tx.close(0)
    with self.lock:
        try:
            self._close_device()
        except Exception:
            self.log.exception("close failed")

RelayWorker

RelayWorker(server: Server, dev_id: str, upstream: RemoteDevice, owns: bool, shm=True, shm_samples=None)

Bases: DeviceWorker

A device hosted by another server, hosted here: a relay

Programs on this machine connect here instead of to the far server, and the far server sees one client however many there are. The samples cross the network once and reach every local program through shared memory. Control passes through to the far device when this relay controls it (Server.relay takes control if it is free).

The upstream is a RemoteDevice. A thread follows its state (a stream started by someone else upstream starts the relay's too), and lost is set when the far server stops answering.

Methods:

Name Description
serial

The far radio's serial number (not asked of a far server that is lost: whoever asks must not wait for it)

status

The far device's state as this relay last heard it (every forwarded call, and the watcher, refresh it)

Source code in src/pysdrlib/remote/server.py
def __init__(self, server: "Server", dev_id: str, upstream: RemoteDevice, owns: bool, shm=True, shm_samples=None):
    self.upstream = upstream
    self._owns = owns                   # the relay opened the far device: closing the relay closes it
    status = upstream.refresh()
    self.lost = threading.Event()
    self._far_health = status.get("health", "ok")   # of the far device's stream, as its server last said
    native = (upstream.capabilities or {}).get("native_wire")
    try:
        protocol.wire_format(native)    # the far device's own layout is the best one to pass on: lossless and compact
    except ValueError:
        native = "complex64"
    super().__init__(server, dev_id, status.get("type", "remote"), upstream, native, shm, shm_samples)
    if upstream.state.get("rx"):
        self.streaming.set()
    watcher = threading.Thread(target=self._watch_loop, name=f"pysdrlib-{dev_id}-watch", daemon=True)
    self._threads.append(watcher)
    watcher.start()
serial
serial()

The far radio's serial number (not asked of a far server that is lost: whoever asks must not wait for it)

Source code in src/pysdrlib/remote/server.py
def serial(self):
    """The far radio's serial number (not asked of a far server that is lost: whoever asks must not wait for it)"""
    return None if self.lost.is_set() else super().serial()
status
status()

The far device's state as this relay last heard it (every forwarded call, and the watcher, refresh it)

Source code in src/pysdrlib/remote/server.py
def status(self):
    """The far device's state as this relay last heard it (every forwarded call, and the watcher, refresh it)"""
    up = self.upstream
    # what is wrong with the far end is what is wrong here: a local client waiting for samples asks, and raises
    health = "lost" if self.lost.is_set() else self._far_health if self._far_health != "ok" else self.health
    return {"health": health, "id": self.id, "type": self.type, "name": up.capabilities["name"], "state": dict(up.state),
            "cf": up._cf, "Fs": up._Fs, "controlled": self.token is not None, "wire": protocol.wire_name(self.wire),
            "rx_channels": list(up.rx_channels), "tx_channels": list(up.tx_channels), "lost": self.lost.is_set(),
            "program": self.program, "need": self.need, "want": self.want, "serial": None}

Server

Server(bind='tcp://127.0.0.1:5555', port_range=None, devices=None, lease=15.0, wire='native', shm=True, shm_samples=None, scan_interval=0.0, frontends=None, advertise=False, name=None, kind='server', stats_interval=0.0, max_devices=MAX_DEVICES, client_args=None)

bind: C2 endpoint, tcp://host:port (port 0 or * picks one; see endpoint) or ipc://path. port_range: (low, high) for the per-device tcp ports; default lets the OS pick. devices: device types clients may open (default: every vendor package). lease: seconds a controller may be silent before it loses control (0 disables). wire: default RX wire format: "native" (the device's own sample layout), "complex64", "int8", "int16", ... shm: let clients on this machine take samples from shared memory (the socket still serves the rest). shm_samples: samples a shared-memory ring holds (default: a quarter second at the device's top rate). scan_interval: seconds between looks at which radios are attached, logging the ones that appear or vanish (0 = never). frontends: what sits between each radio and the air (a frontends.Frontends, or the path of its TOML file). advertise: announce the server on the local network while it serves, for discovery.discover (needs zeroconf, and a bind other clients can reach such as tcp://0.0.0.0:5555). name: the name it announces (default: the host name). kind: what it announces itself as, "server" or "relay". stats_interval: seconds between log lines saying what each streaming device published, to how many subscribers, and what it dropped (0 = never). metrics() (the "metrics" request, pysdrlib client ADDRESS stats) has it all. max_devices: devices hosted at once; a client that asks for one more gets err.Busy. client_args: what a client may pass a driver, {type: [argument names]} on top of CLIENT_ARGS (by default a serial, an index, a UHD radio's addr, and a simulated radio's signal). Anything else is refused, since a driver's arguments name hosts, files and device strings: open those with open_device (--open), or name them here ({"tcpiq": ["host", "port", "sample_format"]}) to let clients choose them.

Methods:

Name Description
start

Serve in a background thread

serve_forever

Serve in this thread until Ctrl+C or SIGTERM (a service being stopped), then stop

stop

Stop serving and close every hosted device

metrics

{"uptime", "devices": {id: DeviceWorker.metrics()}}: what every hosted device (or just device) has passed

scan

Look for attached radios and log what appeared or vanished since the last scan (the first logs all of them).

types

Device types clients may open: the devices given to the server, or every driver

open_device

Create and open a device of vendor package dtype and start hosting it.

available

The radios attached at the last scan, as dicts: driver, label, serial, index and hosted (the id of the worker

choose

The radios a client could use for this request, best first: [(kind, target, caps)] with kind "hosted" (a

candidates

choose for a client that has not decided which server to use: the radios that fit the request, best first, as

open_matching

Open (or take over, if it is hosted and nobody controls it) the best radio for the request (see choose).

relay

Host a device of another server here, so programs on this machine share one connection to it (see RelayWorker).

Attributes:

Name Type Description
advertised_name

The name the server announces on the network (None when not advertising)

Source code in src/pysdrlib/remote/server.py
def __init__(self, bind="tcp://127.0.0.1:5555", port_range=None, devices=None, lease=15.0, wire="native", shm=True,
             shm_samples=None, scan_interval=0.0, frontends=None, advertise=False, name=None, kind="server",
             stats_interval=0.0, max_devices=MAX_DEVICES, client_args=None):
    """
    bind: C2 endpoint, tcp://host:port (port 0 or * picks one; see `endpoint`) or ipc://path.
    port_range: (low, high) for the per-device tcp ports; default lets the OS pick.
    devices: device types clients may open (default: every vendor package).
    lease: seconds a controller may be silent before it loses control (0 disables).
    wire: default RX wire format: "native" (the device's own sample layout), "complex64", "int8", "int16", ...
    shm: let clients on this machine take samples from shared memory (the socket still serves the rest).
    shm_samples: samples a shared-memory ring holds (default: a quarter second at the device's top rate).
    scan_interval: seconds between looks at which radios are attached, logging the ones that appear or vanish (0 = never).
    frontends: what sits between each radio and the air (a `frontends.Frontends`, or the path of its TOML file).
    advertise: announce the server on the local network while it serves, for `discovery.discover` (needs zeroconf, and a
        bind other clients can reach such as tcp://0.0.0.0:5555). name: the name it announces (default: the host name).
    kind: what it announces itself as, "server" or "relay".
    stats_interval: seconds between log lines saying what each streaming device published, to how many subscribers,
        and what it dropped (0 = never). `metrics()` (the "metrics" request, `pysdrlib client ADDRESS stats`) has it all.
    max_devices: devices hosted at once; a client that asks for one more gets `err.Busy`.
    client_args: what a client may pass a driver, {type: [argument names]} on top of `CLIENT_ARGS` (by default a serial, an
        index, a UHD radio's `addr`, and a simulated radio's signal). Anything else is refused, since a driver's arguments name
        hosts, files and device strings: open those with `open_device` (`--open`), or name them here
        (`{"tcpiq": ["host", "port", "sample_format"]}`) to let clients choose them.
    """
    self.log = logger.new("remote.server")
    self.scheme, self._host, self._port = _parse_bind(bind)
    self.port_range = tuple(port_range) if port_range else None
    self.allowed = list(devices) if devices else None
    self.max_devices = int(max_devices)
    self.client_args = {k: {"init": tuple(v["init"]), "open": tuple(v["open"])} for k, v in CLIENT_ARGS.items()}
    for dtype, names in (client_args or {}).items():
        base = self.client_args.get(dtype, self.client_args["*"])
        self.client_args[dtype] = {kind: (*base[kind], *names) for kind in ("init", "open")}
    self.lease = float(lease)
    self.frontends = frontends_mod.load(frontends) if isinstance(frontends, (str, os.PathLike)) else (frontends or frontends_mod.Frontends())
    protocol.wire_format(wire) if wire != "native" else None    # validate now
    self.wire = wire
    self.shm = bool(shm)
    self.shm_samples = shm_samples
    self.endpoint = None        # actual C2 endpoint once bound
    self.workers: dict[str, DeviceWorker] = {}
    self.started = time.monotonic()
    self.stats_interval = float(stats_interval)
    self._stats_at = time.monotonic()
    self._stats_last = {}       # dev id -> the metrics the last stats line was worked out from
    self._counts: dict[str, int] = {}
    self._ctx = zmq.Context()
    self._c2 = None
    self._thread = None
    self._stop = threading.Event()
    self.scan_interval = float(scan_interval)
    self._scan_thread = None
    self._attached = None       # {key: DeviceInfo} at the last scan
    self._scan_lock = threading.Lock()   # one look at the USB bus at a time
    self._bind_c2(bind)
    self._advertiser = None
    if advertise:
        from .discovery import Advertiser
        try:
            self._advertiser = Advertiser(self.endpoint, name=name, kind=kind)
        except BaseException:
            self._c2.close(0)
            self._ctx.term()
            raise
advertised_name property
advertised_name

The name the server announces on the network (None when not advertising)

start
start()

Serve in a background thread

Source code in src/pysdrlib/remote/server.py
def start(self):
    """Serve in a background thread"""
    if self._thread is None:
        self._thread = threading.Thread(target=self._run, name="pysdrlib-c2", daemon=True)
        self._thread.start()
    self._advertise()
    if self.scan_interval > 0 and self._scan_thread is None:
        self._scan_thread = threading.Thread(target=self._scan_loop, name="pysdrlib-scan", daemon=True)
        self._scan_thread.start()
    return self
serve_forever
serve_forever()

Serve in this thread until Ctrl+C or SIGTERM (a service being stopped), then stop

Source code in src/pysdrlib/remote/server.py
def serve_forever(self):
    """Serve in this thread until Ctrl+C or SIGTERM (a service being stopped), then `stop`"""
    if self.scan_interval > 0 and self._scan_thread is None:
        self._scan_thread = threading.Thread(target=self._scan_loop, name="pysdrlib-scan", daemon=True)
        self._scan_thread.start()
    try:
        self._advertise()
        self._run()
    except KeyboardInterrupt:
        pass
    finally:
        self.stop()
stop
stop()

Stop serving and close every hosted device

Source code in src/pysdrlib/remote/server.py
def stop(self):
    """Stop serving and close every hosted device"""
    self._stop.set()
    if self._advertiser is not None:
        try:
            self._advertiser.stop()
        except Exception:
            self.log.exception("withdrawing the announcement failed")
    if self._thread is not None:
        self._thread.join()
        self._thread = None
    if self._scan_thread is not None:
        self._scan_thread.join()
        self._scan_thread = None
    for dev_id in list(self.workers):
        self.workers.pop(dev_id).close()
    if self._c2 is not None:
        self._c2.close(0)
        self._c2 = None
        self._ctx.term()
metrics
metrics(device=None)

{"uptime", "devices": {id: DeviceWorker.metrics()}}: what every hosted device (or just device) has passed

Source code in src/pysdrlib/remote/server.py
def metrics(self, device=None):
    """{"uptime", "devices": {id: DeviceWorker.metrics()}}: what every hosted device (or just `device`) has passed"""
    workers = [self._worker({"device": device})] if device is not None else list(self.workers.values())
    return {"uptime": time.monotonic() - self.started, "devices": {w.id: w.metrics() for w in workers}}
scan
scan()

Look for attached radios and log what appeared or vanished since the last scan (the first logs all of them). -> the list of DeviceInfo

Source code in src/pysdrlib/remote/server.py
def scan(self):
    """Look for attached radios and log what appeared or vanished since the last scan (the first logs all of them).
    -> the list of `DeviceInfo`"""
    with self._scan_lock:
        found = [i for i in devices.find() if i.driver in self.types()]
    now = {self._key(i): i for i in found}
    if self._attached is None:
        if not found:
            self.log.info("no radios found attached to this machine")
        for info in found:
            self.log.info("found %s", self._describe(info))
    else:
        for key, info in now.items():
            if key not in self._attached:
                self.log.info("radio connected: %s", self._describe(info))
        for key, info in self._attached.items():
            if key not in now:
                self.log.warning("radio disconnected: %s", self._describe(info))
    self._attached = now
    return found
types
types()

Device types clients may open: the devices given to the server, or every driver

Source code in src/pysdrlib/remote/server.py
def types(self):
    """Device types clients may open: the `devices` given to the server, or every driver"""
    return self.allowed if self.allowed is not None else devices.ls()
open_device
open_device(dtype, init_args=(), init_kwargs=None, args=(), kwargs=None, controlled=False, wire=None, program=None, need=None, want=None, unit=None, client=False)

Create and open a device of vendor package dtype and start hosting it. program/need/want: what the controller said it runs and needs (shown by list; see choose). unit: the DeviceInfo of the radio, when it was picked from the attached ones. client: the arguments came from a client, and are held to what it may pass (client_args). -> (worker, token) where token is None unless controlled

Source code in src/pysdrlib/remote/server.py
def open_device(self, dtype, init_args=(), init_kwargs=None, args=(), kwargs=None, controlled=False, wire=None,
                program=None, need=None, want=None, unit=None, client=False):
    """Create and open a device of vendor package `dtype` and start hosting it.
    program/need/want: what the controller said it runs and needs (shown by `list`; see `choose`). unit: the `DeviceInfo`
    of the radio, when it was picked from the attached ones.
    client: the arguments came from a client, and are held to what it may pass (`client_args`).
    -> (worker, token) where token is None unless `controlled`"""
    if client:
        self._vet(dtype, init_args, init_kwargs, args, kwargs)
    if len(self.workers) >= self.max_devices:
        raise err.Busy(f"this server hosts {len(self.workers)} devices, the most it allows (max_devices)")
    if dtype not in self.types():
        raise err.NoDevice(f"device type {dtype!r} is not available on this server (have: {', '.join(self.types())})",
                           reason="no_type")
    module = devices.get(dtype)
    device = module.Device(*init_args, **(init_kwargs or {}))
    device.open(*args, **(kwargs or {}))
    serial = (unit.serial if unit is not None else None) or device.caps.info.get("serial")
    fitted = self.frontends.apply(device.caps, dtype, serial, unit.label if unit is not None else module.Device.NAME)
    if fitted is not device.caps:
        device.set_chains(fitted.chains)
    n = self._counts[dtype] = self._counts.get(dtype, -1) + 1
    try:
        worker = DeviceWorker(self, f"{dtype}-{n}", dtype, device, wire or self.wire, self.shm, self.shm_samples)
    except BaseException:
        device.close()
        raise
    worker.unit = unit
    self.workers[worker.id] = worker
    self.log.info("hosting %s (%s) with %s: ctrl %s, rx %s", worker.id, worker.capabilities.get("name", dtype),
                  f"{program or 'a client'} in control" if controlled else "no controller", worker.endpoints["ctrl"], worker.endpoints["rx"])
    token = worker.claim(program) if controlled else None
    if controlled:
        worker.need, worker.want = need or None, want or None
    return worker, token
available
available()

The radios attached at the last scan, as dicts: driver, label, serial, index and hosted (the id of the worker that has it open, or None)

Source code in src/pysdrlib/remote/server.py
def available(self):
    """The radios attached at the last scan, as dicts: driver, label, serial, index and `hosted` (the id of the worker
    that has it open, or None)"""
    taken = {}
    for w in self.workers.values():
        if w.serial():
            taken[w.serial()] = w.id
    out = []
    unknown = {}    # driver -> workers hosting a radio of it whose serial is not known: each has one of that driver's
    for w in self.workers.values():
        if not w.serial():
            unknown.setdefault(w.type, []).append(w.id)
    for info in (self._attached or {}).values():
        hosted = taken.get(info.serial) if info.serial else None
        if hosted is None and unknown.get(info.driver):
            hosted = unknown[info.driver].pop(0)
        out.append({"driver": info.driver, "label": info.label, "serial": info.serial, "index": info.index,
                    "hosted": hosted})
    return out
choose
choose(dtype=None, serial=None, label=None, need=None, want=None)

The radios a client could use for this request, best first: [(kind, target, caps)] with kind "hosted" (a DeviceWorker nobody controls) or "unit" (a DeviceInfo attached and not hosted). A radio meets the request when it is of type dtype, its serial is serial and its label contains label (case ignored), and meets all of need; those that meet most of want come first, attached ones before hosted ones (a free hosted radio is one a client left open). Raises err.NoDevice saying why when none do.

Source code in src/pysdrlib/remote/server.py
def choose(self, dtype=None, serial=None, label=None, need=None, want=None):
    """The radios a client could use for this request, best first: `[(kind, target, caps)]` with kind "hosted" (a
    `DeviceWorker` nobody controls) or "unit" (a `DeviceInfo` attached and not hosted). A radio meets the request when it
    is of type `dtype`, its serial is `serial` and its label contains `label` (case ignored), and meets all of `need`; those
    that meet most of `want` come first, attached ones before hosted ones (a free hosted radio is one a client left open). Raises `err.NoDevice` saying why when none do."""
    need, want = choose.normalize(need, "need"), choose.normalize(want, "want")
    wish = {**need, **want}     # what to rank by: of radios that meet the need, the nearest to it (and to `want`, which goes further)
    if dtype is not None and dtype not in self.types():
        raise err.NoDevice(f"device type {dtype!r} is not available on this server (have: {', '.join(self.types())})",
                           reason="no_type")
    self.scan()     # what is attached now
    reasons, found = [], []

    def consider(kind, target, driver, name, unit_serial, caps):
        if dtype is not None and driver != dtype:
            return
        if serial is not None and str(unit_serial) != str(serial):
            return
        if not self._matches(name, label):
            return
        if kind == "unit":
            caps = self.frontends.apply(caps, driver, unit_serial, name)
        who = f"{driver}: {name}" + (f" (serial {unit_serial})" if unit_serial else "")
        bad = choose.problems(caps, need) if caps is not None else []
        if bad:
            reasons.append(f"{who}: {'; '.join(bad)}")
        else:
            found.append((choose.rank(caps, wish), kind == "hosted", len(found), kind, target, caps))

    for w in self.workers.values():
        if w.token is not None or isinstance(w, RelayWorker):
            continue    # someone controls it (or it is another server's)
        consider("hosted", w, w.type, type(w.device).NAME, w.serial(), w.device.caps)
    unknown = {}
    for w in self.workers.values():
        if not w.serial():
            unknown[w.type] = unknown.get(w.type, 0) + 1
    by_driver = {}
    for info in (self._attached or {}).values():
        if info.serial and info.serial in self._hosted_serials():
            continue
        if not info.serial and unknown.get(info.driver):    # one of these is already open: take it to be this one
            unknown[info.driver] -= 1
            continue
        if info.driver not in by_driver:
            by_driver[info.driver] = self._class_caps(info.driver)
        consider("unit", info, info.driver, info.label, info.serial, by_driver[info.driver])
    if not found:
        what = ", ".join(f"{k}={v}" for k, v in (("type", dtype), ("serial", serial), ("label", label)) if v is not None)
        what = (what + "; " if what else "") + f"need {need}" if need else what
        if reasons:
            raise err.NoDevice(f"no radio on this server meets the request ({what}): " + " | ".join(reasons),
                               reason="unmet")
        attached = self.available()
        raise err.NoDevice(f"no radio on this server is free for the request ({what or 'any'}); "
                           f"attached: {', '.join(i['label'] for i in attached) or 'none'}",
                           reason="none_free" if attached else "none_attached")
    found.sort(key=lambda f: f[:3])
    return [(f[3], f[4], f[5]) for f in found]
candidates
candidates(dtype=None, serial=None, label=None, need=None, want=None)

choose for a client that has not decided which server to use: the radios that fit the request, best first, as dicts of kind ("unit" attached, "hosted" open and uncontrolled), driver, label, serial, id (a hosted one's), rank (choose.rank, comparable between servers), granted and key (give it to open_matching as pick to open that radio and no other). Opens nothing; raises err.NoDevice like choose

Source code in src/pysdrlib/remote/server.py
def candidates(self, dtype=None, serial=None, label=None, need=None, want=None):
    """`choose` for a client that has not decided which server to use: the radios that fit the request, best first, as
    dicts of `kind` ("unit" attached, "hosted" open and uncontrolled), `driver`, `label`, `serial`, `id` (a hosted one's),
    `rank` (`choose.rank`, comparable between servers), `granted` and `key` (give it to `open_matching` as `pick` to open
    that radio and no other). Opens nothing; raises `err.NoDevice` like `choose`"""
    need, want = choose.normalize(need, "need"), choose.normalize(want, "want")
    wish = {**need, **want}
    out = []
    for kind, target, caps in self.choose(dtype, serial, label, need, want):
        if kind == "hosted":
            info = {"driver": target.type, "label": type(target.device).NAME, "serial": target.serial(), "id": target.id}
        else:
            info = {"driver": target.driver, "label": target.label, "serial": target.serial, "id": None}
        out.append({"kind": kind, **info, "key": self._pick_key(kind, target), "rank": list(choose.rank(caps, wish)),
                    "granted": choose.granted(caps, wish) if caps is not None else None})
    return out
open_matching
open_matching(dtype=None, serial=None, label=None, need=None, want=None, program=None, init_args=(), init_kwargs=None, wire=None, pick=None, client=False, args=(), kwargs=None)

Open (or take over, if it is hosted and nobody controls it) the best radio for the request (see choose). pick: the key of one of candidates: open that radio or none, err.Busy if it no longer fits the request or is no longer free (a client that compared servers by candidates then tries its next best, which may be elsewhere). init_args/init_kwargs, args/kwargs: for the driver's constructor and open of a radio this opens. One taken over is open already: the constructor's are not used on it, and with arguments for open it is passed over. -> (worker, token, granted) where granted is what the radio can do nearest to want (and need)

Source code in src/pysdrlib/remote/server.py
def open_matching(self, dtype=None, serial=None, label=None, need=None, want=None, program=None, init_args=(),
                  init_kwargs=None, wire=None, pick=None, client=False, args=(), kwargs=None):
    """Open (or take over, if it is hosted and nobody controls it) the best radio for the request (see `choose`).
    pick: the `key` of one of `candidates`: open that radio or none, `err.Busy` if it no longer fits the request or is
    no longer free (a client that compared servers by `candidates` then tries its next best, which may be elsewhere).
    init_args/init_kwargs, args/kwargs: for the driver's constructor and `open` of a radio this opens. One taken over is
    open already: the constructor's are not used on it, and with arguments for `open` it is passed over.
    -> (worker, token, granted) where `granted` is what the radio can do nearest to `want` (and `need`)"""
    need, want = choose.normalize(need, "need"), choose.normalize(want, "want")
    last = None
    try:
        candidates = self.choose(dtype, serial, label, need, want)
    except err.NoDevice as e:
        if pick is None:
            raise
        raise err.Busy(f"the radio picked is no longer free for the request: {e}") from e
    if pick is not None:
        candidates = [c for c in candidates if self._pick_key(c[0], c[1]) == pick]
        if not candidates:
            raise err.Busy("the radio picked has been taken or has gone since it was offered")
    wish = {**need, **want}
    for i, (kind, target, caps) in enumerate(candidates):
        open_kwargs = None
        if kind != "hosted":   # outside the try: a refused argument is the answer, not a radio that failed
            if client:
                self._vet(target.driver, init_args, init_kwargs, args, kwargs)
            open_kwargs = self._unit_open_args(target, kwargs)
        elif args or any(not (name in ("serial", "serial_number") and str(value) == str(target.serial()))
                         for name, value in (kwargs or {}).items()):
            last = err.InvalidValue(f"{target.id} is open already: it takes no open() arguments")
            continue
        try:
            if kind == "hosted":
                worker, token = target, target.claim(program)
                worker.need, worker.want = need or None, want or None
                self.log.info("%s: taken over by %s", worker.id, program or "a client")
            else:
                worker, token = self.open_device(target.driver, init_args, init_kwargs, args, open_kwargs,
                                                 controlled=True, wire=wire, program=program, need=need, want=want, unit=target)
        except Exception as e:      # taken, gone since the scan, in use by another process, no permission...: next best
            self.log.warning("could not open %s: %s", getattr(target, "label", getattr(target, "id", target)), e)
            last = e
            continue
        live = worker.device.caps
        bad = choose.problems(live, need) if need else []
        if bad:     # the unit is not quite what its driver's class said: it refined its capabilities once open
            self.log.warning("%s does not meet the need once open: %s", worker.id, "; ".join(bad))
            last = err.NoDevice(f"{worker.id}: {'; '.join(bad)}")
            self._give_back(kind, worker)
            continue
        if wish and any(choose.rank(c, wish) < choose.rank(live, wish) for _, _, c in candidates[i + 1:]):
            # opened, it does less of `want` than the class said (discrete rates, a narrower tuner) and a later candidate
            # is expected to do more: let that one have it
            self.log.info("%s does less of the request once open than the next candidate is expected to", worker.id)
            last = err.NoDevice(f"{worker.id} meets less of `want` than another radio")
            self._give_back(kind, worker)
            continue
        granted = choose.granted(live, {**need, **want}) if (want or need) else {}
        return worker, token, granted
    raise err.NoDevice(f"every radio that fits the request failed to open: {last}")
relay
relay(address, device=None, *, open=None, control='auto', name=None, timeout=5.0, transport='auto')

Host a device of another server here, so programs on this machine share one connection to it (see RelayWorker).

address: the far server's endpoint. device: the id of a device it hosts (e.g. "hackrf-0"); or open: a device type to open there instead (the relay then controls it, and closing the relay closes it). control: take control of the device if it is free ("auto"), insist on it (True: err.Busy if someone has it), or only watch it (False: local programs can receive but not change anything). name: the id it has here (default: the far device's). Returns the RelayWorker.

Source code in src/pysdrlib/remote/server.py
def relay(self, address, device=None, *, open=None, control="auto", name=None, timeout=5.0, transport="auto"):
    """Host a device of another server here, so programs on this machine share one connection to it (see `RelayWorker`).

    address: the far server's endpoint. device: the id of a device it hosts (e.g. "hackrf-0"); or open: a device type to
    open there instead (the relay then controls it, and closing the relay closes it).
    control: take control of the device if it is free ("auto"), insist on it (True: `err.Busy` if someone has it), or only
    watch it (False: local programs can receive but not change anything).
    name: the id it has here (default: the far device's). Returns the `RelayWorker`.
    """
    if len(self.workers) >= self.max_devices:
        raise err.Busy(f"this server hosts {len(self.workers)} devices, the most it allows (max_devices)")
    if (device is None) == (open is None):
        raise ValueError("give exactly one of `device` (a hosted device's id) or `open` (a device type to open there)")
    upstream = RemoteDevice(address, open, id=device, timeout=timeout, transport=transport)
    upstream.open()
    try:
        if open is None and control:
            try:
                upstream.claim()
            except err.Busy:
                if control is True:
                    raise
        dev_id = base = name or upstream.id
        n = 0
        while dev_id in self.workers:
            n += 1
            dev_id = f"{base}-r{n}"
        worker = RelayWorker(self, dev_id, upstream, owns=open is not None, shm=self.shm, shm_samples=self.shm_samples)
    except BaseException:
        upstream.close() if open is not None else upstream.detach()
        raise
    self.workers[worker.id] = worker
    self.log.info("relaying %s of %s as %s", upstream.id, address, worker.id)
    return worker