Run the overnight bench test on the spare board, and document it

Track the bench scripts (run_overnight.py and its stages, the link and ITS
client libraries, the phone-vs-node comparison) with the first reports.

Changes for the spare XIAO (no cell):
- run_overnight.py picks the single Espressif board by default and refuses to
  test a build that is not this checkout's HEAD.
- The unsigned soak stops as "transmit path wedged" after 40 resource_limit
  refusals in a row and tries whether a repeated STATION_CONFIGURE clears it.
- "Refused requests put nothing on the radio" counts only own transmissions;
  frames heard from other stations are copied by RAW_CAPTURE too.
- start_overnight.ps1: optional build and flash, host C tests in the
  background, Windows kept awake. setup_workstation.ps1 checks and installs
  git, Python 3.11, pyserial, asn1tools, MSYS2 gcc and make, ESP-IDF 6.0.2.
- obu-firmware/docs/overnight-bench-test.tex (and PDF) describe the test, the
  workstation set-up and the findings of the 2026-11-25 runs.
This commit is contained in:
Ashin Walpola
2026-11-25 14:43:34 +01:00
parent ce18a393ea
commit 462e1898ff
20 changed files with 5938 additions and 0 deletions
+5
View File
@@ -88,3 +88,8 @@ obu-firmware/docs/*.synctex.gz
/.vscode/
obu-firmware/docs/*.synctex*
# Overnight bench test: LaTeX build output (the PDF is committed) and raw run folders (only the reports are committed)
obu-firmware/docs/*.fdb_latexmk
obu-firmware/docs/*.fls
obu-firmware/test/results/*/
Binary file not shown.
+102
View File
@@ -0,0 +1,102 @@
\documentclass[10pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
\usepackage[a4paper,left=18mm,right=18mm,top=18mm,bottom=18mm,headheight=13pt]{geometry}
\usepackage{xcolor}
\usepackage{array,longtable,booktabs}
\usepackage{fancyhdr,lastpage,needspace}
\usepackage[hidelinks]{hyperref}
\definecolor{ink}{HTML}{193447}
\setlength{\parindent}{0pt}
\setlength{\parskip}{4pt}
\setlength{\tabcolsep}{1.5mm}
\renewcommand{\arraystretch}{1.12}
\setlength{\emergencystretch}{3em}
\newcolumntype{P}[1]{>{\raggedright\arraybackslash}p{#1}}
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[L]{\footnotesize Overnight bench test of the micrOBU firmware}
\fancyfoot[R]{\footnotesize\thepage\ / \pageref{LastPage}}
\renewcommand{\headrulewidth}{0pt}
\hypersetup{pdftitle={Overnight bench test of the micrOBU firmware}}
\newcommand{\cmd}[1]{\texttt{\small #1}}
\begin{document}
{\Large\bfseries\color{ink} Overnight bench test of the micrOBU firmware}\par
\smallskip
Status: 2026-11-25. Scripts: \cmd{obu-firmware/test/bench}. Companion documents: \cmd{obu-firmware/test/bench/README.md}, \cmd{obu-firmware/test/host/README.md}, \cmd{obu-firmware/FLASHING.md}.\par
\section*{1\quad Purpose}
The test checks the integrity and function of \cmd{obu-firmware} on a real board over many hours, without a phone. A PC plays the phone over the USB station link, drives every kind of request, resets and reconfigures the board, listens to the air, and watches the board's own counters and heap. A second, board-free part runs the PC-side C tests and a long fuzz of the receive parser.
\section*{2\quad Boards}
\begin{longtable}{@{}P{22mm}P{32mm}P{108mm}@{}}
\toprule\textbf{Port (lab)} & \textbf{Board} & \textbf{Role}\\\midrule\endhead
COM10 & XIAO ESP32-C5 with cell & production OBU. Never used for this test.\\
\textbf{COM6} & XIAO ESP32-C5, no cell & \textbf{spare board: the board under test}, also taken home.\\
COM4 & ESP32-C5 & V2X node (a second station on the air).\\
COM8 & CH343 board & simulated car (CAM beacon).\\\bottomrule
\end{longtable}
The spare's single USB-C port is the chip's native USB Serial/JTAG (VID 303A, PID 1001). \textbf{Opening the port resets the board}, so nothing else may hold it (phone app, \cmd{station\_status\_watch.py}, serial monitor). A board without a cell still reports about 4000\,mV in \cmd{battery\_mv} (the USB charger node), so the battery value cannot tell the spare from the production board: plug in only the spare. The run writes the demo ticket to the board's NVS.
\section*{3\quad What a run does}
Every run starts and ends with the conformance stage, so drift shows as a different result. In between, cycles of about 45 minutes repeat until the time is up.
\begin{longtable}{@{}P{30mm}P{132mm}@{}}
\toprule\textbf{Stage} & \textbf{What it checks}\\\midrule\endhead
conformance & about 100 checks of the link protocol against the specification and the firmware source: opcodes, malformed lengths, fragment reassembly (1536-octet requests, gaps, 2\,s timeout, 8 pending), CRC and resynchronisation, configure and POTI, BTP requests, stale requests, counter wrap.\\
soak-unsigned & BTP requests at 4\,Hz, payload 24 to 1480 octets in turn (494 and 495 are the V2X\_RX edge). Every accepted request must leave the radio byte for byte, with the MAC the phone named. 40 refusals (\cmd{resource\_limit}) in a row end the phase as ``transmit path wedged'', and a repeated configure is tried.\\
soak-signed & the same at 3\,Hz up to 1200 octets, signed with the demo chain; \cmd{sign\_failed} must stay 0.\\
raw-toggle & \cmd{RAW\_CAPTURE} modes 0x00, 0x01, 0x03, 0x05, 0x07 in turn: copies of the station's own frames must appear exactly in the modes with the own-TX bit.\\
reconfigure & \cmd{STATION\_CONFIGURE} every second or two with a new MAC, security on or off, radio TX+RX or RX only; the next frame must carry the new MAC and security.\\
fuzz & the board is reset, then seeded random frames are sent while it is unconfigured, so nothing reaches the radio. Heap afterwards must be within 8\,KB.\\
resets & the port is reopened five times; each time the board must boot, come back unconfigured, configure and transmit.\\
idle-listen & radio receive-only, STATUS once a second; counts what else is on the air and checks the receive queue never overflows.\\\bottomrule
\end{longtable}
\textbf{How a transmitted frame is proven.} One board has no second receiver, so the test uses \cmd{RAW\_CAPTURE} mode 0x05: every frame the station submits to the radio is copied back over the link. The copy is unwrapped by a Python port of \cmd{gn\_unwrap.c} written separately from the firmware, and its ITS payload is compared with what was sent. The payload carries its own size and CRC-32. This does not prove that another station can hear the frame.
\textbf{On the air.} Transmit phases send at most 4 frames per second at 5\,dBm on channel 180. The payload is a made-up ItsPduHeader with messageID \cmd{0xF1}, which is not an assigned ETSI message, so receivers refuse it. MACs are locally administered, \cmd{02:b3:0a:ce:xx:xx}. \cmd{--no-tx} keeps the radio silent.
\textbf{PC-side tests} (\cmd{run\_host\_tests\_overnight.ps1}, no board): \cmd{make check} of \cmd{test/host} (chain test, replay of recorded captures, fuzz, battery policy, 40 firmware unit tests, fragments), then the \cmd{gn\_unwrap} fuzzer with new seeds until the time is up. A \cmd{CRASH} line or a non-zero exit is a failure.
\section*{4\quad Running it}
Close everything that holds the port, run \cmd{git pull}, then from the repository root:
\begin{center}\small\texttt{powershell -ExecutionPolicy Bypass -File obu-firmware\textbackslash test\textbackslash bench\textbackslash start\_overnight.ps1 -Flash -Hours 8}\end{center}
\begin{longtable}{@{}P{34mm}P{128mm}@{}}
\toprule\textbf{Option} & \textbf{Effect}\\\midrule\endhead
\cmd{-Flash} & builds this checkout with ESP-IDF 6.0.2 and writes it to the board first (first build about 20 minutes: components are downloaded).\\
\cmd{-Quick} & about 8 minutes on the board, no host fuzz: does it all work?\\
\cmd{-Port COMx} & names the board; the default finds the one Espressif USB board plugged in and refuses if there are several.\\
\cmd{-NoTx} & the radio stays silent: protocol, fuzz, resets and idle only.\\
\cmd{-NoHostTests} & skips the PC-side C tests.\\\bottomrule
\end{longtable}
The script keeps Windows awake while it runs. \cmd{run\_overnight.py} refuses a board whose firmware is not this checkout's HEAD (\cmd{--allow-stale-firmware} overrides), because the results would then describe another build. Exit status: 0 if no check failed, 1 otherwise, 2 if the board does not speak the station link.
\section*{5\quad Setting up the workstation}
\cmd{setup\_workstation.ps1 -CheckOnly} reports what is missing; without \cmd{-CheckOnly} it installs it (about 3\,GB, 20 to 40 minutes, internet needed). It can be run again after a failure.
\begin{longtable}{@{}P{44mm}P{62mm}P{56mm}@{}}
\toprule\textbf{Needed} & \textbf{Why} & \textbf{Installed as}\\\midrule\endhead
Git, \cmd{core.longpaths true} & \cmd{git pull}; ESP-IDF paths exceed 260 characters & winget \cmd{Git.Git}\\
Python 3.11 (\cmd{py -3.11}) & board tests, \cmd{check\_replay.py} & winget \cmd{Python.Python.3.11}\\
\cmd{pyserial} & the station link & \cmd{pip install --user}\\
\cmd{asn1tools} & host replay check only & \cmd{pip install --user}\\
MSYS2 UCRT64 \cmd{gcc}, \cmd{make} & PC-side C tests & winget \cmd{MSYS2.MSYS2}, then pacman\\
\textbf{ESP-IDF 6.0.2}, esp32c5, in \cmd{C:\textbackslash Espressif} & build and flash; exactly this version, because \cmd{components/microbu\_v2x} pins the radio driver ABI to it & \cmd{git clone --branch v6.0.2 --recursive}, then \cmd{install.ps1 esp32c5}\\\bottomrule
\end{longtable}
Nothing to install for the board itself: the native USB port uses the Windows built-in driver. Internet is needed on the first build (\cmd{espressif/esp-boost}, about 125\,MB, into \cmd{managed\_components/}). \cmd{setup\_workstation.ps1 -PreventSleep} turns off sleep, hibernate, display-off and USB selective suspend on mains power; a suspended USB port drops the board. Pause Windows Update and use mains power.
Not in git, so absent on a fresh checkout: \cmd{its-g5-receiver-firmware/recordings/*.pcap} (the host replay test then skips itself), \cmd{vanetza/} (\cmd{check\_replay.py} then does not decode the 1609.2 envelopes independently) and \cmd{firmware-backups/}.
\textbf{Flashing trouble.} If the flash reports ``No serial data received'': unplug the board, hold BOOT, plug in, release, flash again, then unplug and replug without BOOT. If the flasher stub does not start, use the \cmd{--no-stub} recipe in \cmd{FLASHING.md}.
\section*{6\quad Reading the result}
Results go to \cmd{obu-firmware/test/results/overnight-<time>/}: \cmd{report.txt} (read this), \cmd{results.json}, \cmd{status.csv} (STATUS every few seconds), \cmd{device.log}, \cmd{boot.log} (ROM text and panics), \cmd{run.log}. \textbf{FAIL} contradicts the specification, the source or what the radio did. \textbf{WARN} is a disagreeing counter, a heap trend or a version mismatch. \textbf{INFO} is something the source leaves open, with the observed value. A fuzz failure prints its seed; replay it with \cmd{--fuzz-seed N}. Heap leaks are judged per phase over readings without a reset in between (warning below $-2$\,KB per hour, failure below $-20$\,KB per hour), and the lowest heap ever seen must stay above 16\,KB.
\section*{7\quad Findings so far}
\textbf{Overnight run 2026-11-25 (6.3\,h, home workstation, stale build).} The board ran \cmd{1c3a66e-dirty} of 10 November, which predates the pseudonym MAC commit \cmd{3770754}, because the workstation had no ESP-IDF to flash a current build. 1278 checks passed and 802 failed. About 790 failures are the frame source MAC not being the one named in \cmd{STATION\_CONFIGURE}, explained by the stale build. Two things stand out: in 4 of 11 cycles the unsigned soak accepted about 17 requests and then refused all 2383 others with \cmd{resource\_limit} while \cmd{radio\_failed} rose by the same number (heap stayed healthy; a later configure cleared it), and one of 50 resets ended in a boot panic (illegal instruction in \cmd{app\_main}, 0.39\,s after boot). The heap showed no leak (lowest 49\,736 octets). Nothing else was heard on the air.
\textbf{Quick run 2026-11-25 on the spare, current build \cmd{ce18a39}.} 217 passed, 0 failed, 1 warning (one frame from the board with a bad CRC). The MAC failures are gone. One test bug was fixed on the way: the check ``refused requests put nothing on the radio'' counted frames heard from other stations; it now counts only the station's own transmissions. The wedge and the boot panic were not reproduced in 8 minutes and need the full overnight run.
\section*{Revision history}
Revision 1, 2026-11-25: first version, written with the move of the overnight test to the spare board.
\end{document}
+135
View File
@@ -0,0 +1,135 @@
# Bench tests for obu-firmware
Scripts for testing the firmware on a real board (one micrOBU on a USB port) and for comparing a phone log with a
second receiver's capture. The board tests are Python 3.11 with `pyserial` only (`asn1tools` is for the host replay check
in [`../host`](../host/README.md), where the PC-side C tests live).
**Which board:** the overnight run is for the **spare** XIAO ESP32-C5 (no cell), never the production OBU. It resets the board
every time it opens the port, reconfigures it for hours and writes the demo ticket to its NVS. On the lab bench (2026-11-25):
COM10 production OBU with the cell, **COM6 spare**, COM4 V2X node, COM8 simulated car (CH343). Plug only the spare into the
home workstation; its port number there will differ, and `auto` finds it. A board without a cell still reports
`battery_mv` of about 4000 (the USB charger node), so the battery reading cannot tell the boards apart.
| Script | What it does |
|---|---|
| `start_overnight.ps1` | **the one command**: optionally builds and flashes this checkout (`-Flash`), starts the host C tests in the background, runs the board tests, keeps Windows awake |
| `setup_workstation.ps1` | checks, and installs what is missing, for a PC that has to do all of the above (see "Setting up a workstation") |
| `run_overnight.py` | the overnight run: schedules the stages below, watches for resets and heap leaks, writes the report. Refuses a board whose firmware is not this checkout's HEAD (`--allow-stale-firmware`) |
| `bench_conformance.py` | stage 1: the link protocol against the spec and the firmware source, ~100 checks |
| `bench_soak.py` | stage 2: transmit soak (unsigned, signed), capture-mode toggling, reconfiguration, idle listening, resets |
| `bench_fuzz.py` | stage 3: seeded garbage on the link while the station is unconfigured (never on air) |
| `linklib.py`, `itslib.py`, `bench_common.py` | the station-link client, a port of `gn_unwrap.c` and pcap reader, the result log |
| `compare_phone_vs_node.py` | what the phone's V2X log missed against a pcap recorded at the same time |
| `run_host_tests_overnight.ps1` | `make check` of `../host`, then the gn_unwrap fuzzer with new seeds until the time is up (needs MSYS2) |
## Overnight run on a board
Close everything that holds the port first (phone app over USB, `station_status_watch.py`, a serial monitor): opening
the port resets the board.
```powershell
git pull
powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\start_overnight.ps1 -Flash -Quick # about 8 minutes: does it all work?
powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\start_overnight.ps1 -Flash -Hours 8 # the overnight run
```
`-Flash` builds this checkout and writes it to the board, so the run tests the code you are looking at (the first build
downloads components and takes about 20 minutes). Add `-Port COM6` when more than one Espressif board is plugged in. Without
`start_overnight.ps1`, the board part alone is
`py -3.11 obu-firmware\test\bench\run_overnight.py COM6 --hours 8 --provision-demo`.
Results go to `obu-firmware/test/results/overnight-<time>/`: `report.txt` (read this), `results.json`, `status.csv`
(STATUS once every few seconds: heap, counters), `device.log` (the board's log lines), `boot.log` (ROM and bootloader
text, panics), `run.log`.
### What a cycle (about 45 minutes) does
1. **soak-unsigned**: BTP requests at 4 Hz, payload sizes 24 to 1480 octets in turn (494 and 495 are the V2X_RX edge).
If 40 requests in a row are refused with `resource_limit` the phase stops as "transmit path wedged" (seen 4 times in 11
cycles on 2026-11-25 with the Nov 10 build) and a repeated `STATION_CONFIGURE` is tried to see whether it clears.
2. **soak-signed** (needs a ticket): the same at 3 Hz, sizes up to 1398, signed with the demo chain.
3. **raw-toggle**: `RAW_CAPTURE` modes 0x00/0x01/0x03/0x05/0x07 in turn while transmitting: copies of the station's own frames
must appear exactly in the modes with the own-TX bit.
4. **reconfigure**: `STATION_CONFIGURE` every second or two with a new MAC, security on/off, radio TX+RX or RX only.
5. **fuzz**: reset the board, then random frames for a few minutes.
6. **resets**: reopen the port five times; each time the board must boot, configure and transmit.
7. **idle-listen**: radio receive-only, STATUS once a second; counts whatever else is on the air.
The run starts and ends with the conformance stage (which also resets the board), so a drift shows as a different result.
### How a transmitted frame is proven
On one board there is no second receiver, so the test uses the station's own `RAW_CAPTURE` mode 0x05: every frame the
station submits to the radio is copied back over the link (`RAW_FRAME`). The test unwraps the copy with `itslib.unwrap` (a Python
port of `gn_unwrap.c`, written separately from the firmware), and compares the ITS payload with what it sent. The payload
carries its own size and CRC-32, so truncation or a bit error in fragmentation or TX is caught. This does not prove that
another station can hear it; the compare script covers that when a second receiver records alongside.
### On the air
- Transmit phases send frames at 4 Hz at most, 5 dBm (`--power`), channel 180. The payload is a made-up ItsPduHeader
(protocolVersion 2, **messageID 0xF1**, stationId 0x7E57B0A7): not an assigned ETSI message, so a receiving stack refuses
it. MACs are locally administered, `02:b3:0a:ce:xx:xx`.
- `--no-tx` keeps the radio silent: only the protocol, fuzz, reset and idle stages run, and the checks that need a frame on
the radio are skipped.
- The fuzz stage starts on a freshly reset, unconfigured station and sends no `STATION_CONFIGURE` that decodes, so the radio never
starts. It never sends `CREDENTIALS_*`, the PKI requests or the trust bootstrap/update.
- `--provision-demo` writes `app/src/main/assets/demo-chain.vcr` (the throwaway chain the app provisions on its first
connect) to the board's NVS if it holds no ticket. `CREDENTIALS_ERASE` removes it again.
### Reading the report
`FAIL` is a check that contradicts the spec, the firmware source or what the radio did. `WARN` is a counter that disagrees,
a heap trend, a version mismatch. `INFO` is something the source leaves open, reported with the observed value. The first
lines say which firmware the board runs (`app_init` log) against this checkout's HEAD: a board that runs an older build tests
that build.
A fuzz failure prints the seed and the last frames as hex; replay with `--fuzz-seed N` (the fuzz stage of the first cycle uses it).
## Phone log against a node's pcap
```powershell
& $py obu-firmware\test\bench\compare_phone_vs_node.py "databases\<phone log>.db" "databases\<capture>.pcap" --csv misses.csv
```
Unwraps the pcap, aligns the clocks through the CAMs both saw byte for byte, matches the rest one to one (±0.5 s, identical
bytes), and prints per type and size, per station, when the misses fall, what the board's counters say, and what only the phone
heard. Two receivers at different places lose different frames, so compare runs with each other, not with 100 %.
Reports of the 2026-11-23 runs are in `../results/`.
## Setting up a workstation
`setup_workstation.ps1 -CheckOnly` reports what is missing; without `-CheckOnly` it installs it (about 3 GB, 20 to 40
minutes, needs internet; run it again after a failure). It was written after the first home run (2026-11-25) found no
ESP-IDF on the workstation, so the board there ran a stale build.
| Needed | Why | Installed by the script as |
|---|---|---|
| Git, `core.longpaths true` | `git pull` of this repo; ESP-IDF's tree has paths over 260 characters | `winget install Git.Git` |
| Python 3.11 (`py -3.11`) | the board tests and `check_replay.py` | `winget install Python.Python.3.11` |
| `pyserial` | the station link to the board | `py -3.11 -m pip install --user pyserial` |
| `asn1tools` | `check_replay.py` in the host tests (not the board tests) | `py -3.11 -m pip install --user asn1tools` |
| MSYS2 UCRT64 `gcc` and `make` | the PC-side C tests (`make check`) | `winget install MSYS2.MSYS2`, then `pacman -S mingw-w64-ucrt-x86_64-gcc make` |
| **ESP-IDF 6.0.2**, target esp32c5, in `C:\Espressif` | build and flash the firmware (**exactly 6.0.2**: `components/microbu_v2x` pins the radio driver ABI to it) | `git clone --branch v6.0.2 --recursive` into `C:\Espressif\frameworks\esp-idf-v6.0.2`, then `install.ps1 esp32c5` |
Also needed, but nothing to install: internet on the first build (`idf.py` downloads `espressif/esp-boost` into
`managed_components/`, about 125 MB), and a USB-C cable into the spare's single port (the native USB Serial/JTAG appears as a
COM port with the Windows built-in driver; no CH343 driver is needed for the spare). Not needed at home: Android Studio,
Java, a phone.
Before leaving it overnight: `setup_workstation.ps1 -PreventSleep` turns off sleep, hibernate, display-off and USB selective
suspend on mains power (`start_overnight.ps1` also holds Windows awake while it runs, but a USB port that suspends still drops
the board). Pause Windows Update, and plug the PC into mains.
Not in git, so absent on a fresh checkout: `its-g5-receiver-firmware/recordings/*.pcap` (the host replay test skips itself with
a message without them), `vanetza/` (`check_replay.py` then does not decode the 1609.2 envelopes independently),
`firmware-backups/`. Copy the recordings over if the home run should replay them.
**Flashing trouble:** if the build works but the flash says "No serial data received", unplug the board, hold BOOT, plug in,
release, flash again, then unplug and replug without BOOT. If the stub flasher will not start, use the `--no-stub` recipe in
[`../../FLASHING.md`](../../FLASHING.md).
## Python
`py -3.11` works once a new terminal has opened after the install; the full path in `$py` always does. Packages:
`py -3.11 -m pip install --user pyserial asn1tools`.
+106
View File
@@ -0,0 +1,106 @@
"""What the bench stages share: the result log, the run context and a few helpers."""
import json
import os
import statistics
import time
PASS, FAIL, WARN, INFO, SKIP = "PASS", "FAIL", "WARN", "INFO", "SKIP"
class Results:
"""Collects every check of a run; written to results.json and report.txt by `write`."""
def __init__(self, outdir, echo=print):
self.outdir, self.echo = outdir, echo
self.checks = [] # dicts: t, stage, name, level, detail
self.metrics = {} # stage -> {name: value}
self.started = time.time()
os.makedirs(outdir, exist_ok=True)
def add(self, stage, name, level, detail=""):
self.checks.append(dict(t=round(time.time() - self.started, 1), stage=stage, name=name, level=level, detail=str(detail)))
if level in (FAIL, WARN):
self.echo(" [%s] %s: %s %s" % (level, stage, name, detail))
return level == PASS
def ok(self, stage, name, cond, detail="", level_if_false=FAIL):
return self.add(stage, name, PASS if cond else level_if_false, detail)
def metric(self, stage, name, value):
self.metrics.setdefault(stage, {})[name] = value
def count(self, level):
return sum(1 for c in self.checks if c["level"] == level)
def failures(self):
return [c for c in self.checks if c["level"] == FAIL]
def write(self, extra_text=""):
with open(os.path.join(self.outdir, "results.json"), "w", encoding="utf-8") as f:
json.dump(dict(checks=self.checks, metrics=self.metrics, seconds=round(time.time() - self.started)), f, indent=1)
lines = ["micrOBU bench run, %.1f h" % ((time.time() - self.started) / 3600),
"PASS %d FAIL %d WARN %d INFO %d SKIP %d" % tuple(self.count(l) for l in (PASS, FAIL, WARN, INFO, SKIP)), ""]
# Collapse repeats: one line per (stage, name, level) with a count and the first detail.
groups = {}
for c in self.checks:
g = groups.setdefault((c["stage"], c["name"], c["level"]), [0, c])
g[0] += 1
for level in (FAIL, WARN, INFO, SKIP, PASS):
rows = [(k, v) for k, v in groups.items() if k[2] == level]
if not rows:
continue
lines.append("== %s ==" % level)
for (stage, name, _), (n, first) in rows:
detail = "" if level == PASS else first["detail"][:230]
lines.append(" %-14s %s%s %s" % (stage, name, " (x%d)" % n if n > 1 else "", detail))
lines.append("")
if extra_text:
lines.append(extra_text)
text = "\n".join(lines)
with open(os.path.join(self.outdir, "report.txt"), "w", encoding="utf-8") as f:
f.write(text + "\n")
return text
class Ctx:
"""Everything a stage needs. `mac_n` makes every configure use a fresh locally administered MAC."""
def __init__(self, link, res, args, outdir):
self.link, self.res, self.args, self.outdir = link, res, args, outdir
self.run_id = int(time.time()) & 0xFFFFFFFF
self.tx_seq = 0
self.mac_n = 0
self.credentials = False # the station holds an authorization ticket (provisioned or already there)
self.tx_enabled = not args.no_tx
self.deadline = None
self.phase = "init"
self.rx_stats = {} # (port, flags&2, size bucket) -> count: everything heard on the air
self.heap = [] # (time, phase, heap_free, heap_min_free, heap_largest, uptime_ms) at quiet moments
def next_mac(self):
self.mac_n += 1
return bytes([0x02, 0xB3, 0x0A, 0xCE, (self.mac_n >> 8) & 0xFF, self.mac_n & 0xFF])
def time_left(self):
return float("inf") if self.deadline is None else self.deadline - time.time()
def sample_status(self, label=None):
s = self.link.status(1.5)
self.link.log_status(s, label or self.phase)
return s
def median(xs):
xs = list(xs)
return statistics.median(xs) if xs else None
def slope_per_hour(points):
"""Least-squares slope of (t_seconds, value) points, per hour; None for fewer than 3 points."""
if len(points) < 3:
return None
n = len(points)
mt = sum(t for t, _ in points) / n
mv = sum(v for _, v in points) / n
den = sum((t - mt) ** 2 for t, _ in points)
return None if den == 0 else 3600.0 * sum((t - mt) * (v - mv) for t, v in points) / den
@@ -0,0 +1,300 @@
"""Stage 1: does the station answer the link protocol the way docs/station-link.tex and main/link_service.cpp say?
Every expectation below is taken from the spec text or from the firmware source (cited in the check's name), not
from observed behaviour. What the source leaves open is reported as INFO with the observed value.
The first half runs on a freshly reset, unconfigured station, so nothing in it can reach the radio. The second half
configures it (security 0, low power) and, unless --no-tx, puts a few frames on air whose payload no ITS receiver
accepts as a message (see linklib.test_payload).
"""
import random
import struct
import time
import itslib
import linklib as ll
from bench_common import FAIL, INFO, PASS, SKIP, WARN
S = "conformance"
def expect_code(ctx, name, reply, code):
got = reply.name if reply else "no reply"
return ctx.res.ok(S, name, reply is not None and reply.code == code, "expected %s, got %s" % (ll.CODES[code], got))
def run(ctx):
L, R = ctx.link, ctx.res
ctx.phase = S
L.reboot()
s0 = L.wait_status(20)
if not R.ok(S, "station answers STATUS_REQUEST after a reset", s0 is not None, "no CONFIRM within 20 s"):
return
R.ok(S, "STATUS detail is the 131-octet snapshot (spec: Status confirmation payload)", s0["raw_len"] == 131, "got %d octets" % s0["raw_len"])
R.ok(S, "a reset station is unconfigured", s0["configured"] == 0)
R.ok(S, "uptime restarted at the reset", s0["uptime_ms"] < 30000, "uptime %d ms" % s0["uptime_ms"])
time.sleep(1.5)
s1 = L.status()
if s1:
d = (s1["uptime_ms"] - s0["uptime_ms"]) / 1000.0
R.ok(S, "STATUS uptime runs at real time", 1.0 < d < 3.5, "%.2f s of uptime over ~2 s" % d)
R.metric(S, "heap_free_after_boot", s1["heap_free"])
R.metric(S, "heap_largest_after_boot", s1["heap_largest"])
R.add(S, "battery reading with no cell", INFO, "battery_mv %d (0 = not measured, no shutdown on it)" % s1["battery_mv"])
crc0 = s1["link_crc_errors"] if s1 else 0
# ---- unknown and malformed (no station needed)
for op in (0x00, 0x40, 0x7E, 0x80, 0x85, 0x90, 0xFF):
expect_code(ctx, "opcode 0x%02x is answered unknown_opcode (link_service.cpp default)" % op, L.request(op, b""), ll.UNKNOWN_OPCODE)
expect_code(ctx, "STATUS_REQUEST with a body is malformed", L.request(ll.STATUS_REQUEST, b"\x00"), ll.MALFORMED)
for n in (0, 1, 5, 7, 15, 17):
expect_code(ctx, "STATION_CONFIGURE of %d octets is malformed (spec: 6 or 16)" % n, L.request(ll.STATION_CONFIGURE, bytes(n)), ll.MALFORMED)
expect_code(ctx, "STATION_CONFIGURE security=2 is malformed", L.request(ll.STATION_CONFIGURE, struct.pack("<BHBBB", 2, 180, 5, 2, 0)), ll.MALFORMED)
expect_code(ctx, "STATION_CONFIGURE beaconing=2 is malformed", L.request(ll.STATION_CONFIGURE, struct.pack("<BHBBB", 2, 180, 5, 0, 2)), ll.MALFORMED)
expect_code(ctx, "16-octet STATION_CONFIGURE radio=3 is malformed",
L.request(ll.STATION_CONFIGURE, ll.configure_body(mac=ctx.next_mac(), radio=3)), ll.MALFORMED)
expect_code(ctx, "POTI_UPDATE of 5 octets is malformed", L.request(ll.POTI_UPDATE, bytes(5)), ll.MALFORMED)
expect_code(ctx, "RAW_CAPTURE with a 2-octet body is malformed", L.request(ll.RAW_CAPTURE, b"\x01\x01"), ll.MALFORMED)
expect_code(ctx, "RAW_CAPTURE mode with a high nibble is invalid_argument (raw_capture_policy.hpp)", L.request(ll.RAW_CAPTURE, b"\xF0"), ll.INVALID_ARGUMENT)
expect_code(ctx, "RAW_CAPTURE on before STATION_CONFIGURE is not_configured", L.raw_capture(1), ll.NOT_CONFIGURED)
valid = ll.btp_body(ll.test_payload(ctx.run_id, 0, 43))
expect_code(ctx, "BTP_DATA_REQUEST before STATION_CONFIGURE is not_configured", L.request(ll.BTP_DATA_REQUEST, valid), ll.NOT_CONFIGURED)
expect_code(ctx, "BTP_DATA_REQUEST btp_type=2 is malformed", L.request(ll.BTP_DATA_REQUEST, ll.btp_body(b"x" * 30, btp_type=2)), ll.MALFORMED)
expect_code(ctx, "BTP_DATA_REQUEST with 32 permission octets is malformed", L.request(ll.BTP_DATA_REQUEST, ll.btp_body(b"x" * 30, permissions=bytes(32))), ll.MALFORMED)
expect_code(ctx, "BTP_DATA_REQUEST with 3 stray trailing octets is malformed", L.request(ll.BTP_DATA_REQUEST, valid + b"abc"), ll.MALFORMED)
expect_code(ctx, "BTP_DATA_REQUEST cut short is malformed", L.request(ll.BTP_DATA_REQUEST, valid[:-1]), ll.MALFORMED)
expect_code(ctx, "BTP_DATA_REQUEST with the optional generated_at_ms decodes (then not_configured)",
L.request(ll.BTP_DATA_REQUEST, ll.btp_body(b"x" * 30, generated_at_ms=ll.timestamp_its())), ll.NOT_CONFIGURED)
# ---- sequence numbers
for seq in (65534, 65535, 0, 1):
r = L.request(ll.STATUS_REQUEST, b"", seq=seq)
R.ok(S, "CONFIRM echoes sequence %d (counters wrap 65535 -> 0)" % seq, r is not None and r.code == 0, "no CONFIRM" if r is None else "")
# ---- request fragmentation (spec: Fragmented messages; request_reassembly.hpp). Unconfigured: reaching
# not_configured proves the whole body was joined and decoded, and nothing can go on air.
full = ll.btp_body(ll.test_payload(ctx.run_id, 1, ll.max_btp_payload()))
R.ok(S, "test request is exactly 1536 octets (the request maximum)", len(full) == ll.REQUEST_MAX, "%d" % len(full))
for cap in (240, 504):
expect_code(ctx, "1536-octet request in fragments of %d octets is joined and decoded (-> not_configured)" % cap,
L.request_fragmented(ll.BTP_DATA_REQUEST, full, 3.0, cap=cap), ll.NOT_CONFIGURED)
r = _expect_reply(L, 4242, lambda: L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, 4242, valid + bytes(560)))), 1.0)
R.add(S, "an unfragmented link message over 512 octets", INFO, "reply: %s (the spec says to fragment; link_service.cpp drops it before dispatch)" % (r.name if r else "none"))
over = ll.btp_body(b"y" * 500)
seq = L.next_seq()
reply = _expect_reply(L, seq, lambda: L.send_fragmented(ll.BTP_DATA_REQUEST, over, seq=seq, cap=240, total_override=1537), 2.0)
expect_code(ctx, "fragmented request declaring 1537 octets is resource_limit", reply, ll.RESOURCE_LIMIT)
seq = L.next_seq()
reply = _expect_reply(L, seq, lambda: _gap(L, full, seq), 1.2)
R.ok(S, "a fragment that leaves a gap is dropped without a reply", reply is None, "got %s" % (reply.name if reply else ""))
seq = L.next_seq()
reply = _expect_reply(L, seq, lambda: _expire(L, full, seq), 1.0)
R.ok(S, "an unfinished request is discarded after the 2 s idle timeout (its late last fragment gets no reply)", reply is None,
"got %s" % (reply.name if reply else ""))
got = _nine_streams(ctx, L)
R.ok(S, "at most 8 incomplete requests are held (spec: pending maximum 8)", got == 8, "%d of 9 interleaved requests were answered" % got)
# ---- the USB framing
s_before = L.status()
L.write(ll.frame(ll.LINK, ll.link_message(ll.STATUS_REQUEST, 7), bad_crc=True))
time.sleep(0.4)
s_after = L.status()
if s_before and s_after:
R.ok(S, "a frame with a wrong CRC is counted in link_crc_errors and ignored",
s_after["link_crc_errors"] == s_before["link_crc_errors"] + 1,
"%d -> %d" % (s_before["link_crc_errors"], s_after["link_crc_errors"]))
L.write(bytes(random.Random(5).choice([b for b in range(256) if b != 0xAA]) for _ in range(60)))
R.ok(S, "a valid frame after 60 octets of noise is answered (resync)", L.status() is not None)
L.write(b"\xAA\xAA" + ll.frame(ll.LINK, ll.link_message(ll.STATUS_REQUEST, 8)))
time.sleep(0.3)
R.ok(S, "a valid frame after a doubled 0xAA is answered", L.status() is not None)
for n in (1537, 4000, 65535):
L.write(b"\xAA\x55\x10" + struct.pack("<H", n)) # an untrustworthy length: the decoder resyncs at once
R.ok(S, "a valid frame after a header declaring %d payload octets is answered (resync)" % n, L.status() is not None)
L.write(b"\xAA\x55\x10\x0a\x00" + b"\x01\x02\x03\x04" + b"\x00" * 8) # cut short, then padded to its declared length
time.sleep(0.3)
R.ok(S, "a frame cut short and padded out is dropped and the next valid frame is answered", L.status() is not None)
L.write(ll.frame(0x42, b"unknown frame type"))
time.sleep(0.2)
R.ok(S, "a frame of unknown type does not disturb the link", L.status() is not None)
# ---- the half that configures the station
r = L.configure(secured=False, power=5)
if not expect_code(ctx, "STATION_CONFIGURE (6 octets, unsecured, 5 dBm) is accepted", r, ll.ACCEPTED):
return
R.ok(S, "STATION_CONFIGURE detail is 18 octets (spec: gn_address, identifier, credentials_loaded, tickets)", len(r.detail) == 18, "%d" % len(r.detail))
expect_code(ctx, "RAW_CAPTURE mode 0x05 (on + own TX) after configure is accepted", L.raw_capture(5), ll.ACCEPTED)
expect_code(ctx, "BTP_DATA_REQUEST before the first POTI_UPDATE is rejected (no ITS time, no fix)",
L.request(ll.BTP_DATA_REQUEST, valid), ll.REJECTED)
expect_code(ctx, "POTI_UPDATE with latitude 91 degrees is invalid_argument",
L.request(ll.POTI_UPDATE, ll.poti_body(lat=910000000)), ll.INVALID_ARGUMENT)
p0 = L.status()
reply = _expect_reply(L, 0, lambda: L.send(ll.POTI_UPDATE, ll.poti_body(), seq=0), 0.5)
R.ok(S, "an accepted POTI_UPDATE is silent (spec: errors return CONFIRM)", reply is None, "got %s" % (reply.name if reply else ""))
time.sleep(0.3)
p1 = L.status()
if p0 and p1:
R.ok(S, "an accepted POTI_UPDATE counts in poti_updates", p1["poti_updates"] == p0["poti_updates"] + 1, "%d -> %d" % (p0["poti_updates"], p1["poti_updates"]))
r = L.request(ll.POTI_UPDATE, ll.poti_body(offset_ms=-8000))
R.add(S, "POTI_UPDATE 8 s behind the station clock", INFO, "reply: %s" % (r.name if r else "none (accepted silently)"))
L.poti()
# ---- unsecured transmission
L.raw_frames.clear()
sent = []
if ctx.tx_enabled:
for i, size in enumerate((24, 43, 300)):
payload = ll.test_payload(ctx.run_id, 100 + i, size)
r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(payload))
expect_code(ctx, "unsecured BTP_DATA_REQUEST of %d octets is accepted" % size, r, ll.ACCEPTED)
sent.append(payload)
time.sleep(0.15)
time.sleep(1.0)
got = [itslib.unwrap(f) for _, fl, _, f in L.raw_frames if fl & 1]
got = [g for g in got if g]
seen = {g["payload"] for g in got}
R.ok(S, "every accepted request leaves the radio, byte for byte (own-TX RAW_FRAME copy, unwrapped independently)",
all(p in seen for p in sent), "%d of %d payloads captured" % (sum(p in seen for p in sent), len(sent)))
R.ok(S, "unsecured frames carry no security envelope", all(not g["signed"] for g in got))
macs = {g["src"] for g in got}
R.add(S, "802.11 source of own unsecured frames", INFO, ", ".join(sorted(macs)))
else:
R.add(S, "on-air checks", SKIP, "--no-tx")
# Only the station's own transmissions count: with RAW_CAPTURE on, frames heard from other stations arrive here too
# (the bench has a V2X node and a simulated car on the air; a quiet room does not).
own_frames = lambda: sum(1 for _, fl, _, _ in list(L.raw_frames) if fl & 1)
n_frames = own_frames()
for name, body, code in (
("transport type 2 (TSB) unsecured is unsupported (station_unsecured: geonet.c builds SHB only)", ll.btp_body(b"z" * 30, transport=2), ll.UNSUPPORTED),
("btp_type 2 is malformed", ll.btp_body(b"z" * 30, btp_type=2), ll.MALFORMED),
):
expect_code(ctx, name, L.request(ll.BTP_DATA_REQUEST, body), code)
time.sleep(0.8)
R.ok(S, "refused requests put nothing on the radio", own_frames() == n_frames, "%d new own frames" % (own_frames() - n_frames))
# ---- secured transmission (configure with security on: the reply says whether the board holds a ticket)
mac2 = ctx.next_mac()
r = L.request(ll.STATION_CONFIGURE, ll.configure_body(secured=True, power=5, mac=mac2), 8.0)
if r and r.code == 0 and len(r.detail) == 18:
ctx.credentials = r.detail[16] == 1 and r.detail[17] > 0
R.add(S, "credentials on this board (configure with security on)", INFO, "credentials_loaded %d, tickets %d" % (r.detail[16], r.detail[17]))
else:
R.add(S, "STATION_CONFIGURE with security on", INFO, "reply: %s" % (r.name if r else "none"))
L.poti()
L.raw_capture(5)
if not ctx.credentials:
n_frames = len(L.raw_frames)
r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(ll.test_payload(ctx.run_id, 200, 43), secured=True))
R.add(S, "secured request on a board without a ticket", INFO, "reply: %s" % (r.name if r else "none"))
time.sleep(1.5)
leaked = [itslib.unwrap(f) for _, fl, _, f in list(L.raw_frames)[n_frames:] if fl & 1]
R.ok(S, "a secured request without a ticket never goes out unsigned", not any(leaked), "%d frames appeared" % len([g for g in leaked if g]))
st = L.status()
if st:
R.add(S, "counters after the unsignable request", INFO, "refused_no_ticket %d, requests_refused %d, sign_failed %d" %
(st["refused_no_ticket"], st["requests_refused"], st["sign_failed"]))
elif ctx.tx_enabled:
L.raw_frames.clear()
payload = ll.test_payload(ctx.run_id, 201, 100)
r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(payload, secured=True, generated_at_ms=ll.timestamp_its()))
expect_code(ctx, "signed BTP_DATA_REQUEST is accepted", r, ll.ACCEPTED)
time.sleep(2.0)
got = [itslib.unwrap(f) for _, fl, _, f in L.raw_frames if fl & 1]
got = [g for g in got if g and g["payload"] == payload]
R.ok(S, "the signed request leaves the radio inside a signed envelope (IEEE 1609.2 signedData)", len(got) == 1 and got[0]["signed"],
"%d matching frames, signed=%s" % (len(got), [g["signed"] for g in got]))
R.ok(S, "signed frames use the MAC the phone named", len(got) == 1 and got[0]["src"] == mac2.hex(":"), "%s want %s" % ([g["src"] for g in got], mac2.hex(":")))
L.raw_frames.clear()
stale = ll.test_payload(ctx.run_id, 202, 100)
r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(stale, secured=True, generated_at_ms=ll.timestamp_its() - 5000))
expect_code(ctx, "a signed request generated 5 s ago is rejected as stale (tx_policy::is_stale)", r, ll.REJECTED)
time.sleep(1.0)
R.ok(S, "a stale request is never transmitted", not any(itslib.unwrap(f) for _, fl, _, f in L.raw_frames if fl & 1))
# How large a signed payload still leaves the radio: Vanetza's itsGnMaxSduSize is 1398 octets; the CONFIRM only says "queued"
for size in (1398, 1399, 1400):
L.poti()
st0 = L.status()
L.raw_frames.clear()
payload = ll.test_payload(ctx.run_id, 210 + size, size)
r = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(payload, secured=True, generated_at_ms=ll.timestamp_its()), 3.0)
time.sleep(1.5)
out = any((itslib.unwrap(f) or {}).get("payload") == payload for _, fl, _, f in L.raw_frames if fl & 1)
st1 = L.status()
R.add(S, "signed payload of %d octets" % size, INFO, "CONFIRM %s, transmitted %s, requests_refused %+d, sign_failed %+d" %
(r.name if r else "none", "yes" if out else "NO", (st1["requests_refused"] - st0["requests_refused"]) if st0 and st1 else 0,
(st1["sign_failed"] - st0["sign_failed"]) if st0 and st1 else 0))
else:
R.add(S, "signed transmission", SKIP, "--no-tx")
# ---- reconfigure with a named MAC
mac = ctx.next_mac()
r = L.request(ll.STATION_CONFIGURE, ll.configure_body(mac=mac, power=5))
expect_code(ctx, "16-octet STATION_CONFIGURE naming a MAC is accepted", r, ll.ACCEPTED)
if r and len(r.detail) == 18:
R.add(S, "GN address after naming MAC %s" % mac.hex(":"), INFO, r.detail[:8].hex(":"))
if ctx.tx_enabled and r and r.code == 0:
L.raw_frames.clear()
L.poti()
r2 = L.request(ll.BTP_DATA_REQUEST, ll.btp_body(ll.test_payload(ctx.run_id, 300, 43)))
time.sleep(1.0)
macs = {itslib.unwrap(f)["src"] for _, fl, _, f in L.raw_frames if fl & 1 and itslib.unwrap(f)}
R.ok(S, "frames use the MAC the phone named (spec: MicrOBU 16-octet STATION_CONFIGURE)", macs == {mac.hex(":")}, "on air: %s" % sorted(macs))
L.raw_capture(0)
end = L.status()
if end:
R.add(S, "after the stage", INFO, "uptime %d ms, heap_free %d, heap_min %d, radio failed %d, resets seen %d" %
(end["uptime_ms"], end["heap_free"], end["heap_min_free"], end["radio_failed"], L.boots))
R.ok(S, "the station did not reset during the stage", end["uptime_ms"] > s0["uptime_ms"])
def _expect_reply(L, seq, action, wait):
"""Run `action` (which sends with this sequence) and wait up to `wait` s for a CONFIRM to it."""
import threading
ev = [threading.Event(), None, time.time()]
with L.lock:
L.pending[seq] = ev
try:
action()
ev[0].wait(wait)
return ev[1]
finally:
with L.lock:
L.pending.pop(seq, None)
def _gap(L, body, seq):
cap = 240
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, seq, struct.pack("<HH", len(body), 0) + body[:cap], 1)))
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, seq, struct.pack("<HH", len(body), 2 * cap) + body[2 * cap:3 * cap], 2)))
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, seq, struct.pack("<HH", len(body), len(body) - 100) + body[-100:], 3)))
def _expire(L, body, seq):
cap = 240
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, seq, struct.pack("<HH", len(body), 0) + body[:cap], 1)))
time.sleep(2.6)
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, seq, struct.pack("<HH", len(body), cap) + body[cap:], 3)))
def _nine_streams(ctx, L):
"""Nine interleaved fragmented requests; the station holds eight. Returns how many were answered."""
import threading
body = ll.btp_body(ll.test_payload(ctx.run_id, 2, 574)) # 600 octets in two fragments of 300
cap = 300
seqs = [L.next_seq() for _ in range(9)]
evs = {}
for s in seqs:
evs[s] = [threading.Event(), None, time.time()]
with L.lock:
L.pending.update(evs)
try:
for s in seqs:
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, s, struct.pack("<HH", len(body), 0) + body[:cap], 1)))
for s in seqs:
L.write(ll.frame(ll.LINK, ll.link_message(ll.BTP_DATA_REQUEST, s, struct.pack("<HH", len(body), cap) + body[cap:], 3)))
time.sleep(1.5)
return sum(1 for s in seqs if evs[s][1] is not None)
finally:
with L.lock:
for s in seqs:
L.pending.pop(s, None)
+160
View File
@@ -0,0 +1,160 @@
"""Stage 3: does the station survive garbage on the link?
A seeded random generator sends frames the station must refuse or ignore: valid CRC around random link messages,
random fragment flags/offsets/totals, truncated and corrupted frames, noise, oversize length fields. After every
burst the station must still answer STATUS_REQUEST, must not have reset (uptime keeps growing, no ROM banner, no
panic text), and must not have lost heap.
Safety rules, so a fuzz run can never put anything on the air or change what the board stores:
* it starts from a freshly reset, UNCONFIGURED station, and never sends a STATION_CONFIGURE that decodes
(valid bodies are 6 or 16 octets with small field values: every body here is the wrong length or has a field out of
range), so the radio never starts and BTP_DATA_REQUEST can only answer not_configured;
* it never sends CREDENTIALS_PROVISION / CREDENTIALS_ERASE, the PKI requests (they create keys and write NVS) or
the trust bootstrap/update.
A failure prints the seed and the last frames sent (hex), so it can be replayed with --seed.
"""
import collections
import random
import struct
import time
import linklib as ll
from bench_common import FAIL, INFO, PASS, WARN
S = "fuzz"
# opcodes the generator may use: harmless without a configured radio, or unknown
SAFE_KNOWN = [ll.POTI_UPDATE, ll.BTP_DATA_REQUEST, ll.SF_IDCHANGE_SUBSCRIBE, ll.SF_IDCHANGE_UNSUBSCRIBE, ll.SF_IDCHANGE_EVENT_RESPONSE,
ll.SF_IDCHANGE_TRIGGER, ll.SF_ID_LOCK, ll.SF_ID_UNLOCK, ll.STATUS_REQUEST, ll.RAW_CAPTURE, ll.PKI_STATUS]
UNKNOWN = [o for o in range(0x00, 0x100)
if o not in (0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D)
and not 0x0E <= o <= 0x17] # everything PKI is excluded, known or not
def bad_configure_body(rnd):
"""A STATION_CONFIGURE body the station must refuse: wrong length, or a field out of range."""
kind = rnd.randrange(4)
if kind == 0:
n = rnd.choice([n for n in range(0, 40) if n not in (6, 16)])
return bytes(rnd.getrandbits(8) for _ in range(n))
if kind == 1:
return struct.pack("<BHBBB", rnd.getrandbits(8), rnd.getrandbits(16), rnd.getrandbits(8), rnd.randrange(2, 256), rnd.getrandbits(8))
if kind == 2:
return struct.pack("<BHBBB", 2, 180, 5, rnd.randrange(2), rnd.randrange(2, 256))
return struct.pack("<BBB6sBHBBBB", 2, 0, rnd.randrange(2, 256), bytes(6), 0, 180, 5, rnd.randrange(3, 256), 2, 5)
def random_message(rnd):
"""(opcode, flags, seq, body) of a random link message."""
roll = rnd.random()
if roll < 0.12:
return ll.STATION_CONFIGURE, 0, rnd.getrandbits(16), bad_configure_body(rnd)
op = rnd.choice(SAFE_KNOWN) if roll < 0.7 else rnd.choice(UNKNOWN)
flags = 0 if rnd.random() < 0.6 else rnd.choice([1, 2, 3, 4, 5, 0x80, 0xFF])
n = rnd.choice([0, 1, 2, 3, 4, 5, 8, 16, 26, 31, 32, 64, 100, 255, 256, 500, 504])
body = bytes(rnd.getrandbits(8) for _ in range(n))
if flags and rnd.random() < 0.7 and n >= 4: # fragment header with believable numbers
total = rnd.choice([n, n + 10, 600, 1536, 1537, 4000, 65535, 0])
body = struct.pack("<HH", total, rnd.choice([0, 0, n - 4, 100, 65535])) + body[4:]
return op, flags, rnd.getrandbits(16), body
def random_wire(rnd):
"""Bytes for the serial port: usually a valid frame, sometimes broken in one way or another."""
op, flags, seq, body = random_message(rnd)
msg = ll.link_message(op, seq, body, flags)
roll = rnd.random()
if roll < 0.55:
return ll.frame(ll.LINK, msg)
if roll < 0.65:
return ll.frame(ll.LINK, msg, bad_crc=True)
if roll < 0.72:
return ll.frame(ll.LINK, msg)[:rnd.randrange(1, max(2, len(msg)))] # cut off: the next frame completes it
if roll < 0.78:
return bytes(rnd.getrandbits(8) for _ in range(rnd.randrange(1, 40))) # noise
if roll < 0.82:
return b"\xAA\x55" + bytes([rnd.getrandbits(8)]) + struct.pack("<H", rnd.choice([1537, 2000, 65535, 0xAA55]))
if roll < 0.86:
return ll.frame(rnd.choice([0x00, 0x11, 0x42, 0x7E, 0xFF]), msg) # unknown frame type
if roll < 0.90:
return ll.frame(ll.LINK, msg[:rnd.randrange(0, 4)]) # a link message shorter than its header
if roll < 0.93:
return ll.frame(ll.LINK, bytes(rnd.getrandbits(8) for _ in range(rnd.choice([513, 600, 1000, 1536])))) # over one message
if roll < 0.96:
return ll.frame(ll.LINK, b"")
return ll.frame(ll.LINK, msg) * rnd.randrange(2, 6)
def run(ctx, seconds, seed=None):
L, R = ctx.link, ctx.res
ctx.phase = S
seed = seed if seed is not None else random.SystemRandom().randrange(1 << 32)
rnd = random.Random(seed)
R.add(S, "seed", INFO, "%d (replay with --fuzz-seed %d)" % (seed, seed))
L.reboot()
s0 = L.wait_status(20)
if not R.ok(S, "station answers before the fuzz run", s0 is not None):
return
R.ok(S, "fuzz starts unconfigured (nothing can reach the radio)", s0["configured"] == 0)
if s0["configured"]:
return
ring = collections.deque(maxlen=25)
sent = bursts = 0
boots0 = L.boots
panics0 = len(L.panics)
end = min(time.time() + seconds, ctx.deadline or 1e18)
start_heap = last_heap = worst_heap = s0["heap_free"]
failed = False
while time.time() < end and not failed:
for _ in range(rnd.randrange(20, 120)):
wire = random_wire(rnd)
ring.append(wire)
try:
L.write(wire)
except Exception as e:
R.add(S, "serial write", FAIL, repr(e))
failed = True
break
sent += 1
if rnd.random() < 0.3:
time.sleep(0.002)
bursts += 1
# A cut-off frame leaves the station's decoder waiting for up to 1536 payload octets; zeros finish it (bad CRC,
# counted, then it resyncs on the next 0xAA55). Without this the liveness request below would be swallowed.
L.write(b"\x00" * 1542)
time.sleep(0.4)
s = None
for _ in range(3):
s = L.status(2.0)
if s:
break
time.sleep(0.3)
L.log_status(s, S)
if s is None:
R.add(S, "station stopped answering after a fuzz burst", FAIL, "burst %d, seed %d; last frames:\n%s" % (bursts, seed, _dump(ring)))
failed = True
else:
if s["uptime_ms"] < s0["uptime_ms"] or L.boots > boots0:
R.add(S, "station reset during fuzz", FAIL, "burst %d, seed %d, uptime %d; last frames:\n%s" % (bursts, seed, s["uptime_ms"], _dump(ring)))
failed = True
if s["configured"]:
R.add(S, "fuzz managed to configure the station", FAIL, "burst %d, seed %d; last frames:\n%s" % (bursts, seed, _dump(ring)))
failed = True
worst_heap = min(worst_heap, s["heap_free"])
last_heap = s["heap_free"]
s0 = dict(s0, uptime_ms=s["uptime_ms"])
if len(L.panics) > panics0:
R.add(S, "panic or error text on the console", FAIL, "%s; seed %d; last frames:\n%s" % (L.panics[panics0:][:3], seed, _dump(ring)))
failed = True
L.log_status(L.status(), S)
if not failed:
R.add(S, "fuzz run", PASS, "%d frames in %d bursts, no reset, no panic, always answered" % (sent, bursts))
R.ok(S, "heap after fuzz is within 8 KB of the start", abs(last_heap - start_heap) <= 8192,
"start %d, end %d, lowest %d" % (start_heap, last_heap, worst_heap), WARN)
R.metric(S, "frames_sent", sent)
R.metric(S, "device_counts", {k: v for k, v in L.counts.items() if k.startswith(("frames_", "frag_", "confirm"))})
# leave the board in a known state
L.reboot()
def _dump(ring):
return "\n".join(" " + w.hex() for w in list(ring)[-12:])
+425
View File
@@ -0,0 +1,425 @@
"""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("<HHB", len(bundle), off, len(seg)) + seg, 20.0 if last else 3.0)
if not (r and r.code == ll.ACCEPTED):
ctx.res.add(S, "CREDENTIALS_PROVISION segment at %d" % off, FAIL, "reply %s" % (r.name if r else "none"))
return False
if last:
ctx.res.add(S, "demo chain applied", INFO, "roots %d, authorities %d, tickets %d" % tuple(r.detail[:3]) if len(r.detail) >= 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("<HbB", body[:4])
payload = body[14:]
if ll.check_test_payload(payload):
own += 1
key = (itslib.PORT_NAMES.get(port, port), bool(flags & 2), _bucket(len(payload)))
ctx.rx_stats[key] = ctx.rx_stats.get(key, 0) + 1
return n, own
def _bucket(n):
for b in (64, 128, 256, 494, 1000, 1500, 2300):
if n <= b:
return "<=%d" % b
return ">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)
@@ -0,0 +1,367 @@
#!/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())
+131
View File
@@ -0,0 +1,131 @@
"""Shared helpers of the bench tests: pcap reading and a Python port of obu-firmware/main/gn_unwrap.c.
The port is written from the C file and EN 302 636-4-1, not from the firmware's behaviour on a board, so it is
a second opinion on what the firmware's own unwrapper should extract from a frame. It is what the bench tests
use to check the frames the station puts on the radio (RAW_FRAME own-TX copies) and what compare_phone_vs_node.py
uses to read a pcap.
"""
import struct
PORT_NAMES = {2001: "CAM", 2002: "DENM", 2003: "MAPEM", 2004: "SPATEM", 2018: "VAM"}
LLC_SNAP = b"\xaa\xaa\x03\x00\x00\x00\x89\x47"
def read_pcap(path):
"""Yield (time_s, 802.11 frame) for every record of a linktype 105 (802.11) or 127 (radiotap) pcap."""
d = open(path, "rb").read()
if len(d) < 24:
return
magic = struct.unpack("<I", d[:4])[0]
e = "<" if magic in (0xA1B2C3D4, 0xA1B23C4D) else ">"
nano = magic == 0xA1B23C4D or struct.unpack(">I", d[:4])[0] == 0xA1B23C4D
link = struct.unpack(e + "I", d[20:24])[0]
if link not in (105, 127):
raise SystemExit("pcap linktype %d: only 105 (802.11) and 127 (radiotap) are read" % link)
off = 24
while off + 16 <= len(d):
s, frac, incl, _ = struct.unpack(e + "IIII", d[off:off + 16])
if incl > len(d) - off - 16:
break
pkt = d[off + 16:off + 16 + incl]
off += 16 + incl
if link == 127:
if len(pkt) < 4:
continue
rl = pkt[2] | pkt[3] << 8
if rl > len(pkt):
continue
pkt = pkt[rl:]
yield s + frac / (1e9 if nano else 1e6), pkt
def coer_length(p, i):
"""(length, bytes used) of a COER length determinant at p[i], or (None, 0)."""
if i >= len(p):
return None, 0
if p[i] < 0x80:
return p[i], 1
n = p[i] & 0x7F
if n < 1 or n > 2 or i + 1 + n > len(p):
return None, 0
return int.from_bytes(p[i + 1:i + 1 + n], "big"), 1 + n
def unwrap(f, ports=None):
"""gn_unwrap_its in Python.
Returns dict(port, payload, signed, area, truncated, src, dst, header_type) or None. `ports` limits the BTP
destination ports accepted (default: the five the firmware forwards).
"""
ports = PORT_NAMES if ports is None else ports
if len(f) < 24:
return None
t, sub = (f[0] >> 2) & 3, (f[0] >> 4) & 15
if t != 2 or (f[1] & 3) == 3:
return None
o = 24 + (2 if sub & 8 else 0)
if len(f) < o + 8 or f[o:o + 8] != LLC_SNAP or len(f) < o + 12:
return None
o += 8
bnh = f[o] & 0x0F
o += 4
limit, env_end, signed = len(f), -1, False
if bnh == 2:
p, avail = f[o:], len(f) - o
if avail < 2 or p[0] != 3:
return None
if p[1] == 0x81:
if avail < 6 or p[2] >= 0x80 or not p[3] & 0x40 or p[4] != 3 or p[5] != 0x80:
return None
i, signed = 6, True
elif p[1] == 0x80:
i = 2
else:
return None
n, used = coer_length(p, i)
if not used:
return None
env_end = o + i + used + n
o += i + used
limit = min(limit, env_end)
elif bnh != 1:
return None
if limit < o + 8:
return None
nh, ht, hst = f[o] >> 4, f[o + 1] >> 4, f[o + 1] & 15
gn_len = int.from_bytes(f[o + 4:o + 6], "big")
if nh != 2:
return None
o += 8
area = None
if ht == 5 and hst == 0:
ext = 28
elif ht == 4:
ext = 44
else:
return None
if limit < o + ext:
return None
if ht == 4:
area = (int.from_bytes(f[o + 28:o + 32], "big", signed=True), int.from_bytes(f[o + 32:o + 36], "big", signed=True),
int.from_bytes(f[o + 36:o + 38], "big"))
o += ext
if limit < o + 4:
return None
port = int.from_bytes(f[o:o + 2], "big")
if port not in ports or gn_len <= 4:
return None
start, end = o + 4, o + gn_len
if env_end >= 0 and end > env_end:
return None
trunc = end > len(f)
payload = f[start:(len(f) if trunc else end)]
if not payload:
return None
return dict(port=port, payload=bytes(payload), signed=signed, area=area, truncated=trunc,
src=f[10:16].hex(":"), dst=f[4:10].hex(":"), header_type=(ht, hst))
def station_of(payload):
"""ItsPduHeader.stationId (CAM/DENM/SPATEM/MAPEM/VAM all start protocolVersion, messageId, stationId)."""
return int.from_bytes(payload[2:6], "big") if len(payload) >= 6 else None
+475
View File
@@ -0,0 +1,475 @@
"""Station-link client for the bench tests (obu-firmware/docs/station-link.tex, revision 3), over the native USB
Serial/JTAG port. Standard library plus pyserial. Written from the spec and main/link_protocol.*, not from the
phone app, so it is a second implementation of the host side.
Opening the port resets the board (USB Serial/JTAG): a reopen is how the tests get a clean, unconfigured station.
"""
import collections
import os
import random
import re
import struct
import threading
import time
import zlib
import serial
LINK, LOG = 0x10, 0x7F
# opcodes, host -> station
STATION_CONFIGURE, POTI_UPDATE, BTP_DATA_REQUEST, CREDENTIALS_PROVISION, CREDENTIALS_ERASE = 0x01, 0x02, 0x03, 0x04, 0x05
SF_IDCHANGE_SUBSCRIBE, SF_IDCHANGE_UNSUBSCRIBE, SF_IDCHANGE_EVENT_RESPONSE, SF_IDCHANGE_TRIGGER = 0x06, 0x07, 0x08, 0x09
SF_ID_LOCK, SF_ID_UNLOCK, STATUS_REQUEST, RAW_CAPTURE, PKI_STATUS = 0x0A, 0x0B, 0x0C, 0x0D, 0x15
# station -> host
CONFIRM, BTP_DATA_INDICATION, SF_IDCHANGE_EVENT, RAW_FRAME, PKI_REQUEST_DATA, V2X_RX = 0x80, 0x81, 0x82, 0x85, 0x87, 0x90
CODES = {0: "accepted", 1: "invalid_argument", 2: "unsupported", 3: "wrong_entry_point", 4: "security_unavailable",
5: "resource_limit", 6: "rejected", 7: "time_regression", 8: "identity_change_pending", 0x10: "unknown_opcode",
0x11: "malformed", 0x12: "not_configured", 0x13: "busy", 0x14: "no_credentials"}
ACCEPTED, INVALID_ARGUMENT, UNSUPPORTED, RESOURCE_LIMIT, REJECTED, TIME_REGRESSION = 0, 1, 2, 5, 6, 7
UNKNOWN_OPCODE, MALFORMED, NOT_CONFIGURED, NO_CREDENTIALS = 0x10, 0x11, 0x12, 0x14
ITS_EPOCH_UNIX_MS = 1072915200000 # 2004-01-01T00:00:00Z
LEAP_SECONDS_MS = 5000 # TimestampIts counts TAI: 5 leap seconds ahead of UTC
MAX_FRAME_PAYLOAD = 1536 # serial_link.hpp maximum_payload
MAX_MESSAGE = 512 # link message, header included
REQUEST_MAX = 1536 # complete host-to-station body
PANIC_PATTERNS = re.compile(r"Guru Meditation|abort\(\)|assert failed|Task watchdog|stack overflow|panic|Backtrace:|"
r"CORRUPT HEAP|heap_caps_|LoadProhibited|StoreProhibited|Illegal instruction|rst:0x(?!15)|"
r"Rebooting|Brownout|brownout", re.I)
STATUS_FIELDS = ( # name, offset, struct format; the 131-octet snapshot (link_protocol.cpp encode(Status))
("uptime_ms", 0, "<I"), ("configured", 4, "<B"), ("change_pending", 21, "<B"), ("tickets", 22, "<B"),
("signed_messages", 23, "<I"), ("refused_no_ticket", 27, "<I"), ("refused_change_pending", 31, "<I"),
("refused_permission", 35, "<I"), ("sign_failed", 39, "<I"), ("verified", 43, "<I"), ("rejected", 47, "<I"),
("requests_accepted", 51, "<I"), ("requests_refused", 55, "<I"), ("indications", 59, "<I"),
("radio_submitted", 63, "<I"), ("radio_failed", 67, "<I"), ("radio_received", 71, "<I"), ("radio_dropped", 75, "<I"),
("link_rx_frames", 79, "<I"), ("link_crc_errors", 83, "<I"), ("link_malformed", 87, "<I"), ("poti_updates", 91, "<I"),
("its_time_ms", 95, "<Q"), ("cbr_local", 103, "<H"), ("cbr_global", 105, "<H"), ("dcc_delta", 107, "<H"),
("heap_free", 111, "<I"), ("heap_min_free", 115, "<I"), ("heap_largest", 119, "<I"), ("dma_largest", 123, "<I"),
("temp_deci", 127, "<h"), ("battery_mv", 129, "<H"),
)
def crc16(data, crc=0xFFFF):
"""CRC-16/CCITT-FALSE, the frame checksum."""
for b in data:
crc ^= b << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
return crc
def frame(ftype, payload, bad_crc=False):
head = bytes([ftype]) + struct.pack("<H", len(payload))
crc = crc16(head + payload)
if bad_crc:
crc ^= 0x5A5A
return b"\xAA\x55" + head + payload + struct.pack("<H", crc)
def link_message(opcode, seq, body=b"", flags=0):
return bytes([opcode, flags]) + struct.pack("<H", seq & 0xFFFF) + body
def timestamp_its(offset_ms=0):
return int(time.time() * 1000) - ITS_EPOCH_UNIX_MS + LEAP_SECONDS_MS + offset_ms
def parse_status(detail):
"""131-octet STATUS (or one of its older, shorter forms) -> dict, or None."""
if len(detail) not in (111, 127, 129, 131):
return None
out = {}
for name, off, fmt in STATUS_FIELDS:
if off + struct.calcsize(fmt) <= len(detail):
out[name] = struct.unpack_from(fmt, detail, off)[0]
out["raw_len"] = len(detail)
return out
# ---------------------------------------------------------------- message bodies --------------------------
def configure_body(secured=False, power=5, channel=180, station_type=2, beaconing=0, mac=None, radio=2):
"""STATION_CONFIGURE: the 6-octet form, or with `mac` the 16-octet form that names the MAC."""
if mac is None and radio == 2:
return struct.pack("<BHBBB", station_type, channel, power, 1 if secured else 0, beaconing)
mac = mac or bytes([2, 0xB3, 0x0A, 0xCE, 0, 1])
# type, security, address_configuration 0 (AUTO: the MID below), mid, beaconing, channel, power, radio, DP2, 1 s
return struct.pack("<BBB6sBHBBBB", station_type, 1 if secured else 0, 0, mac, beaconing, channel, power, radio, 2, 5)
def poti_body(lat=535546667, lon=100223889, offset_ms=0, speed_cms=0, flags=0x02 | 0x08):
"""POTI_UPDATE: Hamburg St. Georg, standing still, position accuracy indicator set."""
return struct.pack("<QiiHHHBiHH", timestamp_its(offset_ms), lat, lon, 300, 300, 0, flags, 0, speed_cms, 0)
def btp_body(payload, secured=False, port=2001, aid=36, permissions=bytes.fromhex("010000"), btp_type=1,
transport=1, profile=None, generated_at_ms=None, context=b"", extra=b""):
"""BTP_DATA_REQUEST. profile None: 1 unsecured / 2 secured by `secured`. Destination area only for transport 3."""
if profile is None:
profile = 2 if secured else 1
body = (struct.pack("<BHHBBBBBBHHI", btp_type, port, 0, transport, 1, profile, 0xFF, 0xFF, 0, 0, 0, aid)
+ bytes([len(permissions)]) + permissions + bytes([len(context)]) + context)
if transport == 3:
body += struct.pack("<BiiHHH", 0, 535546667, 100223889, 50, 0, 0)
body += struct.pack("<H", len(payload)) + payload
if generated_at_ms is not None:
body += struct.pack("<Q", generated_at_ms)
return body + extra
def max_btp_payload(permissions=b"\x01\x00\x00"):
"""Largest fl_sdu that keeps the whole request body at 1536 octets."""
return REQUEST_MAX - (19 + 1 + len(permissions) + 1 + 2)
# ---------------------------------------------------------------- test payloads ----------------------------
TEST_STATION_ID = 0x7E57B0A7
TEST_MESSAGE_ID = 0xF1 # not an assigned ETSI messageID: a receiver that decodes it as a CAM refuses it
def test_payload(run_id, seq, size):
"""A payload that no ITS receiver will take for a real message and that proves its own integrity.
ItsPduHeader (protocolVersion 2, messageID 0xF1, stationId 0x7E57B0A7), u32 run id, u32 sequence, u16 size, pseudo-random
filler seeded by (run, seq), CRC-32 of everything before it. At least 24 octets.
"""
size = max(24, size)
head = bytes([2, TEST_MESSAGE_ID]) + struct.pack(">I", TEST_STATION_ID) + struct.pack("<IIH", run_id, seq, size)
rnd = random.Random((run_id << 32) | seq)
filler = bytes(rnd.getrandbits(8) for _ in range(size - len(head) - 4))
body = head + filler
return body + struct.pack("<I", zlib.crc32(body))
def check_test_payload(payload):
"""(run_id, seq, size, ok) of a test payload; ok False when the size or the CRC is wrong. None if not ours."""
if len(payload) < 24 or payload[0] != 2 or payload[1] != TEST_MESSAGE_ID or payload[2:6] != struct.pack(">I", TEST_STATION_ID):
return None
run_id, seq, size = struct.unpack_from("<IIH", payload, 6)
ok = size == len(payload) and zlib.crc32(payload[:-4]) == struct.unpack("<I", payload[-4:])[0]
return run_id, seq, size, ok
# ---------------------------------------------------------------- the link ---------------------------------
class Reply:
def __init__(self, code, detail, latency):
self.code, self.detail, self.latency = code, detail, latency
@property
def name(self):
return CODES.get(self.code, "0x%02x" % self.code)
def __repr__(self):
return "Reply(%s, %d detail octets)" % (self.name, len(self.detail))
class Link:
"""One open station-link session over USB. A background thread decodes frames; everything is thread safe."""
def __init__(self, port, outdir, baud=115200, echo=None):
self.port, self.baud, self.outdir = port, baud, outdir
self.echo = echo or (lambda s: None)
self.ser = None
self.lock = threading.Lock()
self.pending = {} # seq -> [Event, Reply|None, sent_at]
self._seq = random.randrange(1000, 30000)
self.reader = None
self.stop = threading.Event()
self.v2x_rx = collections.deque(maxlen=20000) # (t, body) complete V2X_RX messages
self.raw_frames = collections.deque(maxlen=20000) # (t, flags, rssi, 802.11 frame)
self.counts = collections.Counter() # frames_ok, frames_bad_crc, opcodes, fragments, ...
self.frag = {} # (opcode, seq) -> [total, bytearray, t]
self.log_lines = collections.deque(maxlen=5000)
self.noise = bytearray() # bytes outside frames: ROM boot text, panic output
self.boots = 0 # "ESP-ROM:" banners seen on the port since open
self.panics = [] # (t, line) of every line matching PANIC_PATTERNS
self.opened_at = 0.0
os.makedirs(outdir, exist_ok=True)
self.app_version = self.app_compile_time = self.app_project = None # from the boot log (esp app_init lines)
self.logfile = open(os.path.join(outdir, "device.log"), "a", encoding="utf-8", buffering=1)
self.bootfile = open(os.path.join(outdir, "boot.log"), "a", encoding="utf-8", errors="replace", buffering=1)
self.statuslog = open(os.path.join(outdir, "status.csv"), "a", encoding="utf-8", buffering=1)
if self.statuslog.tell() == 0:
self.statuslog.write("time,phase," + ",".join(n for n, _, _ in STATUS_FIELDS) + "\n")
# -- open / close
def open(self, boot_wait=4.0, retries=40):
last = None
for _ in range(retries):
try:
self.ser = serial.Serial(self.port, self.baud, timeout=0.05, write_timeout=3)
break
except (serial.SerialException, OSError) as e: # the port briefly disappears when the board resets
last = e
time.sleep(0.5)
else:
raise RuntimeError("cannot open %s: %s" % (self.port, last))
self.ser.dtr = False
self.ser.rts = False
self.stop.clear()
self.opened_at = time.time()
self.boots = 0
self.noise.clear()
self.reader = threading.Thread(target=self._read_loop, daemon=True)
self.reader.start()
time.sleep(boot_wait)
def close(self):
self.stop.set()
if self.reader:
self.reader.join(2)
if self.ser:
try:
self.ser.close()
except Exception:
pass
self.ser = None
def reboot(self, boot_wait=4.0):
"""Close and reopen the port: the board resets. Clears the receive queues."""
self.close()
time.sleep(0.7)
self.open(boot_wait)
self.v2x_rx.clear()
self.raw_frames.clear()
self.frag.clear()
with self.lock:
self.pending.clear()
# -- reader thread
def _read_loop(self):
buf = bytearray()
while not self.stop.is_set():
try:
data = self.ser.read(4096)
except (serial.SerialException, OSError, AttributeError, TypeError):
time.sleep(0.2)
continue
if not data:
continue
buf += data
while True:
i = buf.find(b"\xAA\x55")
if i < 0:
if len(buf) > 8192:
self._noise(bytes(buf[:-2]))
del buf[:-2]
break
if i > 0:
self._noise(bytes(buf[:i]))
del buf[:i]
if len(buf) < 7:
break
ftype, n = buf[2], struct.unpack("<H", buf[3:5])[0]
if n > MAX_FRAME_PAYLOAD:
del buf[:2]
self.counts["frames_bad_length"] += 1
continue
if len(buf) < 5 + n + 2:
break
payload = bytes(buf[5:5 + n])
got = struct.unpack("<H", buf[5 + n:7 + n])[0]
if got != crc16(bytes(buf[2:5 + n])):
del buf[:2] # resync at the next marker
self.counts["frames_bad_crc"] += 1
continue
del buf[:5 + n + 2]
self.counts["frames_ok"] += 1
try:
self._frame(ftype, payload)
except Exception as e: # a bug here must not kill the reader
self.counts["frame_handler_errors"] += 1
self.echo("reader: %r" % e)
def _noise(self, data):
self.noise += data
text = data.decode("utf-8", "replace")
if "ESP-ROM:" in text:
self.boots += 1
for line in text.splitlines():
if PANIC_PATTERNS.search(line):
self.panics.append((time.time(), line.strip()))
self.bootfile.write(text)
for key, attr in (("App version:", "app_version"), ("Compile time:", "app_compile_time"), ("Project name:", "app_project")):
m = re.search(re.escape(key) + r"[ \t]*([^\r\n]+)", text)
if m:
setattr(self, attr, m.group(1).strip())
def _frame(self, ftype, payload):
now = time.time()
if ftype == LOG:
text = payload.decode("utf-8", "replace").rstrip()
self.log_lines.append((now, text))
self.logfile.write("%.3f %s\n" % (now, text))
if PANIC_PATTERNS.search(text):
self.panics.append((now, text))
return
if ftype != LINK or len(payload) < 4:
self.counts["frames_other_type"] += 1
return
op, flags, seq = payload[0], payload[1], struct.unpack("<H", payload[2:4])[0]
body = payload[4:]
self.counts["op_0x%02x" % op] += 1
if flags:
body = self._reassemble(op, flags, seq, body, now)
if body is None:
return
if op == CONFIRM:
with self.lock:
p = self.pending.get(seq)
if p and len(body) >= 2:
p[1] = Reply(body[0], body[2:2 + body[1]], now - p[2])
p[0].set()
else:
self.counts["confirm_unmatched"] += 1
elif op == V2X_RX:
self.v2x_rx.append((now, body))
elif op == RAW_FRAME:
if len(body) >= 20 and body[6:10] == b"ITS5":
n = struct.unpack("<H", body[18:20])[0]
self.raw_frames.append((now, body[4], struct.unpack("<b", body[5:6])[0], bytes(body[20:20 + n])))
else:
self.counts["raw_frame_malformed"] += 1
def _reassemble(self, op, flags, seq, body, now):
"""Strict host-side reassembly (spec: validate length + offset, drop gaps/duplicates, complete exactly)."""
key = (op, seq)
for k in [k for k, v in self.frag.items() if now - v[2] > 2.0]:
del self.frag[k]
self.counts["frag_timeouts"] += 1
if len(body) < 4:
self.counts["frag_errors"] += 1
return None
total, offset = struct.unpack("<HH", body[:4])
data = body[4:]
cur = self.frag.get(key)
if flags == 1:
if cur is not None:
self.counts["frag_restarted"] += 1
if offset != 0:
self.counts["frag_errors"] += 1
return None
cur = self.frag[key] = [total, bytearray(), now]
elif cur is None:
self.counts["frag_orphans"] += 1
return None
if cur[0] != total or len(cur[1]) != offset:
self.counts["frag_errors"] += 1
del self.frag[key]
return None
cur[1] += data
cur[2] = now
if flags == 3:
del self.frag[key]
if len(cur[1]) != total:
self.counts["frag_errors"] += 1
return None
self.counts["frag_complete"] += 1
return bytes(cur[1])
if len(cur[1]) >= total:
self.counts["frag_errors"] += 1
del self.frag[key]
return None
# -- sending
def next_seq(self):
self._seq = (self._seq + 1) & 0xFFFF or 1
return self._seq
def write(self, data):
with self.lock:
ser = self.ser
if ser is None:
raise RuntimeError("port closed")
ser.write(data)
def send(self, opcode, body=b"", seq=None, flags=0):
seq = self.next_seq() if seq is None else seq
self.write(frame(LINK, link_message(opcode, seq, body, flags)))
return seq
def request(self, opcode, body=b"", timeout=2.0, seq=None):
"""Send one request and wait for its CONFIRM; Reply or None on timeout.
A body that does not fit one 512-octet link message is sent in fragments, as the spec requires (the station
silently ignores an unfragmented message over 512 octets).
"""
seq = self.next_seq() if seq is None else seq
ev = [threading.Event(), None, time.time()]
with self.lock:
self.pending[seq] = ev
try:
if len(body) > MAX_MESSAGE - 4:
self.send_fragmented(opcode, body, seq=seq, cap=MAX_MESSAGE - 8)
else:
self.write(frame(LINK, link_message(opcode, seq, body)))
ev[0].wait(timeout)
return ev[1]
finally:
with self.lock:
self.pending.pop(seq, None)
def send_fragmented(self, opcode, body, seq=None, cap=240, total_override=None):
"""The request fragments of the spec: flags 1/2/3, then u16 total, u16 offset, data. Returns the sequence."""
seq = self.next_seq() if seq is None else seq
total = len(body) if total_override is None else total_override
for off in range(0, len(body), cap):
chunk = body[off:off + cap]
flags = 1 if off == 0 else (3 if off + len(chunk) == len(body) else 2)
self.write(frame(LINK, link_message(opcode, seq, struct.pack("<HH", total, off) + chunk, flags)))
return seq
def request_fragmented(self, opcode, body, timeout=3.0, cap=240):
seq = self.next_seq()
ev = [threading.Event(), None, time.time()]
with self.lock:
self.pending[seq] = ev
try:
self.send_fragmented(opcode, body, seq=seq, cap=cap)
ev[0].wait(timeout)
return ev[1]
finally:
with self.lock:
self.pending.pop(seq, None)
# -- conveniences
def status(self, timeout=2.0):
r = self.request(STATUS_REQUEST, b"", timeout)
if r is None or r.code != ACCEPTED:
return None
s = parse_status(r.detail)
if s is not None:
s["_t"] = time.time()
return s
def wait_status(self, timeout=15.0):
"""Poll STATUS until the board answers (after a reset), or None."""
end = time.time() + timeout
while time.time() < end:
s = self.status(1.0)
if s:
return s
return None
def log_status(self, s, phase):
if s:
self.statuslog.write("%.3f,%s,%s\n" % (s["_t"], phase, ",".join(str(s.get(n, "")) for n, _, _ in STATUS_FIELDS)))
def configure(self, secured=False, power=5, mac=None, timeout=5.0, **kw):
r = self.request(STATION_CONFIGURE, configure_body(secured=secured, power=power, mac=mac, **kw), timeout)
return r
def raw_capture(self, mode, timeout=2.0):
return self.request(RAW_CAPTURE, bytes([mode]), timeout)
def poti(self, **kw):
self.send(POTI_UPDATE, poti_body(**kw))
def drain_log(self, since):
return [t for (ts, t) in self.log_lines if ts >= since]
@@ -0,0 +1,55 @@
# Overnight run of the PC-side firmware tests (obu-firmware/test/host): the whole suite once, then the mutation fuzzer of
# gn_unwrap_its with a new seed and a long iteration count until the time is up. Needs MSYS2 UCRT64 (gcc, make) and Python
# 3.11 with asn1tools, as obu-firmware/test/host/README.md describes. It needs no board.
#
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\run_host_tests_overnight.ps1 -Hours 8
#
# Output: obu-firmware\test\results\host-<time>\ (suite.log, fuzz-<seed>.log, summary.txt). Exit code 1 if anything failed.
param(
[double]$Hours = 8,
[int]$FuzzIterations = 200000000,
[string]$Msys = "C:\msys64"
)
$ErrorActionPreference = "Continue"
$root = Resolve-Path (Join-Path $PSScriptRoot "..\..") # obu-firmware
$hostDir = Join-Path $root "test\host"
$out = Join-Path $root ("test\results\host-" + (Get-Date -Format "yyyyMMdd-HHmmss"))
New-Item -ItemType Directory -Force $out | Out-Null
$summary = Join-Path $out "summary.txt"
function Log($m) { $line = "{0} {1}" -f (Get-Date -Format "HH:mm:ss"), $m; Write-Host $line; Add-Content -Path $summary -Value $line }
$bin = Join-Path $Msys "ucrt64\bin"
if (-not (Test-Path (Join-Path $bin "gcc.exe"))) {
Log "gcc not found in $bin. Install MSYS2 UCRT64 (obu-firmware/test/host/README.md, Option B) or pass -Msys."
exit 2
}
$env:PATH = "$bin;" + (Join-Path $Msys "usr\bin") + ";$env:PATH"
$pyLocal = Join-Path $env:LOCALAPPDATA "Programs\Python\Python311\python.exe"
$pyArg = if (Get-Command py -ErrorAction SilentlyContinue) { "py -3.11" } elseif (Test-Path $pyLocal) { "`"$pyLocal`"" } else { "python" }
Set-Location $hostDir
$failed = 0
Log "make clean; make check (chain, replay with asn1tools, fuzz, battery, firmware unit tests, fragments)"
& make clean *> $null
& make check "PYTHON_ASN1=$pyArg" *> (Join-Path $out "suite.log")
if ($LASTEXITCODE -ne 0) { $failed++; Log "make check FAILED (exit $LASTEXITCODE): see suite.log" } else { Log "make check passed" }
Select-String -Path (Join-Path $out "suite.log") -Pattern "RESULT:|FAIL|CRASH" | Select-Object -First 20 | ForEach-Object { Log (" " + $_.Line.Trim()) }
$end = (Get-Date).AddHours($Hours)
$seed = 100
$runs = 0
while ((Get-Date) -lt $end) {
$seed++
$log = Join-Path $out ("fuzz-{0}.log" -f $seed)
Log "fuzz seed $seed, $FuzzIterations iterations"
& make fuzz "FUZZ_ITER=$FuzzIterations" "FUZZ_SEED=$seed" *> $log
$runs++
if ($LASTEXITCODE -ne 0 -or (Select-String -Path $log -Pattern "CRASH" -Quiet)) {
$failed++
Log " FUZZ FAILURE with seed $seed (exit $LASTEXITCODE): see fuzz-$seed.log, which lists the input as hex"
}
}
Log "finished: $runs fuzz runs after the suite, $failed failure(s)"
exit ([int]($failed -gt 0))
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""Overnight firmware test of one micrOBU board on a USB port (station-link, revision 3).
py -3.11 obu-firmware/test/bench/run_overnight.py COM6 --hours 8 --provision-demo # COM6 = the spare board; 'auto' if only one is plugged in
py -3.11 obu-firmware/test/bench/run_overnight.py COM6 --quick # about 8 minutes, to see that it works
py -3.11 obu-firmware/test/bench/run_overnight.py COM6 --hours 8 --no-tx # nothing on the air: protocol, fuzz, idle
(start_overnight.ps1 wraps this with flashing, the host C tests and keep-awake.) It refuses a board whose firmware is not this
checkout's HEAD, because the results would describe another build.
What it does, in order (details in README.md):
1. conformance the link protocol against the spec and the source, on a freshly reset board
2. cycles repeated until the time is up: transmit soak unsigned -> transmit soak signed (needs a ticket) ->
capture-mode toggling -> reconfigure churn -> link fuzz (unconfigured board, never on air) ->
resets -> idle listening
3. conformance again, to see that nothing drifted
4. report results/overnight-<time>/report.txt, results.json, status.csv, device.log
The board is reset every time the port is opened (USB Serial/JTAG), so run it with no other program holding the port
(close Android Studio's serial monitor, tools/station_status_watch.py, the phone app's USB link).
On the air: transmit phases send unsecured or signed frames at a few Hz and 5 dBm (--power) on channel 180 whose
payload is not a valid ITS message (ItsPduHeader messageID 0xF1). --no-tx keeps the radio silent. --provision-demo
writes the throwaway demo certificate chain from app/src/main/assets/demo-chain.vcr to the board's NVS, which is what
the phone app does on its first connection; without it the signed phases are skipped.
Exit status: 0 if no check failed, 1 otherwise, 2 if the board does not speak the station link.
"""
import argparse
import datetime
import os
import sys
import time
import traceback
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bench_conformance
import bench_fuzz
import bench_soak
import linklib as ll
from bench_common import Ctx, FAIL, INFO, PASS, Results, WARN, slope_per_hour
HERE = os.path.dirname(os.path.abspath(__file__))
RESULTS = os.path.normpath(os.path.join(HERE, "..", "results"))
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("port", nargs="?", default="auto",
help="serial port of the spare board, e.g. COM6; default 'auto' = the one Espressif native-USB board that is plugged in")
ap.add_argument("--allow-stale-firmware", action="store_true",
help="run even if the board's firmware is not this checkout's HEAD (default: refuse, the results would describe another build)")
ap.add_argument("--hours", type=float, default=8.0, help="total run time (default 8)")
ap.add_argument("--quick", action="store_true", help="about 6 minutes in all: one short pass of every phase")
ap.add_argument("--no-tx", action="store_true", help="never transmit: skips every phase that needs the radio to emit")
ap.add_argument("--provision-demo", action="store_true", help="write the demo certificate chain to the board if it has no ticket")
ap.add_argument("--power", type=int, default=5, help="transmit power in dBm (default 5)")
ap.add_argument("--rate", type=float, default=4.0, help="frames per second in the soak phases (default 4)")
ap.add_argument("--phase-minutes", type=float, default=10.0, help="length of each soak phase (default 10)")
ap.add_argument("--fuzz-seed", type=int, help="replay a fuzz run")
ap.add_argument("--out", help="result folder (default obu-firmware/test/results/overnight-<time>)")
args = ap.parse_args()
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
outdir = args.out or os.path.join(RESULTS, "overnight-" + stamp)
os.makedirs(outdir, exist_ok=True)
logf = open(os.path.join(outdir, "run.log"), "a", encoding="utf-8", buffering=1)
def echo(msg):
line = "%s %s" % (datetime.datetime.now().strftime("%H:%M:%S"), msg)
print(line, flush=True)
logf.write(line + "\n")
args.port = resolve_port(args.port, echo)
if args.port is None:
return 2
link = ll.Link(args.port, outdir, echo=echo)
res = Results(outdir, echo=echo)
ctx = Ctx(link, res, args, outdir)
total_s = (8 * 60 if args.quick else args.hours * 3600)
ctx.deadline = time.time() + total_s
phase_s = 20 if args.quick else args.phase_minutes * 60
echo("results in %s" % outdir)
echo("run for %.1f h, port %s, tx %s, power %d dBm" % (total_s / 3600, args.port, "off" if args.no_tx else "on", args.power))
try:
link.open()
except Exception as e:
echo("cannot open %s: %s" % (args.port, e))
return 2
first = link.wait_status(20)
if first is None:
echo("no STATUS reply from the board: is it running obu-firmware, and is nothing else holding the port?")
echo("device said: %s" % (list(link.log_lines)[-5:] or bytes(link.noise[-300:])))
return 2
echo("board answers: uptime %d ms, heap_free %d, tickets %d, battery %d mV" % (first["uptime_ms"], first["heap_free"], first["tickets"], first["battery_mv"]))
if not check_firmware_version(ctx, echo) and not args.allow_stale_firmware:
echo("refusing to test a stale build: flash this checkout first (start_overnight.ps1 -Flash, or obu-firmware/FLASHING.md), "
"or pass --allow-stale-firmware")
return 2
def guarded(name, fn, *a, **kw):
"""Run one phase; a serial error or a bug in it is recorded, the port is reopened and the run goes on."""
if ctx.time_left() < 5:
return
echo("-- %s" % name)
ctx.phase = name
t0 = time.time()
try:
fn(*a, **kw)
except Exception as e:
res.add(name, "phase aborted by an exception", FAIL, "%r\n%s" % (e, traceback.format_exc()[-600:]))
echo(" exception: %r" % e)
try:
link.close()
time.sleep(1.0)
link.open()
except Exception as e2:
echo(" cannot reopen the port: %r" % e2)
if link.panics:
for t, line in link.panics:
res.add(name, "panic/error text on the console", FAIL, line[:200])
link.panics.clear()
res.write()
echo(" %s took %.0f s; PASS %d FAIL %d WARN %d" % (name, time.time() - t0, res.count(PASS), res.count(FAIL), res.count(WARN)))
guarded("conformance", bench_conformance.run, ctx) # also finds out whether the board holds a ticket
echo("board holds a ticket: %s" % ctx.credentials)
if args.provision_demo and not ctx.credentials and not args.no_tx:
guarded("provision", bench_soak.provision_demo, ctx)
cycle = 0
while ctx.time_left() > 30:
cycle += 1
echo("== cycle %d, %.1f h left" % (cycle, ctx.time_left() / 3600))
guarded("soak-unsigned", bench_soak.tx_phase, ctx, "soak-unsigned", phase_s, False, rate_hz=args.rate, power=args.power)
if ctx.credentials:
guarded("soak-signed", bench_soak.tx_phase, ctx, "soak-signed", phase_s, True, rate_hz=min(args.rate, 3.0), power=args.power, sizes=bench_soak.SIGNED_SIZES)
guarded("raw-toggle", bench_soak.raw_toggle_phase, ctx, "raw-toggle", (phase_s if args.quick else max(60, phase_s * 0.3)), power=args.power)
guarded("reconfigure", bench_soak.reconfigure_phase, ctx, "reconfigure", (phase_s if args.quick else max(45, phase_s * 0.3)), power=args.power)
guarded("fuzz", bench_fuzz.run, ctx, (phase_s if args.quick else max(30, phase_s * 0.3)), seed=(args.fuzz_seed if args.fuzz_seed is not None and cycle == 1 else None))
guarded("resets", bench_soak.reset_cycles, ctx, "resets", 2 if args.quick else 5)
guarded("idle-listen", bench_soak.idle_listen_phase, ctx, "idle-listen", (phase_s if args.quick else max(60, phase_s * 0.5)))
if args.quick:
break
ctx.deadline = None
guarded("conformance-final", bench_conformance.run, ctx)
analyse_heap(ctx)
summarise_rx(ctx)
text = res.write()
link.close()
echo("")
echo(text)
echo("report: %s" % os.path.join(outdir, "report.txt"))
return 1 if res.failures() else 0
def resolve_port(port, echo):
"""'auto' picks the single Espressif native-USB serial port (VID 303A) that is plugged in; anything else is used as given."""
if port.lower() != "auto":
return port
from serial.tools import list_ports
found = [p for p in list_ports.comports() if p.vid == 0x303A]
if len(found) == 1:
echo("port: %s (%s)" % (found[0].device, found[0].description))
return found[0].device
if not found:
echo("no Espressif USB serial port (VID 303A) found: plug in the spare board, or name the port")
else:
echo("several Espressif boards are plugged in (%s): name the spare one, e.g. COM6" % ", ".join(p.device for p in found))
return None
def check_firmware_version(ctx, echo):
"""Record which firmware the board runs and whether it is the one in this checkout. True if it is (or HEAD is unknown)."""
import subprocess
L, R = ctx.link, ctx.res
board = L.app_version or "unknown"
try:
head = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=HERE, capture_output=True, text=True, timeout=10).stdout.strip()
except Exception:
head = ""
echo("firmware on the board: %s, built %s (%s); this checkout is at %s" % (board, L.app_compile_time, L.app_project, head or "?"))
R.add("firmware", "board runs", INFO, "version %s, compiled %s, project %s; checkout HEAD %s" % (board, L.app_compile_time, L.app_project, head or "?"))
if head and board.split("-")[0] != head:
R.add("firmware", "the board does not run this checkout's firmware", WARN,
"board %s, checkout %s: results describe the board's build, not the source here (flash it: obu-firmware/FLASHING.md)" % (board, head))
return False
return True
def analyse_heap(ctx):
"""Leak check on the quiet-moment heap readings: per phase kind, and the lowest the heap ever got."""
R = ctx.res
S = "heap"
if not ctx.heap:
return
by_phase = {}
for t, phase, free, minimum, largest, uptime in ctx.heap:
by_phase.setdefault(phase, []).append((t, free, minimum, largest, uptime))
lowest = min(p[2] for pts in by_phase.values() for p in pts)
R.add(S, "lowest free heap ever seen by the station (heap_min_free)", INFO, "%d octets" % lowest)
R.ok(S, "heap_min_free stays above 16 KB", lowest > 16384, "%d" % lowest, WARN)
for phase, pts in sorted(by_phase.items()):
# compare like with like: a reading taken after a phase's work, from reset to reset the heap legitimately starts over,
# so only readings of one uptime lineage (monotonic uptime) go into a slope
lineage, prev = [], None
for t, free, minimum, largest, uptime in pts:
if prev is not None and uptime < prev:
lineage = []
lineage.append((t, free, largest))
prev = uptime
if len(lineage) >= 4:
sl = slope_per_hour([(t, f) for t, f, _ in lineage])
sl_big = slope_per_hour([(t, l) for t, _, l in lineage])
level = PASS
if sl is not None and sl < -2048:
level = WARN
if sl is not None and sl < -20480:
level = FAIL
R.add(S, "%s: free heap trend over %d readings (no reset in between)" % (phase, len(lineage)), level,
"%+.0f octets/hour free, %+.0f octets/hour largest block; first %d, last %d" %
(sl or 0, sl_big or 0, lineage[0][1], lineage[-1][1]))
ctx.link.statuslog.flush()
def summarise_rx(ctx):
R = ctx.res
if ctx.rx_stats:
R.add("rx", "everything the radio heard on the air during the run (V2X_RX)", 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)))
else:
R.add("rx", "nothing was heard on the air during the run", INFO, "no other ITS station in range of this board, or the radio was never on")
c = ctx.link.counts
R.add("link", "host-side counters", INFO, ", ".join("%s %d" % kv for kv in sorted(c.items()) if not kv[0].startswith("op_") and kv[0] != "confirm_unmatched"))
if c["frames_bad_crc"]:
R.add("link", "frames from the board with a bad CRC", WARN, "%d (USB corruption or a board-side write cut short)" % c["frames_bad_crc"])
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,104 @@
# Checks (and, unless -CheckOnly, installs) everything a PC needs to flash and test the spare micrOBU board overnight:
# git, Python 3.11 + pyserial + asn1tools, MSYS2 gcc + make, ESP-IDF 6.0.2 for the ESP32-C5. Safe to run again: a step that is
# already satisfied is left alone. Needs internet (winget, GitHub, pacman, Espressif's download servers; about 3 GB, 20-40 min).
#
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\setup_workstation.ps1 -CheckOnly # just report
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\setup_workstation.ps1 # install what is missing
# ... -PreventSleep also turns off sleep, display-off and USB selective suspend while on mains (an overnight run needs it)
#
# What each step is for is in obu-firmware/test/bench/README.md ("Setting up a workstation"). Exit code 1 if something is
# still missing at the end.
param(
[switch]$CheckOnly,
[switch]$PreventSleep,
[string]$IdfVersion = "v6.0.2",
[string]$IdfToolsPath = "C:\Espressif",
[string]$Msys = "C:\msys64"
)
$ErrorActionPreference = "Stop"
$report = New-Object System.Collections.Generic.List[object]
function Add-Row($name, $ok, $detail) { $report.Add([pscustomobject]@{ Step = $name; OK = $(if ($ok) { "ok" } else { "MISSING" }); Detail = $detail }) }
function Have-Winget { [bool](Get-Command winget -ErrorAction SilentlyContinue) }
function Winget-Install($id) {
if (-not (Have-Winget)) { throw "winget is not available: install '$id' by hand (Microsoft Store: App Installer)" }
& winget install -e --id $id --accept-source-agreements --accept-package-agreements
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne -1978335189) { throw "winget install $id failed ($LASTEXITCODE)" } # -1978335189: already installed, nothing to do
$env:PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [Environment]::GetEnvironmentVariable("PATH", "User")
}
function Find-Python {
if (Get-Command py -ErrorAction SilentlyContinue) { $v = & py -3.11 --version 2>$null; if ($LASTEXITCODE -eq 0) { return @("py", "-3.11") } }
$p = Join-Path $env:LOCALAPPDATA "Programs\Python\Python311\python.exe"
if (Test-Path $p) { return @($p) }
return $null
}
function Run-Python($py, [string[]]$a) { $rest = @(); if ($py.Count -gt 1) { $rest = $py[1..($py.Count - 1)] }; & $py[0] @rest @a }
# ---- 1. git -------------------------------------------------------------------------------------------------------
$haveGit = [bool](Get-Command git -ErrorAction SilentlyContinue)
if (-not $haveGit -and -not $CheckOnly) { Winget-Install "Git.Git"; $haveGit = [bool](Get-Command git -ErrorAction SilentlyContinue) }
Add-Row "git" $haveGit $(if ($haveGit) { (& git --version) } else { "winget install -e --id Git.Git" })
if ($haveGit -and -not $CheckOnly) { & git config --global core.longpaths true } # ESP-IDF's tree has paths past 260 characters
# ---- 2. Python 3.11 + pyserial + asn1tools --------------------------------------------------------------------------
$py = Find-Python
if (-not $py -and -not $CheckOnly) { Winget-Install "Python.Python.3.11"; $py = Find-Python }
Add-Row "python 3.11" ([bool]$py) $(if ($py) { (Run-Python $py @("--version")) } else { "winget install -e --id Python.Python.3.11" })
if ($py) {
foreach ($pair in @(@("pyserial", "serial"), @("asn1tools", "asn1tools"))) {
Run-Python $py @("-c", "import $($pair[1])") 2>$null
$have = ($LASTEXITCODE -eq 0)
if (-not $have -and -not $CheckOnly) { Run-Python $py @("-m", "pip", "install", "--user", $pair[0]); Run-Python $py @("-c", "import $($pair[1])") 2>$null; $have = ($LASTEXITCODE -eq 0) }
Add-Row "pip: $($pair[0])" $have $(if ($have) { "importable" } else { "py -3.11 -m pip install --user $($pair[0])" })
}
}
# ---- 3. MSYS2 UCRT64 gcc + make (the PC-side C tests in obu-firmware/test/host) --------------------------------------
$gcc = Join-Path $Msys "ucrt64\bin\gcc.exe"
$make = Join-Path $Msys "usr\bin\make.exe"
if (-not (Test-Path $gcc) -or -not (Test-Path $make)) {
if (-not $CheckOnly) {
if (-not (Test-Path (Join-Path $Msys "usr\bin\bash.exe"))) { Winget-Install "MSYS2.MSYS2" }
$bash = Join-Path $Msys "usr\bin\bash.exe"
& $bash -lc "pacman -Syu --noconfirm" # the first run may end the shell after updating pacman itself, so it is run twice
& $bash -lc "pacman -Syu --noconfirm"
& $bash -lc "pacman -S --needed --noconfirm mingw-w64-ucrt-x86_64-gcc make"
}
}
$haveC = (Test-Path $gcc) -and (Test-Path $make)
Add-Row "MSYS2 gcc + make" $haveC $(if ($haveC) { "$gcc, $make" } else { "winget install -e --id MSYS2.MSYS2, then pacman -S mingw-w64-ucrt-x86_64-gcc make" })
# ---- 4. ESP-IDF (exactly this version: components/microbu_v2x pins the C5 radio driver ABI to it) ---------------------
$idfDir = Join-Path $IdfToolsPath "frameworks\esp-idf-$IdfVersion"
$idfExport = Join-Path $idfDir "export.ps1"
$envDirs = @(Get-ChildItem (Join-Path $IdfToolsPath "python_env") -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "idf$($IdfVersion.TrimStart('v') -replace '^(\d+\.\d+).*', '$1')_*" })
if ((-not (Test-Path $idfExport) -or -not $envDirs) -and -not $CheckOnly -and $haveGit) {
if (-not (Test-Path $idfExport)) {
New-Item -ItemType Directory -Force (Split-Path $idfDir) | Out-Null
& git clone --branch $IdfVersion --depth 1 --recursive --shallow-submodules https://github.com/espressif/esp-idf.git $idfDir
if ($LASTEXITCODE -ne 0) { throw "git clone of ESP-IDF $IdfVersion failed" }
}
$env:IDF_TOOLS_PATH = $IdfToolsPath
Push-Location $idfDir
try { & .\install.ps1 esp32c5; if ($LASTEXITCODE -ne 0) { throw "ESP-IDF install.ps1 failed" } } finally { Pop-Location }
$envDirs = @(Get-ChildItem (Join-Path $IdfToolsPath "python_env") -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "idf$($IdfVersion.TrimStart('v') -replace '^(\d+\.\d+).*', '$1')_*" })
}
$haveIdf = (Test-Path $idfExport) -and [bool]$envDirs
Add-Row "ESP-IDF $IdfVersion" $haveIdf $(if ($haveIdf) { "$idfDir (python env $($envDirs[0].Name))" } else { "git clone --branch $IdfVersion --recursive https://github.com/espressif/esp-idf.git $idfDir; then .\install.ps1 esp32c5 with IDF_TOOLS_PATH=$IdfToolsPath" })
# ---- 5. sleep (an overnight run dies when Windows sleeps or suspends the USB port) --------------------------------------
if ($PreventSleep -and -not $CheckOnly) {
& powercfg /change standby-timeout-ac 0
& powercfg /change hibernate-timeout-ac 0
& powercfg /change monitor-timeout-ac 0
& powercfg /setacvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 # USB selective suspend: disabled
& powercfg /setactive SCHEME_CURRENT
Add-Row "power plan (on mains)" $true "no sleep, no hibernate, display stays on, USB selective suspend off"
} else {
Add-Row "power plan (on mains)" $true "unchanged (start_overnight.ps1 keeps Windows awake while it runs; -PreventSleep also fixes USB suspend)"
}
$report | Format-Table -AutoSize -Wrap
$missing = @($report | Where-Object { $_.OK -ne "ok" })
if ($missing.Count) { Write-Host "$($missing.Count) step(s) still missing." -ForegroundColor Yellow; exit 1 }
Write-Host "Workstation ready. Next: start_overnight.ps1 -Flash -Hours 8 (README.md, 'Setting up a workstation')." -ForegroundColor Green
@@ -0,0 +1,84 @@
# One command for the overnight run on the SPARE board (no battery): optionally builds and flashes this checkout's firmware,
# runs the PC-side C tests in the background, runs the board tests, and keeps Windows awake meanwhile.
#
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\start_overnight.ps1 -Flash -Hours 8
# ... -Port COM6 name the port (default: the one Espressif native-USB board that is plugged in)
# ... -Quick about 8 minutes on the board, no host fuzz: does everything work?
# ... -NoTx the radio stays silent
# ... -NoHostTests skip the PC-side C tests
#
# Before it: git pull, close everything that holds the port (the phone app, station_status_watch.py, a serial monitor).
# Opening the port resets the board, and the run reconfigures it for hours and writes the demo ticket to its NVS: plug in
# ONLY the spare board (a board without a cell reads about 4000 mV from the USB charger, so battery_mv cannot tell them apart).
param(
[double]$Hours = 8,
[string]$Port = "auto",
[switch]$Flash,
[switch]$Quick,
[switch]$NoTx,
[switch]$NoHostTests,
[string]$IdfVersion = "v6.0.2",
[string]$IdfToolsPath = "C:\Espressif",
[string]$Msys = "C:\msys64"
)
$ErrorActionPreference = "Stop"
$bench = $PSScriptRoot
$fw = (Resolve-Path (Join-Path $bench "..\..")).Path # obu-firmware
$py = if (Get-Command py -ErrorAction SilentlyContinue) { @("py", "-3.11") } else { @(Join-Path $env:LOCALAPPDATA "Programs\Python\Python311\python.exe") }
function Run-Python([string[]]$a) { $rest = @(); if ($py.Count -gt 1) { $rest = $py[1..($py.Count - 1)] }; & $py[0] @rest @a }
# Keep Windows awake for as long as this PowerShell process lives.
Add-Type -Namespace Win -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'
[void][Win.Power]::SetThreadExecutionState(0x80000001) # ES_CONTINUOUS | ES_SYSTEM_REQUIRED
# Which board: the one Espressif native-USB port, unless named.
if ($Port -eq "auto") {
$found = @(Run-Python @("-c", "from serial.tools import list_ports; print(' '.join(p.device for p in list_ports.comports() if p.vid == 0x303A))") -split "\s+" | Where-Object { $_ })
if ($found.Count -ne 1) { Write-Host "Found $($found.Count) Espressif USB boards ($($found -join ', ')): pass -Port COMx." -ForegroundColor Red; exit 2 }
$Port = $found[0]
}
Write-Host "Board port: $Port"
if ($Flash) {
$idf = Join-Path $IdfToolsPath "frameworks\esp-idf-$IdfVersion\export.ps1"
if (-not (Test-Path $idf)) { Write-Host "ESP-IDF $IdfVersion not found at ${idf}: run setup_workstation.ps1 first." -ForegroundColor Red; exit 2 }
# A fresh PowerShell, so no other IDF's environment is in the way (two exports in one window fail).
$cmd = "`$env:IDF_TOOLS_PATH='$IdfToolsPath'; Remove-Item Env:IDF_PYTHON_ENV_PATH,Env:IDF_PATH -ErrorAction SilentlyContinue; " +
"& '$idf' *> `$null; Set-Location '$fw'; " +
"if (-not (Test-Path build\CMakeCache.txt)) { idf.py set-target esp32c5; if (`$LASTEXITCODE) { exit 1 } }; " +
"idf.py build; if (`$LASTEXITCODE) { exit 1 }; " +
"Set-Location build; python -m esptool --chip esp32c5 -p $Port -b 460800 --before default-reset --after hard-reset write-flash '@flash_args'; exit `$LASTEXITCODE"
Write-Host "Building and flashing (the first build downloads components and takes ~20 minutes) ..."
& powershell -NoProfile -ExecutionPolicy Bypass -Command $cmd
if ($LASTEXITCODE -ne 0) {
Write-Host ("Build or flash failed. If the port was not found or no serial data arrived: unplug the board, hold BOOT, plug in, release, run again; " +
"if the stub flasher will not start, see obu-firmware/FLASHING.md ('--no-stub'). Unplug and replug WITHOUT BOOT afterwards.") -ForegroundColor Red
exit 3
}
Start-Sleep -Seconds 5 # the board re-enumerates after the hard reset
}
# PC-side C tests, in the background (they need no board).
$hostJob = $null
if (-not $NoHostTests -and -not $Quick) {
if (Test-Path (Join-Path $Msys "ucrt64\bin\gcc.exe")) {
$hostJob = Start-Process powershell -PassThru -WindowStyle Minimized -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", (Join-Path $bench "run_host_tests_overnight.ps1"), "-Hours", [string]($Hours - 0.2), "-Msys", $Msys)
Write-Host "PC-side tests started in the background (pid $($hostJob.Id)); results in obu-firmware\test\results\host-*"
} else { Write-Host "MSYS2 gcc not found: skipping the PC-side tests (setup_workstation.ps1 installs it)." -ForegroundColor Yellow }
}
# The board tests.
$runArgs = @((Join-Path $bench "run_overnight.py"), $Port, "--provision-demo")
if ($Quick) { $runArgs += "--quick" } else { $runArgs += @("--hours", [string]$Hours) }
if ($NoTx) { $runArgs += "--no-tx" }
Run-Python $runArgs
$code = $LASTEXITCODE
if ($hostJob) {
Write-Host "Waiting for the PC-side tests ..."
$hostJob.WaitForExit()
Write-Host "PC-side tests exit code: $($hostJob.ExitCode)"
if ($hostJob.ExitCode -ne 0 -and $code -eq 0) { $code = 1 }
}
Write-Host "Board tests exit code: $code. Reports: obu-firmware\test\results\overnight-*\report.txt and host-*\summary.txt"
exit $code
@@ -0,0 +1,97 @@
====================================================================================================
PHONE LOG databases\MicrOBU V2X log - v2x_log_20261123_152248_esp32.db
hardware esp32_c5, phone Google Pixel 9 Pro, app 0.1.0, link ble
20256 messages over 3350 s (first 15:22:48, last 16:18:38)
by type: CAM 16334, DENM 90, MAPEM 1261, SPATEM 2571
====================================================================================================
NODE PCAP databases\its5_20261123_150746.pcap
27367 records, 27366 unwrapped to a CAM/DENM/MAPEM/SPATEM/VAM payload, 1 not (beacons, other BTP ports, unsigned-but-not-GN, truncated)
by type: CAM 17485, DENM 76, MAPEM 3277, SPATEM 6528
signed 322, unsigned 27044, GeoBroadcast 9881, truncated 0
====================================================================================================
CLOCK ALIGNMENT: node clock + 1795443494.178 s = phone clock; spread 25 ms over 12887 shared CAMs; first quarter 1795443494.153 s, last quarter 1795443494.204 s (drift 51 ms)
the node heard 21513 messages inside the phone's recording window (5853 outside it are ignored)
====================================================================================================
WHAT THE NODE HEARD vs WHAT THE PHONE LOGGED (one-to-one, +/-0.50 s, identical bytes)
type bytes signed node phone missed share
CAM 43 unsigned 8240 7873 367 95.5%
CAM 26 unsigned 5218 5014 204 96.1%
SPATEM 888 unsigned 3002 0 3002 0.0%
SPATEM 58 unsigned 2091 2018 73 96.5%
MAPEM 1198 unsigned 1536 0 1536 0.0%
MAPEM 377 unsigned 1034 977 57 94.5%
CAM 43 signed 316 0 316 0.0%
DENM 329 unsigned 48 43 5 89.6%
DENM 311 unsigned 17 16 1 94.1%
DENM 303 unsigned 11 9 2 81.8%
ALL 21513 15950 5563 74.1%
per type: CAM 12887/13774 93.6%; DENM 68/76 89.5%; MAPEM 977/2570 38.0%; SPATEM 2018/5093 39.6%
====================================================================================================
PER SENDING STATION (ItsPduHeader.stationId)
station type node phone share first..last heard by the node
195936478 CAM 8240 7873 95.5% +1 s .. +3350 s
1095348116 CAM 5218 5014 96.1% +1 s .. +3350 s
1095348116 SPATEM 5093 2018 39.6% +1 s .. +3350 s
1095348116 MAPEM 2570 977 38.0% +2 s .. +3350 s
4011198281 CAM 316 0 0.0% +1 s .. +426 s
2829209000 DENM 48 43 89.6% +1103 s .. +1160 s
7798929 DENM 28 25 89.3% +153 s .. +975 s
====================================================================================================
WHEN THE MISSES HAPPEN
miss runs in node order (all types): 3944 runs, longest 4; run length 1: 2390, 2: 1491, 3-4: 63, 5-9: 0, 10+: 0
CAM 887 misses in 662 runs; longest run 5; single-message misses 501 (56 % of the misses)
DENM 8 misses in 6 runs; longest run 2; single-message misses 4 (50 % of the misses)
MAPEM 1593 misses in 55 runs; longest run 1537; single-message misses 52 (3 % of the misses)
SPATEM 3075 misses in 62 runs; longest run 3002; single-message misses 52 (2 % of the misses)
minute by minute (node messages / share the phone logged):
0 s: 218 89.0% 30 s: 223 88.8% 60 s: 201 88.1% 90 s: 216 89.4%
120 s: 201 89.1% 150 s: 239 74.1% 180 s: 202 80.7% 210 s: 229 53.7%
240 s: 206 53.9% 270 s: 231 51.9% 300 s: 216 76.9% 330 s: 215 81.9%
360 s: 221 82.4% 390 s: 205 87.3% 420 s: 204 92.6% 450 s: 179 96.6%
480 s: 200 97.5% 510 s: 180 97.2% 540 s: 195 97.4% 570 s: 182 98.9%
600 s: 193 98.4% 630 s: 188 98.4% 660 s: 186 97.8% 690 s: 193 99.0%
720 s: 184 98.9% 750 s: 204 96.1% 780 s: 179 97.8% 810 s: 197 94.9%
840 s: 186 98.4% 870 s: 193 97.4% 900 s: 180 98.3% 930 s: 201 99.0%
960 s: 201 98.0% 990 s: 181 99.4% 1020 s: 195 99.0% 1050 s: 187 98.9%
1080 s: 202 98.0% 1110 s: 209 98.1% 1140 s: 221 96.8% 1170 s: 187 96.8%
1200 s: 209 96.7% 1230 s: 195 94.9% 1260 s: 192 80.7% 1290 s: 200 75.5%
1320 s: 150 68.7% 1350 s: 202 45.5% 1380 s: 192 48.4% 1410 s: 204 59.8%
1440 s: 168 60.7% 1470 s: 206 59.2% 1500 s: 188 61.2% 1530 s: 192 62.0%
1560 s: 190 63.2% 1590 s: 192 63.5% 1620 s: 200 63.0% 1650 s: 183 66.1%
1680 s: 200 65.5% 1710 s: 177 62.7% 1740 s: 191 61.8% 1770 s: 178 64.6%
1800 s: 198 63.1% 1830 s: 188 63.3% 1860 s: 189 66.7% 1890 s: 199 62.3%
1920 s: 171 64.9% 1950 s: 201 61.2% 1980 s: 177 63.3% 2010 s: 198 64.6%
2040 s: 182 63.7% 2070 s: 200 64.5% 2100 s: 180 63.9% 2130 s: 199 67.3%
2160 s: 192 64.1% 2190 s: 183 62.8% 2220 s: 193 65.3% 2250 s: 182 62.1%
2280 s: 192 63.5% 2310 s: 178 62.4% 2340 s: 198 63.6% 2370 s: 179 63.7%
2400 s: 194 61.9% 2430 s: 193 63.7% 2460 s: 181 64.6% 2490 s: 200 63.5%
2520 s: 185 64.3% 2550 s: 202 63.4% 2580 s: 185 66.5% 2610 s: 202 63.4%
2640 s: 178 62.4% 2670 s: 194 63.4% 2700 s: 184 65.2% 2730 s: 196 63.3%
2760 s: 182 64.8% 2790 s: 77 100.0% 2820 s: 164 70.1% 2850 s: 179 62.6%
2880 s: 198 62.6% 2910 s: 180 62.2% 2940 s: 198 64.1% 2970 s: 180 65.6%
3000 s: 207 63.8% 3030 s: 185 63.2% 3060 s: 203 64.0% 3090 s: 195 64.6%
3120 s: 182 62.6% 3150 s: 196 62.2% 3180 s: 176 61.9% 3210 s: 199 63.8%
3240 s: 189 64.0% 3270 s: 199 62.3% 3300 s: 174 63.2% 3330 s: 138 63.0%
====================================================================================================
WHERE THE MISSES ARE LOST (from the phone's once-a-second link_status rows; the board's counters as the phone read them)
over the run (ble link): board radio_received +15577, radio_dropped (its 16-frame queue overflowed) +0,
link CRC errors 0, malformed 0, app received 20256 link frames, board TX submitted 398 / failed 0
link state per second: connected 3189
board restarts seen (uptime went backwards): 0
the 5563 missed messages, by what the counters did in that second:
5563 no counter moved (not heard by this board's radio, or lost on the BLE/USB hop)
If the last row dominates, the loss is invisible to the phone-side counters: either the phone's board never heard the
frame (different antenna than the node, a collision, the radio held out for a BLE connection event), or a V2X_RX
notification/fragment was dropped on the way (the firmware counts that only in a LOG line the phone cannot see over BLE).
note: 'radio_received' is not compared with the log; it counts frames the board's stack took, not every V2X_RX it forwarded.
====================================================================================================
LARGE MESSAGES (above 494 bytes: sent as link fragments since 2026-11-23) vs small MAPEM/SPATEM
MAPEM+SPATEM > 494 B node 4538 phone 0 0.0%
MAPEM+SPATEM <= 494 B node 3125 phone 2995 95.8%
====================================================================================================
ONLY THE PHONE HEARD (in the log, not in the pcap within +/-0.50 s)
CAM 3447 of 16334 phone messages not in the node's capture (21.1%)
DENM 22 of 90 phone messages not in the node's capture (24.4%)
MAPEM 283 of 1261 phone messages not in the node's capture (22.4%)
SPATEM 553 of 2571 phone messages not in the node's capture (21.5%)
(a node-side miss is a different antenna, a collision, or a node that was busy; read it against the node's own loss)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,63 @@
====================================================================================================
PHONE LOG databases\MicrOBU V2X log - v2x_log_20261123_171249_esp32.db
hardware esp32_c5, phone Google Pixel 9 Pro, app 0.1.0, link ble
3255 messages over 440 s (first 17:12:50, last 17:20:09)
by type: CAM 2186, MAPEM 351, SPATEM 718
====================================================================================================
NODE PCAP databases\its5_20261123_170818.pcap
3292 records, 3292 unwrapped to a CAM/DENM/MAPEM/SPATEM/VAM payload, 0 not (beacons, other BTP ports, unsigned-but-not-GN, truncated)
by type: CAM 2077, MAPEM 392, SPATEM 794, VAM 29
signed 38, unsigned 3254, GeoBroadcast 1186, truncated 0
====================================================================================================
CLOCK ALIGNMENT: node clock + 1795447789.240 s = phone clock; spread 15 ms over 1710 shared CAMs; first quarter 1795447789.238 s, last quarter 1795447789.242 s (drift 4 ms)
the node heard 2773 messages inside the phone's recording window (519 outside it are ignored)
====================================================================================================
WHAT THE NODE HEARD vs WHAT THE PHONE LOGGED (one-to-one, +/-0.50 s, identical bytes)
type bytes signed node phone missed share
CAM 43 unsigned 1070 1069 1 99.9%
CAM 26 unsigned 689 641 48 93.0%
SPATEM 888 unsigned 680 559 121 82.2%
MAPEM 1198 unsigned 334 261 73 78.1%
ALL 2773 2530 243 91.2%
per type: CAM 1710/1759 97.2%; MAPEM 261/334 78.1%; SPATEM 559/680 82.2%
====================================================================================================
PER SENDING STATION (ItsPduHeader.stationId)
station type node phone share first..last heard by the node
195936478 CAM 1070 1069 99.9% +0 s .. +440 s
1095348116 CAM 689 641 93.0% +0 s .. +440 s
1095348116 SPATEM 680 559 82.2% +0 s .. +439 s
1095348116 MAPEM 334 261 78.1% +1 s .. +439 s
====================================================================================================
WHEN THE MISSES HAPPEN
miss runs in node order (all types): 239 runs, longest 2; run length 1: 235, 2: 4, 3-4: 0, 5-9: 0, 10+: 0
CAM 49 misses in 47 runs; longest run 2; single-message misses 45 (92 % of the misses)
MAPEM 73 misses in 55 runs; longest run 5; single-message misses 45 (62 % of the misses)
SPATEM 121 misses in 79 runs; longest run 4; single-message misses 52 (43 % of the misses)
minute by minute (node messages / share the phone logged):
0 s: 196 91.8% 30 s: 180 92.2% 60 s: 198 91.9% 90 s: 188 94.7%
120 s: 198 90.9% 150 s: 197 92.9% 180 s: 194 93.3% 210 s: 190 93.7%
240 s: 183 94.0% 270 s: 195 92.3% 300 s: 175 90.3% 330 s: 203 91.1%
360 s: 173 91.3% 390 s: 192 81.2% 420 s: 111 83.8%
====================================================================================================
WHERE THE MISSES ARE LOST (from the phone's once-a-second link_status rows; the board's counters as the phone read them)
over the run (ble link): board radio_received +1895, radio_dropped (its 16-frame queue overflowed) +0,
link CRC errors 0, malformed 0, app received 3253 link frames, board TX submitted 0 / failed 0
link state per second: connected 421
board restarts seen (uptime went backwards): 0
the 243 missed messages, by what the counters did in that second:
243 no counter moved (not heard by this board's radio, or lost on the BLE/USB hop)
If the last row dominates, the loss is invisible to the phone-side counters: either the phone's board never heard the
frame (different antenna than the node, a collision, the radio held out for a BLE connection event), or a V2X_RX
notification/fragment was dropped on the way (the firmware counts that only in a LOG line the phone cannot see over BLE).
note: 'radio_received' is not compared with the log; it counts frames the board's stack took, not every V2X_RX it forwarded.
====================================================================================================
LARGE MESSAGES (above 494 bytes: sent as link fragments since 2026-11-23) vs small MAPEM/SPATEM
MAPEM+SPATEM > 494 B node 1014 phone 820 80.9%
MAPEM+SPATEM <= 494 B node 0 phone 0 -
====================================================================================================
ONLY THE PHONE HEARD (in the log, not in the pcap within +/-0.50 s)
CAM 476 of 2186 phone messages not in the node's capture (21.8%)
MAPEM 90 of 351 phone messages not in the node's capture (25.6%)
SPATEM 159 of 718 phone messages not in the node's capture (22.1%)
(a node-side miss is a different antenna, a collision, or a node that was busy; read it against the node's own loss)
wrote obu-firmware\test\results\2026-11-23_1712_misses.csv
@@ -0,0 +1,159 @@
micrOBU bench run, 6.3 h
PASS 1278 FAIL 802 WARN 5 INFO 67 SKIP 0
== FAIL ==
conformance frames use the MAC the phone named (spec: MicrOBU 16-octet STATION_CONFIGURE) (x2) on air: ['66:f1:4c:b7:92:65']
soak-unsigned every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x11) 2400 of 2400 frames differ, e.g. ['a2:68:56:aa:e7:40'] (wanted 02:b3:0a:ce:00:04)
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x781) reply accepted, 1 frames, src 72:80:ec:aa:4b:62 want 02:b3:0a:ce:00:08
soak-unsigned requests accepted (queue not full, no refusal) (x4) 2383 refused: {'accepted': 17, 'resource_limit': 2383}
resets panic/error text on the console (x4) Guru Meditation Error: Core 0 panic'ed (Illegal instruction). Exception was unhandled.
== WARN ==
firmware the board does not run this checkout's firmware board 1c3a66e-dirty, checkout ce18a39: results describe the board's build, not the source here (flash it: obu-firmware/FLASHING.md)
soak-unsigned radio_failed stays 0 (x4) +2383
== INFO ==
firmware board runs version 1c3a66e-dirty, compiled Nov 10 2026 23:04:26, project microbu_firmware; checkout HEAD ce18a39
conformance battery reading with no cell (x2) battery_mv 0 (0 = not measured, no shutdown on it)
conformance an unfragmented link message over 512 octets (x2) reply: none (the spec says to fragment; link_service.cpp drops it before dispatch)
conformance POTI_UPDATE 8 s behind the station clock (x2) reply: time_regression
conformance 802.11 source of own unsecured frames (x2) 72:08:38:b1:d8:2f
conformance credentials on this board (configure with security on) (x2) credentials_loaded 1, tickets 1
conformance signed payload of 1398 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1399 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1400 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance GN address after naming MAC 02:b3:0a:ce:00:03 88:00:02:b3:0a:ce:00:03
conformance after the stage (x2) uptime 28976 ms, heap_free 75268, heap_min 55028, radio failed 0, resets seen 1
soak-unsigned host-side fragment accounting (x11) {'frag_complete': 1526}
soak-signed host-side fragment accounting (x11) {'frag_complete': 2596}
fuzz seed (x11) 333791341 (replay with --fuzz-seed 333791341)
idle-listen V2X_RX heard on the air while listening (x10) 0 messages in 300 s
conformance GN address after naming MAC 02:b3:0a:ce:06:1a 88:00:02:b3:0a:ce:06:1a
heap lowest free heap ever seen by the station (heap_min_free) 49736 octets
rx nothing was heard on the air during the run no other ITS station in range of this board, or the radio was never on
link host-side counters frag_complete 23441, frames_ok 366523
== PASS ==
conformance station answers STATUS_REQUEST after a reset (x2)
conformance STATUS detail is the 131-octet snapshot (spec: Status confirmation payload) (x2)
conformance a reset station is unconfigured (x2)
conformance uptime restarted at the reset (x2)
conformance STATUS uptime runs at real time (x2)
conformance opcode 0x00 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x40 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x7e is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x80 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x85 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x90 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0xff is answered unknown_opcode (link_service.cpp default) (x2)
conformance STATUS_REQUEST with a body is malformed (x2)
conformance STATION_CONFIGURE of 0 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 1 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 5 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 7 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 15 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 17 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE security=2 is malformed (x2)
conformance STATION_CONFIGURE beaconing=2 is malformed (x2)
conformance 16-octet STATION_CONFIGURE radio=3 is malformed (x2)
conformance POTI_UPDATE of 5 octets is malformed (x2)
conformance RAW_CAPTURE with a 2-octet body is malformed (x2)
conformance RAW_CAPTURE mode with a high nibble is invalid_argument (raw_capture_policy.hpp) (x2)
conformance RAW_CAPTURE on before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST btp_type=2 is malformed (x2)
conformance BTP_DATA_REQUEST with 32 permission octets is malformed (x2)
conformance BTP_DATA_REQUEST with 3 stray trailing octets is malformed (x2)
conformance BTP_DATA_REQUEST cut short is malformed (x2)
conformance BTP_DATA_REQUEST with the optional generated_at_ms decodes (then not_configured) (x2)
conformance CONFIRM echoes sequence 65534 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 65535 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 0 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 1 (counters wrap 65535 -> 0) (x2)
conformance test request is exactly 1536 octets (the request maximum) (x2)
conformance 1536-octet request in fragments of 240 octets is joined and decoded (-> not_configured) (x2)
conformance 1536-octet request in fragments of 504 octets is joined and decoded (-> not_configured) (x2)
conformance fragmented request declaring 1537 octets is resource_limit (x2)
conformance a fragment that leaves a gap is dropped without a reply (x2)
conformance an unfinished request is discarded after the 2 s idle timeout (its late last fragment gets no reply) (x2)
conformance at most 8 incomplete requests are held (spec: pending maximum 8) (x2)
conformance a frame with a wrong CRC is counted in link_crc_errors and ignored (x2)
conformance a valid frame after 60 octets of noise is answered (resync) (x2)
conformance a valid frame after a doubled 0xAA is answered (x2)
conformance a valid frame after a header declaring 1537 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 4000 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 65535 payload octets is answered (resync) (x2)
conformance a frame cut short and padded out is dropped and the next valid frame is answered (x2)
conformance a frame of unknown type does not disturb the link (x2)
conformance STATION_CONFIGURE (6 octets, unsecured, 5 dBm) is accepted (x2)
conformance STATION_CONFIGURE detail is 18 octets (spec: gn_address, identifier, credentials_loaded, tickets) (x2)
conformance RAW_CAPTURE mode 0x05 (on + own TX) after configure is accepted (x2)
conformance BTP_DATA_REQUEST before the first POTI_UPDATE is rejected (no ITS time, no fix) (x2)
conformance POTI_UPDATE with latitude 91 degrees is invalid_argument (x2)
conformance an accepted POTI_UPDATE is silent (spec: errors return CONFIRM) (x2)
conformance an accepted POTI_UPDATE counts in poti_updates (x2)
conformance unsecured BTP_DATA_REQUEST of 24 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 43 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 300 octets is accepted (x2)
conformance every accepted request leaves the radio, byte for byte (own-TX RAW_FRAME copy, unwrapped independently) (x2)
conformance unsecured frames carry no security envelope (x2)
conformance transport type 2 (TSB) unsecured is unsupported (station_unsecured: geonet.c builds SHB only) (x2)
conformance btp_type 2 is malformed (x2)
conformance refused requests put nothing on the radio (x2)
conformance signed BTP_DATA_REQUEST is accepted (x2)
conformance the signed request leaves the radio inside a signed envelope (IEEE 1609.2 signedData) (x2)
conformance signed frames use the MAC the phone named (x2)
conformance a signed request generated 5 s ago is rejected as stale (tx_policy::is_stale) (x2)
conformance a stale request is never transmitted (x2)
conformance 16-octet STATION_CONFIGURE naming a MAC is accepted (x2)
conformance the station did not reset during the stage (x2)
soak-unsigned RAW_CAPTURE own-TX capture accepted (x11)
soak-unsigned every request got a CONFIRM (x11)
soak-unsigned requests accepted (queue not full, no refusal) (x7)
soak-unsigned the station did not reset during the phase (x11)
soak-unsigned STATUS requests_accepted counts the accepted requests (x11)
soak-unsigned radio_failed stays 0 (x7)
soak-unsigned link_crc_errors stays 0 (host sends valid frames only) (x11)
soak-unsigned no captured own-TX frame was corrupted (x11)
soak-unsigned no request was transmitted twice (x11)
soak-unsigned accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x11)
soak-signed RAW_CAPTURE own-TX capture accepted (x11)
soak-signed every request got a CONFIRM (x11)
soak-signed requests accepted (queue not full, no refusal) (x11)
soak-signed the station did not reset during the phase (x11)
soak-signed STATUS requests_accepted counts the accepted requests (x11)
soak-signed radio_failed stays 0 (x11)
soak-signed link_crc_errors stays 0 (host sends valid frames only) (x11)
soak-signed sign_failed stays 0 (x11)
soak-signed every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x11)
soak-signed no captured own-TX frame was corrupted (x11)
soak-signed no request was transmitted twice (x11)
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x11)
raw-toggle RAW_CAPTURE 0x00 accepted (x22)
raw-toggle mode 0x00 copies none of the station's own frames (x22)
raw-toggle RAW_CAPTURE 0x05 accepted (x22)
raw-toggle mode 0x05 copies the station's own frames (x22)
raw-toggle RAW_CAPTURE 0x01 accepted (x11)
raw-toggle mode 0x01 copies none of the station's own frames (x11)
raw-toggle RAW_CAPTURE 0x07 accepted (x11)
raw-toggle mode 0x07 copies the station's own frames (x11)
raw-toggle RAW_CAPTURE 0x03 accepted (x11)
raw-toggle mode 0x03 copies none of the station's own frames (x11)
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x396)
reconfigure every STATION_CONFIGURE was accepted (x11)
reconfigure the station did not reset while being reconfigured (x11)
fuzz station answers before the fuzz run (x11)
fuzz fuzz starts unconfigured (nothing can reach the radio) (x11)
fuzz fuzz run (x11)
fuzz heap after fuzz is within 8 KB of the start (x11)
resets board answers after a reset (x50)
resets board comes back unconfigured (x50)
resets the reset was a fresh boot (uptime small) (x50)
resets ROM boot banner seen on reopen (x50)
resets first frame after a reset is transmitted (x50)
idle-listen STATUS answered once a second throughout (x10)
idle-listen the station did not reset while idle (x10)
idle-listen receive queue never overflowed (radio_dropped) (x10)
heap heap_min_free stays above 16 KB
heap resets: free heap trend over 5 readings (no reset in between)
@@ -0,0 +1,156 @@
micrOBU bench run, 0.1 h
PASS 217 FAIL 0 WARN 1 INFO 29 SKIP 1
== WARN ==
link frames from the board with a bad CRC 1 (USB corruption or a board-side write cut short)
== INFO ==
firmware board runs version ce18a39-dirty, compiled Nov 25 2026 14:23:51, project microbu_firmware; checkout HEAD ce18a39
conformance battery reading with no cell (x2) battery_mv 4007 (0 = not measured, no shutdown on it)
conformance an unfragmented link message over 512 octets (x2) reply: none (the spec says to fragment; link_service.cpp drops it before dispatch)
conformance POTI_UPDATE 8 s behind the station clock (x2) reply: time_regression
conformance 802.11 source of own unsecured frames (x2) 02:7f:88:bf:4e:cd
conformance credentials on this board (configure with security on) (x2) credentials_loaded 1, tickets 1
conformance signed payload of 1398 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1399 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1400 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance GN address after naming MAC 02:b3:0a:ce:00:03 88:00:02:b3:0a:ce:00:03
conformance after the stage (x2) uptime 29333 ms, heap_free 75268, heap_min 55028, radio failed 0, resets seen 1
soak-unsigned host-side fragment accounting {'frag_complete': 49}
soak-signed host-side fragment accounting {'frag_complete': 83}
fuzz seed 1599518015 (replay with --fuzz-seed 1599518015)
idle-listen V2X_RX heard on the air while listening 61 messages in 20 s
idle-listen V2X_RX by type/signed/size so far CAM <=64 x410
conformance GN address after naming MAC 02:b3:0a:ce:00:1b 88:00:02:b3:0a:ce:00:1b
heap lowest free heap ever seen by the station (heap_min_free) 49128 octets
rx everything the radio heard on the air during the run (V2X_RX) CAM <=64 x410
link host-side counters frag_complete 103, frames_bad_crc 1, frames_ok 4392
== SKIP ==
idle-listen large V2X_RX (above 494 B) reassembled intact by the host 0; fragments completed 103, errors 0
== PASS ==
conformance station answers STATUS_REQUEST after a reset (x2)
conformance STATUS detail is the 131-octet snapshot (spec: Status confirmation payload) (x2)
conformance a reset station is unconfigured (x2)
conformance uptime restarted at the reset (x2)
conformance STATUS uptime runs at real time (x2)
conformance opcode 0x00 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x40 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x7e is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x80 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x85 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x90 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0xff is answered unknown_opcode (link_service.cpp default) (x2)
conformance STATUS_REQUEST with a body is malformed (x2)
conformance STATION_CONFIGURE of 0 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 1 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 5 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 7 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 15 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 17 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE security=2 is malformed (x2)
conformance STATION_CONFIGURE beaconing=2 is malformed (x2)
conformance 16-octet STATION_CONFIGURE radio=3 is malformed (x2)
conformance POTI_UPDATE of 5 octets is malformed (x2)
conformance RAW_CAPTURE with a 2-octet body is malformed (x2)
conformance RAW_CAPTURE mode with a high nibble is invalid_argument (raw_capture_policy.hpp) (x2)
conformance RAW_CAPTURE on before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST btp_type=2 is malformed (x2)
conformance BTP_DATA_REQUEST with 32 permission octets is malformed (x2)
conformance BTP_DATA_REQUEST with 3 stray trailing octets is malformed (x2)
conformance BTP_DATA_REQUEST cut short is malformed (x2)
conformance BTP_DATA_REQUEST with the optional generated_at_ms decodes (then not_configured) (x2)
conformance CONFIRM echoes sequence 65534 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 65535 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 0 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 1 (counters wrap 65535 -> 0) (x2)
conformance test request is exactly 1536 octets (the request maximum) (x2)
conformance 1536-octet request in fragments of 240 octets is joined and decoded (-> not_configured) (x2)
conformance 1536-octet request in fragments of 504 octets is joined and decoded (-> not_configured) (x2)
conformance fragmented request declaring 1537 octets is resource_limit (x2)
conformance a fragment that leaves a gap is dropped without a reply (x2)
conformance an unfinished request is discarded after the 2 s idle timeout (its late last fragment gets no reply) (x2)
conformance at most 8 incomplete requests are held (spec: pending maximum 8) (x2)
conformance a frame with a wrong CRC is counted in link_crc_errors and ignored (x2)
conformance a valid frame after 60 octets of noise is answered (resync) (x2)
conformance a valid frame after a doubled 0xAA is answered (x2)
conformance a valid frame after a header declaring 1537 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 4000 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 65535 payload octets is answered (resync) (x2)
conformance a frame cut short and padded out is dropped and the next valid frame is answered (x2)
conformance a frame of unknown type does not disturb the link (x2)
conformance STATION_CONFIGURE (6 octets, unsecured, 5 dBm) is accepted (x2)
conformance STATION_CONFIGURE detail is 18 octets (spec: gn_address, identifier, credentials_loaded, tickets) (x2)
conformance RAW_CAPTURE mode 0x05 (on + own TX) after configure is accepted (x2)
conformance BTP_DATA_REQUEST before the first POTI_UPDATE is rejected (no ITS time, no fix) (x2)
conformance POTI_UPDATE with latitude 91 degrees is invalid_argument (x2)
conformance an accepted POTI_UPDATE is silent (spec: errors return CONFIRM) (x2)
conformance an accepted POTI_UPDATE counts in poti_updates (x2)
conformance unsecured BTP_DATA_REQUEST of 24 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 43 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 300 octets is accepted (x2)
conformance every accepted request leaves the radio, byte for byte (own-TX RAW_FRAME copy, unwrapped independently) (x2)
conformance unsecured frames carry no security envelope (x2)
conformance transport type 2 (TSB) unsecured is unsupported (station_unsecured: geonet.c builds SHB only) (x2)
conformance btp_type 2 is malformed (x2)
conformance refused requests put nothing on the radio (x2)
conformance signed BTP_DATA_REQUEST is accepted (x2)
conformance the signed request leaves the radio inside a signed envelope (IEEE 1609.2 signedData) (x2)
conformance signed frames use the MAC the phone named (x2)
conformance a signed request generated 5 s ago is rejected as stale (tx_policy::is_stale) (x2)
conformance a stale request is never transmitted (x2)
conformance 16-octet STATION_CONFIGURE naming a MAC is accepted (x2)
conformance frames use the MAC the phone named (spec: MicrOBU 16-octet STATION_CONFIGURE) (x2)
conformance the station did not reset during the stage (x2)
soak-unsigned RAW_CAPTURE own-TX capture accepted
soak-unsigned every request got a CONFIRM
soak-unsigned requests accepted (queue not full, no refusal)
soak-unsigned the station did not reset during the phase
soak-unsigned STATUS requests_accepted counts the accepted requests
soak-unsigned radio_failed stays 0
soak-unsigned link_crc_errors stays 0 (host sends valid frames only)
soak-unsigned every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form)
soak-unsigned no captured own-TX frame was corrupted
soak-unsigned no request was transmitted twice
soak-unsigned accepted requests seen leaving the radio (own-TX RAW_FRAME copy)
soak-signed RAW_CAPTURE own-TX capture accepted
soak-signed every request got a CONFIRM
soak-signed requests accepted (queue not full, no refusal)
soak-signed the station did not reset during the phase
soak-signed STATUS requests_accepted counts the accepted requests
soak-signed radio_failed stays 0
soak-signed link_crc_errors stays 0 (host sends valid frames only)
soak-signed sign_failed stays 0
soak-signed every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form)
soak-signed no captured own-TX frame was corrupted
soak-signed no request was transmitted twice
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy)
raw-toggle RAW_CAPTURE 0x00 accepted (x2)
raw-toggle mode 0x00 copies none of the station's own frames (x2)
raw-toggle RAW_CAPTURE 0x05 accepted (x2)
raw-toggle mode 0x05 copies the station's own frames (x2)
raw-toggle RAW_CAPTURE 0x01 accepted
raw-toggle mode 0x01 copies none of the station's own frames
raw-toggle RAW_CAPTURE 0x07 accepted
raw-toggle mode 0x07 copies the station's own frames
raw-toggle RAW_CAPTURE 0x03 accepted
raw-toggle mode 0x03 copies none of the station's own frames
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x12)
reconfigure every STATION_CONFIGURE was accepted
reconfigure the station did not reset while being reconfigured
fuzz station answers before the fuzz run
fuzz fuzz starts unconfigured (nothing can reach the radio)
fuzz fuzz run
fuzz heap after fuzz is within 8 KB of the start
resets board answers after a reset (x2)
resets board comes back unconfigured (x2)
resets the reset was a fresh boot (uptime small) (x2)
resets ROM boot banner seen on reopen (x2)
resets first frame after a reset is transmitted (x2)
idle-listen STATUS answered once a second throughout
idle-listen the station did not reset while idle
idle-listen receive queue never overflowed (radio_dropped)
heap heap_min_free stays above 16 KB