"""Stage 2: phases that run for minutes to hours - transmit soak, capture toggling, reconfiguration, idle listening, resets - each checked against the station's own counters and against what its radio really emitted. How a frame is proven to have left the radio on a single board: RAW_CAPTURE mode 0x05 (on + own transmissions) makes the station copy every frame it submits to the radio back over the link as a RAW_FRAME. The test unwraps that copy with itslib.unwrap (a port of gn_unwrap.c written independently of the firmware build) and compares the ITS payload with what it sent, octet for octet (a CRC-32 and the size are inside the payload). This covers the TX path (request -> queue -> signing -> GeoNetworking -> 802.11) and the fragmentation of large RAW_FRAME messages over USB. It does not prove that another receiver can hear the frame. Everything that goes on air carries a payload no ITS receiver accepts as a message: ItsPduHeader messageID 0xF1 is not an assigned messageID (see linklib.test_payload). """ import collections import os import struct import time import itslib import linklib as ll from bench_common import FAIL, INFO, PASS, SKIP, WARN, median DEFAULT_SIZES = (24, 43, 100, 300, 494, 495, 700, 1000, 1200, 1400, 1480) # 494/495: the V2X_RX single/fragment edge SIGNED_SIZES = (24, 43, 100, 300, 494, 495, 700, 1000, 1200) # a signed payload of 1398 is queued but never sent (see conformance); the limit lies in 1201-1397 DEMO_CHAIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "app", "src", "main", "assets", "demo-chain.vcr") # ---------------------------------------------------------------- helpers ------------------------------- def percentile(xs, p): xs = sorted(xs) return xs[min(len(xs) - 1, int(p / 100.0 * len(xs)))] if xs else None def checkpoint(ctx, label): """Heap figures at a quiet moment, for the leak analysis at the end of the run.""" s = ctx.sample_status(label) if s: ctx.heap.append((time.time(), label, s["heap_free"], s["heap_min_free"], s["heap_largest"], s["uptime_ms"])) return s def configure_for(ctx, S, secured, power, radio=2, mac=None): L = ctx.link mac = mac or ctx.next_mac() if radio == 2: body = ll.configure_body(secured=secured, power=power, mac=mac) else: body = ll.configure_body(secured=secured, power=power, mac=mac, radio=radio) r = L.request(ll.STATION_CONFIGURE, body, 5.0) if not (r and r.code == ll.ACCEPTED): ctx.res.add(S, "STATION_CONFIGURE", FAIL, "reply %s" % (r.name if r else "none")) return None if secured and len(r.detail) == 18: # with security off the station reports no credentials either way ctx.credentials = r.detail[16] == 1 and r.detail[17] > 0 return mac def provision_demo(ctx): """CREDENTIALS_PROVISION of the app's throwaway demo chain (what the app does on its first connect).""" S, L = "provision", ctx.link ctx.phase = S path = os.path.normpath(DEMO_CHAIN) if not os.path.exists(path): ctx.res.add(S, "demo chain", SKIP, "%s not found" % path) return False if configure_for(ctx, S, True, 5) is None: return False bundle = open(path, "rb").read() off = 0 while off < len(bundle): seg = bundle[off:off + 240] last = off + len(seg) == len(bundle) r = L.request(ll.CREDENTIALS_PROVISION, struct.pack("= 3 else "no report") ctx.credentials = len(r.detail) >= 3 and r.detail[2] > 0 off += len(seg) ctx.res.ok(S, "the station reports a ticket after provisioning", ctx.credentials) return ctx.credentials def drain_rx(ctx): """Move every V2X_RX the link collected into ctx.rx_stats; returns how many arrived and how many were our own test frames.""" L = ctx.link n = own = 0 while L.v2x_rx: _, body = L.v2x_rx.popleft() n += 1 if len(body) < 14: ctx.res.add("rx", "V2X_RX shorter than its 14-octet prefix", FAIL, "%d octets" % len(body)) continue port, rssi, flags = struct.unpack("2300" # ---------------------------------------------------------------- transmit soak ------------------------- WEDGE_REFUSALS = 40 # this many resource_limit CONFIRMs in a row end a transmit phase as "TX wedged" def report_wedge(ctx, S, s0, s1, mac, secured, power, replies): """The radio stopped completing frames and the station refuses everything: record the counters, then try a plain STATION_CONFIGURE with the same settings to see whether that is enough to bring transmission back.""" L, R = ctx.link, ctx.res d = {k: s1[k] - s0[k] for k in ("requests_accepted", "requests_refused", "radio_submitted", "radio_failed")} if s0 and s1 else {} R.add(S, "transmit path wedged: the station refuses every request (resource_limit)", FAIL, "after %d requests %s; STATUS change over the phase %s; heap_free %s; uptime %s ms" % (sum(replies.values()), dict(replies), d, s1["heap_free"] if s1 else "?", s1["uptime_ms"] if s1 else "?")) if configure_for(ctx, S, secured, power, mac=mac) is None: return L.poti() time.sleep(0.5) ctx.tx_seq += 1 r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(ll.test_payload(ctx.run_id, ctx.tx_seq, 100), secured=secured, generated_at_ms=ll.timestamp_its() if secured else None), 2.0) s2 = checkpoint(ctx, S) R.add(S, "a repeated STATION_CONFIGURE clears the wedge", INFO if r and r.code == ll.ACCEPTED else FAIL, "next request: %s; radio_submitted %s -> %s, radio_failed %s -> %s" % (r.name if r else "no reply", s1["radio_submitted"] if s1 else "?", s2["radio_submitted"] if s2 else "?", s1["radio_failed"] if s1 else "?", s2["radio_failed"] if s2 else "?")) def tx_phase(ctx, label, seconds, secured, rate_hz=4.0, sizes=DEFAULT_SIZES, power=5, capture_mode=0x05): """Configure, transmit test frames at `rate_hz` for `seconds`, then reconcile requests, counters and captured frames.""" S, L, R = label, ctx.link, ctx.res ctx.phase = label if not ctx.tx_enabled: R.add(S, "transmit phase", SKIP, "--no-tx") return if secured and not ctx.credentials: R.add(S, "signed transmit phase", SKIP, "no ticket on this board (use --provision-demo)") return mac = configure_for(ctx, S, secured, power) if mac is None: return R.ok(S, "RAW_CAPTURE own-TX capture accepted", (L.raw_capture(capture_mode) or ll.Reply(255, b"", 0)).code == 0) L.raw_frames.clear() L.v2x_rx.clear() L.poti() time.sleep(0.2) s0 = checkpoint(ctx, label) crc0 = L.counts["frames_bad_crc"] sent = {} # seq -> (size, t_sent, reply code) replies = collections.Counter() latencies = [] t0 = time.time() end = min(t0 + seconds, ctx.deadline or 1e18) nxt, next_poti, next_status = t0, t0 + 1, t0 + 5 i = 0 refused_run, wedged = 0, False while time.time() < end: now = time.time() if now >= next_poti: L.poti() next_poti += 1 if now >= next_status: ctx.sample_status(label) next_status += 5 if now >= nxt: size = sizes[i % len(sizes)] ctx.tx_seq += 1 seq = ctx.tx_seq payload = ll.test_payload(ctx.run_id, seq, size) body = ll.btp_body(payload, secured=secured, generated_at_ms=ll.timestamp_its() if secured else None) r = L.request(ll.BTP_DATA_REQUEST, body, 2.0) replies[r.name if r else "no reply"] += 1 if r: latencies.append(r.latency * 1000) sent[seq] = (size, now, r.code if r else None) # 2026-11-25 overnight run: after ~17 frames the radio stopped completing them and every later request # got resource_limit for the rest of the phase (2383 of 2400, four times in eleven cycles). Stop early # instead of spending the phase on it, and see below whether a STATION_CONFIGURE clears it. refused_run = refused_run + 1 if r and r.name == "resource_limit" else 0 if refused_run >= WEDGE_REFUSALS: wedged = True break nxt += 1.0 / rate_hz if nxt < now - 1: # fell far behind (a stalled port): do not burst to catch up nxt = now i += 1 else: time.sleep(0.005) time.sleep(2.5) # let the queue drain and the last frames come back s1 = checkpoint(ctx, label) n_rx, n_own_heard = drain_rx(ctx) if wedged: report_wedge(ctx, S, s0, s1, mac, secured, power, replies) n = len(sent) accepted = [q for q, v in sent.items() if v[2] == ll.ACCEPTED] R.metric(S, "requests", n) R.metric(S, "reply_codes", dict(replies)) if latencies: R.metric(S, "confirm_latency_ms_p50_p99_max", [round(median(latencies), 1), round(percentile(latencies, 99), 1), round(max(latencies), 1)]) R.ok(S, "every request got a CONFIRM", replies.get("no reply", 0) == 0, "%d of %d without" % (replies.get("no reply", 0), n)) refused = n - len(accepted) - replies.get("no reply", 0) R.ok(S, "requests accepted (queue not full, no refusal)", refused <= 0.02 * n, "%d refused: %s" % (refused, dict(replies)), FAIL if refused > 0.1 * n else WARN) if s0 and s1: R.ok(S, "the station did not reset during the phase", s1["uptime_ms"] > s0["uptime_ms"], "uptime %d -> %d" % (s0["uptime_ms"], s1["uptime_ms"])) for name, want, level in (("requests_accepted", len(accepted), WARN), ): d = s1[name] - s0[name] R.ok(S, "STATUS %s counts the accepted requests" % name, abs(d - want) <= max(2, 0.01 * n), "counter +%d, CONFIRMs accepted %d" % (d, want), level) R.ok(S, "radio_failed stays 0", s1["radio_failed"] == s0["radio_failed"], "+%d" % (s1["radio_failed"] - s0["radio_failed"]), WARN) R.ok(S, "link_crc_errors stays 0 (host sends valid frames only)", s1["link_crc_errors"] == s0["link_crc_errors"], "+%d" % (s1["link_crc_errors"] - s0["link_crc_errors"]), WARN) if secured: R.ok(S, "sign_failed stays 0", s1["sign_failed"] == s0["sign_failed"], "+%d" % (s1["sign_failed"] - s0["sign_failed"])) R.metric(S, "signed_messages", s1["signed_messages"] - s0["signed_messages"]) R.metric(S, "radio_submitted", s1["radio_submitted"] - s0["radio_submitted"]) R.metric(S, "radio_dropped_rx_queue", s1["radio_dropped"] - s0["radio_dropped"]) # What the radio emitted captured = collections.defaultdict(list) bad = 0 foreign_own = 0 wrong_mac = [] for _, fl, _, frame in L.raw_frames: if not fl & 1: continue u = itslib.unwrap(frame) info = ll.check_test_payload(u["payload"]) if u else None if not info: foreign_own += 1 continue run, seq, size, ok = info if run != ctx.run_id: continue if not ok: bad += 1 R.add(S, "captured payload fails its own CRC/size check", FAIL, "seq %d, size field %d, %d octets captured" % (seq, size, len(u["payload"]))) continue if u["signed"] != secured: R.add(S, "frame signed flag differs from the request's profile", FAIL, "seq %d signed=%s" % (seq, u["signed"])) if u["src"] != mac.hex(":"): wrong_mac.append((seq, u["src"])) captured[seq].append(u) R.ok(S, "every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form)", not wrong_mac, "%d of %d frames differ, e.g. %s (wanted %s)" % (len(wrong_mac), sum(len(v) for v in captured.values()), sorted({m for _, m in wrong_mac})[:3], mac.hex(":"))) R.ok(S, "no captured own-TX frame was corrupted", bad == 0 and foreign_own == 0, "%d corrupt, %d own frames not ours" % (bad, foreign_own)) dup = sum(1 for v in captured.values() if len(v) > 1) R.ok(S, "no request was transmitted twice", dup == 0, "%d duplicated" % dup, WARN) by_size = collections.defaultdict(lambda: [0, 0]) for q in accepted: by_size[sent[q][0]][0] += 1 by_size[sent[q][0]][1] += q in captured seen = sum(v[1] for v in by_size.values()) ratio = seen / len(accepted) if accepted else 1.0 R.metric(S, "own_tx_captured_by_size", {k: "%d/%d" % (v[1], v[0]) for k, v in sorted(by_size.items())}) lost = ", ".join("%d B: %d/%d" % (k, v[1], v[0]) for k, v in sorted(by_size.items()) if v[1] < v[0]) level = PASS if ratio >= 0.98 else WARN if ratio >= 0.90 else FAIL R.add(S, "accepted requests seen leaving the radio (own-TX RAW_FRAME copy)", level, "%d of %d (%.1f%%)%s" % (seen, len(accepted), 100 * ratio, "; short: " + lost if lost else "")) if n_own_heard: R.add(S, "own test frames also heard back by the radio receive path as V2X_RX", INFO, "%d" % n_own_heard) R.metric(S, "v2x_rx_during_phase", n_rx) frag_err = {k: v for k, v in L.counts.items() if k.startswith("frag_") and v} if frag_err: R.add(S, "host-side fragment accounting", INFO, str(frag_err)) L.raw_capture(0) # ---------------------------------------------------------------- capture toggling ----------------------- def raw_toggle_phase(ctx, label, seconds, power=5): """RAW_CAPTURE on/off/own-TX combinations while transmitting at 2 Hz: the copies must follow the mode exactly.""" S, L, R = label, ctx.link, ctx.res ctx.phase = label if not ctx.tx_enabled: R.add(S, "capture toggling", SKIP, "--no-tx") return if configure_for(ctx, S, False, power) is None: return L.poti() # mode -> (own frames expected, raw frames of any kind expected) modes = [(0x00, False), (0x05, True), (0x01, False), (0x07, True), (0x03, False), (0x00, False), (0x05, True)] per = max(6.0, seconds / len(modes)) for mode, want_own in modes: if ctx.time_left() < per + 5: break r = L.raw_capture(mode) R.ok(S, "RAW_CAPTURE 0x%02x accepted" % mode, r is not None and r.code == 0, r.name if r else "no reply") time.sleep(0.3) L.raw_frames.clear() end = time.time() + per n_req = 0 next_poti = time.time() + 1 while time.time() < end: if time.time() >= next_poti: L.poti() next_poti += 1 ctx.tx_seq += 1 r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(ll.test_payload(ctx.run_id, ctx.tx_seq, 100 + (ctx.tx_seq % 5) * 250)), 2.0) n_req += 1 if r and r.code == 0 else 0 time.sleep(0.5) time.sleep(1.0) own = sum(1 for _, fl, _, _ in L.raw_frames if fl & 1) if want_own: R.ok(S, "mode 0x%02x copies the station's own frames" % mode, own >= 0.9 * n_req, "%d copies of %d requests" % (own, n_req), WARN) else: R.ok(S, "mode 0x%02x copies none of the station's own frames" % mode, own == 0, "%d copies" % own) L.raw_capture(0) checkpoint(ctx, label) # ---------------------------------------------------------------- reconfigure churn --------------------- def reconfigure_phase(ctx, label, seconds, power=5): """STATION_CONFIGURE over and over (new MAC, security on/off, radio tx+rx / rx only), transmitting in between.""" S, L, R = label, ctx.link, ctx.res ctx.phase = label end = min(time.time() + seconds, ctx.deadline or 1e18) n = fails = 0 s0 = checkpoint(ctx, label) while time.time() < end: secured = ctx.credentials and n % 3 == 0 radio = 1 if n % 5 == 4 else 2 t = time.time() mac = configure_for(ctx, S, secured, power, radio=radio) if mac is None: fails += 1 else: R.metric(S, "last_configure_seconds", round(time.time() - t, 2)) L.poti() if ctx.tx_enabled and radio == 2: L.raw_capture(0x05) L.raw_frames.clear() ctx.tx_seq += 1 r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(ll.test_payload(ctx.run_id, ctx.tx_seq, 100), secured=secured, generated_at_ms=ll.timestamp_its() if secured else None), 2.0) time.sleep(1.2) frames = [itslib.unwrap(f) for _, fl, _, f in L.raw_frames if fl & 1] frames = [f for f in frames if f and ll.check_test_payload(f["payload"])] ok = r and r.code == 0 and len(frames) == 1 and frames[0]["src"] == mac.hex(":") and frames[0]["signed"] == bool(secured) R.ok(S, "a frame sent right after a reconfigure leaves with the new MAC and security", ok, "reply %s, %d frames, src %s want %s" % (r.name if r else "none", len(frames), frames[0]["src"] if frames else "-", mac.hex(":"))) else: time.sleep(1.2) drain_rx(ctx) n += 1 s1 = checkpoint(ctx, label) R.metric(S, "configures", n) R.ok(S, "every STATION_CONFIGURE was accepted", fails == 0, "%d of %d refused" % (fails, n)) if s0 and s1: R.ok(S, "the station did not reset while being reconfigured", s1["uptime_ms"] > s0["uptime_ms"]) L.raw_capture(0) # ---------------------------------------------------------------- idle listening ------------------------ def idle_listen_phase(ctx, label, seconds): """Radio receive-only, nothing sent but STATUS_REQUEST at 1 Hz: stability, and whatever is on the air is counted.""" S, L, R = label, ctx.link, ctx.res ctx.phase = label if configure_for(ctx, S, False, 5, radio=1) is None: return L.raw_capture(0) L.poti() L.v2x_rx.clear() s0 = checkpoint(ctx, label) end = min(time.time() + seconds, ctx.deadline or 1e18) next_poti = time.time() + 1 miss = 0 while time.time() < end: if time.time() >= next_poti: L.poti() next_poti += 1 s = ctx.sample_status(label) miss += s is None time.sleep(1.0) s1 = checkpoint(ctx, label) n_rx, own = drain_rx(ctx) R.ok(S, "STATUS answered once a second throughout", miss == 0, "%d missed" % miss) if s0 and s1: R.ok(S, "the station did not reset while idle", s1["uptime_ms"] > s0["uptime_ms"]) R.metric(S, "radio_received", s1["radio_received"] - s0["radio_received"]) R.ok(S, "receive queue never overflowed (radio_dropped)", s1["radio_dropped"] == s0["radio_dropped"], "+%d" % (s1["radio_dropped"] - s0["radio_dropped"]), WARN) R.add(S, "V2X_RX heard on the air while listening", INFO, "%d messages in %.0f s" % (n_rx, seconds)) large = sum(v for (p, sg, b), v in ctx.rx_stats.items() if b in ("<=1000", "<=1500", "<=2300")) if n_rx: R.add(S, "V2X_RX by type/signed/size so far", INFO, "; ".join("%s%s %s x%d" % (p, " signed" if sg else "", b, v) for (p, sg, b), v in sorted(ctx.rx_stats.items(), key=str))) R.add(S, "large V2X_RX (above 494 B) reassembled intact by the host", INFO if large else SKIP, "%d; fragments completed %d, errors %d" % (large, L.counts["frag_complete"], L.counts["frag_errors"])) # ---------------------------------------------------------------- resets -------------------------------- def reset_cycles(ctx, label, cycles=5): """Close and reopen the port (the board resets): it must boot, answer, configure and transmit every time.""" S, L, R = label, ctx.link, ctx.res ctx.phase = label for k in range(cycles): L.reboot(boot_wait=3.0) s = L.wait_status(20) if not R.ok(S, "board answers after a reset", s is not None, "cycle %d" % k): continue R.ok(S, "board comes back unconfigured", s["configured"] == 0) R.ok(S, "the reset was a fresh boot (uptime small)", s["uptime_ms"] < 30000, "%d ms" % s["uptime_ms"]) R.ok(S, "ROM boot banner seen on reopen", L.boots >= 1, "banners %d" % L.boots, WARN) mac = configure_for(ctx, S, False, 5) if mac and ctx.tx_enabled: L.raw_capture(0x05) L.poti() L.raw_frames.clear() ctx.tx_seq += 1 payload = ll.test_payload(ctx.run_id, ctx.tx_seq, 100) r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(payload), 2.0) time.sleep(1.2) got = [itslib.unwrap(f) for _, fl, _, f in L.raw_frames if fl & 1] R.ok(S, "first frame after a reset is transmitted", bool(r and r.code == 0) and any(g and g["payload"] == payload for g in got), "reply %s, %d own frames" % (r.name if r else "none", len(got))) checkpoint(ctx, label)