You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

171 lines
8.0 KiB

#!/usr/bin/env python3
"""Unattended long run: Pluto -> attenuator -> RTL-SDR, decoded live.
Transmits one frame in a loop for --hours at a fixed TX gain while the
streaming receiver (c/cm_rx if built, else stream_rx.py) decodes the RTL-SDR
in real time. At the end it reports delivery, any frame whose body is wrong,
the receiver's load, and how SNR and the frequency offset moved over the
run. Every decoded frame goes to <name>_soak.ods (odfpy) or .csv.
Run it cabled through attenuators: nothing should radiate for hours.
./soak_test.py --hours 2 # SF12 62.5 kHz, -78 dB TX (~ -24 dB SNR)
./soak_test.py --hours 8 --tx-gain -76 --sf 12 --decoder python
"""
import argparse, os, re, shutil, signal, subprocess, sys, threading, time
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import iq_io
from sweep_test import write_table
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--src", default="KD2HSG")
ap.add_argument("--sf", type=int, default=12)
ap.add_argument("--bw", type=float, default=62.5e3)
ap.add_argument("--freq", type=float, default=223.58e6)
ap.add_argument("--hours", type=float, default=2.0)
ap.add_argument("--tx-gain", type=float, default=-78.0, help="Pluto TX gain, dB")
ap.add_argument("--rx-gain", type=float, default=49.6, help="RTL gain, dB")
ap.add_argument("--rx-fs", type=float, default=1e6)
ap.add_argument("--rx-if", type=float, default=250e3)
ap.add_argument("--tx-if", type=float, default=100e3)
ap.add_argument("--uri", default="ip:192.168.2.1")
ap.add_argument("--rtl-device", default="0")
ap.add_argument("--decoder", choices=["auto", "c", "python"], default="auto")
ap.add_argument("--coherent", action="store_true")
ap.add_argument("--noncoherent", action="store_true")
ap.add_argument("--status", type=float, default=300.0, help="load report interval, s")
ap.add_argument("--name", default="soak")
a = ap.parse_args()
if not shutil.which("rtl_sdr"):
sys.exit("rtl_sdr not found on PATH")
cm_rx = os.path.join(HERE, "c", "cm_rx")
use_c = a.decoder == "c" or (a.decoder == "auto" and os.access(cm_rx, os.X_OK))
if a.decoder == "c" and not os.access(cm_rx, os.X_OK):
sys.exit("c/cm_rx not built: (cd c && make)")
msg = f"soak de {a.src}"
rec, py = f"{a.name}_tx", sys.executable
cmd = [py, os.path.join(HERE, "tx_file.py"), rec, "--src", a.src, "--msg", msg,
"--sf", str(a.sf), "--bw", repr(a.bw), "--freq", repr(a.freq),
"--if-offset", repr(a.tx_if), "--repeat", "1", "--gap", "0.5"] + \
(["--coherent"] if a.coherent else []) + (["--noncoherent"] if a.noncoherent else [])
subprocess.run(cmd, check=True)
m = iq_io.read_sigmf_meta(rec)
loop_s = iq_io.recording_samples(rec) / m["fs"]
seconds = a.hours * 3600
expect = seconds / loop_s
rx_lo = a.freq - a.rx_if
log_path = f"{a.name}_soak.log"
pluto = subprocess.Popen([py, os.path.join(HERE, "tools", "pluto_tx.py"), rec, "--uri", a.uri,
"--gain", repr(a.tx_gain), "--seconds", repr(seconds + 120)],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
env=dict(os.environ, PYTHONUNBUFFERED="1"))
t_start = time.time()
rtl = stop = None
try:
while True:
line = pluto.stdout.readline()
if not line:
sys.exit(f"pluto_tx exited (code {pluto.wait()}) before transmitting")
print(" pluto: " + line.rstrip(), flush=True)
if "looping" in line:
break
time.sleep(1.0)
# rtl_sdr computes -n x 2 bytes in 32 bits, so past 2^31 samples (35.8 min
# at 1 MS/s) the count wraps and it stops early (an hour ended at 1452.5 s).
# Longer runs stream without -n and are stopped by a timer instead.
n_samp = int(seconds * a.rx_fs)
use_n = 2 * n_samp < 2 ** 32
rtl = subprocess.Popen(["rtl_sdr", "-d", a.rtl_device, "-f", str(int(round(rx_lo))),
"-s", str(int(a.rx_fs)), "-g", repr(a.rx_gain)]
+ (["-n", str(n_samp)] if use_n else []) + ["-"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if not use_n:
stop = threading.Timer(seconds, rtl.terminate)
stop.daemon = True
stop.start()
if use_c:
dec = [cm_rx, "-", "--fs", repr(a.rx_fs), "--lo", repr(rx_lo), "--freq", repr(a.freq),
"--sf", str(a.sf), "--bw", repr(a.bw), "--status", repr(a.status), "-v"]
else:
dec = [py, os.path.join(HERE, "stream_rx.py"), "-", "--format", "cu8",
"--fs", repr(a.rx_fs), "--lo", repr(rx_lo), "--freq", repr(a.freq),
"--sf", str(a.sf), "--bw", repr(a.bw), "--status", repr(a.status), "-v"]
print(f"$ rtl_sdr ... | {' '.join(os.path.basename(c) if i == 0 else c for i, c in enumerate(dec))}"
f"\n{a.hours:g} h, ~{expect:.0f} frames expected; log in {log_path}", flush=True)
with open(log_path, "w") as log:
d = subprocess.Popen(dec, stdin=rtl.stdout, stdout=subprocess.PIPE, text=True,
env=dict(os.environ, PYTHONUNBUFFERED="1"))
rtl.stdout.close()
for line in d.stdout:
log.write(line)
log.flush()
if not line.lstrip().startswith("SNR"):
print(line.rstrip(), flush=True)
d.wait()
rtl.wait()
except KeyboardInterrupt:
print("\ninterrupted")
finally:
if stop is not None:
stop.cancel()
if rtl is not None and rtl.poll() is None:
rtl.terminate()
if pluto.poll() is None:
pluto.send_signal(signal.SIGINT)
try:
pluto.communicate(timeout=10)
except subprocess.TimeoutExpired:
pluto.kill()
print("Pluto stopped")
summarize(log_path, a.src, msg, seconds, expect, a.name)
print(f"wall time {(time.time() - t_start) / 3600:.2f} h")
def summarize(log_path, src, msg, seconds, expect, name):
lines = open(log_path).read().splitlines() if os.path.exists(log_path) else []
rows, wrong, fails = [], 0, 0
head = re.compile(r"\[\s*([\d.]+) s\] (\S+?)(?: -> \S+)?: (.*)$")
snr = re.compile(r"SNR ([+-][\d.]+) dB, offset ([+-][\d.]+) Hz")
for i, ln in enumerate(lines):
if "preamble found" in ln:
fails += 1
continue
h = head.search(ln)
if not h or i + 1 >= len(lines):
continue
s = snr.search(lines[i + 1])
if not s:
continue
ok = h.group(2) == src.upper() and h.group(3) == repr(msg)
wrong += not ok
rows.append(dict(t_s=float(h.group(1)), snr_db=float(s.group(1)),
offset_hz=float(s.group(2)), body_ok=ok,
flags=lines[i + 1].split(";", 1)[1].strip() if ";" in lines[i + 1] else ""))
n = len(rows)
print(f"\n{n} frames decoded of ~{expect:.0f} ({n / expect:.1%}); {fails} failed after sync; "
f"{wrong} with a wrong source or body" + (" <-- investigate" if wrong else ""))
load = [ln for ln in lines if "load" in ln]
if load:
print("last load report: " + load[-1].strip())
if n:
t = np.array([r["t_s"] for r in rows])
for lo_t in np.arange(0, seconds, 3600):
sel = [r for r in rows if lo_t <= r["t_s"] < lo_t + 3600]
if sel:
print(f" hour {int(lo_t // 3600) + 1}: {len(sel)} frames, SNR median "
f"{np.median([r['snr_db'] for r in sel]):+.1f} dB, offset "
f"{min(r['offset_hz'] for r in sel):+.1f} to {max(r['offset_hz'] for r in sel):+.1f} Hz")
print(f"results: {write_table(rows, name + '_soak')}")
if __name__ == "__main__":
main()