Files
heltec-repeater/hil/verify_repeats_iq.py
T

148 lines
5.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Verify repeater behaviour from raw IQ, independent of packet decoding.
Why: on this bench the Heltec transmission arrives at the SDR roughly 36 dB
stronger than real meter traffic and sits at the dongle's full scale, so
rtl-wmbus frequently cannot decode the repeat even though the RF is present
and correct. Burst-envelope analysis is immune to that: it measures whether
a second transmission occurred at the configured delay with the expected
airtime.
This does NOT prove the repeat is decodable as C1 -- that is proven
separately by the synthetic-burst phase (hil/verify_tx.py). Together they
close the loop: framing is decodable, and real repeats are emitted with the
right timing and duration.
Usage:
verify_repeats_iq.py --iq iq.raw --serial serial.log --delay-ms 200
[--rate 1600000] [--tol-ms 40] [--json]
"""
import argparse
import json
import sys
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument("--iq", required=True)
ap.add_argument("--serial", required=True)
ap.add_argument("--delay-ms", type=float, required=True)
ap.add_argument("--rate", type=int, default=1_600_000)
ap.add_argument("--tol-ms", type=float, default=40.0)
ap.add_argument("--strong-db", type=float, default=25.0,
help="bursts this far over floor are attributed to the DUT")
ap.add_argument("--json", action="store_true")
args = ap.parse_args()
WIN = args.rate // 1000 # 1 ms
env = []
with open(args.iq, "rb") as f:
while True:
raw = f.read(args.rate * 2)
if len(raw) < WIN * 2:
break
b = np.frombuffer(raw, dtype=np.uint8).astype(np.float32) - 127.5
iq = b[0::2] + 1j * b[1::2]
p = np.abs(iq) ** 2
p = p[: (len(p) // WIN) * WIN].reshape(-1, WIN).mean(axis=1)
env.append(p)
if not env:
print(json.dumps({"error": "iq too short"}) if args.json else "ERROR: iq too short")
sys.exit(3)
db = 10 * np.log10(np.concatenate(env) + 1e-9)
floor = float(np.median(db))
# any burst at all: 8 dB over floor; DUT bursts: --strong-db over floor
idx = np.where(db > floor + 8.0)[0]
bursts = []
if len(idx):
start = prev = idx[0]
for i in idx[1:]:
if i > prev + 3:
bursts.append((start, prev))
start = i
prev = i
bursts.append((start, prev))
burst_info = [{
"t_ms": int(s),
"duration_ms": int(e - s + 1),
"peak_db_over_floor": float(db[s:e + 1].max() - floor),
} for s, e in bursts]
# Pair: any burst followed by a STRONG burst at delay +/- tol
lo = args.delay_ms - args.tol_ms
hi = args.delay_ms + args.tol_ms
pairs = []
for i, a in enumerate(burst_info):
a_end = a["t_ms"] + a["duration_ms"]
for b in burst_info[i + 1:]:
gap = b["t_ms"] - a_end
if gap > hi:
break
if lo <= gap <= hi and b["peak_db_over_floor"] >= args.strong_db:
pairs.append({
"original_t_ms": a["t_ms"],
"repeat_t_ms": b["t_ms"],
"gap_ms": int(gap),
"original_peak_db": round(a["peak_db_over_floor"], 1),
"repeat_peak_db": round(b["peak_db_over_floor"], 1),
"repeat_duration_ms": b["duration_ms"],
})
break
# firmware ground truth for the same window
tx_ok = 0
rx_ok = 0
for line in open(args.serial, errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
ev = json.loads(line)
except json.JSONDecodeError:
continue
if ev.get("event") == "wmbus_tx" and str(ev.get("result", "")).startswith("ok"):
tx_ok += 1
elif ev.get("event") == "wmbus_rx" and ev.get("crc_ok"):
rx_ok += 1
strong = [b for b in burst_info if b["peak_db_over_floor"] >= args.strong_db]
gaps = sorted(p["gap_ms"] for p in pairs)
result = {
"iq_seconds": round(len(db) / 1000.0, 1),
"noise_floor_db": round(floor, 1),
"bursts_total": len(burst_info),
"bursts_strong_dut": len(strong),
"firmware_tx_ok": tx_ok,
"firmware_rx_crc_ok": rx_ok,
"repeat_pairs_at_delay": len(pairs),
"expected_delay_ms": args.delay_ms,
"gap_ms": {
"min": gaps[0] if gaps else None,
"median": gaps[len(gaps) // 2] if gaps else None,
"max": gaps[-1] if gaps else None,
},
"pairs": pairs[:50],
}
if args.json:
print(json.dumps(result, indent=2))
else:
print(f"IQ_REPEAT_PROOF iq={result['iq_seconds']}s floor={floor:.1f}dB")
print(f" bursts total / strong(DUT): {len(burst_info)} / {len(strong)}")
print(f" firmware TX ok / RX crc-ok: {tx_ok} / {rx_ok}")
print(f" repeat pairs at {args.delay_ms:.0f}+-{args.tol_ms:.0f} ms: {len(pairs)}")
if gaps:
print(f" observed gap min/med/max: "
f"{gaps[0]}/{gaps[len(gaps)//2]}/{gaps[-1]} ms")
for p in pairs[:10]:
print(f" t={p['original_t_ms']/1000:.3f}s -> +{p['gap_ms']}ms "
f"({p['original_peak_db']:+.1f} dB -> {p['repeat_peak_db']:+.1f} dB, "
f"{p['repeat_duration_ms']} ms)")
sys.exit(0 if pairs else 1)