Skip to content

Commit fdfca3e

Browse files
committed
bin issue corrected, truncation fix
1 parent fe28540 commit fdfca3e

3 files changed

Lines changed: 32 additions & 10 deletions

File tree

‎hackrfpy/src/hackrfpy/__init__.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,14 @@
1111
)
1212
from . import constants
1313

14+
try:
15+
from importlib.metadata import PackageNotFoundError, version as _pkg_version
16+
__version__ = _pkg_version("hackrfpy")
17+
except PackageNotFoundError: # running from a checkout
18+
__version__ = "0.0.0+unknown"
19+
1420
__all__ = [
15-
"HackRF", "load_iq", "parse_freq", "constants",
21+
"HackRF", "load_iq", "parse_freq", "constants", "__version__",
1622
"write_sigmf_meta", "read_sigmf_meta",
1723
"HackRFError", "HackRFValueError", "HackRFModeError",
1824
"HackRFDeviceError", "HackRFEnvironmentError",

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

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,19 @@ def sweep(self, f_min_hz: float, f_max_hz: float, *,
4646
self.print_message(f"[*] mode: {self.mode}")
4747

4848
lo = int(f_min_hz // 1_000_000)
49-
hi = int(f_max_hz // 1_000_000)
49+
hi = -int(-f_max_hz // 1_000_000) # ceil: never truncate the top
5050
# hackrf_sweep takes integer MHz edges, so sub-MHz precision is lost.
51-
# Warn rather than silently shift the band the user asked for.
51+
# Snap OUTWARD (floor the low edge, ceil the high edge) so the swept
52+
# range always CONTAINS the requested band -- flooring both edges
53+
# silently dropped everything above the last whole MHz (e.g.
54+
# 433.9:434.1 swept 433:434 and never covered 434.0-434.1). Warn so
55+
# the user knows the edges moved.
5256
if f_min_hz % 1_000_000 or f_max_hz % 1_000_000:
5357
self.warn(
54-
f"sweep edges snapped to MHz: "
58+
f"sweep edges snapped to MHz (outward): "
5559
f"{f_min_hz/1e6:g}:{f_max_hz/1e6:g} -> {lo}:{hi} MHz "
56-
f"(hackrf_sweep takes integer MHz)")
60+
f"(hackrf_sweep takes integer MHz; requested band fully "
61+
f"covered)")
5762
argv = ["sweep", "-f", f"{lo}:{hi}", "-l", lna, "-g", vga,
5863
"-a", 1 if amp else 0]
5964
if bin_width is not None:
@@ -124,13 +129,20 @@ def monitor_frequencies(self, freqs_hz: list[float], *,
124129
t0 = _time.time()
125130

126131
def _nearest_power(rows_by_low: dict[int, Any], f: float) -> Any:
127-
# find the sweep segment whose [hz_low, hz_high) covers f, return
128-
# the mean dB of that segment's bins (a simple power proxy)
132+
# find the sweep segment whose [hz_low, hz_high) covers f and
133+
# return the dB of the BIN covering f (max of that bin +/-1 for
134+
# tuning slop). Averaging the whole segment diluted a narrowband
135+
# carrier toward the noise floor: in a 5 MHz segment a strong
136+
# signal occupying one bin barely moved the mean.
129137
for low in sorted(rows_by_low):
130138
r = rows_by_low[low]
131139
if r["hz_low"] <= f < r["hz_high"]:
132140
db = r["db"]
133-
return sum(db) / len(db) if db else float("-inf")
141+
if not db:
142+
return float("-inf")
143+
idx = int((f - r["hz_low"]) / r["bin_width"])
144+
idx = max(0, min(idx, len(db) - 1))
145+
return max(db[max(0, idx - 1):idx + 2])
134146
return None
135147

136148
from .._stream_ctx import StreamCtx
@@ -189,7 +201,7 @@ def sweep_to_file(self, f_min_hz: float, f_max_hz: float, out: str, *,
189201
lna = self._snap_gain("lna_gain", lna, C.LNA_GAIN)
190202
vga = self._snap_gain("vga_gain", vga, C.VGA_GAIN)
191203
lo = int(f_min_hz // 1_000_000)
192-
hi = int(f_max_hz // 1_000_000)
204+
hi = -int(-f_max_hz // 1_000_000) # ceil: never truncate the top
193205
argv = ["sweep", "-f", f"{lo}:{hi}", "-l", lna, "-g", vga,
194206
"-a", 1 if amp else 0, "-r", out]
195207
if bin_width is not None:

‎hackrfpy/src/hackrfpy/core.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,11 @@ def from_device(cls, *, tools_dir: str | None = None, verbose: bool = False,
492492
# present. Use it when you want a fail-fast handle for scripting.
493493
h = cls(tools_dir=tools_dir, verbose=verbose, serial=serial)
494494
info = h.info() # raises if no tools / no board
495-
assert isinstance(info, dict) # raw=False -> parsed dict
495+
if not isinstance(info, dict): # raw=False -> parsed dict
496+
# a plain assert is stripped under `python -O`, which would let a
497+
# str flow onward; keep the guard a real, typed error
498+
raise HackRFDeviceError(
499+
"hackrf_info output could not be parsed into a device dict")
496500
if not info.get("boards"):
497501
raise HackRFDeviceError("no HackRF board detected")
498502
h._probed = info

0 commit comments

Comments
 (0)