|
| 1 | +#! /usr/bin/python3 |
| 2 | + |
| 3 | +##--------------------------------------------------------------------\ |
| 4 | +# hackrfpy 'src/hackrfpy/_receiver.py' |
| 5 | +# Persistent fixed-frequency receiver. Opens ONE long-lived |
| 6 | +# hackrf_transfer stream and serves decoded complex64 segments on demand, |
| 7 | +# so you don't pay the ~1-2 s process spin-up for every capture. This is |
| 8 | +# the data-collection answer to the per-capture startup cost measured by |
| 9 | +# examples/benchmark.py. |
| 10 | +# |
| 11 | +# ARCHITECTURAL HONESTY: hackrf_transfer cannot retune mid-stream, so this |
| 12 | +# is FIXED-FREQUENCY by design. It is "start once, drain over time at one |
| 13 | +# frequency", NOT "one process I can retune". For multiple frequencies use |
| 14 | +# scan_frequencies (separate captures) or monitor_frequencies (sweep). True |
| 15 | +# gapless retuning needs the C library. |
| 16 | +##--------------------------------------------------------------------\ |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | + |
| 21 | +class PersistentReceiver: |
| 22 | + # A long-lived RX stream at one frequency. Created via |
| 23 | + # HackRF.open_receiver(...); use as a context manager so the child is |
| 24 | + # always reaped: |
| 25 | + # |
| 26 | + # with h.open_receiver(100e6, 8e6) as rx: |
| 27 | + # a = rx.read(1_000_000) # exactly 1e6 complex64 samples |
| 28 | + # b = rx.read(1_000_000) # again, NO new process spin-up |
| 29 | + # for block in rx.blocks(): # or iterate raw decoded blocks |
| 30 | + # ... |
| 31 | + # |
| 32 | + # The underlying hackrf_transfer is launched once on __enter__ (or first |
| 33 | + # use) and runs continuously until close()/__exit__. |
| 34 | + def __init__(self, hackrf, freq, sample_rate, *, lna=16, vga=20, amp=False, |
| 35 | + baseband_bw=None, read_samples=131072): |
| 36 | + self._h = hackrf |
| 37 | + self.freq = freq |
| 38 | + self.sample_rate = sample_rate |
| 39 | + self.lna = lna |
| 40 | + self.vga = vga |
| 41 | + self.amp = amp |
| 42 | + self.baseband_bw = baseband_bw |
| 43 | + self.read_samples = read_samples |
| 44 | + self._gen = None # the raw-bytes stream generator |
| 45 | + self._carry = b"" # leftover bytes between reads (odd splits) |
| 46 | + self._closed = False |
| 47 | + self.total_samples = 0 # cumulative samples served |
| 48 | + |
| 49 | + # ---- lifecycle --------------------------------------------------------- |
| 50 | + def _ensure_open(self): |
| 51 | + if self._gen is not None or self._closed: |
| 52 | + return |
| 53 | + h = self._h |
| 54 | + # validate + snap exactly like capture() does, and record params so |
| 55 | + # relative_power_db() etc. can read the gains back. validate_rx returns |
| 56 | + # (freq, sample_rate, lna, vga); amp passes through untouched on RX. |
| 57 | + freq, sample_rate, lna, vga = h.validate_rx( |
| 58 | + self.freq, self.sample_rate, self.lna, self.vga) |
| 59 | + amp = bool(self.amp) |
| 60 | + bw = h._auto_baseband(sample_rate, self.baseband_bw) |
| 61 | + self.freq, self.sample_rate = freq, sample_rate |
| 62 | + self.lna, self.vga, self.amp = lna, vga, amp |
| 63 | + h._record_params(freq=freq, sample_rate=sample_rate, lna=lna, vga=vga, |
| 64 | + amp=amp, baseband_bw=bw, mode="rx") |
| 65 | + argv = ["transfer", "-r", "-", "-f", int(freq), "-s", int(sample_rate), |
| 66 | + "-l", lna, "-g", vga, "-a", 1 if amp else 0, "-b", int(bw)] |
| 67 | + # one long-lived stream; large read granularity for sustained rate |
| 68 | + self._gen = h._run(argv, mode="stream", read_samples=self.read_samples) |
| 69 | + # register on the live backstop so a dying script reaps it |
| 70 | + from .core import _LIVE |
| 71 | + try: |
| 72 | + _LIVE.add(self) |
| 73 | + except Exception: |
| 74 | + pass |
| 75 | + |
| 76 | + def __enter__(self): |
| 77 | + self._ensure_open() |
| 78 | + return self |
| 79 | + |
| 80 | + def __exit__(self, exc_type, exc, tb): |
| 81 | + self.close() |
| 82 | + return False |
| 83 | + |
| 84 | + def close(self): |
| 85 | + if self._closed: |
| 86 | + return |
| 87 | + self._closed = True |
| 88 | + if self._gen is not None: |
| 89 | + try: |
| 90 | + self._gen.close() # interrupts + reaps the child |
| 91 | + except Exception: |
| 92 | + pass |
| 93 | + self._gen = None |
| 94 | + try: |
| 95 | + from .core import _LIVE |
| 96 | + _LIVE.discard(self) |
| 97 | + except Exception: |
| 98 | + pass |
| 99 | + |
| 100 | + def stop(self): |
| 101 | + # alias so PersistentReceiver works with the _LIVE backstop, which |
| 102 | + # calls .stop() on whatever it holds |
| 103 | + self.close() |
| 104 | + |
| 105 | + # ---- data access ------------------------------------------------------- |
| 106 | + def read(self, n_samples): |
| 107 | + # Return EXACTLY n_samples complex64 (or fewer if the stream ends). |
| 108 | + # Pulls and decodes raw bytes from the persistent stream until it has |
| 109 | + # enough; carries any partial trailing pair between calls. No new |
| 110 | + # process is launched -- this is the whole point. |
| 111 | + self._ensure_open() |
| 112 | + need_bytes = int(n_samples) * 2 # 2 int8 per complex sample |
| 113 | + buf = self._carry |
| 114 | + for chunk in self._gen: |
| 115 | + buf += chunk |
| 116 | + if len(buf) >= need_bytes: |
| 117 | + break |
| 118 | + take = buf[:need_bytes] |
| 119 | + self._carry = buf[need_bytes:] |
| 120 | + # decode, dropping any odd trailing byte (shouldn't happen since we |
| 121 | + # cut on an even boundary, but be safe) |
| 122 | + iq = self._h.decode_iq(take) |
| 123 | + self.total_samples += len(iq) |
| 124 | + return iq |
| 125 | + |
| 126 | + def blocks(self): |
| 127 | + # Yield decoded complex64 blocks as they arrive (raw cadence), until |
| 128 | + # the stream ends or the caller stops iterating. Good for a continuous |
| 129 | + # consumer that doesn't need a fixed sample count per read. |
| 130 | + self._ensure_open() |
| 131 | + if self._carry: |
| 132 | + lead = self._h.decode_iq(self._carry) |
| 133 | + self._carry = b"" |
| 134 | + if len(lead): |
| 135 | + self.total_samples += len(lead) |
| 136 | + yield lead |
| 137 | + for chunk in self._gen: |
| 138 | + iq = self._h.decode_iq(chunk) |
| 139 | + self.total_samples += len(iq) |
| 140 | + yield iq |
| 141 | + |
| 142 | + def callback(self, on_block, *, max_samples=None): |
| 143 | + # Inverted loop over blocks(): call on_block(iq, total) per block; |
| 144 | + # stop on False, on max_samples, or stream end. |
| 145 | + for iq in self.blocks(): |
| 146 | + cont = on_block(iq, self.total_samples) |
| 147 | + if cont is False: |
| 148 | + break |
| 149 | + if max_samples is not None and self.total_samples >= max_samples: |
| 150 | + break |
| 151 | + return self.total_samples |
0 commit comments