Files

368 lines
18 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""What did the phone miss that the V2X node heard? (and the other way round)
Compares the phone app's V2X log (SQLite, schema 3, ESP32-C5) with a pcap recorded at the same time by a
second receiver (the CiT/ESP32-C5 node's its5_*.pcap, linktype 105 or 127). Each side is read on its own:
* the pcap is unwrapped here, in Python, by a port of obu-firmware/main/gn_unwrap.c (802.11 -> LLC/SNAP ->
GeoNetworking, the TS 103 097 envelope, BTP-B). No C toolchain and no firmware code is involved;
* the log is read from its `messages` table (the UPER bytes exactly as the phone received them) and its
once-a-second `link_status` table (the board's own counters as the phone saw them).
The two clocks are aligned through the messages both sides received byte for byte (the node's clock is often
seconds since its boot). A node message counts as "received" when the phone logged the same message type with
identical payload bytes within --window seconds, matched one-to-one (a MAPEM repeats unchanged every second,
so a plain "any match" test would count one phone copy for several node copies).
py -3.11 obu-firmware/test/bench/compare_phone_vs_node.py LOG.db capture.pcap [--window 0.5] [--csv misses.csv]
Output: clock alignment, a table per message type and size, per sending station, the miss pattern over time
(bursts, the minute-by-minute share), what the board's counters say about where the misses happen (radio
queue drop, USB/BLE link, or never seen by this board's radio), and the messages only the phone heard.
Exit status 0 always: it reports, it does not judge. The numbers are comparable between runs, not absolute: the
node and the phone's board are different antennas in different places.
"""
import argparse
import bisect
import collections
import csv
import sqlite3
import statistics
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from itslib import PORT_NAMES, read_pcap, station_of, unwrap # noqa: E402
# ---------------------------------------------------------------- matching ------------------------------
def match_one_to_one(node_times, phone_times, window):
"""Greedy one-to-one match of two sorted time lists; returns the list of matched phone times (or None) per node time."""
used = [False] * len(phone_times)
out = []
for t in node_times:
k = bisect.bisect_left(phone_times, t - window)
best, bd = None, window
while k < len(phone_times) and phone_times[k] <= t + window:
if not used[k] and abs(phone_times[k] - t) <= bd:
best, bd = k, abs(phone_times[k] - t)
k += 1
if best is None:
out.append(None)
else:
used[best] = True
out.append(phone_times[best])
return out
def bursts(flags):
"""Run lengths of consecutive False (miss) in a list of booleans."""
runs, n = [], 0
for ok in flags:
if ok:
if n:
runs.append(n)
n = 0
else:
n += 1
if n:
runs.append(n)
return runs
def pct(a, b):
return "%5.1f%%" % (100.0 * a / b) if b else " - "
# ---------------------------------------------------------------- main ---------------------------------
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("log")
ap.add_argument("pcap")
ap.add_argument("--window", type=float, default=0.5, help="match tolerance, seconds (default 0.5)")
ap.add_argument("--csv", help="write every node message with its verdict to this CSV")
ap.add_argument("--min-station-msgs", type=int, default=20, help="stations with fewer messages are grouped")
a = ap.parse_args()
con = sqlite3.connect("file:%s?mode=ro" % a.log.replace("\\", "/"), uri=True)
meta = dict(con.execute("select key, value from meta").fetchall())
phone = [(ts / 1000.0, kind, bytes(pl), own, rssi) for ts, kind, pl, own, rssi in
con.execute("select ts_ms, msg_type, payload, is_own, rssi_dbm from messages where payload is not null order by ts_ms, id")]
if not phone:
raise SystemExit("the log holds no messages")
status = con.execute("select ts_ms, link_state, transport, uptime_ms, radio_submitted, radio_failed, radio_received, "
"radio_dropped, requests_accepted, requests_refused, link_crc_errors, link_malformed, app_rx_frames, "
"v2x_sending from link_status order by ts_ms").fetchall()
node = []
seen = skipped = 0
for t, f in read_pcap(a.pcap):
seen += 1
u = unwrap(f)
if u:
node.append((t, PORT_NAMES[u["port"]], u))
else:
skipped += 1
node.sort(key=lambda x: x[0])
# ---- the phone log on its own
print("=" * 100)
print("PHONE LOG %s" % a.log)
print(" hardware %s, phone %s, app %s, link %s" % (meta.get("hardware"), meta.get("phone"), meta.get("app_version"),
status[0][2] if status else "?"))
dur = phone[-1][0] - phone[0][0]
print(" %d messages over %.0f s (first %s, last %s)" % (len(phone), dur, fmt_t(phone[0][0]), fmt_t(phone[-1][0])))
kinds = collections.Counter(k for _, k, _, _, _ in phone)
print(" by type: " + ", ".join("%s %d" % kv for kv in sorted(kinds.items())))
own = sum(1 for p in phone if p[3])
if own:
print(" of which logged as the phone's own transmissions: %d (not counted below)" % own)
print("=" * 100)
print("NODE PCAP %s" % a.pcap)
print(" %d records, %d unwrapped to a CAM/DENM/MAPEM/SPATEM/VAM payload, %d not (beacons, other BTP ports, "
"unsigned-but-not-GN, truncated)" % (seen, len(node), skipped))
ncount = collections.Counter(k for _, k, _ in node)
print(" by type: " + ", ".join("%s %d" % kv for kv in sorted(ncount.items())))
signed = sum(1 for _, _, u in node if u["signed"])
print(" signed %d, unsigned %d, GeoBroadcast %d, truncated %d" % (signed, len(node) - signed,
sum(1 for _, _, u in node if u["area"]), sum(1 for _, _, u in node if u["truncated"])))
if not node:
raise SystemExit("nothing could be unwrapped from the pcap")
# ---- align the clocks through shared, once-only CAMs
first_phone = collections.defaultdict(list)
for t, k, pl, own, _ in phone:
first_phone[(k, pl)].append(t)
pairs = []
for t, k, u in node:
if k == "CAM":
times = first_phone.get((k, u["payload"]))
if times and len(times) == 1:
pairs.append((t, times[0] - t))
if len(pairs) < 20:
raise SystemExit("only %d CAMs seen by both: cannot align the two clocks (is it the same recording?)" % len(pairs))
off = statistics.median(o for _, o in pairs)
spread = statistics.pstdev(o for _, o in pairs)
pairs.sort()
q = max(1, len(pairs) // 4)
off_first = statistics.median(o for _, o in pairs[:q])
off_last = statistics.median(o for _, o in pairs[-q:])
print("=" * 100)
print("CLOCK ALIGNMENT: node clock + %.3f s = phone clock; spread %.0f ms over %d shared CAMs; first quarter %.3f s, last "
"quarter %.3f s (drift %.0f ms)" % (off, 1000 * spread, len(pairs), off_first, off_last, 1000 * (off_last - off_first)))
if abs(off_last - off_first) > 0.2:
print(" WARNING: the clocks drift by more than 200 ms; the match window may need widening (--window)")
lo, hi = phone[0][0], phone[-1][0]
node = [(t + off, k, u) for t, k, u in node]
inside = [(t, k, u) for t, k, u in node if lo <= t <= hi]
print(" the node heard %d messages inside the phone's recording window (%d outside it are ignored)"
% (len(inside), len(node) - len(inside)))
# ---- one-to-one matching, per (type, payload)
phone_by_key = collections.defaultdict(list)
for t, k, pl, own, _ in phone:
if not own:
phone_by_key[(k, pl)].append(t)
node_by_key = collections.defaultdict(list)
for idx, (t, k, u) in enumerate(inside):
node_by_key[(k, u["payload"])].append((t, idx))
verdict = [None] * len(inside)
matched_phone = collections.defaultdict(int)
for key, lst in node_by_key.items():
pts = sorted(phone_by_key.get(key, []))
res = match_one_to_one([t for t, _ in lst], pts, a.window)
for (t, idx), m in zip(lst, res):
verdict[idx] = m is not None
if m is not None:
matched_phone[key] += 1
# ---- table by type and size
print("=" * 100)
print("WHAT THE NODE HEARD vs WHAT THE PHONE LOGGED (one-to-one, +/-%.2f s, identical bytes)" % a.window)
table = collections.defaultdict(lambda: [0, 0])
for (t, k, u), ok in zip(inside, verdict):
r = table[(k, len(u["payload"]), u["signed"])]
r[0] += 1
r[1] += ok
print("%-7s %6s %-8s %8s %8s %8s %7s" % ("type", "bytes", "signed", "node", "phone", "missed", "share"))
tot = [0, 0]
for (k, size, sg), (n, got) in sorted(table.items(), key=lambda kv: (-kv[1][0], kv[0])):
if n >= 5 or len(table) < 40:
print("%-7s %6d %-8s %8d %8d %8d %s" % (k, size, "signed" if sg else "unsigned", n, got, n - got, pct(got, n)))
tot[0] += n
tot[1] += got
print("%-7s %6s %-8s %8d %8d %8d %s" % ("ALL", "", "", tot[0], tot[1], tot[0] - tot[1], pct(tot[1], tot[0])))
by_type = collections.defaultdict(lambda: [0, 0])
for (t, k, u), ok in zip(inside, verdict):
by_type[k][0] += 1
by_type[k][1] += ok
print("per type: " + "; ".join("%s %d/%d %s" % (k, g, n, pct(g, n).strip()) for k, (n, g) in sorted(by_type.items())))
# ---- per station
print("=" * 100)
print("PER SENDING STATION (ItsPduHeader.stationId)")
st = collections.defaultdict(lambda: [0, 0])
for (t, k, u), ok in zip(inside, verdict):
sid = station_of(u["payload"])
r = st[(sid, k)]
r[0] += 1
r[1] += ok
print("%-12s %-7s %8s %8s %7s first..last heard by the node" % ("station", "type", "node", "phone", "share"))
times_by = collections.defaultdict(list)
for (t, k, u) in inside:
times_by[(station_of(u["payload"]), k)].append(t)
for (sid, k), (n, got) in sorted(st.items(), key=lambda kv: -kv[1][0]):
if n < a.min_station_msgs:
continue
ts = times_by[(sid, k)]
print("%-12s %-7s %8d %8d %s +%.0f s .. +%.0f s" % (sid, k, n, got, pct(got, n), ts[0] - phone[0][0], ts[-1] - phone[0][0]))
# ---- the pattern of the misses
print("=" * 100)
print("WHEN THE MISSES HAPPEN")
flags = [ok for (_, _, _), ok in zip(inside, verdict)]
miss = [(t, k, u) for (t, k, u), ok in zip(inside, verdict) if not ok]
runs = bursts(flags)
if runs:
hist = collections.Counter(min(r, 10) for r in runs)
print(" miss runs in node order (all types): %d runs, longest %d; run length 1: %d, 2: %d, 3-4: %d, 5-9: %d, 10+: %d"
% (len(runs), max(runs), hist[1], hist[2], hist[3] + hist[4], sum(hist[i] for i in range(5, 10)), hist[10]))
for k in sorted(by_type):
series = [ok for (t, kk, u), ok in zip(inside, verdict) if kk == k]
r = bursts(series)
if r:
print(" %-7s %d misses in %d runs; longest run %d; single-message misses %d (%.0f %% of the misses)"
% (k, sum(r), len(r), max(r), sum(1 for x in r if x == 1), 100.0 * sum(1 for x in r if x == 1) / sum(r)))
# time gaps in the phone log vs gaps in the node, for the busiest station
print(" minute by minute (node messages / share the phone logged):")
t0 = phone[0][0]
buckets = collections.defaultdict(lambda: [0, 0])
for (t, k, u), ok in zip(inside, verdict):
b = int((t - t0) // 30)
buckets[b][0] += 1
buckets[b][1] += ok
line = []
for b in sorted(buckets):
n, g = buckets[b]
line.append("%3d s:%4d %s" % (b * 30, n, pct(g, n).strip()))
for i in range(0, len(line), 4):
print(" " + " ".join(line[i:i + 4]))
# phone-side silence: gaps with no message at all
ts_phone = [t for t, _, _, own, _ in phone if not own]
gaps = sorted(((b - a_, a_) for a_, b in zip(ts_phone, ts_phone[1:]) if b - a_ >= 2.0), reverse=True)
node_gap_cover = 0
if gaps:
print(" gaps of 2 s or more with no message in the phone log: %d (longest %.1f s at +%.0f s)"
% (len(gaps), gaps[0][0], gaps[0][1] - t0))
for g, at in gaps[:8]:
heard = sum(1 for t, _, _ in inside if at < t < at + g)
print(" +%.1f s for %.1f s: the node heard %d messages in that time" % (at - t0, g, heard))
# ---- where did they go? the board's own counters
print("=" * 100)
print("WHERE THE MISSES ARE LOST (from the phone's once-a-second link_status rows; the board's counters as the phone read them)")
if not status:
print(" the log has no link_status rows")
else:
s0, s1 = status[0], status[-1]
names = ("ts", "state", "transport", "uptime", "submitted", "failed", "received", "dropped", "accepted", "refused",
"crc", "malformed", "app_rx", "sending")
d = {n: s1[i] - s0[i] for i, n in enumerate(names) if n not in ("ts", "state", "transport", "sending")}
print(" over the run (%s link): board radio_received %+d, radio_dropped (its 16-frame queue overflowed) %+d,"
% (s0[2], d["received"], d["dropped"]))
print(" link CRC errors %d, malformed %d, app received %d link frames, board TX submitted %d / failed %d"
% (d["crc"], d["malformed"], d["app_rx"], d["submitted"], d["failed"]))
states = collections.Counter(s[1] for s in status)
print(" link state per second: " + ", ".join("%s %d" % kv for kv in sorted(states.items())))
resets = [i for i in range(1, len(status)) if status[i][3] < status[i - 1][3]]
print(" board restarts seen (uptime went backwards): %d" % len(resets))
# per-miss: was a counter moving in the second around it?
def row_at(t):
i = bisect.bisect_left([s[0] / 1000.0 for s in status], t)
return max(1, min(i, len(status) - 1))
ts_status = [s[0] / 1000.0 for s in status]
cause = collections.Counter()
for t, k, u in miss:
i = max(1, min(bisect.bisect_left(ts_status, t), len(status) - 1))
r0, r1 = status[i - 1], status[i]
if r1[1].lower() != "connected" or r0[1].lower() != "connected":
cause["the link was not connected around it"] += 1
elif r1[7] > r0[7]:
cause["the board's radio queue dropped frames in that second"] += 1
elif r1[10] > r0[10] or r1[11] > r0[11]:
cause["link CRC or malformed errors in that second"] += 1
elif r1[12] == r0[12]:
cause["the phone received no link frame at all in that second (link stall)"] += 1
else:
cause["no counter moved (not heard by this board's radio, or lost on the BLE/USB hop)"] += 1
if miss:
print(" the %d missed messages, by what the counters did in that second:" % len(miss))
for c, n in cause.most_common():
print(" %5d %s" % (n, c))
print(" If the last row dominates, the loss is invisible to the phone-side counters: either the phone's board never heard the")
print(" frame (different antenna than the node, a collision, the radio held out for a BLE connection event), or a V2X_RX")
print(" notification/fragment was dropped on the way (the firmware counts that only in a LOG line the phone cannot see over BLE).")
print(" note: 'radio_received' is not compared with the log; it counts frames the board's stack took, not every V2X_RX it forwarded.")
# ---- fragments: do the large ones lose more? (the point of the 2026-11-23 change)
big = [(k, ok) for (t, k, u), ok in zip(inside, verdict) if len(u["payload"]) > 494]
small = [(k, ok) for (t, k, u), ok in zip(inside, verdict) if len(u["payload"]) <= 494 and k in ("MAPEM", "SPATEM")]
print("=" * 100)
print("LARGE MESSAGES (above 494 bytes: sent as link fragments since 2026-11-23) vs small MAPEM/SPATEM")
for name, lst in (("MAPEM+SPATEM > 494 B", big), ("MAPEM+SPATEM <= 494 B", small)):
n = len(lst)
g = sum(1 for _, ok in lst if ok)
print(" %-24s node %5d phone %5d %s" % (name, n, g, pct(g, n).strip()))
# ---- what only the phone heard
print("=" * 100)
print("ONLY THE PHONE HEARD (in the log, not in the pcap within +/-%.2f s)" % a.window)
node_keys = collections.defaultdict(list)
for t, k, u in node:
node_keys[(k, u["payload"])].append(t)
extra = collections.Counter()
extra_total = collections.Counter()
for t, k, pl, own, rssi in phone:
if own:
continue
extra_total[k] += 1
ts = sorted(node_keys.get((k, pl), []))
if not match_near(ts, t, a.window):
extra[k] += 1
for k in sorted(extra_total):
print(" %-7s %5d of %5d phone messages not in the node's capture (%s)" % (k, extra[k], extra_total[k], pct(extra[k], extra_total[k]).strip()))
print(" (a node-side miss is a different antenna, a collision, or a node that was busy; read it against the node's own loss)")
# ---- phone's own transmissions seen by the node
if own:
print("=" * 100)
print("THE PHONE'S OWN TRANSMISSIONS (is_own rows) vs what the node heard")
own_ids = {station_of(pl) for t, k, pl, o, _ in phone if o}
heard = [(t, k) for t, k, u in node if station_of(u["payload"]) in own_ids]
print(" own station ids %s: %d logged by the phone as own, %d heard by the node" % (sorted(own_ids)[:4], own, len(heard)))
if a.csv:
with open(a.csv, "w", newline="") as fh:
w = csv.writer(fh)
w.writerow(["phone_clock_s", "offset_into_run_s", "type", "bytes", "signed", "station", "received_by_phone"])
for (t, k, u), ok in zip(inside, verdict):
w.writerow(["%.3f" % t, "%.3f" % (t - phone[0][0]), k, len(u["payload"]), int(u["signed"]), station_of(u["payload"]), int(ok)])
print("wrote %s" % a.csv)
def match_near(sorted_times, t, window):
i = bisect.bisect_left(sorted_times, t - window)
return i < len(sorted_times) and sorted_times[i] <= t + window
def fmt_t(t):
import datetime
return datetime.datetime.fromtimestamp(t).strftime("%H:%M:%S")
if __name__ == "__main__":
sys.exit(main())