17 Commits
Author SHA1 Message Date
Ashin Walpola 875b389496 Add the bench RSU to the stored MAPEMs and let the bundle script take new files
The list now includes Berliner Tor / Kolbergstrasse (-1/23 rev 2), taken
from the 2026-11-25 V2X log. tools/mapem_bundle.py merges MAPEMs from V2X
log databases or hex text files into the existing list instead of
rebuilding it from the test corpus.
2026-11-30 14:00:59 +01:00
Ashin Walpola 750a752527 Ship the recorded HafenCity MAPEMs with the app and match SPATEMs to them
A SPATEM can now be placed on its lanes without the intersection's MAPEM
being received. The bundle (assets/mapem/hamburg.txt, built by
tools/mapem_bundle.py) holds 15 intersections, 16 revisions, from the
2026-03-18 drive.

Matching is on region, intersection id and revision, never on station id,
and a stored map more than 2 km from the rider is ignored. A live MAPEM of
the SPATEM's revision wins; a stored one of another revision is never used.
2026-11-30 13:45:34 +01:00
Ashin Walpola f3457dbd84 Report the 6 h overnight run of 2026-11-26 (bench test document, revision 2)
Open: the transmit path stalls in 4 of 12 cycles. The 273 fuzz failures in the host summary are false (case-insensitive match of 'no crash').
2026-11-27 10:58:30 +01:00
Ashin Walpola d27856aba1 Fix the bench scripts on Windows PowerShell 5.1
setup_workstation.ps1 stopped on the failed import of a missing Python package instead of installing it; start_overnight.ps1 stopped on the keep-awake call, whose 0x80000001 literal is read as a negative int.
2026-11-27 10:58:30 +01:00
Ashin Walpola aef65394ea Correct the firmware README's receive-path description and link the bench tests 2026-11-25 16:54:42 +01:00
Ashin Walpola 462e1898ff 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.
2026-11-25 14:43:34 +01:00
Ashin Walpola ce18a393ea Fragment large V2X_RX messages and decode road-RSU SPATEMs
The firmware dropped every received ITS message over 494 bytes (one link
message), so a road RSU's 888-byte SPATEM and 1198-byte MAPEM never reached
the phone. V2X_RX now goes out in link fragments up to 2300 bytes, best
effort and non-blocking; messages up to 494 bytes are unchanged.

The app's SPATEM decoder then refused those messages because they carry
intersection and movement names and advisory speed lists. It now reads past
both, checked against asn1tools on 718 distinct messages.

Adds the pure fragmenter with host tests and a pcap replay, a Kotlin
cross-check on the firmware's own fragments, tools/rx_size_compare.py,
docs/08-large-message-reception.md and station-link revision 3.
2026-11-23 17:34:56 +01:00
Ashin Walpola 7dd83dba3d Record motion sensors, raw GPS and clocks for sensor fusion, and add Ride settings
Phase 1 of GNSS/IMU sensor fusion: record what the filter needs, so it can
be built and tuned offline against real rides before it changes anything
on air (docs/07-sensor-fusion-logging.md).

Settings > Ride replaces Units, whose metric switch did nothing (the app is
metric throughout). It holds the phone position (handlebar, bag or pocket),
written into every V2X log as meta.phone_mount, and "Record motion
sensors", off by default.

With that switch on when a V2X log starts, the log (schema 2, file name
ending in _imu-<mount>) also records:
- accelerometer, gyroscope and gravity at 100 Hz into a new imu table, each
  sample with its own SensorEvent timestamp, collected on a background
  thread;
- raw GPS_PROVIDER fixes as gnss source phone_gps, next to the fused
  location, and for every phone fix its monotonic time, speed and bearing
  accuracy and provider;
- the monotonic, wall and GNSS clocks once a second into a new clock table,
  to line all timestamps up afterwards and show any phone clock step;
- the sensors' names and rates and the GNSS chip in meta.

Both settings are read once at the start, so one log is one mount and one
mode. The logger screen shows the mount, the motion sensor row count and
the raw GPS fix age while it runs.

tools/fusion_log_check.py checks a recorded log (sensor rates and gaps, both
phone sources, clock alignment and steps) and ends in PASS, WARN or FAIL.
Tested on synthetic logs built from V2xLogWriter's own table definitions;
the bench and ride checks on the Pixel 9 Pro are in TODO.
2026-11-19 15:17:02 +01:00
Ashin Walpola 275d382a1d Parse the CiT One's real obu_gnss and processed CAM payloads
Both JSON parsers returned null for every real CiT One message, checked
against the logged runs:

- ObuGnssParser read everything from own_info, but obu_gnss keeps the
  position, speed, heading and acceleration under gnss (as its API document
  shows). So on the CiT One the ego state never came from obu_gnss, the own
  station ID was never learned from it, and the V2X logger wrote no OBU
  fixes. Kinematics now come from gnss and identity, yaw rate and vehicle
  size from own_info. The documented no-fix (91/181) and invalid-speed
  (163.82) markers are rejected.
- CamParser only took stationType as a number, but the CAM topic sends the
  name ("passengerCar"), so the processed CAM fallback was dead. Names are
  now mapped too, and the vehicle size is read from vehicleLength_m and
  vehicleWidth_m, the keys actually sent.

The name table moves from DenmEvent into StationType.fromApiName so the
DENM and CAM parsers share one copy. The tests use payloads with the keys,
nesting and types of the logged ones.
2026-11-18 14:56:26 +01:00
Ashin Walpola 6fa91d1702 Send and read the CAM yaw rate with the ETSI sign
YawRateValue is positive to the left (degSec-000-01ToLeft(1), TS 102 894-2),
while Cam.yawRateDps is positive clockwise, to the right, which is what the
use-case engine and its heading-trend fallback assume. CamUperCodec used the
value as it is in both directions, so every CAM this phone sent showed a
standard receiver the opposite turn, and received CAMs were read the wrong
way round in turn detection. It now negates on encode and decode. The
expected bytes for a right turn in CamEncodeGoldenTest come from asn1tools,
not from this encoder.

The CiT One's CAM topic (v2x-uca/output/json/cam) is left-positive too, as
its API document says and as 316 of 316 turning samples in the logged runs
confirm, so CamParser negates as well. Its obu_gnss topic is documented as
left-positive but sends yawRate_degps right-positive in practice (27 of 27
turning windows in the 2026-03-18 bacospat log), so ObuGnssParser keeps the
value and now reads that documented key, which it used to miss.
2026-11-18 14:56:17 +01:00
Ashin Walpola 727c9116dd Take the yaw rate about the vertical and stamp fixes with their GNSS time
The phone's CAM and VAM used the gyroscope's z axis as the yaw rate. That
is rotation about the screen's normal, so it only matched the bike's
turning with the phone flat, screen up: tilted on a handlebar it read about
64 % at 50 degrees, upright close to nothing. The gyroscope is now projected
onto gravity (TYPE_GRAVITY), which gives the rotation about the true
vertical however the phone is held, averaged over 100 ms. Gyroscope and
gravity run at SENSOR_DELAY_GAME for this; the yaw rate used to come from a
single sample at SENSOR_DELAY_UI.

Fixes now carry their own monotonic time (Location.getElapsedRealtimeNanos),
speed and bearing accuracy and provider, and sensor samples their own
SensorEvent.timestamp. What goes on air is the GNSS time of the fix itself,
from its monotonic age (GnssTimeSource.atElapsedRealtime), so neither the
phone's clock setting nor a step of it between the fix and transmission
reaches the CAM or GN timestamps. The loop's own intervals (elevated rate,
VAM generation rules) and the GNSS speed differencing for acceleration use
the monotonic clock too, so a clock set back can no longer hold VAMs off.

This is phase 0 of GNSS/IMU sensor fusion: YawRateEstimator is the first
piece of domain/fusion. Unit-tested; the bench and ride checks are in TODO.
2026-11-18 14:56:05 +01:00
Ashin Walpola b4e3385721 Fix the V2X logger note: MAPEM and VAM are forwarded, and it logs the decoded message on both receive paths 2026-11-11 16:39:43 +01:00
Ashin Walpola ecf16289a3 Rebuild the station-link revision 2 PDF with the receive path and fragmentation sections 2026-11-11 16:27:08 +01:00
Ashin Walpola 457ad47521 Update the diagrams, READMEs and spec for the two receive paths
Add data-flow diagrams of both paths (V2X_RX and RAW_FRAME with the app's Receive path
switch) to the app README, the firmware README and docs/06, and bring the draw.io
architecture labels up to station-link revision 2. The spec (revision 2) gains
"V2X_RX and RAW_FRAME: both stay" and "Fragmentation on the host side". Document the corpus
generator in test/host.
2026-11-11 16:25:34 +01:00
Ashin Walpola 1697091d3a Add a receive path switch: V2X_RX or the spec's RAW_FRAME, with fragment reassembly
Settings > Connection > ESP32-C5 > Receive path chooses where received ITS messages come from.
V2X_RX (default) is the MicrOBU extension the board builds with gn_unwrap.c. Raw frames is the
station-link RAW_FRAME debug capture: the app switches RAW_CAPTURE on (mode 3), reassembles
fragmented link messages as the spec defines (LinkReassembly), parses the ITS5 record
(RawFrame) and unwraps the 802.11 frame with GnUnwrap, a Kotlin port of gn_unwrap.c. Both end
as the same V2X_RX frames, so nothing above the link changes, and the firmware keeps both.

GnUnwrapTest checks the port against the C code on 602 recorded, cut and corrupted frames
(corpus from obu-firmware/test/host: make corpus). 145 app tests. Fix the Connection text that
claimed the app picks the strongest micrOBU.
2026-11-11 16:19:32 +01:00
Ashin Walpola c96fd0086f Remove a stray LaTeX lock file that was committed by mistake 2026-11-11 15:43:19 +01:00
Ashin Walpola 07cce90b9f Fix the row ends of the 16-octet STATION_CONFIGURE table and rebuild the PDF
The new table ended its rows with a single backslash, which gave 'Extra alignment tab'
errors and a broken layout. Built with two pdflatex passes, so the footer shows the page
count (24). The remaining 'infinite glue shrinkage in box being split' messages are the
same harmless kind Niklas Dathe's original produces.
2026-11-11 15:43:13 +01:00
96 changed files with 13912 additions and 2585 deletions
+7
View File
@@ -86,3 +86,10 @@ obu-firmware/docs/*.synctex.gz
# Editor settings
/.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/*/
+33 -5
View File
@@ -42,7 +42,7 @@ hardware_paths:
messages_received: V2X_RX (0x90), signed or not, up to 494 octets
messages_sent: signed or unsigned per setting (Settings > Connection > ESP32-C5)
credentials: throwaway demo chain in app/src/main/assets/demo-chain.vcr
tests: 131 JVM unit tests, no emulator needed (domain/ has no Android imports)
tests: 145 JVM unit tests, no emulator needed (domain/ has no Android imports)
```
## Project goal
@@ -82,7 +82,9 @@ Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived
**OBU status**; the ESP32-C5 card shows the link in use, signing (tickets, signed, refused, on air) and the board's battery voltage with a low/critical warning, which also appears in the top bar.
**V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside.
**V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside. With Settings > Ride > Record motion sensors on, a log also records accelerometer, gyroscope and gravity at 100 Hz, raw GPS fixes next to the fused location, and the phone's clocks, for sensor fusion; `tools/fusion_log_check.py` checks such a log. See `docs/07-sensor-fusion-logging.md`.
**Ride settings**; Settings > Ride. Where the phone rides (handlebar, bag or pocket), recorded in every V2X log for sensor fusion, and the motion sensor recording switch above.
**Trip recording**; foreground service records all sensor streams and detects cycling manoeuvres (braking, turning, stopping) using orientation-independent signal processing. Works fully offline with no OBU connected. The detected manoeuvres are neither shown nor stored - their only effect is to raise the CAM transmit rate through the manoeuvre on the ESP32-C5 path.
@@ -98,13 +100,13 @@ MVVM with Repository pattern throughout. Jetpack Compose for all UI (no XML layo
app/src/main/java/com/hawhamburg/micr0bu/
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor and map, Settings, V2X logger...)
ui/navigation/ Navigation graph and bottom nav bar
viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel
viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel, RideSettingsViewModel
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope
data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport
data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager
data/log/ V2xLogger, V2xLogWriter (the V2X data logger)
data/db/ Room database (sessions, trips, V2X messages)
data/ SensorRepository, GnssTimeSource, TripRepository, CsvExporter, TripExporter
data/ SensorRepository, GnssTimeSource, RidePreferences, TripRepository, CsvExporter, TripExporter
domain/asn1/ BitReader/BitWriter, ItsTime, and the CAM, DENM, SPATEM, MAPEM and VAM UPER codecs
domain/map/ MAPEM intersection geometry: lanes, nodes, connections, maneuvers
domain/spat/ SPATEM signal state, and TrafficLights (SPATEM on MAPEM lanes, the rider's approach)
@@ -112,6 +114,7 @@ app/src/main/java/com/hawhamburg/micr0bu/
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig, Pseudonym
domain/fusion/ Sensor fusion: YawRateEstimator (yaw rate about the vertical), PhoneMount
service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService
obu-firmware/ ESP32-C5 OBU on Niklas Dathe's microbu-firmware (station, signing, BTP, GeoNetworking,
@@ -124,7 +127,7 @@ tools/ Bench scripts: STATUS watcher, bench-listener tally, MAPEM
docs/ Requirements traceability, signed ITS / VAM / BLE design, architecture diagrams
```
The `domain/` packages contain no Android imports. That is what makes the 131-test JVM suite possible without an emulator or instrumentation.
The `domain/` packages contain no Android imports. That is what makes the 145-test JVM suite possible without an emulator or instrumentation.
## Connectivity
@@ -156,6 +159,30 @@ Whether an active BLE connection costs 5.9 GHz reception has not been measured y
vanetza-idf verifies strictly and would drop anything unsigned or signed under another root, i.e. the bench car and every RSU. So every captured frame also goes through `gn_unwrap.c`, which strips 802.11, LLC/SNAP, GeoNetworking (single-hop and GeoBroadcast), an IEEE 1609.2 signed envelope if there is one, and BTP, and forwards the ITS payload for BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM. Signatures are not checked on this path; the message is flagged "signed, not verified". A payload over 494 bytes does not fit one link message and is dropped and counted.
**Two receive paths, switchable** (Settings > Connection > ESP32-C5 > Receive path). Both end in the same decoded messages, so nothing above the link changes:
| | V2X_RX (default) | Raw frames |
|---|---|---|
| Source | the MicrOBU extension, opcode 0x90 | the spec's `RAW_FRAME` (0x85), switched on with `RAW_CAPTURE` |
| Who unpacks the frame | the board (`gn_unwrap.c`) | the app (`GnUnwrap.kt`, a port tested frame by frame against the C code) |
| Size | up to 494 octets | not limited: fragments are reassembled (`LinkReassembly`, as the spec defines) |
| Reliability | normal indication | debug copy: can be dropped when the link is busy, more bandwidth, especially over BLE |
```mermaid
flowchart LR
Air[ITS-G5 frame] --> Board[ESP32-C5: radio, gn_unwrap.c, raw capture tap]
Board -->|V2X_RX 0x90, always| Link[USB or BLE]
Board -->|RAW_FRAME 0x85, after RAW_CAPTURE| Link
Link --> Re[LinkReassembly]
Re --> Sel{Receive path setting}
Sel -->|V2X_RX, default| Dec[V2xRxFrame]
Sel -->|Raw frames| Raw[RawFrame + GnUnwrap]
Raw --> Dec
Dec --> Rest[Codecs, use cases, V2X screens, logger]
```
The board always sends `V2X_RX`; the app consumes one path and ignores the other. Changing the setting takes effect at once on a configured station (`RAW_CAPTURE` mode 3 = on and broadcast frames only, mode 0 = off). `GnUnwrapTest` checks the Kotlin unwrapper against `obu-firmware/test/host/dump_corpus.c`'s output for 602 recorded, cut and corrupted frames.
## Verification
The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path, which is the highest-risk code in the project. Round-trip tests through the project's own codecs structurally cannot catch a shared mistake about a field's bit width, and this project shipped exactly that bug three times (`CurvatureCalculationMode`, the GeoNetworking reserved bytes, `yawRateConfidence`). Phone and ESP32 agreed with each other and with nothing else.
@@ -181,6 +208,7 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
| [docs/MicrOBU-Technical-Documentation.docx](docs/MicrOBU-Technical-Documentation.docx) | Supervisors and stakeholders. Architecture, message path, verification, results, decisions |
| [docs/01-requirements-traceability.md](docs/01-requirements-traceability.md) | Requirements chapters 0 to 13 mapped to implementation and evidence |
| [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md) | Signed ITS messages, VAM and the BLE link: who does what, link protocol, recovery, verification |
| [docs/07-sensor-fusion-logging.md](docs/07-sensor-fusion-logging.md) | Sensor fusion phases 0 and 1: yaw rate and GNSS time inputs, Ride settings, the fusion log schema, `tools/fusion_log_check.py`, test rides |
| [docs/Architecture-signed-its.drawio.png](docs/Architecture-signed-its.drawio.png) | Block diagram of the signed-ITS architecture |
| [05-obu-bench-test-2026-08-25.md](05-obu-bench-test-2026-08-25.md) | Bench campaign T1 to T9, measured results |
| [04-transmit-setup.md](04-transmit-setup.md) | Transmitter bring-up, radio configuration diagnosis, the TX bypass |
+166
View File
@@ -5,6 +5,165 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware
### Stored HafenCity MAPEMs (added 2026-11-30)
The app ships 15 intersections (16 revisions) from the 2026-03-18 drive plus the bench RSU
(Berliner Tor / Kolbergstrasse, -1/23 rev 2) in `assets/mapem/hamburg.txt`, and matches a SPATEM to
them on region, intersection id, revision and, when known, position within 2 km. Add to the list with
`py -3.11 tools/mapem_bundle.py <V2X log .db or hex .txt>`, then run the tests and rebuild.
- [ ] Bench RSU sending its SPATEM **without** the MAPEM: the lanes appear on the V2X map; logcat says
`storedMaps: 17 intersection revisions loaded`.
- [ ] Ride through HafenCity: note intersections whose SPATEM shows no lanes (revision changed since
March, or not in the bundle) and check on the ones that do that the shown light matches the real one.
- [ ] Not built yet: saving newly heard or changed MAPEMs on the phone, so the list updates itself.
### Large SPATEM / MAPEM through V2X_RX in fragments (added 2026-11-23)
The 2026-11-23 bench run (CiT node sending a 377 B MAPEM and 58 B SPATEM, then 1198 B and 888 B ones; phone on
BLE) lost every large message: 0 of 1537 MAPEMs and 0 of 3004 SPATEMs against 98.5 % / 96.5 % of the small ones,
because `Station::forward_raw` dropped everything over 494 bytes. Firmware now sends those in link fragments
(`link_fragment.hpp`, `v2x_rx_plan`; NOTES.md). Done on the PC, not flashed yet: `make check` in
`obu-firmware/test/host` (46 unit tests, the pcap replay of 3384 + 1727 large messages through unwrap -> fragments ->
two reassemblers, fuzz), the app's `LinkReassemblyTest` on the firmware's own fragments, asn1tools on the large
payloads, ESP-IDF 6.0.2 image build.
- [x] Flashed to COM10 and run against the Berliner Tor RSU (2026-11-23 17:08-17:20, phone on BLE): MAPEM 1198 B 92.9 %,
SPATEM 888 B 81.7 % of what the node heard, `radio_dropped` 0. The V2X screens stayed empty because the app's
`SpatemUperCodec` refused the RSU's SPATEMs (intersection and movement names, advisory speeds); fixed and checked
against asn1tools on all 718 distinct messages, **needs the app reinstalled on the phone**.
- [ ] (original plan) Flash COM6 (`--no-stub` recipe, read the app descriptor first) and repeat the bench run: the node alternating
small and large MAPEM/SPATEM, the phone on BLE, a pcap recorded at the same time. Compare with
`py -3.11 tools/rx_size_compare.py LOG.db capture.pcap replay.tsv` (the header says how to make replay.tsv).
Accept: small messages stay at ~96-98 % of what the node saw, the large ones arrive at a comparable rate,
CAMs unchanged (92-96 % on 2026-11-23).
- [ ] `radio_dropped` (link_status) stays 0 with the large messages, as it did on 2026-11-23 without them, and no BLE
disconnects. If it moves, the fragments hold the station task too long: look at the fragment cap and BLE notify
failures (the board's LOG line "V2X_RX: ... fragmented (... not taken by any transport)", 1 per 10 s).
- [ ] The same over USB, and once with the app set to Raw frames: RAW_FRAME must still deliver the large ones, V2X_RX must
not send them a second time (`raw_covered_`), and switching back to V2X_RX must work without a reconnect.
- [ ] TX unchanged: a phone-originated CAM (signed and unsigned) is still seen by the node in the same session.
### App refresh: map dashboard, V2X switch, routing (added 2026-11-19)
Map-first dashboard (MapLibre, glass panels, folding bottom bar), "V2X ON/OFF" switch in the MicrOBU
box, V2X sending decoupled from trip recording, "Where to?" search and bicycle routing. Built, 185
unit tests green, and driven on the emulator with a mocked GPS fix (map, search, route preview and
guidance all work). Not checked without the ESP32-C5 or a phone on a bike:
- [ ] Connect the ESP32-C5 with no trip recording: V2X turns on by itself and the second ESP32 (or
`tools/cit_one_rx_watch.py`) hears the phone's CAMs. Switch it off on the Connection screen (tap the
MicrOBU box on the dashboard): they stop, and the dashboard box reads "V2X OFF".
Unplug and reconnect: it is on again, even if it was switched off before.
- [ ] Screen off for 5 minutes with V2X on: CAMs keep coming at 1 Hz (`V2xTransmitService` holds the
process and GNSS; the "V2X on" notification is showing).
- [ ] Connect while the app is in the background on Android 14+: the loop still sends if the foreground
service is refused (the start is allowed to fail), but the notification will be missing.
- [ ] CiT One selected: the V2X switch is disabled and mirrors the link, and nothing is sent by the phone.
- [ ] MicrOBU box shows the real battery percentage over BLE and USB, amber and red at the warn and
shutdown voltages.
- [ ] On a ride: heading-up mode tilts and turns the map with the course; guidance announces the turn
before the corner; going off route reroutes within about 15 s.
- [ ] GLOSA hint (speed box) at a real signalised junction with MAPEM and SPATEM on the air: the
advice matches the lights. The rules are unit-tested only; never tried against a live signal.
- [ ] Motion gate (`MotionDetector`): standing still indoors with GPS wandering, the speed box reads 0;
then ride: it never reads 0 while moving, in each mount (handlebar, bag, pocket). Thresholds
(`ENTER_STD` 0.15, `EXIT_STD` 0.07 m/s², 8 s hold) are from synthetic data only; a smooth-road
ride on a handlebar mount is the case most likely to need tuning. Not applied to the CAM speed
the phone transmits yet, which is still the raw GNSS speed.
- [ ] Settings > Developer > CAM pinger (moved from the V2X screen): starts and stops, shows the
loopback count, only appears with the ESP32-C5 selected.
- [ ] Decide the satellite and terrain tile provider (the layer buttons are in the map settings,
disabled until `MapLayer.styleUrl` has a source), and where routing and search run for real:
the app now sends the rider's position to photon.komoot.io and valhalla1.openstreetmap.de, which
are shared demo instances.
### Why the simulated car drops out of the V2X screen while the phone transmits (added 2026-11-19)
The bench beacon (`obu-cam-transmistter`, station 0x0BADC0DE) vanishes from the V2X screen for a
moment and comes back while the phone is sending. The V2X screen forgets a station after 3 s without
a CAM (`staleRemoteMs`), so these are gaps of 3 s or more. Hypothesis: the ESP32-C5 shares its radio
between BLE and ITS-G5 and a transmission and a reception collide with a BLE event.
Not confirmed. Read from the firmware source only, not measured: the TX hold for BLE
(`Station::hold_for_ble_guard`) is a busy-wait of at most 3.5 ms, too short to overflow the 16-frame
receive queue, so a queue overflow from transmitting is unlikely; the firmware's own notes say a frame
handed to the radio during a BLE connection event is accepted and never transmitted, and nothing says
reception is spared; frames the radio never delivers (or the PHY flags bad) are in no counter.
Tooling is in: the V2X data logger (schema 3) now records `link_status` once a second, and
`tools/rx_gap_analysis.py` accounts for every gap in the beacon's frames (lost before the radio saw
them, dropped in the firmware queue, or lost between board and phone) per condition, and checks
whether the gaps recur at a steady interval (two clocks beating). Self-tested on synthetic data only.
- [ ] Install the current build on the Pixel. Beacon on, 1-2 m from the OBU, nothing else on 5.9 GHz.
- [ ] Settings > Developer > V2X data logger > Start logging, then four stretches of at least 3
minutes each in one log, switching between them without stopping the log:
BLE with V2X off (Connection screen), BLE with V2X on, then the same two over USB
(cable from the phone to the OBU, Settings > Connection > ESP32 link = USB).
- [ ] Stop, pull the `.db` (`adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/<file>`)
and run `python tools/rx_gap_analysis.py <file>.db`. The table says which condition loses frames,
and where; if the beacon's frames vanish before the radio and only on BLE with V2X on, BLE
coexistence with transmitting is the cause, and the recurrence line says whether it is a beat.
- [ ] If it is coexistence: the lever is in the firmware (the colleague's BLE guard calibrates only
TX), not the app; options are fewer or longer-interval BLE events while transmitting, or USB.
### Sensor fusion phase 1: logging and test rides (added 2026-11-18)
Settings > Ride (phone position, Record motion sensors) and the fusion data in the V2X data logger,
described in `docs/07-sensor-fusion-logging.md`. Unit-tested and built; `tools/fusion_log_check.py`
tested on synthetic logs only. On the Pixel 9 Pro:
- [ ] Settings > Ride: Units is gone, Ride is there; the position and the switch survive an app restart.
- [ ] One-minute bench log with Record motion sensors on: the logger screen shows the mount, the motion
sensor count climbing by about 300 a second, and a raw GPS fix age; the file is named
`..._imu-<mount>.db`; `fusion_log_check.py` on it gives no FAIL (accel, gyro, gravity at about
100 Hz, `phone` and `phone_gps` fixes with `elapsed_ns`, `clock` rows with GNSS time).
- [ ] Screen off for 5 minutes during a log: no motion sensor gap over 1 s in the check (the log
service holds the CPU awake; confirm the sensors keep coming too).
- [ ] Record motion sensors off: the log has empty `imu` and `clock` tables, no `phone_gps` rows,
and no `_imu-` in its name, but still `meta.phone_mount`.
- [ ] Rides, 20-30 minutes each, mount set before Start, each with left and right turns, a
roundabout, stops of 10 s or more and if possible a bridge or underpass. Run the check on each
and keep the files for phase 2:
- [ ] handlebar
- [ ] bag (on the bike)
- [ ] pocket or backpack
### Sensor fusion phase 0: yaw rate about the vertical, fix times on GNSS time (added 2026-11-18)
The phone's own CAM/VAM now take the yaw rate from the gyroscope projected onto gravity
(`domain/fusion/YawRateEstimator`, 100 ms average, gyro and gravity at `SENSOR_DELAY_GAME`) instead of
the raw z axis. They stamp the GNSS time of the fix itself, through its monotonic
`elapsedRealtimeNanos` (`GnssTimeSource.atElapsedRealtime`). The loop's own intervals (elevated rate, VAM
rules) run on `SystemClock.elapsedRealtime`. Unit-tested (`YawRateEstimatorTest`), not yet on the phone.
With the CAM pinger on and a listener that decodes yawRate:
- [ ] Turn the Pixel 9 Pro on an office chair at about 90°/s: flat, tilted about 50° as on the
handlebar, and upright. All three should read about the same yaw rate. The old z-axis value
fell to about 64 % tilted and to about 0 upright.
- [ ] Phone still on the desk: yaw rate stays inside the 1 °/s noise floor, so it goes out as 0.
- [ ] Set the phone's clock 10 minutes wrong by hand (automatic time off) with a GNSS fix: the CAM
generationDeltaTime and GN TST still match GNSS time. Then step the clock back mid-run: CAMs and
VAMs keep going at their rate, with no gap and no time_regression on the micrOBU.
- [ ] Ride with the phone on the handlebar, then in a bag: the yaw rate's sign and size match the
turns (left and right, roundabout).
- [ ] Yaw rate sign on air (fixed 2026-11-18: `CamUperCodec` and `CamParser` now flip the ETSI/CiT
left-positive value into the app's clockwise-positive one). Turn the pinging phone left: a
standard decoder (asn1tools, or the CiT One's `v2x-uca/output/json/cam`) shows a positive
YawRateValue, and the app's own decode of the same CAM reads a negative yaw rate (left, in the
app's clockwise-positive convention).
The logs in `databases/` (not committed) already settled the CiT One side: its CAM topic is
left-positive (316 of 316 turning samples), its `obu_gnss` `yawRate_degps` right-positive
despite the API document (27 of 27, bacospat ride of 2026-03-18). Only 27 samples from one
ride: re-check on the next CiT One ride with turns.
- [ ] CiT One JSON parsers (fixed 2026-11-18): `ObuGnssParser` returned null for every real `obu_gnss`
message (position is under `gnss`, it read `own_info`), and `CamParser` for every real CAM-topic
message (`stationType` is a name). So on the CiT One the ego state never came from `obu_gnss`,
the app's V2X logger wrote no OBU fixes, and the processed CAM fallback was dead. On the next
CiT One session: the use-case engine runs on `obu_gnss` (the phone GNSS fallback only kicks in
after 2.5 s without it), the own station ID is learned so own CAMs stop showing as remote, and
the V2X log has `obu` rows in its `gnss` table.
### obu-firmware on Niklas Dathe's microbu-firmware (added 2026-11-10, bench run 2026-11-11)
Flashed on the production XIAO (COM10) and the phone (Pixel 9 Pro, BLE) on 2026-11-11. Done, by hand
@@ -23,6 +182,13 @@ on the bench with the COM3 board as a listener:
Still open:
- [x] Receive path switch (2026-11-11, over BLE): `Raw frames` gave `RAW_CAPTURE mode 3 -> accepted` and the simulated car kept
arriving through the app's own unwrapper; back to `V2X_RX` gave mode 0 and it kept arriving.
- [x] V2X data logger on both receive paths (2026-11-11, 33 s each, the simulated car): `V2X_RX` 103 CAMs, `Raw frames` 106 CAMs; the logger
listens to the same decoded frames for both, so it needs no change. It stores the decoded message, not the radio frame.
- [ ] Fragmentation on air: a RAW_FRAME above one link message (a large MAPEM or SPATEM from a road RSU) reassembled in the
app over BLE and over USB; only unit-tested so far.
- [ ] Count both paths on the same traffic to see how many frames the raw copy drops on a busy link.
- [x] Bond persistence (2026-11-11): the board was reflashed (MTU 517) with its NVS kept; the phone reconnected to
micrOBU-66AA without a pairing prompt.
- [ ] Verify a captured signature with `test/verify_signed_pcap.py` (needs the sniffer firmware).
+36
View File
@@ -0,0 +1,36 @@
# Stored MAPEMs. One UPER MAPEM per line, hex, each below a comment naming its intersections.
# Written by tools/mapem_bundle.py; add to it with that script.
# -1/23 rev 2 Berliner Tor / Kolbergstrasse
02054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
# 1/1 rev 2 MAP_ITS_03\310\5.2
020500ff3b6208000308cd8342fc9a94efb067719b16171aae6500010001042ac7d5cd389e98d881450d240314200000057fb8d632200bce2061ad419ea25e00b0c8000101100c22200000059f074a9208f383d45501c3ae04804284000000b3028afdd1005e7102f56a8cf4b2f10585c00008108059110000002cf9d66620479c1ea2a80e1d70240e14021000000afe339584401544436946e3336cd18161f0000406201e4404200000166fb9320822a20f5136070eac12049210000002da0a08c79440179c983032e44c65da950583400018208030910000002cc6471bc0479c01555001829524082420000005b405716c08802f393038666c98e9b4ca0b0580003051005122000000598a2612208f3802aaa003052a480e484000000b3fb5a9011005e726084ccb931dd694c1609000060c2008244000000b30d2bda811e70055540060a54900450800000166133693a200bce205cad619e8e5e40b0a8000107100a22200000059f6e4ef808f383d45501c3ae0
# 1/1 rev 3 MAP_ITS_03_312_6.3
020500122a7408000308cd8342fc9a94efb0677d9b1657db2e6700010001062ac7e6c6389e8341014524240624200000059ea6242680020f415a1ec1588e2b0f800010c58190001008807a1100000024c39963a0047520009a34400c488800001275dcc1282adf5432370612029210000002cf37d0e1400107a6ac8f5e2c3f05874000086880721100000024c1d54ff004d518015aa09010908000001678e47d7a00083d55607af462682c36000043840350880000011fff07a800a6a209f39744818884000008b2e9d3f290004010d4a213ca82111ad0e8406d62116d4d68858e97467aa96a885aa924436b45c23d796a1058d3a083a6a50464733833c0cbd4669e94f0c8072c4103fcbb04b1c511588900018cac26000103c4044c8880000126576511013e0d00a711e201244400000093af12d881eb2b01e74b60902d1080000115fc181fa80020096a4109f540888ce878201eb208b6e6b442cb4b833d54b5442d549221b4a2e11eb4b5082d69cc41d3528232199c19dea5f03346ca8c63f7963881d25e025263702c2200010404020888000001276bc64a03d65603ce96c12052210000022bfb788c50004014d442140a801118d0f0401566116e4d60859e97067aa96a885aa924436545e23d596b105cd39083a2a50463f33a33b9cbe8667c9540c7d52ca10344bd048d4700583c000208880391100000024ef2cdc507aaac079d2d8241034220000459a259348800204f8341af5cf8611763104bd05d624aa065128a0f7894104006bc13240944056c49e62aa158c3a828600085500c622eb8730895ccd000030ba13ca530488e430eb0920005125841000289ac1c800145161a8000a34b0e400051b587a00028e2c0e00020256568000a3a4804284400003b386364310004156faa39c2e57035afc482b6f2813cf0819cdb785571ada1979ba9161e4000c04b0e200060358690003022c460001c156564000c164802284400008b399d62a10004156faa2a42e231d0a74fa39696cb07321e5992446dae872dbc7a8ebb98b61552610872ffbd15a5e5087ccf660f91e9e1c977e43c4680876ec760f448f61f5b1bcd60e8000c0cb084000607584a0003042ca9000182840ad08084000002ccd297ba0460c01c590010ab6102a22021000000b38ab28f0118307acb383d159810498102000000ced41692400104bef10084c04104d8102000000cdbf17ed400103430f008480810518102000000cd5a8a54400104baee008540c10558102000000cc7bcbaa4001034712008501010590084000000cedf14c3400104bef08085c14005c8084000000cd63565e400103410d020c2010800000198af19ba8002068a20010c83000c901080000019aee16ac80020979dd042c604080000033c1c4df11005e7043d2f828b4245410b58102000000ceb84f91440179c0f13420a2c0a16042e604080000033a813b591005e7043f2f828bc2c5c10bd8102000000ce568b4e440179c0f0b420a2e0c18043060408000003326059991005e704412f828c4347810c58102000000cc4c12e7440179c0f53720a300e1f04326040800000330d948d51005e704432f028cc3c8010cd8102000000cbe80ebb440179c0efb440a32102100346021000004b46d8a439011511e0c1d8a4cb65b8926d06c5e07ab22d1f7516880fe5da278bab400f658c450f407da2e614f600356021000000b6a9c1bb5811511071d308806ee200
# 1900/2396 rev 3 MAP_ITS_23_2396_12.3
02050000302908000309cd8342fc9a94efb2677d93372dafb164b99c1db0257018ab1d58e8e27e146a05147090109080000036724ae59a00082bf0c873a533b86ab9744e0f30280082b0f800011b581200010f0807a1100000024c7271ad0283e701d9938901490800000267454e862200b9c0afc325d81822680081a9433856210000238b0b2000226101042200000049982e3d20507ce03794c12099201080000059d293e968802ce02c00c4940c976e2b14800011d589100010f880a2101080000059a3d628608c18141f380fad9620042440000012f9c386f0479c083bf6815a10400402d50288091901080000059fb1c8a208ce0741b960462fa92049a10000002cf2f675e400107d6d59337672e4160e8000640200e444000000b36da793011e7057e1902305ec9028d08000001679c9464a200bce0fadab26710e4a82c0a00010849044d0084000002ceca6a5144017381f63564ce21c951581c0002112c508000cdc400c48084000002be5766e0118302dcd220224750010903510800000165f65842a0008141f3849d7eee0b0b4000523100b32200000059ed9cbb208dfa3eb6ac12280586f092072210000002cbab7026440179c0a0f9c24e7f3a1583c0003122c08800149490045088000055f69ed86880319003180044a105023267dc19ec9ec221fd7801103bc52ac2e0001c9d60e4001050b082000829589400039b2c3d00020e1620800107220104404200000166abcf410233809194d052051120aa201080000097df5f51a200b061627950072de224f7e6515844000495ac0c80028a810598102000002cc90aebd400142bedca002018f738142e1658082ec08100000066a9780a200083129e4142c185a0830c0810000005f9539de800203c182050c8697020cb020400000598af5cae8002890e1f4004059b2f8286038bc10698102000000ce416b404001031d8a8286c3cc0106d8102000000cf0c2383400104e475828683cc410718102000000bf0debb500040d06380a1d1032041d60408000002ffb15c3400104c0720287044cc10798102000000cd03e0c5400101aaf68287c48d0107d8102000000ce9f212e400106a7098287848d40
# 3/120 rev 1 MAP_ITS_01_120_6.1
0205000177d308000308cd8342fc9a94efb0637d8b2617db2e6300030078022ac82671b8a0b56681450d24082420000009b0b7aaf068002007d7d19e59bdc336c362416070000210200624400000096234d61701f050c0ca66424072420000009b0c26ac968002007d7d026ce490efc723816090000212200824400000096248d5c701f050c0d0e7424062420000009b0cc0aa228002007d7d080962c3107b510160b000020a200a24400000096261157941f050c0d82502401142000000db0fc4b77480020f76960f87a503d0ad0bc79c59d402c2a000081840288880000012c26a2d6700225b426f5aa12010a10000006d883e5a74400107c1430b95a9745ea760a3cf1cf101613000040e20124440000009614e56644008aba13a8d84102d8102000000d86415bfe4001032b83828300c0410318102000000d86ed5961400104ac708282c0c0810358102000000d871b5886400103599002838100c10398102000000d87f954df400105027c028341010
# 3/121 rev 4 MAP_ITS_01_121_17.4
0205001233b4080003094d8342fc9a94efb0637d8b2637d8b75cd2000600f211558fedf6713dabfa1000028a1648042804200000461f312fd8230614fdc0c4cf1896272fc441ba6f9ae4761b7ed0585c0000808805990108000001619f932823061bca52c900450c00000518076e341515ba04d9582c271ad0113b9eec89daf8b08ebaeeb00b0a8000102100a3230000000628f98c86f294b2408342000000d65639ec023ce0bc87315ca1680f3262e715db99b82c18800080c4018888800001596176a20970839bc6c386ab992049a010800001165c5ab2823060bb87a15a395f0afc0a005b9e08a2c4a27e1582c0001822c188000814401448084000002b0c0f68c11830315ea81a1ff8901cd0c0000045913a65c08f382f71ac57385883cbe0c641b58521d003d41609000060c20082460000008c0e9d5b0311ef05cfe08040c60408000000cb496b0061f3f828341030103581020000003014d07c078b020a0c040d
# 3/165 rev 1 MAP_ITS_01_165_15.1
020500ffef5d080003094d8342fc9a94efb0637d8b66b7d8b55cc60006014a04558f6b78713f201c028a364802284000001b33e3b8c100040ef7fab781e42500100fec303744f578961b0000202b1220002025889000103080699100000024d519dfa049209022245c40490888000011f11e60c01390a099d54a4820884400000afcd8fe8400100a0859557cd9ebc56150000618b0b800030e100a22200000049fe5d2fe0e7b1607ffb91207a210000002bee6440d0004027214555f367af0584c000186880491100000024f9f2a440e16ad00daef7100b22021000000b68056211811830e626d40e12172405242000000d9d5252d880023c10d5205c537262e3faab1707ce302c35000103c9018908000008673e753ea0008f05154c16fb5c40bb02bb05e073cc3f04474c781990a8f2b13721e25a9243d2ed82416230000a2020228440000008f9dd1e5009c8504ceaa5240724200000219d5058fa8002aed1c60400416f65cb0bc0abf45e6d3e43f0547505fed4183c9a4d90787da428f4b16060589400028892061a11000006cda81e3440010492091612197b20918f19604973cd51458510003092c24800184d6164000c28b0380007045824000382920e1210000004ce74320940010e2b41c1e8ad8538c2b2200202c0c801040c400c48800000126e8fad98211d6c2fe76488020901080000059cb06a5c08c182b8f2415ada64836480420000016667b4bda200ad407e67103ed3c02c3900020544038c8084000002cd075dd60460c124824088917240824021000004b3960b365100551176a63106d8f01160ed380b4c295c5d194622d7e9812681d23d0fa5153e0ff17b23d7ada3016250000a2c480428042000001665e96d0a200b06276ad495432f25a00202c3a000241c104d8102000000cca3ec05440179c0cf3d80a140a08041460408000003371db3e11005e704c50a0084c2410558102000000cdfd6c42440179c0f34c00a160b0a04166040800000339da94cd1005e70434d0028542c2c105d8102000000ccd1a110440179c0d3ba60a180c1704186040800000336ec8bb11005e704b3168285c306010658102000000bfd757351005e703a33782868346410698102000000cc6020f9440179c1123460a190d1a
# 3/1745 rev 3 MAP_ITS_17_1745_10.3
0205001232f808000309cd8342fc9a94efb16f7d8b768d6fb160b99c000c1b441aab20465ce27b0616200005142c9018500840000029cdab9811831be7757237397f3c160700002022006640420000014eca07808c18a1a4d701130f2480a28400000107be3e71bdfb7b02763f7313a5f2c02c0a00004084008c880000010fd80c408c00f14389e912009a100000022e1e3902466a17006191ec0583c000101880389100000022dc876e13eb63681e7ff09010d0084000002af164ba0460c9109184e38b68e58161100004082010240420000015767bcb8230627d6c7703d9f20205b020400000058a2ba0899615400405060185820630204000000388cc701917d014160818081ac08100000016992fc21847b50010141c061a081cc08100000017afb170258840141a081c
# 3/2052 rev 3 MAP_ITS_20_2052_12.3
020500ffb03a08000309cd8342fc9a94efb2617d9306acafb164b99c000c20101aab1e4648e2792cf4200005147090045088000012ae75c04981c3fc0af425700c8b0d200010758610000842c19000082560e8000414b08400020b100d4220000004ab43ef77211deee423f1e00806211000000255a2f7a5208797761300f50401888800000120b8a97e07cdbd20e6a7c4200e444000000905b146b83ac1f207a9bd5100822021000000b05b242b411830e6f7c81f28f50900c90800000220af6ee48700c2b164fc27a3da35900101604400060c200424400000095784205742e3bd205e9e6f2404242000000882c6b8f61c030a55ccf0ea80084ecde1f20586c0002021202921000000241669b230e1e8425a1908269058640002029204a21000000855a3271aa0901774433c9e8a19741bfa20c68e211d4cb282c1e000140890291080000042ad05397784753c821a86f430cb7ae071091c6a88f22548160d0000a024816880420000056ad90b85d822d41344f6086dcbd3e210366a115fba3080ea34047072f80b088000503040e604080000015718dfd3c06c3ac0a0f060e040f6040800000157df5fefc1944540a0e060f04104021000001b00937ad811510e408dc1d26fe87d4687c9364585f014220e20002240420000006ae33bf0a022a223e379604126040800000103c179400f8cf40a130813041360408000001041e69b010e1aa0a120812041460210000003023a78e8118303f92e02854245010558084000000c09b5a490460c1049a80a140915041660408000001045f4e6c1096560a170a16041760408000001042e41a40f71aa0a160a1704186021000000302ce4e841183042f95828642c6010658084000000c0a3d0730460c0f49aa0a180b19041a60408000001573d9dc4c0663de0a1b0c1a041b6040800000157b79dcbc195c2c0a1a0c1b041c602100000035734de22411830176f202874347010758084000000d5ec978a30460c195c1e0a1c0d1d
# 3/2349 rev 5 MAP_ITS_23_2349_7.5
0205001225f4080003094d8342fc9a94efb2677d93368e6fb75cd60006125a15558ef699713ed5421000028a32480628400000210dd38b307adb8d50fd212fb05ab16030deb8169c6c0b08400010410082220000004816f339a186c76031b42312051a1000000255ab37dd109db78654f907a8b15841000103ac160001018901c908000004210c0d4f8e26a6b0146282d061e1af13b19a906239b1158290001842c108000c24401448800000121c5b01c831e898595f156200824400000090dee85fc19d45c2ca58a824093420000004ab50afe2213b4f0ca9f2cf4d80b04800040524011402100000110d8195a09810c4e83c5748003d127582c3200014084030c8084000002559df82ee00f0ea08dc9e10900850800000221b5120e930ef8b0c5ea73302c0a9080585c0002818805991000000255a06819e01b8ee88c2ddec901890800000220e3cd351232117c07112216961cccdfcc16168000c14081ac081000000217ed2e681e2ca8141c0e1a081cc0810000002193cfa7820f60c141a0e1c081ec0810000002adab420381ed9f41420101e0820c0810000002add6c085a2165c10010141e12200822c08100000060cb4dc40230682d5d0400405090508820930204000001847937b208c182bb86c142216240826c08100000060280d8c023060529f5050a0589820a3020400000181c8366608c1a37f895001014261828082a804200000160148e0e022a2434b5e1b2adb7bdf182858342c00588084000000c0dddc35045451bec288008082e804200000060c78e3b022a282e1d34004050c0706000c101080000058494b9be08a8876547d07c51a820fb0204000000ab7a2ffd287ce9140040510078f821030204000000ab83efa6c083d85050f84100
# 3/2394 rev 4 MAP_ITS_23_2394_9.4
0205001230ec080003094d8342fc9a94efb2677d93372d2fb95cd2000612b411558ef699713ed5421000028a2a480248042000002276537e41352fa0187e4eae20b232790161b0000208201a840420000011f6e775412e4d4c2411a3120112100000044ee66e9026a8940b8f2153a91e74a8160b0e8000105100e42200000047dfcd300485b4f096d6b4480e680420000072711f1330e7745db154609e8e8505fb5cdc8f1480082a4e2f20d442b039f41fb073c33ae82c3500008309018d080000072739316c8e7765da151d0fd0e8bc55115a30148a96cadc3520920e8647a51ce54ec42b0420003075829000184080211100000024f4269620717400728cb5100522200000049e5055560e127a0e55974480648400000213bf6b5249c49d2e83edad69c14947809678005251e02c2500010184024c8800000126a950af02bc0d836a839920622100000043f9e5cf020dd9f8cc4ee1619511c880b058000503240b44200000087f6cb00845234f196fdc18329f38dc16090000a0448148840000020ff594ba084c6a632a037bc4536e52109921c0773ce0b092000601241734200000189bad43cc0ae830155b0460e67a77e1cf18dd60b5c581595995a2a11d90010161c800041c081e80420000026657d178823063261b84844d2dd4332fbbb814200e1400204042000001673b12d4823061c4b3983d6ea00208b020400000099d0c3b40635d2050904088209302040000009cf748780a3a32050884090209b02040000009d69d88c894d4e4004050a0489820a302040000009ce35ff00776720509850a020ab02040000009db5d5d286eaab4004050b058a820b302040000009e12d10408a578050a860b00
# 3/2421 rev 3 MAP_ITS_24_2421_4.3
020500ffa9ca080003094d8342fc9a94efb2697d93464c6fb45cce000612ea0d558ed997713d5c091000028a2648028824000050a83ba1c42fcf8a22e087009109a0126f6242756da84fc6101980f4cc2083ff41236e31890ef08087c4e20c2b0980001015859000284880491090000024c6167cf07d31607f246d24034420000028540df9e22a37b710e244384d34b50953af8002f8b09dcc26311ef95821d7ec091d316c482f86843e5f109158340000812c2c80014204018888000001262c947503ef8c83f623992029201080000089815d9100fd2321ef762924dc7229605824000101880221010800000470b7d8404e63d909567a4480e4840000011304dad2c1f7c643cdec4749c95458c0b0280002041002422000000470dace3000f7882439e992041211000008cc18aa2c0479c3d7a240b1de1d41834360edb79060d0f02c2d0000c14402cc888000011e4d25a0093c110c8907848146864000020f8173670c4b30018d83c010d28c03c8a60434a30ac24800101960c400080e48186844000010f59d338046c080a39070871382b80ac0900018296088000c16081ac0810000001ccd781a07ea53050703868207302040000007378cb1a2116410010141a101c081ec0810000001fa73a1e07d27c050804878208302040000007f22b6d020758c141e12200822c081000000178e62a013b7c0142414220824c0810000001f3ca9d00ba20a05088509020ab020400000073a1c3a21e79fd0010142c102a082cc08100000015dd6f682085ac142a0e2c0
# 3/2422 rev 3 MAP_ITS_24_2422_4.3
02050012453c080003094d8342fc9a94efb2697d93464cafb45cce000612ec0d558edbb6713db4271000028a1648022804200000124e7184f87144432d02ac1ce82c22000040440208808400000239b7ff2c25d5b508b8dd1490085080000011de03e583e53c5acb595d0a660b07800010210072220000004737bf2b84d6b881167b9c120312100000023a8ef010644b72a905e574d41607000040620062440000008f085cb40f9e8f21eeb18c90149048000011c9174ac213e70b207d4e6d02c12000081040104848000011e10b6ee1c5110c5a5113c0812c0810000001d8abc640881760505018482053020400000092cce1fa077ace050482050206b0204000000766ce9001dda20141c061a081cc0810000001dc574e0087969050682070
# 3/2423 rev 3 MAP_ITS_24_2423_9.3
020500ffaf52080003094d8342fc9a94efb2697d93464cefb95cce000612ee0d558ee835713e2ed41000025826481468400000088b6f52463d9757153c45e9d4160f0000208200e4440000008f4296df0e2a86e1ecf15c9024d0800000111547408c7b0eae2a78bbd3702c1a000041440188880000011e7df0461c550dc3d9e2b92041a100000082284fc10020e5088f1d20037b3c00ecf5020ce582c110000818401048c800001242f185c81e4ab42d4ffd920092100000043c2b6a5c38aa1b933e488c0b420307422b0b80003075821000209880599100000023519e4202759e188fd9e3c90149048000021e0d77d61c530dc99dd44445a12783c7158210002042c560000c0c90085088000011bc63d1247523222237efe748ac2c800142562a4008228480628400000211fb6ca700ece3a374ee35c0ea6360233e403ad8e0ac19000182960e8000c16202a6424000008d429a420020e508ef1e201035810200000035e96c980f8d040a0e070d040e604080000009203260103b5e0a0d070e040f60408000000e6ffd6f05a50802840203c1041810200000036ed72c00bd3ee0a0f0810041160408000000eb13c5803eb2e028482444104981020000002e34dc6040ac3828442448104d0084000000acddda4045a8104b2a0a140a0c001420210000002e85bc2d045a80fc4ba0
# 3/2429 rev 1 MAP_ITS_24_2429_6.1
020500ffbb17080003094d8342fc9a94efb2697d93464e6fb65cc6000612fa04558f3b5e713fb33b028a16480228400000136f2ba4725000401215623f755b21ddebb582c2e0000404402c8880000012dfd6ca280750f1915e966412010a10000004dbd7290ba4001003e4b042b99a21c94b9082c32000040840308880000012e038c9a88784f2c15e966412019210000010dbdbc972940010e7bbda2c97bff1682f008f119b1d1e4bf4583cc268205a4fd783cf46d201906bc0b09800030310091220000004b749f29e800e8ff11252858202b0204000001b7f012348800208e5ae05030202020330204000001b7c1b276e8002876a3e40242828141014101d8102000000dbca595644001468448a0121414100a0c0810c0810000006dd8f4bc2200081c6944140e0a0e081a80420000076e0c2cde820008b3db3a477dcd350b15b57c58d1a163cc668245cabe041ae1fe87b16e1b02838082000388084000000dbce298244001084d33a
# 3/256 rev 1 HH02\256\9
02050012346c08000304c890c195c64d5b5c7300030100022ac7c7a8389ef572014534240324200000199b50cc1808f38b1e5c807c676f18f952ee11f1a1fea4e0861aa276811138fd611600587400030088072110000002b900ea3011e700353b04e7c88240424200000199b6dce6408f38b1d9c807c586f30f920ee31f141fea4e0561a9276791138fd5d1600587c0003010807a110000002b9246ebc11e700353b04e7c88240524200000199b8ad0b208f38b1c9c847c486f40f8eeee61f0e5fea4e0261a9276711130fd5916015884000301ac46000181040410880000015ca3f9a608f3801a9d8273e440808a110000002b96af7dc11e700353b04e7c88240b442000000571d7c37823ce006a762ad88446502c1a0001c144018888000001670131d7023ce0fb1a50ec56f84818884000000aa643d2c11e700373b156c422328160f0000e0c200e444000000b37d28a1c11e707d8d28762b7c240d44200000055295c5008f3801d9d4ab62111942b088000707585100068408041110000002cde6e1600479c1f634a1d8adf04028c880000011f325e3c08ec100c403d24802284000000b2a9bc23811e75bcd3166800a473afb2445871000084ac3c80004296204000216b11200010c585400018b92010a10000008cb09f0250479c4f0bafa075fce43e54f8233801a29443e34fa00292c21000083560e800041cb06400020f240934200000087fd26b5061a9f32c43e2a2a926300681960c4001020b07200081158410004092c45000384d6208001c28b0f4000e15587200070b0209203040800009a074bf208199c0509848c00099030408000099eb539a07ea64041440608100001344da7180fbcc80a150a1900152060810000134a89790104b38082c80c1020000268d30788209670142e1634002e40c10200002681d27e81f7990106101820400004d2864f603fb3202864306c006481820400004d3121060406ce020d202040800007416c37821a98414362a38003640810200001597e8201e667c107101020400002a5dd2003d2cf828745874007481020400003997e22c10bcc2083c80810200001d5b7bf8086261050f8b8f000f90204080000744ecb581e867c1081010204000039a9661c0f433e0a21181f002120408100000e8e3e2604313082112010408000076bdee5821998414463240004640410200001d64324a079d9f042440208100000eadb837043530828946884009480820400002c7fcb703cccf8213302040800007dd2f3d02627b4144e0844084ec0810200001e603ea6067a13051302118214201040800007e57e7c82627ac14520a48005240410200001e24bc76067a15042a40408100000fd8f057033d0a028ac3c9400ac81020400004c661fc504c4f602162020408000098a5be020981e3051688130016902040800007edc7df01a087410b901020400003da3c5140cfc2e0a2f1127002f20408100000fafd0c004c2f48218202040800007dab80b82617a814622450006240810200001ee6a120067e16043240208100000fd1f170033f0b828cc4ca400cc80820400004c9ea08204c2f4821a201040800007a92935819f868146a2854006a40410200001f5223660985e6
# 4/937 rev 4 MAP_ITS_09_937_23.4
0205000161d3080003094d8342fc9a94efb0737dcb36f7d9335cd20008075210558f5971713d6892028a6e48042840000022c6c0b9c40010d27c262b5fd6d04692a02de8f01164b04b19200010158b40001012c52000080c4065088800001211eeb9c08d0254c4483312202c64440000090a2f2a1829ec3405110e71014322200000485d4143c159243427882192008a11000006b2582bd90004166f902ba8f452c7d7501092facf54856168000608b041000313100b22220000048d5f923a1e8ca5858a0c364834884400002306464ad90004015d544352e75e02e51c00ba5b00b94722b044000405585c0002830802091100000234af1c50537d8501afde48906110880000160b608c9a000909aaa420642eb9312c3a000141d62c4000810b14200040a100e22220000048d120fe61db6b2859b0bb64826684400001313ec197d000469d62738cf7293720e568530ac12000182560b0000c28481448440000231cb93bf500045a40a182d2b4fb0598c482df0b41673182b04200070b58cc00040612069211000004c758cba940011ff68eba3edcad4c98f33af20b14400090d24255422000005944a82e6800200e6cc0947a720b2a8000a0e102a7222000004b458cb5700fbdc216caba692132a11000002ca44829e4001000f6b84bcd2e0594c0005078814b9110000025a2ff5bea07dee10b655d34908d9088000036c157ae9620008c64ecc118d7540c43c89530219c6a7182caa0002c4090919088000036c1572f5020008c9c8d981894d3c643b214f12197ca6082ca60002c44900c50084000006b0d9ac051005512547788092989d1a09680f09c2b25fc2058bc000609080b990108000005848c15d208a8812d0442a086588028901080000056a9a355022a219c7894545fb0c481848440000131da833c900047bd54a98fceaa0b26b1ee3a02c5900024549054d088000046256038520008d6c074e12219ce00d127027048a809736016328001a2c080cc08100000059f94c10800203a66b0503870b8203b02040000016a67288a0008317654140c1c300810c081000000581d541a800203de8c0504878c8204b02040000016401421a000830b5e014101e34081ec081000000635166592000819c394142020360820c0810000005af6c0d2800209931b0507880e0208b02040000018ce5949a800209931b0509088e8209302040000018c788fca80020670e50508888f020db020400000184f62b94800205d0f7050e090f820e30204000001859fb09c80020a3309050d8910020eb02040000018403a50280020a130d050f0990820f30204000001836da038800205f0f3050e8991020fb02040000018461186c8002038a5905100a11821030204000001866015ec80020c79a7050f8a120210b0204000001892d9084800203ae7005110a928211302040000018a7e0e6280020c559005108a930213b0204000001b08a2b91e80020838d405140b13821430204000001b0860bebe800207cb2c05138b140215a0108000001895212308002039e6605160a948016101080000018aa8103e80020c659a042d60210000003615c97dc500040f26540a2e162a042e60210000003616d972b1000410e1ac0a2d162b042f4021000000317bf219900040ce9ca0a30112c00302021000000318a12bb10004131e36086280420000005a8846b080020c3d82051907168019101080000016740257200080f19f810cd0084000000b1909a7d00041862f60a340f2e0034202100000030f4e6219000407a50a086a8042000000633066aa200081b237c146c205e006c40420000005aa9c31e8002093b21043740210000003087f37a10004079d060a3814300038202100000030d202e990004186afa0
@@ -54,11 +54,12 @@ import com.hawhamburg.micr0bu.ui.screens.LanguageSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UnitsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.RideSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UseCaseAlertsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.V2xLogSettingsScreen
import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
import com.hawhamburg.micr0bu.viewmodel.RideSettingsViewModel
import com.hawhamburg.micr0bu.viewmodel.SensorViewModel
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
@@ -71,6 +72,7 @@ class MainActivity : AppCompatActivity() {
private val mqttViewModel: MqttViewModel by viewModels()
private val tripViewModel: TripRecordingViewModel by viewModels()
private val logViewModel: V2xLogViewModel by viewModels()
private val rideViewModel: RideSettingsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
@@ -97,6 +99,9 @@ class MainActivity : AppCompatActivity() {
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
val phoneMount by rideViewModel.phoneMount.collectAsState()
val fusionLogging by rideViewModel.fusionLogging.collectAsState()
val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
// Received hazards and live signal state, for the Dashboard's V2X summary cards.
// Both flows already expire their own entries on a clock, so nothing here has to
// decide when a hazard or a traffic light has gone stale.
@@ -303,7 +308,7 @@ class MainActivity : AppCompatActivity() {
onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) },
onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.route) },
onOpenSensors = { navController.navigate(Screen.SettingsSensors.route) },
onOpenUnits = { navController.navigate(Screen.SettingsUnits.route) },
onOpenRide = { navController.navigate(Screen.SettingsRide.route) },
onOpenConnection = { navController.navigate(Screen.SettingsConnection.route) },
onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) },
onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) },
@@ -328,6 +333,8 @@ class MainActivity : AppCompatActivity() {
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
outgoingMessage = outgoingMessage,
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
esp32RxPath = esp32RxPath,
onEsp32RxPathChange = mqttViewModel::setEsp32RxPath,
signOutgoing = signOutgoing,
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
onBack = { navController.popBackStack() },
@@ -354,11 +361,13 @@ class MainActivity : AppCompatActivity() {
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsUnits.route) {
UnitsSettingsScreen(
useMetric = state.useMetric,
onUseMetric = viewModel::setUseMetric,
onBack = { navController.popBackStack() },
composable(Screen.SettingsRide.route) {
RideSettingsScreen(
phoneMount = phoneMount,
onPhoneMount = rideViewModel::setPhoneMount,
fusionLogging = fusionLogging,
onFusionLogging = rideViewModel::setFusionLogging,
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsMqtt.route) {
@@ -58,6 +58,20 @@ object GnssTimeSource {
return ItsTime.onGnssTime(systemMs, lastErrorMs?.let { systemNow + it }, systemNow)
}
/**
* GNSS time of an instant given on the monotonic `elapsedRealtimeNanos` base, such as a fix's
* [GnssReading.elapsedRealtimeNanos]: GNSS time now, minus the instant's age.
*
* Prefer this to [correct] on a stored wall-clock stamp. The age comes from the monotonic
* clock, and the wall clock is only read now, inside [correct], where its error cancels out.
* A phone clock that is stepped between the fix and its transmission (automatic time catching
* up, or someone setting it) therefore cannot move the result.
*/
fun atElapsedRealtime(elapsedRealtimeNanos: Long): Long {
val ageMs = (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
return correct(System.currentTimeMillis() - ageMs)
}
private fun noteSource(gnssNow: Long?, systemNow: Long) {
val usingGnss = gnssNow != null
if (lastUsedGnss == usingGnss) return
@@ -0,0 +1,49 @@
package com.hawhamburg.micr0bu.data
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
private val Context.rideDataStore by preferencesDataStore(name = "ride_prefs")
/**
* Settings > Ride: where the phone rides ([PhoneMount]) and whether the V2X data logger also
* records the motion sensors and raw GPS for sensor fusion (see `docs/07-sensor-fusion-logging.md`).
*/
@Singleton
class RidePreferences @Inject constructor(
@ApplicationContext private val context: Context,
) {
private object Keys {
val PHONE_MOUNT = stringPreferencesKey("phone_mount")
val FUSION_LOGGING = booleanPreferencesKey("fusion_logging")
}
val phoneMountFlow: Flow<PhoneMount> = context.rideDataStore.data.map { prefs ->
PhoneMount.fromId(prefs[Keys.PHONE_MOUNT])
}
suspend fun setPhoneMount(mount: PhoneMount) {
context.rideDataStore.edit { it[Keys.PHONE_MOUNT] = mount.id }
}
/**
* Off by default: at 100 Hz the motion sensors add about 300 rows a second, tens of MB per
* hour, which only a fusion test ride needs.
*/
val fusionLoggingFlow: Flow<Boolean> = context.rideDataStore.data.map { prefs ->
prefs[Keys.FUSION_LOGGING] ?: false
}
suspend fun setFusionLogging(enabled: Boolean) {
context.rideDataStore.edit { it[Keys.FUSION_LOGGING] = enabled }
}
}
@@ -6,6 +6,10 @@ import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.SystemClock
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
@@ -15,13 +19,35 @@ import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
/**
* One sample of a three-axis sensor.
*
* @property timestamp wall-clock ms of the moment the sample was taken (not of its delivery), for
* logs and the UI, which compare it with other wall-clock stamps.
* @property elapsedRealtimeNanos the sample's own `SensorEvent.timestamp`, on the
* `SystemClock.elapsedRealtimeNanos` base. Monotonic: use it for intervals and for lining samples
* up with GNSS fixes, never [timestamp], which jumps whenever the phone's clock is set.
*/
data class ImuReading(
val x: Float,
val y: Float,
val z: Float,
val timestamp: Long = System.currentTimeMillis()
val timestamp: Long = System.currentTimeMillis(),
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
)
/**
* One location fix.
*
* @property timestamp wall-clock ms of the moment of the fix (not of its delivery), for in-app
* comparisons with other wall-clock stamps. What goes on air is GNSS time instead, from
* [GnssTimeSource.atElapsedRealtime] on [elapsedRealtimeNanos].
* @property elapsedRealtimeNanos `Location.getElapsedRealtimeNanos()`: the moment of the fix on the
* monotonic clock that sensor samples are also stamped with. Use it for intervals between fixes.
* @property speedAccuracyMps 1-sigma speed accuracy, null when the provider gives none.
* @property bearingAccuracyDeg 1-sigma bearing accuracy, null when the provider gives none.
* @property provider the location provider that produced the fix, e.g. "fused" or "gps".
*/
data class GnssReading(
val latitude: Double,
val longitude: Double,
@@ -29,7 +55,11 @@ data class GnssReading(
val speedMs: Float,
val bearingDeg: Float,
val accuracyM: Float,
val timestamp: Long = System.currentTimeMillis()
val timestamp: Long = System.currentTimeMillis(),
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
val speedAccuracyMps: Float? = null,
val bearingAccuracyDeg: Float? = null,
val provider: String? = null,
)
class SensorRepository(private val context: Context) {
@@ -37,12 +67,30 @@ class SensorRepository(private val context: Context) {
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val fusedLocation = LocationServices.getFusedLocationProviderClient(context)
fun accelerometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_ACCELEROMETER)
/**
* @param samplingPeriodUs a `SensorManager.SENSOR_DELAY_*` constant or a period in µs. The
* default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
*/
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun gyroscopeFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_GYROSCOPE)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs, handler)
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
/**
* Gravity in the device frame, m/s². Points up (it reads +9.81 on z with the phone flat, screen
* up), as the accelerometer does at rest.
*
* From the platform's `TYPE_GRAVITY` virtual sensor, which separates gravity from motion with
* the gyroscope. On a phone without it the raw accelerometer stands in, which still carries
* the bike's own accelerations and vibration.
*/
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs, handler)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun barometerFlow(): Flow<Float> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
if (sensor == null) {
@@ -75,9 +123,37 @@ class SensorRepository(private val context: Context) {
awaitClose { fusedLocation.removeLocationUpdates(callback) }
}
/**
* Fixes from the platform's `GPS_PROVIDER` alone, next to [gnssFlow]'s fused location: no Wi-Fi
* or cell positions mixed in and no smoothing by Google Play services, so a fusion filter sees
* the GNSS chip's own errors. As fast as the chip delivers (minimum time and distance 0); on
* most phones that is 1 Hz.
*/
@Suppress("MissingPermission")
fun gpsProviderFlow(): Flow<GnssReading> = callbackFlow {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val listener = LocationListener { loc -> trySend(loc.toReading()) }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, listener, context.mainLooper)
awaitClose { locationManager.removeUpdates(listener) }
}
/** "name (vendor), max N Hz" for the sensor of [type], or null if the phone has none. For log metadata. */
fun describeSensor(type: Int): String? = sensorManager.getDefaultSensor(type)?.let { s ->
val maxHz = if (s.minDelay > 0) ", max ${1_000_000 / s.minDelay} Hz" else ""
"${s.name} (${s.vendor})$maxHz"
}
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
private fun sensorFlow(type: Int): Flow<ImuReading> = callbackFlow {
/**
* @param handler where sensor callbacks run; null for the main thread. A high-rate consumer
* passes a background handler so 100 Hz callbacks neither wait on nor slow down the UI.
*/
private fun sensorFlow(
type: Int,
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
handler: Handler? = null,
): Flow<ImuReading> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(type)
if (sensor == null) {
close()
@@ -85,20 +161,42 @@ class SensorRepository(private val context: Context) {
}
val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
trySend(ImuReading(event.values[0], event.values[1], event.values[2]))
trySend(ImuReading(
x = event.values[0],
y = event.values[1],
z = event.values[2],
timestamp = wallClockMsAt(event.timestamp),
elapsedRealtimeNanos = event.timestamp,
))
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
sensorManager.registerListener(listener, sensor, samplingPeriodUs, handler)
awaitClose { sensorManager.unregisterListener(listener) }
}
}
private fun Location.toReading() = GnssReading(
latitude = latitude,
longitude = longitude,
altitude = altitude,
speedMs = speed,
bearingDeg = bearing,
accuracyM = accuracy
)
/**
* The wall-clock ms of an instant given on the `elapsedRealtimeNanos` base: now minus its age.
* Both clocks are read together, so a clock change only moves the result by the change itself.
*/
private fun wallClockMsAt(elapsedRealtimeNanos: Long): Long =
System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
private fun Location.toReading(): GnssReading {
// A fix without its own monotonic stamp (0, as some mock providers leave it) is taken as now.
val fixNanos = elapsedRealtimeNanos.takeIf { it > 0L } ?: SystemClock.elapsedRealtimeNanos()
return GnssReading(
latitude = latitude,
longitude = longitude,
altitude = altitude,
speedMs = speed,
bearingDeg = bearing,
accuracyM = accuracy,
timestamp = wallClockMsAt(fixNanos),
elapsedRealtimeNanos = fixNanos,
speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond else null,
bearingAccuracyDeg = if (hasBearingAccuracy()) bearingAccuracyDegrees else null,
provider = provider,
)
}
@@ -30,7 +30,9 @@ import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
import com.hawhamburg.micr0bu.domain.cam.OwnTxLoopback
import com.hawhamburg.micr0bu.domain.cam.StationType
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.MapEvent
import com.hawhamburg.micr0bu.domain.map.StoredMaps
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
@@ -210,6 +212,10 @@ class CamUseCaseRepository @Inject constructor(
*/
val decodedMap: SharedFlow<MapEvent> = _decodedMap.asSharedFlow()
private val _storedMaps = MutableStateFlow<List<IntersectionGeometry>>(emptyList())
/** The intersections the app ships with ([StoredMaps]); empty until the asset has been read. */
val storedMaps: StateFlow<List<IntersectionGeometry>> = _storedMaps.asStateFlow()
private val _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
/**
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
@@ -220,6 +226,17 @@ class CamUseCaseRepository @Inject constructor(
val decodedDenm: SharedFlow<DenmEvent> = _decodedDenm.asSharedFlow()
init {
scope.launch {
runCatching {
context.assets.open(StoredMaps.ASSET_PATH).bufferedReader().use { StoredMaps.parse(it.readText()) }
}
.onSuccess {
_storedMaps.value = it
Log.d(TAG, "storedMaps: ${it.size} intersection revisions loaded")
}
.onFailure { Log.e(TAG, "storedMaps: cannot read ${StoredMaps.ASSET_PATH}", it) }
}
scope.launch {
mqttRepository.messages.collect { msg ->
when (msg.topic) {
@@ -15,6 +15,13 @@ data class LogGnss(
val accuracyM: Double? = null,
/** Epoch ms the fix was taken, so a stale fix shows as one instead of passing for current. */
val fixMs: Long,
/** The fix's own monotonic time (`Location.getElapsedRealtimeNanos`); phone fixes only. */
val elapsedNs: Long? = null,
/** 1-sigma speed and bearing accuracy, where the provider gives them; phone fixes only. */
val speedAccuracyMps: Double? = null,
val bearingAccuracyDeg: Double? = null,
/** The location provider, e.g. `fused` or `gps`; phone fixes only. */
val provider: String? = null,
)
/** One received V2X message, ready to be written. */
@@ -45,6 +52,18 @@ class LogMessage(
/** One GNSS fix for the `gnss` table: the receiver's own track, independent of any message. */
class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss)
/**
* One motion sensor sample for the `imu` table (sensor fusion logging only). [sensor] is `accel`,
* `gyro` or `gravity`; [elapsedNs] the sample's own `SensorEvent.timestamp`.
*/
class LogImuSample(val sensor: String, val elapsedNs: Long, val tsMs: Long, val x: Float, val y: Float, val z: Float)
/**
* The phone's three clocks read together, for the `clock` table: what lines the monotonic sensor
* and fix times up with wall-clock and GNSS time afterwards. [gnssMs] is null without GNSS time.
*/
class LogClockSample(val elapsedNs: Long, val wallMs: Long, val gnssMs: Long?)
/**
* A V2X log: one self-contained SQLite file. Not Room, on purpose: a log is a file the developer
* pulls off the phone and opens in any SQLite tool or pandas, so it carries its own schema and
@@ -57,12 +76,19 @@ class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss)
* Columns that do not apply to a row are NULL rather than invented: `rssi_dbm` is NULL for the
* CiT One, `obu_*` is NULL when no OBU position is available (always on the ESP32-C5, which has no
* GNSS), and the `sender_*` fields are NULL for messages the app has no decoder for.
*
* Schema 2 (2026-11-18) adds what sensor fusion needs, described in
* `docs/07-sensor-fusion-logging.md`: the monotonic time, accuracies and provider of each phone fix
* in `gnss`, and the `imu` and `clock` tables. Those two stay empty unless Settings > Ride >
* "Record motion sensors" was on when the log started.
*/
class V2xLogWriter(val file: File, meta: Map<String, String>) {
private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null)
private val insertMessage: SQLiteStatement
private val insertGnss: SQLiteStatement
private val insertImu: SQLiteStatement
private val insertClock: SQLiteStatement
init {
db.execSQL(
@@ -121,11 +147,39 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
speed_mps REAL,
heading_deg REAL,
accuracy_m REAL,
fix_ms INTEGER NOT NULL
fix_ms INTEGER NOT NULL,
elapsed_ns INTEGER,
speed_accuracy_mps REAL,
bearing_accuracy_deg REAL,
provider TEXT
)
""".trimIndent()
)
db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)")
// No index: about 300 rows a second, read back in order by replay, never searched on the phone.
db.execSQL(
"""
CREATE TABLE imu (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sensor TEXT NOT NULL,
elapsed_ns INTEGER NOT NULL,
ts_ms INTEGER NOT NULL,
x REAL NOT NULL,
y REAL NOT NULL,
z REAL NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE clock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
elapsed_ns INTEGER NOT NULL,
wall_ms INTEGER NOT NULL,
gnss_ms INTEGER
)
""".trimIndent()
)
// Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI.
db.execSQL(
"CREATE VIEW messages_v AS SELECT *, " +
@@ -144,8 +198,14 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
"obu_heading_deg, obu_fix_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertGnss = db.compileStatement(
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms) " +
"VALUES (?,?,?,?,?,?,?,?,?)"
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms, " +
"elapsed_ns, speed_accuracy_mps, bearing_accuracy_deg, provider) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertImu = db.compileStatement(
"INSERT INTO imu (sensor, elapsed_ns, ts_ms, x, y, z) VALUES (?,?,?,?,?,?)"
)
insertClock = db.compileStatement(
"INSERT INTO clock (elapsed_ns, wall_ms, gnss_ms) VALUES (?,?,?)"
)
}
@@ -153,13 +213,20 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value))
}
/** Writes [messages] and [gnss] in one transaction. */
fun writeBatch(messages: List<LogMessage>, gnss: List<LogGnssSample>) {
if (messages.isEmpty() && gnss.isEmpty()) return
/** Writes all rows in one transaction. */
fun writeBatch(
messages: List<LogMessage>,
gnss: List<LogGnssSample>,
imu: List<LogImuSample> = emptyList(),
clock: List<LogClockSample> = emptyList(),
) {
if (messages.isEmpty() && gnss.isEmpty() && imu.isEmpty() && clock.isEmpty()) return
db.beginTransaction()
try {
for (m in messages) bindAndRun(m)
for (g in gnss) bindAndRun(g)
for (i in imu) bindAndRun(i)
for (c in clock) bindAndRun(c)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
@@ -169,6 +236,8 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
fun close() {
runCatching { insertMessage.close() }
runCatching { insertGnss.close() }
runCatching { insertImu.close() }
runCatching { insertClock.close() }
runCatching { db.close() }
}
@@ -220,6 +289,31 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
s.bind(7, g.fix.headingDeg)
s.bind(8, g.fix.accuracyM)
s.bind(9, g.fix.fixMs)
s.bind(10, g.fix.elapsedNs)
s.bind(11, g.fix.speedAccuracyMps)
s.bind(12, g.fix.bearingAccuracyDeg)
s.bind(13, g.fix.provider)
s.executeInsert()
}
private fun bindAndRun(i: LogImuSample) {
val s = insertImu
s.clearBindings()
s.bind(1, i.sensor)
s.bind(2, i.elapsedNs)
s.bind(3, i.tsMs)
s.bind(4, i.x.toDouble())
s.bind(5, i.y.toDouble())
s.bind(6, i.z.toDouble())
s.executeInsert()
}
private fun bindAndRun(c: LogClockSample) {
val s = insertClock
s.clearBindings()
s.bind(1, c.elapsedNs)
s.bind(2, c.wallMs)
s.bind(3, c.gnssMs)
s.executeInsert()
}
@@ -230,6 +324,6 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
private fun SQLiteStatement.bind(i: Int, v: ByteArray?) { if (v != null) bindBlob(i, v) }
companion object {
const val SCHEMA_VERSION = 1
const val SCHEMA_VERSION = 2
}
}
@@ -1,9 +1,16 @@
package com.hawhamburg.micr0bu.data.log
import android.content.Context
import android.hardware.Sensor
import android.location.LocationManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.ImuReading
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.data.SensorRepository
import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository
import com.hawhamburg.micr0bu.data.mqtt.MessageDirection
@@ -23,6 +30,7 @@ import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import com.hawhamburg.micr0bu.domain.log.classifyItsPdu
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -32,14 +40,18 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File
import java.time.DateTimeException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -52,9 +64,18 @@ private const val PROCESSED_PREFIX = "v2x-uca/output/json/"
private const val OBU_GNSS_TOPIC = "v2x/rx/obu_gnss"
private const val SOURCE_ESP32 = "esp32"
private const val SOURCE_CIT_ONE = "cit_one"
/** The phone's fused location (Google Play services). */
private const val SOURCE_PHONE = "phone"
/** The phone's raw `GPS_PROVIDER` fixes; sensor fusion logging only. */
private const val SOURCE_PHONE_GPS = "phone_gps"
private const val SOURCE_OBU = "obu"
/** Motion sensor rate while sensor fusion logging is on: 10 000 us, 100 Hz. */
private const val IMU_PERIOD_US = 10_000
/** How often the three clocks are read together into the `clock` table. */
private const val CLOCK_INTERVAL_MS = 1_000L
/** How long the writer collects rows before it commits them. */
private const val FLUSH_INTERVAL_MS = 250L
@@ -70,6 +91,13 @@ data class V2xLogState(
/** Age of the newest phone / OBU fix at the time of the last update; null if none yet. */
val phoneFixAgeMs: Long? = null,
val obuFixAgeMs: Long? = null,
/** Whether this log records the motion sensors and raw GPS (Settings > Ride), and the mount it started with. */
val fusionLogging: Boolean = false,
val phoneMount: PhoneMount? = null,
/** Motion sensor rows written so far. */
val imuSamples: Long = 0L,
/** Age of the newest raw GPS_PROVIDER fix; null if none yet or not logging it. */
val phoneGpsFixAgeMs: Long? = null,
/** Set when the file could not be created or written. */
val error: String? = null,
)
@@ -101,6 +129,11 @@ data class V2xLogFile(val file: File, val sizeBytes: Long, val modifiedMs: Long,
* BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only
* messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One.
*
* With Settings > Ride > "Record motion sensors" on when the log starts, it also records what sensor
* fusion needs (`docs/07-sensor-fusion-logging.md`): accelerometer, gyroscope and gravity at 100 Hz
* into `imu`, the raw `GPS_PROVIDER` fixes next to the fused ones in `gnss`, and the three phone
* clocks once a second into `clock`. The phone mount is recorded in `meta` either way.
*
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
* keeps the process alive and the CPU awake while a log runs; this class does the work.
*/
@@ -111,6 +144,7 @@ class V2xLogger @Inject constructor(
private val esp32Link: Esp32Link,
private val camUseCaseRepository: CamUseCaseRepository,
private val camCodec: RealAsn1UperCodec,
private val ridePreferences: RidePreferences,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -127,15 +161,22 @@ class V2xLogger @Inject constructor(
private var rows = Channel<Any>(Channel.UNLIMITED)
@Volatile private var phoneFix: LogGnss? = null
@Volatile private var phoneGpsFix: LogGnss? = null
@Volatile private var obuFix: LogGnss? = null
fun start() {
if (session?.isActive == true) return
val startedMs = System.currentTimeMillis()
val hardware = mqttRepository.obuHardware.value
val file = File(logDir, fileNameFor(startedMs, hardware))
// Read once, at the start: a log is one mount and one mode, so changing either mid-log
// must not quietly mix two kinds of data in one file. DataStore answers in milliseconds.
val (mount, fusion) = runBlocking {
ridePreferences.phoneMountFlow.first() to ridePreferences.fusionLoggingFlow.first()
}
val sensors = SensorRepository(context)
val file = File(logDir, fileNameFor(startedMs, hardware, mount.takeIf { fusion }))
val writer = try {
V2xLogWriter(file, metaFor(startedMs, hardware))
V2xLogWriter(file, metaFor(startedMs, hardware, mount, fusion, sensors))
} catch (e: Exception) {
Log.e(TAG, "cannot create ${file.name}", e)
file.delete()
@@ -143,22 +184,36 @@ class V2xLogger @Inject constructor(
return
}
phoneFix = null
phoneGpsFix = null
obuFix = null
rows = Channel(Channel.UNLIMITED)
_state.value = V2xLogState(active = true, fileName = file.name, startedMs = startedMs)
_state.value = V2xLogState(
active = true, fileName = file.name, startedMs = startedMs,
fusionLogging = fusion, phoneMount = mount,
)
refreshFiles()
// Sensor callbacks at 100 Hz get a thread of their own, off the main thread.
val sensorThread = if (fusion) HandlerThread("V2xLogger-imu").apply { start() } else null
session = scope.launch {
val sources = listOf(
val sources = mutableListOf(
launch { collectEsp32() },
launch { collectCitOneRaw() },
launch { collectCitOneMessages() },
launch { collectPhoneGnss() },
launch { collectPhoneGnss(sensors) },
)
if (sensorThread != null) {
val handler = Handler(sensorThread.looper)
sources += launch { collectImu(sensors, handler) }
sources += launch { collectPhoneGps(sensors) }
sources += launch { collectClock() }
}
try {
runWriter(writer, file)
} finally {
sources.forEach { it.cancel() }
sensorThread?.quitSafely()
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
writer.close()
}
@@ -258,8 +313,7 @@ class V2xLogger @Inject constructor(
* can be started before the location permission is granted, and a single attempt would then
* leave every row without a phone position for the whole run.
*/
private suspend fun collectPhoneGnss() {
val sensors = SensorRepository(context)
private suspend fun collectPhoneGnss(sensors: SensorRepository) {
while (true) {
runCatching {
sensors.gnssFlow().collect { reading ->
@@ -272,6 +326,50 @@ class V2xLogger @Inject constructor(
}
}
/** Raw `GPS_PROVIDER` fixes, retried like [collectPhoneGnss] in case permission comes later. */
private suspend fun collectPhoneGps(sensors: SensorRepository) {
while (true) {
runCatching {
sensors.gpsProviderFlow().collect { reading ->
val fix = reading.toLogGnss()
phoneGpsFix = fix
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE_GPS, fix))
}
}
delay(5_000L)
}
}
/** Accelerometer, gyroscope and gravity at 100 Hz, each sample with its own monotonic time. */
private suspend fun collectImu(sensors: SensorRepository, handler: Handler) = coroutineScope {
launch { sensors.accelerometerFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("accel")) } }
launch { sensors.gyroscopeFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gyro")) } }
// Only from the real TYPE_GRAVITY sensor: gravityFlow's accelerometer stand-in would only
// repeat the accel rows under another name.
if (sensors.hasSensor(Sensor.TYPE_GRAVITY)) {
launch { sensors.gravityFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gravity")) } }
}
}
/**
* The monotonic, wall and GNSS clocks read back to back once a second. Sensor samples and fixes
* carry monotonic time, messages and OBU fixes wall time, and the transmit path GNSS time; these
* rows convert between them, and show the phone clock's error and any step in it.
*/
private suspend fun collectClock() {
while (true) {
val elapsedNs = SystemClock.elapsedRealtimeNanos()
val wallMs = System.currentTimeMillis()
val gnssMs = try {
SystemClock.currentGnssTimeClock().millis()
} catch (e: DateTimeException) {
null
}
rows.trySend(LogClockSample(elapsedNs, wallMs, gnssMs))
delay(CLOCK_INTERVAL_MS)
}
}
// ── Rows ──────────────────────────────────────────────────────────────────
private fun enqueueRaw(
@@ -344,20 +442,23 @@ class V2xLogger @Inject constructor(
var failure: String? = null
val messages = ArrayList<LogMessage>()
val gnss = ArrayList<LogGnssSample>()
val imu = ArrayList<LogImuSample>()
val clock = ArrayList<LogClockSample>()
var imuTotal = 0L
while (true) {
// Block for the first row of a batch, give more a moment to arrive, then take
// whatever is queued. No timeout around receive: a cancelled receive can lose the
// element it was handing over, which a logger must not do.
val first = rows.receiveCatching().getOrNull() ?: break
add(first, messages, gnss)
add(first, messages, gnss, imu, clock)
delay(FLUSH_INTERVAL_MS)
while (true) {
val next = rows.tryReceive().getOrNull() ?: break
add(next, messages, gnss)
add(next, messages, gnss, imu, clock)
}
try {
writer.writeBatch(messages, gnss)
writer.writeBatch(messages, gnss, imu, clock)
} catch (e: Exception) {
// Disk full or the file went away. Say so on screen rather than logging into a void.
Log.e(TAG, "write failed", e)
@@ -367,7 +468,8 @@ class V2xLogger @Inject constructor(
}
for (m in messages) counts.merge(m.kind, 1, Int::plus)
total += messages.size
messages.clear(); gnss.clear()
imuTotal += imu.size
messages.clear(); gnss.clear(); imu.clear(); clock.clear()
val now = System.currentTimeMillis()
_state.update {
@@ -375,16 +477,26 @@ class V2xLogger @Inject constructor(
counts = counts.toMap(), total = total, fileBytes = file.length(),
phoneFixAgeMs = phoneFix?.let { f -> now - f.fixMs },
obuFixAgeMs = obuFix?.let { f -> now - f.fixMs },
imuSamples = imuTotal,
phoneGpsFixAgeMs = phoneGpsFix?.let { f -> now - f.fixMs },
)
}
}
_state.update { it.copy(fileBytes = file.length(), error = failure ?: it.error, active = it.active && failure == null) }
}
private fun add(row: Any, messages: MutableList<LogMessage>, gnss: MutableList<LogGnssSample>) {
private fun add(
row: Any,
messages: MutableList<LogMessage>,
gnss: MutableList<LogGnssSample>,
imu: MutableList<LogImuSample>,
clock: MutableList<LogClockSample>,
) {
when (row) {
is LogMessage -> messages += row
is LogGnssSample -> gnss += row
is LogImuSample -> imu += row
is LogClockSample -> clock += row
}
}
@@ -402,23 +514,54 @@ class V2xLogger @Inject constructor(
latitude = latitude, longitude = longitude, altitudeM = altitude,
speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(),
accuracyM = accuracyM.toDouble(), fixMs = timestamp,
elapsedNs = elapsedRealtimeNanos,
speedAccuracyMps = speedAccuracyMps?.toDouble(),
bearingAccuracyDeg = bearingAccuracyDeg?.toDouble(),
provider = provider,
)
private fun fileNameFor(startedMs: Long, hardware: ObuHardware): String {
private fun ImuReading.toLogImu(sensor: String) =
LogImuSample(sensor, elapsedRealtimeNanos, timestamp, x, y, z)
/** `v2x_log_<start>_<hardware>.db`, with `_imu-<mount>` when it records sensor fusion data. */
private fun fileNameFor(startedMs: Long, hardware: ObuHardware, fusionMount: PhoneMount?): String {
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(startedMs))
val mode = if (hardware == ObuHardware.ESP32_C5) "esp32" else "citone"
return "v2x_log_${stamp}_$mode.db"
val fusion = fusionMount?.let { "_imu-${it.id}" }.orEmpty()
return "v2x_log_${stamp}_$mode$fusion.db"
}
private fun metaFor(startedMs: Long, hardware: ObuHardware) = mapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5.",
)
private fun metaFor(
startedMs: Long,
hardware: ObuHardware,
mount: PhoneMount,
fusion: Boolean,
sensors: SensorRepository,
): Map<String, String> {
val meta = linkedMapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"phone_mount" to mount.id,
"fusion_logging" to fusion.toString(),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5. gnss.source: phone = " +
"fused location, phone_gps = raw GPS_PROVIDER, obu = the CiT One's obu_gnss. " +
"elapsed_ns is SystemClock.elapsedRealtimeNanos; the clock table converts it to wall " +
"and GNSS time. See docs/07-sensor-fusion-logging.md.",
)
if (fusion) {
meta["imu_period_us"] = IMU_PERIOD_US.toString()
sensors.describeSensor(Sensor.TYPE_ACCELEROMETER)?.let { meta["sensor_accel"] = it }
sensors.describeSensor(Sensor.TYPE_GYROSCOPE)?.let { meta["sensor_gyro"] = it }
meta["sensor_gravity"] = sensors.describeSensor(Sensor.TYPE_GRAVITY) ?: "none (not logged)"
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
meta["gnss_hardware"] = "${lm.gnssHardwareModelName ?: "?"} (year ${lm.gnssYearOfHardware})"
}
return meta
}
}
@@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
@@ -38,6 +39,7 @@ class ObuHardwarePreferences @Inject constructor(
// ESP32-C5 only.
val ESP32_TRANSPORT = stringPreferencesKey("esp32_transport")
val OUTGOING_MESSAGE = stringPreferencesKey("outgoing_message")
val ESP32_RX_PATH = stringPreferencesKey("esp32_rx_path")
val SIGN_OUTGOING = booleanPreferencesKey("sign_outgoing")
}
@@ -58,6 +60,15 @@ class ObuHardwarePreferences @Inject constructor(
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_TRANSPORT] = transport.id }
}
/** Where received ITS messages come from on the ESP32-C5 path: V2X_RX (default) or the RAW_FRAME debug capture. */
val esp32RxPathFlow: Flow<Esp32RxPath> = context.obuHardwareDataStore.data.map { prefs ->
Esp32RxPath.entries.firstOrNull { it.id == prefs[Keys.ESP32_RX_PATH] } ?: Esp32RxPath.V2X_RX
}
suspend fun setEsp32RxPath(path: Esp32RxPath) {
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_RX_PATH] = path.id }
}
/** What the ESP32-C5 path transmits while recording: CAM (default) or VAM. */
val outgoingMessageFlow: Flow<OutgoingMessage> = context.obuHardwareDataStore.data.map { prefs ->
OutgoingMessage.entries.firstOrNull { it.id == prefs[Keys.OUTGOING_MESSAGE] } ?: OutgoingMessage.CAM
@@ -39,6 +39,21 @@ enum class Esp32LinkState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED,
/** Which physical link the phone uses to reach the ESP32-C5 (Settings). */
enum class Esp32Transport(val id: String) { USB("usb"), BLE("ble") }
/**
* Where the app takes received ITS messages from (Settings > Connection > ESP32-C5 > Receive path).
*
* - [V2X_RX]: the MicrOBU extension (opcode 0x90). The board unwraps every received frame itself and
* sends the finished ITS message, signed or not. Small, always on, the default.
* - [RAW_FRAME]: the station-link `RAW_FRAME` debug capture of docs/station-link.pdf (opcode 0x85,
* switched on with `RAW_CAPTURE`). The board sends the whole 802.11 frame, possibly fragmented, and
* the app unwraps it with [GnUnwrap]. Spec-defined and not limited to 494 octets, but best effort:
* copies can be dropped when the link is busy, and it costs more bandwidth, especially over BLE.
*
* Both reach the rest of the app as the same [SerialFrameType.V2X_RX] frames, so nothing above this
* class changes with the setting. The board keeps sending `V2X_RX` regardless; the app uses one path.
*/
enum class Esp32RxPath(val id: String) { V2X_RX("v2x_rx"), RAW_FRAME("raw_frame") }
/** What the phone transmits while a trip records (Settings). */
enum class OutgoingMessage(val id: String) { CAM("cam"), VAM("vam") }
@@ -96,6 +111,8 @@ class Esp32Link @Inject constructor(
private const val TAG = "Esp32Link"
private const val REPLY_TIMEOUT_MS = 3_000L
private const val STATUS_POLL_MS = 1_000L
/** RAW_CAPTURE mode: on (bit 0) and broadcast frames only (bit 1): every ITS-G5 frame, no unicast noise. */
private const val RAW_CAPTURE_ON_BROADCAST = 0x03
/** Applying a bundle verifies the chain and rebuilds the stack on the C5: seconds, not ms. */
private const val PROVISION_TIMEOUT_MS = 15_000L
private const val SEGMENT_SIZE = 240
@@ -124,6 +141,17 @@ class Esp32Link @Inject constructor(
val transport: StateFlow<Esp32Transport> =
prefs.esp32TransportFlow.stateIn(scope, SharingStarted.Eagerly, Esp32Transport.USB)
/** Which received-message path is in use. See [Esp32RxPath]. */
val rxPath: StateFlow<Esp32RxPath> =
prefs.esp32RxPathFlow.stateIn(scope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
/** Fragments of RAW_FRAME (and any other large indication) in flight; reset with every session. */
private val reassembly = LinkReassembly()
/** RAW_FRAME bodies seen, unwrapped to an ITS message, and not an ITS message (the usual case on air). */
@Volatile private var rawSeen = 0L
@Volatile private var rawForwarded = 0L
val state: StateFlow<Esp32LinkState> = combine(transport, usb.state, ble.state) { t, u, b ->
if (t == Esp32Transport.USB) u else b
}.stateIn(scope, SharingStarted.Eagerly, Esp32LinkState.DISCONNECTED)
@@ -185,12 +213,15 @@ class Esp32Link @Inject constructor(
_linkStatus.value = null
pending.values.forEach { it.cancel() }
pending.clear()
reassembly.reset()
} else if (transport.value == Esp32Transport.BLE) {
_protocol.value = Esp32Protocol.STATION_LINK // BLE exists only on the current firmware
scope.launch { ensureConfigured(null) }
}
}
}
// A change of receive path in Settings takes effect at once on a configured station.
scope.launch { rxPath.collect { scope.launch { applyRxPath() } } }
scope.launch { ble.detail.collect { if (transport.value == Esp32Transport.BLE) _detail.value = it } }
// Switching transport in Settings closes the other one; connecting stays a user action.
scope.launch {
@@ -287,9 +318,36 @@ class Esp32Link @Inject constructor(
}
configured = config
_detail.value = null
scope.launch { applyRxPath() } // a (re)configured station starts with raw capture off
true
}
/**
* Switches the station's raw capture to match [rxPath]: on (receive only, broadcast frames) for
* [Esp32RxPath.RAW_FRAME], off for [Esp32RxPath.V2X_RX]. RAW_CAPTURE needs a started radio, so it
* is sent only once the station is configured; a station that restarted forgets it and is
* configured again, which sends it again.
*/
private suspend fun applyRxPath() {
if (_protocol.value != Esp32Protocol.STATION_LINK || state.value != Esp32LinkState.CONNECTED) return
if (configured == null) return
val mode = if (rxPath.value == Esp32RxPath.RAW_FRAME) RAW_CAPTURE_ON_BROADCAST else 0
val result = request(LinkOpcode.RAW_CAPTURE, byteArrayOf(mode.toByte()), REPLY_TIMEOUT_MS)
Log.i(TAG, "receive path ${rxPath.value}: RAW_CAPTURE mode $mode -> ${result?.let { LinkResultCode.name(it.code) } ?: "no reply"}")
if (result != null && !result.accepted && mode != 0) _detail.value = "Raw capture refused: ${LinkResultCode.name(result.code)}"
}
/** One RAW_FRAME: unwrap it to the ITS message inside and hand it on like a V2X_RX message. */
private fun onRawFrame(body: ByteArray) {
val raw = RawFrame.parse(body) ?: return
if (raw.ownTransmission) return
rawSeen++
val unwrapped = GnUnwrap.unwrap(raw.frame) ?: return
val v2xRx = GnUnwrap.toV2xRxBody(unwrapped, raw.rssiDbm) ?: return
rawForwarded++
_incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, v2xRx))
}
private suspend fun provisionDemoCredentials(): Boolean {
_detail.value = "Provisioning the demo credentials"
val bundle = runCatching { context.assets.open(DEMO_BUNDLE_ASSET).use { it.readBytes() } }.getOrElse {
@@ -370,9 +428,13 @@ class Esp32Link @Inject constructor(
}
private fun onLinkMessage(octets: ByteArray) {
val message = LinkMessage.decode(octets) ?: return
// Fragments are put back together first (flags 1-3 of docs/station-link.pdf); a complete
// message, the usual case, passes straight through.
val message = reassembly.feed(LinkMessage.decode(octets) ?: return) ?: return
when (message.opcode) {
LinkOpcode.V2X_RX -> _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
LinkOpcode.V2X_RX ->
if (rxPath.value == Esp32RxPath.V2X_RX) _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
LinkOpcode.RAW_FRAME -> if (rxPath.value == Esp32RxPath.RAW_FRAME) onRawFrame(message.body)
LinkOpcode.CONFIRM -> {
val result = LinkResult.decode(message.body) ?: return
val waiting = pending.remove(message.sequence)
@@ -0,0 +1,220 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Kotlin counterpart of obu-firmware's `gn_unwrap.c`: takes one received 802.11 data frame down
* through LLC/SNAP, GeoNetworking and BTP-B to the ITS message inside, signed or not.
*
* It exists so the app can consume the station's `RAW_FRAME` debug capture the way it consumes
* `V2X_RX` (which the board builds with the C version). The two are tested against each other on the
* same frames (`GnUnwrapTest`, corpus from the C code), so they accept and reject the same frames and
* return the same fields.
*
* What it does and does not do, as in the C version:
* - Plain Data frames only, QoS or not, no WDS; LLC/SNAP with the GeoNetworking ethertype 0x8947.
* - Single-hop broadcast (TSB subtype 0) and GeoBroadcast; BTP-B on ports 2001-2004 and 2018.
* - A secured packet (TS 103 097 / IEEE 1609.2 `signedData` or `unsecuredData`, protocolVersion 3) is
* unwrapped WITHOUT verifying the signature or certificate; the result says it was signed.
* Encrypted and legacy v1.2.1 envelopes are rejected.
* - The payload is exactly as long as the Common Header declares, not what is left of the frame.
*/
object GnUnwrap {
/** An unwrapped ITS message. [payload] is its UPER encoding. */
class Result(
val btpPort: Int,
val payload: ByteArray,
val hasGeoArea: Boolean,
val areaLatTenMicroDeg: Int,
val areaLonTenMicroDeg: Int,
val areaDistanceAMeters: Int,
/** The packet carried a signature envelope; it was not checked. */
val signedUnverified: Boolean,
/** The frame ended before the payload its headers declare; [payload] is only what arrived. */
val truncated: Boolean,
)
private const val GN_ETHERTYPE = 0x8947
private const val LLC_SNAP_HEADER_LEN = 8
private const val IEEE80211_HEADER_LEN = 24
private const val IEEE80211_QOS_CTRL_LEN = 2
private const val FC_TYPE_DATA = 2
private const val FC_QOS_SUBTYPE_BIT = 0x08
private const val GN_BASIC_HEADER_LEN = 4
private const val GN_COMMON_HEADER_LEN = 8
private const val BTP_B_HEADER_LEN = 4
private const val GN_SHB_EXT_HEADER_LEN = 28
private const val GN_GBC_EXT_HEADER_LEN = 44
private const val GBC_AREA_LAT_OFFSET = 28
private const val GBC_AREA_LON_OFFSET = 32
private const val GBC_AREA_DIST_A_OFFSET = 36
private const val GN_HEADER_TYPE_GBC = 4
private const val GN_HEADER_TYPE_TSB = 5
private const val GN_HEADER_SUBTYPE_SINGLE_HOP = 0
private const val GN_NEXT_HEADER_COMMON = 1
private const val GN_NEXT_HEADER_SECURED = 2
private const val GN_COMMON_NEXT_HEADER_BTP_B = 2
private const val GN_COMMON_PAYLOAD_LEN_OFFSET = 4
private const val IEEE1609DOT2_VERSION = 3
private const val CONTENT_TAG_UNSECURED_DATA = 0x80
private const val CONTENT_TAG_SIGNED_DATA = 0x81
private const val SIGNED_PAYLOAD_HAS_DATA = 0x40
private val BTP_PORTS = setOf(2001, 2002, 2003, 2004, 2018)
private val LLC_SNAP_PREFIX = intArrayOf(0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00)
private fun ByteArray.u8(i: Int) = this[i].toInt() and 0xFF
private fun ByteArray.be16(i: Int) = (u8(i) shl 8) or u8(i + 1)
private fun ByteArray.be32(i: Int) = (u8(i) shl 24) or (u8(i + 1) shl 16) or (u8(i + 2) shl 8) or u8(i + 3)
/** COER length determinant: returns (octets used, length), or null when it does not fit. */
private fun coerLength(f: ByteArray, at: Int, avail: Int): Pair<Int, Int>? {
if (avail < 1) return null
val first = f.u8(at)
if (first < 0x80) return 1 to first
val n = first and 0x7F
if (n < 1 || n > 2 || avail < 1 + n) return null
var v = 0
for (i in 1..n) v = (v shl 8) or f.u8(at + i)
return (1 + n) to v
}
/**
* Returns the Common Header offset inside the envelope, the end of the envelope's inner packet
* and whether it was signed; null for anything this does not handle.
*/
private fun unwrapSecured(f: ByteArray, offset: Int, frameLen: Int): Triple<Int, Int, Boolean>? {
val avail = frameLen - offset
if (avail < 2 || f.u8(offset) != IEEE1609DOT2_VERSION) return null
val i: Int
val signed: Boolean
if (f.u8(offset + 1) == CONTENT_TAG_SIGNED_DATA) {
if (avail < 6 ||
f.u8(offset + 2) >= 0x80 ||
(f.u8(offset + 3) and SIGNED_PAYLOAD_HAS_DATA) == 0 ||
f.u8(offset + 4) != IEEE1609DOT2_VERSION ||
f.u8(offset + 5) != CONTENT_TAG_UNSECURED_DATA
) return null
i = 6
signed = true
} else if (f.u8(offset + 1) == CONTENT_TAG_UNSECURED_DATA) {
i = 2
signed = false
} else {
return null
}
val (used, len) = coerLength(f, offset + i, avail - i) ?: return null
val innerStart = offset + i + used
return Triple(innerStart, offset + i + used + len, signed)
}
/** Unwraps one 802.11 frame; null when it is not an ITS message this handles (the common case on air). */
fun unwrap(frame: ByteArray): Result? {
val frameLen = frame.size
if (frameLen < IEEE80211_HEADER_LEN) return null
val fc0 = frame.u8(0)
val fc1 = frame.u8(1)
val type = (fc0 shr 2) and 0x03
val subtype = (fc0 shr 4) and 0x0F
val toDs = (fc1 and 0x01) != 0
val fromDs = (fc1 and 0x02) != 0
if (type != FC_TYPE_DATA || (toDs && fromDs)) return null
var offset = IEEE80211_HEADER_LEN
if ((subtype and FC_QOS_SUBTYPE_BIT) != 0) offset += IEEE80211_QOS_CTRL_LEN
if (frameLen < offset + LLC_SNAP_HEADER_LEN) return null
for (k in LLC_SNAP_PREFIX.indices) if (frame.u8(offset + k) != LLC_SNAP_PREFIX[k]) return null
if (frame.be16(offset + 6) != GN_ETHERTYPE) return null
offset += LLC_SNAP_HEADER_LEN
if (frameLen < offset + GN_BASIC_HEADER_LEN) return null
val basicNextHeader = frame.u8(offset) and 0x0F
offset += GN_BASIC_HEADER_LEN
var limit = frameLen
var envelopeEnd = -1
var signed = false
if (basicNextHeader == GN_NEXT_HEADER_SECURED) {
val (inner, end, isSigned) = unwrapSecured(frame, offset, frameLen) ?: return null
offset = inner
envelopeEnd = end
signed = isSigned
if (envelopeEnd < limit) limit = envelopeEnd
} else if (basicNextHeader != GN_NEXT_HEADER_COMMON) {
return null
}
if (limit < offset + GN_COMMON_HEADER_LEN) return null
val nextHeader = (frame.u8(offset) shr 4) and 0x0F
val headerType = (frame.u8(offset + 1) shr 4) and 0x0F
val headerSubtype = frame.u8(offset + 1) and 0x0F
val gnPayloadLen = frame.be16(offset + GN_COMMON_PAYLOAD_LEN_OFFSET)
if (nextHeader != GN_COMMON_NEXT_HEADER_BTP_B) return null
offset += GN_COMMON_HEADER_LEN
val extLen: Int
var isGbc = false
if (headerType == GN_HEADER_TYPE_TSB && headerSubtype == GN_HEADER_SUBTYPE_SINGLE_HOP) {
extLen = GN_SHB_EXT_HEADER_LEN
} else if (headerType == GN_HEADER_TYPE_GBC) {
extLen = GN_GBC_EXT_HEADER_LEN
isGbc = true
} else {
return null
}
if (limit < offset + extLen) return null
var areaLat = 0
var areaLon = 0
var areaDist = 0
if (isGbc) {
areaLat = frame.be32(offset + GBC_AREA_LAT_OFFSET)
areaLon = frame.be32(offset + GBC_AREA_LON_OFFSET)
areaDist = frame.be16(offset + GBC_AREA_DIST_A_OFFSET)
}
offset += extLen
if (limit < offset + BTP_B_HEADER_LEN) return null
val destPort = frame.be16(offset)
if (destPort !in BTP_PORTS) return null
if (gnPayloadLen <= BTP_B_HEADER_LEN) return null
val payloadStart = offset + BTP_B_HEADER_LEN
val payloadEnd = offset + gnPayloadLen
if (envelopeEnd >= 0 && payloadEnd > envelopeEnd) return null
val truncated = payloadEnd > frameLen
val payloadLen = (if (truncated) frameLen else payloadEnd) - payloadStart
if (payloadLen <= 0) return null
return Result(
btpPort = destPort,
payload = frame.copyOfRange(payloadStart, payloadStart + payloadLen),
hasGeoArea = isGbc,
areaLatTenMicroDeg = areaLat,
areaLonTenMicroDeg = areaLon,
areaDistanceAMeters = areaDist,
signedUnverified = signed,
truncated = truncated,
)
}
/**
* The `V2X_RX` body for [result] (the layout [V2xRxFrame.parse] reads and the firmware's
* `encode_v2x_rx` writes): `u16 port, i8 rssi, u8 flags (bit 0 GBC area, bit 1 signed), i32 lat,
* i32 lon, u16 distance_a, payload`. Null for a truncated message, which must not be forwarded.
*/
fun toV2xRxBody(result: Result, rssiDbm: Int): ByteArray? {
if (result.truncated || result.payload.isEmpty()) return null
val out = java.io.ByteArrayOutputStream(V2xRxFrame.PREFIX_SIZE + result.payload.size)
fun u8(v: Int) = out.write(v and 0xFF)
fun u16(v: Int) { u8(v); u8(v shr 8) }
fun i32(v: Int) { u16(v); u16(v shr 16) }
u16(result.btpPort)
u8(rssiDbm.coerceIn(-128, 127))
u8((if (result.hasGeoArea) 0x01 else 0) or (if (result.signedUnverified) 0x02 else 0))
i32(result.areaLatTenMicroDeg)
i32(result.areaLonTenMicroDeg)
u16(result.areaDistanceAMeters)
out.write(result.payload)
return out.toByteArray()
}
}
@@ -0,0 +1,92 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Reassembles fragmented station-link messages (docs/station-link.pdf, "Fragmented messages").
*
* A body too large for one transport message is split in order, every fragment carrying the same
* opcode and sequence and `flags` 1 (first), 2 (middle) or 3 (last). Each fragment's body starts with
* `total_length u16` and `body_offset u16`, then the data. The complete body is handed on once the
* last fragment brings it to exactly `total_length`.
*
* Validation follows the spec: gaps, duplicates, wrong order and a changed total drop the stream;
* an unfinished stream is discarded after [IDLE_TIMEOUT_MS] of silence; at most [MAX_PENDING] streams
* are held; a complete body is at most [MAX_BODY] octets (the largest station-to-host indication).
*
* One instance per link session (USB and BLE keep separate streams in the spec; the app uses one
* transport at a time and starts a new instance when the session restarts).
*/
class LinkReassembly(private val nowMs: () -> Long = { System.currentTimeMillis() }) {
private class Stream(val opcode: Int, val sequence: Int, val total: Int, var lastMs: Long) {
val bytes = java.io.ByteArrayOutputStream()
}
private val streams = ArrayList<Stream>()
/** Fragments dropped for any validation reason since this instance was created. */
var dropped: Int = 0
private set
/**
* Feeds one received message. Returns it unchanged when it is complete (`flags` 0), the
* reassembled message (`flags` 0) when [message] was the last fragment, and null otherwise.
*/
fun feed(message: LinkMessage): LinkMessage? {
val now = nowMs()
streams.removeAll { now - it.lastMs > IDLE_TIMEOUT_MS }
if (message.flags == 0) {
// A complete message supersedes any unfinished stream with the same key.
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
return message
}
val flags = message.flags
val body = message.body
if (flags > FLAG_LAST || body.size <= FRAGMENT_HEADER) return drop(message)
fun u16(i: Int) = (body[i].toInt() and 0xFF) or ((body[i + 1].toInt() and 0xFF) shl 8)
val total = u16(0)
val offset = u16(2)
val length = body.size - FRAGMENT_HEADER
if (total == 0 || total > MAX_BODY || offset + length > total) return drop(message)
// the last fragment ends exactly at the declared total, and only the last one does
if ((flags == FLAG_LAST) != (offset + length == total)) return drop(message)
var stream = streams.firstOrNull { it.opcode == message.opcode && it.sequence == message.sequence }
if (flags == FLAG_FIRST) {
if (offset != 0) return drop(message)
stream?.let { streams.remove(it) } // a restarted stream replaces the old one
if (streams.size >= MAX_PENDING) return drop(message)
stream = Stream(message.opcode, message.sequence, total, now)
streams.add(stream)
} else if (stream == null) {
return drop(message) // a middle or last fragment without a first
}
if (stream.total != total || stream.bytes.size() != offset) {
streams.remove(stream) // changed total, a gap or a duplicate
return drop(message)
}
stream.bytes.write(body, FRAGMENT_HEADER, length)
stream.lastMs = now
if (flags != FLAG_LAST) return null
streams.remove(stream)
return LinkMessage(message.opcode, message.sequence, stream.bytes.toByteArray(), 0)
}
/** Forgets every unfinished stream (a new session, a reconnect). */
fun reset() = streams.clear()
private fun drop(message: LinkMessage): LinkMessage? {
dropped++
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
return null
}
companion object {
const val FLAG_FIRST = 1
const val FLAG_MIDDLE = 2
const val FLAG_LAST = 3
const val FRAGMENT_HEADER = 4
const val IDLE_TIMEOUT_MS = 2_000L
const val MAX_PENDING = 8
const val MAX_BODY = 65_535
}
}
@@ -0,0 +1,55 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Body of the station-link `RAW_FRAME` (0x85, docs/station-link.pdf, "Raw capture"): a debug copy of
* a radio frame the station received (or, with the own-transmission option, sent).
*
* u32 counter, u8 flags (bit 0 own transmission, bit 1 UTC time stamp), i8 rssi,
* ITS5 record: "ITS5", u32 seconds, u32 microseconds, u16 frame_length, frame[frame_length]
*
* The frame is the 802.11 MPDU without its FCS. [GnUnwrap] turns it into the ITS message.
*/
data class RawFrame(
val counter: Long,
val ownTransmission: Boolean,
/** The record time is UTC (the station's clock was synchronised) rather than time since boot. */
val utcTime: Boolean,
val rssiDbm: Int,
val seconds: Long,
val microseconds: Long,
val frame: ByteArray,
) {
override fun equals(other: Any?): Boolean = other is RawFrame && counter == other.counter &&
ownTransmission == other.ownTransmission && utcTime == other.utcTime && rssiDbm == other.rssiDbm &&
seconds == other.seconds && microseconds == other.microseconds && frame.contentEquals(other.frame)
override fun hashCode(): Int = 31 * counter.hashCode() + frame.contentHashCode()
companion object {
/** `[counter 4][flags 1][rssi 1]` before the record, `["ITS5" 4][sec 4][usec 4][len 2]` in it. */
const val HEADER_SIZE = 6 + 14
private val MAGIC = byteArrayOf('I'.code.toByte(), 'T'.code.toByte(), 'S'.code.toByte(), '5'.code.toByte())
/** Returns null for a body that is not a well-formed RAW_FRAME (short, wrong magic, bad length). */
fun parse(body: ByteArray): RawFrame? {
if (body.size < HEADER_SIZE) return null
for (i in 0 until 4) if (body[6 + i] != MAGIC[i]) return null
fun u8(i: Int) = body[i].toInt() and 0xFF
fun u16(i: Int) = u8(i) or (u8(i + 1) shl 8)
fun u32(i: Int) = (u16(i).toLong()) or (u16(i + 2).toLong() shl 16)
val length = u16(18)
if (body.size != HEADER_SIZE + length) return null
val flags = u8(4)
return RawFrame(
counter = u32(0),
ownTransmission = (flags and 0x01) != 0,
utcTime = (flags and 0x02) != 0,
rssiDbm = body[5].toInt(),
seconds = u32(10),
microseconds = u32(14),
frame = body.copyOfRange(HEADER_SIZE, body.size),
)
}
}
}
@@ -32,8 +32,12 @@ object LinkOpcode {
const val CREDENTIALS_PROVISION = 0x04
const val CREDENTIALS_ERASE = 0x05
const val STATUS_REQUEST = 0x0C
/** Debug path: body is one mode octet (bit 0 on, bit 1 broadcast only, bit 2 own transmissions); 0 switches it off. */
const val RAW_CAPTURE = 0x0D
const val CONFIRM = 0x80
const val BTP_DATA_INDICATION = 0x81
/** Raw 802.11 frame copy of the RAW_CAPTURE debug path, fragmented when large: see [RawFrame]. */
const val RAW_FRAME = 0x85
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
const val V2X_RX = 0x90
}
@@ -144,8 +144,11 @@ object CamUperCodec {
bw.putBits(0, 1) // extension bit: value is in the root list
bw.putBits(2, 2) // curvatureCalculationMode: unavailable(2)
// YawRateValue is positive to the LEFT (degSec-000-01ToLeft(1), TS 102 894-2), the opposite
// of Cam.yawRateDps (positive clockwise, i.e. to the right). Until 2026-11-18 neither side
// negated, so every CAM this phone sent turned the wrong way for a standard receiver.
val yawRateCentiDegS = cam.yawRateDps
?.let { (it * 100.0).roundToInt().coerceIn(-32766, 32766) }
?.let { (-it * 100.0).roundToInt().coerceIn(-32766, 32766) }
?: YAW_RATE_UNAVAILABLE
bw.putBits(yawRateCentiDegS - (-32766), 16)
// YawRateConfidence has NINE enumerands (degSec-000-01(0) .. unavailable(8), see
@@ -306,7 +309,8 @@ object CamUperCodec {
val yawRateRaw = br.getBitsInt(16) + (-32766)
br.getBits(4) // yawRateConfidence: 9 enumerands -> 4 bits, see the note in encode()
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else yawRateRaw / 100.0
// Left-positive on air, clockwise-positive in Cam: negate, as encode() does.
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else -yawRateRaw / 100.0
// Everything after yawRate is deliberately left unread: the 7 optional high-frequency
// fields, then lowFrequencyContainer (vehicleRole / exteriorLights / pathHistory), then
@@ -28,6 +28,10 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
* A `SEQUENCE (SIZE(lo..hi)) OF` writes its count in `ceil(log2(hi-lo+1))` bits holding `n-lo`:
* intersections 1..32 gives 5 bits, movements 1..255 gives 8, events 1..16 gives 4.
*
* Names and advisory speeds are walked, not kept: a road RSU (Hamburg, 2026-11-23: 888-byte SPATEMs naming
* "Berliner Tor / Kolbergstrasse" and each movement, with a greenwave and an ecoDrive advice per event) sends
* both, and until then every one of its SPATEMs was refused.
*
* Two traps worth naming, both of which silently shift every later field:
* - `TimeChangeDetails` is **not** extensible, so it has 5 optional bits and no extension bit,
* unlike almost every other SEQUENCE here, which all carry one.
@@ -41,7 +45,7 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
* exactly, with no message hitting an unsupported branch.
*
* Returns null rather than guessing whenever an extension bit is set or an unsupported optional
* appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
* (regional extensions) appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
* the wrong light.
*/
object SpatemUperCodec {
@@ -73,9 +77,7 @@ object SpatemUperCodec {
val hasName = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
val minuteOfYear = if (hasTimeStamp) br.getBitsInt(20) else null
// DescriptiveName is a variable-length IA5String. Nothing in 79k real messages uses it,
// and guessing its length would desynchronise everything after it.
if (hasName) return null
if (hasName) skipName(br)
val intersectionCount = br.getBitsInt(5) + 1
if (intersectionCount > MAX_INTERSECTIONS) return null
@@ -102,7 +104,7 @@ object SpatemUperCodec {
val hasEnabledLanes = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (hasName) return null
if (hasName) skipName(br)
// IntersectionReferenceID - not extensible, one optional bit for region.
val region = if (br.getBitsInt(1) == 1) br.getBitsInt(16) else null
@@ -133,7 +135,7 @@ object SpatemUperCodec {
val hasName = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (hasName) return null
if (hasName) skipName(br)
val signalGroup = br.getBitsInt(8)
val eventCount = br.getBitsInt(4) + 1
@@ -162,7 +164,8 @@ object SpatemUperCodec {
if (hasConfidence) br.getBits(4)
if (hasNext) br.getBits(16)
}
if (hasSpeeds || hasRegionalEvent) return null
if (hasSpeeds && !skipAdvisorySpeedList(br)) return null
if (hasRegionalEvent) return null
events.add(SignalPhaseEvent(phase, minEnd, maxEnd, likely))
}
@@ -171,6 +174,41 @@ object SpatemUperCodec {
return SignalMovement(signalGroup, events)
}
/**
* `DescriptiveName` IA5String (SIZE(1..63)): 6-bit length holding n-1, then 7 bits per character.
* Not surfaced (a real RSU names its intersections and movements, the app does not show them here), but
* it has to be walked: it sits in front of fields that are.
*/
private fun skipName(br: BitReader) {
val length = br.getBitsInt(6) + 1
repeat(length) { br.getBits(7) }
}
/**
* Walks an `AdvisorySpeedList` (SIZE(1..16) OF AdvisorySpeed: the RSU's green wave and eco-drive advice)
* without keeping it; nothing consumes it yet. AdvisorySpeed is extensible with five optional fields
* (speed, confidence, distance, class, regional); `type` is an extensible ENUMERATED of four values.
* Returns false for an extension value or a regional extension, which this decoder cannot size.
*/
private fun skipAdvisorySpeedList(br: BitReader): Boolean {
repeat(br.getBitsInt(4) + 1) {
if (br.getBitsInt(1) != 0) return false // AdvisorySpeed extension
val hasSpeed = br.getBitsInt(1) == 1
val hasConfidence = br.getBitsInt(1) == 1
val hasDistance = br.getBitsInt(1) == 1
val hasClass = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (br.getBitsInt(1) != 0) return false // AdvisorySpeedType extension value
br.getBits(2) // type: none, greenwave, ecoDrive, transit
if (hasSpeed) br.getBits(9) // SpeedAdvice (0..500)
if (hasConfidence) br.getBits(3) // SpeedConfidenceDSRC, 8 values, not extensible
if (hasDistance) br.getBits(14) // ZoneLength (0..10000)
if (hasClass) br.getBits(8) // RestrictionClassID (0..255)
if (hasRegional) return false
}
return true
}
/**
* Walks a `ManeuverAssistList` without keeping it. Nothing consumes queue lengths yet, but the
* list is variable-length, so it has to be parsed to find where the next field starts.
@@ -14,6 +14,20 @@ object StationType {
* is 15 and not 12 - mapping by list position mislabels every RSU.
*/
const val ROAD_SIDE_UNIT = 15
/**
* The Use Case API's `stationType` string enum ("passengerCar") mapped to its ITS-G5 integer,
* per StationType in the ETSI CDD (CiT MQTT API v6, sections 2.1.1 and 2.2.3). Mapped by name,
* never by list position, because of the gap before [ROAD_SIDE_UNIT].
*/
private val BY_API_NAME = mapOf(
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
)
/** The ITS-G5 integer for an API station type name, or null for a blank or unknown name. */
fun fromApiName(name: String?): Int? = name?.takeIf { it.isNotBlank() }?.let { BY_API_NAME[it] }
}
/**
@@ -45,8 +59,13 @@ data class Cam(
val headingDeg: Double,
/**
* Yaw rate, degrees per second, where available (positive = turning clockwise).
* Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and `v2x-uca/output/json/cam` (remote).
* Yaw rate, degrees per second, where available (positive = turning clockwise, to the right,
* like [headingDeg] increasing). Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and
* `v2x-uca/output/json/cam` (remote).
*
* The CAM's YawRateValue and the CiT One's CAM topic count the other way, positive to the
* left, so `CamUperCodec` and `CamParser` flip the sign. The CiT One's `obu_gnss` topic is
* already positive to the right in practice, despite its document, so `ObuGnssParser` does not.
* A much more direct "is this road user turning" signal than heading-delta heuristics —
* see [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
*/
@@ -27,17 +27,24 @@ object CamParser {
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
val stationId = JsonFieldReader.firstLong(obj, "stationId", "stationID", "station_id") ?: return null
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: return null
// The API sends the name ("passengerCar", CiT MQTT API v6 section 2.2.3); a number is still
// accepted. Until 2026-11-18 only a number was, so every real payload was dropped here.
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: StationType.fromApiName(obj.optString("stationType"))
?: return null
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
// Positive to the left on this topic (CiT MQTT API v6, v2x-uca/output/json/cam), as in the CAM
// itself; negated into Cam.yawRateDps, which is positive clockwise.
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
?.let { -it }
val driveDirection = JsonFieldReader.firstInt(obj, "driveDirection", "drive_direction")
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength", "vehicle_length")
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth", "vehicle_width")
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength_m", "vehicleLength", "vehicle_length")
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth_m", "vehicleWidth", "vehicle_width")
val accel = JsonFieldReader.firstDouble(obj, "accelerationControl", "longitudinalAcceleration", "acceleration_mps2")
// Own/remote: prefer an explicit flag if the API provides one; otherwise compare
@@ -24,16 +24,34 @@ object ObuGnssParser {
*/
fun parseEgo(json: String, fallbackStationId: Long = 0L, timestamp: Long = System.currentTimeMillis()): Cam? {
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
// Identity and yaw rate are in `own_info`, kinematics in `gnss` (CiT MQTT API v6 Listing 2.1,
// and every logged payload). Until 2026-11-18 everything was read from `own_info`, which
// has no position, so every real message was dropped and the ego state never came from
// here. A flat payload with everything on the root is still accepted.
val obj = root.optJSONObject("own_info") ?: root
val gnss = root.optJSONObject("gnss") ?: obj
val stationId = JsonFieldReader.firstLong(obj, "stationID", "stationId", "station_id") ?: fallbackStationId
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: StationType.CYCLIST
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: StationType.fromApiName(obj.optString("stationType"))
?: StationType.CYCLIST
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
val (lat, lon) = JsonFieldReader.firstLatLon(gnss) ?: JsonFieldReader.firstLatLon(obj) ?: return null
// 91 / 181 is the API's "no 2D fix" marker, not a place.
if (lat > 90.0 || lon > 180.0) return null
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
// 163.82 m/s is the API's "invalid speed" marker; treated like a missing speed.
val speed = JsonFieldReader.firstDouble(gnss, "speed_mps", "speed", "speedMps")
?.takeIf { it < INVALID_SPEED_MPS } ?: 0.0
val heading = JsonFieldReader.firstDouble(gnss, "heading_deg", "heading", "headingDeg") ?: 0.0
val acceleration = JsonFieldReader.firstDouble(gnss, "acceleration_mpss")
// `yawRate_degps` is this topic's name (CiT MQTT API v6, Listing 2.1, own_info, and every
// logged payload). The document says positive to the left, but the CiT One sends it positive
// to the RIGHT: in the 2026-03-18 bacospat log, all 27 one-second windows of turning at over
// 4 m/s had it with the same sign as the clockwise heading change. That is already
// Cam.yawRateDps's convention, so it is taken as it is - unlike the CAM topic (CamParser),
// which the logs show is left-positive, as documented.
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_degps", "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
return Cam(
stationId = stationId,
@@ -43,11 +61,17 @@ object ObuGnssParser {
speedMps = speed,
headingDeg = JsonFieldReader.normaliseHeadingDeg(heading),
yawRateDps = yawRate,
vehicleLengthM = JsonFieldReader.firstDouble(obj, "vehicleLength_m"),
vehicleWidthM = JsonFieldReader.firstDouble(obj, "vehicleWidth_m"),
accelerationMps2 = acceleration,
timestamp = timestamp,
isOwn = true,
)
}
/** The API's "invalid speed calculation" value (CiT MQTT API v6 section 2.1.1). */
private const val INVALID_SPEED_MPS = 163.82
/** Just the stationID/stationType, for when only identity (not a full fix) is needed. */
fun parseOwnIdentity(json: String): Pair<Long, Int>? {
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
@@ -12,18 +12,19 @@ import kotlin.math.abs
*
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
*
* Position/speed/heading come straight from GNSS. Yaw rate is derived from the gyroscope's
* z-axis reading (rotation about the vertical axis while the phone is roughly flat/mounted
* upright) rather than from GNSS heading deltas, which are noisy at low speed — same rationale
* already used for remote-vehicle turn detection in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
* Position/speed/heading come straight from GNSS. Yaw rate comes from the gyroscope projected
* onto gravity ([com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]), so it is the rotation
* about the true vertical however the phone is mounted, rather than from GNSS heading deltas,
* which are noisy at low speed — same rationale already used for remote-vehicle turn detection
* in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
*/
object PhoneCamBuilder {
/**
* @param gnss latest phone GNSS fix.
* @param gyroZRadPerSec latest gyroscope z-axis reading, rad/s (device frame). Positive per
* Android's convention is counter-clockwise around +Z; converted to the clockwise-positive
* yaw rate convention already used by [Cam.yawRateDps] to match OBU/remote CAM data.
* @param gnss latest phone GNSS fix, its timestamp already on the time base to transmit.
* @param yawRateDps yaw rate about the vertical, deg/s, in the convention of [Cam.yawRateDps]
* (positive = clockwise), from [com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator].
* Null encodes as the ASN.1 `unavailable` sentinel.
* @param stationId the station ID to transmit under: the current pseudonym from
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager], or the bench pinger's fixed ID.
* Receivers track a station across successive CAMs by this ID, which is why it only ever
@@ -37,12 +38,10 @@ object PhoneCamBuilder {
*/
fun build(
gnss: GnssReading,
gyroZRadPerSec: Float?,
yawRateDps: Double?,
stationId: Long,
longitudinalAccelMps2: Double? = null,
): Cam {
val yawRateDps = gyroZRadPerSec?.let { -it * RAD_TO_DEG } // negate: CCW+ -> CW+ convention
return Cam(
stationId = stationId,
stationType = StationType.CYCLIST,
@@ -63,8 +62,6 @@ object PhoneCamBuilder {
return h
}
private const val RAD_TO_DEG = 180.0 / Math.PI
/**
* Gyro noise floor below which yaw rate is clamped to zero. Placeholder — initial
* engineering estimate pending real-world tuning, same disclaimer as
@@ -1,6 +1,7 @@
package com.hawhamburg.micr0bu.domain.denm
import com.hawhamburg.micr0bu.domain.cam.JsonFieldReader
import com.hawhamburg.micr0bu.domain.cam.StationType
import org.json.JSONObject
/**
@@ -123,17 +124,6 @@ object DenmParser {
*/
fun causeCodeName(causeCode: Int?): String? = causeCode?.let { NAME_BY_CAUSE_CODE[it] }
/**
* The Use Case API's `stationType` string enum mapped to its ITS-G5 integer, per StationType in
* the ETSI CDD. Note roadSideUnit is **15**, not 12 - the enumeration has a gap after tram(11),
* so mapping by list position would silently mislabel every RSU.
*/
private val STATION_TYPE_BY_NAME = mapOf(
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
)
/**
* Parses the API's RFC3339 timestamps ("2021-05-11T12:01:02+00:00") to epoch millis. The air
* path carries a binary TimestampIts instead, so the two transports arrive here in completely
@@ -187,7 +177,7 @@ object DenmParser {
val isTermination = obj.has("termination") && obj.optBoolean("termination", true)
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: STATION_TYPE_BY_NAME[obj.optString("stationType").takeIf { it.isNotBlank() }]
?: StationType.fromApiName(obj.optString("stationType"))
return DenmEvent(
stationId = stationId,
@@ -0,0 +1,25 @@
package com.hawhamburg.micr0bu.domain.fusion
/**
* Where the phone rides, as set in Settings > Ride.
*
* The sensor fusion filter treats the motion sensors differently per mount: on the handlebar the
* phone is fixed to the bike (but turns with the steering), in a bag on the bike it is mostly fixed
* but can shift, and in a pocket or backpack it moves with the rider's body, so shoulder checks look
* like turns. Every V2X log records the setting (`meta.phone_mount`), so a recorded ride says which
* mount it was.
*
* [id] is what is stored and logged; it must not change once logs exist.
*/
enum class PhoneMount(val id: String) {
HANDLEBAR("handlebar"),
BAG("bag"),
POCKET("pocket");
companion object {
val DEFAULT = HANDLEBAR
/** The mount stored under [id], or [DEFAULT] for a missing or unknown value. */
fun fromId(id: String?): PhoneMount = entries.firstOrNull { it.id == id } ?: DEFAULT
}
}
@@ -0,0 +1,123 @@
package com.hawhamburg.micr0bu.domain.fusion
import kotlin.math.sqrt
/**
* Yaw rate about the true vertical, whatever way up the phone is held.
*
* ## Why
* Yaw rate used to be the gyroscope's z axis alone. That is rotation about the screen's normal, so
* it is the yaw rate only with the phone lying flat, screen up. On a handlebar mount tilted towards
* the rider it is scaled down by the tilt and mixed with pitch and roll; with the phone upright,
* or loose in a bag, it is unrelated to the bike's turning at all.
*
* ## How
* Gravity (from `TYPE_GRAVITY`, in the device frame) gives the up direction. The rate about it is
* the gyroscope vector projected onto that unit vector: `ω · up`. That is the same number for any
* orientation of the phone, as long as the phone is held still relative to the bike.
*
* Samples are averaged over [windowNanos] ending at the newest gyroscope sample, rather than taking
* one raw sample: a single gyroscope sample on a bike is mostly vibration.
*
* A bike leans into a turn, and over a sustained turn `TYPE_GRAVITY` drifts toward the bike's own
* vertical. The result is then the turn rate scaled by the cosine of the lean, about 6 % low at
* 20° of lean. Small next to what the z-axis reading got wrong.
*
* All times are on the monotonic `SystemClock.elapsedRealtimeNanos` base (`SensorEvent.timestamp`),
* never the wall clock. Pure Kotlin, so it is tested apart from Android. Thread-safe: samples and
* reads may come from different threads.
*/
class YawRateEstimator(
private val windowNanos: Long = DEFAULT_WINDOW_NANOS,
private val staleNanos: Long = DEFAULT_STALE_NANOS,
) {
private val lock = Any()
private var upX = 0.0
private var upY = 0.0
private var upZ = 0.0
/** When the up direction was last measured; null until the first gravity sample. */
private var upAtNanos: Long? = null
private val times = LongArray(CAPACITY)
/** Rotation about up, rad/s, counter-clockwise seen from above (Android's sign convention). */
private val rates = DoubleArray(CAPACITY)
private var next = 0
private var count = 0
/** A gravity sample, m/s², device frame, pointing up. Ignored if too weak to give a direction. */
fun onGravity(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
val norm = sqrt(x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
if (norm < MIN_GRAVITY_MPS2) return // free fall or a broken sample: no direction to trust
synchronized(lock) {
upX = x / norm
upY = y / norm
upZ = z / norm
upAtNanos = elapsedRealtimeNanos
}
}
/**
* A gyroscope sample, rad/s, device frame. Dropped while the up direction is unknown or stale,
* since projecting onto an old up vector would report the phone's rotation since then as yaw.
*/
fun onGyro(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
synchronized(lock) {
val upAt = upAtNanos ?: return
if (elapsedRealtimeNanos - upAt > staleNanos) return
times[next] = elapsedRealtimeNanos
rates[next] = x * upX + y * upY + z * upZ
next = (next + 1) % CAPACITY
if (count < CAPACITY) count++
}
}
/**
* Mean yaw rate over the last [windowNanos] of samples, deg/s, positive = turning clockwise
* seen from above: the convention of [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps].
* Null when there is no sample newer than [staleNanos] before [nowElapsedRealtimeNanos].
*/
fun yawRateDps(nowElapsedRealtimeNanos: Long): Double? {
synchronized(lock) {
if (count == 0) return null
val newestIndex = (next - 1 + CAPACITY) % CAPACITY
val newest = times[newestIndex]
if (nowElapsedRealtimeNanos - newest > staleNanos) return null
var sum = 0.0
var n = 0
for (k in 0 until count) {
val i = (newestIndex - k + CAPACITY) % CAPACITY
if (newest - times[i] > windowNanos) break
sum += rates[i]
n++
}
// Negate: counter-clockwise positive (Android) -> clockwise positive (Cam.yawRateDps).
return -(sum / n) * RAD_TO_DEG
}
}
fun reset() {
synchronized(lock) {
upAtNanos = null
next = 0
count = 0
}
}
companion object {
/** 100 ms: five samples at `SENSOR_DELAY_GAME` (about 50 Hz). */
const val DEFAULT_WINDOW_NANOS = 100_000_000L
/** Older than this, a gyroscope or gravity sample no longer describes the present. */
const val DEFAULT_STALE_NANOS = 500_000_000L
/** Room for the window at up to a few hundred Hz. */
private const val CAPACITY = 128
/** Well below 9.81: gravity this weak means free fall or a bad sample, not a direction. */
private const val MIN_GRAVITY_MPS2 = 3.0
private const val RAD_TO_DEG = 180.0 / Math.PI
}
}
@@ -0,0 +1,38 @@
package com.hawhamburg.micr0bu.domain.map
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
/**
* Intersection geometry the app ships with (`assets/mapem/hamburg.txt`, built by
* `tools/mapem_bundle.py` from recorded MAPEMs), so a SPATEM can be placed on its lanes without
* waiting for, or ever receiving, the intersection's MAPEM.
*
* Which stored intersection a SPATEM belongs to is decided in
* [com.hawhamburg.micr0bu.domain.spat.TrafficLights.geometryFor].
*/
object StoredMaps {
const val ASSET_PATH = "mapem/hamburg.txt"
/**
* One UPER MAPEM per line as hex; blank lines and `#` comments are skipped, as is a line that
* does not decode, so one bad entry does not cost the rest.
*/
fun parse(text: String): List<IntersectionGeometry> =
text.lineSequence()
.map { it.trim() }
.filter { it.isNotEmpty() && !it.startsWith("#") }
.mapNotNull { hexToBytes(it) }
.flatMap { MapemUperCodec.decode(it, 0L)?.intersections.orEmpty() }
.toList()
private fun hexToBytes(hex: String): ByteArray? {
if (hex.length % 2 != 0) return null
return ByteArray(hex.length / 2) { i ->
val high = Character.digit(hex[2 * i], 16)
val low = Character.digit(hex[2 * i + 1], 16)
if (high < 0 || low < 0) return null
(high * 16 + low).toByte()
}
}
}
@@ -153,6 +153,44 @@ object TrafficLights {
fun pickGeometry(candidates: List<IntersectionGeometry>, spatRevision: Int?): IntersectionGeometry? =
candidates.lastOrNull { it.revision == spatRevision } ?: candidates.lastOrNull()
/** A stored MAPEM is only used for a rider this close to its reference point. */
const val STORED_MAP_RADIUS_M = 2_000.0
/**
* The geometry for the intersection a SPATEM names, out of what was heard on air ([live],
* oldest first) and what the app ships with ([stored]).
*
* Both are matched on region and intersection id ([IntersectionGeometry.key]), never on the
* sending station: one intersection is heard under several station ids. In order:
*
* 1. a live MAPEM of the SPATEM's revision;
* 2. a stored one of that revision, within [STORED_MAP_RADIUS_M] of [own] when the position
* is known;
* 3. the newest live one of another revision (flagged by [TrafficLight.revisionMismatch]).
*
* A stored MAPEM of another revision is never used: it may be months old, and its signal groups
* could put the wrong light on a lane.
*/
fun geometryFor(
key: String,
spatRevision: Int,
live: List<IntersectionGeometry>,
stored: List<IntersectionGeometry>,
own: MapPoint? = null,
): IntersectionGeometry? {
val heard = pickGeometry(live.filter { it.key == key }, spatRevision)
if (heard?.revision == spatRevision) return heard
val shipped = stored.lastOrNull {
it.key == key && it.revision == spatRevision && (own == null || isNear(it, own))
}
return shipped ?: heard
}
private fun isNear(geometry: IntersectionGeometry, own: MapPoint): Boolean {
val (east, north) = geometry.toLocal(own)
return hypot(east, north) <= STORED_MAP_RADIUS_M
}
internal fun Maneuvers.single(): Turn? {
val turns = listOfNotNull(
Turn.STRAIGHT.takeIf { straight }, Turn.LEFT.takeIf { left },
@@ -1,6 +1,7 @@
package com.hawhamburg.micr0bu.service
import android.content.Context
import android.hardware.SensorManager
import android.os.SystemClock
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.GnssTimeSource
@@ -13,6 +14,7 @@ import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -62,7 +64,7 @@ class CamPinger @Inject constructor(
private var job: Job? = null
@Volatile private var latestGnss: GnssReading? = null
@Volatile private var latestGyroZ: Float? = null
private val yawRate = YawRateEstimator()
@Volatile private var previousGnss: GnssReading? = null
private val _isActive = MutableStateFlow(false)
@@ -102,16 +104,24 @@ class CamPinger @Inject constructor(
private suspend fun runPingLoop() = coroutineScope {
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
yawRate.reset()
launch {
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch {
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
while (true) {
val gnss = latestGnss
_hasFix.value = gnss != null
if (gnss != null) {
val cam = PhoneCamBuilder.build(
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource.
gnss = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)),
gyroZRadPerSec = latestGyroZ,
// Stamped with the GNSS time of the fix itself; see GnssTimeSource.atElapsedRealtime.
gnss = gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos)),
yawRateDps = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos()),
stationId = OwnStationIds.BENCH_PING,
longitudinalAccelMps2 = longitudinalAccel(gnss),
)
@@ -140,7 +150,7 @@ class CamPinger @Inject constructor(
previousGnss = gnss
if (prev == null) return null
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec
@@ -1,6 +1,8 @@
package com.hawhamburg.micr0bu.service
import android.content.Context
import android.hardware.SensorManager
import android.os.SystemClock
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.GnssTimeSource
import com.hawhamburg.micr0bu.data.SensorRepository
@@ -16,6 +18,7 @@ import com.hawhamburg.micr0bu.domain.asn1.VamContent
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
import com.hawhamburg.micr0bu.domain.cam.CamTransmitConfig
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -73,7 +76,9 @@ class CamTransmitLoop @Inject constructor(
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@Volatile private var latestGnss: GnssReading? = null
@Volatile private var latestGyroZ: Float? = null
private val yawRate = YawRateEstimator()
/** [SystemClock.elapsedRealtime] until which the elevated rate holds; monotonic, see [nowMs]. */
@Volatile private var elevatedUntilMs: Long = 0L
/** Previous GNSS fix, kept only to derive along-track acceleration — see [longitudinalAccel]. */
@@ -89,7 +94,7 @@ class CamTransmitLoop @Inject constructor(
* denser updates through the maneuver, not just at the instant it was detected.
*/
fun onDetectedEvent() {
elevatedUntilMs = System.currentTimeMillis() + ELEVATED_HOLD_MS
elevatedUntilMs = nowMs() + ELEVATED_HOLD_MS
}
/**
@@ -118,7 +123,15 @@ class CamTransmitLoop @Inject constructor(
private suspend fun runTransmitLoop() = coroutineScope {
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
yawRate.reset()
launch {
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch {
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
launch {
obuHardwarePrefs.outgoingMessageFlow.collect {
@@ -143,25 +156,23 @@ class CamTransmitLoop @Inject constructor(
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
// rotation fall cleanly between two frames instead of inside one.
val pseudonym = pseudonymManager.current()
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the
// outgoing CAM is: acceleration below still differences wall-clock samples.
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
val fix = onAirFix(gnss)
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
val bytes = codec.encodeCam(cam)
esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes,
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
}
private suspend fun sendVamIfDue(gnss: GnssReading) {
val now = System.currentTimeMillis()
val now = nowMs()
val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude,
gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble())
if (!vamRules.due(now, kinematics)) return
val pseudonym = pseudonymManager.current()
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
val fix = onAirFix(gnss)
// The CAM view of this fix is built only for its position vector, so the GN header of a VAM
// follows exactly the rules a CAM's does. It is not transmitted.
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
val withLowFrequency = vamRules.includeLowFrequency(now)
val bytes = VamUperCodec.encode(VamContent(
stationId = pseudonym.stationId,
@@ -198,15 +209,31 @@ class CamTransmitLoop @Inject constructor(
previousGnss = gnss
if (prev == null) return null
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble()
return dv / dtSec
}
/**
* [gnss] stamped with the GNSS time of the fix itself, for what goes on air: the fix's
* monotonic stamp moved onto GNSS time ([GnssTimeSource.atElapsedRealtime]). Neither the
* phone's clock setting nor a step of it between the fix and now can reach the result.
*/
private fun onAirFix(gnss: GnssReading): GnssReading =
gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos))
private fun currentYawRateDps(): Double? = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos())
/**
* The clock for this loop's own intervals (elevated-rate hold, VAM generation rules). Monotonic,
* so a phone clock that is set back cannot hold transmission off until it catches up again.
*/
private fun nowMs(): Long = SystemClock.elapsedRealtime()
private fun currentRateHz(gnss: GnssReading?): Double {
val now = System.currentTimeMillis()
val now = nowMs()
val inGeofence = gnss != null && config.geofences.any { fence ->
GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM
}
@@ -46,7 +46,7 @@ sealed class Screen(val route: String, val labelRes: Int) {
data object SettingsLanguage : Screen("settings/language", R.string.settings_language)
data object SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance)
data object SettingsSensors : Screen("settings/sensors", R.string.settings_sensors)
data object SettingsUnits : Screen("settings/units", R.string.settings_units)
data object SettingsRide : Screen("settings/ride", R.string.settings_ride)
data object SettingsConnection : Screen("settings/connection", R.string.settings_connection)
data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts)
@@ -4,6 +4,7 @@ import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -47,9 +48,11 @@ import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttPrefs
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionConfig
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -68,7 +71,7 @@ fun SettingsScreen(
onOpenLanguage: () -> Unit,
onOpenAppearance: () -> Unit,
onOpenSensors: () -> Unit,
onOpenUnits: () -> Unit,
onOpenRide: () -> Unit,
onOpenConnection: () -> Unit,
onOpenMqtt: () -> Unit,
onOpenUseCaseAlerts: () -> Unit,
@@ -99,7 +102,7 @@ fun SettingsScreen(
RowDivider()
MenuRow(stringResource(R.string.settings_sensors), onOpenSensors)
RowDivider()
MenuRow(stringResource(R.string.settings_units), onOpenUnits)
MenuRow(stringResource(R.string.settings_ride), onOpenRide)
RowDivider()
MenuRow(stringResource(R.string.settings_connection), onOpenConnection)
RowDivider()
@@ -171,6 +174,8 @@ fun ConnectionSettingsScreen(
onEsp32TransportChange: (Esp32Transport) -> Unit = {},
outgoingMessage: OutgoingMessage = OutgoingMessage.CAM,
onOutgoingMessageChange: (OutgoingMessage) -> Unit = {},
esp32RxPath: Esp32RxPath = Esp32RxPath.V2X_RX,
onEsp32RxPathChange: (Esp32RxPath) -> Unit = {},
signOutgoing: Boolean = true,
onSignOutgoingChange: (Boolean) -> Unit = {},
onBack: () -> Unit,
@@ -248,6 +253,21 @@ fun ConnectionSettingsScreen(
onSecond = { onOutgoingMessageChange(OutgoingMessage.VAM) },
)
Divider()
TwoWayChoice(
label = stringResource(R.string.settings_esp32_rx_path),
first = stringResource(R.string.settings_esp32_rx_v2x),
second = stringResource(R.string.settings_esp32_rx_raw),
firstSelected = esp32RxPath == Esp32RxPath.V2X_RX,
onFirst = { onEsp32RxPathChange(Esp32RxPath.V2X_RX) },
onSecond = { onEsp32RxPathChange(Esp32RxPath.RAW_FRAME) },
)
Text(
stringResource(if (esp32RxPath == Esp32RxPath.V2X_RX) R.string.settings_esp32_rx_v2x_note else R.string.settings_esp32_rx_raw_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
Divider()
SettingToggleRow(
label = stringResource(R.string.settings_esp32_sign),
checked = signOutgoing,
@@ -367,19 +387,51 @@ fun SensorsSettingsScreen(
}
}
/**
* Settings > Ride. Replaced the old Units screen: the app is metric throughout, so that switch had
* nothing to switch. Where the phone rides, and whether the V2X data logger also records the motion
* sensors and raw GPS for sensor fusion (`docs/07-sensor-fusion-logging.md`).
*/
@Composable
fun UnitsSettingsScreen(
useMetric: Boolean,
onUseMetric: (Boolean) -> Unit,
fun RideSettingsScreen(
phoneMount: PhoneMount,
onPhoneMount: (PhoneMount) -> Unit,
fusionLogging: Boolean,
onFusionLogging: (Boolean) -> Unit,
onBack: () -> Unit,
) {
SubScreen(stringResource(R.string.settings_units), onBack) {
SubScreen(stringResource(R.string.settings_ride), onBack) {
Text(
stringResource(R.string.settings_ride_mount_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard {
SettingToggleRow(stringResource(R.string.settings_metric), useMetric, onUseMetric)
Choice(
label = stringResource(R.string.settings_ride_mount),
options = PhoneMount.entries.map { it to stringResource(phoneMountLabel(it)) },
selected = phoneMount,
onSelect = onPhoneMount,
)
}
Text(
stringResource(R.string.settings_ride_fusion_log_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard {
SettingToggleRow(stringResource(R.string.settings_ride_fusion_log), fusionLogging, onFusionLogging)
}
}
}
/** The display name of a [PhoneMount]; also used by the V2X logger screen. */
internal fun phoneMountLabel(mount: PhoneMount): Int = when (mount) {
PhoneMount.HANDLEBAR -> R.string.settings_ride_mount_handlebar
PhoneMount.BAG -> R.string.settings_ride_mount_bag
PhoneMount.POCKET -> R.string.settings_ride_mount_pocket
}
@Composable
fun MqttSettingsScreen(
mqttPrefs: MqttPrefs,
@@ -699,6 +751,40 @@ private fun TwoWayChoice(
}
}
/** [TwoWayChoice] for any number of options: a labelled row of outlined buttons, the selected one filled. */
@Composable
private fun <T> Choice(
label: String,
options: List<Pair<T, String>>,
selected: T,
onSelect: (T) -> Unit,
) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
Spacer(Modifier.height(6.dp))
Row(
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
for ((value, text) in options) {
val isSelected = value == selected
OutlinedButton(
onClick = { onSelect(value) },
modifier = Modifier.weight(1f),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
),
) { Text(text, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, maxLines = 1) }
}
}
}
@Composable
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@@ -150,6 +150,21 @@ fun V2xLogSettingsScreen(
stringResource(R.string.v2xlog_obu_gnss),
if (isEsp32) stringResource(R.string.v2xlog_not_available) else fixAge(state.obuFixAgeMs),
)
Divider()
DisabledRow(
stringResource(R.string.v2xlog_fusion),
if (state.fusionLogging && state.phoneMount != null) {
stringResource(R.string.v2xlog_fusion_on, stringResource(phoneMountLabel(state.phoneMount)))
} else {
stringResource(R.string.v2xlog_fusion_off)
},
)
if (state.fusionLogging) {
Divider()
DisabledRow(stringResource(R.string.v2xlog_imu), state.imuSamples.toString())
Divider()
DisabledRow(stringResource(R.string.v2xlog_phone_gps), fixAge(state.phoneGpsFixAgeMs))
}
}
if (state.total == 0) {
Text(
@@ -15,6 +15,7 @@ import com.hawhamburg.micr0bu.data.transport.TransportType
import com.hawhamburg.micr0bu.data.transport.UsbNetworkDetector
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.data.transport.StationStatus
@@ -117,6 +118,13 @@ class MqttViewModel @Inject constructor(
viewModelScope.launch { obuHardwarePrefs.setOutgoingMessage(message) }
}
val esp32RxPath: StateFlow<Esp32RxPath> = obuHardwarePrefs.esp32RxPathFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
fun setEsp32RxPath(path: Esp32RxPath) {
viewModelScope.launch { obuHardwarePrefs.setEsp32RxPath(path) }
}
val signOutgoing: StateFlow<Boolean> = obuHardwarePrefs.signOutgoingFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
@@ -294,20 +302,22 @@ class MqttViewModel @Inject constructor(
/**
* [spatIntersections] with each SPATEM's signal groups placed on its MAPEM's lanes, and the
* rider's own approach picked from their position and heading. An intersection whose MAPEM has
* not been heard (yet) is still listed, with no lanes: its signal groups stay bare numbers.
* rider's own approach picked from their position and heading. The MAPEM is one heard on air or
* one the app ships with ([TrafficLights.geometryFor]). An intersection with neither is still
* listed, with no lanes: its signal groups stay bare numbers.
*/
val trafficLights: StateFlow<List<TrafficLight>> = combine(
spatIntersections,
mapGeometries,
camUseCaseRepository.storedMaps,
camUseCaseRepository.ownPosition,
) { spats, geometries, own ->
val byKey = geometries.groupBy { it.key }
) { spats, live, stored, own ->
val position = own?.let { MapPoint(it.latitude, it.longitude) }
spats.map { spat ->
TrafficLights.join(
signal = spat,
geometry = TrafficLights.pickGeometry(byKey[spat.key].orEmpty(), spat.state.revision),
own = own?.let { MapPoint(it.latitude, it.longitude) },
geometry = TrafficLights.geometryFor(spat.key, spat.state.revision, live, stored, position),
own = position,
ownHeadingDeg = own?.headingDeg,
ownSpeedMps = own?.speedMps,
)
@@ -0,0 +1,33 @@
package com.hawhamburg.micr0bu.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Backs Settings > Ride. */
@HiltViewModel
class RideSettingsViewModel @Inject constructor(
private val prefs: RidePreferences,
) : ViewModel() {
val phoneMount: StateFlow<PhoneMount> =
prefs.phoneMountFlow.stateIn(viewModelScope, SharingStarted.Eagerly, PhoneMount.DEFAULT)
val fusionLogging: StateFlow<Boolean> =
prefs.fusionLoggingFlow.stateIn(viewModelScope, SharingStarted.Eagerly, false)
fun setPhoneMount(mount: PhoneMount) {
viewModelScope.launch { prefs.setPhoneMount(mount) }
}
fun setFusionLogging(enabled: Boolean) {
viewModelScope.launch { prefs.setFusionLogging(enabled) }
}
}
@@ -65,7 +65,6 @@ data class SensorUiState(
val barometerEnabled: Boolean = true,
val gnssEnabled: Boolean = true,
val developerMode: Boolean = true,
val useMetric: Boolean = true,
val darkTheme: Boolean = true,
)
@@ -295,6 +294,5 @@ class SensorViewModel(application: Application) : AndroidViewModel(application)
if (!v) _state.value = _state.value.copy(gnss = null)
}
fun setDeveloperMode(v: Boolean) { _state.value = _state.value.copy(developerMode = v) }
fun setUseMetric(v: Boolean) { _state.value = _state.value.copy(useMetric = v) }
fun setDarkTheme(v: Boolean) { _state.value = _state.value.copy(darkTheme = v) }
}
+20 -4
View File
@@ -169,8 +169,14 @@
<string name="settings_gyro">Gyroskop</string>
<string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_units">Einheiten</string>
<string name="settings_metric">Metrisch (m, km/h, hPa)</string>
<string name="settings_ride">Fahrt</string>
<string name="settings_ride_mount">Position des Telefons</string>
<string name="settings_ride_mount_handlebar">Lenker</string>
<string name="settings_ride_mount_bag">Tasche</string>
<string name="settings_ride_mount_pocket">Hosentasche</string>
<string name="settings_ride_mount_desc">Wo das Telefon mitfährt: in einer Lenkerhalterung, in einer Tasche am Fahrrad oder in einer Hosentasche bzw. einem Rucksack. Die Sensorfusion wertet die Bewegungssensoren je nach Position anders aus, und jedes V2X-Log hält sie fest.</string>
<string name="settings_ride_fusion_log">Bewegungssensoren aufzeichnen</string>
<string name="settings_ride_fusion_log_desc">Für Testfahrten zur Sensorfusion: Der V2X-Datenlogger zeichnet zusätzlich Beschleunigungssensor, Gyroskop und Schwerkraft mit 100 Hz auf, sowie rohe GPS-Positionen neben der fusionierten Position. Das sind einige zehn MB pro Stunde.</string>
<string name="settings_mqtt_section">MQTT-Broker</string>
<string name="settings_broker_ip">Broker-IP</string>
<string name="settings_port">Port</string>
@@ -323,7 +329,12 @@
<string name="v2x_spat_countdown">%1$.0f s</string>
<string name="settings_esp32_link">ESP32-C5-Verbindung</string>
<string name="settings_esp32_link_ble">Bluetooth</string>
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, wählt die App den stärksten. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, zuerst das richtige in den Android-Bluetooth-Einstellungen koppeln. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
<string name="settings_esp32_rx_path">Empfangspfad</string>
<string name="settings_esp32_rx_v2x">V2X_RX</string>
<string name="settings_esp32_rx_raw">Rohframes</string>
<string name="settings_esp32_rx_v2x_note">Die Platine entpackt jedes empfangene Frame und sendet die fertige Nachricht, signiert oder nicht (MicrOBU-Erweiterung, bis 494 Byte). Klein und immer aktiv.</string>
<string name="settings_esp32_rx_raw_note">Debug: Die Platine sendet das ganze Funkframe (RAW_FRAME aus der Spezifikation, bei Bedarf fragmentiert) und die App entpackt es. Keine 494-Byte-Grenze, aber Frames können bei ausgelastetem Link verloren gehen und es braucht mehr Bandbreite, besonders über Bluetooth.</string>
<string name="settings_esp32_message">Senden während der Aufzeichnung</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
@@ -344,7 +355,7 @@
<string name="v2xlog_desc">Zeichnet jede empfangene V2X-Nachricht (CAM, DENM, SPATEM, MAPEM, VAM) in einer Datenbankdatei auf, mit Zeitstempel, der GNSS-Position des Telefons und, wenn vorhanden, der GNSS-Position der OBU und der Signalstärke (RSSI).</string>
<string name="v2xlog_mode_esp32">ESP32-C5: protokolliert, was das Board über die Verbindung weiterleitet, mit RSSI. Das Board hat kein GNSS, daher gibt es keine OBU-Position.</string>
<string name="v2xlog_mode_cit">CiT One: protokolliert die MQTT-Topics. Die API liefert keine RSSI; die OBU-Position stammt aus v2x/rx/obu_gnss.</string>
<string name="v2xlog_esp32_firmware_note">Die aktuelle ESP32-C5-Firmware leitet nur CAM, DENM und SPATEM weiter; MAPEM und VAM erscheinen erst, wenn die Firmware sie annimmt.</string>
<string name="v2xlog_esp32_firmware_note">Die Platine leitet CAM, DENM, SPATEM, MAPEM und VAM weiter. Auf dem Empfangspfad V2X_RX passt eine Nachricht über 494 Byte nicht in eine Link-Nachricht und wird verworfen; der Pfad Rohframes kennt diese Grenze nicht. Der Logger speichert auf beiden Pfaden die dekodierte Nachricht, nicht das Funkframe.</string>
<string name="v2xlog_start">Aufzeichnung starten</string>
<string name="v2xlog_stop">Aufzeichnung beenden</string>
<string name="v2xlog_error">Aufzeichnung fehlgeschlagen: %1$s</string>
@@ -353,6 +364,11 @@
<string name="v2xlog_total_val">%1$d Nachrichten · %2$s</string>
<string name="v2xlog_phone_gnss">Telefon-GNSS</string>
<string name="v2xlog_obu_gnss">OBU-GNSS</string>
<string name="v2xlog_fusion">Daten für Sensorfusion</string>
<string name="v2xlog_fusion_off">aus (Einstellungen > Fahrt)</string>
<string name="v2xlog_fusion_on">an · Telefon: %1$s</string>
<string name="v2xlog_imu">Bewegungssensor-Messwerte</string>
<string name="v2xlog_phone_gps">Telefon-GPS (roh)</string>
<string name="v2xlog_fix_age">Fix vor %1$d s</string>
<string name="v2xlog_no_fix">kein Fix</string>
<string name="v2xlog_not_available">nicht verfügbar</string>
+20 -4
View File
@@ -170,8 +170,14 @@
<string name="settings_gyro">Gyroscope</string>
<string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_units">Units</string>
<string name="settings_metric">Metric (m, km/h, hPa)</string>
<string name="settings_ride">Ride</string>
<string name="settings_ride_mount">Phone position</string>
<string name="settings_ride_mount_handlebar">Handlebar</string>
<string name="settings_ride_mount_bag">Bag</string>
<string name="settings_ride_mount_pocket">Pocket</string>
<string name="settings_ride_mount_desc">Where the phone rides: on a handlebar mount, in a bag on the bike, or in a pocket or backpack. Sensor fusion reads the motion sensors differently for each, and every V2X log records it.</string>
<string name="settings_ride_fusion_log">Record motion sensors</string>
<string name="settings_ride_fusion_log_desc">For sensor fusion test rides: the V2X data logger also records accelerometer, gyroscope and gravity at 100 Hz, and raw GPS fixes next to the fused location. Adds tens of MB per hour.</string>
<string name="settings_mqtt_section">MQTT Broker</string>
<string name="settings_broker_ip">Broker IP</string>
<string name="settings_port">Port</string>
@@ -330,7 +336,12 @@
<string name="trip_review_title">Trip Review</string>
<string name="settings_esp32_link">ESP32-C5 link</string>
<string name="settings_esp32_link_ble">Bluetooth</string>
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. If several micrOBUs are nearby the app picks the strongest one. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. With several micrOBUs nearby, pair the right one in Android\'s Bluetooth settings first. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
<string name="settings_esp32_rx_path">Receive path</string>
<string name="settings_esp32_rx_v2x">V2X_RX</string>
<string name="settings_esp32_rx_raw">Raw frames</string>
<string name="settings_esp32_rx_v2x_note">The board unpacks every received frame and sends the finished message, signed or not (MicrOBU extension, up to 494 bytes). Small and always on.</string>
<string name="settings_esp32_rx_raw_note">Debug: the board sends the whole radio frame (the spec\'s RAW_FRAME, fragmented if large) and the app unpacks it. No 494-byte limit, but frames can be lost when the link is busy and it needs more bandwidth, especially over Bluetooth.</string>
<string name="settings_esp32_message">Transmit while recording</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
@@ -351,7 +362,7 @@
<string name="v2xlog_desc">Records every V2X message received (CAM, DENM, SPATEM, MAPEM, VAM) into a database file, with a timestamp, the phone GNSS fix and, where available, the OBU GNSS fix and the signal strength (RSSI).</string>
<string name="v2xlog_mode_esp32">ESP32-C5: logging what the board forwards over the link, with RSSI. The board has no GNSS, so there is no OBU position.</string>
<string name="v2xlog_mode_cit">CiT One: logging the MQTT topics. The API carries no RSSI; the OBU position comes from v2x/rx/obu_gnss.</string>
<string name="v2xlog_esp32_firmware_note">The current ESP32-C5 firmware forwards only CAM, DENM and SPATEM, so MAPEM and VAM appear only once the firmware accepts them.</string>
<string name="v2xlog_esp32_firmware_note">The board forwards CAM, DENM, SPATEM, MAPEM and VAM. On the V2X_RX receive path a message over 494 bytes does not fit one link message and is dropped; the Raw frames path has no such limit. The logger stores the decoded message, not the radio frame, on either path.</string>
<string name="v2xlog_start">Start logging</string>
<string name="v2xlog_stop">Stop logging</string>
<string name="v2xlog_error">Logging failed: %1$s</string>
@@ -360,6 +371,11 @@
<string name="v2xlog_total_val">%1$d messages · %2$s</string>
<string name="v2xlog_phone_gnss">Phone GNSS</string>
<string name="v2xlog_obu_gnss">OBU GNSS</string>
<string name="v2xlog_fusion">Sensor fusion data</string>
<string name="v2xlog_fusion_off">off (Settings > Ride)</string>
<string name="v2xlog_fusion_on">on · phone on %1$s</string>
<string name="v2xlog_imu">Motion sensor samples</string>
<string name="v2xlog_phone_gps">Phone GPS (raw)</string>
<string name="v2xlog_fix_age">fix %1$d s ago</string>
<string name="v2xlog_no_fix">no fix</string>
<string name="v2xlog_not_available">not available</string>
@@ -61,6 +61,29 @@ class CamEncodeGoldenTest {
assertEquals(expectedHex, encoded)
}
/**
* [referenceCam] turning right at 12.34 deg/s, encoded by asn1tools with `yawRateValue` -1234:
* YawRateValue is positive to the LEFT (TS 102 894-2), while [Cam.yawRateDps] is positive
* clockwise. Only the yawRate bits differ from [expectedHex]. Generated 2026-11-18 by decoding
* [expectedHex] with asn1tools (cam_1_4_1 + cdd_1_3_1_1), setting the value, and re-encoding.
*/
private val rightTurnHex =
"0202000f423f4a88402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337fee9ecb2000000"
@Test
fun `a right turn goes on air as a negative YawRateValue`() {
val encoded = CamUperCodec.encode(referenceCam.copy(yawRateDps = 12.34))
.joinToString("") { "%02x".format(it) }
assertEquals(rightTurnHex, encoded)
}
@Test
fun `a negative YawRateValue from the air is a right turn`() {
val bytes = rightTurnHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
val cam = requireNotNull(CamUperCodec.decode(bytes, referenceCam.timestamp))
assertEquals(12.34, cam.yawRateDps!!, 1e-9)
}
@Test
fun `own decoder agrees with the encoder on every field it reads`() {
// Self-consistency is necessary but NOT sufficient - see the class KDoc. This guards the
@@ -0,0 +1,110 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.cam.CamParser
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.cam.StationType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The two CiT One JSON parsers against payloads shaped exactly like the ones the CiT One really
* sends (keys, nesting and types copied from the logged runs, values changed). Both parsers used to
* return null for every one of them: `obu_gnss` keeps its position under `gnss`, not `own_info`,
* and the CAM topic sends `stationType` as a name.
*/
class CitOneJsonParsersTest {
private val obuGnss = """
{ "type": "v2xgw-owninfo", "obu_timestamp_sec": 1773834329.0660601,
"gnss": { "latitude": 53.5551, "longitude": 10.0222, "altitude_m": 60.5, "speed_mps": 5.25,
"time_utc": "2026-03-18T11:45:29Z", "heading_deg": 87.5, "acceleration_mpss": -0.25,
"curvature": { "radiusOfCurve_m": 3276.0, "confidence": 100.0 },
"positionError_stdDev": { "posErrSemiMajorAxisLen_m": 0.446, "posErrSemiMinorAxisLen_m": 0.446,
"posErrSemiMajorAxisOrientation_deg": 0.0, "altitudeErr_m": 0.609, "headingErr_deg": 361.0,
"groundSpeedErr_mps": 0.077, "verticalSpeedErr_mps": -1.0, "DOP": -4.45e-25 },
"satInfo": { "fix": "3d", "numSatUsed": 14,
"numSatVisible": { "gps": 0, "gbas": 0, "sbas": 0, "gnss": 0 } } },
"own_info": { "stationID": 319450879, "stationType": 5, "vehicleRole": 0, "vehicleWidth_m": 1.8,
"vehicleLength_m": 4.26, "yawRate_degps": 6.5, "isBreaking": false },
"pathHistory": { "refLatitude": 53.5551, "refLongitude": 10.0222, "refAltitude": 60.5,
"pathPoints": [ { "deltaLatitude": -3.5e-06, "deltaLongitude": 1.31e-05,
"deltaAltitude_m": -5.0, "pathDeltaTime_ms": 834 } ] } }
""".trimIndent()
private val processedCam = """
{"heading_deg":1.2,"pathHistory":{"path":{"coordinates":[[10.0258218,53.5526996,52.6],
[10.0258295,53.5524988,51.6]],"type":"LineString"}},"position":{"coordinates":[10.0258076,53.5528397,52.6],
"type":"Point"},"positionError_stdDev":{"altitudeErr_m":10.0,"groundSpeedErr_mps":0.105,"headingErr_deg":0.5,
"posErrSemiMajorAxisLen_m":1.57,"posErrSemiMajorAxisOrientation_deg":5.4,"posErrSemiMinorAxisLen_m":1.56},
"speed_mps":7.25,"stationId":3124041003,"stationType":"passengerCar","type":"v2x-cam",
"vehicleLength_m":4.9,"vehicleRole":"default","vehicleWidth_m":1.8,"yawRate_dps":-1.43}
""".trimIndent()
@Test
fun `obu_gnss - kinematics from gnss, identity and yaw rate from own_info`() {
val ego = ObuGnssParser.parseEgo(obuGnss, timestamp = 1_000L)!!
assertEquals(319450879L, ego.stationId)
assertEquals(StationType.PASSENGER_CAR, ego.stationType)
assertEquals(53.5551, ego.latitude, 1e-9)
assertEquals(10.0222, ego.longitude, 1e-9)
assertEquals(5.25, ego.speedMps, 1e-9)
assertEquals(87.5, ego.headingDeg, 1e-9)
assertEquals(-0.25, ego.accelerationMps2!!, 1e-9)
// Right-positive on this topic in practice, as Cam.yawRateDps is: taken as it is.
assertEquals(6.5, ego.yawRateDps!!, 1e-9)
assertEquals(4.26, ego.vehicleLengthM!!, 1e-9)
assertEquals(1.8, ego.vehicleWidthM!!, 1e-9)
assertTrue(ego.isOwn)
}
@Test
fun `obu_gnss - the no-fix marker is not a position`() {
val noFix = obuGnss.replace("\"latitude\": 53.5551", "\"latitude\": 91.0")
.replace("\"longitude\": 10.0222", "\"longitude\": 181.0")
assertNull(ObuGnssParser.parseEgo(noFix))
}
@Test
fun `obu_gnss - the invalid speed marker reads as no speed`() {
val badSpeed = obuGnss.replace("\"speed_mps\": 5.25", "\"speed_mps\": 163.82")
assertEquals(0.0, ObuGnssParser.parseEgo(badSpeed)!!.speedMps, 0.0)
}
@Test
fun `CAM topic - station type name, vehicle size and a left-positive yaw rate`() {
val cam = CamParser.parse(processedCam, ownStationId = null)!!
assertEquals(3124041003L, cam.stationId)
assertEquals(StationType.PASSENGER_CAR, cam.stationType)
assertEquals(53.5528397, cam.latitude, 1e-9)
assertEquals(10.0258076, cam.longitude, 1e-9)
assertEquals(7.25, cam.speedMps, 1e-9)
assertEquals(1.2, cam.headingDeg, 1e-9)
// -1.43 on this left-positive topic is 1.43 deg/s to the right: +1.43 in Cam.yawRateDps.
assertEquals(1.43, cam.yawRateDps!!, 1e-9)
assertEquals(4.9, cam.vehicleLengthM!!, 1e-9)
assertEquals(1.8, cam.vehicleWidthM!!, 1e-9)
assertFalse(cam.isOwn)
}
@Test
fun `CAM topic - own CAM recognised by the station id learned from obu_gnss`() {
assertTrue(CamParser.parse(processedCam, ownStationId = 3124041003L)!!.isOwn)
}
@Test
fun `CAM topic - an unknown station type name is still rejected`() {
assertNull(CamParser.parse(processedCam.replace("passengerCar", "spaceship"), ownStationId = null))
}
@Test
fun `station type names map by name, with the gap before roadSideUnit`() {
assertEquals(2, StationType.fromApiName("cyclist"))
assertEquals(11, StationType.fromApiName("tram"))
assertEquals(15, StationType.fromApiName("roadSideUnit"))
assertNull(StationType.fromApiName(""))
assertNull(StationType.fromApiName(null))
}
}
@@ -0,0 +1,131 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.GnUnwrap
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The Kotlin port of `gn_unwrap.c` against the firmware's own code.
*
* `gn_unwrap_corpus.tsv` is written by `make corpus` in obu-firmware/test/host: frames from the recorded
* captures (unsigned and signed, single-hop and GeoBroadcast, CAM, DENM, MAPEM, SPATEM), copies cut at
* several lengths, copies with flipped bytes, and a few rejected frames, each with the verdict and the
* fields that `gn_unwrap_its` returns. Every line must come out the same here: same accept or reject,
* same port, flags, destination area, truncation and payload bytes.
*/
class GnUnwrapTest {
private class Line(
val frame: ByteArray, val accepted: Boolean, val port: Int, val flags: Int,
val lat: Int, val lon: Int, val dist: Int, val truncated: Boolean, val payload: ByteArray,
)
private fun String.hex(): ByteArray = ByteArray(length / 2) { substring(2 * it, 2 * it + 2).toInt(16).toByte() }
private fun corpus(): List<Line> {
val text = javaClass.classLoader!!.getResourceAsStream("gn_unwrap_corpus.tsv")!!.bufferedReader().readText()
return text.lines().filter { it.isNotBlank() }.map { l ->
val f = l.split("\t")
assertEquals("fields in: ${l.take(60)}", 9, f.size)
Line(f[0].hex(), f[1] == "A", f[2].toInt(), f[3].toInt(), f[4].toInt(), f[5].toInt(), f[6].toInt(),
f[7] == "1", f[8].hex())
}
}
@Test
fun `every corpus frame gets the verdict and fields of the C code`() {
val lines = corpus()
assertTrue("corpus too small: ${lines.size}", lines.size > 400)
var accepted = 0
var rejected = 0
for ((n, line) in lines.withIndex()) {
val r = GnUnwrap.unwrap(line.frame)
if (!line.accepted) {
assertNull("line $n: C rejects, Kotlin accepted", r)
rejected++
continue
}
assertNotNull("line $n: C accepts, Kotlin rejected", r)
r!!
assertEquals("line $n port", line.port, r.btpPort)
assertEquals("line $n area flag", line.flags and 1 != 0, r.hasGeoArea)
assertEquals("line $n signed flag", line.flags and 2 != 0, r.signedUnverified)
assertEquals("line $n area lat", line.lat, r.areaLatTenMicroDeg)
assertEquals("line $n area lon", line.lon, r.areaLonTenMicroDeg)
assertEquals("line $n area dist", line.dist, r.areaDistanceAMeters)
assertEquals("line $n truncated", line.truncated, r.truncated)
assertArrayEquals("line $n payload", line.payload, r.payload)
accepted++
}
// the corpus has both kinds in quantity: the test means something only if it does
assertTrue("accepted $accepted", accepted > 100)
assertTrue("rejected $rejected", rejected > 100)
}
@Test
fun `the corpus covers every message kind and both security shapes`() {
val seen = corpus().filter { it.accepted && !it.truncated }.map { Triple(it.port, it.flags and 2 != 0, it.flags and 1 != 0) }.toSet()
assertTrue(seen.contains(Triple(2001, false, false))) // unsigned single-hop CAM
assertTrue(seen.contains(Triple(2001, true, false))) // signed CAM
assertTrue(seen.any { it.first == 2002 && it.third }) // GeoBroadcast DENM
assertTrue(seen.any { it.first == 2003 }) // MAPEM
assertTrue(seen.any { it.first == 2004 }) // SPATEM
}
@Test
fun `a frame for a port that is not an ITS message port is rejected, VAM 2018 is accepted`() {
val cam = corpus().first { it.accepted && !it.truncated && it.port == 2001 && it.flags == 0 }
val vam = patchBtpPort(cam.frame, 2018)
assertEquals(2018, GnUnwrap.unwrap(vam)!!.btpPort)
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 1234)))
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 2005)))
}
/** The BTP-B destination port sits right after the GN headers: find it by the known payload start. */
private fun patchBtpPort(frame: ByteArray, port: Int): ByteArray {
val r = GnUnwrap.unwrap(frame)!!
val start = frame.indices.first { i -> i + r.payload.size <= frame.size && (r.payload.indices).all { frame[i + it] == r.payload[it] } }
val copy = frame.copyOf()
copy[start - 4] = (port shr 8).toByte() // BTP-B header: port u16 BE, port info u16 BE
copy[start - 3] = port.toByte()
return copy
}
@Test
fun `short and garbage input is rejected without an exception`() {
assertNull(GnUnwrap.unwrap(ByteArray(0)))
assertNull(GnUnwrap.unwrap(ByteArray(23)))
assertNull(GnUnwrap.unwrap(ByteArray(200)))
assertNull(GnUnwrap.unwrap(ByteArray(200) { 0xFF.toByte() }))
// every prefix of a real frame: never throws
val frame = corpus().first { it.accepted && !it.truncated && it.flags and 2 != 0 }.frame
for (n in 0..frame.size) GnUnwrap.unwrap(frame.copyOf(n))
}
@Test
fun `the V2X_RX body is the one V2xRxFrame reads and the firmware writes`() {
val line = corpus().first { it.accepted && !it.truncated && it.port == 2002 && it.flags and 1 != 0 }
val r = GnUnwrap.unwrap(line.frame)!!
val body = GnUnwrap.toV2xRxBody(r, -61)!!
assertEquals(V2xRxFrame.PREFIX_SIZE + r.payload.size, body.size)
val parsed = V2xRxFrame.parse(body)!!
assertEquals(2002, parsed.btpPort)
assertEquals(-61, parsed.rssiDbm)
assertNotNull(parsed.geoArea)
assertEquals(line.lat / 1e7, parsed.geoArea!!.latitude, 1e-9)
assertEquals(line.dist, parsed.geoArea!!.radiusMeters)
assertArrayEquals(r.payload, parsed.uper)
// flags: bit 0 area, bit 1 signed
assertEquals(0x01 or (if (r.signedUnverified) 0x02 else 0), body[3].toInt())
// a truncated message is not forwarded
val cut = corpus().firstOrNull { it.accepted && it.truncated }
if (cut != null) assertNull(GnUnwrap.toV2xRxBody(GnUnwrap.unwrap(cut.frame)!!, -50))
assertEquals(127, GnUnwrap.toV2xRxBody(r, 500)!![2].toInt()) // clamped like the firmware
assertEquals(-128, GnUnwrap.toV2xRxBody(r, -500)!![2].toInt())
}
}
@@ -0,0 +1,200 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.LinkMessage
import com.hawhamburg.micr0bu.data.transport.LinkReassembly
import com.hawhamburg.micr0bu.data.transport.RawFrame
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** Fragment reassembly as docs/station-link.pdf specifies it, and the RAW_FRAME record parser. */
class LinkReassemblyTest {
private var clock = 0L
private val reassembly = LinkReassembly { clock }
private fun fragment(flags: Int, seq: Int, total: Int, offset: Int, data: ByteArray, opcode: Int = LinkOpcode_RAW_FRAME) =
LinkMessage(
opcode, seq,
byteArrayOf(total.toByte(), (total shr 8).toByte(), offset.toByte(), (offset shr 8).toByte()) + data,
flags,
)
private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
@Test
fun `a complete message passes through unchanged`() {
val m = LinkMessage(0x81, 5, bytes(1, 2, 3))
assertArrayEquals(bytes(1, 2, 3), reassembly.feed(m)!!.body)
}
@Test
fun `three fragments in order become one message with flags 0`() {
assertNull(reassembly.feed(fragment(1, 9, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 9, 6, 2, bytes(3, 4))))
val whole = reassembly.feed(fragment(3, 9, 6, 4, bytes(5, 6)))!!
assertArrayEquals(bytes(1, 2, 3, 4, 5, 6), whole.body)
assertEquals(0, whole.flags)
assertEquals(9, whole.sequence)
assertEquals(LinkOpcode_RAW_FRAME, whole.opcode)
}
@Test
fun `a gap, a duplicate and a changed total drop the stream`() {
assertNull(reassembly.feed(fragment(1, 1, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 1, 6, 4, bytes(5, 6)))) // skipped the middle
assertNull(reassembly.feed(fragment(3, 1, 6, 2, bytes(3, 4)))) // the stream is gone: nothing completes
assertNull(reassembly.feed(fragment(1, 2, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 2, 6, 0, bytes(1, 2)))) // the same offset twice
assertNull(reassembly.feed(fragment(1, 3, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 3, 8, 2, bytes(3, 4)))) // total changed
assertNull(reassembly.feed(fragment(2, 4, 6, 2, bytes(3, 4)))) // a middle without a first
assertTrue(reassembly.dropped >= 4)
}
@Test
fun `an unfinished stream is discarded after two seconds of silence`() {
assertNull(reassembly.feed(fragment(1, 7, 4, 0, bytes(1, 2))))
clock += 2_500
assertNull(reassembly.feed(fragment(3, 7, 4, 2, bytes(3, 4)))) // the first fragment is gone
assertNull(reassembly.feed(fragment(1, 8, 4, 0, bytes(1, 2))))
clock += 1_500 // still inside the window
assertNotNull(reassembly.feed(fragment(3, 8, 4, 2, bytes(3, 4))))
}
@Test
fun `at most eight streams are held and the ninth is refused`() {
for (s in 1..8) assertNull(reassembly.feed(fragment(1, s, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(1, 9, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 9, 4, 2, bytes(3, 4)))) // refused, so nothing to complete
assertNotNull(reassembly.feed(fragment(3, 1, 4, 2, bytes(3, 4)))) // the held ones still finish
}
@Test
fun `an indication of 65535 octets is the largest, more is refused, a message of 2000 octets works`() {
val big = ByteArray(2000) { it.toByte() }
val chunk = 500
var out: LinkMessage? = null
var offset = 0
while (offset < big.size) {
val n = minOf(chunk, big.size - offset)
val flags = if (offset == 0) 1 else if (offset + n == big.size) 3 else 2
out = reassembly.feed(fragment(flags, 11, big.size, offset, big.copyOfRange(offset, offset + n)))
offset += n
}
assertArrayEquals(big, out!!.body)
assertNull(reassembly.feed(fragment(1, 12, 65_536 + 4, 0, bytes(1, 2))))
}
@Test
fun `different opcodes with the same sequence are separate streams`() {
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(1, 2), opcode = 0x85)))
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(9, 9), opcode = 0x81)))
val a = reassembly.feed(fragment(3, 5, 4, 2, bytes(3, 4), opcode = 0x85))!!
val b = reassembly.feed(fragment(3, 5, 4, 2, bytes(8, 8), opcode = 0x81))!!
assertArrayEquals(bytes(1, 2, 3, 4), a.body)
assertArrayEquals(bytes(9, 9, 8, 8), b.body)
}
// ---- large V2X_RX, fragmented by the firmware ---------------------------------------------
private fun hexBytes(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
/**
* `v2x_rx_fragments.tsv` is written by `test_v2x_fragments --dump` in obu-firmware/test/host: the first 888-byte
* SPATEM and 1198-byte MAPEM of the CiT node's 2026-11-23 recording, as the firmware's own code splits them for
* serial / BLE MTU 517 (512-octet messages) and BLE MTU 247 (244). Each line: port, UPER size, limit, V2X_RX body,
* then the link messages in order. The app must put back exactly that body and read the message out of it.
*/
@Test
fun `the firmware's fragments of a large V2X_RX reassemble to the body and parse`() {
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
assertEquals(4, lines.size)
for (line in lines) {
val f = line.split('\t')
val port = f[0].toInt()
val size = f[1].toInt()
val limit = f[2].toInt()
val body = hexBytes(f[3])
val wires = f.drop(4).map { hexBytes(it) }
assertTrue("$port/$size at $limit: needs fragments", wires.size >= 2)
var whole: LinkMessage? = null
wires.forEachIndexed { i, wire ->
assertTrue("$port/$size at $limit: a message of ${wire.size} octets exceeds $limit", wire.size <= limit)
val message = LinkMessage.decode(wire)!!
assertEquals(0x90, message.opcode)
assertEquals(if (i == 0) 1 else if (i == wires.size - 1) 3 else 2, message.flags)
whole = reassembly.feed(message)
if (i < wires.size - 1) assertNull(whole)
}
assertEquals(0x90, whole!!.opcode)
assertEquals(0, whole!!.flags)
assertArrayEquals(body, whole!!.body)
val v2x = V2xRxFrame.parse(whole!!.body)!!
assertEquals(port, v2x.btpPort)
assertEquals(size, v2x.uper.size)
assertEquals(if (port == 2003) 5 else 4, v2x.uper[1].toInt() and 0xFF) // ItsPduHeader.messageId: MAPEM 5, SPATEM 4
}
}
@Test
fun `losing one fragment of a large V2X_RX costs that message only`() {
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
val f = lines.first { it.split('\t')[2] == "512" && it.split('\t')[0] == "2003" }.split('\t')
val wires = f.drop(4).map { hexBytes(it) }
// the first message loses its middle fragment; the same message again, in full, still completes afterwards
val lost = wires.mapIndexedNotNull { i, w -> if (i == 1) null else LinkMessage.decode(w)!! }
for (m in lost) assertNull(reassembly.feed(m))
val next = wires.map { w -> LinkMessage.decode(w)!!.let { LinkMessage(it.opcode, it.sequence + 1, it.body, it.flags) } }
var whole: LinkMessage? = null
for (m in next) whole = reassembly.feed(m)
assertArrayEquals(hexBytes(f[3]), whole!!.body)
}
// ---- RAW_FRAME record ------------------------------------------------------------------
private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray {
val h = java.io.ByteArrayOutputStream()
fun u8(v: Int) = h.write(v and 0xFF)
fun u16(v: Int) { u8(v); u8(v shr 8) }
fun u32(v: Long) { u16(v.toInt()); u16((v shr 16).toInt()) }
u32(42); u8(flags); u8(rssi)
h.write("ITS5".toByteArray())
u32(1_900_000_000L); u32(123_456); u16(frame.size)
h.write(frame)
return h.toByteArray()
}
@Test
fun `a RAW_FRAME body parses into its fields and frame`() {
val frame = ByteArray(30) { (it * 3).toByte() }
val r = RawFrame.parse(rawBody(frame))!!
assertEquals(42L, r.counter)
assertTrue(r.utcTime)
assertFalse(r.ownTransmission)
assertEquals(-61, r.rssiDbm)
assertEquals(1_900_000_000L, r.seconds)
assertEquals(123_456L, r.microseconds)
assertArrayEquals(frame, r.frame)
assertTrue(RawFrame.parse(rawBody(frame, flags = 0x01))!!.ownTransmission)
}
@Test
fun `a malformed RAW_FRAME is refused`() {
val good = rawBody(ByteArray(10))
assertNull(RawFrame.parse(good.copyOf(19))) // shorter than the header
assertNull(RawFrame.parse(good.copyOf(good.size - 1))) // length field says more
assertNull(RawFrame.parse(good + byteArrayOf(0))) // or less
val bad = good.copyOf(); bad[6] = 'X'.code.toByte()
assertNull(RawFrame.parse(bad)) // wrong magic
}
private companion object {
const val LinkOpcode_RAW_FRAME = 0x85
}
}
@@ -0,0 +1,25 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import org.junit.Assert.assertEquals
import org.junit.Test
/** The stored and logged ids of [PhoneMount] are a file format: logs on disk carry them. */
class PhoneMountTest {
@Test
fun `ids are the ones written to settings and logs`() {
assertEquals(listOf("handlebar", "bag", "pocket"), PhoneMount.entries.map { it.id })
}
@Test
fun `every id reads back as its mount`() {
PhoneMount.entries.forEach { assertEquals(it, PhoneMount.fromId(it.id)) }
}
@Test
fun `a missing or unknown id falls back to the handlebar`() {
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId(null))
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId("roof"))
}
}
@@ -153,6 +153,34 @@ class SpatemUperCodecTest {
assertNull(SignalPhaseEvent(SignalPhase.DARK, null, null, null).secondsUntil(topOfHour))
}
@Test
fun `decodes a road RSU SPATEM with names and advisory speeds`() {
// 888 bytes from the Berliner Tor RSU (2026-11-23): intersection and movement names, and a greenwave
// plus an ecoDrive AdvisorySpeed on every event. Before names and speeds were walked, every one of
// its SPATEMs was refused and the V2X screens stayed empty. Expected values: asn1tools, ETSI modules.
val bytes = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim().hexToBytes()
assertEquals(888, bytes.size)
val spat = SpatemUperCodec.decode(bytes, receivedAt)
assertNotNull(spat)
spat!!
assertEquals(1_095_348_116L, spat.stationId)
assertEquals(470_408, spat.minuteOfYear)
val i = spat.intersections.single()
assertEquals("-1/23", i.key)
assertEquals(2, i.revision)
assertEquals(470_408, i.moy)
assertEquals(59_719, i.timeStampMs)
assertEquals(listOf(1, 2, 3, 4, 5), i.movements.map { it.signalGroup })
i.movements.forEach { assertEquals(8, it.events.size) }
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5562, 5562, 5562), i.movements[0].events.first())
assertEquals(SignalPhase.PERMISSIVE_CLEARANCE, i.movements[0].events.last().phase)
assertEquals(6522, i.movements[0].events.last().minEndTimeDs)
assertEquals(SignalPhase.PROTECTED_MOVEMENT_ALLOWED, i.movements[2].events.first().phase)
assertEquals(SignalPhase.PERMISSIVE_MOVEMENT_ALLOWED, i.movements[3].events.first().phase)
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5802, 5802, 5802), i.movements[4].events.first())
assertEquals(6762, i.movements[4].events.last().minEndTimeDs)
}
@Test
fun `does not decode another message type as SPATEM`() {
// protocolVersion 2, messageId 2 (CAM) - the header guard must reject it outright.
@@ -0,0 +1,105 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.map.StoredMaps
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
/** The bundled intersections, and which of them a SPATEM is matched to. */
class StoredMapsTest {
private val stored by lazy { StoredMaps.parse(File("src/main/assets/${StoredMaps.ASSET_PATH}").readText()) }
private val one by lazy { stored.last { it.key == "3/2349" } }
private val here by lazy { MapPoint(one.refLatitude, one.refLongitude) }
private fun pick(
key: String = one.key,
revision: Int = one.revision,
live: List<com.hawhamburg.micr0bu.domain.map.IntersectionGeometry> = emptyList(),
own: MapPoint? = here,
) = TrafficLights.geometryFor(key, revision, live, stored, own)
@Test
fun `bundle holds the recorded Hamburg intersections and the bench RSU, one per revision`() {
// Lower bounds: tools/mapem_bundle.py adds to the list.
assertTrue(stored.size >= 17)
assertTrue(stored.count { it.region != null } >= 16)
assertEquals(stored.size, stored.map { it.key to it.revision }.toSet().size)
}
@Test
fun `the bench RSU's SPATEM joins its stored intersection`() {
val hex = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim()
val spat = SpatemUperCodec.decode(hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray(), 0L)!!
val state = spat.intersections.single()
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)!!
assertEquals("-1/23", matched.key)
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
assertTrue(light.approaches.isNotEmpty())
assertFalse(light.revisionMismatch)
}
@Test
fun `every recorded intersection joins the SPATEM recorded for it`() {
val samples = javaClass.classLoader!!.getResource("mapem/spat_samples.txt")!!.readText()
.lines().filter { it.isNotBlank() }.associate { line ->
val (key, revision, hex) = line.split(" ")
(key to revision.toInt()) to hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
}
// Entries added later may have no recorded SPATEM; the original 16 all do.
val sampled = stored.filter { it.region != null && (it.key to it.revision) in samples }
assertTrue(sampled.size >= 16)
for (geometry in sampled) {
val spat = SpatemUperCodec.decode(samples.getValue(geometry.key to geometry.revision), 0L)!!
val state = spat.intersections.single { it.key == geometry.key && it.revision == geometry.revision }
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)
assertSame(geometry, matched)
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
assertTrue("no approaches for ${geometry.key}", light.approaches.isNotEmpty())
assertFalse(light.revisionMismatch)
}
}
@Test
fun `matched on region and id together`() {
assertSame(one, pick())
assertNull(pick(key = "4/2349"))
assertNull(pick(key = "-1/2349"))
}
@Test
fun `a stored map of another revision is not used`() {
assertNull(pick(revision = one.revision + 1))
}
@Test
fun `a stored map far from the rider is not used, an unknown position does not block it`() {
// 0.03 deg of latitude is 3.3 km, beyond the radius; 0.01 deg is 1.1 km, inside it.
assertNull(pick(own = MapPoint(one.refLatitude + 0.03, one.refLongitude)))
assertSame(one, pick(own = MapPoint(one.refLatitude + 0.01, one.refLongitude)))
assertSame(one, pick(own = null))
}
@Test
fun `a live map of the same revision wins over the stored one`() {
val live = one.copy(name = "live")
assertSame(live, pick(live = listOf(live)))
}
@Test
fun `the stored map wins over a live one of another revision`() {
val live = one.copy(revision = one.revision + 1)
assertSame(one, pick(live = listOf(live)))
// And with nothing stored for the SPATEM's revision, the live one is still the fallback.
assertSame(live, pick(revision = one.revision + 2, live = listOf(live)))
}
}
@@ -0,0 +1,121 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import kotlin.math.cos
import kotlin.math.sin
/**
* The yaw rate must be the rotation about the true vertical whatever way up the phone is, which is
* what the old z-axis reading got wrong for anything but a phone lying flat, screen up.
*/
class YawRateEstimatorTest {
private val g = 9.81f
private val ms = 1_000_000L
private val radToDeg = 180.0 / Math.PI
/** Feeds [up] (a unit vector, device frame) as gravity and a pure yaw of [ccwRadPerSec] about it. */
private fun YawRateEstimator.yawAbout(up: DoubleArray, ccwRadPerSec: Double, startNanos: Long, samples: Int = 5) {
onGravity((up[0] * g).toFloat(), (up[1] * g).toFloat(), (up[2] * g).toFloat(), startNanos)
for (i in 0 until samples) {
onGyro(
(up[0] * ccwRadPerSec).toFloat(),
(up[1] * ccwRadPerSec).toFloat(),
(up[2] * ccwRadPerSec).toFloat(),
startNanos + i * 20 * ms,
)
}
}
@Test
fun `flat phone, left turn, is negative in the clockwise-positive convention`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
// 0.5 rad/s counter-clockwise = turning left = -28.6 deg/s clockwise-positive, as the old z-axis path gave.
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
}
@Test
fun `handlebar tilt does not shrink the yaw rate`() {
// Phone tilted 50 deg toward the rider about its x axis: up is (0, sin 50, cos 50) in the device frame.
val tilt = Math.toRadians(50.0)
val up = doubleArrayOf(0.0, sin(tilt), cos(tilt))
val est = YawRateEstimator()
est.yawAbout(up, 0.5, 0L)
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
// The z axis alone would have read only cos 50 = 64 % of it.
assertEquals(0.643, up[2], 1e-3)
}
@Test
fun `upright phone, where the z axis reads nothing, still gives the yaw rate`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 1.0, 0.0), -0.3, 0L)
assertEquals(0.3 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
}
@Test
fun `rotation about a horizontal axis is not yaw`() {
// Flat phone pitching about its x axis, as on a bump: no yaw at all.
val est = YawRateEstimator()
est.onGravity(0f, 0f, g, 0L)
for (i in 0 until 5) est.onGyro(1.0f, 0f, 0f, i * 20 * ms)
assertEquals(0.0, est.yawRateDps(80 * ms)!!, 1e-9)
}
@Test
fun `averages over the window ending at the newest sample`() {
val est = YawRateEstimator(windowNanos = 100 * ms)
est.onGravity(0f, 0f, g, 0L)
est.onGyro(0f, 0f, 10f, 0L) // 300 ms before the newest: outside the window
est.onGyro(0f, 0f, 0.2f, 220 * ms)
est.onGyro(0f, 0f, 0.4f, 260 * ms)
est.onGyro(0f, 0f, 0.6f, 300 * ms)
assertEquals(-0.4 * radToDeg, est.yawRateDps(300 * ms)!!, 1e-3)
}
@Test
fun `no yaw rate before gravity is known`() {
val est = YawRateEstimator()
est.onGyro(0f, 0f, 0.5f, 0L)
assertNull(est.yawRateDps(0L))
}
@Test
fun `no yaw rate once the gyroscope has gone quiet`() {
val est = YawRateEstimator(staleNanos = 500 * ms)
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
assertNotNull(est.yawRateDps(500 * ms))
assertNull(est.yawRateDps(600 * ms))
}
@Test
fun `gyroscope samples are dropped against a stale up direction`() {
val est = YawRateEstimator(staleNanos = 500 * ms)
est.onGravity(0f, 0f, g, 0L)
est.onGyro(0f, 0f, 0.5f, 900 * ms)
assertNull(est.yawRateDps(900 * ms))
}
@Test
fun `a gravity sample too weak to give a direction is ignored`() {
val est = YawRateEstimator()
est.onGravity(0f, 0f, 0.5f, 0L)
est.onGyro(0f, 0f, 0.5f, 0L)
assertNull(est.yawRateDps(0L))
}
@Test
fun `reset forgets the up direction and the samples`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
est.reset()
assertNull(est.yawRateDps(80 * ms))
est.onGyro(0f, 0f, 0.5f, 100 * ms)
assertNull(est.yawRateDps(100 * ms))
}
}
@@ -0,0 +1,37 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.cam.CamParser
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps] is positive clockwise. The CiT One's CAM topic
* is positive to the left (documented, and 316 of 316 turning samples in the logged runs), so
* [CamParser] flips it. Its `obu_gnss` topic is documented as left-positive too, but the logs show
* it positive to the right (27 of 27), so [ObuGnssParser] keeps it.
*/
class YawRateJsonSignTest {
@Test
fun `CAM topic - positive is a left turn, so it becomes negative`() {
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02,
"yawRate_dps": 15.0}"""
assertEquals(-15.0, CamParser.parse(json, ownStationId = null)!!.yawRateDps!!, 1e-9)
}
@Test
fun `CAM topic - a missing yaw rate stays unavailable`() {
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02}"""
assertNull(CamParser.parse(json, ownStationId = null)!!.yawRateDps)
}
@Test
fun `obu_gnss - yawRate_degps is read as it is, since the CiT One sends it right-positive`() {
// own_info as in Listing 2.1, with the position placed where this parser reads it.
val json = """{"own_info": {"stationID": 1345678, "stationType": 2,
"latitude": 53.55, "longitude": 10.02, "yawRate_degps": -7.5}}"""
assertEquals(-7.5, ObuGnssParser.parseEgo(json)!!.yawRateDps!!, 1e-9)
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
02044149af94472d8803872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c10200396c474a3823310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966670b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966670ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e000018028191859796cd3bb2f241537f241cb4e7d1d009d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966570b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966570ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e01001c02819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb33856485648564bc5c28b804b388a700966770add0add0add78b851700967114e012cc6e179a179a179af170a2e012ce229c025991c2f5c2f5c2f5de2e145c0259c453804b333861886188618bc5c28b804b388a700966770c450c450c4578b851700967114e012cc6e1a6a1a6a1a6af170a2e012ce229c025991c34fc34fc34fde2e145c0259c453804b03c06002805031f2f7ecc597967e7d3920e5a73e8e808ecae159215921592f170a2e012ce229c02599dc2b742b742b75e2e145c0259c453804b31b85e685e685e6bc5c28b804b388a700966470bd70bd70bd778b851700967114e012ccae186218621862f170a2e012ce229c02599dc311431143115e2e145c0259c453804b31b869a869a869abc5c28b804b388a700966470d3f0d3f0d3f78b851700967114e012c0f0100140140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b85aa85aa85aabc5c28b804b388a700966470b5f0b5f0b5f78b851700967114e012ccce177217721772f170a2e012ce229c02599dc2f342f342f35e2e145c0259c453804b31b865e865e865ebc5c28b804b388a700966470cc70cc70cc778b851700967114e012ccce1a421a421a42f170a2e012ce229c02599dc34d434d434d5e2e145c0259c453804b0bc0800400503c0a00480500
@@ -0,0 +1,4 @@
2004 888 512 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a70096 90034d008603f80164732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
2004 888 244 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd 90024d008603ec003bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7 90024d008603d801c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358 90034d008603c402f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
2003 1198 512 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a7712100001400781 90024d00bc04f80119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900 90034d00bc04f003a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
2003 1198 244 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b049 90024d00bc04ec004af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f 90024d00bc04d80154c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181 90024d00bc04c402a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5 90024d00bc04b003df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49 90034d00bc049c04201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
1 2004 888 512 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a70096 90034d008603f80164732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
2 2004 888 244 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd 90024d008603ec003bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7 90024d008603d801c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358 90034d008603c402f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
3 2003 1198 512 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a7712100001400781 90024d00bc04f80119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900 90034d00bc04f003a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
4 2003 1198 244 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b049 90024d00bc04ec004af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f 90024d00bc04d80154c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181 90024d00bc04c402a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5 90024d00bc04b003df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49 90034d00bc049c04201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
+31 -1
View File
@@ -17,7 +17,8 @@ the parts below that describe the earlier vanetza-idf port say so. Hardware chec
- **Two links, one protocol.** USB-C (native USB Serial/JTAG) or Bluetooth LE, chosen in Settings.
Both carry Niklas Dathe's station-link protocol (revision 2 of the spec adds the MicrOBU extensions: `V2X_RX`, unsigned sending, battery guard).
- **Reception is unchanged for the app.** Every ITS message heard on air reaches the phone, signed
or not, verifiable or not, exactly as with the previous firmware.
or not, verifiable or not, exactly as with the previous firmware. Since 2026-11-11 the app can instead take the spec's
`RAW_FRAME` debug capture and unwrap it itself (Settings > Receive path); both paths stay in the firmware.
- **Demo PKI, not the EU trust list.** Signed messages carry a throwaway chain. Receivers that
verify against the EU trust list drop them; unsigned sending remains available.
@@ -86,6 +87,7 @@ firmware is what counts; the current spec table lists the same UUIDs).
| phone → board | `STATUS_REQUEST` | once a second; the answer is the heartbeat |
| board → phone | `CONFIRM` | answer to a request; for `STATUS_REQUEST` its detail is the 131-octet snapshot: counters, tickets, signed/refused counts, battery |
| board → phone | `V2X_RX` (0x90, MicrOBU) | every ITS message heard on air |
| board → phone | `RAW_FRAME` (0x85, spec) | debug copy of each radio frame, only while `RAW_CAPTURE` is on; the app can use it instead of `V2X_RX` (Settings > Receive path) |
The app side is `Esp32Link.kt` (session), `StationLink.kt` (codec, pinned by unit tests to bytes
from Niklas Dathe's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
@@ -95,6 +97,34 @@ spec retires but the station still decodes, and revision 2 documents): a ride ro
pinger keeps one fixed MAC, and a new MAC reconfigures the station. Without one a signed station takes its address from the
ticket and an unsigned one draws a random MAC per configuration. With one, signed and unsigned frames both leave from it.
Data flow of a received frame, with both paths:
```mermaid
flowchart TB
subgraph Board[ESP32-C5 board]
Air[ITS-G5 frame] --> Radio[Radio, promiscuous RX]
Radio --> Stack[Vanetza: decap, verify]
Radio --> Unwrap[gn_unwrap.c]
Radio -->|RAW_CAPTURE on| Tap[Raw capture tap]
Stack -->|verified| Ind[BTP_DATA_INDICATION]
Unwrap --> Rx[V2X_RX 0x90]
Tap --> RawF[RAW_FRAME 0x85, fragmented]
end
Ind & Rx & RawF --> Link[USB or BLE link]
subgraph Phone[Android app]
Link --> Re[LinkReassembly]
Re --> Sel{Receive path}
Sel -->|V2X_RX| Dec[V2xRxFrame]
Sel -->|Raw frames| Pr[RawFrame, then GnUnwrap]
Pr --> Dec
Dec --> Cod[CAM, DENM, SPATEM, MAPEM, VAM codecs]
Cod --> UI[Use cases, V2X screens, logger]
end
```
The app also **reassembles fragmented link messages** (flags 1-3 of the spec) and has two receive paths: `V2X_RX`
(default) and `RAW_FRAME`, which it unwraps itself with `GnUnwrap.kt`; see the README for the comparison.
## Redundancy and recovery
| Situation | What notices | What happens |
+131
View File
@@ -0,0 +1,131 @@
# 07 – Sensor fusion, phase 0 and 1: inputs and logging (2026-11-18)
The goal is a GNSS/IMU fusion filter on the phone that gives the CAM and VAM a fresh position at
every send, plus a better heading, yaw rate and acceleration, on any phone mount. Phase 0 fixed the
inputs the transmit path already had. Phase 1 records everything the filter needs, so the filter can
be built and tuned offline against real rides before it touches what goes on air. Hardware checks
still to do are in `TODO.md` ("Sensor fusion ...").
## Phases
| Phase | What | State |
|---|---|---|
| 0 | Correct inputs: yaw rate about the vertical, fix times on GNSS time, monotonic clock for intervals | done (727c911, sign fix 6fa91d1) |
| 1 | Logging: motion sensors, both phone GNSS sources, clocks, phone mount | done, rides pending |
| 2 | Filter core: 5-state EKF (position, heading, speed, gyro bias), pure Kotlin, replayed on phase 1 logs | next |
| 3 | Any mount: forward-axis estimate, rigidity check, mount-dependent noise | after 2 |
| 4 | Offline tuning: GNSS outage drift, heading vs. course over ground, innovation statistics | with 2 and 3 |
| 5 | Into CAM/VAM, the confidence ellipse and the use-case engine, behind a switch | last |
## Phase 0 in short
- **Yaw rate** is the gyroscope projected onto gravity (`domain/fusion/YawRateEstimator`), the
rotation about the true vertical however the phone is held, averaged over 100 ms, at
`SENSOR_DELAY_GAME`. The gyroscope's z axis alone was only right with the phone flat, screen up.
- **Time on air** is the GNSS time of the fix itself: its monotonic age
(`Location.getElapsedRealtimeNanos`) taken off GNSS time now (`GnssTimeSource.atElapsedRealtime`).
The phone's clock setting, or a step of it, cannot reach the CAM or GN timestamps.
- **Intervals** (elevated CAM rate, VAM generation rules, acceleration from GNSS speed) use the
monotonic clock, so setting the phone clock back cannot hold VAMs off.
- **Yaw rate sign**: the CAM's YawRateValue is positive to the left; the app's `Cam.yawRateDps` is
positive to the right. `CamUperCodec` and `CamParser` flip it; the CiT One's `obu_gnss` sends it
right-positive already (checked against logged rides), so `ObuGnssParser` does not.
## Settings > Ride
Replaces the old Units screen (the app is metric throughout; that switch did nothing).
- **Phone position**: Handlebar, Bag (on the bike) or Pocket (also a backpack). Stored in
`RidePreferences` as `handlebar` / `bag` / `pocket` and written into every V2X log as
`meta.phone_mount`. The filter will use it to choose how much to trust the gyroscope: fixed to the
bike on the handlebar (but turning with the steering), mostly fixed in a bag, moving with the
rider's body in a pocket. It is a manual setting; detecting the mount from the sensors is phase 3
work, and these labelled logs are what it would be built and checked on.
- **Record motion sensors**: off by default. When on at the moment a V2X log starts, that log also
records the data below. It adds about 300 rows a second, tens of MB per hour.
Both are read once when a log starts, so one file is always one mount and one mode. Changing them
mid-log takes effect from the next log.
## What a fusion log contains
Settings > Developer > V2X data logger, with Record motion sensors on. File name
`v2x_log_<start>_<hardware>_imu-<mount>.db` (without the suffix when it is off). Schema version 2
(`meta.schema_version`, `PRAGMA user_version`); version 1 logs have no `imu` or `clock` table and
none of the new `gnss` columns.
### `imu` (new)
| Column | |
|---|---|
| `sensor` | `accel` (m/s², gravity included), `gyro` (rad/s), `gravity` (m/s², `TYPE_GRAVITY`, points up) |
| `elapsed_ns` | the sample's own `SensorEvent.timestamp`, on `SystemClock.elapsedRealtimeNanos` |
| `ts_ms` | the same instant as wall-clock epoch ms, for browsing only |
| `x`, `y`, `z` | device frame: x right, y up the screen, z out of the screen |
Requested at 100 Hz (`meta.imu_period_us` = 10000), on a background thread of its own. `gravity` is
only logged when the phone has a real `TYPE_GRAVITY` sensor (the Pixel 9 Pro does); the sensors'
names, vendors and maximum rates are in `meta.sensor_*`.
### `gnss` (new columns)
| Column | |
|---|---|
| `source` | `phone` = fused location (Google Play services, as before), `phone_gps` = raw `GPS_PROVIDER` (new, fusion logging only), `obu` = the CiT One's `obu_gnss` |
| `elapsed_ns` | the fix's own monotonic time; phone sources only. What fusion lines fixes up with sensor samples on |
| `speed_accuracy_mps`, `bearing_accuracy_deg` | 1-sigma, where the provider gives them |
| `provider` | `fused` or `gps` |
`fix_ms` is the fix's instant as wall-clock ms and `ts_ms` when the app received it, so
`ts_ms - fix_ms` is the delivery delay. The fused and the raw source are logged side by side because
the Pixel's fused location includes Google's city-street corrections while the raw one is the chip
alone and not pre-filtered; the rides decide which one the filter uses. `meta.gnss_hardware` names
the GNSS chip.
### `clock` (new)
Once a second, the three phone clocks read back to back: `elapsed_ns` (monotonic), `wall_ms` (the
phone clock), `gnss_ms` (`SystemClock.currentGnssTimeClock`, NULL without GNSS time). Sensor samples
and phone fixes carry monotonic time, received messages and OBU fixes wall time, and the transmit
path GNSS time; these rows convert between them, and show the phone clock's error and any step in it.
## Checking a log
```
py -3.11 tools/fusion_log_check.py v2x_log_..._imu-handlebar.db
```
Read-only, standard library only. Per file it prints the metadata, each sensor's sample count, rate,
interval distribution, gaps and magnitude, each GNSS source's rate, accuracy, delivery delay and
whether its fixes fall inside the sensor recording, the distance between the fused and raw fixes
(and the OBU's, on the CiT One), and the phone clock's error and steps. It ends with PASS, WARN or
FAIL lines, and exits with 1 if anything failed:
- FAIL: logging was off, no `imu`/`clock` table, a sensor missing, a sensor gap over 1 s, a phone
source missing, phone fixes without `elapsed_ns`.
- WARN: a sensor rate outside 80–130 Hz, gaps over 100 ms, an accelerometer or gravity magnitude far
from g, a GNSS gap over 5 s, fixes with no gyroscope sample within 20 ms, no GNSS time, a phone
clock step, a log that was not stopped cleanly.
Tested against synthetic logs built from `V2xLogWriter`'s own table definitions (a clean ride, an
injected 300 ms gyroscope gap, a 14-minute clock step, logging off, fixes without monotonic time);
not yet against a real ride.
## Test rides
Recorded per mount (handlebar, bag, pocket), 20–30 minutes each, with Record motion sensors on and the
phone mount set before pressing Start. Each ride should include left and right turns, a roundabout,
stops of at least 10 s (the filter estimates the gyroscope offset while standing), and if possible a
bridge or underpass for a real GNSS outage. The list to tick off is in `TODO.md`.
## Code
| | |
|---|---|
| `domain/fusion/PhoneMount.kt` | the mount setting and its stored ids |
| `data/RidePreferences.kt`, `viewmodel/RideSettingsViewModel.kt` | Settings > Ride storage and screen state |
| `ui/screens/SettingsScreen.kt` (`RideSettingsScreen`) | the screen |
| `data/SensorRepository.kt` | `gpsProviderFlow`, sensor flows on a chosen thread, `describeSensor` |
| `data/log/V2xLogger.kt`, `data/log/V2xLogWriter.kt` | the logging and the schema |
| `ui/screens/V2xLogSettingsScreen.kt` | shows mount, motion sensor row count and raw GPS fix age while logging |
| `tools/fusion_log_check.py` | the check above |
+113
View File
@@ -0,0 +1,113 @@
# Large SPATEM / MAPEM reception (2026-11-23)
Why a road RSU's SPATEMs and MAPEMs did not reach the phone's V2X screens, in two independent places, and what was
changed. Interface changes are in `obu-firmware/docs/station-link.tex` (revision 3).
## Symptom
A MAPEM and a SPATEM compiled to sit below 494 bytes arrived on the phone; larger ones did not. Later, with the
firmware fixed, the phone *logger* showed the RSU's large messages but the app's V2X screens stayed empty.
The "larger" test messages were far above the limit: **888 bytes (SPATEM) and 1198 bytes (MAPEM)**, from the
Berliner Tor RSU (station 1095348116, intersection 23, 6 lanes, 5 signal groups). The small pair were 377 B (MAPEM)
and 58 B (SPATEM). The test therefore showed that nothing is fragmented on that path, not where a cutoff sits.
## Problem 1: the firmware dropped everything over 494 bytes
**It did receive them.** The radio captures frames up to 2346 bytes, and the firmware's own `gn_unwrap.c`, replayed
on the PC over the CiT node's pcap (`its5_20261123_150746.pcap`, 27 367 frames), accepts all of them: 1727 MAPEMs
of 1198 B and 3384 SPATEMs of 888 B. They are valid: asn1tools decodes every distinct one and re-encodes it
byte-identically.
**The firmware then threw them away.** `V2X_RX` (opcode 0x90, MicrOBU's own) was designed as one link message. A link
message is at most 512 octets (the largest GATT value), minus 4 header and 14 prefix octets leaves **494 bytes** of
ITS payload. `Station::forward_raw` called `v2x_rx_fits()`, and for a longer message only incremented
`raw_oversize_` and returned. The fragmenting code (`LinkService::send_fragmented`, used for `RAW_FRAME`, PKI and
indications) existed and the app already reassembled any fragmented opcode, but the gate in front of it meant a
`V2X_RX` was never offered to it.
**Why nobody noticed:**
- It was a known, documented limit (`gn_unwrap.h`, `NOTES.md`, TODO.md: "road MAPEMs over 494 bytes are still dropped as
oversize (no fragmentation)"), but every earlier bench run used the bench RSU, whose messages are 58 and 295 bytes.
- The drop was silent where the phone could see it. The counter lived only in the firmware, STATUS has a fixed
131-octet layout with no field for it, and the only trace was one LOG line per 10 s on the USB log, which a phone on
BLE never gets.
- Comparing the phone log with a second receiver (the node's pcap) is what exposed it: 0 of 1537 large MAPEMs and
0 of 3004 large SPATEMs reached the phone, against 98.5 % and 96.5 % of the small ones.
**What the 2026-11-23 COM10 read did and did not show.** An early check of COM10's log concluded the board "never saw
a large message". That was wrong. `tools/station_status_watch.py` prints only the first few V2X_RX lines unless asked,
and opening the port reset the board. It showed nothing about large messages either way.
### Fix (obu-firmware)
- `v2x_rx.hpp`: `v2x_rx_plan()` decides `single` (up to 494 B, byte-identical to before), `fragmented` (up to
`v2x_rx_max_forward` = 2300 B), `covered_by_raw` (large and `RAW_CAPTURE` on) or `drop`.
- `link_fragment.hpp` (new, host-testable): `split_fragments()` is the one fragmenter. `LinkService::send_fragmented`
uses it, with the same bytes on the wire as before.
- Best effort, never blocking: fragments of a large `V2X_RX` go out on serial through the non-blocking
`try_write`, no retry, no wait. The first failed fragment ends that message; the app drops the incomplete stream
(2 s idle, or the next first fragment). A transport that would need more than 8 fragments (ATT MTU 23) skips the
message.
- `serial::try_write` now writes nothing when no USB host is connected.
- Counters `raw_fragmented_`, `raw_fragment_failed_`, `raw_covered_`, `raw_oversize_`, in the throttled LOG line.
STATUS is unchanged.
- The app's V2X_RX / Raw frames switch is untouched. While `RAW_CAPTURE` is on a large message is not sent a second
time as V2X_RX.
- TX path untouched.
### Result on air (COM10, BLE, 17:08-17:20)
`tools/rx_size_compare.py` on the new phone log and node pcap: MAPEM 1198 B 92.9 % of what the node heard, SPATEM
888 B 81.7 %, CAMs 92.5-99.3 %, `radio_dropped` 0, no BLE disconnects.
## Problem 2: the app's SPATEM decoder refused the RSU's messages
**Why the logger had them and the screens did not.** Both read the same `V2X_RX` frames from `Esp32Link`. They differ
in what they do with the bytes:
- `V2xLogger` stores the raw UPER payload and classifies it from the ITS PDU header. Decoding only fills convenience
columns (position, speed, a summary), inside `runCatching`, so a decoder that fails leaves them NULL and the row is
stored anyway.
- `CamUseCaseRepository.handleSpatUper` hands the bytes to `SpatemUperCodec.decode`; on `null` it logs
"decode FAILED" and emits nothing, so no SPAT reached the traffic-light screens.
**Why the decoder returned null.** `SpatemUperCodec` returned null whenever it met an optional it could not size.
The RSU's SPATEM uses two such fields on every intersection:
- `name` / `movementName` (`DescriptiveName`, IA5String SIZE(1..63)): "Berliner Tor / Kolbergstrasse" and one per
movement.
- `speeds` (`AdvisorySpeedList`) on every event: a greenwave and an ecoDrive advice per phase. This, with the names
and the 8 events per movement, is why the message is 888 bytes and not ~58.
The decoder's header comment said it had been validated against 79 042 SPATEMs from the 2026-03-18 drive; those
messages simply carried neither field. The gap was latent: until the firmware forwarded large messages, an 888-byte
SPATEM never reached the app, so the decoder never met one.
The MAPEM decoded correctly all along (it already reads names); the traffic-light screens need the SPATEM as well.
### Fix (app)
`SpatemUperCodec` now walks, without keeping, `DescriptiveName` (6-bit length n-1, then 7 bits per character) and
`AdvisorySpeedList` (4-bit count n-1; per entry: extension bit, five optional bits, type = extension bit plus 2 bits,
speed 9 bits, confidence 3 bits, distance 14 bits, class 8 bits). Regional extensions and extension values still
return null. Widths come from `dsrc_2_2_1.asn`.
## Verification
| Check | Result |
|---|---|
| Firmware host suite (`make check` in `obu-firmware/test/host`): chain, replay with asn1tools, 2 M-iteration fuzz, battery, firmware | pass; the firmware unit tests grew from 40 to 46 |
| `test_v2x_fragments`: the node pcap through unwrap, plan, fragments, two independent reassemblers, at link limits 512 and 244, with a lost fragment | 5111 large messages, 0 failures |
| App `LinkReassemblyTest` on the firmware's own fragments (`v2x_rx_fragments.tsv`) | pass |
| `SpatemUperCodec` against asn1tools on every distinct SPATEM of the new phone log | 718 of 718 equal field for field, 3590 movements |
| App unit suite | 197 tests, 0 failures |
| ESP-IDF 6.0.2 image build | 0x1f7aa0 bytes, 34 % of the app partition free |
## Files changed
Firmware: `v2x_rx.hpp`, `link_fragment.hpp` (new), `link_service.cpp/.hpp`, `station.cpp/.hpp`, `serial_link.cpp`,
`gn_unwrap.h` (comment), `NOTES.md`, `README.md`, `docs/station-link.tex`. Tests: `test_firmware.cpp`,
`test_v2x_fragments.cpp` (new), `Makefile`. App: `SpatemUperCodec.kt`, `SpatemUperCodecTest.kt`,
`LinkReassemblyTest.kt`, resources `v2x_rx_fragments.tsv`, `spatem_road_rsu_888.hex`. Tool: `tools/rx_size_compare.py`.
## Still open
- The V2X screens on the phone with the rebuilt app (this document was written before that check).
- MAPEM / SPATEM loss on BLE rises with size (58-byte SPATEM 96.5 % on 2026-11-23 earlier, 888-byte SPATEM 81.7 % now): a lost fragment loses
the message. If the screens need better, options are a smaller fragment cadence or a loss counter in the app
(`LinkReassembly.dropped`).
- Advisory speeds are walked, not used; a GLOSA display could read them.
File diff suppressed because one or more lines are too long
+20 -3
View File
@@ -35,8 +35,16 @@ custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
(`Station::forward_raw`) and reaches the phone as `V2X_RX`. Body: `u16 port, i8 rssi, u8 flags
(bit0 GBC area, bit1 signed), i32 lat, i32 lon, u16 distance_a, ITS payload`. `0x85` is the spec's
`RAW_FRAME` debug capture and `0x86` is reserved by Niklas Dathe, hence `0x90`. BTP ports 2001
CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM, 2018 VAM pass; a message over 494 bytes does not fit a
512-octet link message and is dropped and counted (not fragmented).
CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM, 2018 VAM pass. A message up to 494 bytes is one link
message, unchanged. Since 2026-11-23 a larger one (a road SPATEM or MAPEM, 555-1243 bytes; up to
`v2x_rx_max_forward` = 2300) goes out in link fragments (`link_fragment.hpp`, flags 1/2/3 as the spec
defines them), best effort: no retry and no waiting, a fragment no transport takes ends that message
(the app drops the incomplete stream) and `raw_fragment_failed_` counts it, and the serial fragments use
the non-blocking `try_write` so a stalled USB host cannot hold the station task that drains the radio queue.
A transport that would need more than 8 fragments (ATT MTU 23) skips the message. While `RAW_CAPTURE` is on
the app reads `RAW_FRAME`, so a large message is not sent a second time as `V2X_RX` (`raw_covered_`).
Before this change a message over 494 bytes was dropped and counted (the 2026-11-23 bench run lost every
888-byte SPATEM and 1198-byte MAPEM that way).
- **Unsigned transmission.** Niklas Dathe's station signs everything. A request with GN security
profile 1 (or 0 while the station is configured `security = 0`) goes out unsigned with
`geonet.c`'s header and the position of the last PoTi (`Station::unsecured_request`), from a
@@ -64,7 +72,7 @@ custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
- **Flash size 8 MB** (XIAO), TX power ceiling 20 dBm (`radio_policy.hpp` admits 20 dBm on channel 180).
- **ATT MTU 517** (`CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU`, Niklas Dathe's 512): the app asks for 517 and a 494-octet
V2X_RX is a 512-octet link message, which needs a value of 512, i.e. an MTU of 515. At 512 such a message was
split into fragments the app does not reassemble.
split into fragments the app did not reassemble then (it does now, `LinkReassembly`).
- **Link-layer address.** A signed station without a named MAC uses the address derived from its ticket; with the
16-octet STATION_CONFIGURE the phone names it (see "Unsigned transmission"). The CAM and VAM station ID still
rotates in the app; the app now rotates the MAC with it on a ride and keeps one fixed for the bench pinger.
@@ -101,6 +109,15 @@ eFuse-based gates, an on-device TS 102 941 client (enrolment and authorisation r
update), the `RAW_CAPTURE` debug path, fragmentation of link messages, the XIAO and `mainboard-v5` boards, and the
battery reading.
### Both receive paths stay
`V2X_RX` (ours) and `RAW_FRAME` / `RAW_CAPTURE` (Niklas Dathe's, in the spec) both stay in the firmware, and the app has a switch
(Settings > Connection > ESP32-C5 > Receive path) that chooses which one it consumes. The firmware does not know which: it
always sends `V2X_RX`, and sends `RAW_FRAME` while `RAW_CAPTURE` is on (the app turns it on, mode 0x03, only in raw mode). In raw
mode the app unwraps the frame itself with `GnUnwrap.kt`, a port of `gn_unwrap.c` that `GnUnwrapTest` checks against the C code
on a corpus (`make corpus` in `test/host` writes `app/src/test/resources/gn_unwrap_corpus.tsv`). The app also reassembles
fragmented link messages as the spec defines them, so a raw frame or an indication above one link message works.
### Measured on the bench, 2026-11-11
Production XIAO on COM10, Pixel 9 Pro on BLE, COM3 board as an on-air listener (details and open points in `TODO.md`):
+22 -1
View File
@@ -39,6 +39,7 @@ link:
max_message: 512 octets, fragmented above that by the spec
microbu_extensions:
V2X_RX: opcode 0x90, every ITS message heard on air, verified or not
receive_paths: V2X_RX and the spec's RAW_FRAME both stay; the app chooses (Settings > Receive path), RAW_CAPTURE mode 3 turns raw on
unsigned_tx: security profile 1, or 0 with station security 0
radio: polled from STATION_CONFIGURE on
battery_guard: deep sleep below 3.30 V, no phone on USB, runs again from 3.60 V
@@ -89,6 +90,26 @@ It prints the log, the 131-octet STATUS once a second (uptime, signing and radio
battery) and the first V2X_RX messages. Status exchange: the host sends `STATUS_REQUEST` every
1000 ms; `CONFIRM.detail` contains the snapshot.
Received messages reach the phone on two paths that both stay in the firmware: `V2X_RX` (ours, always on, already unwrapped, one message up to 494 octets, fragmented above that up to 2300) and `RAW_FRAME` (the spec's debug capture, on after `RAW_CAPTURE`, the whole radio frame, fragmented when large). The Android app has a switch for which one it consumes. The board always sends `V2X_RX` for a message that fits one link message (up to 494 octets), also while the raw capture is on; a larger one (a road SPATEM or MAPEM) goes out as fragmented `V2X_RX`, except while `RAW_CAPTURE` is on, when the `RAW_FRAME` copy carries it and it is not sent twice. `RAW_CAPTURE` modes are bits: 0x01 on, 0x02 broadcast only, 0x04 own transmissions too (the app uses 0x03; the bench tests use 0x05 to read back the station's own frames). See [NOTES.md](NOTES.md).
```mermaid
flowchart LR
Air[ITS-G5 frame on air] --> Radio[C5 radio, promiscuous RX]
Radio --> Stack[Vanetza stack: decap and verify]
Radio --> Unwrap[gn_unwrap.c: 802.11, LLC, GN, BTP, signature envelope]
Radio -->|only while RAW_CAPTURE is on| Cap[Raw capture tap: ITS5 record]
Stack -->|verified only| Ind[BTP_DATA_INDICATION 0x81]
Unwrap -->|signed or not, fragmented above 494 octets, not when RAW_CAPTURE is on| Rx[V2X_RX 0x90, MicrOBU]
Cap -->|fragmented if large| Raw[RAW_FRAME 0x85, spec]
Ind --> Link[Station link: USB or BLE]
Rx --> Link
Raw --> Link
Link --> App[Android app]
App -->|Receive path: V2X_RX| UseA[uses V2X_RX, ignores RAW_FRAME]
App -->|Receive path: Raw frames| UseB[reassembles, unwraps with GnUnwrap, ignores V2X_RX]
```
## BLE pairing
```yaml
@@ -119,7 +140,7 @@ make firmware # 40 unit tests: link codec, STATUS, reassembly, V2X_RX, poli
make # everything: chain, replay of recorded frames, fuzz, battery, firmware
```
These run on the PC and cannot test the radio, BLE, NVS or USB. What still needs a board, a phone or a
These run on the PC and cannot test the radio, BLE, NVS or USB. The board-side tests (link conformance, transmit soak, reset and fuzz, run overnight on the spare board) are in [test/bench](test/bench/README.md), described in [docs/overnight-bench-test.pdf](docs/overnight-bench-test.pdf). What still needs a board, a phone or a
second ESP32-C5 is listed in [../TODO.md](../TODO.md). More: [test/host/README.md](test/host/README.md).
## More
Binary file not shown.
+143
View File
@@ -0,0 +1,143 @@
\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
Revision 2, status 2026-11-27. Scripts: \cmd{obu-firmware/test/bench}.\newline Companion documents: \cmd{obu-firmware/test/bench/README.md}, \cmd{obu-firmware/test/host/README.md},\newline\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 reach the radio driver 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 checked.} 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. The copy is made when the radio driver \emph{accepts} the frame, not when it reports the transmission complete, so it proves neither that the frame went on the air nor that another station can hear it (section 7). The driver's completion count is in \cmd{device.log} (\cmd{TX observation: submitted= completed=}); the test does not check it yet.
\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, 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. The script's search for that line currently also matches ``no crash'' (section 7).
\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}
\subsection*{7.1\quad Overnight run 2026-11-26 (6.0\,h, current build)}
Spare board on COM3 of the home workstation, firmware \cmd{aef6539-dirty} (built 2026-11-26 01:47; the uncommitted changes were in the bench scripts), transmitting at 5\,dBm, 02:39 to 08:40: 11 full cycles and the transmit phases of a twelfth. Results: \cmd{test/results/overnight-20261126-023952} and \cmd{host-20261126-023952}. An 8\,h run started before it was cancelled by mistake and is not evaluated here.
\textbf{Board checks: 2113 passed, 16 failed, 8 warnings, 70 information.} All 16 failures and all 8 warnings come from one fault, the transmit stall below, in 4 of the 12 cycles.
\begin{longtable}{@{}P{34mm}P{128mm}@{}}
\toprule\textbf{Area} & \textbf{Result}\\\midrule\endhead
conformance & start and end of the run: 74 checks each, none failed.\\
transmitted content & no corrupted or duplicated copy and no wrong source MAC in any soak phase; 1175 frames sent right after a reconfigure carried the new MAC and security. The MAC failures of the stale build are gone. \cmd{sign\_failed} stayed 0.\\
resets and boots & 55 reset cycles passed. 80 boots in \cmd{boot.log}, all with reset reason ``USB peripheral'', no panic or watchdog text. The boot panic of 2026-11-25 did not recur.\\
link fuzz & 11 passes, no failed check, heap within 8\,KB each time.\\
heap & lowest ever 39\,712 octets (limit 16\,KB), reached during a stall. Reconfigure trend $+196$\,octets per hour over 4 readings: no sign of a leak.\\
receive & \textbf{not exercised}: no other station was heard (\cmd{radio\_received} 0), so the receive-queue check passed without any load.\\\bottomrule
\end{longtable}
\needspace{50mm}
\textbf{Transmit stall (open).} The radio driver accepted 16 frames, reported none of them complete, and refused every further frame with \cmd{ESP\_ERR\_NO\_MEM}.
\begin{longtable}{@{}P{16mm}P{34mm}P{48mm}P{60mm}@{}}
\toprule\textbf{Cycle} & \textbf{Unsigned soak began} & \textbf{First refusal to first completion} & \textbf{Signed requests accepted but never sent}\\\midrule\endhead
3 & 03:50:19 & 155\,s & 423 of 1801\\
5 & 04:50:27 & 151\,s & 413 of 1800\\
10 & 07:35:23 & 186\,s & 516 of 1800\\
12 & 08:35:28 & 159\,s & 436 of 740 (phase cut short by the end of the run)\\\bottomrule
\end{longtable}
\begin{itemize}
\item \textbf{When:} always at the start of the first transmit phase after the 300\,s receive-only idle stage, where the station restarts the radio for transmit and receive: 4 of the 11 such starts (cycles 2 to 12). Cycle 1, which follows the conformance stage, did not stall.
\item \textbf{What the phone is told:} unsigned requests are refused with \cmd{resource\_limit} (164 here, then the test stops the phase). Signed requests are \textbf{answered accepted and then dropped}, 1788 in total; only \cmd{radio\_failed} in STATUS shows it.
\item \textbf{Configure does not clear it.} A repeated \cmd{STATION\_CONFIGURE}, and the signed phase's configure, left the stall in place. The station keeps the running Wi-Fi driver unless radio mode, channel or power change (\cmd{main/station.cpp}, \cmd{radio\_changed}).
\item \textbf{It clears by itself} after about 2.5 to 3 minutes. The driver then reports the 16 waiting frames as sent successfully (one further frame per stall is reported failed). If they did go on the air, they were that old; a second receiver is needed to tell.
\item \textbf{Heap:} about 13\,KB stay allocated during the stall and are released when it ends. The 1952 \cmd{ESP\_ERR\_NO\_MEM} warnings in \cmd{device.log} equal the sum of \cmd{radio\_failed}.
\end{itemize}
The cause is not known. The same pattern (about 17 requests accepted, 4 of 11 cycles) appeared on 2026-11-25 with the build of 10 November, so it predates the changes since then. The note of that day that a later configure cleared it is not confirmed: passing time or a radio restart would explain it too.
\textbf{Also open.} Signed payloads of 1398 to 1400 octets are answered accepted but not transmitted (\cmd{requests\_refused} $+1$, \cmd{sign\_failed} unchanged).
\textbf{PC-side tests: passed.} \cmd{make check}: chain test 4627 checks, fuzz 2\,000\,000 inputs, battery policy, 46 firmware unit tests, fragments (27\,367 records, 0 failures); the capture replay was skipped (no recordings on this PC). Then 273 fuzz runs of 200 million inputs each (seeds 101 to 373, $5.46\times10^{10}$ inputs): no crash. \cmd{summary.txt} nevertheless lists all 273 as \cmd{FUZZ FAILURE (exit 0)} and the script exits 1. This is a \textbf{false alarm}: \cmd{Select-String} ignores case, so the pattern \cmd{CRASH} matches ``no crash'' in every log. Not fixed yet (\cmd{run\_host\_tests\_overnight.ps1}; \cmd{-CaseSensitive} is needed).
\textbf{Next steps.} (1) A short reproducer: receive-only for 300\,s, then transmit, repeated. (2) Check whether restarting the radio ends a stall; if so, have the firmware do it when no frame completes for a few seconds. (3) Make the bench test compare completed with submitted frames. (4) Do not answer a signed request ``accepted'' without a way to report that the radio refused it. (5) Repeat with a second station on the air, to test reception and to see what happens to the waiting frames.
\subsection*{7.2\quad Earlier runs of 2026-11-25}
\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 2, 2026-11-27: results of the 6\,h run of 2026-11-26 (section 7.1). Corrected what the own-TX copy proves (section 3). Two script fixes for Windows PowerShell 5.1: \cmd{setup\_workstation.ps1} now installs a missing Python package instead of stopping on the failed import, and \cmd{start\_overnight.ps1} no longer fails on the keep-awake call before doing anything.\par
Revision 1, 2026-11-25: first version, written with the move of the overnight test to the spare board.
\end{document}
File diff suppressed because it is too large Load Diff
+47 -20
View File
@@ -21,15 +21,15 @@
\newcolumntype{F}{@{}|P{12mm}|P{43mm}|P{36mm}|P{25mm}|P{48.15mm}|@{}}
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[L]{\footnotesize Document revision 2 (MicrOBU)}
\fancyfoot[L]{\footnotesize Document revision 3 (MicrOBU)}
\fancyfoot[R]{\footnotesize\thepage\ / \pageref{LastPage}}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\hypersetup{pdftitle={microbu station link interface reference, revision 2 (MicrOBU)}}
\hypersetup{pdftitle={microbu station link interface reference, revision 3 (MicrOBU)}}
\begin{document}
microbu station link interface reference, revision 2 (MicrOBU)\par
microbu station link interface reference, revision 3 (MicrOBU)\par
\vspace{3mm}
Revision 1 was written by Niklas Dathe (microbu-firmware, commit e4e4bd8); revision 2 is revision 1 plus the additions of the MicrOBU production firmware (obu-firmware). Every addition is marked \textbf{MicrOBU extension}; the revision history is at the end.\par\smallskip
Revision 1 was written by Niklas Dathe (microbu-firmware, commit e4e4bd8); revisions 2 and 3 are revision 1 plus the additions of the MicrOBU production firmware (obu-firmware). Every addition is marked \textbf{MicrOBU extension}; the revision history is at the end.\par\smallskip
The maximum link message is 512 bytes, including the four-byte header.\par\smallskip
USB Serial/JTAG and BLE GATT carry the same messages.
The host sends a status request as a link heartbeat.\par\smallskip
@@ -1147,7 +1147,7 @@ Marks record origin and time basis.
{\ttfamily 12} & {\ttfamily frame\_\allowbreak{}length} & {\ttfamily u16} & bytes & Gives the raw radio-frame size in bytes. \\
{\ttfamily 14} & {\ttfamily frame} & {\ttfamily bytes[\allowbreak{}frame\_\allowbreak{}length]} & \textemdash & Contains the raw radio-frame bytes. \\
\end{longtable}}
\Needspace{7\baselineskip}\section{MicrOBU extensions (revision 2)}\label{sec:microbu-extensions}
\Needspace{7\baselineskip}\section{MicrOBU extensions (revisions 2 and 3)}\label{sec:microbu-extensions}
These additions are not in revision 1. A host written for revision 1 keeps working: it never sees opcode 0x90 unless it listens for it, and it never sends security profile 0x01.
\Needspace{8\baselineskip}\subsection{{\ttfamily V2X\_\allowbreak{}RX}}
{\small\color{ink}\textbf{0x90}\quad STATION TO HOST \quad (MicrOBU extension)}
@@ -1156,8 +1156,8 @@ Delivers every ITS message heard on air, verified or not. The station stack deca
\toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endfirsthead
\toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endhead
\bottomrule\endfoot
{\ttfamily reply} & {\ttfamily none} & One-way indication, not fragmented. \\
{\ttfamily maximum\_\allowbreak{}payload} & {\ttfamily 494 bytes} & 512 minus the four-byte header and the 14-byte prefix. A longer message is dropped and counted, never fragmented. \\
{\ttfamily reply} & {\ttfamily none} & One-way indication. Fragmented when the body exceeds one link message (revision 3, Section~\ref{sec:microbu-v2xrx-frag}). \\
{\ttfamily maximum\_\allowbreak{}payload} & {\ttfamily 2300 bytes} & Up to 494 bytes (512 minus the four-byte header and the 14-byte prefix) the message is one link message. Revision 3: a longer one is fragmented, up to 2300 bytes; beyond that it is dropped and counted. Revision 2 dropped everything over 494 bytes. \\
{\ttfamily btp\_\allowbreak{}ports} & {\ttfamily 2001--2004, 2018} & CAM, DENM, MAPEM, SPATEM, VAM. Other ports are not delivered. \\
{\ttfamily availability} & {\ttfamily from configure} & The radio is polled from STATION\_CONFIGURE on, before the first POTI\_UPDATE. \\
\end{longtable}}
@@ -1174,6 +1174,32 @@ Delivers every ITS message heard on air, verified or not. The station stack deca
{\ttfamily 12} & {\ttfamily area\_\allowbreak{}distance\_\allowbreak{}a} & {\ttfamily u16} & m & Radius or first dimension of the destination area; 0 when bit 0 is clear. \\
{\ttfamily 14} & {\ttfamily its\_\allowbreak{}payload} & {\ttfamily remaining bytes} & \textemdash & The ITS message (CAM, DENM, MAPEM, SPATEM, VAM) in its UPER encoding. \\
\end{longtable}}
\Needspace{8\baselineskip}\subsection{\texttt{V\_\allowbreak{}2X\_\allowbreak{}RX} and \texttt{RAW\_\allowbreak{}FRAME}: both stay}\label{sec:microbu-rxpaths}
Revision 2 does not replace the debug capture of revision 1 with \texttt{V\_2X\_RX}: the station keeps both, and the host chooses.
\begin{itemize}
\item \texttt{V\_2X\_RX} is sent for every ITS message heard, always, once the radio runs (it needs no \texttt{RAW\_CAPTURE}). The station has already unwrapped the frame, so a host decodes the payload at once; a message of up to 494 octets is one link message, a larger one is fragmented (revision 3, Section~\ref{sec:microbu-v2xrx-frag}).
\item \texttt{RAW\_FRAME} (revision 1) is sent only while \texttt{RAW\_CAPTURE} is on, as a copy of the whole 802.11 frame, fragmented when it exceeds one link message. A host that uses it unwraps the frame itself, is not limited to 494 octets (neither is \texttt{V\_2X\_RX} since revision 3), and accepts that copies may be dropped when the transport is busy.
\end{itemize}
The station does not know which path the host uses and sends \texttt{V\_2X\_RX} regardless. The MicrOBU Android app offers both as a setting (Receive path). In raw mode it sends \texttt{RAW\_CAPTURE} with mode 0x03 (capture on, broadcast frames only), reassembles fragments as described in Section~\ref{sec:fragmentation-host}, unwraps each frame with the same rules as the station does for \texttt{V\_2X\_RX} (single-hop broadcast and GeoBroadcast, BTP-B ports 2001--2004 and 2018, a signature envelope unwrapped without verification) and ignores the \texttt{V\_2X\_RX} messages. In \texttt{V\_2X\_RX} mode it sends mode 0 and ignores \texttt{RAW\_FRAME}.
\Needspace{8\baselineskip}\subsection{Fragmented \texttt{V\_\allowbreak{}2X\_\allowbreak{}RX} (revision 3)}\label{sec:microbu-v2xrx-frag}
Road roadside units send SPATEMs and MAPEMs of 555 to 1243 octets (the Berliner Tor unit: 888 and 1198), more than the 494 octets one link message carries. Revision 2 dropped them in the station, silently as far as the host could tell. From revision 3 the station sends them in fragments, with the framing of the fragmentation section of revision 1 (flags 1, 2 and 3; the same opcode 0x90 and sequence on every fragment; each fragment body starts with total length and offset). The body that is reassembled is the ordinary \texttt{V\_2X\_RX} body of this section, the 14-octet prefix included.
{\small\begin{longtable}{@{}P{45mm}P{55mm}P{72.8mm}@{}}
\toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endfirsthead
\toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endhead
\bottomrule\endfoot
{\ttfamily single message} & {\ttfamily up to 494 bytes} & Unchanged from revision 2: flags 0, one link message, byte for byte. \\
{\ttfamily fragmented} & {\ttfamily 495 to 2300 bytes} & Body of 14 + payload octets, split into fragments of at most the transport message size minus eight octets (four of link header, four of fragment header): 504 octets of body on serial and on BLE with ATT MTU 517. An 888-byte SPATEM is two fragments, a 1198-byte MAPEM three. \\
{\ttfamily dropped} & {\ttfamily over 2300 bytes} & Counted by the station, not sent. Truncated and empty messages are never sent. \\
{\ttfamily delivery} & {\ttfamily best effort} & No acknowledgement, retry or wait. A fragment the transport does not take ends that message; the host discards the incomplete stream (2000 ms idle, or the next first fragment of the same opcode and sequence). A lost fragment costs only that message and never slows reception. \\
{\ttfamily serial} & {\ttfamily non-blocking} & Fragments are queued without waiting for the host, as \texttt{RAW\_FRAME} is, so a stalled USB host cannot hold up the station. Nothing is queued while no USB host is connected. A message that fits one link message keeps its blocking write. \\
{\ttfamily fragment cap} & {\ttfamily 8 per message} & A transport that would need more than eight fragments (an ATT MTU that was never raised, 23) skips the message. \\
{\ttfamily raw capture on} & {\ttfamily large not sent} & While \texttt{RAW\_CAPTURE} is on the host reads \texttt{RAW\_FRAME}, so a message above 494 octets is left to that copy instead of being sent a second time. Messages up to 494 octets are still sent as \texttt{V\_2X\_RX}. \\
\end{longtable}}
A host that already reassembles fragmented messages (the revision 1 requirement, Section~\ref{sec:fragmentation-host}) needs no change. A host that handled only unfragmented \texttt{V\_2X\_RX} sees flags 1 to 3 on opcode 0x90 for the first time and must reassemble or ignore them. The wire format of every other message is unchanged.
\Needspace{5\baselineskip}\paragraph{Host decoding of the larger messages}
Roadside units also fill the messages out: a SPATEM names the intersection and each movement (\texttt{DescriptiveName}, IA5String of 1 to 63 characters) and gives each signal event a list of advisory speeds (greenwave, ecoDrive). A host decoder must read past these optional fields, not refuse the message. A decoder written against shorter messages and refusing them showed no signal state for the Berliner Tor unit, although every SPATEM had arrived and was in the host's log. The MicrOBU app reads past both since 2026-11-23.
\Needspace{8\baselineskip}\subsection{Fragmentation on the host side}\label{sec:fragmentation-host}
The MicrOBU host reassembles fragmented station-to-host messages as the fragmentation section of revision 1 states: fragments of one message share opcode and sequence, flags 1, 2 and 3 mark first, middle and last, each fragment body starts with total length and offset, a gap, a duplicate, a wrong order or a changed total drops the stream, an unfinished stream is discarded after 2000 ms, at most 8 streams are held, and a complete body is at most 65535 octets. A message that fits one link message (flags 0) passes through unchanged.
\Needspace{8\baselineskip}\subsection{Unsecured transmission}\label{sec:microbu-unsecured}
A BTP\_DATA\_REQUEST with \texttt{gn\_security\_profile} 0x01, or 0x00 while the station is configured with \texttt{security} 0, is transmitted without a signature instead of being refused. The station builds the GeoNetworking header itself from the last POTI\_UPDATE, so the same preconditions apply as for a signed request.
{\small\begin{longtable}{@{}P{45mm}P{55mm}P{72.8mm}@{}}
@@ -1190,19 +1216,19 @@ A BTP\_DATA\_REQUEST with \texttt{gn\_security\_profile} 0x01, or 0x00 while the
\Needspace{8\baselineskip}\subsection{Naming the MAC: the 16-octet STATION\_CONFIGURE}\label{sec:microbu-mac}
Revision 1 retires the long STATION\_CONFIGURE and defines only the 6-octet form. The station still decodes the long form, and the MicrOBU host uses it to choose the link-layer address: a rider's phone rotates the MAC with its pseudonym, and the bench CAM pinger keeps one fixed MAC so that its frames stay recognisable in a capture. A different MID is a different configuration, so the station is configured again (the radio keeps running).
{\small\begin{longtable}{F}
\hline\textbf{Offset} & \textbf{Field} & \textbf{Type} & \textbf{Unit / values} & \textbf{Description} \\hline\endfirsthead
\hline\textbf{Offset} & \textbf{Field} & \textbf{Type} & \textbf{Unit / values} & \textbf{Description} \\hline\endhead
\hline\textbf{Offset} & \textbf{Field} & \textbf{Type} & \textbf{Unit / values} & \textbf{Description} \\\hline\endfirsthead
\hline\textbf{Offset} & \textbf{Field} & \textbf{Type} & \textbf{Unit / values} & \textbf{Description} \\\hline\endhead
\hline\endfoot
{\ttfamily 0} & {\ttfamily station\_\allowbreak{}type} & {\ttfamily u8} & \textemdash & As in the 6-octet form. \
{\ttfamily 1} & {\ttfamily security} & {\ttfamily u8} & 0 or 1 & As in the 6-octet form. \
{\ttfamily 2} & {\ttfamily address\_\allowbreak{}configuration} & {\ttfamily u8} & 0=AUTO, 1=anonymous & 0 uses the MID below as the GN address MID and the 802.11 source address. \
{\ttfamily 3} & {\ttfamily mid} & {\ttfamily u8[6]} & \textemdash & The MAC (locally administered, unicast). Ignored when address\_configuration is 1. \
{\ttfamily 9} & {\ttfamily beaconing} & {\ttfamily u8} & 0 or 1 & As in the 6-octet form. \
{\ttfamily 10} & {\ttfamily channel\_\allowbreak{}number} & {\ttfamily u16} & \textemdash & As in the 6-octet form. \
{\ttfamily 12} & {\ttfamily transmit\_\allowbreak{}power\_\allowbreak{}dbm} & {\ttfamily u8} & dBm & As in the 6-octet form. \
{\ttfamily 13} & {\ttfamily radio} & {\ttfamily u8} & 0, 1 or 2 & 2 transmits and receives. \
{\ttfamily 14} & {\ttfamily default\_\allowbreak{}traffic\_\allowbreak{}class} & {\ttfamily u8} & raw GN octet & 2 (DP2). \
{\ttfamily 15} & {\ttfamily default\_\allowbreak{}lifetime} & {\ttfamily u8} & raw GN octet & 0x05 (1 s). \
{\ttfamily 0} & {\ttfamily station\_\allowbreak{}type} & {\ttfamily u8} & \textemdash & As in the 6-octet form. \\
{\ttfamily 1} & {\ttfamily security} & {\ttfamily u8} & 0 or 1 & As in the 6-octet form. \\
{\ttfamily 2} & {\ttfamily address\_\allowbreak{}configuration} & {\ttfamily u8} & 0=AUTO, 1=anonymous & 0 uses the MID below as the GN address MID and the 802.11 source address. \\
{\ttfamily 3} & {\ttfamily mid} & {\ttfamily u8[6]} & \textemdash & The MAC (locally administered, unicast). Ignored when address\_configuration is 1. \\
{\ttfamily 9} & {\ttfamily beaconing} & {\ttfamily u8} & 0 or 1 & As in the 6-octet form. \\
{\ttfamily 10} & {\ttfamily channel\_\allowbreak{}number} & {\ttfamily u16} & \textemdash & As in the 6-octet form. \\
{\ttfamily 12} & {\ttfamily transmit\_\allowbreak{}power\_\allowbreak{}dbm} & {\ttfamily u8} & dBm & As in the 6-octet form. \\
{\ttfamily 13} & {\ttfamily radio} & {\ttfamily u8} & 0, 1 or 2 & 2 transmits and receives. \\
{\ttfamily 14} & {\ttfamily default\_\allowbreak{}traffic\_\allowbreak{}class} & {\ttfamily u8} & raw GN octet & 2 (DP2). \\
{\ttfamily 15} & {\ttfamily default\_\allowbreak{}lifetime} & {\ttfamily u8} & raw GN octet & 0x05 (1 s). \\
\end{longtable}}
Checked on the bench (2026-11-11) with the station's own raw capture: a signed CAM sent with MID 02:aa:bb:cc:dd:01 left the radio from 802.11 source 02:aa:bb:cc:dd:01; the 6-octet form gave the ticket-derived address of the authorization ticket (4a:38:7a:4c:12:eb) when signed and a fresh random MAC per configuration when unsigned.
\Needspace{8\baselineskip}\subsection{Battery protection}\label{sec:microbu-battery}
@@ -1225,6 +1251,7 @@ MicrOBU extension. While no USB host is connected to the native port (the phone
\toprule\textbf{Revision} & \textbf{Date} & \textbf{Changes} \\\midrule\endhead
\bottomrule\endfoot
1 & 2026-11 & Niklas Dathe: the microbu-firmware interface reference, commit e4e4bd8. \\
2 & 2026-11-10 & MicrOBU additions: opcode 0x90 V2X\_RX (all heard ITS messages, unverified); unsecured transmission for security profile 0x01 and for profile 0x00 with \texttt{security} 0, from a random MAC per configuration, or the MAC named by the host in the 16-octet STATION\_CONFIGURE; the radio is polled from STATION\_CONFIGURE on; battery protection by deep sleep; no USB writes without a host. Wire format of revision 1 unchanged; the original is kept as microbu-firmware/docs/station-link.pdf. \\
2 & 2026-11-10 & MicrOBU additions: opcode 0x90 V2X\_RX (all heard ITS messages, unverified); unsecured transmission for security profile 0x01 and for profile 0x00 with \texttt{security} 0, from a random MAC per configuration, or the MAC named by the host in the 16-octet STATION\_CONFIGURE; V\_2X\_RX and RAW\_FRAME both kept, the host choosing (Section~\ref{sec:microbu-rxpaths}); the radio is polled from STATION\_CONFIGURE on; battery protection by deep sleep; no USB writes without a host. Wire format of revision 1 unchanged; the original is kept as microbu-firmware/docs/station-link.pdf. \\
3 & 2026-11-23 & \texttt{V\_2X\_RX} larger than 494 octets is fragmented, up to 2300 octets, best effort and non-blocking (Section~\ref{sec:microbu-v2xrx-frag}); revision 2 dropped it. Serial writes of fragments and of \texttt{RAW\_FRAME} are skipped while no USB host is connected. Found on the 2026-11-23 bench run against the Berliner Tor roadside unit (888-byte SPATEM, 1198-byte MAPEM); the findings are in docs/08-large-message-reception.md. Wire format of messages up to 494 octets unchanged. \\
\end{longtable}}
\end{document}
+7 -7
View File
@@ -52,13 +52,13 @@
// only this path). Other ports are dropped. The link message itself is generic: the port says what
// the payload is.
//
// Size caveat: a link message is at most 512 octets (link::maximum_message, which is also the
// largest GATT attribute value), so Station::forward_raw() drops a message whose UPER exceeds
// 494 bytes and counts it as oversize instead of forwarding it. Nothing is fragmented. The bench
// RSU's messages all fit (2026-10-28 capture: SPATEM 58, MAPEM 295 bytes); real road SPATEMs and
// MAPEMs often do not (SPATEM 555 bytes median, 1243 max on the 2026-03-18 drive). The radio
// itself captures frames of up to 2346 bytes (c5_radio.cpp), so `truncated` does not happen on
// this firmware.
// Size: a link message is at most 512 octets (link::maximum_message, which is also the largest
// GATT attribute value), so a UPER up to 494 bytes goes to the phone as one V2X_RX message. A larger
// one (real road SPATEMs and MAPEMs: SPATEM 555 bytes median, 1243 max on the 2026-03-18 drive;
// the 2026-11-23 bench node sent 888 and 1198) is sent by Station::forward_raw() in link fragments,
// see v2x_rx.hpp (v2x_rx_plan) and link_fragment.hpp. Only a message beyond v2x_rx_max_forward is
// dropped and counted as oversize. The radio itself captures frames of up to 2346 bytes
// (c5_radio.cpp), so `truncated` does not happen on this firmware.
//
// No FCS/CRC check here: the WiFi driver has already validated the frame.
typedef struct {
+53
View File
@@ -0,0 +1,53 @@
#pragma once
// Splits a link message body into fragments (station-link "Fragmented messages": the link header with
// flags 1 first / 2 middle / 3 last and the same opcode and sequence on every fragment, then
// u16 total body size, u16 body offset, data). Header-only and free of ESP-IDF, so the host tests compile it
// unmodified and check it against the app's reassembly. LinkService::send_fragmented is the only caller.
#include "link_protocol.hpp"
namespace microbu::link {
/// One fragment: the flags for the link header and the body (u16 total, u16 offset, data).
struct Fragment {
std::uint8_t flags;
Bytes body;
};
/// Largest body that goes out as one unfragmented message on a transport whose messages are at most `limit` octets.
constexpr std::size_t unfragmented_capacity(std::size_t limit) {
return limit > header_size ? limit - header_size : 0;
}
/// Data octets one fragment carries on a transport whose messages are at most `limit` octets.
constexpr std::size_t fragment_capacity(std::size_t limit) {
return limit > header_size + fragment_header_size ? limit - header_size - fragment_header_size : 0;
}
/// @brief Fragments `body`, which must not fit one message of `limit` octets (the caller sends those as they are).
/// @param body Message body to split.
/// @param limit Largest message the transport carries, header included (512, or the BLE ATT MTU - 3).
/// @param out Receives the fragments in order; empty when false is returned.
/// @param max_fragments Refuse when more fragments would be needed (a V2X_RX on a transport with a tiny MTU).
/// @return false when the body fits one message, exceeds 65535 octets, the limit leaves no room for data, or
/// more than max_fragments are needed.
inline bool split_fragments(const Bytes& body, std::size_t limit, std::vector<Fragment>& out,
std::size_t max_fragments = 65535) {
out.clear();
const std::size_t capacity = fragment_capacity(limit);
if (body.size() <= unfragmented_capacity(limit) || body.size() > 65535 || capacity == 0) return false;
if ((body.size() + capacity - 1) / capacity > max_fragments) return false;
for (std::size_t offset = 0; offset < body.size(); offset += capacity) {
const std::size_t n = body.size() - offset < capacity ? body.size() - offset : capacity;
Fragment fragment;
fragment.flags = offset == 0 ? flag_fragment_first
: offset + n == body.size() ? flag_fragment_last : flag_fragment_middle;
fragment.body = {static_cast<std::uint8_t>(body.size()), static_cast<std::uint8_t>(body.size() >> 8),
static_cast<std::uint8_t>(offset), static_cast<std::uint8_t>(offset >> 8)};
fragment.body.insert(fragment.body.end(), body.begin() + static_cast<std::ptrdiff_t>(offset),
body.begin() + static_cast<std::ptrdiff_t>(offset + n));
out.push_back(std::move(fragment));
}
return true;
}
} // namespace microbu::link
+21 -17
View File
@@ -1,4 +1,5 @@
#include "link_service.hpp"
#include "link_fragment.hpp"
#include "simple_ble.hpp"
#include "serial_link.hpp"
#include <esp_log.h>
@@ -19,7 +20,7 @@ LinkService::LinkService(Station& station) : station_(station) {
});
// MicrOBU: every ITS message heard on air, verified or not (Station::on_raw_its).
station_.on_raw_its([this](const link::Bytes& body) {
broadcast(link::Opcode::V2X_RX, ++own_sequence_, body);
return broadcast(link::Opcode::V2X_RX, ++own_sequence_, body);
});
// T_GenVam is included in the status snapshot returned on request.
station_.on_id_event([this](const link::IdChangeEvent& event) {
@@ -34,7 +35,11 @@ bool LinkService::send(LinkTransport transport, link::Opcode opcode, std::uint16
link::Message message {{opcode, flags, sequence}, body};
if (!link::encode(message, octets)) { ESP_LOGE(TAG, "message 0x%02x too long (%u)", unsigned(opcode), unsigned(body.size())); return false; }
if (transport == LinkTransport::serial) {
if (opcode == link::Opcode::RAW_FRAME) return serial::try_write(serial::FrameType::LINK, octets);
// Never wait for the host: RAW_FRAME and the fragments of a large V2X_RX are best effort, a stalled USB
// host must not hold the station task that also drains the radio queue. A V2X_RX that fits one message
// keeps the blocking write it always had.
if (opcode == link::Opcode::RAW_FRAME || (opcode == link::Opcode::V2X_RX && flags != 0))
return serial::try_write(serial::FrameType::LINK, octets);
return serial::write(serial::FrameType::LINK, octets);
}
return ble::write(octets);
@@ -42,26 +47,25 @@ bool LinkService::send(LinkTransport transport, link::Opcode opcode, std::uint16
bool LinkService::send_fragmented(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
const std::size_t limit = transport == LinkTransport::ble ? ble::max_message() : link::maximum_message;
const std::size_t chunk = limit - link::header_size;
if (body.size() <= chunk) return send(transport, opcode, sequence, body);
if (body.size() > 65535 || chunk <= link::fragment_header_size) return false;
const std::size_t capacity = chunk - link::fragment_header_size;
for (std::size_t offset = 0; offset < body.size(); offset += capacity) {
const std::size_t n = std::min(capacity, body.size() - offset);
const std::uint8_t flags = offset == 0 ? link::flag_fragment_first :
(offset + n == body.size() ? link::flag_fragment_last : link::flag_fragment_middle);
link::Bytes part {std::uint8_t(body.size()), std::uint8_t(body.size() >> 8),
std::uint8_t(offset), std::uint8_t(offset >> 8)};
part.insert(part.end(), body.begin() + offset, body.begin() + offset + n);
if (!send(transport, opcode, sequence, part, flags)) return false;
if (body.size() <= link::unfragmented_capacity(limit)) return send(transport, opcode, sequence, body);
// A received message is never worth a flood of notifications: with a small ATT MTU (no exchange yet, 23) one
// MAPEM would need dozens, so beyond max_received_fragments that transport skips the message.
const std::size_t max_fragments = opcode == link::Opcode::V2X_RX ? max_received_fragments : 65535;
std::vector<link::Fragment> fragments;
if (!link::split_fragments(body, limit, fragments, max_fragments)) return false;
for (const auto& fragment : fragments) {
// The first failed fragment ends this message (the app drops the incomplete stream by itself); nothing is
// retried, and nothing here waits for the transport.
if (!send(transport, opcode, sequence, fragment.body, fragment.flags)) return false;
}
return true;
}
void LinkService::broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
bool LinkService::broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) {
// Fragmented when needed: a MAPEM indication is larger than one message on either transport.
send_fragmented(LinkTransport::serial, opcode, sequence, body);
if (ble::connected()) send_fragmented(LinkTransport::ble, opcode, sequence, body);
const bool serial_taken = send_fragmented(LinkTransport::serial, opcode, sequence, body);
const bool ble_taken = ble::connected() && send_fragmented(LinkTransport::ble, opcode, sequence, body);
return serial_taken || ble_taken;
}
void LinkService::reply(LinkTransport transport, std::uint16_t sequence, link::Code code, const link::Bytes& detail) {
+4 -1
View File
@@ -38,7 +38,10 @@ private:
/// @param opcode Message opcode.
/// @param sequence Sequence number to stamp on the header.
/// @param body Encoded message body.
void broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body);
/// @return whether at least one transport took the whole message (the caller only counts a false).
bool broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body);
/// Most fragments one received ITS message (V2X_RX) may take on a transport; 8 x 504 octets at the full MTU.
static constexpr std::size_t max_received_fragments = 8;
/// @brief Sends a CONFIRM reply to the message's origin transport.
/// @param origin Transport to reply on.
/// @param sequence Sequence number of the message being replied to.
+3
View File
@@ -162,6 +162,9 @@ bool write(FrameType type, const Bytes& payload) {
bool try_write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock || stalled) return false;
// Like write(): no host on the native port means nothing to queue, or the 8 kB TX buffer fills with
// fragments nobody reads and the next host starts on stale bytes.
if (!usb_serial_jtag_is_connected()) return false;
const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, 0) != pdTRUE) return false;
const bool queued = usb_serial_jtag_write_bytes(frame.data(), frame.size(), 0) == static_cast<int>(frame.size());
+21 -13
View File
@@ -644,20 +644,28 @@ void Station::forward_raw(const ByteBuffer& frame, int rssi) {
// Most captured frames are not ITS traffic this handles; false is the common case, not an error.
gn_rx_t rx;
if (!gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx)) return;
const bool fits = link::v2x_rx_fits(rx);
if (!fits) {
++raw_oversize_;
static std::int64_t last_report = 0; // one line per 10 s at most, the counter has the rest
const auto now = esp_timer_get_time();
if (now - last_report > 10000000) {
last_report = now;
ESP_LOGW(TAG, "V2X_RX: port %u message of %d bytes does not fit a link message (%lu dropped so far)",
unsigned(rx.btp_dest_port), rx.payload_len, (unsigned long)raw_oversize_);
}
return;
const auto plan = link::v2x_rx_plan(rx, (raw_mode_ & C5Radio::capture_on) != 0);
// A message above one link message goes out in fragments (LinkService), best effort: no retry, no waiting, so
// a lost fragment costs that message only and never the receive path.
switch (plan) {
case link::V2xRxPlan::drop: ++raw_oversize_; break;
case link::V2xRxPlan::covered_by_raw: ++raw_covered_; break;
case link::V2xRxPlan::single: ++raw_forwarded_; break;
case link::V2xRxPlan::fragmented: ++raw_fragmented_; break;
}
if (plan == link::V2xRxPlan::single || plan == link::V2xRxPlan::fragmented) {
if (!raw_its_(link::encode_v2x_rx(rx, rssi)) && plan == link::V2xRxPlan::fragmented) ++raw_fragment_failed_;
}
if (plan == link::V2xRxPlan::single || plan == link::V2xRxPlan::covered_by_raw) return;
static std::int64_t last_report = 0; // one line per 10 s at most, the counters have the rest
const auto now = esp_timer_get_time();
if (now - last_report > 10000000) {
last_report = now;
ESP_LOGW(TAG, "V2X_RX: port %u message of %d bytes: %lu fragmented (%lu not taken by any transport), "
"%lu dropped as unusable or over %u bytes",
unsigned(rx.btp_dest_port), rx.payload_len, (unsigned long)raw_fragmented_,
(unsigned long)raw_fragment_failed_, (unsigned long)raw_oversize_, unsigned(link::v2x_rx_max_forward));
}
++raw_forwarded_;
raw_its_(link::encode_v2x_rx(rx, rssi));
}
link::Code Station::unsecured_request(const link::BtpDataRequest& q) {
+6 -3
View File
@@ -30,8 +30,9 @@ public:
using Received = std::function<void()>;
/// RAW_FRAME body (u32 counter, u8 flags, i8 RSSI, ITS5 record) for the link service.
using RawFrame = std::function<void(const link::Bytes&)>;
/// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp).
using RawIts = std::function<void(const link::Bytes&)>;
/// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp). Returns whether a transport took it;
/// a body above one link message goes out in fragments, best effort (a false return is only counted).
using RawIts = std::function<bool(const link::Bytes&)>;
/// DCC_T_GEN_VAM body for the link service (TS 103 300-3 clause 6.2: T_GenVam from management).
using DccUpdate = std::function<void(const link::Bytes&)>;
@@ -283,7 +284,9 @@ private:
bool have_fix_ = false;
link::PotiUpdate last_poti_; // MicrOBU: the GN Source Position Vector of unsecured_request()
std::uint8_t unsecured_mid_[6] = {2, 0, 0, 0, 0, 1}; // MicrOBU: random per configure(); MAC of unsecured frames
std::uint32_t raw_forwarded_ = 0, raw_oversize_ = 0;
// MicrOBU V2X_RX: forwarded in one message, forwarded in fragments (and how many of those no transport took),
// dropped as unusable or beyond v2x_rx_max_forward, and large ones left to the RAW_FRAME copy.
std::uint32_t raw_forwarded_ = 0, raw_fragmented_ = 0, raw_fragment_failed_ = 0, raw_oversize_ = 0, raw_covered_ = 0;
// declared before everything that refers to its keys (security_, pki_pending_), so it is destroyed last
std::unique_ptr<microbu_v2x::security::SecurityModule> module_;
std::unique_ptr<vanetza::ManualRuntime> runtime_;
+22
View File
@@ -14,11 +14,33 @@ constexpr std::size_t v2x_rx_prefix = 14;
/// Largest ITS payload that fits one link message (512 - 4 - 14).
constexpr std::size_t v2x_rx_max_payload = maximum_message - header_size - v2x_rx_prefix;
/// Largest ITS payload forwarded at all (fragmented when it exceeds v2x_rx_max_payload): what one 802.11 frame
/// of the radio's 2346-octet buffer can hold. Real road SPATEMs and MAPEMs reach about 1.3 kB.
constexpr std::size_t v2x_rx_max_forward = 2300;
/// @brief Whether an unwrapped message fits one link message. A truncated or empty one never does.
inline bool v2x_rx_fits(const gn_rx_t& rx) {
return !rx.truncated && rx.payload_len > 0 && static_cast<std::size_t>(rx.payload_len) <= v2x_rx_max_payload;
}
/// What Station::forward_raw does with an unwrapped message.
enum class V2xRxPlan {
drop, ///< truncated, empty or beyond v2x_rx_max_forward: counted as oversize, not sent
single, ///< one link message, exactly as before the fragmentation was added
fragmented, ///< larger than one link message: sent in fragments, best effort
covered_by_raw, ///< larger than one link message while the raw capture is on: the RAW_FRAME copy carries it
};
/// @brief Decides how an unwrapped message goes to the phone.
/// @param raw_capture_on The phone switched RAW_CAPTURE on, so it reads RAW_FRAME and ignores V2X_RX; a large
/// message is then not sent a second time as fragmented V2X_RX (small ones still are, as before).
inline V2xRxPlan v2x_rx_plan(const gn_rx_t& rx, bool raw_capture_on) {
if (rx.truncated || rx.payload_len <= 0 || static_cast<std::size_t>(rx.payload_len) > v2x_rx_max_forward)
return V2xRxPlan::drop;
if (v2x_rx_fits(rx)) return V2xRxPlan::single;
return raw_capture_on ? V2xRxPlan::covered_by_raw : V2xRxPlan::fragmented;
}
/// @brief Builds the V2X_RX body. The caller checks v2x_rx_fits first.
/// @param rx Message unwrapped by gn_unwrap_its (its payload pointer must still be valid).
/// @param rssi Received signal strength, dBm.
+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,111 @@
# 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 {
$ErrorActionPreference = "Continue" # see Test-Import
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 }
# Under "Stop", Windows PowerShell 5.1 turns a native command's redirected stderr into a terminating error, so the traceback of
# a missing module would end the script instead of leading to the install.
function Test-Import($py, $module) {
$ErrorActionPreference = "Continue"
Run-Python $py @("-c", "import $module") 2>$null | Out-Null
return ($LASTEXITCODE -eq 0)
}
# ---- 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"))) {
$have = Test-Import $py $pair[1]
if (-not $have -and -not $CheckOnly) { Run-Python $py @("-m", "pip", "install", "--user", $pair[0]); $have = Test-Import $py $pair[1] }
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([uint32]2147483649) # 0x80000001 = ES_CONTINUOUS | ES_SYSTEM_REQUIRED (PowerShell 5.1 reads that literal as a negative int)
# 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
+30 -2
View File
@@ -27,11 +27,11 @@ CFLAGS = -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW) -I. \
FW_SRCS = $(FW)/geonet.c dot11p.c $(FW)/gn_unwrap.c
DEPS = test_util.c test_util.h dot11p.h $(FW_SRCS) $(wildcard $(FW)/*.h)
.PHONY: all check chain replay fuzz battery firmware clean
.PHONY: all check chain replay fuzz battery firmware fragments corpus clean
all: check
check: chain replay fuzz battery firmware
check: chain replay fuzz battery firmware fragments
$(BUILD):
mkdir -p $@
@@ -82,3 +82,31 @@ $(BUILD)/test_firmware$(EXE): test_firmware.cpp $(FW_CXX_SRCS) $(wildcard $(FW)/
firmware: $(BUILD)/test_firmware$(EXE)
$(BUILD)/test_firmware$(EXE)
# Recorded traffic through unwrap -> V2X_RX body -> fragments -> reassembly (the large MAPEMs and SPATEMs of a road RSU).
# Needs a capture: the CiT node's 2026-11-23 recording has 1198-byte MAPEMs and 888-byte SPATEMs.
FRAG_PCAPS = $(wildcard ../../../databases/its5_20261123_150746.pcap) $(RECORDINGS)
$(BUILD)/fw_c_test_util.o: test_util.c test_util.h | $(BUILD)
$(CC) $(CFLAGS) -c -o $@ $<
$(BUILD)/test_v2x_fragments$(EXE): test_v2x_fragments.cpp $(BUILD)/fw_c_test_util.o $(BUILD)/fw_c_gn_unwrap.o $(FW)/link_protocol.cpp $(wildcard $(FW)/*.hpp) | $(BUILD)
$(CXX) $(CXXFLAGS) -std=c++20 -I. -fsanitize=undefined -fsanitize-undefined-trap-on-error -o $@ test_v2x_fragments.cpp $(FW)/link_protocol.cpp $(BUILD)/fw_c_test_util.o $(BUILD)/fw_c_gn_unwrap.o
fragments: $(BUILD)/test_v2x_fragments$(EXE)
ifeq ($(FRAG_PCAPS),)
@echo "fragments: no captures, skipped"
else
$(BUILD)/test_v2x_fragments$(EXE) $(FRAG_PCAPS)
endif
# Corpus for the app's GnUnwrapTest (the Kotlin port of gn_unwrap.c): recorded frames, cut and corrupted copies of
# them, with the verdict and fields of the firmware's own code. Writes ../../../app/src/test/resources/gn_unwrap_corpus.tsv
CORPUS_OUT = ../../../app/src/test/resources/gn_unwrap_corpus.tsv
$(BUILD)/dump_corpus$(EXE): dump_corpus.c test_util.c test_util.h $(FW)/gn_unwrap.c $(FW)/gn_unwrap.h | $(BUILD)
$(CC) $(CFLAGS) -o $@ dump_corpus.c test_util.c $(FW)/gn_unwrap.c
corpus: $(BUILD)/dump_corpus$(EXE)
mkdir -p $(dir $(CORPUS_OUT))
$(BUILD)/dump_corpus$(EXE) $(CORPUS_OUT) $(RECORDINGS)
+3 -1
View File
@@ -4,9 +4,11 @@
results under "Running". Toolchain: MSYS2 UCRT64 gcc, Option B below (chosen and
installed 2026-09-11).
**Corpus for the app (`make corpus`, `dump_corpus.c`):** runs the firmware's `gn_unwrap_its` on frames from the recorded captures, copies of them cut at several lengths and copies with flipped bytes, and writes the verdict and fields of each to `app/src/test/resources/gn_unwrap_corpus.tsv`. The app's `GnUnwrapTest` requires its Kotlin port of `gn_unwrap.c` (used for the raw frame receive path) to match every line.
**Firmware unit tests (`make firmware`, `test_firmware.cpp`, 40 tests):** the station-link codec byte-exact against
the app's `StationLinkTest` hex, the 131-octet STATUS offsets, request reassembly, the V2X_RX extension
(`main/v2x_rx.hpp`; the 494-octet limit, the 14-octet prefix, TX code -> air frame -> RX path), radio operating
(`main/v2x_rx.hpp`; the 494-octet limit, the 14-octet prefix, TX code -> air frame -> RX path; the plan for large messages and `link_fragment.hpp`'s fragments, round-tripped through two reassemblers), radio operating
points, the BLE TX guard, the ITS clock, CCA counters, BLE security and the battery policy. It prints PASS or FAIL
per test and a `RESULT:` line, and exits non-zero on a failure. It cannot test the radio, BLE, NVS or USB: those are
on the bench list in `TODO.md`.
+96
View File
@@ -0,0 +1,96 @@
// Writes a corpus for the app's GnUnwrapTest: frames from recorded captures, cut and corrupted copies of
// them, and what gn_unwrap_its (the firmware's own code) makes of each. The Kotlin port must give the
// same verdict and the same fields for every line.
//
// dump_corpus <out.tsv> <capture.pcap>...
//
// One line per frame, tab separated:
// frame hex | A (accepted) or R (rejected) | port | flags (bit 0 GBC area, bit 1 signed) |
// area lat | area lon | area distance A | truncated 0/1 | payload hex (empty when rejected)
//
// Selection is deterministic (fixed counts per category and a fixed-seed generator), so the file is
// reproducible. Build and run: `make corpus` in this folder.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gn_unwrap.h"
#include "test_util.h"
#define MAX_PER_CATEGORY 20
#define MAX_REJECTED 60
#define MAX_MUTATED 250
static FILE *out;
static unsigned rng_state = 12345u;
static int accepted_total, rejected_total, mutated_total, cut_total;
static int category_count[5 * 2 * 2 + 5]; // port index * 4 + signed * 2 + gbc
static int seen_accepted;
static unsigned rng(void) { rng_state = rng_state * 1664525u + 1013904223u; return rng_state >> 8; }
static int port_index(int port) {
switch (port) { case 2001: return 0; case 2002: return 1; case 2003: return 2; case 2004: return 3; default: return 4; }
}
static void emit(const uint8_t *frame, int len) {
gn_rx_t rx;
const bool ok = gn_unwrap_its(frame, len, &rx);
for (int i = 0; i < len; i++) fprintf(out, "%02x", frame[i]);
if (!ok) { fprintf(out, "\tR\t0\t0\t0\t0\t0\t0\t\n"); return; }
fprintf(out, "\tA\t%u\t%d\t%d\t%d\t%u\t%d\t", rx.btp_dest_port, (rx.has_geo_area ? 1 : 0) | (rx.signed_unverified ? 2 : 0),
(int)rx.geo_area_lat_tenmicrodeg, (int)rx.geo_area_lon_tenmicrodeg, (unsigned)rx.geo_area_distance_a_m,
rx.truncated ? 1 : 0);
for (int i = 0; i < rx.payload_len; i++) fprintf(out, "%02x", rx.payload[i]);
fprintf(out, "\n");
}
static void on_frame(const uint8_t *frame, int len, int index, void *ctx) {
(void)ctx; (void)index;
gn_rx_t rx;
if (!gn_unwrap_its(frame, len, &rx)) {
if (rejected_total < MAX_REJECTED && (rng() % 7) == 0) { emit(frame, len); ++rejected_total; }
return;
}
++seen_accepted;
const int cat = port_index(rx.btp_dest_port) * 4 + (rx.signed_unverified ? 2 : 0) + (rx.has_geo_area ? 1 : 0);
if (category_count[cat] < MAX_PER_CATEGORY) {
++category_count[cat];
emit(frame, len);
++accepted_total;
// a few cut copies: the frame ends inside the payload, inside the headers, and at odd places
const int cuts[] = {len - 3, len - 17, len / 2, len / 3, 40, 70};
for (unsigned c = 0; c < sizeof cuts / sizeof cuts[0]; c++)
if (cuts[c] > 0 && cuts[c] < len && (rng() % 3) == 0) { emit(frame, cuts[c]); ++cut_total; }
}
// corrupted copies of frames taken at a steady rate: a few flipped bytes, anywhere
if (mutated_total < MAX_MUTATED && (seen_accepted % 40) == 0) {
uint8_t *copy = malloc((size_t)len);
if (!copy) return;
memcpy(copy, frame, (size_t)len);
const int flips = 1 + (int)(rng() % 4);
for (int k = 0; k < flips; k++) copy[rng() % (unsigned)len] ^= (uint8_t)(1u << (rng() % 8));
emit(copy, len);
free(copy);
++mutated_total;
}
}
int main(int argc, char **argv) {
if (argc < 3) { fprintf(stderr, "usage: dump_corpus <out.tsv> <capture.pcap>...\n"); return 2; }
out = fopen(argv[1], "w");
if (!out) { perror(argv[1]); return 2; }
for (int i = 2; i < argc; i++) {
const int n = tu_pcap_foreach(argv[i], on_frame, NULL);
if (n < 0) { fprintf(stderr, "cannot read %s\n", argv[i]); return 2; }
}
fclose(out);
printf("corpus: %d accepted, %d cut, %d corrupted, %d rejected (of %d accepted frames seen)\n", accepted_total, cut_total,
mutated_total, rejected_total, seen_accepted);
for (int p = 0; p < 5; p++)
printf(" port index %d: unsigned SHB %d, unsigned GBC %d, signed SHB %d, signed GBC %d\n", p, category_count[p * 4],
category_count[p * 4 + 1], category_count[p * 4 + 2], category_count[p * 4 + 3]);
return 0;
}
+120
View File
@@ -9,6 +9,7 @@
#include "battery_policy.hpp"
#include "cca_window.hpp"
#include "its_clock.hpp"
#include "link_fragment.hpp"
#include "link_protocol.hpp"
#include "radio_policy.hpp"
#include "raw_capture_policy.hpp"
@@ -369,6 +370,125 @@ TEST(the_494_octet_limit_is_exact) {
}
}
TEST(v2x_rx_plan_keeps_small_messages_single_and_fragments_large_ones) {
gn_rx_t rx {};
const std::uint8_t byte = 0;
rx.payload = &byte;
const auto plan = [&](int len, bool raw_on, bool truncated = false) {
rx.payload_len = len; rx.truncated = truncated;
return link::v2x_rx_plan(rx, raw_on);
};
using P = link::V2xRxPlan;
CHECK(plan(1, false) == P::single);
CHECK(plan(58, false) == P::single);
CHECK(plan(494, false) == P::single);
CHECK(plan(495, false) == P::fragmented);
CHECK(plan(888, false) == P::fragmented);
CHECK(plan(1198, false) == P::fragmented);
CHECK(plan(2300, false) == P::fragmented);
CHECK(plan(2301, false) == P::drop);
CHECK(plan(0, false) == P::drop);
CHECK(plan(-1, false) == P::drop);
CHECK(plan(600, false, true) == P::drop); // truncated is never forwarded
// raw capture on: the app reads RAW_FRAME, so a large message is not sent twice; small ones are as before
CHECK(plan(494, true) == P::single);
CHECK(plan(495, true) == P::covered_by_raw);
CHECK(plan(1198, true) == P::covered_by_raw);
CHECK(plan(2301, true) == P::drop);
}
// What a phone does with the fragments, written here without link::RequestReassembly.
static bool put_back(const std::vector<link::Fragment>& fragments, Bytes& out) {
out.clear();
std::size_t total = 0;
for (std::size_t i = 0; i < fragments.size(); ++i) {
const auto& b = fragments[i].body;
if (b.size() <= link::fragment_header_size) return false;
const std::size_t t = b[0] | (std::size_t(b[1]) << 8), offset = b[2] | (std::size_t(b[3]) << 8);
if (fragments[i].flags != (i == 0 ? 1 : i + 1 == fragments.size() ? 3 : 2)) return false;
if (i == 0) total = t;
if (t != total || offset != out.size()) return false;
out.insert(out.end(), b.begin() + link::fragment_header_size, b.end());
}
return out.size() == total;
}
TEST(fragments_of_a_large_v2x_rx_reassemble_exactly_on_both_transports) {
for (const int len : {495, 504, 888, 1198, 2300}) {
Bytes mapem(len);
for (std::size_t i = 0; i < mapem.size(); ++i) mapem[i] = static_cast<std::uint8_t>(i * 31 + len);
Bytes frame;
CHECK(air_frame(mapem, 2003, frame));
gn_rx_t rx;
CHECK(gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx));
CHECK_EQ(rx.payload_len, len);
const auto body = link::encode_v2x_rx(rx, -48);
for (const std::size_t limit : {std::size_t(512), std::size_t(244)}) { // serial / MTU 517, MTU 247
std::vector<link::Fragment> fragments;
const bool split = link::split_fragments(body, limit, fragments, 16);
CHECK(split);
if (!split) continue;
CHECK(fragments.size() >= 2);
Bytes rebuilt;
CHECK(put_back(fragments, rebuilt));
CHECK(rebuilt == body);
for (std::size_t i = 0; i < fragments.size(); ++i) {
Bytes wire;
CHECK(link::encode(link::Message {{link::Opcode::V2X_RX, fragments[i].flags, 5}, fragments[i].body}, wire));
CHECK(wire.size() <= limit);
if (i + 1 < fragments.size()) CHECK_EQ(wire.size(), limit); // full except the last
}
}
}
}
TEST(fragment_counts_for_the_bench_messages_at_the_full_mtu) {
// 14 octets of prefix + the UPER payload; a fragment carries 512 - 4 - 4 = 504 octets of it
std::vector<link::Fragment> f;
CHECK(link::split_fragments(Bytes(14 + 888), 512, f)); CHECK_EQ(f.size(), 2u);
CHECK(link::split_fragments(Bytes(14 + 1198), 512, f)); CHECK_EQ(f.size(), 3u);
CHECK(link::split_fragments(Bytes(14 + 495), 512, f)); CHECK_EQ(f.size(), 2u);
CHECK_STR(to_hex(Bytes(f[0].body.begin(), f[0].body.begin() + 4)), std::string("fd010000")); // total 509, offset 0
CHECK_STR(to_hex(Bytes(f[1].body.begin(), f[1].body.begin() + 4)), std::string("fd01f801")); // total 509, offset 504
}
TEST(a_message_that_fits_one_link_message_is_never_fragmented) {
std::vector<link::Fragment> f;
CHECK(!link::split_fragments(Bytes(508), 512, f)); // 508 + 4 = 512: exactly one message
CHECK(f.empty());
CHECK(link::split_fragments(Bytes(509), 512, f));
CHECK(!link::split_fragments(Bytes(240), 244, f)); // MTU 247: 240 + 4 = 244
CHECK(link::split_fragments(Bytes(241), 244, f));
}
TEST(fragmenting_refuses_what_a_transport_cannot_carry_sensibly) {
std::vector<link::Fragment> f;
CHECK(!link::split_fragments(Bytes(1212), 20, f, 8)); // ATT MTU 23: 12 octets a fragment, 101 fragments
CHECK(f.empty());
CHECK(!link::split_fragments(Bytes(1212), 8, f)); // no room for data at all
CHECK(!link::split_fragments(Bytes(65536), 512, f)); // total is a u16
CHECK(link::split_fragments(Bytes(65535), 512, f));
CHECK(link::split_fragments(Bytes(1212), 244, f, 6)); // exactly 6 fragments of 236
CHECK(!link::split_fragments(Bytes(1212), 244, f, 5));
}
TEST(a_lost_fragment_loses_that_message_only) {
std::vector<link::Fragment> a, b;
Bytes first(1212, 0xA1), second(1212, 0xB2);
CHECK(link::split_fragments(first, 512, a));
CHECK(link::split_fragments(second, 512, b));
link::RequestReassembly phone;
std::optional<link::Message> done;
for (std::size_t i = 0; i < a.size(); ++i) {
if (i == 1) continue; // the middle fragment never arrives
done = phone.feed(link::Message {{link::Opcode::V2X_RX, a[i].flags, 1}, a[i].body}, 1, i);
CHECK(!done);
}
for (std::size_t i = 0; i < b.size(); ++i) done = phone.feed(link::Message {{link::Opcode::V2X_RX, b[i].flags, 2}, b[i].body}, 1, 10 + i);
CHECK(done.has_value());
if (done) CHECK(done->body == second);
}
TEST(ports_outside_the_its_set_are_not_forwarded) {
Bytes frame;
CHECK(air_frame(Bytes(20, 1), 1234, frame));
@@ -0,0 +1,171 @@
// Replays recorded air traffic through the whole V2X_RX send path that needs no ESP32: gn_unwrap_its ->
// v2x_rx_plan -> encode_v2x_rx -> split_fragments -> link::encode of every fragment -> reassembly, and checks
// that what a phone would reassemble is byte for byte the body that was sent. Messages that fit one link message
// must stay one message and be byte-identical to the unfragmented encoding.
//
// Usage: test_v2x_fragments capture.pcap [capture.pcap ...]
//
// The reassembly here is written independently of link::RequestReassembly (which is also run, for bodies it
// accepts) and of the app's Kotlin LinkReassembly (checked by LinkReassemblyTest on the same fragments).
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <vector>
extern "C" {
#include "gn_unwrap.h"
#include "test_util.h"
}
#include "link_fragment.hpp"
#include "request_reassembly.hpp"
#include "v2x_rx.hpp"
using namespace microbu;
using link::Bytes;
namespace {
constexpr int rx_frame_max_len = 2346; // c5_radio.cpp's Raw::bytes, as in test_replay.c
struct Stats {
long records = 0, accepted = 0, single = 0, fragmented = 0, dropped = 0, fragments = 0, failures = 0;
std::map<std::pair<unsigned, std::size_t>, long> by_port_size;
};
FILE* dump = nullptr; // --dump out.tsv
std::set<std::pair<unsigned, std::size_t>> dumped;
bool fail(Stats& s, const char* what, int index) {
std::fprintf(stderr, "FAIL record %d: %s\n", index, what);
++s.failures;
return false;
}
// What a phone does with the link messages of one body: independent of every other reassembler.
bool reassemble(const std::vector<link::Message>& messages, Bytes& out) {
out.clear();
std::size_t total = 0;
for (std::size_t i = 0; i < messages.size(); ++i) {
const auto& m = messages[i];
const auto& b = m.body;
if (b.size() <= link::fragment_header_size) return false;
const std::size_t t = b[0] | (std::size_t(b[1]) << 8), offset = b[2] | (std::size_t(b[3]) << 8);
const std::uint8_t want = i == 0 ? 1 : (i + 1 == messages.size() ? 3 : 2);
if (m.header.flags != want || m.header.opcode != link::Opcode::V2X_RX) return false;
if (i == 0) total = t;
if (t != total || offset != out.size()) return false;
out.insert(out.end(), b.begin() + link::fragment_header_size, b.end());
}
return out.size() == total;
}
void check(Stats& s, const gn_rx_t& rx, int index) {
++s.accepted;
const auto plan = link::v2x_rx_plan(rx, false);
if (link::v2x_rx_plan(rx, true) == link::V2xRxPlan::fragmented) { fail(s, "raw capture on still fragments", index); return; }
if (plan == link::V2xRxPlan::drop) { ++s.dropped; return; }
const Bytes body = link::encode_v2x_rx(rx, -60);
if (body.size() != link::v2x_rx_prefix + static_cast<std::size_t>(rx.payload_len)) { fail(s, "body size", index); return; }
++s.by_port_size[{rx.btp_dest_port, static_cast<std::size_t>(rx.payload_len)}];
if (plan == link::V2xRxPlan::single) {
++s.single;
std::vector<link::Fragment> none;
Bytes wire;
if (link::split_fragments(body, link::maximum_message, none)) { fail(s, "a single message was fragmented", index); return; }
if (!link::encode(link::Message {{link::Opcode::V2X_RX, 0, 7}, body}, wire) || wire.size() != body.size() + link::header_size)
fail(s, "single message does not encode", index);
return;
}
++s.fragmented;
if (dump && dumped.insert({rx.btp_dest_port, static_cast<std::size_t>(rx.payload_len)}).second) {
// For the app's LinkReassemblyTest: the first message of each large size, its body and the link messages
// (hex) both transports would carry. `port size limit body wire wire ...`
for (const std::size_t limit : {std::size_t(512), std::size_t(244)}) {
std::vector<link::Fragment> fragments;
if (!link::split_fragments(body, limit, fragments, 8)) continue;
std::fprintf(dump, "%u\t%d\t%zu\t", rx.btp_dest_port, rx.payload_len, limit);
for (const auto b : body) std::fprintf(dump, "%02x", b);
for (const auto& f : fragments) {
Bytes wire;
link::encode(link::Message {{link::Opcode::V2X_RX, f.flags, 77}, f.body}, wire);
std::fputc('\t', dump);
for (const auto b : wire) std::fprintf(dump, "%02x", b);
}
std::fputc('\n', dump);
}
}
// 512: serial and the full BLE MTU 517. 244: ATT MTU 247. Both must carry the message; 20 (MTU 23) must refuse it.
for (const std::size_t limit : {std::size_t(512), std::size_t(244)}) {
std::vector<link::Fragment> fragments;
if (!link::split_fragments(body, limit, fragments, 8)) { fail(s, "split refused", index); return; }
std::vector<link::Message> messages;
link::RequestReassembly oracle;
std::optional<link::Message> done;
for (std::size_t i = 0; i < fragments.size(); ++i) {
link::Message m {{link::Opcode::V2X_RX, fragments[i].flags, 9}, fragments[i].body};
Bytes wire;
if (!link::encode(m, wire) || wire.size() > limit) { fail(s, "fragment exceeds the transport limit", index); return; }
link::Message back;
if (!link::decode(wire, back)) { fail(s, "fragment does not decode", index); return; }
messages.push_back(back);
done = oracle.feed(back, 0, i);
++s.fragments;
}
Bytes rebuilt;
if (!reassemble(messages, rebuilt) || rebuilt != body) { fail(s, "independent reassembly differs", index); return; }
if (body.size() <= link::maximum_request_body && (!done || done->body != body)) { fail(s, "RequestReassembly differs", index); return; }
// One fragment lost anywhere but at the end, then the next message: nothing completes, nothing is poisoned.
if (fragments.size() > 2) {
link::RequestReassembly lossy;
for (std::size_t i = 0; i < fragments.size(); ++i) {
if (i == 1) continue;
const auto got = lossy.feed(link::Message {{link::Opcode::V2X_RX, fragments[i].flags, 9}, fragments[i].body}, 0, i);
if (got) { fail(s, "a message with a lost fragment completed", index); return; }
}
if (body.size() <= link::maximum_request_body) {
std::optional<link::Message> next;
for (std::size_t i = 0; i < fragments.size(); ++i)
next = lossy.feed(link::Message {{link::Opcode::V2X_RX, fragments[i].flags, 10}, fragments[i].body}, 0, 100 + i);
if (!next || next->body != body) { fail(s, "the message after a lost fragment did not complete", index); return; }
}
}
}
std::vector<link::Fragment> too_small;
if (link::split_fragments(body, 20, too_small, 8)) fail(s, "MTU 23 should skip a large message", index);
}
} // namespace
int main(int argc, char** argv) {
int first = 1;
if (argc > 2 && std::strcmp(argv[1], "--dump") == 0) {
dump = std::fopen(argv[2], "w");
if (!dump) { std::fprintf(stderr, "cannot write %s\n", argv[2]); return 2; }
first = 3;
}
if (argc <= first) { std::fprintf(stderr, "usage: test_v2x_fragments [--dump out.tsv] capture.pcap [capture.pcap ...]\n"); return 2; }
tu_install_crash_handler();
tu_guard_init();
Stats stats;
for (int a = first; a < argc; ++a) {
struct Ctx { Stats* s; const char* path; } ctx {&stats, argv[a]};
const int n = tu_pcap_foreach(argv[a], [](const uint8_t* frame, int len, int index, void* c) {
auto* x = static_cast<Ctx*>(c);
++x->s->records;
if (len > rx_frame_max_len) len = rx_frame_max_len;
tu_set_context("fragments %s record %d (%d bytes)", x->path, index, len);
gn_rx_t rx;
if (gn_unwrap_its(tu_guarded(frame, len), len, &rx)) check(*x->s, rx, index);
}, &ctx);
if (n < 0) { std::fprintf(stderr, "cannot read %s as a pcap\n", argv[a]); return 2; }
}
std::printf("test_v2x_fragments: %ld records, %ld accepted: %ld single, %ld fragmented (%ld fragments built for "
"two transports), %ld dropped, %ld failures\n",
stats.records, stats.accepted, stats.single, stats.fragmented, stats.fragments, stats.dropped, stats.failures);
for (const auto& [key, count] : stats.by_port_size)
if (key.second > link::v2x_rx_max_payload) std::printf(" port %u, %zu bytes: %ld\n", key.first, key.second, count);
return stats.failures ? 1 : 0;
}
@@ -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,555 @@
02:39:52 make clean; make check (chain, replay with asn1tools, fuzz, battery, firmware unit tests, fragments)
02:40:18 make check passed
02:40:18 test_chain: 4627 checks, 0 failed
02:40:18 fuzz_gn_unwrap: 2000000 iterations from 2 seed frames, 671348 accepted (0 signed, 70963 truncated), no crash
02:40:18 PASS garbage_is_ignored_without_crashing
02:40:18 46 passed, 0 failed, 0 checks failed
02:40:18 RESULT: PASS
02:40:18 test_v2x_fragments: 27367 records, 27366 accepted: 22255 single, 5111 fragmented (35847 fragments built for two transports), 0 dropped, 0 failures
02:40:18 fuzz seed 101, 200000000 iterations
02:41:35 FUZZ FAILURE with seed 101 (exit 0): see fuzz-101.log, which lists the input as hex
02:41:35 fuzz seed 102, 200000000 iterations
02:42:51 FUZZ FAILURE with seed 102 (exit 0): see fuzz-102.log, which lists the input as hex
02:42:51 fuzz seed 103, 200000000 iterations
02:44:08 FUZZ FAILURE with seed 103 (exit 0): see fuzz-103.log, which lists the input as hex
02:44:08 fuzz seed 104, 200000000 iterations
02:45:25 FUZZ FAILURE with seed 104 (exit 0): see fuzz-104.log, which lists the input as hex
02:45:25 fuzz seed 105, 200000000 iterations
02:46:42 FUZZ FAILURE with seed 105 (exit 0): see fuzz-105.log, which lists the input as hex
02:46:42 fuzz seed 106, 200000000 iterations
02:47:58 FUZZ FAILURE with seed 106 (exit 0): see fuzz-106.log, which lists the input as hex
02:47:58 fuzz seed 107, 200000000 iterations
02:49:15 FUZZ FAILURE with seed 107 (exit 0): see fuzz-107.log, which lists the input as hex
02:49:15 fuzz seed 108, 200000000 iterations
02:50:32 FUZZ FAILURE with seed 108 (exit 0): see fuzz-108.log, which lists the input as hex
02:50:32 fuzz seed 109, 200000000 iterations
02:51:51 FUZZ FAILURE with seed 109 (exit 0): see fuzz-109.log, which lists the input as hex
02:51:51 fuzz seed 110, 200000000 iterations
02:53:07 FUZZ FAILURE with seed 110 (exit 0): see fuzz-110.log, which lists the input as hex
02:53:07 fuzz seed 111, 200000000 iterations
02:54:24 FUZZ FAILURE with seed 111 (exit 0): see fuzz-111.log, which lists the input as hex
02:54:24 fuzz seed 112, 200000000 iterations
02:55:41 FUZZ FAILURE with seed 112 (exit 0): see fuzz-112.log, which lists the input as hex
02:55:41 fuzz seed 113, 200000000 iterations
02:56:58 FUZZ FAILURE with seed 113 (exit 0): see fuzz-113.log, which lists the input as hex
02:56:58 fuzz seed 114, 200000000 iterations
02:58:15 FUZZ FAILURE with seed 114 (exit 0): see fuzz-114.log, which lists the input as hex
02:58:15 fuzz seed 115, 200000000 iterations
02:59:32 FUZZ FAILURE with seed 115 (exit 0): see fuzz-115.log, which lists the input as hex
02:59:32 fuzz seed 116, 200000000 iterations
03:00:49 FUZZ FAILURE with seed 116 (exit 0): see fuzz-116.log, which lists the input as hex
03:00:49 fuzz seed 117, 200000000 iterations
03:02:06 FUZZ FAILURE with seed 117 (exit 0): see fuzz-117.log, which lists the input as hex
03:02:06 fuzz seed 118, 200000000 iterations
03:03:22 FUZZ FAILURE with seed 118 (exit 0): see fuzz-118.log, which lists the input as hex
03:03:22 fuzz seed 119, 200000000 iterations
03:04:38 FUZZ FAILURE with seed 119 (exit 0): see fuzz-119.log, which lists the input as hex
03:04:38 fuzz seed 120, 200000000 iterations
03:05:54 FUZZ FAILURE with seed 120 (exit 0): see fuzz-120.log, which lists the input as hex
03:05:54 fuzz seed 121, 200000000 iterations
03:07:11 FUZZ FAILURE with seed 121 (exit 0): see fuzz-121.log, which lists the input as hex
03:07:11 fuzz seed 122, 200000000 iterations
03:08:28 FUZZ FAILURE with seed 122 (exit 0): see fuzz-122.log, which lists the input as hex
03:08:28 fuzz seed 123, 200000000 iterations
03:09:45 FUZZ FAILURE with seed 123 (exit 0): see fuzz-123.log, which lists the input as hex
03:09:45 fuzz seed 124, 200000000 iterations
03:11:02 FUZZ FAILURE with seed 124 (exit 0): see fuzz-124.log, which lists the input as hex
03:11:02 fuzz seed 125, 200000000 iterations
03:12:18 FUZZ FAILURE with seed 125 (exit 0): see fuzz-125.log, which lists the input as hex
03:12:18 fuzz seed 126, 200000000 iterations
03:13:35 FUZZ FAILURE with seed 126 (exit 0): see fuzz-126.log, which lists the input as hex
03:13:35 fuzz seed 127, 200000000 iterations
03:14:52 FUZZ FAILURE with seed 127 (exit 0): see fuzz-127.log, which lists the input as hex
03:14:52 fuzz seed 128, 200000000 iterations
03:16:09 FUZZ FAILURE with seed 128 (exit 0): see fuzz-128.log, which lists the input as hex
03:16:09 fuzz seed 129, 200000000 iterations
03:17:25 FUZZ FAILURE with seed 129 (exit 0): see fuzz-129.log, which lists the input as hex
03:17:25 fuzz seed 130, 200000000 iterations
03:18:41 FUZZ FAILURE with seed 130 (exit 0): see fuzz-130.log, which lists the input as hex
03:18:41 fuzz seed 131, 200000000 iterations
03:19:58 FUZZ FAILURE with seed 131 (exit 0): see fuzz-131.log, which lists the input as hex
03:19:58 fuzz seed 132, 200000000 iterations
03:21:14 FUZZ FAILURE with seed 132 (exit 0): see fuzz-132.log, which lists the input as hex
03:21:14 fuzz seed 133, 200000000 iterations
03:22:30 FUZZ FAILURE with seed 133 (exit 0): see fuzz-133.log, which lists the input as hex
03:22:30 fuzz seed 134, 200000000 iterations
03:23:46 FUZZ FAILURE with seed 134 (exit 0): see fuzz-134.log, which lists the input as hex
03:23:46 fuzz seed 135, 200000000 iterations
03:25:03 FUZZ FAILURE with seed 135 (exit 0): see fuzz-135.log, which lists the input as hex
03:25:03 fuzz seed 136, 200000000 iterations
03:26:19 FUZZ FAILURE with seed 136 (exit 0): see fuzz-136.log, which lists the input as hex
03:26:19 fuzz seed 137, 200000000 iterations
03:27:36 FUZZ FAILURE with seed 137 (exit 0): see fuzz-137.log, which lists the input as hex
03:27:36 fuzz seed 138, 200000000 iterations
03:28:53 FUZZ FAILURE with seed 138 (exit 0): see fuzz-138.log, which lists the input as hex
03:28:53 fuzz seed 139, 200000000 iterations
03:30:10 FUZZ FAILURE with seed 139 (exit 0): see fuzz-139.log, which lists the input as hex
03:30:10 fuzz seed 140, 200000000 iterations
03:31:26 FUZZ FAILURE with seed 140 (exit 0): see fuzz-140.log, which lists the input as hex
03:31:26 fuzz seed 141, 200000000 iterations
03:32:42 FUZZ FAILURE with seed 141 (exit 0): see fuzz-141.log, which lists the input as hex
03:32:42 fuzz seed 142, 200000000 iterations
03:33:59 FUZZ FAILURE with seed 142 (exit 0): see fuzz-142.log, which lists the input as hex
03:33:59 fuzz seed 143, 200000000 iterations
03:35:15 FUZZ FAILURE with seed 143 (exit 0): see fuzz-143.log, which lists the input as hex
03:35:15 fuzz seed 144, 200000000 iterations
03:36:31 FUZZ FAILURE with seed 144 (exit 0): see fuzz-144.log, which lists the input as hex
03:36:31 fuzz seed 145, 200000000 iterations
03:37:47 FUZZ FAILURE with seed 145 (exit 0): see fuzz-145.log, which lists the input as hex
03:37:47 fuzz seed 146, 200000000 iterations
03:39:03 FUZZ FAILURE with seed 146 (exit 0): see fuzz-146.log, which lists the input as hex
03:39:03 fuzz seed 147, 200000000 iterations
03:40:19 FUZZ FAILURE with seed 147 (exit 0): see fuzz-147.log, which lists the input as hex
03:40:19 fuzz seed 148, 200000000 iterations
03:41:36 FUZZ FAILURE with seed 148 (exit 0): see fuzz-148.log, which lists the input as hex
03:41:36 fuzz seed 149, 200000000 iterations
03:42:55 FUZZ FAILURE with seed 149 (exit 0): see fuzz-149.log, which lists the input as hex
03:42:55 fuzz seed 150, 200000000 iterations
03:44:12 FUZZ FAILURE with seed 150 (exit 0): see fuzz-150.log, which lists the input as hex
03:44:12 fuzz seed 151, 200000000 iterations
03:45:29 FUZZ FAILURE with seed 151 (exit 0): see fuzz-151.log, which lists the input as hex
03:45:29 fuzz seed 152, 200000000 iterations
03:46:49 FUZZ FAILURE with seed 152 (exit 0): see fuzz-152.log, which lists the input as hex
03:46:49 fuzz seed 153, 200000000 iterations
03:48:05 FUZZ FAILURE with seed 153 (exit 0): see fuzz-153.log, which lists the input as hex
03:48:05 fuzz seed 154, 200000000 iterations
03:49:21 FUZZ FAILURE with seed 154 (exit 0): see fuzz-154.log, which lists the input as hex
03:49:21 fuzz seed 155, 200000000 iterations
03:50:38 FUZZ FAILURE with seed 155 (exit 0): see fuzz-155.log, which lists the input as hex
03:50:38 fuzz seed 156, 200000000 iterations
03:51:54 FUZZ FAILURE with seed 156 (exit 0): see fuzz-156.log, which lists the input as hex
03:51:54 fuzz seed 157, 200000000 iterations
03:53:11 FUZZ FAILURE with seed 157 (exit 0): see fuzz-157.log, which lists the input as hex
03:53:11 fuzz seed 158, 200000000 iterations
03:54:27 FUZZ FAILURE with seed 158 (exit 0): see fuzz-158.log, which lists the input as hex
03:54:27 fuzz seed 159, 200000000 iterations
03:55:43 FUZZ FAILURE with seed 159 (exit 0): see fuzz-159.log, which lists the input as hex
03:55:43 fuzz seed 160, 200000000 iterations
03:57:00 FUZZ FAILURE with seed 160 (exit 0): see fuzz-160.log, which lists the input as hex
03:57:00 fuzz seed 161, 200000000 iterations
03:58:17 FUZZ FAILURE with seed 161 (exit 0): see fuzz-161.log, which lists the input as hex
03:58:17 fuzz seed 162, 200000000 iterations
03:59:34 FUZZ FAILURE with seed 162 (exit 0): see fuzz-162.log, which lists the input as hex
03:59:34 fuzz seed 163, 200000000 iterations
04:00:51 FUZZ FAILURE with seed 163 (exit 0): see fuzz-163.log, which lists the input as hex
04:00:51 fuzz seed 164, 200000000 iterations
04:02:06 FUZZ FAILURE with seed 164 (exit 0): see fuzz-164.log, which lists the input as hex
04:02:06 fuzz seed 165, 200000000 iterations
04:03:23 FUZZ FAILURE with seed 165 (exit 0): see fuzz-165.log, which lists the input as hex
04:03:23 fuzz seed 166, 200000000 iterations
04:04:40 FUZZ FAILURE with seed 166 (exit 0): see fuzz-166.log, which lists the input as hex
04:04:40 fuzz seed 167, 200000000 iterations
04:05:58 FUZZ FAILURE with seed 167 (exit 0): see fuzz-167.log, which lists the input as hex
04:05:58 fuzz seed 168, 200000000 iterations
04:07:14 FUZZ FAILURE with seed 168 (exit 0): see fuzz-168.log, which lists the input as hex
04:07:14 fuzz seed 169, 200000000 iterations
04:08:31 FUZZ FAILURE with seed 169 (exit 0): see fuzz-169.log, which lists the input as hex
04:08:31 fuzz seed 170, 200000000 iterations
04:09:50 FUZZ FAILURE with seed 170 (exit 0): see fuzz-170.log, which lists the input as hex
04:09:50 fuzz seed 171, 200000000 iterations
04:11:08 FUZZ FAILURE with seed 171 (exit 0): see fuzz-171.log, which lists the input as hex
04:11:08 fuzz seed 172, 200000000 iterations
04:12:24 FUZZ FAILURE with seed 172 (exit 0): see fuzz-172.log, which lists the input as hex
04:12:24 fuzz seed 173, 200000000 iterations
04:13:40 FUZZ FAILURE with seed 173 (exit 0): see fuzz-173.log, which lists the input as hex
04:13:40 fuzz seed 174, 200000000 iterations
04:14:57 FUZZ FAILURE with seed 174 (exit 0): see fuzz-174.log, which lists the input as hex
04:14:57 fuzz seed 175, 200000000 iterations
04:16:13 FUZZ FAILURE with seed 175 (exit 0): see fuzz-175.log, which lists the input as hex
04:16:13 fuzz seed 176, 200000000 iterations
04:17:29 FUZZ FAILURE with seed 176 (exit 0): see fuzz-176.log, which lists the input as hex
04:17:29 fuzz seed 177, 200000000 iterations
04:18:45 FUZZ FAILURE with seed 177 (exit 0): see fuzz-177.log, which lists the input as hex
04:18:45 fuzz seed 178, 200000000 iterations
04:20:02 FUZZ FAILURE with seed 178 (exit 0): see fuzz-178.log, which lists the input as hex
04:20:02 fuzz seed 179, 200000000 iterations
04:21:19 FUZZ FAILURE with seed 179 (exit 0): see fuzz-179.log, which lists the input as hex
04:21:19 fuzz seed 180, 200000000 iterations
04:22:35 FUZZ FAILURE with seed 180 (exit 0): see fuzz-180.log, which lists the input as hex
04:22:35 fuzz seed 181, 200000000 iterations
04:23:52 FUZZ FAILURE with seed 181 (exit 0): see fuzz-181.log, which lists the input as hex
04:23:52 fuzz seed 182, 200000000 iterations
04:25:09 FUZZ FAILURE with seed 182 (exit 0): see fuzz-182.log, which lists the input as hex
04:25:09 fuzz seed 183, 200000000 iterations
04:26:26 FUZZ FAILURE with seed 183 (exit 0): see fuzz-183.log, which lists the input as hex
04:26:26 fuzz seed 184, 200000000 iterations
04:27:48 FUZZ FAILURE with seed 184 (exit 0): see fuzz-184.log, which lists the input as hex
04:27:48 fuzz seed 185, 200000000 iterations
04:29:05 FUZZ FAILURE with seed 185 (exit 0): see fuzz-185.log, which lists the input as hex
04:29:05 fuzz seed 186, 200000000 iterations
04:30:22 FUZZ FAILURE with seed 186 (exit 0): see fuzz-186.log, which lists the input as hex
04:30:22 fuzz seed 187, 200000000 iterations
04:31:38 FUZZ FAILURE with seed 187 (exit 0): see fuzz-187.log, which lists the input as hex
04:31:38 fuzz seed 188, 200000000 iterations
04:32:55 FUZZ FAILURE with seed 188 (exit 0): see fuzz-188.log, which lists the input as hex
04:32:55 fuzz seed 189, 200000000 iterations
04:34:12 FUZZ FAILURE with seed 189 (exit 0): see fuzz-189.log, which lists the input as hex
04:34:12 fuzz seed 190, 200000000 iterations
04:35:28 FUZZ FAILURE with seed 190 (exit 0): see fuzz-190.log, which lists the input as hex
04:35:28 fuzz seed 191, 200000000 iterations
04:36:45 FUZZ FAILURE with seed 191 (exit 0): see fuzz-191.log, which lists the input as hex
04:36:45 fuzz seed 192, 200000000 iterations
04:38:01 FUZZ FAILURE with seed 192 (exit 0): see fuzz-192.log, which lists the input as hex
04:38:01 fuzz seed 193, 200000000 iterations
04:39:18 FUZZ FAILURE with seed 193 (exit 0): see fuzz-193.log, which lists the input as hex
04:39:18 fuzz seed 194, 200000000 iterations
04:40:34 FUZZ FAILURE with seed 194 (exit 0): see fuzz-194.log, which lists the input as hex
04:40:34 fuzz seed 195, 200000000 iterations
04:41:51 FUZZ FAILURE with seed 195 (exit 0): see fuzz-195.log, which lists the input as hex
04:41:51 fuzz seed 196, 200000000 iterations
04:43:08 FUZZ FAILURE with seed 196 (exit 0): see fuzz-196.log, which lists the input as hex
04:43:08 fuzz seed 197, 200000000 iterations
04:44:24 FUZZ FAILURE with seed 197 (exit 0): see fuzz-197.log, which lists the input as hex
04:44:24 fuzz seed 198, 200000000 iterations
04:45:41 FUZZ FAILURE with seed 198 (exit 0): see fuzz-198.log, which lists the input as hex
04:45:41 fuzz seed 199, 200000000 iterations
04:46:58 FUZZ FAILURE with seed 199 (exit 0): see fuzz-199.log, which lists the input as hex
04:46:58 fuzz seed 200, 200000000 iterations
04:48:14 FUZZ FAILURE with seed 200 (exit 0): see fuzz-200.log, which lists the input as hex
04:48:14 fuzz seed 201, 200000000 iterations
04:49:31 FUZZ FAILURE with seed 201 (exit 0): see fuzz-201.log, which lists the input as hex
04:49:31 fuzz seed 202, 200000000 iterations
04:50:47 FUZZ FAILURE with seed 202 (exit 0): see fuzz-202.log, which lists the input as hex
04:50:47 fuzz seed 203, 200000000 iterations
04:52:04 FUZZ FAILURE with seed 203 (exit 0): see fuzz-203.log, which lists the input as hex
04:52:04 fuzz seed 204, 200000000 iterations
04:53:21 FUZZ FAILURE with seed 204 (exit 0): see fuzz-204.log, which lists the input as hex
04:53:21 fuzz seed 205, 200000000 iterations
04:54:38 FUZZ FAILURE with seed 205 (exit 0): see fuzz-205.log, which lists the input as hex
04:54:38 fuzz seed 206, 200000000 iterations
04:55:54 FUZZ FAILURE with seed 206 (exit 0): see fuzz-206.log, which lists the input as hex
04:55:54 fuzz seed 207, 200000000 iterations
04:57:11 FUZZ FAILURE with seed 207 (exit 0): see fuzz-207.log, which lists the input as hex
04:57:11 fuzz seed 208, 200000000 iterations
04:58:27 FUZZ FAILURE with seed 208 (exit 0): see fuzz-208.log, which lists the input as hex
04:58:27 fuzz seed 209, 200000000 iterations
04:59:44 FUZZ FAILURE with seed 209 (exit 0): see fuzz-209.log, which lists the input as hex
04:59:44 fuzz seed 210, 200000000 iterations
05:01:00 FUZZ FAILURE with seed 210 (exit 0): see fuzz-210.log, which lists the input as hex
05:01:00 fuzz seed 211, 200000000 iterations
05:02:17 FUZZ FAILURE with seed 211 (exit 0): see fuzz-211.log, which lists the input as hex
05:02:17 fuzz seed 212, 200000000 iterations
05:03:33 FUZZ FAILURE with seed 212 (exit 0): see fuzz-212.log, which lists the input as hex
05:03:33 fuzz seed 213, 200000000 iterations
05:04:49 FUZZ FAILURE with seed 213 (exit 0): see fuzz-213.log, which lists the input as hex
05:04:49 fuzz seed 214, 200000000 iterations
05:06:05 FUZZ FAILURE with seed 214 (exit 0): see fuzz-214.log, which lists the input as hex
05:06:05 fuzz seed 215, 200000000 iterations
05:07:21 FUZZ FAILURE with seed 215 (exit 0): see fuzz-215.log, which lists the input as hex
05:07:21 fuzz seed 216, 200000000 iterations
05:08:38 FUZZ FAILURE with seed 216 (exit 0): see fuzz-216.log, which lists the input as hex
05:08:38 fuzz seed 217, 200000000 iterations
05:09:56 FUZZ FAILURE with seed 217 (exit 0): see fuzz-217.log, which lists the input as hex
05:09:56 fuzz seed 218, 200000000 iterations
05:11:14 FUZZ FAILURE with seed 218 (exit 0): see fuzz-218.log, which lists the input as hex
05:11:14 fuzz seed 219, 200000000 iterations
05:12:30 FUZZ FAILURE with seed 219 (exit 0): see fuzz-219.log, which lists the input as hex
05:12:30 fuzz seed 220, 200000000 iterations
05:13:47 FUZZ FAILURE with seed 220 (exit 0): see fuzz-220.log, which lists the input as hex
05:13:47 fuzz seed 221, 200000000 iterations
05:15:03 FUZZ FAILURE with seed 221 (exit 0): see fuzz-221.log, which lists the input as hex
05:15:03 fuzz seed 222, 200000000 iterations
05:16:19 FUZZ FAILURE with seed 222 (exit 0): see fuzz-222.log, which lists the input as hex
05:16:19 fuzz seed 223, 200000000 iterations
05:17:35 FUZZ FAILURE with seed 223 (exit 0): see fuzz-223.log, which lists the input as hex
05:17:35 fuzz seed 224, 200000000 iterations
05:18:52 FUZZ FAILURE with seed 224 (exit 0): see fuzz-224.log, which lists the input as hex
05:18:52 fuzz seed 225, 200000000 iterations
05:20:08 FUZZ FAILURE with seed 225 (exit 0): see fuzz-225.log, which lists the input as hex
05:20:08 fuzz seed 226, 200000000 iterations
05:21:24 FUZZ FAILURE with seed 226 (exit 0): see fuzz-226.log, which lists the input as hex
05:21:24 fuzz seed 227, 200000000 iterations
05:22:41 FUZZ FAILURE with seed 227 (exit 0): see fuzz-227.log, which lists the input as hex
05:22:41 fuzz seed 228, 200000000 iterations
05:23:58 FUZZ FAILURE with seed 228 (exit 0): see fuzz-228.log, which lists the input as hex
05:23:58 fuzz seed 229, 200000000 iterations
05:25:15 FUZZ FAILURE with seed 229 (exit 0): see fuzz-229.log, which lists the input as hex
05:25:15 fuzz seed 230, 200000000 iterations
05:26:31 FUZZ FAILURE with seed 230 (exit 0): see fuzz-230.log, which lists the input as hex
05:26:31 fuzz seed 231, 200000000 iterations
05:27:48 FUZZ FAILURE with seed 231 (exit 0): see fuzz-231.log, which lists the input as hex
05:27:48 fuzz seed 232, 200000000 iterations
05:29:04 FUZZ FAILURE with seed 232 (exit 0): see fuzz-232.log, which lists the input as hex
05:29:04 fuzz seed 233, 200000000 iterations
05:30:21 FUZZ FAILURE with seed 233 (exit 0): see fuzz-233.log, which lists the input as hex
05:30:21 fuzz seed 234, 200000000 iterations
05:31:37 FUZZ FAILURE with seed 234 (exit 0): see fuzz-234.log, which lists the input as hex
05:31:37 fuzz seed 235, 200000000 iterations
05:32:53 FUZZ FAILURE with seed 235 (exit 0): see fuzz-235.log, which lists the input as hex
05:32:53 fuzz seed 236, 200000000 iterations
05:34:09 FUZZ FAILURE with seed 236 (exit 0): see fuzz-236.log, which lists the input as hex
05:34:09 fuzz seed 237, 200000000 iterations
05:35:26 FUZZ FAILURE with seed 237 (exit 0): see fuzz-237.log, which lists the input as hex
05:35:26 fuzz seed 238, 200000000 iterations
05:36:43 FUZZ FAILURE with seed 238 (exit 0): see fuzz-238.log, which lists the input as hex
05:36:43 fuzz seed 239, 200000000 iterations
05:37:59 FUZZ FAILURE with seed 239 (exit 0): see fuzz-239.log, which lists the input as hex
05:37:59 fuzz seed 240, 200000000 iterations
05:39:15 FUZZ FAILURE with seed 240 (exit 0): see fuzz-240.log, which lists the input as hex
05:39:15 fuzz seed 241, 200000000 iterations
05:40:32 FUZZ FAILURE with seed 241 (exit 0): see fuzz-241.log, which lists the input as hex
05:40:32 fuzz seed 242, 200000000 iterations
05:41:49 FUZZ FAILURE with seed 242 (exit 0): see fuzz-242.log, which lists the input as hex
05:41:49 fuzz seed 243, 200000000 iterations
05:43:06 FUZZ FAILURE with seed 243 (exit 0): see fuzz-243.log, which lists the input as hex
05:43:06 fuzz seed 244, 200000000 iterations
05:44:22 FUZZ FAILURE with seed 244 (exit 0): see fuzz-244.log, which lists the input as hex
05:44:22 fuzz seed 245, 200000000 iterations
05:45:39 FUZZ FAILURE with seed 245 (exit 0): see fuzz-245.log, which lists the input as hex
05:45:39 fuzz seed 246, 200000000 iterations
05:46:55 FUZZ FAILURE with seed 246 (exit 0): see fuzz-246.log, which lists the input as hex
05:46:55 fuzz seed 247, 200000000 iterations
05:48:12 FUZZ FAILURE with seed 247 (exit 0): see fuzz-247.log, which lists the input as hex
05:48:12 fuzz seed 248, 200000000 iterations
05:49:31 FUZZ FAILURE with seed 248 (exit 0): see fuzz-248.log, which lists the input as hex
05:49:31 fuzz seed 249, 200000000 iterations
05:50:49 FUZZ FAILURE with seed 249 (exit 0): see fuzz-249.log, which lists the input as hex
05:50:49 fuzz seed 250, 200000000 iterations
05:52:05 FUZZ FAILURE with seed 250 (exit 0): see fuzz-250.log, which lists the input as hex
05:52:05 fuzz seed 251, 200000000 iterations
05:53:21 FUZZ FAILURE with seed 251 (exit 0): see fuzz-251.log, which lists the input as hex
05:53:21 fuzz seed 252, 200000000 iterations
05:54:37 FUZZ FAILURE with seed 252 (exit 0): see fuzz-252.log, which lists the input as hex
05:54:37 fuzz seed 253, 200000000 iterations
05:55:54 FUZZ FAILURE with seed 253 (exit 0): see fuzz-253.log, which lists the input as hex
05:55:54 fuzz seed 254, 200000000 iterations
05:57:10 FUZZ FAILURE with seed 254 (exit 0): see fuzz-254.log, which lists the input as hex
05:57:10 fuzz seed 255, 200000000 iterations
05:58:27 FUZZ FAILURE with seed 255 (exit 0): see fuzz-255.log, which lists the input as hex
05:58:27 fuzz seed 256, 200000000 iterations
05:59:44 FUZZ FAILURE with seed 256 (exit 0): see fuzz-256.log, which lists the input as hex
05:59:44 fuzz seed 257, 200000000 iterations
06:01:01 FUZZ FAILURE with seed 257 (exit 0): see fuzz-257.log, which lists the input as hex
06:01:01 fuzz seed 258, 200000000 iterations
06:02:17 FUZZ FAILURE with seed 258 (exit 0): see fuzz-258.log, which lists the input as hex
06:02:17 fuzz seed 259, 200000000 iterations
06:03:34 FUZZ FAILURE with seed 259 (exit 0): see fuzz-259.log, which lists the input as hex
06:03:34 fuzz seed 260, 200000000 iterations
06:04:50 FUZZ FAILURE with seed 260 (exit 0): see fuzz-260.log, which lists the input as hex
06:04:50 fuzz seed 261, 200000000 iterations
06:06:07 FUZZ FAILURE with seed 261 (exit 0): see fuzz-261.log, which lists the input as hex
06:06:07 fuzz seed 262, 200000000 iterations
06:07:23 FUZZ FAILURE with seed 262 (exit 0): see fuzz-262.log, which lists the input as hex
06:07:23 fuzz seed 263, 200000000 iterations
06:08:40 FUZZ FAILURE with seed 263 (exit 0): see fuzz-263.log, which lists the input as hex
06:08:40 fuzz seed 264, 200000000 iterations
06:09:59 FUZZ FAILURE with seed 264 (exit 0): see fuzz-264.log, which lists the input as hex
06:09:59 fuzz seed 265, 200000000 iterations
06:11:16 FUZZ FAILURE with seed 265 (exit 0): see fuzz-265.log, which lists the input as hex
06:11:16 fuzz seed 266, 200000000 iterations
06:12:33 FUZZ FAILURE with seed 266 (exit 0): see fuzz-266.log, which lists the input as hex
06:12:33 fuzz seed 267, 200000000 iterations
06:13:50 FUZZ FAILURE with seed 267 (exit 0): see fuzz-267.log, which lists the input as hex
06:13:50 fuzz seed 268, 200000000 iterations
06:15:06 FUZZ FAILURE with seed 268 (exit 0): see fuzz-268.log, which lists the input as hex
06:15:06 fuzz seed 269, 200000000 iterations
06:16:22 FUZZ FAILURE with seed 269 (exit 0): see fuzz-269.log, which lists the input as hex
06:16:22 fuzz seed 270, 200000000 iterations
06:17:39 FUZZ FAILURE with seed 270 (exit 0): see fuzz-270.log, which lists the input as hex
06:17:39 fuzz seed 271, 200000000 iterations
06:18:56 FUZZ FAILURE with seed 271 (exit 0): see fuzz-271.log, which lists the input as hex
06:18:56 fuzz seed 272, 200000000 iterations
06:20:13 FUZZ FAILURE with seed 272 (exit 0): see fuzz-272.log, which lists the input as hex
06:20:13 fuzz seed 273, 200000000 iterations
06:21:29 FUZZ FAILURE with seed 273 (exit 0): see fuzz-273.log, which lists the input as hex
06:21:29 fuzz seed 274, 200000000 iterations
06:22:47 FUZZ FAILURE with seed 274 (exit 0): see fuzz-274.log, which lists the input as hex
06:22:47 fuzz seed 275, 200000000 iterations
06:24:03 FUZZ FAILURE with seed 275 (exit 0): see fuzz-275.log, which lists the input as hex
06:24:03 fuzz seed 276, 200000000 iterations
06:25:19 FUZZ FAILURE with seed 276 (exit 0): see fuzz-276.log, which lists the input as hex
06:25:19 fuzz seed 277, 200000000 iterations
06:26:36 FUZZ FAILURE with seed 277 (exit 0): see fuzz-277.log, which lists the input as hex
06:26:36 fuzz seed 278, 200000000 iterations
06:27:53 FUZZ FAILURE with seed 278 (exit 0): see fuzz-278.log, which lists the input as hex
06:27:53 fuzz seed 279, 200000000 iterations
06:29:09 FUZZ FAILURE with seed 279 (exit 0): see fuzz-279.log, which lists the input as hex
06:29:09 fuzz seed 280, 200000000 iterations
06:30:26 FUZZ FAILURE with seed 280 (exit 0): see fuzz-280.log, which lists the input as hex
06:30:26 fuzz seed 281, 200000000 iterations
06:31:42 FUZZ FAILURE with seed 281 (exit 0): see fuzz-281.log, which lists the input as hex
06:31:42 fuzz seed 282, 200000000 iterations
06:32:59 FUZZ FAILURE with seed 282 (exit 0): see fuzz-282.log, which lists the input as hex
06:32:59 fuzz seed 283, 200000000 iterations
06:34:16 FUZZ FAILURE with seed 283 (exit 0): see fuzz-283.log, which lists the input as hex
06:34:16 fuzz seed 284, 200000000 iterations
06:35:33 FUZZ FAILURE with seed 284 (exit 0): see fuzz-284.log, which lists the input as hex
06:35:33 fuzz seed 285, 200000000 iterations
06:36:49 FUZZ FAILURE with seed 285 (exit 0): see fuzz-285.log, which lists the input as hex
06:36:49 fuzz seed 286, 200000000 iterations
06:38:05 FUZZ FAILURE with seed 286 (exit 0): see fuzz-286.log, which lists the input as hex
06:38:05 fuzz seed 287, 200000000 iterations
06:39:21 FUZZ FAILURE with seed 287 (exit 0): see fuzz-287.log, which lists the input as hex
06:39:21 fuzz seed 288, 200000000 iterations
06:40:39 FUZZ FAILURE with seed 288 (exit 0): see fuzz-288.log, which lists the input as hex
06:40:39 fuzz seed 289, 200000000 iterations
06:41:55 FUZZ FAILURE with seed 289 (exit 0): see fuzz-289.log, which lists the input as hex
06:41:55 fuzz seed 290, 200000000 iterations
06:43:11 FUZZ FAILURE with seed 290 (exit 0): see fuzz-290.log, which lists the input as hex
06:43:11 fuzz seed 291, 200000000 iterations
06:44:27 FUZZ FAILURE with seed 291 (exit 0): see fuzz-291.log, which lists the input as hex
06:44:27 fuzz seed 292, 200000000 iterations
06:45:45 FUZZ FAILURE with seed 292 (exit 0): see fuzz-292.log, which lists the input as hex
06:45:45 fuzz seed 293, 200000000 iterations
06:47:01 FUZZ FAILURE with seed 293 (exit 0): see fuzz-293.log, which lists the input as hex
06:47:01 fuzz seed 294, 200000000 iterations
06:48:18 FUZZ FAILURE with seed 294 (exit 0): see fuzz-294.log, which lists the input as hex
06:48:18 fuzz seed 295, 200000000 iterations
06:49:35 FUZZ FAILURE with seed 295 (exit 0): see fuzz-295.log, which lists the input as hex
06:49:35 fuzz seed 296, 200000000 iterations
06:50:51 FUZZ FAILURE with seed 296 (exit 0): see fuzz-296.log, which lists the input as hex
06:50:51 fuzz seed 297, 200000000 iterations
06:52:07 FUZZ FAILURE with seed 297 (exit 0): see fuzz-297.log, which lists the input as hex
06:52:07 fuzz seed 298, 200000000 iterations
06:53:24 FUZZ FAILURE with seed 298 (exit 0): see fuzz-298.log, which lists the input as hex
06:53:24 fuzz seed 299, 200000000 iterations
06:54:40 FUZZ FAILURE with seed 299 (exit 0): see fuzz-299.log, which lists the input as hex
06:54:40 fuzz seed 300, 200000000 iterations
06:55:57 FUZZ FAILURE with seed 300 (exit 0): see fuzz-300.log, which lists the input as hex
06:55:57 fuzz seed 301, 200000000 iterations
06:57:14 FUZZ FAILURE with seed 301 (exit 0): see fuzz-301.log, which lists the input as hex
06:57:14 fuzz seed 302, 200000000 iterations
06:58:30 FUZZ FAILURE with seed 302 (exit 0): see fuzz-302.log, which lists the input as hex
06:58:30 fuzz seed 303, 200000000 iterations
06:59:46 FUZZ FAILURE with seed 303 (exit 0): see fuzz-303.log, which lists the input as hex
06:59:46 fuzz seed 304, 200000000 iterations
07:01:03 FUZZ FAILURE with seed 304 (exit 0): see fuzz-304.log, which lists the input as hex
07:01:03 fuzz seed 305, 200000000 iterations
07:02:19 FUZZ FAILURE with seed 305 (exit 0): see fuzz-305.log, which lists the input as hex
07:02:19 fuzz seed 306, 200000000 iterations
07:03:36 FUZZ FAILURE with seed 306 (exit 0): see fuzz-306.log, which lists the input as hex
07:03:36 fuzz seed 307, 200000000 iterations
07:04:53 FUZZ FAILURE with seed 307 (exit 0): see fuzz-307.log, which lists the input as hex
07:04:53 fuzz seed 308, 200000000 iterations
07:06:10 FUZZ FAILURE with seed 308 (exit 0): see fuzz-308.log, which lists the input as hex
07:06:10 fuzz seed 309, 200000000 iterations
07:07:27 FUZZ FAILURE with seed 309 (exit 0): see fuzz-309.log, which lists the input as hex
07:07:27 fuzz seed 310, 200000000 iterations
07:08:44 FUZZ FAILURE with seed 310 (exit 0): see fuzz-310.log, which lists the input as hex
07:08:44 fuzz seed 311, 200000000 iterations
07:10:01 FUZZ FAILURE with seed 311 (exit 0): see fuzz-311.log, which lists the input as hex
07:10:01 fuzz seed 312, 200000000 iterations
07:11:18 FUZZ FAILURE with seed 312 (exit 0): see fuzz-312.log, which lists the input as hex
07:11:18 fuzz seed 313, 200000000 iterations
07:12:35 FUZZ FAILURE with seed 313 (exit 0): see fuzz-313.log, which lists the input as hex
07:12:35 fuzz seed 314, 200000000 iterations
07:13:53 FUZZ FAILURE with seed 314 (exit 0): see fuzz-314.log, which lists the input as hex
07:13:53 fuzz seed 315, 200000000 iterations
07:15:10 FUZZ FAILURE with seed 315 (exit 0): see fuzz-315.log, which lists the input as hex
07:15:10 fuzz seed 316, 200000000 iterations
07:16:27 FUZZ FAILURE with seed 316 (exit 0): see fuzz-316.log, which lists the input as hex
07:16:27 fuzz seed 317, 200000000 iterations
07:17:44 FUZZ FAILURE with seed 317 (exit 0): see fuzz-317.log, which lists the input as hex
07:17:44 fuzz seed 318, 200000000 iterations
07:19:01 FUZZ FAILURE with seed 318 (exit 0): see fuzz-318.log, which lists the input as hex
07:19:01 fuzz seed 319, 200000000 iterations
07:20:17 FUZZ FAILURE with seed 319 (exit 0): see fuzz-319.log, which lists the input as hex
07:20:17 fuzz seed 320, 200000000 iterations
07:21:33 FUZZ FAILURE with seed 320 (exit 0): see fuzz-320.log, which lists the input as hex
07:21:33 fuzz seed 321, 200000000 iterations
07:22:50 FUZZ FAILURE with seed 321 (exit 0): see fuzz-321.log, which lists the input as hex
07:22:50 fuzz seed 322, 200000000 iterations
07:24:07 FUZZ FAILURE with seed 322 (exit 0): see fuzz-322.log, which lists the input as hex
07:24:07 fuzz seed 323, 200000000 iterations
07:25:24 FUZZ FAILURE with seed 323 (exit 0): see fuzz-323.log, which lists the input as hex
07:25:24 fuzz seed 324, 200000000 iterations
07:26:41 FUZZ FAILURE with seed 324 (exit 0): see fuzz-324.log, which lists the input as hex
07:26:41 fuzz seed 325, 200000000 iterations
07:27:58 FUZZ FAILURE with seed 325 (exit 0): see fuzz-325.log, which lists the input as hex
07:27:58 fuzz seed 326, 200000000 iterations
07:29:15 FUZZ FAILURE with seed 326 (exit 0): see fuzz-326.log, which lists the input as hex
07:29:15 fuzz seed 327, 200000000 iterations
07:30:32 FUZZ FAILURE with seed 327 (exit 0): see fuzz-327.log, which lists the input as hex
07:30:32 fuzz seed 328, 200000000 iterations
07:31:49 FUZZ FAILURE with seed 328 (exit 0): see fuzz-328.log, which lists the input as hex
07:31:49 fuzz seed 329, 200000000 iterations
07:33:06 FUZZ FAILURE with seed 329 (exit 0): see fuzz-329.log, which lists the input as hex
07:33:06 fuzz seed 330, 200000000 iterations
07:34:22 FUZZ FAILURE with seed 330 (exit 0): see fuzz-330.log, which lists the input as hex
07:34:22 fuzz seed 331, 200000000 iterations
07:35:38 FUZZ FAILURE with seed 331 (exit 0): see fuzz-331.log, which lists the input as hex
07:35:38 fuzz seed 332, 200000000 iterations
07:36:55 FUZZ FAILURE with seed 332 (exit 0): see fuzz-332.log, which lists the input as hex
07:36:55 fuzz seed 333, 200000000 iterations
07:38:11 FUZZ FAILURE with seed 333 (exit 0): see fuzz-333.log, which lists the input as hex
07:38:11 fuzz seed 334, 200000000 iterations
07:39:28 FUZZ FAILURE with seed 334 (exit 0): see fuzz-334.log, which lists the input as hex
07:39:28 fuzz seed 335, 200000000 iterations
07:40:45 FUZZ FAILURE with seed 335 (exit 0): see fuzz-335.log, which lists the input as hex
07:40:45 fuzz seed 336, 200000000 iterations
07:42:02 FUZZ FAILURE with seed 336 (exit 0): see fuzz-336.log, which lists the input as hex
07:42:02 fuzz seed 337, 200000000 iterations
07:43:19 FUZZ FAILURE with seed 337 (exit 0): see fuzz-337.log, which lists the input as hex
07:43:19 fuzz seed 338, 200000000 iterations
07:44:36 FUZZ FAILURE with seed 338 (exit 0): see fuzz-338.log, which lists the input as hex
07:44:36 fuzz seed 339, 200000000 iterations
07:45:52 FUZZ FAILURE with seed 339 (exit 0): see fuzz-339.log, which lists the input as hex
07:45:52 fuzz seed 340, 200000000 iterations
07:47:10 FUZZ FAILURE with seed 340 (exit 0): see fuzz-340.log, which lists the input as hex
07:47:10 fuzz seed 341, 200000000 iterations
07:48:27 FUZZ FAILURE with seed 341 (exit 0): see fuzz-341.log, which lists the input as hex
07:48:27 fuzz seed 342, 200000000 iterations
07:49:43 FUZZ FAILURE with seed 342 (exit 0): see fuzz-342.log, which lists the input as hex
07:49:43 fuzz seed 343, 200000000 iterations
07:51:01 FUZZ FAILURE with seed 343 (exit 0): see fuzz-343.log, which lists the input as hex
07:51:01 fuzz seed 344, 200000000 iterations
07:52:17 FUZZ FAILURE with seed 344 (exit 0): see fuzz-344.log, which lists the input as hex
07:52:17 fuzz seed 345, 200000000 iterations
07:53:40 FUZZ FAILURE with seed 345 (exit 0): see fuzz-345.log, which lists the input as hex
07:53:40 fuzz seed 346, 200000000 iterations
07:54:57 FUZZ FAILURE with seed 346 (exit 0): see fuzz-346.log, which lists the input as hex
07:54:57 fuzz seed 347, 200000000 iterations
07:56:13 FUZZ FAILURE with seed 347 (exit 0): see fuzz-347.log, which lists the input as hex
07:56:13 fuzz seed 348, 200000000 iterations
07:57:30 FUZZ FAILURE with seed 348 (exit 0): see fuzz-348.log, which lists the input as hex
07:57:30 fuzz seed 349, 200000000 iterations
07:58:46 FUZZ FAILURE with seed 349 (exit 0): see fuzz-349.log, which lists the input as hex
07:58:46 fuzz seed 350, 200000000 iterations
08:00:02 FUZZ FAILURE with seed 350 (exit 0): see fuzz-350.log, which lists the input as hex
08:00:02 fuzz seed 351, 200000000 iterations
08:01:19 FUZZ FAILURE with seed 351 (exit 0): see fuzz-351.log, which lists the input as hex
08:01:19 fuzz seed 352, 200000000 iterations
08:02:37 FUZZ FAILURE with seed 352 (exit 0): see fuzz-352.log, which lists the input as hex
08:02:37 fuzz seed 353, 200000000 iterations
08:03:54 FUZZ FAILURE with seed 353 (exit 0): see fuzz-353.log, which lists the input as hex
08:03:54 fuzz seed 354, 200000000 iterations
08:05:10 FUZZ FAILURE with seed 354 (exit 0): see fuzz-354.log, which lists the input as hex
08:05:10 fuzz seed 355, 200000000 iterations
08:06:27 FUZZ FAILURE with seed 355 (exit 0): see fuzz-355.log, which lists the input as hex
08:06:27 fuzz seed 356, 200000000 iterations
08:07:43 FUZZ FAILURE with seed 356 (exit 0): see fuzz-356.log, which lists the input as hex
08:07:43 fuzz seed 357, 200000000 iterations
08:09:00 FUZZ FAILURE with seed 357 (exit 0): see fuzz-357.log, which lists the input as hex
08:09:00 fuzz seed 358, 200000000 iterations
08:10:17 FUZZ FAILURE with seed 358 (exit 0): see fuzz-358.log, which lists the input as hex
08:10:17 fuzz seed 359, 200000000 iterations
08:11:33 FUZZ FAILURE with seed 359 (exit 0): see fuzz-359.log, which lists the input as hex
08:11:33 fuzz seed 360, 200000000 iterations
08:12:49 FUZZ FAILURE with seed 360 (exit 0): see fuzz-360.log, which lists the input as hex
08:12:49 fuzz seed 361, 200000000 iterations
08:14:05 FUZZ FAILURE with seed 361 (exit 0): see fuzz-361.log, which lists the input as hex
08:14:05 fuzz seed 362, 200000000 iterations
08:15:25 FUZZ FAILURE with seed 362 (exit 0): see fuzz-362.log, which lists the input as hex
08:15:25 fuzz seed 363, 200000000 iterations
08:16:41 FUZZ FAILURE with seed 363 (exit 0): see fuzz-363.log, which lists the input as hex
08:16:41 fuzz seed 364, 200000000 iterations
08:17:58 FUZZ FAILURE with seed 364 (exit 0): see fuzz-364.log, which lists the input as hex
08:17:58 fuzz seed 365, 200000000 iterations
08:19:15 FUZZ FAILURE with seed 365 (exit 0): see fuzz-365.log, which lists the input as hex
08:19:15 fuzz seed 366, 200000000 iterations
08:20:32 FUZZ FAILURE with seed 366 (exit 0): see fuzz-366.log, which lists the input as hex
08:20:32 fuzz seed 367, 200000000 iterations
08:21:49 FUZZ FAILURE with seed 367 (exit 0): see fuzz-367.log, which lists the input as hex
08:21:49 fuzz seed 368, 200000000 iterations
08:23:07 FUZZ FAILURE with seed 368 (exit 0): see fuzz-368.log, which lists the input as hex
08:23:07 fuzz seed 369, 200000000 iterations
08:24:23 FUZZ FAILURE with seed 369 (exit 0): see fuzz-369.log, which lists the input as hex
08:24:23 fuzz seed 370, 200000000 iterations
08:25:40 FUZZ FAILURE with seed 370 (exit 0): see fuzz-370.log, which lists the input as hex
08:25:40 fuzz seed 371, 200000000 iterations
08:26:57 FUZZ FAILURE with seed 371 (exit 0): see fuzz-371.log, which lists the input as hex
08:26:57 fuzz seed 372, 200000000 iterations
08:28:13 FUZZ FAILURE with seed 372 (exit 0): see fuzz-372.log, which lists the input as hex
08:28:13 fuzz seed 373, 200000000 iterations
08:29:31 FUZZ FAILURE with seed 373 (exit 0): see fuzz-373.log, which lists the input as hex
08:29:31 finished: 273 fuzz runs after the suite, 273 failure(s)
@@ -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,160 @@
micrOBU bench run, 6.0 h
PASS 2113 FAIL 16 WARN 8 INFO 70 SKIP 0
== FAIL ==
soak-unsigned transmit path wedged: the station refuses every request (resource_limit) (x4) after 56 requests {'accepted': 16, 'resource_limit': 40}; STATUS change over the phase {'requests_accepted': 16, 'requests_refused': 40, 'radio_submitted': 16, 'radio_failed': 40}; heap_free 68092; uptime 321210 ms
soak-unsigned a repeated STATION_CONFIGURE clears the wedge (x4) next request: resource_limit; radio_submitted 16 -> 0, radio_failed 40 -> 1
soak-unsigned requests accepted (queue not full, no refusal) (x4) 40 refused: {'accepted': 16, 'resource_limit': 40}
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x4) 1378 of 1801 (76.5%); short: 24 B: 154/201, 43 B: 153/200, 100 B: 153/200, 300 B: 153/200, 494 B: 153/200, 495 B: 153/200, 700 B: 153/200, 1000 B: 153/200, 1200 B: 153/200
== WARN ==
soak-unsigned radio_failed stays 0 (x4) +40
soak-signed radio_failed stays 0 (x4) +423
== INFO ==
firmware board runs version aef6539-dirty, compiled Nov 26 2026 01:47:59, project microbu_firmware; checkout HEAD aef6539
conformance battery reading with no cell (x2) battery_mv 4010 (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) c6:3b:6b:d4:84:0c
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 29285 ms, heap_free 75268, heap_min 55028, radio failed 0, resets seen 1
soak-unsigned host-side fragment accounting (x12) {'frag_complete': 1526}
soak-signed host-side fragment accounting (x12) {'frag_complete': 2598}
fuzz seed (x11) 1078587315 (replay with --fuzz-seed 1078587315)
idle-listen V2X_RX heard on the air while listening (x11) 0 messages in 300 s
conformance GN address after naming MAC 02:b3:0a:ce:06:20 88:00:02:b3:0a:ce:06:20
heap lowest free heap ever seen by the station (heap_min_free) 39712 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 24343, frames_ok 357082
== 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 (x12)
soak-unsigned every request got a CONFIRM (x12)
soak-unsigned requests accepted (queue not full, no refusal) (x8)
soak-unsigned the station did not reset during the phase (x12)
soak-unsigned STATUS requests_accepted counts the accepted requests (x12)
soak-unsigned radio_failed stays 0 (x8)
soak-unsigned link_crc_errors stays 0 (host sends valid frames only) (x12)
soak-unsigned every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x12)
soak-unsigned no captured own-TX frame was corrupted (x12)
soak-unsigned no request was transmitted twice (x12)
soak-unsigned accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x12)
soak-signed RAW_CAPTURE own-TX capture accepted (x12)
soak-signed every request got a CONFIRM (x12)
soak-signed requests accepted (queue not full, no refusal) (x12)
soak-signed the station did not reset during the phase (x12)
soak-signed STATUS requests_accepted counts the accepted requests (x12)
soak-signed radio_failed stays 0 (x8)
soak-signed link_crc_errors stays 0 (host sends valid frames only) (x12)
soak-signed sign_failed stays 0 (x12)
soak-signed every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x12)
soak-signed no captured own-TX frame was corrupted (x12)
soak-signed no request was transmitted twice (x12)
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x8)
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 (x1175)
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 (x55)
resets board comes back unconfigured (x55)
resets the reset was a fresh boot (uptime small) (x55)
resets ROM boot banner seen on reopen (x55)
resets first frame after a reset is transmitted (x55)
idle-listen STATUS answered once a second throughout (x11)
idle-listen the station did not reset while idle (x11)
idle-listen receive queue never overflowed (radio_dropped) (x11)
heap heap_min_free stays above 16 KB
heap reconfigure: free heap trend over 4 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
+244
View File
@@ -0,0 +1,244 @@
"""Checks a V2X log recorded with Settings > Ride > "Record motion sensors" on, before it is used for
sensor fusion: are the motion sensors complete and at their rate, are both phone GNSS sources there,
and do the clocks line up. See docs/07-sensor-fusion-logging.md.
py -3.11 tools/fusion_log_check.py LOG.db [LOG.db ...]
Pull a log off the phone with Share on the V2X data logger screen, or with
adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/<name>.db > <name>.db
Reads the file read-only. Prints a report per file and ends with PASS, WARN or FAIL lines; the exit
code is 1 if any file has a FAIL. Standard library only.
"""
import math
import sqlite3
import statistics
import sys
from bisect import bisect_left
from pathlib import Path
IMU_SENSORS = ('accel', 'gyro', 'gravity')
G = 9.80665
# What a usable fusion log looks like. Rates are what the logger asks for (100 Hz); the phone may
# deliver a little more or less.
IMU_RATE_MIN_HZ, IMU_RATE_MAX_HZ = 80.0, 130.0
IMU_GAP_WARN_MS, IMU_GAP_FAIL_MS = 100.0, 1000.0
GNSS_GAP_WARN_S = 5.0
class Report:
def __init__(self):
self.verdicts = []
def line(self, text=''):
print(text)
def verdict(self, level, text):
self.verdicts.append((level, text))
@property
def failed(self):
return any(level == 'FAIL' for level, _ in self.verdicts)
def pct(values, q):
"""The q-th percentile (0..100) of a non-empty list, nearest rank."""
s = sorted(values)
return s[min(len(s) - 1, max(0, math.ceil(q / 100 * len(s)) - 1))]
def haversine_m(lat1, lon1, lat2, lon2):
r = 6_371_000.0
p1, p2 = math.radians(lat1), math.radians(lat2)
a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
def tables(db):
return {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
def check_meta(db, rep):
meta = dict(db.execute('SELECT key, value FROM meta'))
rep.line('meta')
for key in ('schema_version', 'phone', 'android_sdk', 'app_version', 'hardware', 'phone_mount',
'fusion_logging', 'imu_period_us', 'sensor_accel', 'sensor_gyro', 'sensor_gravity',
'gnss_hardware', 'started_ms', 'ended_ms'):
if key in meta:
rep.line(f' {key:15} {meta[key]}')
if int(meta.get('schema_version', '1')) < 2:
rep.verdict('FAIL', 'schema version below 2: recorded before sensor fusion logging existed')
if meta.get('fusion_logging') != 'true':
rep.verdict('FAIL', 'fusion_logging is not on: turn on Settings > Ride > Record motion sensors before starting the log')
if 'ended_ms' not in meta:
rep.verdict('WARN', 'no ended_ms: the log was not stopped cleanly (app killed?); data up to the last batch is still usable')
return meta
def check_imu(db, rep):
rep.line('imu')
spans = {}
for sensor in IMU_SENSORS:
t = [r[0] for r in db.execute('SELECT elapsed_ns FROM imu WHERE sensor=? ORDER BY id', (sensor,))]
if not t:
level = 'WARN' if sensor == 'gravity' else 'FAIL'
rep.line(f' {sensor:8} no samples')
rep.verdict(level, f'imu {sensor}: no samples')
continue
backwards = sum(1 for a, b in zip(t, t[1:]) if b <= a)
ts = sorted(t)
dts = [(b - a) / 1e6 for a, b in zip(ts, ts[1:]) if b > a]
span_s = (ts[-1] - ts[0]) / 1e9
rate = (len(ts) - 1) / span_s if span_s > 0 else 0.0
max_gap = max(dts) if dts else 0.0
gaps = sum(1 for d in dts if d > IMU_GAP_WARN_MS)
spans[sensor] = (ts[0], ts[-1])
rep.line(f' {sensor:8} {len(ts):8d} samples over {span_s:7.1f} s = {rate:6.1f} Hz, '
f'dt median {statistics.median(dts):5.2f} ms, p99 {pct(dts, 99):6.2f} ms, max {max_gap:7.1f} ms, '
f'{gaps} gaps > {IMU_GAP_WARN_MS:.0f} ms, {backwards} out of order')
if not IMU_RATE_MIN_HZ <= rate <= IMU_RATE_MAX_HZ:
rep.verdict('WARN', f'imu {sensor}: {rate:.1f} Hz, expected about 100')
if max_gap > IMU_GAP_FAIL_MS:
rep.verdict('FAIL', f'imu {sensor}: a gap of {max_gap / 1000:.1f} s (screen off without the log service? app paused?)')
elif gaps:
rep.verdict('WARN', f'imu {sensor}: {gaps} gaps over {IMU_GAP_WARN_MS:.0f} ms')
if backwards:
rep.verdict('WARN', f'imu {sensor}: {backwards} samples not after the previous one in write order')
# Magnitudes: accelerometer and gravity should average to g; the gyroscope tells how much it turned.
mags = [math.sqrt(x * x + y * y + z * z) for x, y, z in
db.execute('SELECT x, y, z FROM imu WHERE sensor=?', (sensor,))]
unit = 'rad/s' if sensor == 'gyro' else 'm/s^2'
rep.line(f' {"":8} |v| median {statistics.median(mags):.3f} {unit}, p95 {pct(mags, 95):.3f}')
if sensor in ('accel', 'gravity') and abs(statistics.median(mags) - G) > 0.5:
rep.verdict('WARN', f'imu {sensor}: median magnitude {statistics.median(mags):.2f}, expected about {G:.2f}')
return spans
def check_gnss(db, rep, imu_spans):
rep.line('gnss')
sources = [r[0] for r in db.execute('SELECT DISTINCT source FROM gnss ORDER BY source')]
by_source = {}
imu_t = [r[0] for r in db.execute("SELECT elapsed_ns FROM imu WHERE sensor='gyro' ORDER BY elapsed_ns")]
for src in sources:
rows = list(db.execute(
'SELECT ts_ms, fix_ms, elapsed_ns, lat, lon, accuracy_m, speed_mps, speed_accuracy_mps, '
'bearing_accuracy_deg, provider FROM gnss WHERE source=? ORDER BY id', (src,)))
by_source[src] = rows
fix_ms = [r[1] for r in rows]
dts = [(b - a) / 1000 for a, b in zip(fix_ms, fix_ms[1:]) if b > a]
acc = [r[5] for r in rows if r[5] is not None]
latency = [r[0] - r[1] for r in rows]
with_elapsed = sum(1 for r in rows if r[2] is not None)
with_speed_acc = sum(1 for r in rows if r[7] is not None)
with_bearing_acc = sum(1 for r in rows if r[8] is not None)
providers = sorted({r[9] for r in rows if r[9]})
rate = 1 / statistics.median(dts) if dts else 0.0
rep.line(f' {src:9} {len(rows):6d} fixes, interval median {statistics.median(dts) if dts else 0:5.2f} s '
f'({rate:4.1f} Hz), max {max(dts) if dts else 0:6.1f} s, accuracy median '
f'{statistics.median(acc) if acc else float("nan"):5.1f} m p95 {pct(acc, 95) if acc else float("nan"):5.1f} m')
rep.line(f' {"":9} received after the fix: median {statistics.median(latency):.0f} ms, p95 {pct(latency, 95):.0f} ms; '
f'elapsed_ns {with_elapsed}/{len(rows)}, speed accuracy {with_speed_acc}, bearing accuracy {with_bearing_acc}; '
f'provider {", ".join(providers) or "-"}')
if dts and max(dts) > GNSS_GAP_WARN_S:
rep.verdict('WARN', f'gnss {src}: a gap of {max(dts):.1f} s between fixes')
if src in ('phone', 'phone_gps') and with_elapsed < len(rows):
rep.verdict('FAIL', f'gnss {src}: {len(rows) - with_elapsed} fixes without elapsed_ns, which fusion lines up on')
if src in ('phone', 'phone_gps') and imu_t:
inside = sum(1 for r in rows if r[2] is not None and imu_t[0] <= r[2] <= imu_t[-1])
covered = sum(1 for r in rows if r[2] is not None and _near(imu_t, r[2], 20_000_000))
rep.line(f' {"":9} {inside}/{len(rows)} fixes inside the gyro recording, {covered} with a gyro sample within 20 ms')
if inside and covered < inside:
rep.verdict('WARN', f'gnss {src}: {inside - covered} fixes inside the recording with no gyro sample within 20 ms')
for needed in ('phone', 'phone_gps'):
if needed not in by_source:
rep.verdict('FAIL', f'gnss: no {needed} fixes'
+ (' (location permission? GPS off?)' if needed == 'phone_gps' else ''))
if 'phone' in by_source and 'phone_gps' in by_source:
compare_sources(rep, by_source['phone_gps'], by_source['phone'], 'phone_gps vs phone (fused)')
if 'obu' in by_source and 'phone_gps' in by_source:
compare_sources(rep, by_source['phone_gps'], by_source['obu'], 'phone_gps vs obu', key=1, tol_ms=500)
def _near(sorted_t, t, tol):
i = bisect_left(sorted_t, t)
return any(0 <= j < len(sorted_t) and abs(sorted_t[j] - t) <= tol for j in (i - 1, i))
def compare_sources(rep, a_rows, b_rows, label, key=2, tol_ms=500):
"""Horizontal distance between two sources' fixes taken at about the same time (key: 2 = elapsed_ns, 1 = fix_ms)."""
scale = 1_000_000 if key == 2 else 1
b = sorted((r[key], r[3], r[4]) for r in b_rows if r[key] is not None)
bt = [x[0] for x in b]
d = []
for r in a_rows:
if r[key] is None:
continue
i = bisect_left(bt, r[key])
best = min((j for j in (i - 1, i) if 0 <= j < len(b)), key=lambda j: abs(bt[j] - r[key]), default=None)
if best is not None and abs(bt[best] - r[key]) <= tol_ms * scale:
d.append(haversine_m(r[3], r[4], b[best][1], b[best][2]))
if d:
rep.line(f' {label}: {len(d)} pairs within {tol_ms} ms, distance median {statistics.median(d):.1f} m, '
f'p95 {pct(d, 95):.1f} m, max {max(d):.1f} m')
def check_clock(db, rep):
rep.line('clock')
rows = list(db.execute('SELECT elapsed_ns, wall_ms, gnss_ms FROM clock ORDER BY id'))
if not rows:
rep.verdict('FAIL', 'clock: no rows')
return
with_gnss = [r for r in rows if r[2] is not None]
# Wall clock against the monotonic clock: a step shows up as a jump in their difference.
off = [r[1] - r[0] / 1e6 for r in rows]
steps = [(b - a) for a, b in zip(off, off[1:]) if abs(b - a) > 100]
rep.line(f' {len(rows)} rows, {len(with_gnss)} with GNSS time')
if with_gnss:
err = [r[1] - r[2] for r in with_gnss]
rep.line(f' phone clock minus GNSS time: median {statistics.median(err):+.0f} ms, '
f'range {min(err):+.0f} .. {max(err):+.0f} ms')
else:
rep.verdict('WARN', 'clock: no GNSS time at all (no fix for the whole log?)')
if steps:
rep.line(f' phone clock stepped {len(steps)} times: ' + ', '.join(f'{s:+.0f} ms' for s in steps[:10]))
rep.verdict('WARN', f'clock: the phone clock stepped {len(steps)} times; use elapsed_ns and the clock table, not ts_ms, to line data up')
def check(path):
rep = Report()
print(f'== {path}')
db = sqlite3.connect(f'file:{Path(path).as_posix()}?mode=ro', uri=True)
have = tables(db)
if 'meta' not in have:
rep.verdict('FAIL', 'not a MicrOBU V2X log (no meta table)')
else:
check_meta(db, rep)
if not {'imu', 'clock'} <= have:
rep.verdict('FAIL', 'no imu/clock tables: recorded with an app from before sensor fusion logging')
else:
spans = check_imu(db, rep)
check_gnss(db, rep, spans)
check_clock(db, rep)
db.close()
for level, text in rep.verdicts:
print(f'{level}: {text}')
if not rep.verdicts:
print('PASS: ready for sensor fusion')
elif not any(level in ('FAIL', 'WARN') for level, _ in rep.verdicts):
print('PASS')
print()
return rep.failed
def main(argv):
if not argv:
print(__doc__)
return 2
failed = [p for p in argv if check(p)]
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
+96
View File
@@ -0,0 +1,96 @@
"""Adds MAPEMs to the list the app ships with (app/src/main/assets/mapem/hamburg.txt).
py -3.11 tools/mapem_bundle.py FILE [FILE ...]
FILE is either
- a .db saved by the app's V2X data logger (its MAPEM rows are taken), or
- a text file with one UPER MAPEM per line as hex (`#hex <hex>` lines, as in the test corpus, too).
The list keeps what it already has and gains one entry per intersection and revision. A MAPEM of an
intersection and revision already listed replaces that entry. Review the printed changes, run the
unit tests, rebuild the app. Needs asn1tools (the ETSI modules in asn1/).
"""
import re
import sqlite3
import sys
from pathlib import Path
import asn1tools
ROOT = Path(__file__).resolve().parent.parent
ASN = ROOT / 'asn1'
OUT = ROOT / 'app/src/main/assets/mapem/hamburg.txt'
HEADER = ['# Stored MAPEMs. One UPER MAPEM per line, hex, each below a comment naming its intersections.',
'# Written by tools/mapem_bundle.py; add to it with that script.']
HEX = re.compile(r'(?:#hex )?((?:[0-9a-fA-F]{2})+)$')
def read_hex_lines(path):
for line in path.read_text(encoding='utf-8').splitlines():
found = HEX.match(line.strip())
if found:
yield bytes.fromhex(found[1])
def read_log(path):
db = sqlite3.connect(f'file:{path.resolve().as_posix()}?mode=ro', uri=True)
try:
for (payload,) in db.execute("select distinct payload from messages where msg_type = 'MAPEM'"):
yield bytes(payload)
finally:
db.close()
def add(entries, spec, uper, source):
"""Puts [uper] into entries {(key, revision): (uper, label)}; returns the keys that changed."""
try:
decoded = spec.decode('MAPEM', uper)
except Exception as error: # asn1tools raises several types
print(f' skipped a message from {source} that does not decode: {error}')
return []
changed = []
for i in decoded['map'].get('intersections', []):
key = (f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision'])
if key not in entries or entries[key][0] != uper:
changed.append((key, 'replaced' if key in entries else 'added', i.get('name')))
entries[key] = (uper, i.get('name'))
return changed
def main(files):
if not files:
raise SystemExit(__doc__)
spec = asn1tools.compile_files([str(ASN / n) for n in
('spatem_2_2_1.asn', 'mapem_2_2_1.asn', 'dsrc_2_2_1.asn', 'cdd_2_2_1.asn')], 'uper')
entries = {}
if OUT.exists():
for uper in read_hex_lines(OUT):
add(entries, spec, uper, OUT.name)
for name in files:
path = Path(name)
if not path.is_file():
raise SystemExit(f'{name}: no such file')
reader = read_log if path.suffix.lower() == '.db' else read_hex_lines
changed = [c for uper in reader(path) for c in add(entries, spec, uper, path.name)]
print(f'{path.name}: {len(changed)} change(s)')
for (key, revision), what, label in changed:
print(f' {what} {key} rev {revision} {label}')
body = []
written = set()
for (key, revision), (uper, _) in sorted(entries.items()):
if uper in written:
continue
written.add(uper)
body += [f'# {k} rev {r} {label}' for (k, r), (u, label) in sorted(entries.items()) if u == uper]
body.append(uper.hex())
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text('\n'.join(HEADER + body) + '\n', encoding='utf-8', newline='\n')
print(f'{OUT.relative_to(ROOT)}: {len(entries)} intersection revisions, '
f'{len({k for k, _ in entries})} intersections')
if __name__ == '__main__':
main(sys.argv[1:])
+81
View File
@@ -0,0 +1,81 @@
"""Which received ITS messages did the phone get, by size? Compares a V2X log (schema 3, ESP32-C5) with a
pcap recorded at the same time by another receiver (the CiT node's its5_*.pcap, linktype 105 or 127).
# 1. unwrap the capture with the firmware's own code (obu-firmware/test/host, MSYS2 gcc on PATH):
# gcc -std=c11 -O2 -I../../main -I. -o test_replay test_replay.c test_util.c \
# ../../main/geonet.c dot11p.c ../../main/gn_unwrap.c
# test_replay replay.tsv capture.pcap
# 2. py -3.11 tools/rx_size_compare.py LOG.db capture.pcap replay.tsv
Written for the 2026-11-23 bench run: the node sent a 377-byte MAPEM and a 58-byte SPATEM, then an 1198-byte
MAPEM and an 888-byte SPATEM, and the phone received only the small ones (the firmware dropped everything over
494 bytes). Run it again after the V2X_RX fragmentation to see the large ones arrive.
The pcap clock is the capture device's own (often seconds since its boot, and it can wrap), so it is aligned to
the phone's wall clock through the CAMs both received byte for byte. A message counts as received when the
phone logged the same message type with identical payload bytes within 1 s of it. The pcap receiver is a
different antenna in a different place, so even small messages sit below 100 %: compare sizes with each other.
"""
import collections
import csv
import sqlite3
import statistics
import struct
import sys
NAMES = {2001: 'CAM', 2002: 'DENM', 2003: 'MAPEM', 2004: 'SPATEM', 2018: 'VAM'}
WINDOW_S = 1.0
def pcap_times(path):
data = open(path, 'rb').read()
little = struct.unpack('<I', data[:4])[0] in (0xA1B2C3D4, 0xA1B23C4D)
e = '<' if little else '>'
nano = struct.unpack(e + 'I', data[:4])[0] in (0xA1B23C4D,)
out, off = [], 24
while off + 16 <= len(data):
s, us, incl, _ = struct.unpack(e + 'IIII', data[off:off + 16])
out.append(s + us / (1e9 if nano else 1e6))
off += 16 + incl
return out
def main(log, pcap, tsv):
times = pcap_times(pcap)
heard = []
for r in csv.DictReader(open(tsv), delimiter='\t'):
if r['accepted'] == '1' and int(r['port']) in NAMES:
heard.append((times[int(r['record'])], int(r['port']), bytes.fromhex(r['payload'])))
con = sqlite3.connect('file:%s?mode=ro' % log.replace('\\', '/'), uri=True)
phone = con.execute('select ts_ms, msg_type, payload from messages order by ts_ms, id').fetchall()
meta = dict(con.execute('select key, value from meta').fetchall())
if not phone:
raise SystemExit('the log holds no messages')
seen = collections.defaultdict(list)
for ts, kind, payload in phone:
seen[(kind, bytes(payload))].append(ts / 1000)
cams = {k[1]: v[0] for k, v in seen.items() if k[0] == 'CAM' and len(v) == 1}
offsets = [cams[p] - t for t, port, p in heard if port == 2001 and p in cams]
if len(offsets) < 20:
raise SystemExit('only %d CAMs in common: cannot align the two clocks' % len(offsets))
off = statistics.median(offsets)
print('log: %s, hardware %s; %d messages; clock offset %.3f s (spread %.0f ms over %d shared CAMs)'
% (log, meta.get('hardware'), len(phone), off, 1000 * statistics.pstdev(offsets), len(offsets)))
first, last = phone[0][0] / 1000, phone[-1][0] / 1000
table = collections.defaultdict(lambda: [0, 0])
for t, port, p in heard:
t += off
if not first - WINDOW_S <= t <= last + WINDOW_S:
continue
key = (NAMES[port], len(p))
table[key][0] += 1
table[key][1] += any(abs(x - t) < WINDOW_S for x in seen.get((NAMES[port], p), ()))
print('%-7s %6s %9s %9s %7s' % ('type', 'bytes', 'on air', 'phone', 'share'))
for (kind, size), (n, got) in sorted(table.items()):
print('%-7s %6d %9d %9d %6.1f%%' % (kind, size, n, got, 100.0 * got / n))
if __name__ == '__main__':
if len(sys.argv) != 4:
raise SystemExit(__doc__)
main(*sys.argv[1:])