Skip to content

Receiving

Every radio has the same calls. The examples here run on the simulated radio ("sim"); put a driver name ("rtl_sdr", "hackrf", "uhd"...) or a DeviceInfo from find() in its place for real hardware.

Find, open, read

for info in pysdrlib.find(virtual=True):    # radios attached (virtual=True: the simulated one too)
    print(info.driver, info.label, info.serial)
sdr = pysdrlib.open("sim")                 # a driver name; or a DeviceInfo from find(), or "<driver>@<serial>"
sdr.initialize(cf=100e6, Fs=2e6)           # center frequency and sample rate
sdr.set_rx_gain(0.5)                       # half of this radio's gain range, whatever the radio
sdr.start_rx()
x = sdr.read(65536, timeout=1.0)           # exactly 65536 complex64 samples (err.Timeout after 1 s)
sdr.stop_rx()
sdr.close()
  • pysdrlib.open takes a driver name (serial= picks the unit), a DeviceInfo, a target string ("hackrf@<serial>", "radiohost/hackrf-0": see pysdrlib.targets), and returns the device opened.
  • pysdrlib.device("rtl_sdr", ...) makes one without opening it; its arguments go to the class (sdr.open() next). pysdrlib.devices.ls() lists the drivers, and import pysdrlib.rtl_sdr works as a static import.
  • find() never builds a vendor library (find(build=True) does), probes no network unless given addresses=[...], and lists the simulated radio only with virtual=True.

read: an exact count, and what happened

read and stream are the way to get samples. get_samples() is the low-level call under them: whatever has arrived, any number, without waiting.

x, m = sdr.read(65536, meta=True)        # m: RxMeta
print(m.index, m.freq, m.rate)           # the first sample's position in the stream, what the radio was set to
print(m.gaps, m.dropped, m.events)       # where samples were lost, how many, retunes inside the block
print(m.time, m.hw_time)                 # host time of the first sample; the radio's own clock (or None)

buffer = np.empty(16384, np.complex64)
sdr.read_into(buffer)                    # into an array you own: no allocation per read

RxMeta (reference) says where the block is in the stream and what happened inside it: lost samples (gaps), retunes (events), and the radio's own timestamp where it has one (UHD, a replayed recording).

Retuning

sdr.set_rx_freq(162.4e6, flush=True)     # the next read is all at the new frequency (settling skipped)
x, m = sdr.read(8192, meta=True)
assert m.freq == 162.4e6

flush=True discards what was received before the change and the radio's settling time. Without it, a block can straddle the retune: m.events says where.

Lost samples and stalls

Samples are lost when Python doesn't read often enough, or when the radio delivers fewer than its rate requires. Either way they show as gaps, so indices stay true:

sdr.on_drop = "ignore"                   # lost samples: "warn" (default), "raise", "ignore" or a function
sdr.drop(10_000)                         # (the simulator loses samples on demand, as a radio's overflow would)
for _ in range(8):                       # the loss shows in the block it falls in
    x, m = sdr.read(65536, meta=True)
    if m.dropped:
        print("lost", m.dropped, "samples at", m.gaps)   # [(offset in the block, samples missing just before it)]
        break
try:
    sdr.drop(10_000)
    for _ in range(8):
        x = sdr.read(65536, on_drop="raise")   # per read: raise err.Dropped for a capture that must be whole
except pysdrlib.err.Dropped as e:
    print(e)
print(sdr.stats)                         # delivered, dropped, missing, stalls, seconds since the last samples

Hardware devices also watch their own stream each time you read. A stream that stops delivering raises:

try:
    x = sdr.read(65536, timeout=1.0)
except pysdrlib.err.StreamStalled:       # no samples for sdr.stall_timeout seconds (default 1; None disables)
    sdr.stop_rx(); sdr.start_rx()        # or close and reopen the device

Anything still buffered when a stall is detected is returned first.

Streams and sweeps

with sdr.stream(65536, meta=True) as s:  # starts receiving, stops on exit
    for i, (x, m) in enumerate(s):
        print(m.index, np.mean(np.abs(x) ** 2))
        if i == 3:
            break
for freq, x in sdr.sweep(88e6, 96e6, count=65536):    # start to stop, in steps of 80% of the rate
    print(f"{freq / 1e6:.1f} MHz: {10 * np.log10(np.mean(np.abs(x) ** 2)):.1f} dB")
for freq, x in sdr.sweep([162.4e6, 162.55e6], count=4096, offset=250e3, skip=1000):   # a list; DC off the middle
    pass

A sweep retunes with flush=True at each step, so every block is all at its frequency. offset moves the DC spike off the middle of each step; skip discards more samples after each retune.

Whole script: examples/receiving.py. Next: controls and channels.