#!/usr/bin/env python3 """Functional health check for the RTL-SDR observer. Why this exists: this dongle intermittently enters a state where the R820T tuner is not actually receiving (I2C init failure, PLL wedge, or direct-sampling bypass). Captures then contain gain-independent noise -- indistinguishable from "no meter traffic" unless the receiver is tested. Every empty capture must be attributable. Validated signatures (this hardware, 1.6 Msps at 868.95 MHz): healthy : mean power ~ -3 dB @20.7 dB gain, ~ +5 dB @42.1 dB gain, averaged spectrum span 18-26 dB (filter shape + signals) wedged : mean power ~ +40 dB (railed), spectrum span < 10 dB, and power does not track tuner gain Usage: sdr_health.py [--freq HZ] [--json] Exit 0 = healthy, 2 = deaf/wedged, 3 = could not capture. """ import argparse import json import os import subprocess import sys import tempfile import numpy as np ap = argparse.ArgumentParser() ap.add_argument("--freq", type=int, default=868_950_000) ap.add_argument("--json", action="store_true") args = ap.parse_args() FS = 1_600_000 NS = 480_000 # 0.3 s NFFT = 4096 # Reference measurements on this dongle at 868.95 MHz, 1.6 Msps: # fresh replug (fully healthy) : mean@42.1 ~ +22 dB, span ~ 51 dB, delta ~ 25 dB # after minutes of streaming : mean@42.1 ~ +5 dB, span ~ 21 dB, delta ~ 8 dB # wedged / bypassed : mean ~ +40 dB railed, span < 10 dB, delta ~ 0 # The middle state still decodes strong meters but loses roughly 17 dB of # sensitivity, so it must be reported rather than silently accepted. RAILED_DB = 25.0 MIN_SPAN_DB = 12.0 # below this the receiver is not seeing RF structure MIN_GAIN_DELTA_DB = 3.0 # noise must track tuner gain at all HEALTHY_SPAN_DB = 35.0 # full sensitivity reference HEALTHY_DELTA_DB = 15.0 def measure(gain): fd, path = tempfile.mkstemp(suffix=".raw") os.close(fd) try: p = subprocess.run( ["rtl_sdr", "-f", str(args.freq), "-s", str(FS), "-g", str(gain), "-n", str(NS), path], capture_output=True, timeout=30) raw = np.fromfile(path, dtype=np.uint8) if raw.size < NS: return None, p.stderr.decode(errors="replace") b = raw.astype(np.float32) - 127.5 iq = b[0::2] + 1j * b[1::2] n = (len(iq) // NFFT) * NFFT blocks = iq[:n].reshape(-1, NFFT) * np.hanning(NFFT) sp = np.abs(np.fft.fftshift(np.fft.fft(blocks, axis=1))) ** 2 db = 10 * np.log10(sp.mean(axis=0) + 1e-9) return { "gain": gain, "mean_power_db": float(10 * np.log10(np.mean(np.abs(iq) ** 2) + 1e-9)), "spectrum_span_db": float(db.max() - db.min()), }, p.stderr.decode(errors="replace") finally: os.unlink(path) lo, err_lo = measure(20.7) hi, err_hi = measure(42.1) if lo is None or hi is None: out = {"health": "capture_failed", "stderr": ((err_lo or "") + (err_hi or ""))[-500:]} print(json.dumps(out) if args.json else f"SDR_HEALTH=capture_failed\n{out['stderr']}") sys.exit(3) delta = hi["mean_power_db"] - lo["mean_power_db"] reasons = [] # Railed only counts as a fault together with a flat spectrum: a healthy # receiver with a strong nearby signal can legitimately show high mean power. if hi["mean_power_db"] > RAILED_DB and hi["spectrum_span_db"] < 15.0: reasons.append(f"railed: mean power {hi['mean_power_db']:.1f} dB > {RAILED_DB} " f"with flat spectrum") if hi["spectrum_span_db"] < MIN_SPAN_DB: reasons.append(f"flat spectrum: span {hi['spectrum_span_db']:.1f} dB < {MIN_SPAN_DB}") if delta < MIN_GAIN_DELTA_DB: reasons.append(f"noise does not track gain: delta {delta:.1f} dB < {MIN_GAIN_DELTA_DB}") usable = not reasons if not usable: level = "deaf" elif (hi["spectrum_span_db"] >= HEALTHY_SPAN_DB and delta >= HEALTHY_DELTA_DB): level = "full" else: level = "degraded" result = { "health": "ok" if usable else "deaf", "sensitivity": level, "low": lo, "high": hi, "gain_delta_db": round(delta, 2), "reasons": reasons, } if args.json: print(json.dumps(result)) else: print(f"SDR_HEALTH={result['health']}") print(f"SDR_SENSITIVITY={level}") print(f"SDR_MEAN_POWER_20DB={lo['mean_power_db']:.2f}") print(f"SDR_MEAN_POWER_42DB={hi['mean_power_db']:.2f}") print(f"SDR_SPECTRUM_SPAN_DB={hi['spectrum_span_db']:.2f}") print(f"SDR_GAIN_DELTA_DB={delta:.2f}") for r in reasons: print(f"SDR_REASON={r}") sys.exit(0 if usable else 2)