#!/usr/bin/env python3 """Verify standalone beacon TX from RF evidence alone (no serial log). Use case: DUT on battery/wall power with no USB host, transmitting the synthetic OMS beacon every N ms. Two independent lines of evidence from one recorded IQ stream: 1. Content: rtl_wmbus decodes of the known beacon frame (mfr 0x4D8E "SLN", ID 00000001). Decode timestamps are clustered into airings (two demodulators emit 1-2 lines per airing). 2. Timing: short bursts in the IQ envelope forming a comb at the beacon period. The effective period is fitted from the data, because the firmware schedules the next beacon after the previous TX completes (configured period + a few ms), and a beacon can be delayed by RX activity. Ambient (non-beacon) decodes and long bursts are reported as the observer health control. Usage: verify_beacon_standalone.py --iq iq.raw --decodes decodes.log \ --period-ms 3000 [--rate 1600000] [--json] Exit: 0 = beacon TX confirmed, 1 = not observed, 2 = insufficient data. """ import argparse import json import re import sys import numpy as np BEACON_HEX = "448e4d010000000107" # C + mfr + ID + ver + type, L-agnostic DECODE_RE = re.compile( r"^(?P[TC]1);\d+;\d+;(?P\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+);" r".*0x(?P[0-9a-fA-F]+)") def parse_decodes(path): # Distinct airings are counted by distinct payload: the beacon's # access number increments per airing, so each airing has unique hex, # while rtl_wmbus's two demodulators emitting 1-2 lines per airing # collapse to one. Timestamp-independent, so it works for both live # captures and offline `rtl_wmbus < iq.raw` (compressed wall clock). # acc wraps at 256: valid for captures up to 256 beacon periods. beacon_hex, beacon_lines, ambient = set(), 0, 0 for line in open(path, errors="replace"): m = DECODE_RE.match(line.strip()) if not m: continue if BEACON_HEX in m.group("hex").lower(): beacon_hex.add(m.group("hex").lower()) beacon_lines += 1 else: ambient += 1 return len(beacon_hex), beacon_lines, ambient def envelope_bursts(path, rate): win = rate // 1000 # 1 ms bins env = [] with open(path, "rb") as f: while True: raw = f.read(rate * 2) if len(raw) < win * 2: break u8 = np.frombuffer(raw, dtype=np.uint8) b = u8.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: return None, 0.0, [] db = 10 * np.log10(np.concatenate(env) + 1e-9) floor = float(np.median(db)) idx = np.where(db > floor + 6.0)[0] bursts = [] if len(idx): start = prev = idx[0] for i in idx[1:]: if i > prev + 3: bursts.append((int(start), int(prev - start + 1), float(db[start:prev + 1].max() - floor))) start = i prev = i bursts.append((int(start), int(prev - start + 1), float(db[start:prev + 1].max() - floor))) return db, floor, bursts def main(): ap = argparse.ArgumentParser() ap.add_argument("--iq", required=True) ap.add_argument("--decodes") ap.add_argument("--period-ms", type=float, required=True, help="configured beacon_period_ms") ap.add_argument("--rate", type=int, default=1_600_000) ap.add_argument("--json", action="store_true") args = ap.parse_args() db, floor, bursts = envelope_bursts(args.iq, args.rate) if db is None: print("IQ empty or unreadable", file=sys.stderr) sys.exit(2) # Beacon candidates: short bursts (L=19 beacon airtime is 2.7 ms; # envelope smearing widens that). Longer bursts are ambient meters. cand = [b for b in bursts if b[1] <= 8] long_bursts = [b for b in bursts if b[1] > 8] # Fit the effective period from consecutive candidate intervals near # the configured period, then count on-grid intervals (a missed or # RX-delayed slot shows up as ~2x the period and is counted as a gap). starts = np.array([b[0] for b in cand], dtype=float) iv = np.diff(starts) p = args.period_ms near = iv[(iv > 0.8 * p) & (iv < 1.35 * p)] fitted = float(np.median(near)) if len(near) else None on_grid = int(len(near)) gaps = int(np.count_nonzero((iv > 1.6 * p) & (iv < 2.6 * p))) cand_levels = [b[2] for b in cand] airings, beacon_lines, ambient_decodes = 0, 0, 0 if args.decodes: airings, beacon_lines, ambient_decodes = parse_decodes(args.decodes) decode_ok = airings >= 5 comb_ok = on_grid >= 5 and fitted is not None if decode_ok or comb_ok: verdict = "confirmed" rc = 0 elif len(cand) or airings: verdict = "insufficient" rc = 2 else: verdict = "not_observed" rc = 1 report = { "iq_seconds": round(len(db) / 1000.0, 1), "noise_floor_db": round(floor, 1), "beacon_candidate_bursts": len(cand), "candidate_median_db": (round(float(np.median(cand_levels)), 1) if cand_levels else None), "period_configured_ms": p, "period_fitted_ms": round(fitted, 1) if fitted else None, "intervals_on_grid": on_grid, "missed_slot_gaps": gaps, "beacon_decoded_airings": airings, "beacon_decode_lines": beacon_lines, "ambient_decodes": ambient_decodes, "ambient_long_bursts": len(long_bursts), "verdict": verdict, } if args.json: print(json.dumps(report)) else: print(f"IQ: {report['iq_seconds']} s, floor {report['noise_floor_db']} dB") print(f"beacon bursts: {len(cand)} (median " f"+{report['candidate_median_db']} dB), period fitted " f"{report['period_fitted_ms']} ms vs configured {p:.0f} ms, " f"{on_grid} intervals on grid, {gaps} missed-slot gaps") print(f"decoded beacon airings: {airings} ({beacon_lines} lines); " f"ambient decodes: {ambient_decodes}; " f"ambient long bursts: {len(long_bursts)}") print(f"VERDICT: {verdict}") sys.exit(rc) if __name__ == "__main__": main()