Skip to content

Commit 6aa5318

Browse files
committed
docstrings addition, prep for dev manual
1 parent 8534b25 commit 6aa5318

9 files changed

Lines changed: 306 additions & 2 deletions

File tree

‎hackrfpy/src/hackrfpy/_commands/capture.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@ def capture(self, freq: float, sample_rate: float, *,
4242
baseband_bw: float | None = None, to_stdout: bool = False,
4343
sigmf: bool = True, segment_secs: float | None = None,
4444
print_cmd: bool = False) -> Any:
45+
"""Receive IQ at freq/sample_rate into a file (with SigMF sidecar).
46+
47+
Bound with num_samples or duration, or neither for an open-ended handle
48+
(call .stop() on the returned process handle). segment_secs rolls output
49+
across numbered files (whole files, short re-open gap between them; use
50+
open_receiver for gapless). to_stdout=True streams decoded blocks
51+
instead of writing a file.
52+
"""
4553
self.require_mode(C.MODE_RX)
4654
freq, sample_rate, lna, vga = self.validate_rx(freq, sample_rate, lna, vga)
4755
bw = self._auto_baseband(sample_rate, baseband_bw)
@@ -110,20 +118,29 @@ def _gen() -> Generator[np.ndarray, None, None]: # decoded, not raw
110118

111119
# ---- aliases ----
112120
def rx(self, *a: Any, **k: Any) -> Any:
121+
"""Alias of capture()."""
113122
return self.capture(*a, **k)
114123

115124
def capture_samples(self, freq: float, sample_rate: float,
116125
num_samples: int, **k: Any) -> Any:
126+
"""Alias of capture() with a required num_samples bound."""
117127
return self.capture(freq, sample_rate, num_samples=num_samples, **k)
118128

119129
def capture_seconds(self, freq: float, sample_rate: float,
120130
duration: float, **k: Any) -> Any:
131+
"""Alias of capture() with a required duration bound."""
121132
return self.capture(freq, sample_rate, duration=duration, **k)
122133

123134
def scan_frequencies(self, freqs: list[float], sample_rate: float,
124135
num_samples: int, *,
125136
on_capture: Callable[..., Any] | None = None,
126137
**k: Any) -> dict[float, np.ndarray] | None:
138+
"""Capture num_samples of IQ at each frequency in turn.
139+
140+
Returns {freq: complex64 ndarray}, or None when on_capture consumes
141+
blocks instead. Each visit re-opens the device (short gap between
142+
frequencies).
143+
"""
127144
# Sequentially capture a fixed sample count at each frequency in
128145
# `freqs`, retuning between them. This does NOT close the gapless-
129146
# retune gap (each retune is a fresh hackrf_transfer with a short
@@ -148,6 +165,11 @@ def scan_frequencies(self, freqs: list[float], sample_rate: float,
148165
# ---- in-memory + context-managed entry points ----
149166
def capture_array(self, freq: float, sample_rate: float, num_samples: int,
150167
*, return_params: bool = False, **k: Any) -> Any:
168+
"""Return exactly num_samples complex64 samples in RAM, no file.
169+
170+
The scripting entry point. return_params=True also returns the
171+
validated parameters actually used.
172+
"""
151173
# Scripting entry point: return EXACTLY num_samples complex64 samples
152174
# in RAM, no file. Built on the stdout-stream path so it shares the
153175
# odd-byte carry + clean-reap logic. The stream is closed as soon as
@@ -184,6 +206,12 @@ def open_receiver(self, freq: float, sample_rate: float, *, lna: int = 16,
184206
vga: int = 20, amp: bool = False,
185207
baseband_bw: float | None = None,
186208
read_samples: int = 131072) -> PersistentReceiver:
209+
"""Open a long-lived receive stream; returns a PersistentReceiver.
210+
211+
One hackrf_transfer process serves many .read(n) calls: consecutive
212+
reads are gapless (contrast capture(segment_secs=...)). Use as a context
213+
manager to guarantee the child is reaped.
214+
"""
187215
# Open a PERSISTENT fixed-frequency receiver: one long-lived
188216
# hackrf_transfer you drain in segments over time, so you don't pay the
189217
# ~1-2 s process spin-up per capture. Use as a context manager:
@@ -204,6 +232,11 @@ def open_receiver(self, freq: float, sample_rate: float, *, lna: int = 16,
204232

205233
def capture_stream(self, freq: float, sample_rate: float,
206234
**k: Any) -> StreamCtx:
235+
"""Context manager yielding decoded complex64 blocks from a live stream.
236+
237+
The receiving hackrf_transfer is always reaped on block exit, even on
238+
exception.
239+
"""
207240
# Context manager wrapping the live stdout stream so the receiving
208241
# hackrf_transfer is ALWAYS reaped on exit, even on exception:
209242
# with h.capture_stream(433.92e6, 8e6) as blocks:
@@ -217,6 +250,11 @@ def capture_callback(self, freq: float, sample_rate: float,
217250
on_block: Callable[..., Any], *,
218251
max_samples: int | None = None,
219252
max_blocks: int | None = None, **k: Any) -> int:
253+
"""Invoke on_block(iq) per decoded block until a bound or False return.
254+
255+
Bounds: max_samples, max_blocks, or the callback returning False.
256+
Returns the number of samples delivered.
257+
"""
220258
# Binder-style ergonomics over the subprocess stream: instead of the
221259
# caller writing the receive loop, register a callback that fires with
222260
# each decoded complex64 block as it arrives. This is the usability

‎hackrfpy/src/hackrfpy/_commands/device.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,24 @@
2626
class DeviceMixin(HostOps):
2727
# ---- clock ----
2828
def clock(self, *args: Any, print_cmd: bool = False) -> Any:
29+
"""Passthrough to hackrf_clock with the given arguments."""
2930
argv = ["clock"] + list(args)
3031
return self._run(argv, mode="blocking", text=True, print_cmd=print_cmd)
3132

3233
# ---- operacake antenna switch ----
3334
def operacake(self, *args: Any, print_cmd: bool = False) -> Any:
35+
"""Passthrough to hackrf_operacake with the given arguments."""
3436
argv = ["operacake"] + list(args)
3537
return self._run(argv, mode="blocking", text=True, print_cmd=print_cmd)
3638

3739
def operacake_list(self) -> Any:
40+
"""List attached Opera Cake boards (hackrf_operacake -l)."""
3841
return self.operacake("-l")
3942

4043
# ---- cpld jtag (CPLD firmware) ----
4144
def cpldjtag(self, firmware: str, *, confirm: bool = False,
4245
print_cmd: bool = False) -> Any:
46+
"""Program CPLD firmware (DANGEROUS; requires confirm=True)."""
4347
if not confirm and not print_cmd:
4448
raise HackRFValueError(
4549
"cpldjtag flashes the CPLD and can brick the board. "
@@ -50,6 +54,11 @@ def cpldjtag(self, firmware: str, *, confirm: bool = False,
5054
# ---- spiflash (firmware) ----
5155
def spiflash_write(self, firmware: str, *, confirm: bool = False,
5256
print_cmd: bool = False) -> Any:
57+
"""Write SPI flash firmware (MOST DANGEROUS; requires confirm=True).
58+
59+
A bad image can brick the board until DFU recovery. print_cmd dry-runs
60+
without the confirm gate.
61+
"""
5362
# Writing firmware. The single most dangerous operation in the library.
5463
if not confirm and not print_cmd:
5564
raise HackRFValueError(
@@ -61,17 +70,20 @@ def spiflash_write(self, firmware: str, *, confirm: bool = False,
6170

6271
def spiflash_read(self, out: str, length: int | None = None,
6372
print_cmd: bool = False) -> Any:
73+
"""Read SPI flash contents to a file (safe, read-only)."""
6474
argv: list[Any] = ["spiflash", "-r", out]
6575
if length is not None:
6676
argv += ["-l", int(length)]
6777
return self._run(argv, mode="blocking", text=True, print_cmd=print_cmd)
6878

6979
def spiflash_reset(self, print_cmd: bool = False) -> Any:
80+
"""Reset the device (hackrf_spiflash -R)."""
7081
return self._run(["spiflash", "-R"], mode="blocking", text=True,
7182
print_cmd=print_cmd)
7283

7384
# ---- debug register access ----
7485
def debug(self, *args: Any, print_cmd: bool = False) -> Any:
86+
"""Passthrough to hackrf_debug with the given arguments."""
7587
argv = ["debug"] + list(args)
7688
return self._run(argv, mode="blocking", text=True, print_cmd=print_cmd)
7789

@@ -80,6 +92,11 @@ def debug(self, *args: Any, print_cmd: bool = False) -> Any:
8092
# (was 'doctor' -- kept as an alias below for the familiar CLI verb)
8193
# =================================================================
8294
def preflight(self, capture_path: str = ".") -> dict[str, Any]:
95+
"""Check tools, board, free disk, and mode; return a structured report.
96+
97+
Raises only on hard environment failures; problems are listed in the
98+
report so `doctor && capture` workflows can gate on them.
99+
"""
83100
# Checks tooling, board presence, free disk, and reports the active
84101
# mode. Returns a structured report; raises only on hard environment
85102
# failures the user must fix.
@@ -141,10 +158,16 @@ def preflight(self, capture_path: str = ".") -> dict[str, Any]:
141158
# doctor: familiar alias for preflight (brew/flutter-style verb). The CLI
142159
# still exposes `hrf doctor`; the honest method name is preflight().
143160
def doctor(self, capture_path: str = ".") -> dict[str, Any]:
161+
"""Alias of preflight()."""
144162
return self.preflight(capture_path=capture_path)
145163

146164
def features(self, tool_version: str | None = None,
147165
firmware_version: str | None = None) -> dict[str, Any]:
166+
"""Map tools/firmware version strings to capability flags.
167+
168+
The firmware version (e.g. '2024.02.1') is the reliable signal; tools
169+
versions are often git hashes.
170+
"""
148171
# Map version strings -> capability flags. The reliable year signal is
149172
# the FIRMWARE version (e.g. "2024.02.1"); the tools version is often a
150173
# git tag (e.g. "git-b1dbb47") with no parseable year. If nothing is

‎hackrfpy/src/hackrfpy/_commands/info.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
class InfoMixin(HostOps):
2323
def info(self, raw: bool = False,
2424
print_cmd: bool = False) -> dict[str, Any] | str | None:
25+
"""Run hackrf_info; return a parsed dict (or raw text with raw=True)."""
2526
# Returns a parsed dict by default, or the raw text if raw=True.
2627
if print_cmd:
2728
self._run(["info"], mode="blocking", print_cmd=True)
@@ -33,10 +34,16 @@ def info(self, raw: bool = False,
3334
return self.parse_info(out)
3435

3536
def get_info(self) -> dict[str, Any] | str | None:
37+
"""Alias of info()."""
3638
# alias
3739
return self.info()
3840

3941
def detect(self) -> dict[str, Any]:
42+
"""Detect and identify attached boards (the serial-port-scan analog).
43+
44+
Returns a dict with ready (bool), boards (list of per-board dicts),
45+
tools_version, and problem (actionable message when not ready).
46+
"""
4047
# Hardware autodetection + identification, the HackRF analog of a
4148
# serial-port scan. The HackRF is NOT a serial device -- there are no
4249
# COM ports to walk -- so "detection" means: run hackrf_info, confirm
@@ -108,6 +115,7 @@ def detect(self) -> dict[str, Any]:
108115
return result
109116

110117
def identify(self, serial: str | None = None) -> dict[str, Any] | None:
118+
"""Return one board's identity dict (by serial, or the first found)."""
111119
# Return the identity of a single board: the one matching `serial`, or
112120
# the first detected board if serial is None. Returns the board dict
113121
# from detect()["boards"], or None if not found. Convenience for "what
@@ -124,6 +132,7 @@ def identify(self, serial: str | None = None) -> dict[str, Any] | None:
124132

125133
@staticmethod
126134
def parse_info(text: str) -> dict[str, Any]:
135+
"""Parse hackrf_info text into {library: ..., boards: [...]}."""
127136
# hackrf_info prints "Key: value" lines: a version preamble, then one
128137
# block per board. We keep the preamble under "library" and each board
129138
# under "boards". A board starts at "Found HackRF" or, for outputs that

‎hackrfpy/src/hackrfpy/_commands/sweep.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ def sweep(self, f_min_hz: float, f_max_hz: float, *,
2929
num_sweeps: int | None = None,
3030
print_cmd: bool = False
3131
) -> Generator[dict[str, Any], None, None] | None:
32+
"""Stream a spectrum sweep as parsed dict rows (generator).
33+
34+
Rows carry date, time, hz_low, hz_high, bin_width, num_samples and db
35+
(a list per bin). Segments arrive OUT of frequency order. Edges snap
36+
outward to integer MHz (floor low, ceil high) so the swept range always
37+
contains the requested band.
38+
"""
3239
# GENERATOR yielding parsed rows (dicts). Validate the band edges with
3340
# the same hard-range logic, snap gains. hackrf_sweep takes the range
3441
# in MHz as f_min:f_max.
@@ -96,6 +103,7 @@ def _gen() -> Generator[dict[str, Any], None, None]:
96103

97104
def sweep_collect(self, f_min_hz: float, f_max_hz: float,
98105
num_sweeps: int = 1, **k: Any) -> list[dict[str, Any]]:
106+
"""Run num_sweeps full passes and return the parsed rows as a list."""
99107
# Convenience: collect a bounded number of sweeps into a list.
100108
k.pop("num_sweeps", None)
101109
rows = self.sweep(f_min_hz, f_max_hz, num_sweeps=num_sweeps, **k)
@@ -109,6 +117,12 @@ def monitor_frequencies(self, freqs_hz: list[float], *,
109117
on_update: Callable[..., Any] | None = None,
110118
lna: int = 16, vga: int = 20,
111119
amp: bool = False) -> Any:
120+
"""Track power over time at several frequencies via one sweep.
121+
122+
Yields (or passes to on_update) {freq: dB} per sweep pass; the reading
123+
is the sweep bin covering the frequency (max of that bin +/-1), not a
124+
segment average. Power only -- use scan_frequencies for IQ.
125+
"""
112126
# Watch POWER over time at several frequencies, backed by hackrf_sweep's
113127
# fast internal hardware retuning. This is DELIBERATELY a different
114128
# method from scan_frequencies():
@@ -183,6 +197,11 @@ def sweep_to_file(self, f_min_hz: float, f_max_hz: float, out: str, *,
183197
vga: int = 20, amp: bool = False, one_shot: bool = False,
184198
num_sweeps: int | None = None,
185199
print_cmd: bool = False) -> str | None:
200+
"""Run hackrf_sweep writing to a file (CSV, or -B/-I binary).
201+
202+
binary=True (-B) and inverse_fft=True (-I) produce unparsed binary
203+
passthrough; the library parses only the CSV text format.
204+
"""
186205
# Write sweep output straight to a file instead of yielding parsed
187206
# rows. This is the home for hackrf_sweep's binary-output flags, which
188207
# don't fit the text-CSV generator:
@@ -218,6 +237,7 @@ def sweep_to_file(self, f_min_hz: float, f_max_hz: float, out: str, *,
218237
return None if print_cmd else out
219238

220239
def sweep_stream(self, f_min_hz: float, f_max_hz: float, **k: Any) -> Any:
240+
"""Return a StreamCtx over parsed sweep rows (reaped on context exit)."""
221241
# Context manager around the sweep generator so the underlying
222242
# hackrf_sweep is ALWAYS reaped on exit -- including KeyboardInterrupt
223243
# out of a live consumer loop (e.g. a waterfall). Without this, a
@@ -235,6 +255,7 @@ def sweep_stream(self, f_min_hz: float, f_max_hz: float, **k: Any) -> Any:
235255

236256
@staticmethod
237257
def parse_sweep_line(line: str) -> dict[str, Any] | None:
258+
"""Parse one hackrf_sweep CSV line into a row dict, or None if invalid."""
238259
# Returns {date,time,hz_low,hz_high,bin_width,num_samples,db:[...]} or
239260
# None for blank/garbled lines.
240261
line = line.strip()

‎hackrfpy/src/hackrfpy/_commands/transmit.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ def transmit(self, freq: float, sample_rate: float, source: str, *,
3131
num_samples: int | None = None, duration: float | None = None,
3232
max_duration: float | None = None,
3333
print_cmd: bool = False) -> Any:
34+
"""Transmit an int8 interleaved I/Q file (requires TX mode).
35+
36+
Refuses unless set_mode('tx') was called. Bound with num_samples,
37+
duration, or repeat (optionally capped by max_duration). Duration bounds
38+
are enforced parent-side (timed interrupt): a --print-cmd argv copied and
39+
run by hand carries NO time bound.
40+
"""
3441
# source: path to an int8 I/Q file to transmit.
3542
# max_duration: hard ceiling (seconds) enforced even for open-ended
3643
# repeat transmits. A transmitter that runs until .stop() is a
@@ -80,10 +87,12 @@ def transmit(self, freq: float, sample_rate: float, source: str, *,
8087

8188
# ---- aliases ----
8289
def tx(self, *a: Any, **k: Any) -> Any:
90+
"""Alias of transmit()."""
8391
return self.transmit(*a, **k)
8492

8593
def transmit_file(self, freq: float, sample_rate: float, source: str,
8694
**k: Any) -> Any:
95+
"""Alias of transmit()."""
8796
return self.transmit(freq, sample_rate, source, **k)
8897

8998
def transmit_cw(self, freq: float, sample_rate: float, *,
@@ -92,6 +101,11 @@ def transmit_cw(self, freq: float, sample_rate: float, *,
92101
duration: float | None = None,
93102
max_duration: float | None = None,
94103
print_cmd: bool = False) -> Any:
104+
"""Transmit a constant-wave test tone (requires TX mode).
105+
106+
amplitude is the DAC level 0-127. Same duration semantics as
107+
transmit(): the time bound is parent-side, not in the printed argv.
108+
"""
95109
# Constant-wave / signal-source test mode: hackrf_transfer -c <amp>.
96110
# Transmits a fixed signal at `amplitude` (0-127) instead of a file.
97111
# TX-gated like any transmit. Useful for antenna/range testing. Open-

0 commit comments

Comments
 (0)