Compare commits

..
2 Commits
Author SHA1 Message Date
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
44 changed files with 9243 additions and 2305 deletions
+5
View File
@@ -88,3 +88,8 @@ obu-firmware/docs/*.synctex.gz
/.vscode/ /.vscode/
obu-firmware/docs/*.synctex* 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/*/
+89
View File
@@ -5,6 +5,95 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware ## Waiting on hardware
### 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) ### 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, Settings > Ride (phone position, Record motion sensors) and the fusion data in the V2X data logger,
@@ -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`: * 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. * 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: * 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, * - `TimeChangeDetails` is **not** extensible, so it has 5 optional bits and no extension bit,
* unlike almost every other SEQUENCE here, which all carry one. * 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. * exactly, with no message hitting an unsupported branch.
* *
* Returns null rather than guessing whenever an extension bit is set or an unsupported optional * 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. * the wrong light.
*/ */
object SpatemUperCodec { object SpatemUperCodec {
@@ -73,9 +77,7 @@ object SpatemUperCodec {
val hasName = br.getBitsInt(1) == 1 val hasName = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1 val hasRegional = br.getBitsInt(1) == 1
val minuteOfYear = if (hasTimeStamp) br.getBitsInt(20) else null val minuteOfYear = if (hasTimeStamp) br.getBitsInt(20) else null
// DescriptiveName is a variable-length IA5String. Nothing in 79k real messages uses it, if (hasName) skipName(br)
// and guessing its length would desynchronise everything after it.
if (hasName) return null
val intersectionCount = br.getBitsInt(5) + 1 val intersectionCount = br.getBitsInt(5) + 1
if (intersectionCount > MAX_INTERSECTIONS) return null if (intersectionCount > MAX_INTERSECTIONS) return null
@@ -102,7 +104,7 @@ object SpatemUperCodec {
val hasEnabledLanes = br.getBitsInt(1) == 1 val hasEnabledLanes = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1 val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = 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. // IntersectionReferenceID - not extensible, one optional bit for region.
val region = if (br.getBitsInt(1) == 1) br.getBitsInt(16) else null 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 hasName = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1 val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1 val hasRegional = br.getBitsInt(1) == 1
if (hasName) return null if (hasName) skipName(br)
val signalGroup = br.getBitsInt(8) val signalGroup = br.getBitsInt(8)
val eventCount = br.getBitsInt(4) + 1 val eventCount = br.getBitsInt(4) + 1
@@ -162,7 +164,8 @@ object SpatemUperCodec {
if (hasConfidence) br.getBits(4) if (hasConfidence) br.getBits(4)
if (hasNext) br.getBits(16) 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)) events.add(SignalPhaseEvent(phase, minEnd, maxEnd, likely))
} }
@@ -171,6 +174,41 @@ object SpatemUperCodec {
return SignalMovement(signalGroup, events) 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 * 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. * list is variable-length, so it has to be parsed to find where the next field starts.
@@ -3,6 +3,7 @@ package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.LinkMessage import com.hawhamburg.micr0bu.data.transport.LinkMessage
import com.hawhamburg.micr0bu.data.transport.LinkReassembly import com.hawhamburg.micr0bu.data.transport.LinkReassembly
import com.hawhamburg.micr0bu.data.transport.RawFrame import com.hawhamburg.micr0bu.data.transport.RawFrame
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse import org.junit.Assert.assertFalse
@@ -100,6 +101,61 @@ class LinkReassemblyTest {
assertArrayEquals(bytes(9, 9, 8, 8), b.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 ------------------------------------------------------------------ // ---- RAW_FRAME record ------------------------------------------------------------------
private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray { private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray {
@@ -153,6 +153,34 @@ class SpatemUperCodecTest {
assertNull(SignalPhaseEvent(SignalPhase.DARK, null, null, null).secondsUntil(topOfHour)) 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 @Test
fun `does not decode another message type as SPATEM`() { fun `does not decode another message type as SPATEM`() {
// protocolVersion 2, messageId 2 (CAM) - the header guard must reject it outright. // protocolVersion 2, messageId 2 (CAM) - the header guard must reject it outright.
@@ -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
+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.
+11 -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 (`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 (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 `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 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM, 2018 VAM pass. A message up to 494 bytes is one link
512-octet link message and is dropped and counted (not fragmented). 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 - **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 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 `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). - **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 - **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 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 - **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 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. rotates in the app; the app now rotates the MAC with it on a ride and keeps one fixed for the bench pinger.
+2 -2
View File
@@ -90,7 +90,7 @@ 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 battery) and the first V2X_RX messages. Status exchange: the host sends `STATUS_REQUEST` every
1000 ms; `CONFIRM.detail` contains the snapshot. 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, up to 494 octets) 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`. See [NOTES.md](NOTES.md). 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`. See [NOTES.md](NOTES.md).
```mermaid ```mermaid
flowchart LR flowchart LR
@@ -99,7 +99,7 @@ flowchart LR
Radio --> Unwrap[gn_unwrap.c: 802.11, LLC, GN, BTP, signature envelope] 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] Radio -->|only while RAW_CAPTURE is on| Cap[Raw capture tap: ITS5 record]
Stack -->|verified only| Ind[BTP_DATA_INDICATION 0x81] Stack -->|verified only| Ind[BTP_DATA_INDICATION 0x81]
Unwrap -->|always, signed or not, up to 494 octets| Rx[V2X_RX 0x90, MicrOBU] Unwrap -->|always, signed or not, fragmented above 494 octets| Rx[V2X_RX 0x90, MicrOBU]
Cap -->|fragmented if large| Raw[RAW_FRAME 0x85, spec] Cap -->|fragmented if large| Raw[RAW_FRAME 0x85, spec]
Ind --> Link[Station link: USB or BLE] Ind --> Link[Station link: USB or BLE]
Rx --> Link Rx --> Link
Binary file not shown.
+102
View File
@@ -0,0 +1,102 @@
\documentclass[10pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}
\usepackage[a4paper,left=18mm,right=18mm,top=18mm,bottom=18mm,headheight=13pt]{geometry}
\usepackage{xcolor}
\usepackage{array,longtable,booktabs}
\usepackage{fancyhdr,lastpage,needspace}
\usepackage[hidelinks]{hyperref}
\definecolor{ink}{HTML}{193447}
\setlength{\parindent}{0pt}
\setlength{\parskip}{4pt}
\setlength{\tabcolsep}{1.5mm}
\renewcommand{\arraystretch}{1.12}
\setlength{\emergencystretch}{3em}
\newcolumntype{P}[1]{>{\raggedright\arraybackslash}p{#1}}
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[L]{\footnotesize Overnight bench test of the micrOBU firmware}
\fancyfoot[R]{\footnotesize\thepage\ / \pageref{LastPage}}
\renewcommand{\headrulewidth}{0pt}
\hypersetup{pdftitle={Overnight bench test of the micrOBU firmware}}
\newcommand{\cmd}[1]{\texttt{\small #1}}
\begin{document}
{\Large\bfseries\color{ink} Overnight bench test of the micrOBU firmware}\par
\smallskip
Status: 2026-11-25. Scripts: \cmd{obu-firmware/test/bench}. Companion documents: \cmd{obu-firmware/test/bench/README.md}, \cmd{obu-firmware/test/host/README.md}, \cmd{obu-firmware/FLASHING.md}.\par
\section*{1\quad Purpose}
The test checks the integrity and function of \cmd{obu-firmware} on a real board over many hours, without a phone. A PC plays the phone over the USB station link, drives every kind of request, resets and reconfigures the board, listens to the air, and watches the board's own counters and heap. A second, board-free part runs the PC-side C tests and a long fuzz of the receive parser.
\section*{2\quad Boards}
\begin{longtable}{@{}P{22mm}P{32mm}P{108mm}@{}}
\toprule\textbf{Port (lab)} & \textbf{Board} & \textbf{Role}\\\midrule\endhead
COM10 & XIAO ESP32-C5 with cell & production OBU. Never used for this test.\\
\textbf{COM6} & XIAO ESP32-C5, no cell & \textbf{spare board: the board under test}, also taken home.\\
COM4 & ESP32-C5 & V2X node (a second station on the air).\\
COM8 & CH343 board & simulated car (CAM beacon).\\\bottomrule
\end{longtable}
The spare's single USB-C port is the chip's native USB Serial/JTAG (VID 303A, PID 1001). \textbf{Opening the port resets the board}, so nothing else may hold it (phone app, \cmd{station\_status\_watch.py}, serial monitor). A board without a cell still reports about 4000\,mV in \cmd{battery\_mv} (the USB charger node), so the battery value cannot tell the spare from the production board: plug in only the spare. The run writes the demo ticket to the board's NVS.
\section*{3\quad What a run does}
Every run starts and ends with the conformance stage, so drift shows as a different result. In between, cycles of about 45 minutes repeat until the time is up.
\begin{longtable}{@{}P{30mm}P{132mm}@{}}
\toprule\textbf{Stage} & \textbf{What it checks}\\\midrule\endhead
conformance & about 100 checks of the link protocol against the specification and the firmware source: opcodes, malformed lengths, fragment reassembly (1536-octet requests, gaps, 2\,s timeout, 8 pending), CRC and resynchronisation, configure and POTI, BTP requests, stale requests, counter wrap.\\
soak-unsigned & BTP requests at 4\,Hz, payload 24 to 1480 octets in turn (494 and 495 are the V2X\_RX edge). Every accepted request must leave the radio byte for byte, with the MAC the phone named. 40 refusals (\cmd{resource\_limit}) in a row end the phase as ``transmit path wedged'', and a repeated configure is tried.\\
soak-signed & the same at 3\,Hz up to 1200 octets, signed with the demo chain; \cmd{sign\_failed} must stay 0.\\
raw-toggle & \cmd{RAW\_CAPTURE} modes 0x00, 0x01, 0x03, 0x05, 0x07 in turn: copies of the station's own frames must appear exactly in the modes with the own-TX bit.\\
reconfigure & \cmd{STATION\_CONFIGURE} every second or two with a new MAC, security on or off, radio TX+RX or RX only; the next frame must carry the new MAC and security.\\
fuzz & the board is reset, then seeded random frames are sent while it is unconfigured, so nothing reaches the radio. Heap afterwards must be within 8\,KB.\\
resets & the port is reopened five times; each time the board must boot, come back unconfigured, configure and transmit.\\
idle-listen & radio receive-only, STATUS once a second; counts what else is on the air and checks the receive queue never overflows.\\\bottomrule
\end{longtable}
\textbf{How a transmitted frame is proven.} One board has no second receiver, so the test uses \cmd{RAW\_CAPTURE} mode 0x05: every frame the station submits to the radio is copied back over the link. The copy is unwrapped by a Python port of \cmd{gn\_unwrap.c} written separately from the firmware, and its ITS payload is compared with what was sent. The payload carries its own size and CRC-32. This does not prove that another station can hear the frame.
\textbf{On the air.} Transmit phases send at most 4 frames per second at 5\,dBm on channel 180. The payload is a made-up ItsPduHeader with messageID \cmd{0xF1}, which is not an assigned ETSI message, so receivers refuse it. MACs are locally administered, \cmd{02:b3:0a:ce:xx:xx}. \cmd{--no-tx} keeps the radio silent.
\textbf{PC-side tests} (\cmd{run\_host\_tests\_overnight.ps1}, no board): \cmd{make check} of \cmd{test/host} (chain test, replay of recorded captures, fuzz, battery policy, 40 firmware unit tests, fragments), then the \cmd{gn\_unwrap} fuzzer with new seeds until the time is up. A \cmd{CRASH} line or a non-zero exit is a failure.
\section*{4\quad Running it}
Close everything that holds the port, run \cmd{git pull}, then from the repository root:
\begin{center}\small\texttt{powershell -ExecutionPolicy Bypass -File obu-firmware\textbackslash test\textbackslash bench\textbackslash start\_overnight.ps1 -Flash -Hours 8}\end{center}
\begin{longtable}{@{}P{34mm}P{128mm}@{}}
\toprule\textbf{Option} & \textbf{Effect}\\\midrule\endhead
\cmd{-Flash} & builds this checkout with ESP-IDF 6.0.2 and writes it to the board first (first build about 20 minutes: components are downloaded).\\
\cmd{-Quick} & about 8 minutes on the board, no host fuzz: does it all work?\\
\cmd{-Port COMx} & names the board; the default finds the one Espressif USB board plugged in and refuses if there are several.\\
\cmd{-NoTx} & the radio stays silent: protocol, fuzz, resets and idle only.\\
\cmd{-NoHostTests} & skips the PC-side C tests.\\\bottomrule
\end{longtable}
The script keeps Windows awake while it runs. \cmd{run\_overnight.py} refuses a board whose firmware is not this checkout's HEAD (\cmd{--allow-stale-firmware} overrides), because the results would then describe another build. Exit status: 0 if no check failed, 1 otherwise, 2 if the board does not speak the station link.
\section*{5\quad Setting up the workstation}
\cmd{setup\_workstation.ps1 -CheckOnly} reports what is missing; without \cmd{-CheckOnly} it installs it (about 3\,GB, 20 to 40 minutes, internet needed). It can be run again after a failure.
\begin{longtable}{@{}P{44mm}P{62mm}P{56mm}@{}}
\toprule\textbf{Needed} & \textbf{Why} & \textbf{Installed as}\\\midrule\endhead
Git, \cmd{core.longpaths true} & \cmd{git pull}; ESP-IDF paths exceed 260 characters & winget \cmd{Git.Git}\\
Python 3.11 (\cmd{py -3.11}) & board tests, \cmd{check\_replay.py} & winget \cmd{Python.Python.3.11}\\
\cmd{pyserial} & the station link & \cmd{pip install --user}\\
\cmd{asn1tools} & host replay check only & \cmd{pip install --user}\\
MSYS2 UCRT64 \cmd{gcc}, \cmd{make} & PC-side C tests & winget \cmd{MSYS2.MSYS2}, then pacman\\
\textbf{ESP-IDF 6.0.2}, esp32c5, in \cmd{C:\textbackslash Espressif} & build and flash; exactly this version, because \cmd{components/microbu\_v2x} pins the radio driver ABI to it & \cmd{git clone --branch v6.0.2 --recursive}, then \cmd{install.ps1 esp32c5}\\\bottomrule
\end{longtable}
Nothing to install for the board itself: the native USB port uses the Windows built-in driver. Internet is needed on the first build (\cmd{espressif/esp-boost}, about 125\,MB, into \cmd{managed\_components/}). \cmd{setup\_workstation.ps1 -PreventSleep} turns off sleep, hibernate, display-off and USB selective suspend on mains power; a suspended USB port drops the board. Pause Windows Update and use mains power.
Not in git, so absent on a fresh checkout: \cmd{its-g5-receiver-firmware/recordings/*.pcap} (the host replay test then skips itself), \cmd{vanetza/} (\cmd{check\_replay.py} then does not decode the 1609.2 envelopes independently) and \cmd{firmware-backups/}.
\textbf{Flashing trouble.} If the flash reports ``No serial data received'': unplug the board, hold BOOT, plug in, release, flash again, then unplug and replug without BOOT. If the flasher stub does not start, use the \cmd{--no-stub} recipe in \cmd{FLASHING.md}.
\section*{6\quad Reading the result}
Results go to \cmd{obu-firmware/test/results/overnight-<time>/}: \cmd{report.txt} (read this), \cmd{results.json}, \cmd{status.csv} (STATUS every few seconds), \cmd{device.log}, \cmd{boot.log} (ROM text and panics), \cmd{run.log}. \textbf{FAIL} contradicts the specification, the source or what the radio did. \textbf{WARN} is a disagreeing counter, a heap trend or a version mismatch. \textbf{INFO} is something the source leaves open, with the observed value. A fuzz failure prints its seed; replay it with \cmd{--fuzz-seed N}. Heap leaks are judged per phase over readings without a reset in between (warning below $-2$\,KB per hour, failure below $-20$\,KB per hour), and the lowest heap ever seen must stay above 16\,KB.
\section*{7\quad Findings so far}
\textbf{Overnight run 2026-11-25 (6.3\,h, home workstation, stale build).} The board ran \cmd{1c3a66e-dirty} of 10 November, which predates the pseudonym MAC commit \cmd{3770754}, because the workstation had no ESP-IDF to flash a current build. 1278 checks passed and 802 failed. About 790 failures are the frame source MAC not being the one named in \cmd{STATION\_CONFIGURE}, explained by the stale build. Two things stand out: in 4 of 11 cycles the unsigned soak accepted about 17 requests and then refused all 2383 others with \cmd{resource\_limit} while \cmd{radio\_failed} rose by the same number (heap stayed healthy; a later configure cleared it), and one of 50 resets ended in a boot panic (illegal instruction in \cmd{app\_main}, 0.39\,s after boot). The heap showed no leak (lowest 49\,736 octets). Nothing else was heard on the air.
\textbf{Quick run 2026-11-25 on the spare, current build \cmd{ce18a39}.} 217 passed, 0 failed, 1 warning (one frame from the board with a bad CRC). The MAC failures are gone. One test bug was fixed on the way: the check ``refused requests put nothing on the radio'' counted frames heard from other stations; it now counts only the station's own transmissions. The wedge and the boot panic were not reproduced in 8 minutes and need the full overnight run.
\section*{Revision history}
Revision 1, 2026-11-25: first version, written with the move of the overnight test to the spare board.
\end{document}
File diff suppressed because it is too large Load Diff
+27 -9
View File
@@ -21,15 +21,15 @@
\newcolumntype{F}{@{}|P{12mm}|P{43mm}|P{36mm}|P{25mm}|P{48.15mm}|@{}} \newcolumntype{F}{@{}|P{12mm}|P{43mm}|P{36mm}|P{25mm}|P{48.15mm}|@{}}
\pagestyle{fancy} \pagestyle{fancy}
\fancyhf{} \fancyhf{}
\fancyfoot[L]{\footnotesize Document revision 2 (MicrOBU)} \fancyfoot[L]{\footnotesize Document revision 3 (MicrOBU)}
\fancyfoot[R]{\footnotesize\thepage\ / \pageref{LastPage}} \fancyfoot[R]{\footnotesize\thepage\ / \pageref{LastPage}}
\renewcommand{\headrulewidth}{0pt} \renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{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} \begin{document}
microbu station link interface reference, revision 2 (MicrOBU)\par microbu station link interface reference, revision 3 (MicrOBU)\par
\vspace{3mm} \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 The maximum link message is 512 bytes, including the four-byte header.\par\smallskip
USB Serial/JTAG and BLE GATT carry the same messages. USB Serial/JTAG and BLE GATT carry the same messages.
The host sends a status request as a link heartbeat.\par\smallskip 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 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. \\ {\ttfamily 14} & {\ttfamily frame} & {\ttfamily bytes[\allowbreak{}frame\_\allowbreak{}length]} & \textemdash & Contains the raw radio-frame bytes. \\
\end{longtable}} \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. 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}} \Needspace{8\baselineskip}\subsection{{\ttfamily V2X\_\allowbreak{}RX}}
{\small\color{ink}\textbf{0x90}\quad STATION TO HOST \quad (MicrOBU extension)} {\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\endfirsthead
\toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endhead \toprule\textbf{Parameter} & \textbf{Setting} & \textbf{Description} \\\midrule\endhead
\bottomrule\endfoot \bottomrule\endfoot
{\ttfamily reply} & {\ttfamily none} & One-way indication, not 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 494 bytes} & 512 minus the four-byte header and the 14-byte prefix. A longer message is dropped and counted, never fragmented. \\ {\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 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. \\ {\ttfamily availability} & {\ttfamily from configure} & The radio is polled from STATION\_CONFIGURE on, before the first POTI\_UPDATE. \\
\end{longtable}} \end{longtable}}
@@ -1177,10 +1177,27 @@ Delivers every ITS message heard on air, verified or not. The station stack deca
\Needspace{8\baselineskip}\subsection{\texttt{V\_\allowbreak{}2X\_\allowbreak{}RX} and \texttt{RAW\_\allowbreak{}FRAME}: both stay}\label{sec:microbu-rxpaths} \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. 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} \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; the message is at most 494 octets and is never fragmented. \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, and accepts that copies may be dropped when the transport is busy. \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} \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}. 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} \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. 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} \Needspace{8\baselineskip}\subsection{Unsecured transmission}\label{sec:microbu-unsecured}
@@ -1235,5 +1252,6 @@ MicrOBU extension. While no USB host is connected to the native port (the phone
\bottomrule\endfoot \bottomrule\endfoot
1 & 2026-11 & Niklas Dathe: the microbu-firmware interface reference, commit e4e4bd8. \\ 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; 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. \\ 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{longtable}}
\end{document} \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 // only this path). Other ports are dropped. The link message itself is generic: the port says what
// the payload is. // the payload is.
// //
// Size caveat: a link message is at most 512 octets (link::maximum_message, which is also the // Size: a link message is at most 512 octets (link::maximum_message, which is also the largest
// largest GATT attribute value), so Station::forward_raw() drops a message whose UPER exceeds // GATT attribute value), so a UPER up to 494 bytes goes to the phone as one V2X_RX message. A larger
// 494 bytes and counts it as oversize instead of forwarding it. Nothing is fragmented. The bench // one (real road SPATEMs and MAPEMs: SPATEM 555 bytes median, 1243 max on the 2026-03-18 drive;
// RSU's messages all fit (2026-10-28 capture: SPATEM 58, MAPEM 295 bytes); real road SPATEMs and // the 2026-11-23 bench node sent 888 and 1198) is sent by Station::forward_raw() in link fragments,
// MAPEMs often do not (SPATEM 555 bytes median, 1243 max on the 2026-03-18 drive). The radio // see v2x_rx.hpp (v2x_rx_plan) and link_fragment.hpp. Only a message beyond v2x_rx_max_forward is
// itself captures frames of up to 2346 bytes (c5_radio.cpp), so `truncated` does not happen on // dropped and counted as oversize. The radio itself captures frames of up to 2346 bytes
// this firmware. // (c5_radio.cpp), so `truncated` does not happen on this firmware.
// //
// No FCS/CRC check here: the WiFi driver has already validated the frame. // No FCS/CRC check here: the WiFi driver has already validated the frame.
typedef struct { 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_service.hpp"
#include "link_fragment.hpp"
#include "simple_ble.hpp" #include "simple_ble.hpp"
#include "serial_link.hpp" #include "serial_link.hpp"
#include <esp_log.h> #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). // MicrOBU: every ITS message heard on air, verified or not (Station::on_raw_its).
station_.on_raw_its([this](const link::Bytes& body) { 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. // T_GenVam is included in the status snapshot returned on request.
station_.on_id_event([this](const link::IdChangeEvent& event) { 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}; 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 (!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 (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 serial::write(serial::FrameType::LINK, octets);
} }
return ble::write(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) { 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 limit = transport == LinkTransport::ble ? ble::max_message() : link::maximum_message;
const std::size_t chunk = limit - link::header_size; if (body.size() <= link::unfragmented_capacity(limit)) return send(transport, opcode, sequence, body);
if (body.size() <= chunk) 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
if (body.size() > 65535 || chunk <= link::fragment_header_size) return false; // MAPEM would need dozens, so beyond max_received_fragments that transport skips the message.
const std::size_t capacity = chunk - link::fragment_header_size; const std::size_t max_fragments = opcode == link::Opcode::V2X_RX ? max_received_fragments : 65535;
for (std::size_t offset = 0; offset < body.size(); offset += capacity) { std::vector<link::Fragment> fragments;
const std::size_t n = std::min(capacity, body.size() - offset); if (!link::split_fragments(body, limit, fragments, max_fragments)) return false;
const std::uint8_t flags = offset == 0 ? link::flag_fragment_first : for (const auto& fragment : fragments) {
(offset + n == body.size() ? link::flag_fragment_last : link::flag_fragment_middle); // The first failed fragment ends this message (the app drops the incomplete stream by itself); nothing is
link::Bytes part {std::uint8_t(body.size()), std::uint8_t(body.size() >> 8), // retried, and nothing here waits for the transport.
std::uint8_t(offset), std::uint8_t(offset >> 8)}; if (!send(transport, opcode, sequence, fragment.body, fragment.flags)) return false;
part.insert(part.end(), body.begin() + offset, body.begin() + offset + n);
if (!send(transport, opcode, sequence, part, flags)) return false;
} }
return true; 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. // Fragmented when needed: a MAPEM indication is larger than one message on either transport.
send_fragmented(LinkTransport::serial, opcode, sequence, body); const bool serial_taken = send_fragmented(LinkTransport::serial, opcode, sequence, body);
if (ble::connected()) send_fragmented(LinkTransport::ble, 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) { 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 opcode Message opcode.
/// @param sequence Sequence number to stamp on the header. /// @param sequence Sequence number to stamp on the header.
/// @param body Encoded message body. /// @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. /// @brief Sends a CONFIRM reply to the message's origin transport.
/// @param origin Transport to reply on. /// @param origin Transport to reply on.
/// @param sequence Sequence number of the message being replied to. /// @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) { bool try_write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock || stalled) return false; 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); const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, 0) != pdTRUE) return false; 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()); 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. // Most captured frames are not ITS traffic this handles; false is the common case, not an error.
gn_rx_t rx; gn_rx_t rx;
if (!gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx)) return; if (!gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx)) return;
const bool fits = link::v2x_rx_fits(rx); const auto plan = link::v2x_rx_plan(rx, (raw_mode_ & C5Radio::capture_on) != 0);
if (!fits) { // A message above one link message goes out in fragments (LinkService), best effort: no retry, no waiting, so
++raw_oversize_; // a lost fragment costs that message only and never the receive path.
static std::int64_t last_report = 0; // one line per 10 s at most, the counter has the rest switch (plan) {
const auto now = esp_timer_get_time(); case link::V2xRxPlan::drop: ++raw_oversize_; break;
if (now - last_report > 10000000) { case link::V2xRxPlan::covered_by_raw: ++raw_covered_; break;
last_report = now; case link::V2xRxPlan::single: ++raw_forwarded_; break;
ESP_LOGW(TAG, "V2X_RX: port %u message of %d bytes does not fit a link message (%lu dropped so far)", case link::V2xRxPlan::fragmented: ++raw_fragmented_; break;
unsigned(rx.btp_dest_port), rx.payload_len, (unsigned long)raw_oversize_); }
} if (plan == link::V2xRxPlan::single || plan == link::V2xRxPlan::fragmented) {
return; 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) { link::Code Station::unsecured_request(const link::BtpDataRequest& q) {
+6 -3
View File
@@ -30,8 +30,9 @@ public:
using Received = std::function<void()>; using Received = std::function<void()>;
/// RAW_FRAME body (u32 counter, u8 flags, i8 RSSI, ITS5 record) for the link service. /// RAW_FRAME body (u32 counter, u8 flags, i8 RSSI, ITS5 record) for the link service.
using RawFrame = std::function<void(const link::Bytes&)>; using RawFrame = std::function<void(const link::Bytes&)>;
/// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp). /// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp). Returns whether a transport took it;
using RawIts = std::function<void(const link::Bytes&)>; /// 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). /// 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&)>; using DccUpdate = std::function<void(const link::Bytes&)>;
@@ -283,7 +284,9 @@ private:
bool have_fix_ = false; bool have_fix_ = false;
link::PotiUpdate last_poti_; // MicrOBU: the GN Source Position Vector of unsecured_request() 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::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 // 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<microbu_v2x::security::SecurityModule> module_;
std::unique_ptr<vanetza::ManualRuntime> runtime_; 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). /// 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; 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. /// @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) { 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; 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. /// @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 rx Message unwrapped by gn_unwrap_its (its payload pointer must still be valid).
/// @param rssi Received signal strength, dBm. /// @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,104 @@
# Checks (and, unless -CheckOnly, installs) everything a PC needs to flash and test the spare micrOBU board overnight:
# git, Python 3.11 + pyserial + asn1tools, MSYS2 gcc + make, ESP-IDF 6.0.2 for the ESP32-C5. Safe to run again: a step that is
# already satisfied is left alone. Needs internet (winget, GitHub, pacman, Espressif's download servers; about 3 GB, 20-40 min).
#
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\setup_workstation.ps1 -CheckOnly # just report
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\setup_workstation.ps1 # install what is missing
# ... -PreventSleep also turns off sleep, display-off and USB selective suspend while on mains (an overnight run needs it)
#
# What each step is for is in obu-firmware/test/bench/README.md ("Setting up a workstation"). Exit code 1 if something is
# still missing at the end.
param(
[switch]$CheckOnly,
[switch]$PreventSleep,
[string]$IdfVersion = "v6.0.2",
[string]$IdfToolsPath = "C:\Espressif",
[string]$Msys = "C:\msys64"
)
$ErrorActionPreference = "Stop"
$report = New-Object System.Collections.Generic.List[object]
function Add-Row($name, $ok, $detail) { $report.Add([pscustomobject]@{ Step = $name; OK = $(if ($ok) { "ok" } else { "MISSING" }); Detail = $detail }) }
function Have-Winget { [bool](Get-Command winget -ErrorAction SilentlyContinue) }
function Winget-Install($id) {
if (-not (Have-Winget)) { throw "winget is not available: install '$id' by hand (Microsoft Store: App Installer)" }
& winget install -e --id $id --accept-source-agreements --accept-package-agreements
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne -1978335189) { throw "winget install $id failed ($LASTEXITCODE)" } # -1978335189: already installed, nothing to do
$env:PATH = [Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [Environment]::GetEnvironmentVariable("PATH", "User")
}
function Find-Python {
if (Get-Command py -ErrorAction SilentlyContinue) { $v = & py -3.11 --version 2>$null; if ($LASTEXITCODE -eq 0) { return @("py", "-3.11") } }
$p = Join-Path $env:LOCALAPPDATA "Programs\Python\Python311\python.exe"
if (Test-Path $p) { return @($p) }
return $null
}
function Run-Python($py, [string[]]$a) { $rest = @(); if ($py.Count -gt 1) { $rest = $py[1..($py.Count - 1)] }; & $py[0] @rest @a }
# ---- 1. git -------------------------------------------------------------------------------------------------------
$haveGit = [bool](Get-Command git -ErrorAction SilentlyContinue)
if (-not $haveGit -and -not $CheckOnly) { Winget-Install "Git.Git"; $haveGit = [bool](Get-Command git -ErrorAction SilentlyContinue) }
Add-Row "git" $haveGit $(if ($haveGit) { (& git --version) } else { "winget install -e --id Git.Git" })
if ($haveGit -and -not $CheckOnly) { & git config --global core.longpaths true } # ESP-IDF's tree has paths past 260 characters
# ---- 2. Python 3.11 + pyserial + asn1tools --------------------------------------------------------------------------
$py = Find-Python
if (-not $py -and -not $CheckOnly) { Winget-Install "Python.Python.3.11"; $py = Find-Python }
Add-Row "python 3.11" ([bool]$py) $(if ($py) { (Run-Python $py @("--version")) } else { "winget install -e --id Python.Python.3.11" })
if ($py) {
foreach ($pair in @(@("pyserial", "serial"), @("asn1tools", "asn1tools"))) {
Run-Python $py @("-c", "import $($pair[1])") 2>$null
$have = ($LASTEXITCODE -eq 0)
if (-not $have -and -not $CheckOnly) { Run-Python $py @("-m", "pip", "install", "--user", $pair[0]); Run-Python $py @("-c", "import $($pair[1])") 2>$null; $have = ($LASTEXITCODE -eq 0) }
Add-Row "pip: $($pair[0])" $have $(if ($have) { "importable" } else { "py -3.11 -m pip install --user $($pair[0])" })
}
}
# ---- 3. MSYS2 UCRT64 gcc + make (the PC-side C tests in obu-firmware/test/host) --------------------------------------
$gcc = Join-Path $Msys "ucrt64\bin\gcc.exe"
$make = Join-Path $Msys "usr\bin\make.exe"
if (-not (Test-Path $gcc) -or -not (Test-Path $make)) {
if (-not $CheckOnly) {
if (-not (Test-Path (Join-Path $Msys "usr\bin\bash.exe"))) { Winget-Install "MSYS2.MSYS2" }
$bash = Join-Path $Msys "usr\bin\bash.exe"
& $bash -lc "pacman -Syu --noconfirm" # the first run may end the shell after updating pacman itself, so it is run twice
& $bash -lc "pacman -Syu --noconfirm"
& $bash -lc "pacman -S --needed --noconfirm mingw-w64-ucrt-x86_64-gcc make"
}
}
$haveC = (Test-Path $gcc) -and (Test-Path $make)
Add-Row "MSYS2 gcc + make" $haveC $(if ($haveC) { "$gcc, $make" } else { "winget install -e --id MSYS2.MSYS2, then pacman -S mingw-w64-ucrt-x86_64-gcc make" })
# ---- 4. ESP-IDF (exactly this version: components/microbu_v2x pins the C5 radio driver ABI to it) ---------------------
$idfDir = Join-Path $IdfToolsPath "frameworks\esp-idf-$IdfVersion"
$idfExport = Join-Path $idfDir "export.ps1"
$envDirs = @(Get-ChildItem (Join-Path $IdfToolsPath "python_env") -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "idf$($IdfVersion.TrimStart('v') -replace '^(\d+\.\d+).*', '$1')_*" })
if ((-not (Test-Path $idfExport) -or -not $envDirs) -and -not $CheckOnly -and $haveGit) {
if (-not (Test-Path $idfExport)) {
New-Item -ItemType Directory -Force (Split-Path $idfDir) | Out-Null
& git clone --branch $IdfVersion --depth 1 --recursive --shallow-submodules https://github.com/espressif/esp-idf.git $idfDir
if ($LASTEXITCODE -ne 0) { throw "git clone of ESP-IDF $IdfVersion failed" }
}
$env:IDF_TOOLS_PATH = $IdfToolsPath
Push-Location $idfDir
try { & .\install.ps1 esp32c5; if ($LASTEXITCODE -ne 0) { throw "ESP-IDF install.ps1 failed" } } finally { Pop-Location }
$envDirs = @(Get-ChildItem (Join-Path $IdfToolsPath "python_env") -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "idf$($IdfVersion.TrimStart('v') -replace '^(\d+\.\d+).*', '$1')_*" })
}
$haveIdf = (Test-Path $idfExport) -and [bool]$envDirs
Add-Row "ESP-IDF $IdfVersion" $haveIdf $(if ($haveIdf) { "$idfDir (python env $($envDirs[0].Name))" } else { "git clone --branch $IdfVersion --recursive https://github.com/espressif/esp-idf.git $idfDir; then .\install.ps1 esp32c5 with IDF_TOOLS_PATH=$IdfToolsPath" })
# ---- 5. sleep (an overnight run dies when Windows sleeps or suspends the USB port) --------------------------------------
if ($PreventSleep -and -not $CheckOnly) {
& powercfg /change standby-timeout-ac 0
& powercfg /change hibernate-timeout-ac 0
& powercfg /change monitor-timeout-ac 0
& powercfg /setacvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 # USB selective suspend: disabled
& powercfg /setactive SCHEME_CURRENT
Add-Row "power plan (on mains)" $true "no sleep, no hibernate, display stays on, USB selective suspend off"
} else {
Add-Row "power plan (on mains)" $true "unchanged (start_overnight.ps1 keeps Windows awake while it runs; -PreventSleep also fixes USB suspend)"
}
$report | Format-Table -AutoSize -Wrap
$missing = @($report | Where-Object { $_.OK -ne "ok" })
if ($missing.Count) { Write-Host "$($missing.Count) step(s) still missing." -ForegroundColor Yellow; exit 1 }
Write-Host "Workstation ready. Next: start_overnight.ps1 -Flash -Hours 8 (README.md, 'Setting up a workstation')." -ForegroundColor Green
@@ -0,0 +1,84 @@
# One command for the overnight run on the SPARE board (no battery): optionally builds and flashes this checkout's firmware,
# runs the PC-side C tests in the background, runs the board tests, and keeps Windows awake meanwhile.
#
# powershell -ExecutionPolicy Bypass -File obu-firmware\test\bench\start_overnight.ps1 -Flash -Hours 8
# ... -Port COM6 name the port (default: the one Espressif native-USB board that is plugged in)
# ... -Quick about 8 minutes on the board, no host fuzz: does everything work?
# ... -NoTx the radio stays silent
# ... -NoHostTests skip the PC-side C tests
#
# Before it: git pull, close everything that holds the port (the phone app, station_status_watch.py, a serial monitor).
# Opening the port resets the board, and the run reconfigures it for hours and writes the demo ticket to its NVS: plug in
# ONLY the spare board (a board without a cell reads about 4000 mV from the USB charger, so battery_mv cannot tell them apart).
param(
[double]$Hours = 8,
[string]$Port = "auto",
[switch]$Flash,
[switch]$Quick,
[switch]$NoTx,
[switch]$NoHostTests,
[string]$IdfVersion = "v6.0.2",
[string]$IdfToolsPath = "C:\Espressif",
[string]$Msys = "C:\msys64"
)
$ErrorActionPreference = "Stop"
$bench = $PSScriptRoot
$fw = (Resolve-Path (Join-Path $bench "..\..")).Path # obu-firmware
$py = if (Get-Command py -ErrorAction SilentlyContinue) { @("py", "-3.11") } else { @(Join-Path $env:LOCALAPPDATA "Programs\Python\Python311\python.exe") }
function Run-Python([string[]]$a) { $rest = @(); if ($py.Count -gt 1) { $rest = $py[1..($py.Count - 1)] }; & $py[0] @rest @a }
# Keep Windows awake for as long as this PowerShell process lives.
Add-Type -Namespace Win -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'
[void][Win.Power]::SetThreadExecutionState(0x80000001) # ES_CONTINUOUS | ES_SYSTEM_REQUIRED
# Which board: the one Espressif native-USB port, unless named.
if ($Port -eq "auto") {
$found = @(Run-Python @("-c", "from serial.tools import list_ports; print(' '.join(p.device for p in list_ports.comports() if p.vid == 0x303A))") -split "\s+" | Where-Object { $_ })
if ($found.Count -ne 1) { Write-Host "Found $($found.Count) Espressif USB boards ($($found -join ', ')): pass -Port COMx." -ForegroundColor Red; exit 2 }
$Port = $found[0]
}
Write-Host "Board port: $Port"
if ($Flash) {
$idf = Join-Path $IdfToolsPath "frameworks\esp-idf-$IdfVersion\export.ps1"
if (-not (Test-Path $idf)) { Write-Host "ESP-IDF $IdfVersion not found at ${idf}: run setup_workstation.ps1 first." -ForegroundColor Red; exit 2 }
# A fresh PowerShell, so no other IDF's environment is in the way (two exports in one window fail).
$cmd = "`$env:IDF_TOOLS_PATH='$IdfToolsPath'; Remove-Item Env:IDF_PYTHON_ENV_PATH,Env:IDF_PATH -ErrorAction SilentlyContinue; " +
"& '$idf' *> `$null; Set-Location '$fw'; " +
"if (-not (Test-Path build\CMakeCache.txt)) { idf.py set-target esp32c5; if (`$LASTEXITCODE) { exit 1 } }; " +
"idf.py build; if (`$LASTEXITCODE) { exit 1 }; " +
"Set-Location build; python -m esptool --chip esp32c5 -p $Port -b 460800 --before default-reset --after hard-reset write-flash '@flash_args'; exit `$LASTEXITCODE"
Write-Host "Building and flashing (the first build downloads components and takes ~20 minutes) ..."
& powershell -NoProfile -ExecutionPolicy Bypass -Command $cmd
if ($LASTEXITCODE -ne 0) {
Write-Host ("Build or flash failed. If the port was not found or no serial data arrived: unplug the board, hold BOOT, plug in, release, run again; " +
"if the stub flasher will not start, see obu-firmware/FLASHING.md ('--no-stub'). Unplug and replug WITHOUT BOOT afterwards.") -ForegroundColor Red
exit 3
}
Start-Sleep -Seconds 5 # the board re-enumerates after the hard reset
}
# PC-side C tests, in the background (they need no board).
$hostJob = $null
if (-not $NoHostTests -and -not $Quick) {
if (Test-Path (Join-Path $Msys "ucrt64\bin\gcc.exe")) {
$hostJob = Start-Process powershell -PassThru -WindowStyle Minimized -ArgumentList @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", (Join-Path $bench "run_host_tests_overnight.ps1"), "-Hours", [string]($Hours - 0.2), "-Msys", $Msys)
Write-Host "PC-side tests started in the background (pid $($hostJob.Id)); results in obu-firmware\test\results\host-*"
} else { Write-Host "MSYS2 gcc not found: skipping the PC-side tests (setup_workstation.ps1 installs it)." -ForegroundColor Yellow }
}
# The board tests.
$runArgs = @((Join-Path $bench "run_overnight.py"), $Port, "--provision-demo")
if ($Quick) { $runArgs += "--quick" } else { $runArgs += @("--hours", [string]$Hours) }
if ($NoTx) { $runArgs += "--no-tx" }
Run-Python $runArgs
$code = $LASTEXITCODE
if ($hostJob) {
Write-Host "Waiting for the PC-side tests ..."
$hostJob.WaitForExit()
Write-Host "PC-side tests exit code: $($hostJob.ExitCode)"
if ($hostJob.ExitCode -ne 0 -and $code -eq 0) { $code = 1 }
}
Write-Host "Board tests exit code: $code. Reports: obu-firmware\test\results\overnight-*\report.txt and host-*\summary.txt"
exit $code
+19 -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 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) DEPS = test_util.c test_util.h dot11p.h $(FW_SRCS) $(wildcard $(FW)/*.h)
.PHONY: all check chain replay fuzz battery firmware corpus clean .PHONY: all check chain replay fuzz battery firmware fragments corpus clean
all: check all: check
check: chain replay fuzz battery firmware check: chain replay fuzz battery firmware fragments
$(BUILD): $(BUILD):
mkdir -p $@ mkdir -p $@
@@ -83,6 +83,23 @@ $(BUILD)/test_firmware$(EXE): test_firmware.cpp $(FW_CXX_SRCS) $(wildcard $(FW)/
firmware: $(BUILD)/test_firmware$(EXE) firmware: $(BUILD)/test_firmware$(EXE)
$(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 # 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 # 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 CORPUS_OUT = ../../../app/src/test/resources/gn_unwrap_corpus.tsv
+1 -1
View File
@@ -8,7 +8,7 @@ installed 2026-09-11).
**Firmware unit tests (`make firmware`, `test_firmware.cpp`, 40 tests):** the station-link codec byte-exact against **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 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 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 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`. on the bench list in `TODO.md`.
+120
View File
@@ -9,6 +9,7 @@
#include "battery_policy.hpp" #include "battery_policy.hpp"
#include "cca_window.hpp" #include "cca_window.hpp"
#include "its_clock.hpp" #include "its_clock.hpp"
#include "link_fragment.hpp"
#include "link_protocol.hpp" #include "link_protocol.hpp"
#include "radio_policy.hpp" #include "radio_policy.hpp"
#include "raw_capture_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) { TEST(ports_outside_the_its_set_are_not_forwarded) {
Bytes frame; Bytes frame;
CHECK(air_frame(Bytes(20, 1), 1234, 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,159 @@
micrOBU bench run, 6.3 h
PASS 1278 FAIL 802 WARN 5 INFO 67 SKIP 0
== FAIL ==
conformance frames use the MAC the phone named (spec: MicrOBU 16-octet STATION_CONFIGURE) (x2) on air: ['66:f1:4c:b7:92:65']
soak-unsigned every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x11) 2400 of 2400 frames differ, e.g. ['a2:68:56:aa:e7:40'] (wanted 02:b3:0a:ce:00:04)
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x781) reply accepted, 1 frames, src 72:80:ec:aa:4b:62 want 02:b3:0a:ce:00:08
soak-unsigned requests accepted (queue not full, no refusal) (x4) 2383 refused: {'accepted': 17, 'resource_limit': 2383}
resets panic/error text on the console (x4) Guru Meditation Error: Core 0 panic'ed (Illegal instruction). Exception was unhandled.
== WARN ==
firmware the board does not run this checkout's firmware board 1c3a66e-dirty, checkout ce18a39: results describe the board's build, not the source here (flash it: obu-firmware/FLASHING.md)
soak-unsigned radio_failed stays 0 (x4) +2383
== INFO ==
firmware board runs version 1c3a66e-dirty, compiled Nov 10 2026 23:04:26, project microbu_firmware; checkout HEAD ce18a39
conformance battery reading with no cell (x2) battery_mv 0 (0 = not measured, no shutdown on it)
conformance an unfragmented link message over 512 octets (x2) reply: none (the spec says to fragment; link_service.cpp drops it before dispatch)
conformance POTI_UPDATE 8 s behind the station clock (x2) reply: time_regression
conformance 802.11 source of own unsecured frames (x2) 72:08:38:b1:d8:2f
conformance credentials on this board (configure with security on) (x2) credentials_loaded 1, tickets 1
conformance signed payload of 1398 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1399 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1400 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance GN address after naming MAC 02:b3:0a:ce:00:03 88:00:02:b3:0a:ce:00:03
conformance after the stage (x2) uptime 28976 ms, heap_free 75268, heap_min 55028, radio failed 0, resets seen 1
soak-unsigned host-side fragment accounting (x11) {'frag_complete': 1526}
soak-signed host-side fragment accounting (x11) {'frag_complete': 2596}
fuzz seed (x11) 333791341 (replay with --fuzz-seed 333791341)
idle-listen V2X_RX heard on the air while listening (x10) 0 messages in 300 s
conformance GN address after naming MAC 02:b3:0a:ce:06:1a 88:00:02:b3:0a:ce:06:1a
heap lowest free heap ever seen by the station (heap_min_free) 49736 octets
rx nothing was heard on the air during the run no other ITS station in range of this board, or the radio was never on
link host-side counters frag_complete 23441, frames_ok 366523
== PASS ==
conformance station answers STATUS_REQUEST after a reset (x2)
conformance STATUS detail is the 131-octet snapshot (spec: Status confirmation payload) (x2)
conformance a reset station is unconfigured (x2)
conformance uptime restarted at the reset (x2)
conformance STATUS uptime runs at real time (x2)
conformance opcode 0x00 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x40 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x7e is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x80 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x85 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x90 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0xff is answered unknown_opcode (link_service.cpp default) (x2)
conformance STATUS_REQUEST with a body is malformed (x2)
conformance STATION_CONFIGURE of 0 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 1 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 5 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 7 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 15 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 17 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE security=2 is malformed (x2)
conformance STATION_CONFIGURE beaconing=2 is malformed (x2)
conformance 16-octet STATION_CONFIGURE radio=3 is malformed (x2)
conformance POTI_UPDATE of 5 octets is malformed (x2)
conformance RAW_CAPTURE with a 2-octet body is malformed (x2)
conformance RAW_CAPTURE mode with a high nibble is invalid_argument (raw_capture_policy.hpp) (x2)
conformance RAW_CAPTURE on before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST btp_type=2 is malformed (x2)
conformance BTP_DATA_REQUEST with 32 permission octets is malformed (x2)
conformance BTP_DATA_REQUEST with 3 stray trailing octets is malformed (x2)
conformance BTP_DATA_REQUEST cut short is malformed (x2)
conformance BTP_DATA_REQUEST with the optional generated_at_ms decodes (then not_configured) (x2)
conformance CONFIRM echoes sequence 65534 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 65535 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 0 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 1 (counters wrap 65535 -> 0) (x2)
conformance test request is exactly 1536 octets (the request maximum) (x2)
conformance 1536-octet request in fragments of 240 octets is joined and decoded (-> not_configured) (x2)
conformance 1536-octet request in fragments of 504 octets is joined and decoded (-> not_configured) (x2)
conformance fragmented request declaring 1537 octets is resource_limit (x2)
conformance a fragment that leaves a gap is dropped without a reply (x2)
conformance an unfinished request is discarded after the 2 s idle timeout (its late last fragment gets no reply) (x2)
conformance at most 8 incomplete requests are held (spec: pending maximum 8) (x2)
conformance a frame with a wrong CRC is counted in link_crc_errors and ignored (x2)
conformance a valid frame after 60 octets of noise is answered (resync) (x2)
conformance a valid frame after a doubled 0xAA is answered (x2)
conformance a valid frame after a header declaring 1537 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 4000 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 65535 payload octets is answered (resync) (x2)
conformance a frame cut short and padded out is dropped and the next valid frame is answered (x2)
conformance a frame of unknown type does not disturb the link (x2)
conformance STATION_CONFIGURE (6 octets, unsecured, 5 dBm) is accepted (x2)
conformance STATION_CONFIGURE detail is 18 octets (spec: gn_address, identifier, credentials_loaded, tickets) (x2)
conformance RAW_CAPTURE mode 0x05 (on + own TX) after configure is accepted (x2)
conformance BTP_DATA_REQUEST before the first POTI_UPDATE is rejected (no ITS time, no fix) (x2)
conformance POTI_UPDATE with latitude 91 degrees is invalid_argument (x2)
conformance an accepted POTI_UPDATE is silent (spec: errors return CONFIRM) (x2)
conformance an accepted POTI_UPDATE counts in poti_updates (x2)
conformance unsecured BTP_DATA_REQUEST of 24 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 43 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 300 octets is accepted (x2)
conformance every accepted request leaves the radio, byte for byte (own-TX RAW_FRAME copy, unwrapped independently) (x2)
conformance unsecured frames carry no security envelope (x2)
conformance transport type 2 (TSB) unsecured is unsupported (station_unsecured: geonet.c builds SHB only) (x2)
conformance btp_type 2 is malformed (x2)
conformance refused requests put nothing on the radio (x2)
conformance signed BTP_DATA_REQUEST is accepted (x2)
conformance the signed request leaves the radio inside a signed envelope (IEEE 1609.2 signedData) (x2)
conformance signed frames use the MAC the phone named (x2)
conformance a signed request generated 5 s ago is rejected as stale (tx_policy::is_stale) (x2)
conformance a stale request is never transmitted (x2)
conformance 16-octet STATION_CONFIGURE naming a MAC is accepted (x2)
conformance the station did not reset during the stage (x2)
soak-unsigned RAW_CAPTURE own-TX capture accepted (x11)
soak-unsigned every request got a CONFIRM (x11)
soak-unsigned requests accepted (queue not full, no refusal) (x7)
soak-unsigned the station did not reset during the phase (x11)
soak-unsigned STATUS requests_accepted counts the accepted requests (x11)
soak-unsigned radio_failed stays 0 (x7)
soak-unsigned link_crc_errors stays 0 (host sends valid frames only) (x11)
soak-unsigned no captured own-TX frame was corrupted (x11)
soak-unsigned no request was transmitted twice (x11)
soak-unsigned accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x11)
soak-signed RAW_CAPTURE own-TX capture accepted (x11)
soak-signed every request got a CONFIRM (x11)
soak-signed requests accepted (queue not full, no refusal) (x11)
soak-signed the station did not reset during the phase (x11)
soak-signed STATUS requests_accepted counts the accepted requests (x11)
soak-signed radio_failed stays 0 (x11)
soak-signed link_crc_errors stays 0 (host sends valid frames only) (x11)
soak-signed sign_failed stays 0 (x11)
soak-signed every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form) (x11)
soak-signed no captured own-TX frame was corrupted (x11)
soak-signed no request was transmitted twice (x11)
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy) (x11)
raw-toggle RAW_CAPTURE 0x00 accepted (x22)
raw-toggle mode 0x00 copies none of the station's own frames (x22)
raw-toggle RAW_CAPTURE 0x05 accepted (x22)
raw-toggle mode 0x05 copies the station's own frames (x22)
raw-toggle RAW_CAPTURE 0x01 accepted (x11)
raw-toggle mode 0x01 copies none of the station's own frames (x11)
raw-toggle RAW_CAPTURE 0x07 accepted (x11)
raw-toggle mode 0x07 copies the station's own frames (x11)
raw-toggle RAW_CAPTURE 0x03 accepted (x11)
raw-toggle mode 0x03 copies none of the station's own frames (x11)
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x396)
reconfigure every STATION_CONFIGURE was accepted (x11)
reconfigure the station did not reset while being reconfigured (x11)
fuzz station answers before the fuzz run (x11)
fuzz fuzz starts unconfigured (nothing can reach the radio) (x11)
fuzz fuzz run (x11)
fuzz heap after fuzz is within 8 KB of the start (x11)
resets board answers after a reset (x50)
resets board comes back unconfigured (x50)
resets the reset was a fresh boot (uptime small) (x50)
resets ROM boot banner seen on reopen (x50)
resets first frame after a reset is transmitted (x50)
idle-listen STATUS answered once a second throughout (x10)
idle-listen the station did not reset while idle (x10)
idle-listen receive queue never overflowed (radio_dropped) (x10)
heap heap_min_free stays above 16 KB
heap resets: free heap trend over 5 readings (no reset in between)
@@ -0,0 +1,156 @@
micrOBU bench run, 0.1 h
PASS 217 FAIL 0 WARN 1 INFO 29 SKIP 1
== WARN ==
link frames from the board with a bad CRC 1 (USB corruption or a board-side write cut short)
== INFO ==
firmware board runs version ce18a39-dirty, compiled Nov 25 2026 14:23:51, project microbu_firmware; checkout HEAD ce18a39
conformance battery reading with no cell (x2) battery_mv 4007 (0 = not measured, no shutdown on it)
conformance an unfragmented link message over 512 octets (x2) reply: none (the spec says to fragment; link_service.cpp drops it before dispatch)
conformance POTI_UPDATE 8 s behind the station clock (x2) reply: time_regression
conformance 802.11 source of own unsecured frames (x2) 02:7f:88:bf:4e:cd
conformance credentials on this board (configure with security on) (x2) credentials_loaded 1, tickets 1
conformance signed payload of 1398 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1399 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance signed payload of 1400 octets (x2) CONFIRM accepted, transmitted NO, requests_refused +1, sign_failed +0
conformance GN address after naming MAC 02:b3:0a:ce:00:03 88:00:02:b3:0a:ce:00:03
conformance after the stage (x2) uptime 29333 ms, heap_free 75268, heap_min 55028, radio failed 0, resets seen 1
soak-unsigned host-side fragment accounting {'frag_complete': 49}
soak-signed host-side fragment accounting {'frag_complete': 83}
fuzz seed 1599518015 (replay with --fuzz-seed 1599518015)
idle-listen V2X_RX heard on the air while listening 61 messages in 20 s
idle-listen V2X_RX by type/signed/size so far CAM <=64 x410
conformance GN address after naming MAC 02:b3:0a:ce:00:1b 88:00:02:b3:0a:ce:00:1b
heap lowest free heap ever seen by the station (heap_min_free) 49128 octets
rx everything the radio heard on the air during the run (V2X_RX) CAM <=64 x410
link host-side counters frag_complete 103, frames_bad_crc 1, frames_ok 4392
== SKIP ==
idle-listen large V2X_RX (above 494 B) reassembled intact by the host 0; fragments completed 103, errors 0
== PASS ==
conformance station answers STATUS_REQUEST after a reset (x2)
conformance STATUS detail is the 131-octet snapshot (spec: Status confirmation payload) (x2)
conformance a reset station is unconfigured (x2)
conformance uptime restarted at the reset (x2)
conformance STATUS uptime runs at real time (x2)
conformance opcode 0x00 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x40 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x7e is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x80 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x85 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0x90 is answered unknown_opcode (link_service.cpp default) (x2)
conformance opcode 0xff is answered unknown_opcode (link_service.cpp default) (x2)
conformance STATUS_REQUEST with a body is malformed (x2)
conformance STATION_CONFIGURE of 0 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 1 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 5 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 7 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 15 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE of 17 octets is malformed (spec: 6 or 16) (x2)
conformance STATION_CONFIGURE security=2 is malformed (x2)
conformance STATION_CONFIGURE beaconing=2 is malformed (x2)
conformance 16-octet STATION_CONFIGURE radio=3 is malformed (x2)
conformance POTI_UPDATE of 5 octets is malformed (x2)
conformance RAW_CAPTURE with a 2-octet body is malformed (x2)
conformance RAW_CAPTURE mode with a high nibble is invalid_argument (raw_capture_policy.hpp) (x2)
conformance RAW_CAPTURE on before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST before STATION_CONFIGURE is not_configured (x2)
conformance BTP_DATA_REQUEST btp_type=2 is malformed (x2)
conformance BTP_DATA_REQUEST with 32 permission octets is malformed (x2)
conformance BTP_DATA_REQUEST with 3 stray trailing octets is malformed (x2)
conformance BTP_DATA_REQUEST cut short is malformed (x2)
conformance BTP_DATA_REQUEST with the optional generated_at_ms decodes (then not_configured) (x2)
conformance CONFIRM echoes sequence 65534 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 65535 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 0 (counters wrap 65535 -> 0) (x2)
conformance CONFIRM echoes sequence 1 (counters wrap 65535 -> 0) (x2)
conformance test request is exactly 1536 octets (the request maximum) (x2)
conformance 1536-octet request in fragments of 240 octets is joined and decoded (-> not_configured) (x2)
conformance 1536-octet request in fragments of 504 octets is joined and decoded (-> not_configured) (x2)
conformance fragmented request declaring 1537 octets is resource_limit (x2)
conformance a fragment that leaves a gap is dropped without a reply (x2)
conformance an unfinished request is discarded after the 2 s idle timeout (its late last fragment gets no reply) (x2)
conformance at most 8 incomplete requests are held (spec: pending maximum 8) (x2)
conformance a frame with a wrong CRC is counted in link_crc_errors and ignored (x2)
conformance a valid frame after 60 octets of noise is answered (resync) (x2)
conformance a valid frame after a doubled 0xAA is answered (x2)
conformance a valid frame after a header declaring 1537 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 4000 payload octets is answered (resync) (x2)
conformance a valid frame after a header declaring 65535 payload octets is answered (resync) (x2)
conformance a frame cut short and padded out is dropped and the next valid frame is answered (x2)
conformance a frame of unknown type does not disturb the link (x2)
conformance STATION_CONFIGURE (6 octets, unsecured, 5 dBm) is accepted (x2)
conformance STATION_CONFIGURE detail is 18 octets (spec: gn_address, identifier, credentials_loaded, tickets) (x2)
conformance RAW_CAPTURE mode 0x05 (on + own TX) after configure is accepted (x2)
conformance BTP_DATA_REQUEST before the first POTI_UPDATE is rejected (no ITS time, no fix) (x2)
conformance POTI_UPDATE with latitude 91 degrees is invalid_argument (x2)
conformance an accepted POTI_UPDATE is silent (spec: errors return CONFIRM) (x2)
conformance an accepted POTI_UPDATE counts in poti_updates (x2)
conformance unsecured BTP_DATA_REQUEST of 24 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 43 octets is accepted (x2)
conformance unsecured BTP_DATA_REQUEST of 300 octets is accepted (x2)
conformance every accepted request leaves the radio, byte for byte (own-TX RAW_FRAME copy, unwrapped independently) (x2)
conformance unsecured frames carry no security envelope (x2)
conformance transport type 2 (TSB) unsecured is unsupported (station_unsecured: geonet.c builds SHB only) (x2)
conformance btp_type 2 is malformed (x2)
conformance refused requests put nothing on the radio (x2)
conformance signed BTP_DATA_REQUEST is accepted (x2)
conformance the signed request leaves the radio inside a signed envelope (IEEE 1609.2 signedData) (x2)
conformance signed frames use the MAC the phone named (x2)
conformance a signed request generated 5 s ago is rejected as stale (tx_policy::is_stale) (x2)
conformance a stale request is never transmitted (x2)
conformance 16-octet STATION_CONFIGURE naming a MAC is accepted (x2)
conformance frames use the MAC the phone named (spec: MicrOBU 16-octet STATION_CONFIGURE) (x2)
conformance the station did not reset during the stage (x2)
soak-unsigned RAW_CAPTURE own-TX capture accepted
soak-unsigned every request got a CONFIRM
soak-unsigned requests accepted (queue not full, no refusal)
soak-unsigned the station did not reset during the phase
soak-unsigned STATUS requests_accepted counts the accepted requests
soak-unsigned radio_failed stays 0
soak-unsigned link_crc_errors stays 0 (host sends valid frames only)
soak-unsigned every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form)
soak-unsigned no captured own-TX frame was corrupted
soak-unsigned no request was transmitted twice
soak-unsigned accepted requests seen leaving the radio (own-TX RAW_FRAME copy)
soak-signed RAW_CAPTURE own-TX capture accepted
soak-signed every request got a CONFIRM
soak-signed requests accepted (queue not full, no refusal)
soak-signed the station did not reset during the phase
soak-signed STATUS requests_accepted counts the accepted requests
soak-signed radio_failed stays 0
soak-signed link_crc_errors stays 0 (host sends valid frames only)
soak-signed sign_failed stays 0
soak-signed every frame uses the 802.11 source MAC the phone named in STATION_CONFIGURE (16-octet form)
soak-signed no captured own-TX frame was corrupted
soak-signed no request was transmitted twice
soak-signed accepted requests seen leaving the radio (own-TX RAW_FRAME copy)
raw-toggle RAW_CAPTURE 0x00 accepted (x2)
raw-toggle mode 0x00 copies none of the station's own frames (x2)
raw-toggle RAW_CAPTURE 0x05 accepted (x2)
raw-toggle mode 0x05 copies the station's own frames (x2)
raw-toggle RAW_CAPTURE 0x01 accepted
raw-toggle mode 0x01 copies none of the station's own frames
raw-toggle RAW_CAPTURE 0x07 accepted
raw-toggle mode 0x07 copies the station's own frames
raw-toggle RAW_CAPTURE 0x03 accepted
raw-toggle mode 0x03 copies none of the station's own frames
reconfigure a frame sent right after a reconfigure leaves with the new MAC and security (x12)
reconfigure every STATION_CONFIGURE was accepted
reconfigure the station did not reset while being reconfigured
fuzz station answers before the fuzz run
fuzz fuzz starts unconfigured (nothing can reach the radio)
fuzz fuzz run
fuzz heap after fuzz is within 8 KB of the start
resets board answers after a reset (x2)
resets board comes back unconfigured (x2)
resets the reset was a fresh boot (uptime small) (x2)
resets ROM boot banner seen on reopen (x2)
resets first frame after a reset is transmitted (x2)
idle-listen STATUS answered once a second throughout
idle-listen the station did not reset while idle
idle-listen receive queue never overflowed (radio_dropped)
heap heap_min_free stays above 16 KB
+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:])