Skip to content

Uhd

pysdrlib.uhd

Ettus USRPs through UHD's C API: the B2xx family (B200/B210, on USB) and, experimentally, the X310 and X410 (on a network).

Driver Class Radios Link
uhd B210 B200, B210, B200mini, B205mini USB 3
x310 X310 X300, X310 1/10 GbE, PCIe
x410 X410 X410 10/25/100 GbE

The sections below describe the B2xx; X310 and X410 says what differs.

import pysdrlib
sdr = pysdrlib.open("uhd")                 # or pysdrlib.find("uhd")[0].open()
sdr.set_rx_freq(915e6); sdr.set_rx_sample_rate(10e6); sdr.set_rx_gain_db(40)
sdr.start_rx(); x = sdr.read(1_000_000)    # complex64

sdr.start_tx(); sdr.write(tone)            # complex64, full scale is +-1; sdr.tx_stats
Frequency 50 MHz - 6 GHz
Sample rate 200 kS/s - 61.44 MS/s (about 32 MS/s sustained over USB 3 with Python in the loop)
Channels B210: 2 RX, 2 TX (start_rx(channels=(0, 1)), start_tx(channels=(0, 1))); B200: 1
Gain one stage per direction, the AD9361 PGA: RX 0-76 dB (1 dB), TX 0-89.75 dB (0.25 dB); set_rx_gain_mode("auto") for RX AGC
Antennas RX: TX/RX, RX2. TX: TX/RX
Bandwidth 200 kHz - 56 MHz analog filter, per direction
Settings dc_offset_auto, iq_balance_auto, time_source, master_clock_rate
Clock internal, external, gpsdo (set_clock_source)
Extras sensors() (lo_locked, temp, rssi, ref_locked), time()/set_time(), open(args="type=b200,...")

The master clock is chosen from the sample rate (an even multiple of it in the AD9361's 25-61.44 MHz range) unless master_clock_rate is set; changing it pauses the streams. RX and TX run from the one clock, so it is chosen to give both rates where it can. Where it can't, the rate just set wins: the other direction's becomes what UHD makes of it (read it back; a warning says so). While receiving, a TX rate (or TX channel count) that would move the clock raises err.Busy instead, so a receive stream is never interrupted by the transmitter's settings: stop_rx() first.

Two channels. A B210 has two RX and two TX channels (frontends A and B; a B200 has one). Every control takes channel:

sdr.set_rx_gain_db(50, channel=1); sdr.set_rx_antenna("TX/RX", channel=1)
sdr.set_tx_freq(915e6)                 # RX stays where it was
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
The AD9361 has one RX and one TX synthesizer: a frequency is shared by a direction's channels (caps.shared), and the driver tunes both channels' DSP alike, so they stay phase coherent (measured: the phase between them steady to 0.1 deg). A stream's channels share its rate. With two channels the master clock is at most 30.72 MHz (UHD's limit), so the driver picks a power-of-two multiple of the rate under it (10 MS/s: 20 MHz); 30.72 MS/s per channel is the most. A two-channel stream starts on a timed command so both start on the same sample.

Received samples carry the radio's time: read(..., meta=True) gives RxMeta.hw_time, the device time of the block's first sample (UHD's time_spec; set it with set_time(), or from a PPS/GPS time_source). The driver stamps the stream when it starts and again wherever samples were lost, so it stays exact across overflows. A FileSink SigMF recording takes its core:datetime from it when the clock holds a date. (Not yet checked on hardware.)

On the unit this was tested with, two-channel streams sometimes stop with UHD's accum_timeout control error (about 1 start in 8-16, the same with UHD's own rx_samples_to_file --channels 0,1): read raises err.StreamStalled; close and reopen the device. Single-channel streams were not affected.

X310 and X410

Experimental. These classes were written from UHD's documentation and tested on a fake driver, not on a radio: expect to find things wrong (the first open says so). Reports are welcome.

sdr = pysdrlib.open("x310", addr="192.168.10.2")          # or "x410"
sdr.initialize(cf=2.4e9, Fs=100e6)
sdr.set_rx_rf_gain(20)                                     # or set_rx_gain_db(20)
sdr.start_rx(channels=(0, 1)); x = sdr.read(65536, channel=(0, 1))

for info in pysdrlib.find(addresses=["192.168.10.2"]):     # network radios are only looked for where you say
    print(info.driver, info.label)                          # "x310 UHD X310 3125A1F"
  • Needs a libuhd that has these radios. Install your system's UHD (apt install libuhd-dev uhd-host, pacman -S libuhd...); the copy pysdrlib build uhd makes is B2xx only. pysdrlib finds the system library first. The FPGA image on the radio must match your UHD (uhd_image_loader, uhd_images_downloader): UHD says so when it doesn't.
  • Finding. pysdrlib.find() never touches a network: it lists B2xx on USB. Give addresses= to also ask those hosts. pysdrlib.open("x310", addr=...) and open_args (serial, addr, args="master_clock_rate=184.32e6") go into UHD's device address.
  • What they have. Channels, gains, frequency and bandwidth come from the radio when it is opened (sdr.caps): they depend on the daughterboards (X310: UBX, SBX, CBX...) or the ZBX (X410). Each channel has its own LO (set_rx_freq(f, channel=1)); a stream's channels share a rate. One overall gain per channel, RF; no AGC, no bias tee. sensors(), time(), set_time(), set_clock_source() and the time_source setting are as on a B2xx.
  • Rates. UHD rounds a rate to what the master clock gives: read back what set_rx_sample_rate returns. The link limits the rate (10 GbE: 200 MS/s of sc16; 1 GbE: about 25). Converting 100 MS/s and more to complex64 in the host is heavy; watch sdr.stats and warn.Dropped.
  • Not measured. RETUNE_SAMPLES and RETUNE_SETTLE are estimates, and nothing here was timed on a radio.

Libraries

pysdrlib/_native/uhd/uhd_shim.c is a plain-C face on UHD's C API: <uhd/uhd.h> pulls in UHD's C++ headers and Boost when included from C++, so only the shim sees UHD and the extension builds without Boost. libuhd itself is the system one if installed, else built (pysdrlib build uhd) from a trimmed snapshot of UHD's sources in uhd/vendor/ (B200 family only: the X series needs a system libuhd, which would about double the snapshot; no network or Python needed, just cmake, a C++17 compiler, Boost and libusb). tools/vendor.py regenerates the snapshot from upstream.

Modules:

Name Description
images

Where UHD finds the FPGA images a B2xx loads when it is opened.

uhd

Functions:

Name Description
find

[DeviceInfo] of the USRPs attached: B2xx on USB, always; X3xx and X4xx on a network only at addresses (a host,

find

find(addresses=None)

[DeviceInfo] of the USRPs attached: B2xx on USB, always; X3xx and X4xx on a network only at addresses (a host, or a list of them), as UHD finds them by asking that address

Source code in src/pysdrlib/uhd/__init__.py
def find(addresses=None):
    """[DeviceInfo] of the USRPs attached: B2xx on USB, always; X3xx and X4xx on a network only at `addresses` (a host,
    or a list of them), as UHD finds them by asking that address"""
    from ..devices import DeviceInfo
    from . import images, lib
    images.configure()
    if isinstance(addresses, str):
        addresses = [addresses]
    queries = ["type=b200"] + [f"addr={a}" for a in addresses or ()]   # not UHD's own search: it broadcasts on every network
    found = []
    for query in queries:
        for d in lib.uhd.find(query):
            driver = _driver_of(d)
            if driver is None:
                continue
            product = d.get("product") or d.get("type") or "USRP"
            serial = d.get("serial") or None
            open_args = {k: v for k, v in (("serial", serial), ("addr", d.get("addr"))) if v}
            label = " ".join(x for x in (f"UHD {d.get('name') or product}".strip(), serial) if x)
            info = DeviceInfo(driver, label, serial, len(found), open_args, dict(d))
            if info not in found:
                found.append(info)
    return found

images

Where UHD finds the FPGA images a B2xx loads when it is opened.

libuhd looks in UHD_IMAGES_DIR, then its own install prefix (/usr/share/uhd/images). A libuhd that pysdrlib built has no images, so configure() points UHD_IMAGES_DIR at the first of these that has some:

1. UHD_IMAGES_DIR as the user set it
2. the system's UHD images (/usr/share/uhd/images, /usr/local/share/uhd/images)
3. pysdrlib's cache, filled by `download()`

Functions:

Name Description
find

Directory holding B2xx FPGA images, or None

configure

Make sure libuhd will find the images (does not download). Returns the directory, or None

download

Fetch the B2xx images into pysdrlib's cache with UHD's own downloader (needs network). Returns the directory

find

find()

Directory holding B2xx FPGA images, or None

Source code in src/pysdrlib/uhd/images.py
def find():
    """Directory holding B2xx FPGA images, or None"""
    candidates = [Path(p) for p in os.environ.get("UHD_IMAGES_DIR", "").split(os.pathsep) if p]
    candidates += [*SYSTEM_DIRS, cache_dir()]
    return next((p for p in candidates if has_images(p)), None)

configure

configure()

Make sure libuhd will find the images (does not download). Returns the directory, or None

Source code in src/pysdrlib/uhd/images.py
def configure():
    """Make sure libuhd will find the images (does not download). Returns the directory, or None"""
    found = find()
    if found is not None and str(found) != os.environ.get("UHD_IMAGES_DIR"):
        os.environ["UHD_IMAGES_DIR"] = str(found)
    return found

download

download()

Fetch the B2xx images into pysdrlib's cache with UHD's own downloader (needs network). Returns the directory

Source code in src/pysdrlib/uhd/images.py
def download():
    """Fetch the B2xx images into pysdrlib's cache with UHD's own downloader (needs network). Returns the directory"""
    tool = shutil.which("uhd_images_downloader")
    if tool is None:
        raise RuntimeError("uhd_images_downloader is not installed; install UHD's utilities (e.g. `apt install uhd-host`) "
                           "or download the images by hand and set UHD_IMAGES_DIR")
    target = cache_dir()
    target.mkdir(parents=True, exist_ok=True)
    subprocess.check_call([tool, "-t", "b2xx", "-i", str(target)], stdout=sys.stderr)
    os.environ["UHD_IMAGES_DIR"] = str(target)
    return target

uhd

Classes:

Name Description
USRP

What every USRP has in common through UHD: opening one by serial or address, the per-channel controls, clock and

B210

Ettus USRP B200/B210 (and compatible) through UHD. Two channels each way on a B210 (frontends A and B), one on a

X310

Ettus USRP X300/X310 through UHD, on a 1/10 GbE or PCIe link. Two channels each way with two daughterboards

X410

Ettus USRP X410 through UHD, on a 10/25/100 GbE link. Four channels each way, 1 MHz to 7.2 GHz, up to 400 MS/s

USRP

USRP()

Bases: NativeDevice

What every USRP has in common through UHD: opening one by serial or address, the per-channel controls, clock and time sources, sensors. A family is a subclass that says what its radios can do (CAPS) and how they tune (B210, X310, X410).

Methods:

Name Description
find

[DeviceInfo] of this family's units: pysdrlib.uhd.find, for this driver

sensors

{name: value} of the motherboard's and a channel's frontend sensors (ref_locked, lo_locked, temp, rssi...),

time

The device's time [s]

set_time

Set the device's time; at_pps: on the next PPS edge (to align several devices)

Source code in src/pysdrlib/uhd/uhd.py
def __init__(self):
    super().__init__()
    lib.uhd.init()
find classmethod
find(addresses=None)

[DeviceInfo] of this family's units: pysdrlib.uhd.find, for this driver

Source code in src/pysdrlib/uhd/uhd.py
@classmethod
def find(cls, addresses=None):
    """[DeviceInfo] of this family's units: `pysdrlib.uhd.find`, for this driver"""
    from . import find
    return [info for info in find(addresses) if info.driver == cls.DRIVER]
sensors
sensors(channel=0)

{name: value} of the motherboard's and a channel's frontend sensors (ref_locked, lo_locked, temp, rssi...), keyed "mboard.", "rx." or "tx." + name

Source code in src/pysdrlib/uhd/uhd.py
def sensors(self, channel=0):
    """{name: value} of the motherboard's and a channel's frontend sensors (ref_locked, lo_locked, temp, rssi...),
    keyed "mboard.", "rx." or "tx." + name"""
    self._ensure_open("sensors")
    self._check_channel("rx", channel)
    out = {f"mboard.{k}": v for k, v in self.device.mboard_sensors().items()}
    out.update({f"rx.{k}": v for k, v in self.device.rx_sensors(channel).items()})
    out.update({f"tx.{k}": v for k, v in self.device.tx_sensors(channel).items()})
    return out
time
time()

The device's time [s]

Source code in src/pysdrlib/uhd/uhd.py
def time(self):
    """The device's time [s]"""
    self._ensure_open("time")
    return self.device.time_now()
set_time
set_time(seconds=0.0, at_pps=False)

Set the device's time; at_pps: on the next PPS edge (to align several devices)

Source code in src/pysdrlib/uhd/uhd.py
def set_time(self, seconds=0.0, at_pps=False):
    """Set the device's time; at_pps: on the next PPS edge (to align several devices)"""
    self._ensure_open("set_time")
    (self.device.set_time_next_pps if at_pps else self.device.set_time_now)(float(seconds))

B210

B210()

Bases: USRP

Ettus USRP B200/B210 (and compatible) through UHD. Two channels each way on a B210 (frontends A and B), one on a B200: every control takes channel, and start_rx(channels=(0, 1)) / start_tx(channels=(0, 1)) stream both together (coherent: one clock, one LO per direction).

The AD9361 has one receive and one transmit synthesizer, so a frequency is shared by a direction's channels, and the streams need one rate per direction (caps.shared). Gain, filter and antenna are per channel.

The gain is the AD9361's single programmable gain (PGA): set_rx_pga_gain/set_tx_pga_gain, or the generic set_rx_gain_db/set_tx_gain_db (decibels) or set_rx_gain/set_tx_gain (a fraction of the range).

Source code in src/pysdrlib/uhd/uhd.py
def __init__(self):
    super().__init__()
    self._mcr_pinned = False   # the user chose a master clock rate: don't pick one per sample rate
    self._rx_moved = None      # the receive rate a master clock change left, where it differs

X310

X310()

Bases: _XSeries

Ettus USRP X300/X310 through UHD, on a 1/10 GbE or PCIe link. Two channels each way with two daughterboards (frontends A and B; UBX, SBX, CBX, WBX... set what the frequency, bandwidth and gain are: see caps once open).

sdr = pysdrlib.open("x310", addr="192.168.10.2")          # or pysdrlib.find(addresses=["192.168.10.2"])[0].open()
sdr.initialize(cf=2.4e9, Fs=100e6)
sdr.start_rx(channels=(0, 1))

One overall gain per channel: set_rx_rf_gain / set_tx_rf_gain, or the generic set_rx_gain_db / set_tx_gain_db. The link sets the rate: 10 GbE carries up to 200 MS/s of sc16, 1 GbE about 25 MS/s. Converting that to complex64 on the host is what limits Python at high rates.

Source code in src/pysdrlib/uhd/uhd.py
def __init__(self):
    super().__init__()
    lib.uhd.init()

X410

X410()

Bases: _XSeries

Ettus USRP X410 through UHD, on a 10/25/100 GbE link. Four channels each way, 1 MHz to 7.2 GHz, up to 400 MS/s with the CG_400 FPGA image (200 MS/s with X4_200); it needs UHD 4 and an image that matches it.

sdr = pysdrlib.open("x410", addr="192.168.10.2")
sdr.initialize(cf=3.5e9, Fs=200e6)
sdr.start_rx(channels=(0, 1, 2, 3))

One overall gain per channel: set_rx_rf_gain / set_tx_rf_gain, or the generic set_rx_gain_db / set_tx_gain_db. Converting 400 MS/s to complex64 on the host is more than Python keeps up with: expect warn.Dropped there.

Source code in src/pysdrlib/uhd/uhd.py
def __init__(self):
    super().__init__()
    lib.uhd.init()