uhd-rs
A pure Rust USRP B2xx driver using nusb, without libusb or C++ UHD. Native and browser applications use the same Rust API.
Radio support is B200, B210, B200mini and B205mini RX, channel zero, RX2 or TX/RX. B200 revisions before 5 and B210 use AD9361 frontend two for logical channel zero; newer B200 and mini boards use frontend one. B210 channel zero is the A-side receiver. Mini boards use RF port A without external band switches. TX and multichannel streaming are not implemented.
The B210 revision 4 is hardware-tested. Other models have routing/register
sequence tests but still need physical RX validation. Device::identity()
returns motherboard EEPROM information, which is more precise than USB product
strings shared by B200 and B210.
Owned devices and streams
use Duration;
use ;
#
Opening prepares the radio at 100 MHz, 1 MS/s and manual gain 30 dB; it does not start RX. Discovery (Device::list), opening, configuration, stream operations and shutdown are lazy MaybeFuture operations: call .wait() natively, or .await natively/in wasm. Dropping an unpolled ordinary operation does nothing. Native futures are Send. The default native blocking API needs no async runtime. Optional smol and tokio features enable nusb's executor integration; with neither enabled, nusb discovery/open/interface/control operations use native blocking paths even when awaited. The shared radio algorithms do not depend on an executor.
Select a device with .serial("...") or .descriptor(descriptor). Configure with builder methods .frequency_hz(...), .sample_rate_hz(...), .gain(RxGain::Manual(...)), .gain(RxGain::Automatic) and .lo_offset_hz(...). After opening, use set_center_frequency, tune(RxTuneRequest::with_lo_offset(...)), set_sample_rate and set_gain. Tune and rate operations return actual quantized values. The supported receive-rate range is 429.6875 S/s through 61.44 MS/s. Like UHD through SoapyUHD, the driver automatically selects a power-of-two multiple of the requested rate as its master clock (220 kHz through 61.44 MHz), preferring FPGA halfband filters where possible. The multiplier is limited to the B2xx maximum decimation of 512 so low rates remain attainable. Intermediate requests such as 1.1, 7 and 19 MS/s are supported directly, subject to BBPLL quantization. Stop the RX stream before a rate change that changes the master clock; a failed or cancelled clock change requires reopening the device. Existing LO offsets must fit within half of the selected master clock; offsets are no longer limited to the original 8 MHz bound.
Select the RX connector with .antenna(RxAntenna::Rx2) or .antenna(RxAntenna::TxRx) on the builder, or set_antenna after opening. Both select receive-only routing. Use .bandwidth_hz(...) / set_bandwidth(...) for an analog filter bandwidth from 200 kHz through 56 MHz, limited by the current master clock. Manual requests persist across clock changes; zero restores automatic bandwidth following the clock. .dc_offset_enabled(false) / set_dc_offset_enabled(false) disables baseband DC tracking while retaining static RF and BB calibration. These controls also have antenna, bandwidth and dc_offset_enabled getters. Cancelled or failed control writes make the affected getter return an error until the setting is successfully reapplied.
An RxStream owns its sample endpoint and persistent queue of 16,384-byte transfers: 64 on native targets and 512 in browsers. The browser queue covers about 105 ms at 20 MS/s, allowing rendering or garbage collection pauses without starving USB; reads still return promptly rather than waiting to fill it. The radio sends up to 4,086 complex samples per CHDR packet in UHD's packed sc16 wire format; reads convert these directly into the caller’s Complex32 buffer, keeping reusable storage only for partial packets. Each read combines up to four completed packets without waiting for another transfer after the first samples arrive. At 20 MS/s this needs 80 MB/s of sample payload on USB; at 61.44 MS/s it needs 245.76 MB/s. Sustained throughput depends on the USB link and host. The analog frontend bandwidth is limited to 56 MHz. Ordinary reads do not acquire the radio control lock. Reads return available samples promptly, keep unread samples for the next call, and return Error::Timeout when no samples arrive before the deadline. CHDR loss and device overflow are recovered internally, logged as warnings, and counted in StreamingStats; malformed packets and fatal USB errors invalidate the stream. None waits indefinitely. stop retains the queue, and restart discards stale packets and resets CHDR synchronization.
Close streams explicitly to observe cleanup errors. close consumes the stream and returns an owned lazy operation; dropping or cancelling it still attempts cleanup. shutdown returns Busy while any stream (including a pending close) owns the claim. Once shutdown starts, configuration and new claims are disabled. Cleanup failures can be retried; successful shutdown is idempotent. A stream remains usable after dropping its Device. Final-owner drop attempts bounded synchronous cleanup natively and background cleanup in a browser.
Images and startup
The default embedded-images feature embeds six assets in debug and release builds, including wasm and Cargo packages: the FX3 firmware, available bootloader, and B200/B210/B200mini/B205mini FPGA binaries. rust-embed uses debug-embed, compression and deterministic timestamps. Builds perform no image downloads and need no runtime image directory.
The pinned UHD 4.8 image set uses FPGA revision c37b318 and firmware revision 7f7d016. Archive/file checksums, source URLs, upstream notices and the maintainer refresh procedure are in images/README.md.
Opening loads firmware if needed, reconnects, reads motherboard identity, selects the corresponding FPGA and validates compatibility before radio initialization. Compatible running firmware is reused. Use .reload_firmware(true) to explicitly reload firmware; malformed firmware is rejected before resetting a working device. FPGA loading is skipped only when the selected image hash matches and FX3 reports it running. Opening never installs the bootloader.
The FX3 loader merges adjacent HEX records into writes of up to 4096 bytes, the boot ROM limit documented in Infineon AN76405, only when the entire merged span lies within one ITCM, DTCM or system RAM region from the FX3 memory map (Technical Reference Manual 001-76074, Table 10-1). MMIO and unknown-address records retain their individual writes. Address gaps, overlaps, record order and the final execute request are preserved. The running firmware has a separate FPGA buffer limit: 64 bytes on USB 2 and 512 bytes on USB 3.
FPGA loading follows Ettus UHD's B200 loader:
invalidate the image hash, configure/start the FPGA, send each buffer sequentially,
wait for the running state, then publish the new hash. Control transfers use
nusb on both native and browser targets.
There is no loader build switch. The log facade reports upload counts, USB speed,
chunk size, firmware/FPGA times, reconnection time and radio initialization time.
Measure FX3 upload times from cold starts; warm
opens can reuse both images. In a native B210 USB 3 cold-start comparison, firmware
loading including USB reattachment took 1.484 s with individual HEX records and
0.563 s with RAM-only merging. These are single runs per variant, not browser
timings or guarantees for other hosts. Unlike UHD's record-by-record HEX reader,
adjacent firmware records are merged to reduce browser/USB round trips.
Override individual assets with .image(Image::Firmware, bytes) or supply an ImageCatalog with .images(catalog). Overrides take precedence over embedded bytes. With default-features = false, supply any image that must be loaded. A running FPGA with the pinned catalog hash may be reused without its bytes.
Native reconnection matches the original physical connector and known running-device serial. Linux USB 2/3 companion ports are resolved through the kernel's peer links. There is no fallback to an unrelated device. Set .reconnect_timeout(Duration::from_secs(...)) to change the default 10-second deadline.
Rust in a browser
Use this crate as a Rust dependency in your wasm application. The former JavaScript wrapper and /web probe page have been removed. The legacy wasm feature is an empty compatibility feature; the target selects WebUSB automatically.
#
# async
WebUSB requires a secure browser-window context. Set --cfg=web_sys_unstable_apis in the application's wasm Rust flags; dependencies' .cargo/config.toml files are not inherited. This repository supplies it for local builds:
cargo check --target wasm32-unknown-unknown --all-targets
Permission requests are separate from opening. Browser firmware loading uses device-level control transfers without claiming interface zero, so dropping the disconnected bootloader handle does not try to release an interface. Reconnection retains the selected device's serial, including in bootloader mode. After firmware loading, the browser waits up to one second (or a shorter configured reconnect timeout) for an authorized identity to reappear. If it cannot identify the re-enumerated device, opening returns Error::PermissionRequired; treat this as a setup continuation, request a new user gesture and select it again. Devices without a known serial, or whose serial changes after firmware loading, cannot safely be matched across browser reconnection.
AD9361 FIR and gain-table loading uses a continuously replenished window of up to 64 consecutive register writes in the browser. Each command has its receive posted before submission; both OUT completions and matching acknowledgements are checked. The entire window is drained before returning, so reads, delays and calibration polls retain their ordering. The B200 control processor waits for SPI readiness before accepting the next write; this host queue does not bypass that hardware flow control. Failed or cancelled pipelines require reopening. Native register writes retain their existing serialized behavior. FPGA image writes remain sequential on both targets; their small firmware buffers can make browser startup sensitive to per-transfer latency. Logs report upload progress in 10% steps and FIR/gain-table loading times to distinguish these phases.
In a B210 USB 3 / Chrome hardware comparison, 768-write FIR tables took 1.12–1.19 s at window 3, 0.495 s at 8, 0.285 s at 16, 0.132–0.155 s at 32, and 0.064–0.095 s at 64. With the final window of 64, radio initialization took 16.3–17.3 s versus 25.7 s with the old three-write batches; these runs reused loaded firmware and FPGA images. These are observed diagnostic timings, not guarantees for other devices or hosts. Debug logging can report aggregate submission time and observed OUT/ACK latency. Those timestamps include host queueing and Rust wakeups; they do not isolate browser service time or physical USB latency. Profiling clocks are disabled when debug logging is disabled.
Stopping RX leaves the browser USB device open. After closing or losing a stream that submitted transfers, rx_stream returns ReopenRequired: call shutdown, then open a new Device. WebUSB cannot cancel individual transfers. Terminal shutdown awaits the retained browser UsbDevice.close(), aborting pending operations and releasing interfaces. Drop cleanup retains ownership until its background attempt finishes.
Examples and diagnostics
cargo run --release --example rx_100mhz -- capture.fc32
cargo run --features smol --example rx_async
cargo run -- list
cargo run -- probe
cargo run -- load-firmware images/assets/usrp_b200_fw.hex
cargo run -- load-fpga images/assets/usrp_b210_fpga.bin
cargo run -- peek 0x50
The capture example writes ten seconds of headerless interleaved little-endian f32 IQ. Both examples close the stream and shut down the device explicitly, including after a receive error. Pass a serial after diagnostic command arguments when multiple devices are connected. b2xx::load_firmware_and_reconnect and B2xxDevice::open_fpga_session expose image/reconnection and checked local-control diagnostics without initializing the radio. Radio-register loopback needs the radio clock initialized.
B2xx normally uses unaligned 8176/16360-byte IN requests. nusb 0.2 requires requests aligned to endpoint packet size; the driver retains the existing 16384-byte workaround and accepts short completions. The aligned-transfer workaround is verified on B210; other models still need hardware RX validation.
Migration and verification
Replace B2xxReceiver::open/receive and RxPacket with Device::builder().open, rx_stream, explicit start, and read(&mut [Complex32], timeout). Samples are num_complex::Complex32. Configuration belongs to Device; data and queue ownership belong to RxStream. Replace dropping a JavaScript wrapper with explicit Rust close and shutdown.
Run cargo test --all-targets for the native test suite. Browser tests use wasm-bindgen-test-runner and ChromeDriver. Physical hardware tests are opt-in, ignored by default, and should run serially:
cargo test --features hardware-tests --test hardware -- --ignored --test-threads=1 --nocapture
Run only tests appropriate for the attached model. Set UHD_RS_SERIAL when necessary. UHD_RS_RELOAD_FIRMWARE=1 makes the B2xx diagnostic test exercise a cold firmware reload. The B2xx cold-receive test includes RX restart/cancellation/reopening; optionally set UHD_RS_HANDOFF_COMMAND to an executable that opens the released device in another application.
Releases
The GitHub Actions release workflow publishes uhd-rs to crates.io and creates a GitHub release when a v* tag matches the crate version. Before tagging a release, configure a crates.io trusted publisher for repository bastibl/uhd-rs and workflow release.yml. CI runs native checks, browser lifecycle tests, and embedded-image/package verification on pushes and pull requests.
License
GPL-3.0-or-later, matching UHD's host driver. Embedded image notices and corresponding-source links are documented separately in images/README.md.
If an alternative UHD license is obtained as described by UHD, the authors agree to the same license for this crate without additional compensation.