|
1 | 1 | #! /usr/bin/python3 |
2 | 2 | ##--------------------------------------------------------------------\ |
3 | | -# hackrfpy 'examples/waterfall_persistent.py' |
4 | | -# Single-frequency spectrum waterfall over time, driven by a PERSISTENT |
5 | | -# receiver. Needs the [plotting] extra. |
| 3 | +# hackrfpy 'examples/persistent_capture.py' |
| 4 | +# Collect many CONTIGUOUS segments at one frequency from a single |
| 5 | +# long-lived receive process, using open_receiver(). No plotting. |
6 | 6 | # |
7 | | -# This is the COMPLEMENT to waterfall_realtime.py, not a replacement: |
8 | | -# - waterfall_realtime.py : SWEEP-based. x-axis = frequency across a wide |
9 | | -# band; shows WHERE activity is across the spectrum. |
10 | | -# - waterfall_persistent.py (this) : RECEIVER-based. Locks ONE center |
11 | | -# frequency, FFTs each block; x-axis = frequency WITHIN the capture |
12 | | -# bandwidth; shows how one channel evolves over time at full rate. |
| 7 | +# This is DIFFERENT from capture(segment_secs=...): |
| 8 | +# - capture(segment_secs=...) spawns a fresh hackrf_transfer per file, |
| 9 | +# so each file is whole but there is a short re-open GAP (~hundreds |
| 10 | +# of ms) of missing samples between files. |
| 11 | +# - this script drains ONE continuous stream and cuts it into files, |
| 12 | +# so consecutive segments are GAPLESS (back-to-back samples), at the |
| 13 | +# cost of re-quantizing complex64 -> int8 on write (exact for |
| 14 | +# samples produced by the library's own decode). |
13 | 15 | # |
14 | | -# It uses open_receiver() so the hackrf_transfer process spins up once and |
15 | | -# streams continuously -- the natural fit for a live single-frequency view. |
16 | | -# Read-only / receive-only; the receiver is reaped on exit. |
| 16 | +# Use this when downstream processing cares about continuity across |
| 17 | +# file boundaries (long observations, TDOA-ish work, demod that spans |
| 18 | +# segments). Each file gets a SigMF sidecar. |
| 19 | +# |
| 20 | +# SAFETY: read-only / receive-only. |
17 | 21 | # |
18 | 22 | # Usage: |
19 | | -# uv run python examples/waterfall_persistent.py --freq 100e6 --rate 8e6 |
20 | | -# uv run python examples/waterfall_persistent.py --freq 2437e6 --rate 10e6 |
| 23 | +# uv run python examples/persistent_capture.py --freq 100e6 --rate 2e6 |
| 24 | +# uv run python examples/persistent_capture.py --freq 433.92e6 \ |
| 25 | +# --rate 2e6 --segment-secs 1.0 --count 10 --out-dir segments |
21 | 26 | # |
22 | 27 | # |
23 | 28 | # Author(s): Lauren Linkous |
24 | | -# Last Update: July 11, 2026 |
25 | 29 | ##--------------------------------------------------------------------\ |
26 | 30 | import argparse |
| 31 | +import os |
27 | 32 | import sys |
| 33 | + |
28 | 34 | import numpy as np |
29 | | -import matplotlib.pyplot as plt |
30 | | -from matplotlib import colors |
31 | | -from hackrfpy import HackRF |
32 | 35 |
|
33 | | -# ---- aesthetic: same signals-monitor identity as the sweep waterfall ------ |
34 | | -BG = "#0a0e14" |
35 | | -PANEL = "#0d1320" |
36 | | -GRID = "#1c2738" |
37 | | -ACCENT = "#36e0c8" |
38 | | -TEXT = "#9fb3c8" |
39 | | -TEXTDIM = "#52617a" |
40 | | -CMAP = "turbo" |
| 36 | +from hackrfpy import HackRF, write_sigmf_meta |
| 37 | + |
41 | 38 |
|
42 | | -plt.rcParams.update({ |
43 | | - "figure.facecolor": BG, "axes.facecolor": PANEL, "savefig.facecolor": BG, |
44 | | - "font.family": "monospace", "text.color": TEXT, "axes.edgecolor": GRID, |
45 | | - "axes.labelcolor": TEXT, "xtick.color": TEXTDIM, "ytick.color": TEXTDIM, |
46 | | - "axes.linewidth": 0.8, |
47 | | -}) |
| 39 | +def encode_iq(iq: np.ndarray) -> bytes: |
| 40 | + # complex64 in ~[-1, 1) -> interleaved int8 (HackRF native). Exact |
| 41 | + # round-trip for data that came out of decode_iq (values are k/128). |
| 42 | + out = np.empty(len(iq) * 2, dtype=np.int8) |
| 43 | + out[0::2] = np.clip(np.round(iq.real * 128.0), -128, 127) |
| 44 | + out[1::2] = np.clip(np.round(iq.imag * 128.0), -128, 127) |
| 45 | + return out.tobytes() |
48 | 46 |
|
49 | 47 |
|
50 | 48 | def main(): |
51 | | - p = argparse.ArgumentParser(description="Single-freq waterfall (persistent RX).") |
| 49 | + p = argparse.ArgumentParser( |
| 50 | + description="Gapless segmented capture from one persistent receiver.") |
52 | 51 | p.add_argument("--freq", default="100e6", help="center frequency Hz") |
53 | | - p.add_argument("--rate", default="8e6", help="sample rate sps") |
54 | | - p.add_argument("--fft", type=int, default=1024, help="FFT size (bins)") |
55 | | - p.add_argument("--rows", type=int, default=400, help="time history depth") |
| 52 | + p.add_argument("--rate", default="2e6", help="sample rate sps") |
| 53 | + p.add_argument("--segment-secs", type=float, default=1.0, |
| 54 | + help="seconds of samples per file (default 1.0)") |
| 55 | + p.add_argument("--count", type=int, default=5, |
| 56 | + help="number of segments to collect (default 5)") |
| 57 | + p.add_argument("--out-dir", default="segments", |
| 58 | + help="output directory (default ./segments)") |
| 59 | + p.add_argument("--lna", type=int, default=16) |
| 60 | + p.add_argument("--vga", type=int, default=20) |
56 | 61 | p.add_argument("--tools-dir", default=None) |
57 | 62 | args = p.parse_args() |
58 | | - freq, rate, nfft, rows = float(args.freq), float(args.rate), args.fft, args.rows |
| 63 | + freq, rate = float(args.freq), float(args.rate) |
| 64 | + n_per = int(rate * args.segment_secs) |
59 | 65 |
|
60 | 66 | h = HackRF(tools_dir=args.tools_dir) |
61 | | - det = h.detect() |
62 | | - if not det["ready"]: |
63 | | - print(f"no usable HackRF: {det['problem']}", file=sys.stderr) |
64 | | - return 1 |
65 | | - |
66 | | - # color scale in dBFS-ish FFT magnitude; fixed so colors are stable |
67 | | - DB_FLOOR, DB_CEIL = -90, -20 |
68 | | - win = np.hanning(nfft).astype(np.float32) |
69 | | - |
70 | | - def spectrum(iq): |
71 | | - # Average several FFT frames across the big block for a smoother line, |
72 | | - # then suppress the center DC / LO-leakage spike that every direct- |
73 | | - # conversion SDR shows at 0 Hz (the bright line dead-center). We |
74 | | - # replace the few central bins with their neighbors so a real signal |
75 | | - # isn't hidden under the artifact. |
76 | | - nframes = max(1, len(iq) // nfft) |
77 | | - acc = np.zeros(nfft, dtype=np.float64) |
78 | | - for k in range(nframes): |
79 | | - seg = iq[k * nfft:(k + 1) * nfft] |
80 | | - if len(seg) < nfft: |
81 | | - break |
82 | | - sp = np.fft.fftshift(np.fft.fft(seg * win)) |
83 | | - acc += (np.abs(sp) / nfft) ** 2 |
84 | | - acc /= nframes |
85 | | - db = 10 * np.log10(acc + 1e-12) |
86 | | - # flatten the DC spike: overwrite the center +/-2 bins with a neighbor |
87 | | - c = nfft // 2 |
88 | | - db[c - 2:c + 3] = db[c + 3] |
89 | | - return db |
90 | | - |
91 | | - fig, ax = plt.subplots(figsize=(11, 6)) |
92 | | - try: |
93 | | - fig.canvas.manager.set_window_title( |
94 | | - "hackrfpy :: persistent-RX waterfall") |
95 | | - except Exception: |
96 | | - pass |
97 | | - |
98 | | - history = [] |
99 | | - img = None |
100 | | - cbar = None |
101 | | - # frequency axis: center +/- rate/2, in MHz |
102 | | - f_lo = (freq - rate / 2) / 1e6 |
103 | | - f_hi = (freq + rate / 2) / 1e6 |
104 | | - |
105 | | - print(f"[*] persistent waterfall @ {freq/1e6:g} MHz, {rate/1e6:g} Msps, " |
106 | | - f"{nfft}-pt FFT (close window or Ctrl-C to stop)") |
107 | | - |
108 | | - try: |
109 | | - with h.open_receiver(freq, rate) as rx: |
110 | | - # Read a LARGE block per iteration so the pipe drains fast enough |
111 | | - # to keep hackrf_transfer streaming (reading only nfft=1024 samples |
112 | | - # per loop, with a redraw each time, stalls the device at 10 Msps). |
113 | | - # Each big block becomes one averaged waterfall row. |
114 | | - block_samples = 262144 |
115 | | - while True: |
116 | | - iq = rx.read(block_samples) |
117 | | - if len(iq) < nfft: |
118 | | - break |
119 | | - history.append(spectrum(iq)) |
120 | | - history = history[-rows:] |
121 | | - arr = np.array(history)[::-1] # newest on top |
| 67 | + os.makedirs(args.out_dir, exist_ok=True) |
122 | 68 |
|
123 | | - if img is None: |
124 | | - img = ax.imshow( |
125 | | - arr, aspect="auto", cmap=CMAP, |
126 | | - norm=colors.Normalize(vmin=DB_FLOOR, vmax=DB_CEIL), |
127 | | - interpolation="nearest", origin="upper", |
128 | | - extent=[f_lo, f_hi, 0, len(arr)]) |
129 | | - cbar = fig.colorbar(img, ax=ax, pad=0.01, fraction=0.046) |
130 | | - cbar.set_label("magnitude (dB)", color=TEXT, fontsize=9) |
131 | | - cbar.outline.set_edgecolor(GRID) |
132 | | - plt.setp(plt.getp(cbar.ax, "yticklabels"), color=TEXTDIM) |
133 | | - ax.set_title( |
134 | | - f"SINGLE-FREQ WATERFALL \u2014 {freq/1e6:g} MHz " |
135 | | - f"\u00b1 {rate/2e6:g} MHz", |
136 | | - color=ACCENT, fontsize=13, fontweight="bold", |
137 | | - loc="left", pad=12, family="monospace") |
138 | | - ax.set_xlabel("frequency (MHz)", fontsize=9) |
139 | | - ax.set_ylabel("time (newest at top)", fontsize=9) |
140 | | - ax.set_yticks([]) |
141 | | - for s in ax.spines.values(): |
142 | | - s.set_color(GRID) |
143 | | - fig.tight_layout() |
144 | | - else: |
145 | | - img.set_data(arr) |
146 | | - img.set_extent([f_lo, f_hi, 0, len(arr)]) |
147 | | - plt.pause(0.001) |
148 | | - if not plt.fignum_exists(fig.number): |
| 69 | + print(f"[*] {args.count} x {args.segment_secs}s gapless segments " |
| 70 | + f"@ {freq/1e6:g} MHz, {rate/1e6:g} Msps -> {args.out_dir}/") |
| 71 | + written = [] |
| 72 | + with h.open_receiver(freq, rate, lna=args.lna, vga=args.vga) as rx: |
| 73 | + for i in range(args.count): |
| 74 | + iq = rx.read(n_per) |
| 75 | + if len(iq) < n_per: |
| 76 | + print(f"[!] stream ended early on segment {i}", file=sys.stderr) |
| 77 | + if not len(iq): |
149 | 78 | break |
150 | | - except KeyboardInterrupt: |
151 | | - pass |
152 | | - print("[*] stopped") |
| 79 | + path = os.path.join(args.out_dir, f"seg_{i:03d}.iq") |
| 80 | + with open(path, "wb") as f: |
| 81 | + f.write(encode_iq(iq)) |
| 82 | + write_sigmf_meta(path, freq, rate, lna=rx.lna, vga=rx.vga, |
| 83 | + amp=rx.amp, datatype="ci8") |
| 84 | + db = h.power_dbfs(iq) |
| 85 | + print(f" seg_{i:03d}.iq {len(iq)} samples {db:6.1f} dBFS") |
| 86 | + written.append(path) |
| 87 | + print(f"[*] done: {len(written)} files, " |
| 88 | + f"{rx.total_samples} contiguous samples total") |
153 | 89 | return 0 |
154 | 90 |
|
155 | 91 |
|
|
0 commit comments