Skip to content

Device

pysdrlib.base.device

The device-agnostic interface every SDR presents

Lifecycle and tuning (open, initialize, set_rx_freq, set_rx_sample_rate, start_rx...), reading (read, stream, get_samples), and the controls a device may have, discovered through caps (see pysdrlib.base.caps):

sdr = pysdrlib.device("rtl_sdr"); sdr.open()
sdr.caps.gains["rx"]                     # the device's own gain stages
sdr.set_rx_gain(0.5)                     # gain as a fraction of this device's range: the same call on every radio
sdr.set_rx_gain_db(30)                   # ... or in dB: a total (split by the device) or one stage, set_rx_gain_db(12, stage="IF")
sdr.set_rx_bandwidth(1.5e6)              # analog filter, when the device has one
sdr.set_freq_correction(14.8)            # ppm error of the device's reference
sdr.set_setting("dither", True)          # anything else the device has (caps.settings)
with sdr.stream(65536, meta=True) as s:
    for x, m in s: ...                   # m: RxMeta (sample index, gaps, retunes inside the block)

Every control takes channel=0, and tuning takes direction ("rx", "tx", or None for both). caps.channels has the channel counts and caps.shared what one setting changes (a frequency may be one channel's, shared by a direction's channels, or the whole device's). A multi-channel device streams several channels together:

sdr.start_rx(channels=(0, 1)); x = sdr.read(65536, channel=(0, 1))     # (2, 65536), the same instants
sdr.start_tx(channels=(0, 1)); sdr.write(np.stack((a, b)))              # sent sample for sample together

A device that lacks a control raises err.NotSupported. Values out of range are clamped with a warning, or raise err.InvalidValue with strict = True.

Classes:

Name Description
Device

The interface every driver implements. Use pysdrlib.open or pysdrlib.device to get one; see the module

Device

Device()

The interface every driver implements. Use pysdrlib.open or pysdrlib.device to get one; see the module docs (pysdrlib.base.device) for an overview.

Class attributes a driver sets: NAME, CAPS (its limits and gain stages, pysdrlib.base.caps), CAN_TRANSMIT, DUPLEX (receive and transmit at once) and SAMPLE_FORMAT (the layout of the samples the hardware delivers).

Methods:

Name Description
find

[DeviceInfo] of the units of this driver that are attached, for pysdrlib.find. A driver that can list them

open

Connect to device. serial=...: the unit with this serial number (where the driver can choose)

initialize

Tune the receiver (and the transmitter, where it has its own synthesizer) to cf and Fs, and set the gains.

close

Disconnect from device, stopping what is streaming first

start_rx

Start receiving. channels: which to stream together (default: the last ones, at first channel 0);

stop_rx

Stop receiving

get_samples

The low-level call: whatever has arrived since the last call (any number, possibly none, without waiting). Most

start_tx

Start transmitting (then write). channels: which to transmit together (default: the last ones, at first 0)

stop_tx

Stop transmitting

set_rx_sample_rate

Set the receive sample rate (the nominal one: a frequency correction is applied to what the hardware is asked

set_tx_sample_rate

Set the transmit sample rate (see set_rx_sample_rate). Raises err.NotSupported on a receiver

get_rx_sample_rate

Receive sample rate [Hz] last set for this channel

get_tx_sample_rate

Transmit sample rate [Hz] last set for this channel (None: never set)

set_rx_freq

Set the receive center frequency (corrected by set_freq_correction). What else moves with it:

set_tx_freq

Set the transmit center frequency (see set_rx_freq). Raises err.NotSupported on a receiver

get_rx_inverted

Whether the receive spectrum comes mirrored, from a converter whose LO is above the signal (see caps.Chain):

get_rx_context

How this channel's samples are received, for a recording to keep (RxContext): the frequency over the air and

set_level_calibration

What a level in these samples is at the antenna port: dBm = dBFS + offset_db, where dBFS has full scale at

get_level_calibration

The level calibration given to set_level_calibration (None: none): {"offset_db", "accuracy", "freq", "span",

get_rx_freq

Receive center frequency [Hz] last set for this channel (over the air, whatever converter is on the radio)

get_tx_freq

Transmit center frequency [Hz] last set for this channel (None: never set)

set_freq_correction

Error of the device's frequency reference in parts per million (positive: it runs fast). Tuning and

get_freq_correction

Frequency reference error [ppm] last set with set_freq_correction

get_freq_correction_accuracy

How well the reference's error is known [ppm, a standard error], as given to set_freq_correction (None: not known)

set_rx_gain

The receive gain, as a fraction of the device's range: 0.0 its least, 1.0 its most (linear in dB), of the total

set_tx_gain

The transmit gain, as a fraction of the device's range (see set_rx_gain). Returns the fraction in effect

get_rx_gain

The receive gain last set, as a fraction of the device's range (None before a gain was set); get_rx_gain_db

get_tx_gain

The transmit gain last set, as a fraction of the device's range (None before a gain was set)

set_rx_gain_db

The receive gain in decibels: a total (the device splits it across its stages) or one stage's. None: the

set_tx_gain_db

The transmit gain in decibels (see set_rx_gain_db). Returns the gain in effect

get_rx_gain_db

The receive gain last set in decibels: a stage's, or the total of the stages (None before any was set)

get_tx_gain_db

The transmit gain last set in decibels: a stage's, or the total of the stages (None before any was set)

get_rx_gains_db

{stage name: gain [dB]} of what each receive stage was last set to (stages never set are missing)

get_tx_gains_db

{stage name: gain [dB]} of what each transmit stage was last set to

rx_gain_stages

{stage name: GainStage} of the receiver, as the device names its stages (stage= of the gain calls)

tx_gain_stages

{stage name: GainStage} of the transmitter

rx_gain_modes

["manual"] and, when the receiver can set its own gain, "auto"

tx_gain_modes

The transmitter's gain modes (["manual"])

set_rx_gain_mode

"auto": the receiver sets its own gain (AGC), "manual": the gain last set. Raises err.NotSupported for a mode

set_tx_gain_mode

The transmitter's gain mode (see set_rx_gain_mode)

get_rx_gain_mode

Current receive gain mode, "manual" unless set_rx_gain_mode changed it

get_tx_gain_mode

Current transmit gain mode

set_rx_bandwidth

Receive analog filter bandwidth [Hz]: the narrowest the device has that is at least bandwidth (None: the

set_tx_bandwidth

Transmit analog filter bandwidth [Hz] (see set_rx_bandwidth). Returns the bandwidth set

get_rx_bandwidth

Receive analog filter bandwidth [Hz] last set (None: never set)

get_tx_bandwidth

Transmit analog filter bandwidth [Hz] last set (None: never set)

rx_antennas

The receiver's selectable antenna ports ([]: just the one)

tx_antennas

The transmitter's selectable antenna ports ([]: just the one)

rx_antenna_info

Each receive antenna port and what is on it, as rx_antennas lists them (one entry, port None, when there is

tx_antenna_info

Each transmit antenna port and what is on it: as rx_antenna_info

set_rx_antenna

Select a receive antenna port by name (see rx_antennas). Raises err.NotSupported for a name the device lacks

set_tx_antenna

Select a transmit antenna port by name (see tx_antennas)

get_rx_antenna

The receive antenna port last selected (None: never set)

get_tx_antenna

The transmit antenna port last selected (None: never set)

clock_sources

Reference clock sources ([]: not selectable)

set_clock_source

Select the reference clock by name (see clock_sources). Raises err.NotSupported for a name the device lacks

get_clock_source

The reference clock last selected (None: never set)

set_bias_t

Set bias-t

settings

{name: caps.Setting}: everything else this device can be told (dither, AGC, test modes...)

set_setting

Apply one of settings() (to channel, where the setting is per channel). Returns the value set

get_setting

Value of a device specific setting listed in caps.settings. Raises err.NotSupported for an unknown name

set_chains

The hardware between this radio and the air (caps.Chain: an LNB, a converter, and the antenna on it), for a

get_chains

The chains in use (caps.chains)

get_caps

caps as plain types (what a remote client receives)

read

Exactly count samples (complex64), waiting for them. Raises err.Timeout after timeout seconds

read_into

read into a complex64 array you own (filled completely). Returns its length, or (length, RxMeta)

stream

Blocks of count samples, in a with block that starts receiving (and stops it after) when it wasn't:

sweep

Step the receiver across frequencies, yielding (frequency, samples): count samples at each, all received

find_gain

The highest receive gain at which the signal doesn't clip, found by bisecting the gains the device can set

read_available

What is queued for a channel now (up to count), without waiting: (samples, index of the first). Stops at a

wait_available

Wait up to timeout seconds until a channel has count samples queued; returns how many are queued (fewer

flush

Discard the samples waiting to be read (of every streaming channel: they stay aligned); returns how many

write

Queue samples (complex, full scale +-1) for transmission, after start_tx. Blocks while the queue is full,

get_tx_stats

The transmit stream's counts for a channel (default: its first): written, sent, underruns, pending...

split_rx_gain_db

How a total receive gain [dB] is shared between the stages: _split_gain's answer, {stage: gain}

split_tx_gain_db

How a total transmit gain [dB] is shared between the stages: {stage: gain}

Attributes:

Name Type Description
is_controller bool

Whether this handle may change settings: always for a local device; a remote one may be a viewer

rx_channels

The channels the receive stream carries

tx_channels

The channels the transmit stream carries

caps Capabilities

What this device can do (see pysdrlib.base.caps). Refined by the driver once open

Source code in src/pysdrlib/base/device.py
def __init__(self):
    self.log = logger.new(f"device.{type(self).__name__}")
    self.device: Any = None   # the driver's handle (an extension's device), None until `open`
    self.state = {
        "open": False,
        "rx": False,
        "tx": False
    }
    self._cf: float = type(self).CAPS.default_freq # type: ignore
    self._Fs: float = type(self).CAPS.default_rate # type: ignore
    self._init_generic()

is_controller property

is_controller: bool

Whether this handle may change settings: always for a local device; a remote one may be a viewer

rx_channels property

rx_channels

The channels the receive stream carries

tx_channels property

tx_channels

The channels the transmit stream carries

caps property

caps: Capabilities

What this device can do (see pysdrlib.base.caps). Refined by the driver once open

find classmethod

find(**kwargs) -> list

[DeviceInfo] of the units of this driver that are attached, for pysdrlib.find. A driver that can list them overrides it (it must not open a radio, and takes addresses and/or timeout if it can look at a network: see pysdrlib.find); by default there are none to list, and pysdrlib.open(name, ...) is how it is opened

Source code in src/pysdrlib/base/device.py
@classmethod
def find(cls, **kwargs) -> list:
    """[DeviceInfo] of the units of this driver that are attached, for `pysdrlib.find`. A driver that can list them
    overrides it (it must not open a radio, and takes `addresses` and/or `timeout` if it can look at a network:
    see `pysdrlib.find`); by default there are none to list, and `pysdrlib.open(name, ...)` is how it is opened"""
    return []

open

open(*args, **kwargs)

Connect to device. serial=...: the unit with this serial number (where the driver can choose)

Source code in src/pysdrlib/base/device.py
def open(self, *args, **kwargs):
    """Connect to device. serial=...: the unit with this serial number (where the driver can choose)"""
    if self.state["open"]:
        self.log.warning("Device is already open!")
        return
    if "serial" in kwargs:
        kwargs["serial_number"] = kwargs.pop("serial")
    self.log.trace("open(args:%s, kwargs:%s)", args, kwargs)
    self.device = self._open(*args, **kwargs)
    self.state["open"] = True
    self._caps = None
    _OPEN.add(self)
    if type(self).TUNE_AT_OPEN:
        try:
            self._tune_as_reported()
        except BaseException:
            self.close()
            raise

initialize

initialize(cf=None, Fs=None, rx_gain=None, tx_gain=None, rx_gain_db=None, tx_gain_db=None)

Tune the receiver (and the transmitter, where it has its own synthesizer) to cf and Fs, and set the gains. rx_gain and tx_gain are fractions of the device's range, as set_rx_gain takes; rx_gain_db and tx_gain_db are decibels, as set_rx_gain_db takes. Each is a number for the total, None (the defaults), or a dict of stages, {"IF": 16, "BB": 20} (see rx_gain_stages(); a stage not named keeps the device's). Not both for one direction

Source code in src/pysdrlib/base/device.py
def initialize(self, cf=None, Fs=None, rx_gain=None, tx_gain=None, rx_gain_db=None, tx_gain_db=None):
    """Tune the receiver (and the transmitter, where it has its own synthesizer) to `cf` and `Fs`, and set the gains.
    `rx_gain` and `tx_gain` are fractions of the device's range, as `set_rx_gain` takes; `rx_gain_db` and `tx_gain_db`
    are decibels, as `set_rx_gain_db` takes. Each is a number for the total, None (the defaults), or a dict of
    stages, `{"IF": 16, "BB": 20}` (see `rx_gain_stages()`; a stage not named keeps the device's). Not both for one direction"""
    self.log.trace("initialize(cf=%s, Fs=%s, rx_gain=%s, tx_gain=%s, rx_gain_db=%s, tx_gain_db=%s)",
                   cf, Fs, rx_gain, tx_gain, rx_gain_db, tx_gain_db)
    self._ensure_open("initialize")
    cf = self.set_rx_freq(cf)
    Fs = self.set_rx_sample_rate(Fs)
    can_tx = type(self).CAN_TRANSMIT and bool(self.caps.channels.get("tx"))   # (this unit, as opened, may not)
    if can_tx and self.caps.shared.get("freq") != "device":   # a transmitter of its own
        self.set_tx_freq(cf)
    if can_tx and self.caps.shared.get("rate") != "device":
        self.set_tx_sample_rate(Fs)
    rx_gain = self._initial_gain("rx", rx_gain, rx_gain_db)
    tx_gain = self._initial_gain("tx", tx_gain, tx_gain_db) if can_tx else None
    self._initialize(cf, Fs, rx_gain, tx_gain)   # (the hook gets the total gains in dB)

close

close()

Disconnect from device, stopping what is streaming first

Source code in src/pysdrlib/base/device.py
def close(self):
    """Disconnect from device, stopping what is streaming first"""
    self.log.trace("close()")
    self._ensure_open("close")
    for direction, stop in (("rx", self.stop_rx), ("tx", self.stop_tx)):
        if self.state[direction]:
            try:
                stop()
            except Exception as exc:   # (a device that is gone must still close)
                self.log.warning("close: stop_%s failed: %s", direction, exc)
    self._close()
    self.state.update(open=False, rx=False, tx=False)
    self._caps = None
    _OPEN.discard(self)

start_rx

start_rx(channels=None)

Start receiving. channels: which to stream together (default: the last ones, at first channel 0); read(..., channel=...) reads them

Source code in src/pysdrlib/base/device.py
def start_rx(self, channels=None):
    """Start receiving. channels: which to stream together (default: the last ones, at first channel 0);
    `read(..., channel=...)` reads them"""
    if self.state["rx"]:
        self.log.warning("Device is already receiving!")
        return
    self.log.trace("start_rx(%s)", channels)
    self._ensure_open("start_rx")
    if channels is not None:
        chs = self._channel_list("rx", channels)
        if chs != (0,) or self._rx_channels != (0,):
            self._set_rx_channels(chs)
        self._rx_channels = chs
    self._rx_reset()
    for ch in self._rx_channels:   # what the stream starts at: a block from before a later change keeps saying so
        d = self._direction("rx", ch)
        self._rx_now[("freq", ch)] = self._tuning.get(("freq", d, ch), self._cf)
        self._rx_now[("rate", ch)] = self._tuning.get(("rate", d, ch), self._Fs)
    self._start_rx()
    self.state["rx"] = True

stop_rx

stop_rx()

Stop receiving

Source code in src/pysdrlib/base/device.py
def stop_rx(self):
    """Stop receiving"""
    if not self.state["rx"]:
        self.log.warning("Device isn't receiving!")
        return
    self.log.trace("stop_rx()")
    self._ensure_open("stop_rx")
    self._stop_rx()
    self.state["rx"] = False

get_samples

get_samples() -> np.ndarray

The low-level call: whatever has arrived since the last call (any number, possibly none, without waiting). Most code wants read (an exact count, waiting for it, with the stream's metadata) or stream (blocks until you stop)

Source code in src/pysdrlib/base/device.py
def get_samples(self) -> np.ndarray:
    """The low-level call: whatever has arrived since the last call (any number, possibly none, without waiting). Most
    code wants `read` (an exact count, waiting for it, with the stream's metadata) or `stream` (blocks until you stop)"""
    # self.log.trace("get_samples()")
    self._ensure_open("get_samples")
    x, first = self._rx_take_all()
    if len(x):   # handed out: the next `read` follows on, rather than reporting them lost
        self._rx_next[self._rx_channels[0]] = first + len(x)
    return x

start_tx

start_tx(channels=None)

Start transmitting (then write). channels: which to transmit together (default: the last ones, at first 0)

Source code in src/pysdrlib/base/device.py
def start_tx(self, channels=None):
    """Start transmitting (then `write`). channels: which to transmit together (default: the last ones, at first 0)"""
    if self.state["tx"]:
        self.log.warning("Device is already transmitting!")
        return
    self.log.trace("start_tx(%s)", channels)
    self._ensure_open("start_tx")
    if not self.caps.channels.get("tx"):
        raise err.NotSupported(f"{type(self).NAME} can't transmit")
    if channels is not None:
        chs = self._channel_list("tx", channels)
        if chs != (0,) or self._tx_channels != (0,):
            self._set_tx_channels(chs)
        self._tx_channels = chs
    self._tx_epoch += 1
    self._tx_ahead = {}
    self._start_tx()
    self.state["tx"] = True

stop_tx

stop_tx()

Stop transmitting

Source code in src/pysdrlib/base/device.py
def stop_tx(self):
    """Stop transmitting"""
    if not self.state["tx"]:
        self.log.warning("Device isn't transmitting!")
        return
    self.log.trace("stop_tx()")
    self._ensure_open("stop_tx")
    self._tx_epoch += 1   # first: a `write` another thread is in ends, not waiting on a queue that is stopping
    self._tx_ahead = {}
    self._stop_tx()
    self.state["tx"] = False

set_rx_sample_rate

set_rx_sample_rate(Fs=None, channel=0, flush=False)

Set the receive sample rate (the nominal one: a frequency correction is applied to what the hardware is asked for). What else changes with it: caps.shared["rate"] (a device with one clock for both directions sets both). flush: while receiving, discard the samples from before the change. Returns the rate in effect

Source code in src/pysdrlib/base/device.py
def set_rx_sample_rate(self, Fs=None, channel=0, flush=False):
    """Set the receive sample rate (the nominal one: a frequency correction is applied to what the hardware is asked
    for). What else changes with it: `caps.shared["rate"]` (a device with one clock for both directions sets both).
    flush: while receiving, discard the samples from before the change. Returns the rate in effect"""
    return self._tune_rate(Fs, "rx", channel, flush)

set_tx_sample_rate

set_tx_sample_rate(Fs=None, channel=0)

Set the transmit sample rate (see set_rx_sample_rate). Raises err.NotSupported on a receiver

Source code in src/pysdrlib/base/device.py
def set_tx_sample_rate(self, Fs=None, channel=0):
    """Set the transmit sample rate (see `set_rx_sample_rate`). Raises `err.NotSupported` on a receiver"""
    return self._tune_rate(Fs, "tx", channel, False)

get_rx_sample_rate

get_rx_sample_rate(channel=0)

Receive sample rate [Hz] last set for this channel

Source code in src/pysdrlib/base/device.py
def get_rx_sample_rate(self, channel=0):
    """Receive sample rate [Hz] last set for this channel"""
    return self._tuning.get(("rate", self._direction("rx", channel), channel), self._Fs)

get_tx_sample_rate

get_tx_sample_rate(channel=0)

Transmit sample rate [Hz] last set for this channel (None: never set)

Source code in src/pysdrlib/base/device.py
def get_tx_sample_rate(self, channel=0):
    """Transmit sample rate [Hz] last set for this channel (None: never set)"""
    return self._tuning.get(("rate", self._direction("tx", channel), channel))

set_rx_freq

set_rx_freq(freq=None, channel=0, flush=False)

Set the receive center frequency (corrected by set_freq_correction). What else moves with it: caps.shared["freq"] (channels sharing a synthesizer, or both directions on a device with one). flush: while receiving, discard what was received before the change and the device's settling time after it (caps.retune_settle), so the next read is all at the new frequency. Returns the frequency

Source code in src/pysdrlib/base/device.py
def set_rx_freq(self, freq=None, channel=0, flush=False):
    """Set the receive center frequency (corrected by `set_freq_correction`). What else moves with it:
    `caps.shared["freq"]` (channels sharing a synthesizer, or both directions on a device with one).
    flush: while receiving, discard what was received before the change and the device's settling time
    after it (`caps.retune_settle`), so the next `read` is all at the new frequency. Returns the frequency"""
    return self._tune_freq(freq, "rx", channel, flush)

set_tx_freq

set_tx_freq(freq=None, channel=0)

Set the transmit center frequency (see set_rx_freq). Raises err.NotSupported on a receiver

Source code in src/pysdrlib/base/device.py
def set_tx_freq(self, freq=None, channel=0):
    """Set the transmit center frequency (see `set_rx_freq`). Raises `err.NotSupported` on a receiver"""
    return self._tune_freq(freq, "tx", channel, False)

get_rx_inverted

get_rx_inverted(channel=0)

Whether the receive spectrum comes mirrored, from a converter whose LO is above the signal (see caps.Chain): flip it (samples[::-1] of the spectrum, or conjugate the samples) to read it the right way round

Source code in src/pysdrlib/base/device.py
def get_rx_inverted(self, channel=0):
    """Whether the receive spectrum comes mirrored, from a converter whose LO is above the signal (see `caps.Chain`):
    flip it (`samples[::-1]` of the spectrum, or conjugate the samples) to read it the right way round"""
    chain = self._chain("rx", channel)
    return bool(chain and chain.invert)

get_rx_context

get_rx_context(channel=0)

How this channel's samples are received, for a recording to keep (RxContext): the frequency over the air and the rate, the chain (its LO, whether it inverts), the reference correction and clock source, gains, antenna port

Source code in src/pysdrlib/base/device.py
def get_rx_context(self, channel=0):
    """How this channel's samples are received, for a recording to keep (`RxContext`): the frequency over the air and
    the rate, the chain (its LO, whether it inverts), the reference correction and clock source, gains, antenna port"""
    serial = self.caps.info.get("serial")
    cal = self.get_level_calibration(channel)
    held = cal is not None and cal["holds"]
    return RxContext(freq=self.get_rx_freq(channel), rate=self.get_rx_sample_rate(channel), chain=self._chain("rx", channel),
                     ppm=self.get_freq_correction(channel), ppm_accuracy=self.get_freq_correction_accuracy(channel), clock_source=self._clock_source, gains=self.get_rx_gains_db(channel),
                     level_offset=cal["offset_db"] if held else None, level_accuracy=cal["accuracy"] if held else None,
                     port=self.get_rx_antenna(channel), hw=f"{type(self).NAME}" + (f" {serial}" if serial else ""))

set_level_calibration

set_level_calibration(offset_db, accuracy=None, span=None, channel=0)

What a level in these samples is at the antenna port: dBm = dBFS + offset_db, where dBFS has full scale at |x| = 1 in the complex64 samples read returns. Measured at, and holding for, the receive gains (and gain mode) and frequency current now: get_rx_context carries it (level_offset, level_accuracy) while the gains are unchanged and the frequency is within span, and says None otherwise. accuracy: a standard error [dB] (None: not known). span: the width [Hz] centred on the frequency now that it holds over (None: the sample rate now, the band it was measured in). offset_db None: forget it. Returns get_level_calibration

Source code in src/pysdrlib/base/device.py
def set_level_calibration(self, offset_db, accuracy=None, span=None, channel=0):
    """What a level in these samples is at the antenna port: dBm = dBFS + `offset_db`, where dBFS has full scale at
    |x| = 1 in the complex64 samples `read` returns. Measured at, and holding for, the receive gains (and gain mode)
    and frequency current now: `get_rx_context` carries it (`level_offset`, `level_accuracy`) while the gains are
    unchanged and the frequency is within `span`, and says None otherwise. accuracy: a standard error [dB] (None:
    not known). span: the width [Hz] centred on the frequency now that it holds over (None: the sample rate now, the
    band it was measured in). offset_db None: forget it. Returns `get_level_calibration`"""
    self._ensure_open("set_level_calibration")
    self._check_channel("rx", channel)
    if offset_db is None:
        self._level_cal.pop(channel, None)
        return None
    if accuracy is not None and not accuracy >= 0:
        raise ValueError(f"accuracy is a standard error in dB (>= 0), not {accuracy!r}")
    if span is None:
        span = self.get_rx_sample_rate(channel)
    if span is None or not span > 0:
        raise ValueError(f"span is a width in Hz (> 0), not {span!r}: give one, or set a sample rate first")
    self._level_cal[channel] = {"offset_db": float(offset_db), "accuracy": None if accuracy is None else float(accuracy),
                                "freq": float(self.get_rx_freq(channel)), "span": float(span),
                                "gains": self._level_gains(channel)}
    return self.get_level_calibration(channel)

get_level_calibration

get_level_calibration(channel=0)

The level calibration given to set_level_calibration (None: none): {"offset_db", "accuracy", "freq", "span", "gains", "gain_mode", "holds"}, where freq, span, gains and gain_mode are what it was made at, and holds says whether the gains and frequency now are still those

Source code in src/pysdrlib/base/device.py
def get_level_calibration(self, channel=0):
    """The level calibration given to `set_level_calibration` (None: none): {"offset_db", "accuracy", "freq", "span",
    "gains", "gain_mode", "holds"}, where freq, span, gains and gain_mode are what it was made at, and holds says whether the gains and
    frequency now are still those"""
    cal = self._level_cal.get(channel)
    if cal is None:
        return None
    freq = self.get_rx_freq(channel)
    holds = cal["gains"] == self._level_gains(channel) and freq is not None and abs(freq - cal["freq"]) <= cal["span"] / 2
    return {**cal, "gains": dict(cal["gains"]["db"]), "gain_mode": cal["gains"]["mode"], "holds": bool(holds)}

get_rx_freq

get_rx_freq(channel=0)

Receive center frequency [Hz] last set for this channel (over the air, whatever converter is on the radio)

Source code in src/pysdrlib/base/device.py
def get_rx_freq(self, channel=0):
    """Receive center frequency [Hz] last set for this channel (over the air, whatever converter is on the radio)"""
    return self._tuning.get(("freq", self._direction("rx", channel), channel), self._cf)

get_tx_freq

get_tx_freq(channel=0)

Transmit center frequency [Hz] last set for this channel (None: never set)

Source code in src/pysdrlib/base/device.py
def get_tx_freq(self, channel=0):
    """Transmit center frequency [Hz] last set for this channel (None: never set)"""
    return self._tuning.get(("freq", self._direction("tx", channel), channel))

set_freq_correction

set_freq_correction(ppm, channel=0, accuracy=None)

Error of the device's frequency reference in parts per million (positive: it runs fast). Tuning and sample rate are both corrected, so set_rx_freq(f) gives f and set_rx_sample_rate(r) gives r (the rate only where the device has continuous rates). Re-applies them. accuracy: how well ppm is known, a standard error [ppm] (a calibration's; None: not known), which get_rx_context passes on so a reader can say what a frequency is worth

Source code in src/pysdrlib/base/device.py
def set_freq_correction(self, ppm, channel=0, accuracy=None):
    """Error of the device's frequency reference in parts per million (positive: it runs fast). Tuning and
    sample rate are both corrected, so `set_rx_freq(f)` gives f and `set_rx_sample_rate(r)` gives r (the rate only
    where the device has continuous rates). Re-applies them. accuracy: how well `ppm` is known, a standard error
    [ppm] (a calibration's; None: not known), which `get_rx_context` passes on so a reader can say what a frequency is worth"""
    self._ensure_open("set_freq_correction")
    self._check_channel("rx", channel)
    if accuracy is not None and not accuracy >= 0:
        raise ValueError(f"accuracy is a standard error in ppm (>= 0), not {accuracy!r}")
    self._ppm = float(ppm)
    self._ppm_accuracy = None if accuracy is None else float(accuracy)
    for kind, setter in (("freq", self._tune_freq), ("rate", self._tune_rate)):
        shared = self.caps.shared.get(kind, "channel")
        both = self._tuning.get((kind, "rx", 0)) == self._tuning.get((kind, "tx", 0))
        applied = False
        for (k, d, ch), value in sorted(self._tuning.items(), key=lambda kv: (kv[0][1], kv[0][2])):
            if k != kind or (shared != "channel" and ch) or ((shared == "device" or both) and d != "rx" and not ch):
                continue   # one call per synthesizer / clock
            setter(value, None if shared == "device" or (both and not ch) else d, ch, False)
            applied = True
        if not applied:
            setter(self._cf if kind == "freq" else self._Fs, None, channel, False)
    return self._ppm

get_freq_correction

get_freq_correction(channel=0)

Frequency reference error [ppm] last set with set_freq_correction

Source code in src/pysdrlib/base/device.py
def get_freq_correction(self, channel=0):
    """Frequency reference error [ppm] last set with `set_freq_correction`"""
    return self._ppm

get_freq_correction_accuracy

get_freq_correction_accuracy(channel=0)

How well the reference's error is known [ppm, a standard error], as given to set_freq_correction (None: not known)

Source code in src/pysdrlib/base/device.py
def get_freq_correction_accuracy(self, channel=0):
    """How well the reference's error is known [ppm, a standard error], as given to `set_freq_correction` (None: not known)"""
    return self._ppm_accuracy

set_rx_gain

set_rx_gain(fraction=None, stage=None, channel=0, flush=False)

The receive gain, as a fraction of the device's range: 0.0 its least, 1.0 its most (linear in dB), of the total or of one stage. None: the defaults. The same fraction is the same place in the range on every device, so this is the call for code that should run on more than one kind of radio: 40 dB is most of one radio's gain range, and a third of another's. It takes a fraction, not decibels (for those, set_rx_gain_db): a value outside 0-1 raises err.InvalidValue rather than being clamped, because it is nearly always decibels given to the wrong call, and clamping would set the most gain. flush: while receiving, discard what was received before the change and its settling time (see set_rx_freq). Returns the fraction in effect

Source code in src/pysdrlib/base/device.py
def set_rx_gain(self, fraction=None, stage=None, channel=0, flush=False):
    """The receive gain, as a fraction of the device's range: 0.0 its least, 1.0 its most (linear in dB), of the total
    or of one `stage`. None: the defaults. The same fraction is the same place in the range on every device, so this is
    the call for code that should run on more than one kind of radio: 40 dB is most of one radio's gain range, and a
    third of another's. It takes a fraction, not decibels (for those, `set_rx_gain_db`): a value outside 0-1 raises
    `err.InvalidValue` rather than being clamped, because it is nearly always decibels given to the wrong call, and
    clamping would set the most gain. flush: while receiving, discard what was received before the change and its
    settling time (see `set_rx_freq`). Returns the fraction in effect"""
    return self._set_gain(fraction, "rx", stage, channel, flush)

set_tx_gain

set_tx_gain(fraction=None, stage=None, channel=0)

The transmit gain, as a fraction of the device's range (see set_rx_gain). Returns the fraction in effect

Source code in src/pysdrlib/base/device.py
def set_tx_gain(self, fraction=None, stage=None, channel=0):
    """The transmit gain, as a fraction of the device's range (see `set_rx_gain`). Returns the fraction in effect"""
    return self._set_gain(fraction, "tx", stage, channel, False)

get_rx_gain

get_rx_gain(stage=None, channel=0)

The receive gain last set, as a fraction of the device's range (None before a gain was set); get_rx_gain_db has decibels

Source code in src/pysdrlib/base/device.py
def get_rx_gain(self, stage=None, channel=0):
    """The receive gain last set, as a fraction of the device's range (None before a gain was set); `get_rx_gain_db`
    has decibels"""
    return self._get_gain("rx", stage, channel)

get_tx_gain

get_tx_gain(stage=None, channel=0)

The transmit gain last set, as a fraction of the device's range (None before a gain was set)

Source code in src/pysdrlib/base/device.py
def get_tx_gain(self, stage=None, channel=0):
    """The transmit gain last set, as a fraction of the device's range (None before a gain was set)"""
    return self._get_gain("tx", stage, channel)

set_rx_gain_db

set_rx_gain_db(gain=None, stage=None, channel=0, flush=False)

The receive gain in decibels: a total (the device splits it across its stages) or one stage's. None: the defaults. Decibels mean different things on different radios; for code that should run on any of them use set_rx_gain. Returns the gain in effect (the total, or the stage's)

Source code in src/pysdrlib/base/device.py
def set_rx_gain_db(self, gain=None, stage=None, channel=0, flush=False):
    """The receive gain in decibels: a total (the device splits it across its stages) or one `stage`'s. None: the
    defaults. Decibels mean different things on different radios; for code that should run on any of them use
    `set_rx_gain`. Returns the gain in effect (the total, or the stage's)"""
    return self._set_gain_db("rx", gain, stage, channel, flush)

set_tx_gain_db

set_tx_gain_db(gain=None, stage=None, channel=0)

The transmit gain in decibels (see set_rx_gain_db). Returns the gain in effect

Source code in src/pysdrlib/base/device.py
def set_tx_gain_db(self, gain=None, stage=None, channel=0):
    """The transmit gain in decibels (see `set_rx_gain_db`). Returns the gain in effect"""
    return self._set_gain_db("tx", gain, stage, channel, False)

get_rx_gain_db

get_rx_gain_db(stage=None, channel=0)

The receive gain last set in decibels: a stage's, or the total of the stages (None before any was set)

Source code in src/pysdrlib/base/device.py
def get_rx_gain_db(self, stage=None, channel=0):
    """The receive gain last set in decibels: a stage's, or the total of the stages (None before any was set)"""
    return self._get_gain_db("rx", stage, channel)

get_tx_gain_db

get_tx_gain_db(stage=None, channel=0)

The transmit gain last set in decibels: a stage's, or the total of the stages (None before any was set)

Source code in src/pysdrlib/base/device.py
def get_tx_gain_db(self, stage=None, channel=0):
    """The transmit gain last set in decibels: a stage's, or the total of the stages (None before any was set)"""
    return self._get_gain_db("tx", stage, channel)

get_rx_gains_db

get_rx_gains_db(channel=0)

{stage name: gain [dB]} of what each receive stage was last set to (stages never set are missing)

Source code in src/pysdrlib/base/device.py
def get_rx_gains_db(self, channel=0):
    """{stage name: gain [dB]} of what each receive stage was last set to (stages never set are missing)"""
    return self._get_gains_db("rx", channel)

get_tx_gains_db

get_tx_gains_db(channel=0)

{stage name: gain [dB]} of what each transmit stage was last set to

Source code in src/pysdrlib/base/device.py
def get_tx_gains_db(self, channel=0):
    """{stage name: gain [dB]} of what each transmit stage was last set to"""
    return self._get_gains_db("tx", channel)

rx_gain_stages

rx_gain_stages(channel=0)

{stage name: GainStage} of the receiver, as the device names its stages (stage= of the gain calls)

Source code in src/pysdrlib/base/device.py
def rx_gain_stages(self, channel=0):
    """{stage name: GainStage} of the receiver, as the device names its stages (`stage=` of the gain calls)"""
    return dict(self.caps.gains[self._direction("rx", channel)])

tx_gain_stages

tx_gain_stages(channel=0)

{stage name: GainStage} of the transmitter

Source code in src/pysdrlib/base/device.py
def tx_gain_stages(self, channel=0):
    """{stage name: GainStage} of the transmitter"""
    return dict(self.caps.gains[self._direction("tx", channel)])

rx_gain_modes

rx_gain_modes(channel=0)

["manual"] and, when the receiver can set its own gain, "auto"

Source code in src/pysdrlib/base/device.py
def rx_gain_modes(self, channel=0):
    """["manual"] and, when the receiver can set its own gain, "auto\""""
    return list(self.caps.gain_modes[self._direction("rx", channel)])

tx_gain_modes

tx_gain_modes(channel=0)

The transmitter's gain modes (["manual"])

Source code in src/pysdrlib/base/device.py
def tx_gain_modes(self, channel=0):
    """The transmitter's gain modes (["manual"])"""
    return list(self.caps.gain_modes[self._direction("tx", channel)])

set_rx_gain_mode

set_rx_gain_mode(mode, channel=0)

"auto": the receiver sets its own gain (AGC), "manual": the gain last set. Raises err.NotSupported for a mode the device lacks

Source code in src/pysdrlib/base/device.py
def set_rx_gain_mode(self, mode, channel=0):
    """"auto": the receiver sets its own gain (AGC), "manual": the gain last set. Raises `err.NotSupported` for a mode
    the device lacks"""
    return self._set_gain_mode_of("rx", mode, channel)

set_tx_gain_mode

set_tx_gain_mode(mode, channel=0)

The transmitter's gain mode (see set_rx_gain_mode)

Source code in src/pysdrlib/base/device.py
def set_tx_gain_mode(self, mode, channel=0):
    """The transmitter's gain mode (see `set_rx_gain_mode`)"""
    return self._set_gain_mode_of("tx", mode, channel)

get_rx_gain_mode

get_rx_gain_mode(channel=0)

Current receive gain mode, "manual" unless set_rx_gain_mode changed it

Source code in src/pysdrlib/base/device.py
def get_rx_gain_mode(self, channel=0):
    """Current receive gain mode, "manual" unless `set_rx_gain_mode` changed it"""
    return self._gain_mode.get((self._direction("rx", channel), channel), "manual")

get_tx_gain_mode

get_tx_gain_mode(channel=0)

Current transmit gain mode

Source code in src/pysdrlib/base/device.py
def get_tx_gain_mode(self, channel=0):
    """Current transmit gain mode"""
    return self._gain_mode.get((self._direction("tx", channel), channel), "manual")

set_rx_bandwidth

set_rx_bandwidth(bandwidth=None, channel=0)

Receive analog filter bandwidth [Hz]: the narrowest the device has that is at least bandwidth (None: the sample rate). Returns the bandwidth set

Source code in src/pysdrlib/base/device.py
def set_rx_bandwidth(self, bandwidth=None, channel=0):
    """Receive analog filter bandwidth [Hz]: the narrowest the device has that is at least `bandwidth` (None: the
    sample rate). Returns the bandwidth set"""
    return self._set_bandwidth_of("rx", bandwidth, channel)

set_tx_bandwidth

set_tx_bandwidth(bandwidth=None, channel=0)

Transmit analog filter bandwidth [Hz] (see set_rx_bandwidth). Returns the bandwidth set

Source code in src/pysdrlib/base/device.py
def set_tx_bandwidth(self, bandwidth=None, channel=0):
    """Transmit analog filter bandwidth [Hz] (see `set_rx_bandwidth`). Returns the bandwidth set"""
    return self._set_bandwidth_of("tx", bandwidth, channel)

get_rx_bandwidth

get_rx_bandwidth(channel=0)

Receive analog filter bandwidth [Hz] last set (None: never set)

Source code in src/pysdrlib/base/device.py
def get_rx_bandwidth(self, channel=0):
    """Receive analog filter bandwidth [Hz] last set (None: never set)"""
    return self._bandwidth.get((self._direction("rx", channel), channel))

get_tx_bandwidth

get_tx_bandwidth(channel=0)

Transmit analog filter bandwidth [Hz] last set (None: never set)

Source code in src/pysdrlib/base/device.py
def get_tx_bandwidth(self, channel=0):
    """Transmit analog filter bandwidth [Hz] last set (None: never set)"""
    return self._bandwidth.get((self._direction("tx", channel), channel))

rx_antennas

rx_antennas(channel=0)

The receiver's selectable antenna ports ([]: just the one)

Source code in src/pysdrlib/base/device.py
def rx_antennas(self, channel=0):
    """The receiver's selectable antenna ports ([]: just the one)"""
    return list(self.caps.antennas[self._direction("rx", channel)])

tx_antennas

tx_antennas(channel=0)

The transmitter's selectable antenna ports ([]: just the one)

Source code in src/pysdrlib/base/device.py
def tx_antennas(self, channel=0):
    """The transmitter's selectable antenna ports ([]: just the one)"""
    return list(self.caps.antennas[self._direction("tx", channel)])

rx_antenna_info

rx_antenna_info(channel=0)

Each receive antenna port and what is on it, as rx_antennas lists them (one entry, port None, when there is just the one): [{"port", "chain", "antenna", "inverted", "selected"}]. chain: the name of the caps.Chain the port goes through (None: none declared); antenna: Chain.describe() of the antenna fitted (None: not known; pysdrlib.base.antennas.format_antenna makes text of it); inverted: whether the spectrum comes mirrored there (see get_rx_inverted); selected: whether it is the port in use (None for each of several when none was ever selected: the radio's default)

Source code in src/pysdrlib/base/device.py
def rx_antenna_info(self, channel=0):
    """Each receive antenna port and what is on it, as `rx_antennas` lists them (one entry, port None, when there is
    just the one): [{"port", "chain", "antenna", "inverted", "selected"}]. chain: the name of the `caps.Chain` the
    port goes through (None: none declared); antenna: `Chain.describe()` of the antenna fitted (None: not known;
    `pysdrlib.base.antennas.format_antenna` makes text of it); inverted: whether the spectrum comes mirrored there
    (see `get_rx_inverted`); selected: whether it is the port in use (None for each of several when none was ever
    selected: the radio's default)"""
    return self._antenna_info("rx", channel)

tx_antenna_info

tx_antenna_info(channel=0)

Each transmit antenna port and what is on it: as rx_antenna_info

Source code in src/pysdrlib/base/device.py
def tx_antenna_info(self, channel=0):
    """Each transmit antenna port and what is on it: as `rx_antenna_info`"""
    return self._antenna_info("tx", channel)

set_rx_antenna

set_rx_antenna(name, channel=0)

Select a receive antenna port by name (see rx_antennas). Raises err.NotSupported for a name the device lacks

Source code in src/pysdrlib/base/device.py
def set_rx_antenna(self, name, channel=0):
    """Select a receive antenna port by name (see `rx_antennas`). Raises `err.NotSupported` for a name the device lacks"""
    return self._set_antenna_of("rx", name, channel)

set_tx_antenna

set_tx_antenna(name, channel=0)

Select a transmit antenna port by name (see tx_antennas)

Source code in src/pysdrlib/base/device.py
def set_tx_antenna(self, name, channel=0):
    """Select a transmit antenna port by name (see `tx_antennas`)"""
    return self._set_antenna_of("tx", name, channel)

get_rx_antenna

get_rx_antenna(channel=0)

The receive antenna port last selected (None: never set)

Source code in src/pysdrlib/base/device.py
def get_rx_antenna(self, channel=0):
    """The receive antenna port last selected (None: never set)"""
    return self._antenna.get((self._direction("rx", channel), channel))

get_tx_antenna

get_tx_antenna(channel=0)

The transmit antenna port last selected (None: never set)

Source code in src/pysdrlib/base/device.py
def get_tx_antenna(self, channel=0):
    """The transmit antenna port last selected (None: never set)"""
    return self._antenna.get((self._direction("tx", channel), channel))

clock_sources

clock_sources()

Reference clock sources ([]: not selectable)

Source code in src/pysdrlib/base/device.py
def clock_sources(self):
    """Reference clock sources ([]: not selectable)"""
    return list(self.caps.clock_sources)

set_clock_source

set_clock_source(name)

Select the reference clock by name (see clock_sources). Raises err.NotSupported for a name the device lacks

Source code in src/pysdrlib/base/device.py
def set_clock_source(self, name):
    """Select the reference clock by name (see `clock_sources`). Raises `err.NotSupported` for a name the device lacks"""
    self._ensure_open("set_clock_source")
    if name not in self.caps.clock_sources:
        raise err.NotSupported(f"{type(self).NAME} has no clock source {name!r} (it has {self.caps.clock_sources})")
    self._set_clock_source(name)
    self._clock_source = name
    return name

get_clock_source

get_clock_source()

The reference clock last selected (None: never set)

Source code in src/pysdrlib/base/device.py
def get_clock_source(self):
    """The reference clock last selected (None: never set)"""
    return self._clock_source

set_bias_t

set_bias_t(bias)

Set bias-t

Source code in src/pysdrlib/base/device.py
def set_bias_t(self, bias):
    """Set bias-t"""
    self.log.trace("set_bias_t(%s)", bias)
    self._ensure_open("set_bias_t")
    self._set_bias_t(bias)
    self._settings[("bias_t", 0)] = bool(bias)

settings

settings()

{name: caps.Setting}: everything else this device can be told (dither, AGC, test modes...)

Source code in src/pysdrlib/base/device.py
def settings(self):
    """{name: caps.Setting}: everything else this device can be told (dither, AGC, test modes...)"""
    return dict(self.caps.settings)

set_setting

set_setting(name, value, channel=0)

Apply one of settings() (to channel, where the setting is per channel). Returns the value set

Source code in src/pysdrlib/base/device.py
def set_setting(self, name, value, channel=0):
    """Apply one of `settings()` (to `channel`, where the setting is per channel). Returns the value set"""
    self._ensure_open("set_setting")
    self._check_channel("rx", channel)
    spec = self.caps.settings.get(name)
    if spec is None:
        raise err.NotSupported(f"{type(self).NAME} has no setting {name!r} (it has {list(self.caps.settings)})")
    value = spec.kind(value)
    if spec.choices is not None and value not in spec.choices:
        raise err.InvalidValue(f"{name} must be one of {spec.choices}, not {value!r}")
    method = getattr(self, spec.method)
    method(value, channel=channel) if spec.per_channel else method(value)
    self._settings[(name, channel)] = value
    return value

get_setting

get_setting(name, channel=0)

Value of a device specific setting listed in caps.settings. Raises err.NotSupported for an unknown name

Source code in src/pysdrlib/base/device.py
def get_setting(self, name, channel=0):
    """Value of a device specific setting listed in `caps.settings`. Raises `err.NotSupported` for an unknown name"""
    spec = self.caps.settings.get(name)
    if spec is None:
        raise err.NotSupported(f"{type(self).NAME} has no setting {name!r}")
    if spec.getter:
        getter = getattr(self, spec.getter)
        return getter(channel=channel) if spec.per_channel else getter()
    return self._settings.get((name, channel), spec.default)

set_chains

set_chains(chains)

The hardware between this radio and the air (caps.Chain: an LNB, a converter, and the antenna on it), for a radio on this machine (a server's are in its frontends file, pysdrlib.remote.frontends). Frequencies are over the air from then on: the radio tunes the chain's IF. [] or None: back to the driver's own. The radio stays where it is tuned: get_rx_freq (and a stream's metadata) then says what that is over the air

Source code in src/pysdrlib/base/device.py
def set_chains(self, chains):
    """The hardware between this radio and the air (`caps.Chain`: an LNB, a converter, and the antenna on it), for a
    radio on this machine (a server's are in its frontends file, `pysdrlib.remote.frontends`). Frequencies are over
    the air from then on: the radio tunes the chain's IF. [] or None: back to the driver's own.
    The radio stays where it is tuned: `get_rx_freq` (and a stream's metadata) then says what that is over the air"""
    for c in chains or []:
        if not isinstance(c, _caps.Chain):
            raise TypeError(f"set_chains takes caps.Chain, not {type(c).__name__}")
    tuned = [(key, self._chain(key[1], key[2])) for key in self._tuning if key[0] == "freq"]
    cf_chain = self._chain("rx", 0)
    self._chains = list(chains) if chains else None
    self._caps = None

    def moved(freq, direction, channel, before):   # the same radio frequency, through the new chain
        radio = freq if before is None else before.to_if(freq)
        after = self._chain(direction, channel)
        return radio if after is None else after.to_rf(radio)
    self._cf = moved(self._cf, "rx", 0, cf_chain)
    at = self._rx_mark()
    for key, before in tuned:
        self._tuning[key] = value = moved(self._tuning[key], key[1], key[2], before)
        if key[1] == "rx":
            self._note("freq", value, key[2], False, at=at)

get_chains

get_chains()

The chains in use (caps.chains)

Source code in src/pysdrlib/base/device.py
def get_chains(self):
    """The chains in use (`caps.chains`)"""
    return list(self.caps.chains)

get_caps

get_caps()

caps as plain types (what a remote client receives)

Source code in src/pysdrlib/base/device.py
def get_caps(self):
    """`caps` as plain types (what a remote client receives)"""
    return self.caps.json()

read

read(count, timeout=None, meta=False, channel=0, on_drop=None, latest=False)

Exactly count samples (complex64), waiting for them. Raises err.Timeout after timeout seconds (None: wait as long as the device delivers; a stalled device raises err.StreamStalled). meta=True returns (samples, RxMeta): the first sample's index, where samples were lost, retunes... channel: one of rx_channels, or several (a sequence): then a (channels, count) array whose rows start at the same sample index (the same instant), and a list of RxMeta. (Samples one channel alone lost inside the block move the rest of its row: see its gaps.) on_drop="raise": raise err.Dropped if samples were lost inside this block (RxMeta.gaps), for a capture that must be contiguous; the exception carries the block (.samples, .meta, .lost). None: return it anyway. latest=True: the newest count samples at the current settings, for a display: what is queued before them is skipped, and so is everything from before the last change of a setting (a retune, a new rate or gain...) and its settling (caps.retune_settle); if not enough has arrived since, wait for it. The skipped samples are counted in RxMeta.discarded, not as gaps. A remote viewer learns of its controller's changes from the stream, so a read made as one is still on its way returns samples from before it, and RxMeta.freq says so

Source code in src/pysdrlib/base/device.py
def read(self, count, timeout=None, meta=False, channel=0, on_drop=None, latest=False):
    """Exactly `count` samples (complex64), waiting for them. Raises err.Timeout after `timeout` seconds
    (None: wait as long as the device delivers; a stalled device raises err.StreamStalled).
    meta=True returns (samples, RxMeta): the first sample's index, where samples were lost, retunes...
    channel: one of `rx_channels`, or several (a sequence): then a (channels, count) array whose rows start at
    the same sample index (the same instant), and a list of RxMeta. (Samples one channel alone lost inside the block
    move the rest of its row: see its `gaps`.)
    on_drop="raise": raise err.Dropped if samples were lost inside this block (`RxMeta.gaps`), for a capture that
    must be contiguous; the exception carries the block (`.samples`, `.meta`, `.lost`). None: return it anyway.
    latest=True: the newest `count` samples at the current settings, for a display: what is queued before them
    is skipped, and so is everything from before the last change of a setting (a retune, a new rate or gain...) and
    its settling (`caps.retune_settle`); if not enough has arrived since, wait for it. The skipped samples are
    counted in `RxMeta.discarded`, not as gaps. A remote viewer learns of its controller's changes from the stream,
    so a read made as one is still on its way returns samples from before it, and `RxMeta.freq` says so"""
    _check_on_drop(on_drop)
    if latest:
        self._skip_to_latest(int(count), (channel,) if np.isscalar(channel) else tuple(channel))
    if not np.isscalar(channel):
        out, metas = self._read_aligned(int(count), timeout, True, tuple(channel))
        _gap_check(on_drop, out, metas)
        return (out, metas) if meta else out
    out = np.empty(int(count), dtype=np.complex64)
    m = self._read_into(out, timeout, channel)
    _gap_check(on_drop, out, m)
    return (out, m) if meta else out

read_into

read_into(out, timeout=None, meta=False, channel=0, on_drop=None)

read into a complex64 array you own (filled completely). Returns its length, or (length, RxMeta)

Source code in src/pysdrlib/base/device.py
def read_into(self, out, timeout=None, meta=False, channel=0, on_drop=None):
    """`read` into a complex64 array you own (filled completely). Returns its length, or (length, RxMeta)"""
    _check_on_drop(on_drop)
    if out.dtype != np.complex64 or not out.flags.c_contiguous:
        raise TypeError("read_into needs a contiguous complex64 array")
    m = self._read_into(out, timeout, channel)
    _gap_check(on_drop, out, m)
    return (len(out), m) if meta else len(out)

stream

stream(count, timeout=None, meta=False, channel=0, flush=True, on_drop=None, latest=False)

Blocks of count samples, in a with block that starts receiving (and stops it after) when it wasn't:

with sdr.stream(65536) as s:
    for x in s: ...

flush: when already receiving, discard what was queued before the stream starts. on_drop: as read's, for each block (an err.Dropped ends a for loop over the stream; call s.read() in a loop to carry on past one). latest: each block is the newest (see read), for a display that would rather skip than fall behind

Source code in src/pysdrlib/base/device.py
def stream(self, count, timeout=None, meta=False, channel=0, flush=True, on_drop=None, latest=False):
    """Blocks of `count` samples, in a `with` block that starts receiving (and stops it after) when it wasn't:

        with sdr.stream(65536) as s:
            for x in s: ...

    flush: when already receiving, discard what was queued before the stream starts. on_drop: as `read`'s, for
    each block (an err.Dropped ends a `for` loop over the stream; call `s.read()` in a loop to carry on past one).
    latest: each block is the newest (see `read`), for a display that would rather skip than fall behind"""
    _check_on_drop(on_drop)
    return RxStream(self, count, timeout, meta, channel, flush, on_drop, latest)

sweep

sweep(start, stop=None, step=None, count=65536, timeout=None, meta=False, channel=0, repeat=False, offset=0.0, skip=0, on_drop=None, retries=3)

Step the receiver across frequencies, yielding (frequency, samples): count samples at each, all received after its retune and settling (set_rx_freq(..., flush=True)):

for freq, x in sdr.sweep(88e6, 108e6, count=65536): ...          # start to stop (inclusive)
for freq, x in sdr.sweep([162.4e6, 162.55e6], count=4096): ...   # or a list of frequencies

step: Hz between steps (default: 80% of the sample rate, as a band's edges roll off). offset: tune this far above each frequency and shift the samples back, so the device's DC spike (its LO leaking through) lands offset Hz off the middle of each step's spectrum, not on it (the samples of an inverting chain stay mirrored, see get_rx_inverted). skip: samples to discard after each retune on top of the device's own settling (caps.retune_settle). repeat: sweep again and again, until the loop breaks. meta: yield (frequency, samples, RxMeta). on_drop: "raise" (as read's), or "retry": capture a step again when samples were lost inside it, up to retries times, then raise err.Dropped. Starts receiving if it wasn't, and stops it again when the sweep ends (or the loop breaks)

Source code in src/pysdrlib/base/device.py
def sweep(self, start, stop=None, step=None, count=65536, timeout=None, meta=False, channel=0, repeat=False,
          offset=0.0, skip=0, on_drop=None, retries=3):
    """Step the receiver across frequencies, yielding (frequency, samples): `count` samples at each, all received
    after its retune and settling (`set_rx_freq(..., flush=True)`):

        for freq, x in sdr.sweep(88e6, 108e6, count=65536): ...          # start to stop (inclusive)
        for freq, x in sdr.sweep([162.4e6, 162.55e6], count=4096): ...   # or a list of frequencies

    step: Hz between steps (default: 80% of the sample rate, as a band's edges roll off). offset: tune this far
    above each frequency and shift the samples back, so the device's DC spike (its LO leaking through) lands
    `offset` Hz off the middle of each step's spectrum, not on it (the samples of an inverting chain stay mirrored,
    see `get_rx_inverted`). skip: samples to discard after each retune on top
    of the device's own settling (`caps.retune_settle`). repeat: sweep again and again, until the loop breaks.
    meta: yield (frequency, samples, RxMeta). on_drop: "raise" (as `read`'s), or "retry": capture a step again
    when samples were lost inside it, up to `retries` times, then raise err.Dropped. Starts receiving if it wasn't,
    and stops it again when the sweep ends (or the loop breaks)"""
    if on_drop not in (None, "raise", "retry"):
        raise ValueError(f"on_drop is None, 'raise' or 'retry', not {on_drop!r}")
    if stop is None:
        freqs = np.asarray(list(np.atleast_1d(start)), dtype=float)
    else:
        if step is None:
            step = 0.8 * (self.get_rx_sample_rate(channel) or self.caps.default_rate)
        if step == 0 or (stop - start) * step < 0:
            raise ValueError(f"step {step} doesn't go from {start} to {stop}")
        freqs = start + step * np.arange(int(np.floor((stop - start) / step + 1e-9)) + 1)
    if not len(freqs):
        raise ValueError("no frequencies to sweep")
    started = not self.state["rx"]
    if started:
        self.start_rx(channels=None if channel in self._rx_channels else (channel,))
    shift, shift_of = None, None
    try:
        while True:
            for f in freqs:
                tuned = self.set_rx_freq(float(f) + offset, channel=channel, flush=True) - offset
                if skip:
                    self.read(int(skip), timeout=timeout, channel=channel)
                for attempt in range(int(retries) + 1 if on_drop == "retry" else 1):
                    try:
                        x, m = self.read(count, timeout=timeout, meta=True, channel=channel,
                                         on_drop="raise" if on_drop else None)
                        break
                    except err.Dropped as e:
                        if on_drop != "retry" or attempt == int(retries):
                            raise
                        self.log.debug("sweep at %g Hz lost %d samples: capturing it again", tuned, e.lost)
                if offset:
                    # the signal at `tuned` sat at -offset (+offset where the chain mirrors the spectrum)
                    up = -offset if self.get_rx_inverted(channel) else offset
                    if shift is None or len(shift) != count or shift_of != (up, m.rate):
                        shift_of = (up, m.rate)
                        shift = np.exp(2j * np.pi * up / m.rate * np.arange(count)).astype(np.complex64)
                    x *= shift   # bring it to the middle
                    m = dataclasses.replace(m, freq=m.freq - offset)
                yield (tuned, x, m) if meta else (tuned, x)
            if not repeat:
                break
    finally:
        if started and self.state["rx"]:
            self.stop_rx()

find_gain

find_gain(channel=0, count=65536, max_clip=0.0001, clip_level=0.98, headroom_db=0.0, confirm=None, timeout=None, skip=0)

The highest receive gain at which the signal doesn't clip, found by bisecting the gains the device can set (clipping only grows with gain), and set. Returns it as a fraction of the gain range:

sdr.find_gain()                        # -> 0.62: channel 0's gain, now in effect
sdr.find_gain(channel=[0, 1])          # -> {0: 0.62, 1: 0.71}: each channel's, from aligned reads

At each step the gain is set (skipping its settling, flush=True), skip more samples are discarded, and count are read; a block clips when more than max_clip of its samples have I or Q at clip_level of full scale or beyond. For a bursty signal (TDMA, WiFi, BLE...) count must span a burst: a window that misses them reads as clean. confirm: then read this many samples (default 4 * count) at the gain found, and step down while that clips. headroom_db: back off this much below the gain found. Channels whose gain is one setting (caps.shared["gain"]) get the gain at which none clips. The gain mode is set to "manual" (an AGC would undo it). Starts receiving if it wasn't, and stops it again; when already receiving, the channels must be among rx_channels. The result holds while the signal stays as it was

Source code in src/pysdrlib/base/device.py
def find_gain(self, channel=0, count=65536, max_clip=1e-4, clip_level=0.98, headroom_db=0.0, confirm=None,
              timeout=None, skip=0):
    """The highest receive gain at which the signal doesn't clip, found by bisecting the gains the device can set
    (clipping only grows with gain), and set. Returns it as a fraction of the gain range:

        sdr.find_gain()                        # -> 0.62: channel 0's gain, now in effect
        sdr.find_gain(channel=[0, 1])          # -> {0: 0.62, 1: 0.71}: each channel's, from aligned reads

    At each step the gain is set (skipping its settling, `flush=True`), `skip` more samples are discarded, and
    `count` are read; a block clips when more than `max_clip` of its samples have I or Q at `clip_level` of full
    scale or beyond. For a bursty signal (TDMA, WiFi, BLE...) `count` must span a burst: a window that misses
    them reads as clean. confirm: then read this many samples (default 4 * count) at the gain found, and step down
    while that clips. headroom_db: back off this much below the gain found.
    Channels whose gain is one setting (`caps.shared["gain"]`) get the gain at which none clips.
    The gain mode is set to "manual" (an AGC would undo it). Starts receiving if it wasn't, and stops it again; when
    already receiving, the channels must be among `rx_channels`. The result holds while the signal stays as it was"""
    multi = not np.isscalar(channel)
    channels = tuple(channel) if multi else (channel,)
    if self.state["rx"] and not set(channels) <= set(self.rx_channels):
        raise err.InvalidValue(f"find_gain: channels {list(channels)} aren't all receiving (rx_channels "
                               f"{list(self.rx_channels)}): stop_rx() first, or start_rx(channels=...) with them")
    for ch in channels:
        if self.get_rx_gain_mode(ch) != "manual":
            self.set_rx_gain_mode("manual", ch)
    joint = multi and self.caps.shared.get("gain", "channel") != "channel"
    target = channels if multi else channel
    confirm = 4 * int(count) if confirm is None else int(confirm)
    steps = {ch: _gain_settings(self.caps.gains[self._direction("rx", ch)]) for ch in channels}
    measured = {ch: {} for ch in channels}   # gain in effect [dB] -> share of samples clipping

    def clipping(want, n, cache=True):
        """Set each channel's gain (dB), and the share of `n` samples clipping, by channel. With cache, a gain a
        channel already got is not read again (several settings asked for can come out the same)"""
        got = {ch: self.set_rx_gain_db(g, channel=ch, flush=True) for ch, g in want.items()}
        if cache and all(got[ch] in measured[ch] for ch in channels):
            return {ch: measured[ch][got[ch]] for ch in channels}
        if skip:
            self.read(int(skip), timeout=timeout, channel=target)
        x = np.atleast_2d(self.read(int(n), timeout=timeout, channel=target))
        over = ((np.abs(x.real) >= clip_level) | (np.abs(x.imag) >= clip_level)).mean(axis=1).tolist()
        share = dict(zip(channels, [max(over)] * len(over) if joint else over))
        if cache:
            for ch in channels:
                measured[ch][got[ch]] = share[ch]
        return share

    started = not self.state["rx"]
    if started:
        self.start_rx(channels=None if channels == (0,) and 0 in self._rx_channels else channels)
    self._quiet_gain_rounding = True
    try:
        lo = dict.fromkeys(channels, -1)                          # index of the highest setting known not to clip
        hi = {ch: len(steps[ch]) for ch in channels}              # ... of the lowest known to clip
        share = clipping({ch: steps[ch][-1] for ch in channels}, count)
        for ch in channels:
            if share[ch] <= max_clip:
                lo[ch] = len(steps[ch]) - 1
            else:
                hi[ch] = len(steps[ch]) - 1
        while any(hi[ch] - lo[ch] > 1 for ch in channels):
            mid = {ch: (lo[ch] + hi[ch]) // 2 if hi[ch] - lo[ch] > 1 else max(lo[ch], 0) for ch in channels}
            share = clipping({ch: steps[ch][mid[ch]] for ch in channels}, count)
            for ch in channels:
                if hi[ch] - lo[ch] > 1:
                    if share[ch] <= max_clip:
                        lo[ch] = mid[ch]
                    else:
                        hi[ch] = mid[ch]
        at = {ch: max(lo[ch], 0) for ch in channels}
        while confirm:   # a longer look: a window can miss a burst
            share = clipping({ch: steps[ch][at[ch]] for ch in channels}, confirm, cache=False)
            down = [ch for ch in channels if share[ch] > max_clip and at[ch] > 0]
            if not down:
                break
            for ch in down:
                at[ch] -= 1
        found = {}
        for ch in channels:
            if lo[ch] < 0:
                self.log.warning("find_gain: channel %s clips even at the lowest gain", ch)
            gain = steps[ch][at[ch]]
            if headroom_db:
                gain = max([g for g in steps[ch] if g <= gain - headroom_db] or [steps[ch][0]])
            self.set_rx_gain_db(gain, channel=ch, flush=True)
            found[ch] = self.get_rx_gain(channel=ch)
    finally:
        self._quiet_gain_rounding = False
        if started and self.state["rx"]:
            self.stop_rx()
    return found if multi else found[channel]

read_available

read_available(channel=0, count=None)

What is queued for a channel now (up to count), without waiting: (samples, index of the first). Stops at a gap, so the samples are contiguous; the next call's index shows the jump. For relaying a stream (the remote server); read is the way to read one

Source code in src/pysdrlib/base/device.py
def read_available(self, channel=0, count=None):
    """What is queued for a channel now (up to `count`), without waiting: (samples, index of the first). Stops at a
    gap, so the samples are contiguous; the next call's index shows the jump. For relaying a stream (the remote
    server); `read` is the way to read one"""
    self._ensure_open("read_available")
    slot = self._slot(channel)
    ready = self._rx_wait(0, 0.0, slot=slot)
    if count is not None:
        ready = min(ready, int(count))
    if not ready:
        total, _ = self._rx_position(slot=slot)
        return np.empty(0, dtype=np.complex64), int(total)
    x, idx = self._rx_read(ready, slot=slot)
    return x, int(idx)

wait_available

wait_available(timeout, channel=0, count=1)

Wait up to timeout seconds until a channel has count samples queued; returns how many are queued (fewer than count: the time ran out). For relaying a stream (the remote server) without polling; read is the way to read one

Source code in src/pysdrlib/base/device.py
def wait_available(self, timeout, channel=0, count=1):
    """Wait up to `timeout` seconds until a channel has `count` samples queued; returns how many are queued (fewer
    than `count`: the time ran out). For relaying a stream (the remote server) without polling; `read` is the
    way to read one"""
    self._ensure_open("wait_available")
    return self._rx_wait(count, timeout, slot=self._slot(channel))

flush

flush(channel=None)

Discard the samples waiting to be read (of every streaming channel: they stay aligned); returns how many

Source code in src/pysdrlib/base/device.py
def flush(self, channel=None):
    """Discard the samples waiting to be read (of every streaming channel: they stay aligned); returns how many"""
    self._ensure_open("flush")
    n = 0
    for slot in range(len(self._rx_channels)):
        n += self._rx_flush(slot=slot)
    total, _ = self._rx_position()
    self._rx_discard = max(self._rx_discard, total)
    return n

write

write(samples, timeout=None, channel=None)

Queue samples (complex, full scale +-1) for transmission, after start_tx. Blocks while the queue is full, up to timeout seconds for the whole call (None: until all are queued). Returns how many (per channel) were queued: fewer when the time ran out, or stop_tx or close (from another thread) ended the stream. A queue that takes nothing for stall_timeout seconds raises err.StreamStalled (err.Lost: the device is gone). channel: one of tx_channels (default: the stream's only one), or several with a (channels, n) array: those rows go out sample for sample together. After a short count, carry on from it (samples[:, n:]): a channel that had queued more than that isn't sent those again

Source code in src/pysdrlib/base/device.py
def write(self, samples, timeout=None, channel=None):
    """Queue samples (complex, full scale +-1) for transmission, after `start_tx`. Blocks while the queue is full,
    up to `timeout` seconds for the whole call (None: until all are queued). Returns how many (per channel) were
    queued: fewer when the time ran out, or `stop_tx` or `close` (from another thread) ended the stream. A queue
    that takes nothing for `stall_timeout` seconds raises err.StreamStalled (err.Lost: the device is gone).
    channel: one of `tx_channels` (default: the stream's only one), or several with a (channels, n) array: those
    rows go out sample for sample together. After a short count, carry on from it (`samples[:, n:]`): a channel
    that had queued more than that isn't sent those again"""
    self._ensure_open("write")
    if not self.caps.channels.get("tx"):
        raise err.NotSupported(f"{type(self).NAME} can't transmit")
    if not self.state["tx"]:
        raise err.NotStreaming("write() needs start_tx() first")
    chans = self._tx_channels if channel is None else ((channel,) if np.isscalar(channel) else tuple(channel))
    x = np.asarray(samples, dtype=np.complex64)
    if x.ndim == 1:
        x = x[None]
    if x.ndim != 2 or len(x) != len(chans):
        raise ValueError(f"write {len(chans)} channel(s) {chans}: give a ({len(chans)}, n) array (or 1-D for one)")
    try:
        slots = [self._tx_channels.index(c) for c in chans]
    except ValueError:
        raise err.InvalidValue(f"channels {chans}: start_tx(channels=...) has {self._tx_channels}") from None
    return self._write_queued(x, slots, timeout)

get_tx_stats

get_tx_stats(channel=None)

The transmit stream's counts for a channel (default: its first): written, sent, underruns, pending...

Source code in src/pysdrlib/base/device.py
def get_tx_stats(self, channel=None):
    """The transmit stream's counts for a channel (default: its first): written, sent, underruns, pending..."""
    slot = 0 if channel is None else self._tx_channels.index(channel)
    return self._tx_stats(slot=slot)

split_rx_gain_db

split_rx_gain_db(total)

How a total receive gain [dB] is shared between the stages: _split_gain's answer, {stage: gain}

Source code in src/pysdrlib/base/device.py
def split_rx_gain_db(self, total):
    """How a total receive gain [dB] is shared between the stages: `_split_gain`'s answer, {stage: gain}"""
    return self._split_gain(total, "rx")

split_tx_gain_db

split_tx_gain_db(total)

How a total transmit gain [dB] is shared between the stages: {stage: gain}

Source code in src/pysdrlib/base/device.py
def split_tx_gain_db(self, total):
    """How a total transmit gain [dB] is shared between the stages: {stage: gain}"""
    return self._split_gain(total, "tx")