Files
heltec-repeater/hil/iq_energy.py
T

48 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""Detect burst energy in a raw rtl_sdr u8 IQ capture.
Usage: iq_energy.py iq.raw [sample_rate]
Prints noise floor, and burst groups >9 dB above floor with 1 ms resolution.
Exit code 0 if at least one burst found, 2 otherwise.
"""
import sys
import numpy as np
path = sys.argv[1]
fs = int(sys.argv[2]) if len(sys.argv) > 2 else 1_600_000
win = fs // 1000 # 1 ms
pows = []
with open(path, "rb") as f:
while True:
raw = f.read(fs * 2) # 1 s
if len(raw) < win * 2:
break
buf = np.frombuffer(raw, dtype=np.uint8).astype(np.float32) - 127.5
iq = buf[0::2] + 1j * buf[1::2]
w = np.abs(iq) ** 2
w = w[: (len(w) // win) * win].reshape(-1, win).mean(axis=1)
pows.append(w)
db = 10 * np.log10(np.concatenate(pows) + 1e-9)
floor = np.median(db)
print(f"windows: {len(db)} x 1ms, floor={floor:.1f} dB, "
f"p99={np.percentile(db, 99):.1f}, max={db.max():.1f}")
idx = np.where(db > floor + 9)[0]
groups = []
if len(idx):
start = prev = idx[0]
for i in idx[1:]:
if i > prev + 2:
groups.append((start, prev))
start = i
prev = i
groups.append((start, prev))
print(f"burst groups (>9 dB over floor): {len(groups)}")
for g in groups[:40]:
print(f" t={g[0]/1000:.3f}s dur={g[1]-g[0]+1}ms "
f"peak=+{db[g[0]:g[1]+1].max()-floor:.1f}dB")
sys.exit(0 if groups else 2)