1 Commits
Author SHA1 Message Date
Ashin Walpola 2581c79f49 Ask before disconnecting the OBU on the V2X screen
The disconnect icon sits next to the map button and dropped the ESP32-C5 or
CiT One link on a single tap. It now opens a standard confirmation dialog first.
Connecting still needs no confirmation.

Checked on a Pixel 9 Pro (ESP32 path): Cancel, Back and rotation keep the link
and the dialog; confirming disconnects.
2026-10-20 17:33:38 +02:00
10418 changed files with 850350 additions and 75684 deletions
+1 -31
View File
@@ -55,7 +55,7 @@ sdkconfig.old
# dependencies.lock beside the project pins them and is committed; this is its cache.
managed_components/
# Niklas Dathe's standalone ESP32-C5 VRU station (its own repository, HAW GitLab
# The colleague's standalone ESP32-C5 VRU station (its own repository, HAW GitLab
# urban-mobility-lab/microbu/microbu-esp32c5). Kept beside the project on the lab laptop, for
# reference and because the V2X2MAP bridge runs from its tools/, but not part of this repository:
# obu-firmware only needs its vanetza-idf, which is copied to obu-firmware/external/vanetza-idf.
@@ -63,33 +63,3 @@ managed_components/
# draw.io keeps a backup beside an open diagram.
*.drawio.bkp
# LaTeX build output of obu-firmware/docs/station-link.tex (the PDF itself is committed)
obu-firmware/docs/*.aux
obu-firmware/docs/*.log
obu-firmware/docs/*.out
obu-firmware/docs/*.synctex.gz
# Niklas Dathe's current firmware tree (his own git repository, HAW GitLab): the reference copy
# obu-firmware was built from. Only what obu-firmware needs is copied into it.
/microbu-firmware/
# Reference papers, their markdown conversions and local gateway files kept in the project root for
# reading; not part of the project.
/CI-CiT-*.pdf
/ETSI - *
/Time-Synchronized GNSS-IMU Data Logging.*
/en_302663*
/sensors-23-*
/pre_parts.json
/v2x-v2xgateway.*
# Editor settings
/.vscode/
obu-firmware/docs/*.synctex*
# Overnight bench test: LaTeX build output (the PDF is committed) and raw run folders (only the reports are committed)
obu-firmware/docs/*.fdb_latexmk
obu-firmware/docs/*.fls
obu-firmware/test/results/*/
-6
View File
@@ -1,6 +0,0 @@
# Merge gate: every push runs the affected test plans in microbu-tests (official ETSI TTCN-3 ATS
# suites for now); the result of that pipeline is the result of this one. See microbu-tests README.
include:
- project: urban-mobility-lab/microbu/microbu-tests
ref: main
file: ci/upstream/microbu-tests.yml
+45 -171
View File
@@ -2,90 +2,42 @@
Android companion app for the micrOBU; a compact V2X on-board unit developed by HAW Hamburg and consider it GmbH for vulnerable road users (cyclists, e-bike riders, pedestrians).
The app is the HMI for the OBU hardware and, on the ESP32-C5 path, also the ITS facilities layer: it builds and decodes the ITS messages, while the board does GeoNetworking, signing and the radio. It handles V2X message display, use case detection, traffic lights per lane, sensor collection, trip recording, and the link to the OBU over USB-C or Bluetooth LE.
The app is the HMI for the OBU hardware and, on one of the two supported hardware paths, the entire V2X protocol stack. It handles V2X message display, use case detection, sensor collection, trip recording, and OBU communication over USB-C.
**Platform:** Android (Kotlin) / **Min SDK:** 29 (Android 10) / **Target SDK:** 36 / **Version:** 0.1.0 (`versionName`, Phase 03)
```mermaid
flowchart LR
subgraph Phone[Android app]
UI[Compose UI and use cases]
Fac[ITS facilities: CAM, VAM, DENM, SPATEM and MAPEM codecs]
Sens[GNSS, IMU, trip recording]
Link[Esp32Link and StationLink]
end
Sens --> Fac
Fac -->|BTP_DATA_REQUEST, POTI_UPDATE| Link
Link -->|V2X_RX, CONFIRM with status| Fac
Fac --> UI
Link <-->|USB-C or encrypted BLE, station-link rev. 2| OBU[obu-firmware on the XIAO ESP32-C5]
OBU <-->|BTP, GeoNetworking, signing| Air[ITS-G5 5.9 GHz]
UI <-->|IP over USB tethering, MQTT| CiT[consider it CiT One]
```
```yaml
platform: Android
language: Kotlin
UI: Jetpack-Compose
DI: Hilt
min_sdk: 29
target_sdk: 36
hardware_paths:
esp32_c5: # primary; the app is the ITS facilities layer
firmware: obu-firmware/ # Niklas Dathe's microbu-firmware plus MicrOBU additions
transport: [USB-C native Serial/JTAG, Bluetooth LE GATT]
protocol: station-link revision 2 (obu-firmware/docs/station-link.pdf)
app_builds: [CAM, VAM, decodes CAM, DENM, SPATEM, MAPEM, VAM]
board_does: [BTP, GeoNetworking, signing, radio]
cit_one: # consider it CiT One
transport: IP over USB tethering, MQTT
messages_received: V2X_RX (0x90), signed or not, up to 494 octets
messages_sent: signed or unsigned per setting (Settings > Connection > ESP32-C5)
credentials: throwaway demo chain in app/src/main/assets/demo-chain.vcr
tests: 145 JVM unit tests, no emulator needed (domain/ has no Android imports)
```
**Platform:** Android (Kotlin) / **Min SDK:** 29 (Android 10) / **Target SDK:** 36 / **Version:** 0.5.0 (Phase 03)
## Project goal
Demonstrate V2X communication with at least one C2C-CC bicycle safety use case working on the ESP32-C5, specifically intersection movement assist: a car approaching an intersection on a path that conflicts with the rider's.
That use case is driven entirely from the periodic position and kinematics vehicles broadcast. It needs no traffic light state and no intersection lane geometry. The app now also shows traffic lights per lane from SPATEM and MAPEM, but no use case depends on them.
That use case is driven entirely from the periodic position and kinematics vehicles broadcast. It needs no traffic light state and no intersection lane geometry, which is why several scope decisions in this repository look deliberately narrow.
## Two hardware paths
The project began against the consider it CiT One and later added the ESP32-C5 as a second option. Both paths are supported at runtime and selected by the rider in Settings > OBU Hardware.
| | consider it CiT One | ESP32-C5 (micrOBU, `obu-firmware/`) |
| | consider it CiT One | ESP32-C5 |
|---|---|---|
| What it is | Complete V2X on-board unit | Seeed XIAO ESP32-C5 running Niklas Dathe's microbu-firmware ITS station |
| Transport | IP over USB tethering, MQTT | Station-link protocol over native USB-C or Bluetooth LE |
| Reaches the phone as | Processed JSON, plus raw protobuf-wrapped UPER | Raw ASN.1 UPER per message, with RSSI |
| V2X stack lives | On the OBU | Facilities (CAM/VAM/DENM/SPATEM/MAPEM codecs) on the phone; BTP, GeoNetworking, security and radio on the board |
| Own messages | CAM, generated by the OBU | CAM or VAM, generated by the phone and sent by the board |
| Signing (ETSI TS 103 097) | By the OBU | By the board, with a demo PKI the app provisions; or unsigned |
| What it is | Complete V2X on-board unit | Development board acting as a plain radio |
| Transport | IP over USB tethering, MQTT | Framed binary protocol over USB CDC serial |
| Reaches the phone as | Processed JSON | Raw ASN.1 UPER bytes |
| V2X stack lives | On the OBU | On the phone, except the radio and GeoNetworking |
| Own CAM generated by | The OBU, autonomously | The phone, transmitted on the phone's clock |
| DENM trigger | Available (manual test tool) | Not available |
| Needs a network | Yes, internally | No |
Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived into the domain types (`Cam`, `DenmEvent`, `SpatEvent`, `MapEvent`). Everything above that point, including the use case detection engine and all UI, is shared and transport-agnostic. That is what makes the ESP32-C5 a drop-in second OBU rather than a fork of the application.
Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived into the domain `Cam` type. Everything above that point, including the entire use case detection engine and all UI, is shared and transport-agnostic. That is what makes the ESP32-C5 a drop-in second OBU rather than a fork of the application.
## What it does
**Real-time V2X monitoring**; live CAM, DENM, SPATEM and MAPEM with a station list, active hazards, live signal phase, and a map view. On the CiT One path the topic viewer additionally shows whatever the broker publishes, grouped by topic with pretty-printed JSON and TX/RX badges.
**Traffic lights per lane**; SPATEM says what each signal group shows, MAPEM where each lane runs and which signal group controls each way out of it. `TrafficLights.join` puts the two together and picks the rider's own ingress lane from position and heading. The dashboard card then names the intersection and shows the rider's lane, the distance to its stop line, and one light per signal group with its turn arrows (↑ ← →) and countdown. The V2X map puts the light on the intersection's reference point and draws the lanes in their signal colours. Without a MAPEM, signal groups are shown as bare numbers.
**Real-time V2X monitoring**; live CAM, DENM and SPATEM with a station list, active hazards, live signal phase, and a map view. On the CiT One path the topic viewer additionally shows whatever the broker publishes, grouped by topic with pretty-printed JSON and TX/RX badges.
**CAM-based use case detection**; correlates the rider's own state with a short per-station history of received CAMs to evaluate five C2C-CC bicycle safety use cases (IMA-B, IMA-S, RTW-B, LTW-B, SMVA/BCW-B) and raises alerts under the three-tier Info / Awareness / Warning model. None of these use cases generates a DENM.
**Phone-generated CAM or VAM**; on the ESP32-C5 path the app builds a CAM (EN 302 637-2) or a VAM (TS 103 300-3, cyclist profile, its generation rules included) from live GNSS and IMU, UPER-encodes it, and hands it to the board with "signed" or "unsigned" (Settings > Connection > ESP32-C5). The board adds BTP and GeoNetworking, signs it with its authorization ticket, and transmits it over ITS-G5. The CAM and VAM station ID rotates as a pseudonym, and the link-layer address (802.11 source and GN address) rotates with it: the app sends the pseudonym's MAC in the 16-octet STATION_CONFIGURE and the board reconfigures on a change. The bench CAM pinger keeps one fixed identity and MAC. ITS time is TAI.
**Phone-generated CAM**; on the ESP32-C5 path the app builds a CAM from live GNSS and IMU, UPER-encodes it, and pushes it down the serial link for the board to broadcast over ITS-G5.
**DENM transmission**; CiT One path only. Triggers the stationary vehicle profile (`hln-sv`, causeCode 94) via the consider it Use Case API. This is a manual antenna and range test tool. It is never triggered by a detected event or a use case alert, and the control is hidden entirely on the ESP32-C5 path.
**OBU status**; the ESP32-C5 card shows the link in use, signing (tickets, signed, refused, on air) and the board's battery voltage with a low/critical warning, which also appears in the top bar.
**V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside. With Settings > Ride > Record motion sensors on, a log also records accelerometer, gyroscope and gravity at 100 Hz, raw GPS fixes next to the fused location, and the phone's clocks, for sensor fusion; `tools/fusion_log_check.py` checks such a log. See `docs/07-sensor-fusion-logging.md`.
**Ride settings**; Settings > Ride. Where the phone rides (handlebar, bag or pocket), recorded in every V2X log for sensor fusion, and the motion sensor recording switch above.
**Trip recording**; foreground service records all sensor streams and detects cycling manoeuvres (braking, turning, stopping) using orientation-independent signal processing. Works fully offline with no OBU connected. The detected manoeuvres are neither shown nor stored - their only effect is to raise the CAM transmit rate through the manoeuvre on the ESP32-C5 path.
**Trip review**; past trips displayed as a route on an OpenStreetMap layer, with duration and distance.
@@ -97,91 +49,37 @@ Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived
MVVM with Repository pattern throughout. Jetpack Compose for all UI (no XML layouts). Hilt for dependency injection.
```
app/src/main/java/com/hawhamburg/micr0bu/
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor and map, Settings, V2X logger...)
ui/navigation/ Navigation graph and bottom nav bar
viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel, RideSettingsViewModel
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope
data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport
data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager
data/log/ V2xLogger, V2xLogWriter (the V2X data logger)
data/db/ Room database (sessions, trips, V2X messages)
data/ SensorRepository, GnssTimeSource, RidePreferences, TripRepository, CsvExporter, TripExporter
domain/asn1/ BitReader/BitWriter, ItsTime, and the CAM, DENM, SPATEM, MAPEM and VAM UPER codecs
domain/map/ MAPEM intersection geometry: lanes, nodes, connections, maneuvers
domain/spat/ SPATEM signal state, and TrafficLights (SPATEM on MAPEM lanes, the rider's approach)
domain/vam/ VAM generation rules (TS 103 300-3 clause 6.4)
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig, Pseudonym
domain/fusion/ Sensor fusion: YawRateEstimator (yaw rate about the vertical), PhoneMount
service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService
obu-firmware/ ESP32-C5 OBU on Niklas Dathe's microbu-firmware (station, signing, BTP, GeoNetworking,
station link over USB and BLE) plus our raw receive path (gn_unwrap.c, V2X_RX),
unsigned TX and battery guard; host tests in test/
obu-firmware/{components,external}/ microbu_v2x, Vanetza and its patched source (vendored, unchanged)
obu-cam-transmistter/ Bench CAM beacon (the "simulated car"), fixed station ID, drives a loop in St. Georg
asn1/ Vendored ETSI ASN.1 modules the codecs are verified against
tools/ Bench scripts: STATUS watcher, bench-listener tally, MAPEM test-corpus generator
docs/ Requirements traceability, signed ITS / VAM / BLE design, architecture diagrams
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor, Settings...)
ui/navigation/ Navigation graph and bottom nav bar
viewmodel/ MqttViewModel, SensorViewModel, TripRecordingViewModel
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection
data/transport/ UsbSerialTransport, SerialFrame, UsbNetworkDetector, ObuHardware
data/cam/ CamUseCaseRepository; where both hardware paths converge
data/db/ Room database (sessions, trips, detected events, V2X messages)
data/ SensorRepository, TripRepository, CsvExporter, TripExporter
domain/asn1/ BitReader/BitWriter and the CAM, DENM and SPATEM UPER codecs
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig
service/ TripRecordingService, CamTransmitLoop, CamPinger
obu-firmware/ ESP32-C5 firmware (serial link, GeoNetworking, 802.11 OCB, raw TX)
asn1/ Vendored ETSI ASN.1 modules the codecs are verified against
```
The `domain/` packages contain no Android imports. That is what makes the 145-test JVM suite possible without an emulator or instrumentation.
The `domain/` packages contain no Android imports. That is what makes the 41-test JVM suite possible without an emulator or instrumentation.
## Connectivity
USB-C on both hardware paths. Bluetooth is **not implemented** and remains an open question in the requirements.
| Transport | Path | Status |
|---|---|---|
| USB-C tethering (IP + MQTT) | CiT One | Active |
| USB-C, native USB Serial/JTAG (station link) | ESP32-C5 | Active |
| Bluetooth LE GATT (station link) | ESP32-C5 | Active |
| USB-C serial (framed binary) | ESP32-C5 | Active |
| Wi-Fi | CiT One | Developer builds only |
| Bluetooth | Either | Not implemented |
On the CiT One path the MQTT broker runs on the OBU (Mosquitto 2.0.11, port 1883); Android USB tethering exposes it as a virtual Ethernet interface at `192.168.42.x` and the app auto-detects the gateway IP on plug-in.
On the ESP32-C5 path there is no network layer. Both links carry the same **station-link protocol**, revision 2 ([obu-firmware/docs/station-link.tex](obu-firmware/docs/station-link.tex); revision 1 is Niklas Dathe's, revision 2 adds our extensions): `[opcode][flags][sequence LE][body]`, at most 512 octets per message (`LINK_MAX_MESSAGE` in the app, `link::maximum_message` in the firmware). The phone configures the station, provisions the demo credentials once, keeps the board's clock and position current (`POTI_UPDATE` per new GNSS fix) and submits messages (`BTP_DATA_REQUEST`); the board answers every request with `CONFIRM`, the phone asks for `STATUS_REQUEST` every second (the status snapshot is in the CONFIRM), and the board forwards every ITS message it hears as `V2X_RX` (0x90, a MicrOBU extension). Over USB each message is one `0xAA55` frame with CRC-16; over BLE it is one GATT value. Details: [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md).
### Bluetooth LE
Settings > Connection > ESP32-C5 > link: Bluetooth.
- **GATT layout**: service `0000C175-BA5E-4C17-8000-00805F9B34FB`, one characteristic per primitive. Each value is one whole link message, never fragmented, so the app raises the ATT MTU to 517 first (the firmware asks for 517 too); the firmware drops a notification rather than send it cut short.
- **Pairing**: the board advertises as `micrOBU-XXXX`. LE Secure Connections with a fixed passkey, **123456**, entered once in Android's own pairing dialog. The bond is kept on both sides (the board stores it in its 80 KB NVS). The passkey is public, so this gives an encrypted link but no protection against an active attacker during that first pairing.
- **Reconnect**: after a drop (4 s supervision timeout) the app reconnects by itself, 1 s later and then backing off to 30 s. With several bonded micrOBUs (a replaced board stays bonded), the one that connected last is tried first, then the others in turn.
- **Several boards nearby**: with no bond the app connects to the first micrOBU it hears, which on a bench with several is not necessarily yours. Pair the right one in Android's Bluetooth settings first (name `micrOBU-` plus the last two octets of its BLE address); the app then prefers a bonded micrOBU. See [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md).
- **BLE and ITS-G5 share the C5's single RF front end**: the firmware holds an ITS-G5 frame out of the BLE connection-event windows (`CONFIG_MICROBU_TX_BLE_GUARD`).
- **Permissions**: `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT` (Android 12+), requested at start-up.
Whether an active BLE connection costs 5.9 GHz reception has not been measured yet.
### Received messages on the ESP32-C5 path
vanetza-idf verifies strictly and would drop anything unsigned or signed under another root, i.e. the bench car and every RSU. So every captured frame also goes through `gn_unwrap.c`, which strips 802.11, LLC/SNAP, GeoNetworking (single-hop and GeoBroadcast), an IEEE 1609.2 signed envelope if there is one, and BTP, and forwards the ITS payload for BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM. Signatures are not checked on this path; the message is flagged "signed, not verified". A payload over 494 bytes does not fit one link message and is dropped and counted.
**Two receive paths, switchable** (Settings > Connection > ESP32-C5 > Receive path). Both end in the same decoded messages, so nothing above the link changes:
| | V2X_RX (default) | Raw frames |
|---|---|---|
| Source | the MicrOBU extension, opcode 0x90 | the spec's `RAW_FRAME` (0x85), switched on with `RAW_CAPTURE` |
| Who unpacks the frame | the board (`gn_unwrap.c`) | the app (`GnUnwrap.kt`, a port tested frame by frame against the C code) |
| Size | up to 494 octets | not limited: fragments are reassembled (`LinkReassembly`, as the spec defines) |
| Reliability | normal indication | debug copy: can be dropped when the link is busy, more bandwidth, especially over BLE |
```mermaid
flowchart LR
Air[ITS-G5 frame] --> Board[ESP32-C5: radio, gn_unwrap.c, raw capture tap]
Board -->|V2X_RX 0x90, always| Link[USB or BLE]
Board -->|RAW_FRAME 0x85, after RAW_CAPTURE| Link
Link --> Re[LinkReassembly]
Re --> Sel{Receive path setting}
Sel -->|V2X_RX, default| Dec[V2xRxFrame]
Sel -->|Raw frames| Raw[RawFrame + GnUnwrap]
Raw --> Dec
Dec --> Rest[Codecs, use cases, V2X screens, logger]
```
The board always sends `V2X_RX`; the app consumes one path and ignores the other. Changing the setting takes effect at once on a configured station (`RAW_CAPTURE` mode 3 = on and broadcast frames only, mode 0 = off). `GnUnwrapTest` checks the Kotlin unwrapper against `obu-firmware/test/host/dump_corpus.c`'s output for 602 recorded, cut and corrupted frames.
On the CiT One path the MQTT broker runs on the OBU (Mosquitto 2.0.11, port 1883); Android USB tethering exposes it as a virtual Ethernet interface at `192.168.42.x` and the app auto-detects the gateway IP on plug-in. On the ESP32-C5 path there is no network layer at all: a private framed protocol runs over the board's native USB-C port as a CDC-ACM device.
## Verification
@@ -189,14 +87,9 @@ The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path,
Verification therefore uses an independent oracle: `asn1tools` compiled from the ETSI modules vendored in `asn1/`.
- **Golden-byte fixtures** assert exact encoder output (CAM, VAM), with expected values produced by the oracle rather than by this encoder.
- **Golden-byte fixtures** assert exact encoder output, with expected values produced by the oracle rather than by this encoder.
- **Bulk replay** compares every field over real captures: 79,042 SPATEMs and 1,885 DENMs, zero mismatches.
- **MAPEM**: every distinct MAPEM on record (17 from the 2026-03-18 drive, 288 to 1348 bytes, plus the bench RSU's) decodes field for field like asn1tools (`MapemUperCodecTest`; fixtures from `tools/mapem_corpus.py`). Joined with recorded SPATEMs of the same intersections, 340 of 341 signalled lane exits find their signal group (`TrafficLightsTest`).
- **Station link**: the codec is pinned to bytes from Niklas Dathe's Python implementation (`StationLinkTest`).
- **Signatures on air**: `obu-firmware/test/verify_signed_pcap.py` checks captured frames with asn1tools and OpenSSL, sharing no code with the firmware: 12 of 12 signed CAMs valid, demo chain valid (2026-09-23). The CiT One and the V2X2MAP bridge receive them too.
- **Firmware receive path**: host tests (`obu-firmware/test/host`, `make`) run the TX-to-RX chain, every recorded frame cross-checked by asn1tools, and a guard-page fuzz of `gn_unwrap_its`.
- **Off-air confirmation**: 26 of this project's own CAMs captured back by an independent receiver, all accepted.
- **CI**: every push runs the merge gate in `microbu-tests` (`.gitlab-ci.yml`).
Never regenerate a golden fixture from this project's own encoder output. See `asn1/README.md`.
@@ -207,15 +100,9 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
| [docs/MicrOBU-User-Guide.docx](docs/MicrOBU-User-Guide.docx) | Riders. Setup, screens, what the alerts mean, troubleshooting |
| [docs/MicrOBU-Technical-Documentation.docx](docs/MicrOBU-Technical-Documentation.docx) | Supervisors and stakeholders. Architecture, message path, verification, results, decisions |
| [docs/01-requirements-traceability.md](docs/01-requirements-traceability.md) | Requirements chapters 0 to 13 mapped to implementation and evidence |
| [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md) | Signed ITS messages, VAM and the BLE link: who does what, link protocol, recovery, verification |
| [docs/07-sensor-fusion-logging.md](docs/07-sensor-fusion-logging.md) | Sensor fusion phases 0 and 1: yaw rate and GNSS time inputs, Ride settings, the fusion log schema, `tools/fusion_log_check.py`, test rides |
| [docs/Architecture-signed-its.drawio.png](docs/Architecture-signed-its.drawio.png) | Block diagram of the signed-ITS architecture |
| [05-obu-bench-test-2026-08-25.md](05-obu-bench-test-2026-08-25.md) | Bench campaign T1 to T9, measured results |
| [04-transmit-setup.md](04-transmit-setup.md) | Transmitter bring-up, radio configuration diagnosis, the TX bypass |
| [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md) | Toolchain setup (ESP-IDF 6.0.2), flashing, battery and pins, phone-to-board bring-up |
| [obu-firmware/NOTES.md](obu-firmware/NOTES.md) | What the firmware changes against Niklas Dathe's station, and why |
| [obu-firmware/test/host/README.md](obu-firmware/test/host/README.md) | Host tests of the firmware's frame code |
| [TODO.md](TODO.md) | Open engineering items, including the hardware checks still to run |
| [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md) | Toolchain setup, flashing, phone-to-board bring-up checklist |
| [asn1/README.md](asn1/README.md) | ASN.1 module provenance and the fixture regeneration rule |
| [docs/references.bib](docs/references.bib) | Standards references as BibTeX |
@@ -225,14 +112,12 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
|---|---|
| Jetpack Compose + Material3 | UI |
| Eclipse Paho MQTT | CiT One path communication |
| usb-serial-for-android | ESP32-C5 USB link (custom probe table for Espressif VID/PID) |
| Android BLE (`BluetoothGatt`) | ESP32-C5 Bluetooth link |
| usb-serial-for-android | ESP32-C5 path communication (custom probe table for Espressif VID/PID) |
| Room | Local database |
| Hilt | Dependency injection |
| OSMDroid | Trip review and live V2X map |
| DataStore | Settings persistence |
| FusedLocationProviderClient | GNSS |
| vanetza-idf (firmware) | BTP, GeoNetworking and TS 103 097 security on the ESP32-C5 |
## Getting started
@@ -242,42 +127,31 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
**CiT One path.** Plug the phone into the OBU via USB-C, enable USB tethering on the phone, and the app detects the interface and connects automatically. Broker IP can be overridden in Settings > Connection.
**ESP32-C5 path.**
1. Flash `obu-firmware/` with ESP-IDF 6.0.2 (`obu-firmware/FLASHING.md`; use the full flash the first time, the partition layout differs from older images). The XIAO ESP32-C5 has a single USB-C port, used for both flashing and the phone.
2. In Settings > Connection > ESP32-C5 choose the link (USB-C or Bluetooth), what to transmit while recording (CAM or VAM) and whether to sign it.
3. Tap Connect. USB: grant the USB permission. Bluetooth: pair with `micrOBU-XXXX`, passkey 123456, once. On the first connection the app provisions the demo credentials; the card then shows "Signing on · tickets 1".
4. Use the CAM Pinger on the V2X screen to check the link and radio without starting a trip.
**ESP32-C5 path.** Flash `obu-firmware/` (see `obu-firmware/FLASHING.md`), then plug the phone into the board's **native** USB-C port, not the UART bridge port used for flashing. Tap Connect and grant the USB permission. Use the CAM Pinger on the V2X screen to verify the link and radio without starting a trip.
**Standalone trip recording.** No OBU required. Go to the Record tab and tap REC.
The Wi-Fi transport (broker at `192.168.3.202`) remains available in developer builds via Settings > Developer.
Keep app and firmware in step (the app from 2026-11-10 needs the firmware from 2026-11-10: `CONFIRM` and `STATUS_REQUEST`, `V2X_RX` is 0x90, the configure message has 6 octets): both cap a link message at 512 octets, and the app speaks station-link revision 2 (it still falls back to the previous firmware's frames for CAM over USB).
## Credits
The ESP32-C5 station firmware (BTP, GeoNetworking, TS 103 097 security, the station-link protocol, BLE and the radio driver) and its interface specification are by **Niklas Dathe** (HAW Hamburg, microbu-firmware). `obu-firmware/` is his firmware with the MicrOBU additions listed in [obu-firmware/NOTES.md](obu-firmware/NOTES.md).
Firmware and app must be flashed and installed together: `SERIAL_LINK_MAX_PAYLOAD` is 512 on both sides and a mismatch silently rejects every large frame.
## Status and known limitations
Bench verified against live ITS-G5 traffic on 2026-08-25: 2868 frames over 305 seconds, zero decode failures, zero USB errors, zero crashes. Signed CAM and VAM, the BLE link and reception over both links were checked on the bench on 2026-09-23; on 2026-10-28 the ESP32-C5 forwarded the bench RSU's MAPEM (295 bytes), SPATEM and CAM with nothing dropped. On 2026-11-11 the production XIAO and a Pixel 9 Pro were run together: the simulated car's CAMs reach the app, signed and unsigned CAMs from the phone are heard by a second board, the BLE bond survives a board reset, and BLE adds no measurable transmit loss over USB (95.7 % of signed CAMs heard in both; about 4 % is lost on the air or at the listener). On 2026-11-10 the firmware was rebuilt on Niklas Dathe's newer microbu-firmware layout and the app's link followed (link spec revision 2); that firmware boots, advertises and answers STATUS on the XIAO, while reception, transmission, signing and the battery guard on real hardware are still to be re-checked (`TODO.md`). Not yet road validated.
Bench verified against live ITS-G5 traffic on 2026-08-25: 2868 frames over 305 seconds, zero decode failures, zero USB errors, zero crashes. Not yet road validated.
- **Requirement 11.6, Phase A success criteria, is not met.** The bench proves reception. It cannot prove the use case behaves correctly with two genuinely moving stations, because nothing on the bench moves. This is the main open evidence gap for the project's central claim.
- **Demo PKI only.** Signed messages carry a throwaway chain shipped with the app, not an EU-registered one; receivers that verify against the EU trust list drop them. No TS 102 941 enrolment. The board's stack verifies signatures (counted in STATUS), but the `V2X_RX` path the app uses delivers everything without a verdict, only whether a signature is present.
- **No message signing.** ETSI TS 103 097 is out of scope. Secured frames are rejected rather than mis-parsed.
- **Detection thresholds are untuned engineering estimates**, not calibrated against real intersection data.
- **494-byte receive limit on the ESP32-C5 path.** A larger message does not fit one link message and is dropped: about 70% of real road SPATEMs (median 555 bytes) and many road MAPEMs. The CiT One path is not limited.
- **Traffic lights per lane not yet seen live.** Tested on recorded messages only. Riders on crosswalks or sidewalks are not matched to a lane, and computed lanes (`ComputedLane`) are not decoded.
- **BLE and ITS-G5 share one RF front end**; the effect of an active BLE connection on reception is unmeasured.
- **No automatic reconnect after USB re-enumeration**; requires a manual Connect. BLE reconnects by itself.
- **The prototype cell has no protection board.** The firmware's low-voltage shutdown (below 3.30 V with no phone on USB) is the only guard.
- **512-byte serial payload cap.** Roughly 70% of real road RSU SPATEMs would be dropped as oversize. Accepted deliberately: the intersection use case is CAM-driven and needs none of it.
- **No automatic reconnect** after USB re-enumeration; requires a manual Connect.
- **Station IDs rotate**, so they cannot identify a physical unit over time.
- **No backend, no login.** Everything is on-device.
- **No MAPEM decoder**, so signal groups cannot yet be associated with the rider's lane.
## Project context
The micrOBU project is funded under the ZIM program (BMWK) and targets micromobility users in Hamburg. The companion app offloads processing from the compact OBU hardware to the smartphone; GNSS fusion, event detection, and on the ESP32-C5 path the full ASN.1 encoding and decoding all run on the phone to keep the OBU lightweight and power-efficient. The ESP32-C5 keeps what must stay on the radio side: GeoNetworking, the signing key and the radio itself.
The micrOBU project is funded under the ZIM program (BMWK) and targets micromobility users in Hamburg. The companion app offloads processing from the compact OBU hardware to the smartphone; GNSS fusion, event detection, and on the ESP32-C5 path the full ASN.1 encoding and decoding all run on the phone to keep the OBU lightweight and power-efficient.
V2X communication uses ITS-G5 (IEEE 802.11p) at 5.9 GHz. On the CiT One path the app communicates via the consider it MQTT API v6 (processed JSON and raw protobuf). On the ESP32-C5 path the app performs its own ASN.1 UPER encoding and decoding against the ETSI modules vendored in `asn1/`.
V2X communication uses ITS-G5 (IEEE 802.11p) at 5.9 GHz. On the CiT One path the app communicates via the consider it MQTT API v6 (processed JSON). On the ESP32-C5 path the app performs its own ASN.1 UPER encoding and decoding against the ETSI modules vendored in `asn1/`.
**Owner:** HAW Hamburg
+11 -295
View File
@@ -5,278 +5,6 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware
### Stored HafenCity MAPEMs (added 2026-11-30)
The app ships 15 intersections (16 revisions) from the 2026-03-18 drive plus the bench RSU
(Berliner Tor / Kolbergstrasse, -1/23 rev 2) in `assets/mapem/hamburg.txt`, and matches a SPATEM to
them on region, intersection id, revision and, when known, position within 2 km. Add to the list with
`py -3.11 tools/mapem_bundle.py <V2X log .db or hex .txt>`, then run the tests and rebuild.
- [ ] Bench RSU sending its SPATEM **without** the MAPEM: the lanes appear on the V2X map; logcat says
`storedMaps: 17 intersection revisions loaded`.
- [ ] Ride through HafenCity: note intersections whose SPATEM shows no lanes (revision changed since
March, or not in the bundle) and check on the ones that do that the shown light matches the real one.
- [ ] Not built yet: saving newly heard or changed MAPEMs on the phone, so the list updates itself.
### Large SPATEM / MAPEM through V2X_RX in fragments (added 2026-11-23)
The 2026-11-23 bench run (CiT node sending a 377 B MAPEM and 58 B SPATEM, then 1198 B and 888 B ones; phone on
BLE) lost every large message: 0 of 1537 MAPEMs and 0 of 3004 SPATEMs against 98.5 % / 96.5 % of the small ones,
because `Station::forward_raw` dropped everything over 494 bytes. Firmware now sends those in link fragments
(`link_fragment.hpp`, `v2x_rx_plan`; NOTES.md). Done on the PC, not flashed yet: `make check` in
`obu-firmware/test/host` (46 unit tests, the pcap replay of 3384 + 1727 large messages through unwrap -> fragments ->
two reassemblers, fuzz), the app's `LinkReassemblyTest` on the firmware's own fragments, asn1tools on the large
payloads, ESP-IDF 6.0.2 image build.
- [x] Flashed to COM10 and run against the Berliner Tor RSU (2026-11-23 17:08-17:20, phone on BLE): MAPEM 1198 B 92.9 %,
SPATEM 888 B 81.7 % of what the node heard, `radio_dropped` 0. The V2X screens stayed empty because the app's
`SpatemUperCodec` refused the RSU's SPATEMs (intersection and movement names, advisory speeds); fixed and checked
against asn1tools on all 718 distinct messages, **needs the app reinstalled on the phone**.
- [ ] (original plan) Flash COM6 (`--no-stub` recipe, read the app descriptor first) and repeat the bench run: the node alternating
small and large MAPEM/SPATEM, the phone on BLE, a pcap recorded at the same time. Compare with
`py -3.11 tools/rx_size_compare.py LOG.db capture.pcap replay.tsv` (the header says how to make replay.tsv).
Accept: small messages stay at ~96-98 % of what the node saw, the large ones arrive at a comparable rate,
CAMs unchanged (92-96 % on 2026-11-23).
- [ ] `radio_dropped` (link_status) stays 0 with the large messages, as it did on 2026-11-23 without them, and no BLE
disconnects. If it moves, the fragments hold the station task too long: look at the fragment cap and BLE notify
failures (the board's LOG line "V2X_RX: ... fragmented (... not taken by any transport)", 1 per 10 s).
- [ ] The same over USB, and once with the app set to Raw frames: RAW_FRAME must still deliver the large ones, V2X_RX must
not send them a second time (`raw_covered_`), and switching back to V2X_RX must work without a reconnect.
- [ ] TX unchanged: a phone-originated CAM (signed and unsigned) is still seen by the node in the same session.
### App refresh: map dashboard, V2X switch, routing (added 2026-11-19)
Map-first dashboard (MapLibre, glass panels, folding bottom bar), "V2X ON/OFF" switch in the MicrOBU
box, V2X sending decoupled from trip recording, "Where to?" search and bicycle routing. Built, 185
unit tests green, and driven on the emulator with a mocked GPS fix (map, search, route preview and
guidance all work). Not checked without the ESP32-C5 or a phone on a bike:
- [ ] Connect the ESP32-C5 with no trip recording: V2X turns on by itself and the second ESP32 (or
`tools/cit_one_rx_watch.py`) hears the phone's CAMs. Switch it off on the Connection screen (tap the
MicrOBU box on the dashboard): they stop, and the dashboard box reads "V2X OFF".
Unplug and reconnect: it is on again, even if it was switched off before.
- [ ] Screen off for 5 minutes with V2X on: CAMs keep coming at 1 Hz (`V2xTransmitService` holds the
process and GNSS; the "V2X on" notification is showing).
- [ ] Connect while the app is in the background on Android 14+: the loop still sends if the foreground
service is refused (the start is allowed to fail), but the notification will be missing.
- [ ] CiT One selected: the V2X switch is disabled and mirrors the link, and nothing is sent by the phone.
- [ ] MicrOBU box shows the real battery percentage over BLE and USB, amber and red at the warn and
shutdown voltages.
- [ ] On a ride: heading-up mode tilts and turns the map with the course; guidance announces the turn
before the corner; going off route reroutes within about 15 s.
- [ ] GLOSA hint (speed box) at a real signalised junction with MAPEM and SPATEM on the air: the
advice matches the lights. The rules are unit-tested only; never tried against a live signal.
- [ ] Motion gate (`MotionDetector`): standing still indoors with GPS wandering, the speed box reads 0;
then ride: it never reads 0 while moving, in each mount (handlebar, bag, pocket). Thresholds
(`ENTER_STD` 0.15, `EXIT_STD` 0.07 m/s², 8 s hold) are from synthetic data only; a smooth-road
ride on a handlebar mount is the case most likely to need tuning. Not applied to the CAM speed
the phone transmits yet, which is still the raw GNSS speed.
- [ ] Settings > Developer > CAM pinger (moved from the V2X screen): starts and stops, shows the
loopback count, only appears with the ESP32-C5 selected.
- [ ] Decide the satellite and terrain tile provider (the layer buttons are in the map settings,
disabled until `MapLayer.styleUrl` has a source), and where routing and search run for real:
the app now sends the rider's position to photon.komoot.io and valhalla1.openstreetmap.de, which
are shared demo instances.
### Why the simulated car drops out of the V2X screen while the phone transmits (added 2026-11-19)
The bench beacon (`obu-cam-transmistter`, station 0x0BADC0DE) vanishes from the V2X screen for a
moment and comes back while the phone is sending. The V2X screen forgets a station after 3 s without
a CAM (`staleRemoteMs`), so these are gaps of 3 s or more. Hypothesis: the ESP32-C5 shares its radio
between BLE and ITS-G5 and a transmission and a reception collide with a BLE event.
Not confirmed. Read from the firmware source only, not measured: the TX hold for BLE
(`Station::hold_for_ble_guard`) is a busy-wait of at most 3.5 ms, too short to overflow the 16-frame
receive queue, so a queue overflow from transmitting is unlikely; the firmware's own notes say a frame
handed to the radio during a BLE connection event is accepted and never transmitted, and nothing says
reception is spared; frames the radio never delivers (or the PHY flags bad) are in no counter.
Tooling is in: the V2X data logger (schema 3) now records `link_status` once a second, and
`tools/rx_gap_analysis.py` accounts for every gap in the beacon's frames (lost before the radio saw
them, dropped in the firmware queue, or lost between board and phone) per condition, and checks
whether the gaps recur at a steady interval (two clocks beating). Self-tested on synthetic data only.
- [ ] Install the current build on the Pixel. Beacon on, 1-2 m from the OBU, nothing else on 5.9 GHz.
- [ ] Settings > Developer > V2X data logger > Start logging, then four stretches of at least 3
minutes each in one log, switching between them without stopping the log:
BLE with V2X off (Connection screen), BLE with V2X on, then the same two over USB
(cable from the phone to the OBU, Settings > Connection > ESP32 link = USB).
- [ ] Stop, pull the `.db` (`adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/<file>`)
and run `python tools/rx_gap_analysis.py <file>.db`. The table says which condition loses frames,
and where; if the beacon's frames vanish before the radio and only on BLE with V2X on, BLE
coexistence with transmitting is the cause, and the recurrence line says whether it is a beat.
- [ ] If it is coexistence: the lever is in the firmware (the colleague's BLE guard calibrates only
TX), not the app; options are fewer or longer-interval BLE events while transmitting, or USB.
### Sensor fusion phase 1: logging and test rides (added 2026-11-18)
Settings > Ride (phone position, Record motion sensors) and the fusion data in the V2X data logger,
described in `docs/07-sensor-fusion-logging.md`. Unit-tested and built; `tools/fusion_log_check.py`
tested on synthetic logs only. On the Pixel 9 Pro:
- [ ] Settings > Ride: Units is gone, Ride is there; the position and the switch survive an app restart.
- [ ] One-minute bench log with Record motion sensors on: the logger screen shows the mount, the motion
sensor count climbing by about 300 a second, and a raw GPS fix age; the file is named
`..._imu-<mount>.db`; `fusion_log_check.py` on it gives no FAIL (accel, gyro, gravity at about
100 Hz, `phone` and `phone_gps` fixes with `elapsed_ns`, `clock` rows with GNSS time).
- [ ] Screen off for 5 minutes during a log: no motion sensor gap over 1 s in the check (the log
service holds the CPU awake; confirm the sensors keep coming too).
- [ ] Record motion sensors off: the log has empty `imu` and `clock` tables, no `phone_gps` rows,
and no `_imu-` in its name, but still `meta.phone_mount`.
- [ ] Rides, 20-30 minutes each, mount set before Start, each with left and right turns, a
roundabout, stops of 10 s or more and if possible a bridge or underpass. Run the check on each
and keep the files for phase 2:
- [ ] handlebar
- [ ] bag (on the bike)
- [ ] pocket or backpack
### Sensor fusion phase 0: yaw rate about the vertical, fix times on GNSS time (added 2026-11-18)
The phone's own CAM/VAM now take the yaw rate from the gyroscope projected onto gravity
(`domain/fusion/YawRateEstimator`, 100 ms average, gyro and gravity at `SENSOR_DELAY_GAME`) instead of
the raw z axis. They stamp the GNSS time of the fix itself, through its monotonic
`elapsedRealtimeNanos` (`GnssTimeSource.atElapsedRealtime`). The loop's own intervals (elevated rate, VAM
rules) run on `SystemClock.elapsedRealtime`. Unit-tested (`YawRateEstimatorTest`), not yet on the phone.
With the CAM pinger on and a listener that decodes yawRate:
- [ ] Turn the Pixel 9 Pro on an office chair at about 90°/s: flat, tilted about 50° as on the
handlebar, and upright. All three should read about the same yaw rate. The old z-axis value
fell to about 64 % tilted and to about 0 upright.
- [ ] Phone still on the desk: yaw rate stays inside the 1 °/s noise floor, so it goes out as 0.
- [ ] Set the phone's clock 10 minutes wrong by hand (automatic time off) with a GNSS fix: the CAM
generationDeltaTime and GN TST still match GNSS time. Then step the clock back mid-run: CAMs and
VAMs keep going at their rate, with no gap and no time_regression on the micrOBU.
- [ ] Ride with the phone on the handlebar, then in a bag: the yaw rate's sign and size match the
turns (left and right, roundabout).
- [ ] Yaw rate sign on air (fixed 2026-11-18: `CamUperCodec` and `CamParser` now flip the ETSI/CiT
left-positive value into the app's clockwise-positive one). Turn the pinging phone left: a
standard decoder (asn1tools, or the CiT One's `v2x-uca/output/json/cam`) shows a positive
YawRateValue, and the app's own decode of the same CAM reads a negative yaw rate (left, in the
app's clockwise-positive convention).
The logs in `databases/` (not committed) already settled the CiT One side: its CAM topic is
left-positive (316 of 316 turning samples), its `obu_gnss` `yawRate_degps` right-positive
despite the API document (27 of 27, bacospat ride of 2026-03-18). Only 27 samples from one
ride: re-check on the next CiT One ride with turns.
- [ ] CiT One JSON parsers (fixed 2026-11-18): `ObuGnssParser` returned null for every real `obu_gnss`
message (position is under `gnss`, it read `own_info`), and `CamParser` for every real CAM-topic
message (`stationType` is a name). So on the CiT One the ego state never came from `obu_gnss`,
the app's V2X logger wrote no OBU fixes, and the processed CAM fallback was dead. On the next
CiT One session: the use-case engine runs on `obu_gnss` (the phone GNSS fallback only kicks in
after 2.5 s without it), the own station ID is learned so own CAMs stop showing as remote, and
the V2X log has `obu` rows in its `gnss` table.
### obu-firmware on Niklas Dathe's microbu-firmware (added 2026-11-10, bench run 2026-11-11)
Flashed on the production XIAO (COM10) and the phone (Pixel 9 Pro, BLE) on 2026-11-11. Done, by hand
on the bench with the COM3 board as a listener:
- [x] Beacon on air: V2X_RX of the simulated car (port 2001, unsigned, -39 to -52 dBm) reaches the app,
which shows station 195936478 with speed, heading and distance.
- [x] Signed CAM from the phone (CAM pinger, signing on): "tickets 1, signed 113, refused 0, on air 113"
on the Connection card; the COM3 listener hears them as signed port 2001 CAMs, 17 in 20 s of a 1 Hz
pinger (the signature itself was not verified; `test/verify_signed_pcap.py` on a capture would).
- [x] Unsigned CAM from the phone (signing off): the listener hears 82 unsigned in 20 s, simulated car
(about 60) plus the phone (about 20), none signed.
- [x] BLE: the phone connected and ran the whole test; the demo credentials were provisioned (tickets 1).
- [x] Battery: the app shows 4.16 V, about 95 % on the charging cell (the reading was 0 mV until the
divider settle-time fix, c78b663).
Still open:
- [x] Receive path switch (2026-11-11, over BLE): `Raw frames` gave `RAW_CAPTURE mode 3 -> accepted` and the simulated car kept
arriving through the app's own unwrapper; back to `V2X_RX` gave mode 0 and it kept arriving.
- [x] V2X data logger on both receive paths (2026-11-11, 33 s each, the simulated car): `V2X_RX` 103 CAMs, `Raw frames` 106 CAMs; the logger
listens to the same decoded frames for both, so it needs no change. It stores the decoded message, not the radio frame.
- [ ] Fragmentation on air: a RAW_FRAME above one link message (a large MAPEM or SPATEM from a road RSU) reassembled in the
app over BLE and over USB; only unit-tested so far.
- [ ] Count both paths on the same traffic to see how many frames the raw copy drops on a busy link.
- [x] Bond persistence (2026-11-11): the board was reflashed (MTU 517) with its NVS kept; the phone reconnected to
micrOBU-66AA without a pairing prompt.
- [ ] Verify a captured signature with `test/verify_signed_pcap.py` (needs the sniffer firmware).
- [ ] 17 of 20 signed CAMs heard against 20 sent: measure the loss over a few minutes, with and without
the BLE link busy (TX BLE guard).
- [ ] Battery: no multimeter reference (the board is glued in); compare the plateau at full charge with
the charger's 4.20 V, and run the shutdown rule on a flat cell.
- [ ] The Connection settings text still says "the board only advertises while nothing uses its USB-C port"
(the firmware no longer pauses advertising) and the card header says "ESP32-C5 (USB Serial)" while
connected over Bluetooth.
- [x] Pseudonym rotation (2026-11-11): the app sends the pseudonym MAC in the 16-octet STATION_CONFIGURE
again; checked with `tools/station_tx_test.py` over USB and the station's own raw capture: a named MAC
is the 802.11 source of signed and of unsigned frames; without one a signed frame carries the
ticket-derived address and an unsigned one a random MAC. Still to see on a ride: the MAC changes at the
rotation interval.
- [x] TX loss, measured 2026-11-11 with the COM3 listener: USB with BLE off 287 of 300 signed CAMs heard (95.7 %,
the board reports 300 submitted and 300 completed); BLE from the phone's pinger with the screen on 180 of
the 188 the board put on air (95.7 %). So the BLE link adds no measurable loss, and the ~4 % is on the air
or in the listener. One earlier BLE run, during which the phone screen turned off, heard 261 of about
305 (86 %): to check whether Android's changed connection interval (the board logged 48.75 ms once; the TX
guard is calibrated for 20 ms only) is the cause, log the board's `BLE interval ... no calibrated TX guard`
warning over a longer run with the screen off.
- [ ] BLE with several boards: with no bond the app connects to the first micrOBU it hears. On the bench four
advertise at -49 to -55 dBm (4AFA, 3FAA, A25E, 66AA) and it paired with the wrong one (4AFA). Pair the
right board in Android's Bluetooth settings first, or add a choice to the app.
- [ ] A phone whose bond is gone (it showed none after a Bluetooth toggle) gets a connect-then-drop loop from a
board that still holds the bond: erase the board's NVS (`esptool erase-region 0x9000 0x15000`) and pair again.
### MAPEM decoder and traffic lights per lane (added 2026-10-28)
`MapemUperCodec` decodes every recorded MAPEM (17 from the 2026-03-18 drive + the bench RSU's)
field-for-field like asn1tools (`MapemUperCodecTest`, fixture from `tools/mapem_corpus.py`).
`TrafficLights.join` puts SPATEM signal groups on MAPEM lanes: on the recorded pairs, 340 of 341
signalled exits find their SPATEM movement (3/165's group 65 is never in its SPATEMs), and the
geometric turn fallback agrees with 198 of 201 stated maneuvers (`TrafficLightsTest`). 132 unit
tests pass. Installed on the Pixel 2026-10-28 16:38 (from Android Studio); not yet seen live, the
RSU was switched off.
Needs the Pixel (new APK), the XIAO on COM10 and the bench RSU sending CAM + SPATEM + MAPEM:
- [ ] Dashboard: the signal card says "MicrOBU test crossroads" instead of "Traffic light -1/23".
- [ ] Walk or ride toward the bench crossroads along an ingress lane (the RSU's refPoint is
53.554698, 10.022548; lanes run 12-72 m out N/E/S/W): the card shows "North in · N m to the
stop line" (or the lane you are on) and chips with arrows (↑←→) in the group's colour.
- [ ] V2X map: the light stands on the reference point (no RSU CAM needed), 4 ingress lanes in
their signal colour, the rider's lane thicker, 4 egress lanes grey.
- [ ] logcat `handleMapUper[serial]: decoded station=... -1/23 rev 1 (8 lanes)` about 1 Hz, and no
"unexpected BTP port 2003" lines.
- [ ] V2X data logger: `MAPEM` rows with `source='esp32'`, `lat/lon` = the reference point and a
summary naming the intersection.
### XIAO ESP32-C5 battery: voltage, low-battery warning, shutdown (added 2026-10-05)
The production board is now a Seeed XIAO ESP32-C5 on COM10 (8 MB flash), on a LiPo with no protection
board. Firmware reads the cell (GPIO6 behind the GPIO26 load switch) every 5 s, puts it in STATUS
(octets 103-105), warns below 3.50 V and deep-sleeps below 3.30 V when no phone is on USB; the app shows
voltage, percentage and the warning. Details: `obu-firmware/FLASHING.md`, "Battery and pins".
Host tests (`make battery`, 6 groups) and the app's 116 unit tests pass; the production image was
flashed to COM10 on 2026-10-05 and `tools/station_status_watch.py COM10` showed 106-octet STATUS with
3998 mV, stable over 18 s. Backup of what COM10 held before: `firmware-backups/COM10-xiao-before-obu-firmware-2026-10-05.bin`.
Needs the XIAO, the cell and a multimeter (shutdown test: also the phone, or just the PC script):
- [ ] **Is the reading right?** (3998 mV before the cell was soldered, 4078 then 4104 mV after, rising as USB charges it.) Measure the cell at the BAT pads with the multimeter while the board runs and
compare with `py -3.11 tools/station_status_watch.py COM10`. Off by more than ~2 %: set
`CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` = 1000 x multimeter / reading (the divider is 2 x 100 k into
the ADC, so a high source impedance can read low). Unplug USB first to see the cell alone: with USB
the charger holds the pin above the cell voltage.
- [x] **Low-voltage shutdown and wake (done 2026-10-05 on COM10, cell soldered):** with the bench image the flags were 0x03 at once, the board stayed up for 85 s while the script talked, then slept 87 s after the script stopped (its port close resets the board, so that is 60 s grace + 30 s) and woke every 30 s, measured 4078 mV < 4100 and went straight back to sleep. A RESET press recovers it. Production image reflashed afterwards (c13c389-dirty, IDF v6.0.2, 4104 mV, flags 0). Original steps. Build with
`CONFIG_MICROBU_BATTERY_WARN_MV=4150`, `SHUTDOWN_MV=4100`, `RESUME_MV=4100`, `SLEEP_S=30` (edit a
copy of `sdkconfig`, `idf.py -B <dir> -DSDKCONFIG=<copy> build`), flash it, then expect:
`station_status_watch.py` shows flags 0x01 (low) at once and 0x03 (critical); the board does NOT
shut down while the script keeps talking; stop the script, wait about 2 minutes (60 s uptime + 30 s
+ sampling): COM10 disappears (deep sleep); it reappears about every 30 s for a moment and goes
away again while the cell reads below RESUME_MV. Then flash the production image again.
- [ ] **App** (BLE checked 2026-10-05 on the Pixel: the card shows "Battery 4.12 V · about 90 %"; USB and the low/critical look still to do): with the phone on the XIAO (USB, then BLE), Settings > Connection > ESP32-C5 shows
"Battery 3.xx V · about N %"; with a bench image whose WARN_MV is above the cell the card turns amber
with "Low battery" and the top bar shows the battery-alert icon.
- [ ] **Does the ADC read disturb the radio, or the radio the reading?** Connect the phone, transmit CAMs
(radio on), and check the STATUS voltage does not jump by more than ~50 mV during TX bursts and
that `radio_failed` stays 0 (the C5's ADC power is shared with the Wi-Fi PHY's power detector).
- [ ] **Charge current and charge time.** The XIAO wiki gives no figure for the SGM40567. Measure the
current into the cell with USB plugged in (multimeter in series in the cell's + wire), and note how
the cell voltage rises. A 5000 mAh cell charged at ~100 mA takes days.
- [ ] **Idle current from the cell** with the radio off (before Connect) and on, to estimate runtime.
- [ ] Decide whether the cell needs a protection board before it goes anywhere but the bench: nothing
protects it from a short, an over-current or a charge outside 0-45 degC.
### On-air check of the V2X data logger (added 2026-10-02)
Needs the phone, a second station sending (the simulated car works) and, for the CiT One part, the OBU.
@@ -290,27 +18,15 @@ Settings > Developer > V2X data logger. 110 unit tests pass. ESP32-C5 path check
- [ ] **CiT One:** same, `source='cit_one'`, `rssi_dbm` NULL, `obu_*` filled from `v2x/rx/obu_gnss`.
Expect both `channel='raw'` and `channel='processed'` rows for the same CAM.
- [ ] **Screen off for a few minutes** with the log running: rows keep arriving (foreground service).
- [ ] **MAPEM and VAM on the ESP32-C5.** Firmware side done 2026-10-28: `gn_unwrap.c` accepts 2003
(MAPEM) and 2018 (VAM), signed or not. The bench RSU's MAPEM is 295 bytes and fits; real
road MAPEMs over 494 bytes are still dropped as oversize (no fragmentation). On air with the
bench listener on COM3 (`tools/bench_listen_watch.py COM3 90`): 104 MAPEM (295 B, GBC), 185
SPATEM (58 B), 472 CAM in 90 s, 0 oversize. COM10 app-flashed 2026-10-28 (d0fcb45-dirty, NVS
kept; STATUS 106 octets, 3999 mV). BLE reconnected to the Pixel on the bond it already had
(16:38, bond state 12, ATT MTU 517, credentials loaded, 1 ticket). Still to do (RSU off): a V2X
log shows `MAPEM` rows with `source='esp32'`. App side: MAPEM is decoded since 2026-10-28 (see
"MAPEM decoder and traffic lights per lane"); VAM (2018) still gets "unexpected BTP port" from
`CamUseCaseRepository`. On the CiT One, MAPEM arrives via `v2x/rx/mapem` (subscribed now) or
the processed `v2x-uca/output/json/map` topic; the API lists no VAM topic, so no VAM rows are
expected there.
- [ ] **Signed SPATEM/MAPEM on air.** On 2026-10-28 the bench RSU sent CAM, SPATEM and MAPEM all
unsigned, so the signed path for these two is checked on the host only (`test_secured_gbc`
in `test_chain.c`; the envelope code is the one real signed CAMs and GBC DENMs pass). Once the
RSU signs: `bench_listen_watch.py COM3 60` must show the `signed` column equal to `count` for
ports 2003 and 2004.
- [ ] **MAPEM and VAM on the ESP32-C5 need a firmware change.** `gn_unwrap.c` accepts only BTP ports
2001, 2002, 2004; add 2003 (MAPEM) and 2018 (VAM) and reflash. Real MAPEMs are mostly over the
512-byte link limit, so most will still be counted as oversize drops. The app side already logs
any port. On the CiT One, MAPEM arrives via `v2x/rx/mapem` (subscribed now) or the processed
`v2x-uca/output/json/map` topic; the API lists no VAM topic, so no VAM rows are expected there.
### Signed-TX firmware (vanetza-idf port), VAM and BLE: first on-air checks (added 2026-09-23)
obu-firmware is now a port of Niklas Dathe's `microbu-esp32c5` station (vanetza-idf, TS 103 097
obu-firmware is now a port of the colleague's `microbu-esp32c5` station (vanetza-idf, TS 103 097
signing, station-link protocol, BLE GATT), built with **ESP-IDF 6.0.2**. See `obu-firmware/NOTES.md`.
The previous firmware is backed up in `firmware-backups/` (restore command in its README.txt).
The app speaks the new protocol over USB or BLE and still falls back to the old frames against the
@@ -318,14 +34,14 @@ old firmware.
Done without hardware: IDF 6.0.2 build clean (39 % app partition free); host suite (`make` in
`obu-firmware/test/host`) passes unchanged; app unit tests 103/103, including the VAM encoder
against asn1tools, the station-link codec against Niklas Dathe's Python `messages.py`, and the VAM
against asn1tools, the station-link codec against the colleague's Python `messages.py`, and the VAM
generation rules. Flashed to **COM3** 2026-09-23 (hash verified); boot log: IDF v6.0.2,
`BLE advertising started as 'micrOBU-4AFA'`, station task ready. The radio stays off until the app
configures the station. New app build installed on the Pixel 9 Pro (adb, `install -r`).
First phone session (user, 2026-09-23): BLE works and CAMs go out. Three faults, fixed and
reflashed/reinstalled the same day:
1. No RX until the CAM pinger ran, with ~177 RX-queue drops: Niklas Dathe's `Station::tick()`
1. No RX until the CAM pinger ran, with ~177 RX-queue drops: the colleague's `Station::tick()`
returned before draining the radio until the first PoTi had set the clock. Now drained always.
2. "refused a request: time_regression": the loops re-send the latest fix every tick; a stale fix
timestamp read as the clock going back > 1 s, and each time the board rebuilt its stack.
@@ -336,7 +52,7 @@ reflashed/reinstalled the same day:
Second session (user, 2026-09-23): USB, RX and signing work; BLE still prompted every time and
never connected; time_regression every ~8 s. Found and fixed, reflashed (full flash, NVS erased):
4. The board never stored a bond: NVS (24 KB, Niklas Dathe's 4 MB-board layout) was full, mostly
4. The board never stored a bond: NVS (24 KB, the colleague's 4 MB-board layout) was full, mostly
Wi-Fi settings the previous firmware left behind, and NimBLE's bond write failed. NVS is now
80 KB (app moved to 0x20000) and was erased; boot logs `N bonded phone(s) in NVS`.
5. The station loop waited `pdMS_TO_TICKS(5)` = 0 ticks at 100 Hz, so it spun on the single core
@@ -372,13 +88,13 @@ resets the board, the phone is on the other port.
- [x] **Unsigned toggle.** Signing off: the same capture shows next header 1 (common header), as
the previous firmware sent. The card's `signed` count stops rising.
Confirmed 2026-09-23: unsigned pinger CAMs show on V2X2MAP as unsigned.
- [x] **Signed VAM on V2X2MAP.** Since 2026-09-23 17:16 the COM10 bridge is Niklas Dathe's
- [x] **Signed VAM on V2X2MAP.** Since 2026-09-23 17:16 the COM10 bridge is the colleague's
v2x2map-0.3.0 from source with a new `verify.py` and `--trust demo-chain.vcr` (launcher:
`micrOBU_workspace/v2x-obu-esp32c5/start-v2x2map-signed.bat`, replacing its-g5-bridge.exe).
Signed CAMs from the pinger already show "signature verified" live. Switch to VAM with signing
on: the VAM must be decoded (cyclist, position) and show "signature verified" too.
Confirmed by the user 2026-09-23: signed VAMs decode and verify.
- [x] **VAM.** Transmit VAM: BTP port 2018, psid 638; with `tools/wireshark/psid-vru.lua` from Niklas Dathe's microbu-esp32c5 repository
- [x] **VAM.** Transmit VAM: BTP port 2018, psid 638; with `tools/wireshark/psid-vru.lua` from the colleague's microbu-esp32c5 repository
Wireshark decodes the VAM (stationType cyclist, bicyclist profile in every ~2 s VAM). Rate:
≥1 per 5 s standing still, about one per GNSS fix while riding.
Covered by the V2X2MAP check above (decoded VAM, psid 638); Wireshark not needed.
-36
View File
@@ -1,36 +0,0 @@
# Stored MAPEMs. One UPER MAPEM per line, hex, each below a comment naming its intersections.
# Written by tools/mapem_bundle.py; add to it with that script.
# -1/23 rev 2 Berliner Tor / Kolbergstrasse
02054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
# 1/1 rev 2 MAP_ITS_03\310\5.2
020500ff3b6208000308cd8342fc9a94efb067719b16171aae6500010001042ac7d5cd389e98d881450d240314200000057fb8d632200bce2061ad419ea25e00b0c8000101100c22200000059f074a9208f383d45501c3ae04804284000000b3028afdd1005e7102f56a8cf4b2f10585c00008108059110000002cf9d66620479c1ea2a80e1d70240e14021000000afe339584401544436946e3336cd18161f0000406201e4404200000166fb9320822a20f5136070eac12049210000002da0a08c79440179c983032e44c65da950583400018208030910000002cc6471bc0479c01555001829524082420000005b405716c08802f393038666c98e9b4ca0b0580003051005122000000598a2612208f3802aaa003052a480e484000000b3fb5a9011005e726084ccb931dd694c1609000060c2008244000000b30d2bda811e70055540060a54900450800000166133693a200bce205cad619e8e5e40b0a8000107100a22200000059f6e4ef808f383d45501c3ae0
# 1/1 rev 3 MAP_ITS_03_312_6.3
020500122a7408000308cd8342fc9a94efb0677d9b1657db2e6700010001062ac7e6c6389e8341014524240624200000059ea6242680020f415a1ec1588e2b0f800010c58190001008807a1100000024c39963a0047520009a34400c488800001275dcc1282adf5432370612029210000002cf37d0e1400107a6ac8f5e2c3f05874000086880721100000024c1d54ff004d518015aa09010908000001678e47d7a00083d55607af462682c36000043840350880000011fff07a800a6a209f39744818884000008b2e9d3f290004010d4a213ca82111ad0e8406d62116d4d68858e97467aa96a885aa924436b45c23d796a1058d3a083a6a50464733833c0cbd4669e94f0c8072c4103fcbb04b1c511588900018cac26000103c4044c8880000126576511013e0d00a711e201244400000093af12d881eb2b01e74b60902d1080000115fc181fa80020096a4109f540888ce878201eb208b6e6b442cb4b833d54b5442d549221b4a2e11eb4b5082d69cc41d3528232199c19dea5f03346ca8c63f7963881d25e025263702c2200010404020888000001276bc64a03d65603ce96c12052210000022bfb788c50004014d442140a801118d0f0401566116e4d60859e97067aa96a885aa924436545e23d596b105cd39083a2a50463f33a33b9cbe8667c9540c7d52ca10344bd048d4700583c000208880391100000024ef2cdc507aaac079d2d8241034220000459a259348800204f8341af5cf8611763104bd05d624aa065128a0f7894104006bc13240944056c49e62aa158c3a828600085500c622eb8730895ccd000030ba13ca530488e430eb0920005125841000289ac1c800145161a8000a34b0e400051b587a00028e2c0e00020256568000a3a4804284400003b386364310004156faa39c2e57035afc482b6f2813cf0819cdb785571ada1979ba9161e4000c04b0e200060358690003022c460001c156564000c164802284400008b399d62a10004156faa2a42e231d0a74fa39696cb07321e5992446dae872dbc7a8ebb98b61552610872ffbd15a5e5087ccf660f91e9e1c977e43c4680876ec760f448f61f5b1bcd60e8000c0cb084000607584a0003042ca9000182840ad08084000002ccd297ba0460c01c590010ab6102a22021000000b38ab28f0118307acb383d159810498102000000ced41692400104bef10084c04104d8102000000cdbf17ed400103430f008480810518102000000cd5a8a54400104baee008540c10558102000000cc7bcbaa4001034712008501010590084000000cedf14c3400104bef08085c14005c8084000000cd63565e400103410d020c2010800000198af19ba8002068a20010c83000c901080000019aee16ac80020979dd042c604080000033c1c4df11005e7043d2f828b4245410b58102000000ceb84f91440179c0f13420a2c0a16042e604080000033a813b591005e7043f2f828bc2c5c10bd8102000000ce568b4e440179c0f0b420a2e0c18043060408000003326059991005e704412f828c4347810c58102000000cc4c12e7440179c0f53720a300e1f04326040800000330d948d51005e704432f028cc3c8010cd8102000000cbe80ebb440179c0efb440a32102100346021000004b46d8a439011511e0c1d8a4cb65b8926d06c5e07ab22d1f7516880fe5da278bab400f658c450f407da2e614f600356021000000b6a9c1bb5811511071d308806ee200
# 1900/2396 rev 3 MAP_ITS_23_2396_12.3
02050000302908000309cd8342fc9a94efb2677d93372dafb164b99c1db0257018ab1d58e8e27e146a05147090109080000036724ae59a00082bf0c873a533b86ab9744e0f30280082b0f800011b581200010f0807a1100000024c7271ad0283e701d9938901490800000267454e862200b9c0afc325d81822680081a9433856210000238b0b2000226101042200000049982e3d20507ce03794c12099201080000059d293e968802ce02c00c4940c976e2b14800011d589100010f880a2101080000059a3d628608c18141f380fad9620042440000012f9c386f0479c083bf6815a10400402d50288091901080000059fb1c8a208ce0741b960462fa92049a10000002cf2f675e400107d6d59337672e4160e8000640200e444000000b36da793011e7057e1902305ec9028d08000001679c9464a200bce0fadab26710e4a82c0a00010849044d0084000002ceca6a5144017381f63564ce21c951581c0002112c508000cdc400c48084000002be5766e0118302dcd220224750010903510800000165f65842a0008141f3849d7eee0b0b4000523100b32200000059ed9cbb208dfa3eb6ac12280586f092072210000002cbab7026440179c0a0f9c24e7f3a1583c0003122c08800149490045088000055f69ed86880319003180044a105023267dc19ec9ec221fd7801103bc52ac2e0001c9d60e4001050b082000829589400039b2c3d00020e1620800107220104404200000166abcf410233809194d052051120aa201080000097df5f51a200b061627950072de224f7e6515844000495ac0c80028a810598102000002cc90aebd400142bedca002018f738142e1658082ec08100000066a9780a200083129e4142c185a0830c0810000005f9539de800203c182050c8697020cb020400000598af5cae8002890e1f4004059b2f8286038bc10698102000000ce416b404001031d8a8286c3cc0106d8102000000cf0c2383400104e475828683cc410718102000000bf0debb500040d06380a1d1032041d60408000002ffb15c3400104c0720287044cc10798102000000cd03e0c5400101aaf68287c48d0107d8102000000ce9f212e400106a7098287848d40
# 3/120 rev 1 MAP_ITS_01_120_6.1
0205000177d308000308cd8342fc9a94efb0637d8b2617db2e6300030078022ac82671b8a0b56681450d24082420000009b0b7aaf068002007d7d19e59bdc336c362416070000210200624400000096234d61701f050c0ca66424072420000009b0c26ac968002007d7d026ce490efc723816090000212200824400000096248d5c701f050c0d0e7424062420000009b0cc0aa228002007d7d080962c3107b510160b000020a200a24400000096261157941f050c0d82502401142000000db0fc4b77480020f76960f87a503d0ad0bc79c59d402c2a000081840288880000012c26a2d6700225b426f5aa12010a10000006d883e5a74400107c1430b95a9745ea760a3cf1cf101613000040e20124440000009614e56644008aba13a8d84102d8102000000d86415bfe4001032b83828300c0410318102000000d86ed5961400104ac708282c0c0810358102000000d871b5886400103599002838100c10398102000000d87f954df400105027c028341010
# 3/121 rev 4 MAP_ITS_01_121_17.4
0205001233b4080003094d8342fc9a94efb0637d8b2637d8b75cd2000600f211558fedf6713dabfa1000028a1648042804200000461f312fd8230614fdc0c4cf1896272fc441ba6f9ae4761b7ed0585c0000808805990108000001619f932823061bca52c900450c00000518076e341515ba04d9582c271ad0113b9eec89daf8b08ebaeeb00b0a8000102100a3230000000628f98c86f294b2408342000000d65639ec023ce0bc87315ca1680f3262e715db99b82c18800080c4018888800001596176a20970839bc6c386ab992049a010800001165c5ab2823060bb87a15a395f0afc0a005b9e08a2c4a27e1582c0001822c188000814401448084000002b0c0f68c11830315ea81a1ff8901cd0c0000045913a65c08f382f71ac57385883cbe0c641b58521d003d41609000060c20082460000008c0e9d5b0311ef05cfe08040c60408000000cb496b0061f3f828341030103581020000003014d07c078b020a0c040d
# 3/165 rev 1 MAP_ITS_01_165_15.1
020500ffef5d080003094d8342fc9a94efb0637d8b66b7d8b55cc60006014a04558f6b78713f201c028a364802284000001b33e3b8c100040ef7fab781e42500100fec303744f578961b0000202b1220002025889000103080699100000024d519dfa049209022245c40490888000011f11e60c01390a099d54a4820884400000afcd8fe8400100a0859557cd9ebc56150000618b0b800030e100a22200000049fe5d2fe0e7b1607ffb91207a210000002bee6440d0004027214555f367af0584c000186880491100000024f9f2a440e16ad00daef7100b22021000000b68056211811830e626d40e12172405242000000d9d5252d880023c10d5205c537262e3faab1707ce302c35000103c9018908000008673e753ea0008f05154c16fb5c40bb02bb05e073cc3f04474c781990a8f2b13721e25a9243d2ed82416230000a2020228440000008f9dd1e5009c8504ceaa5240724200000219d5058fa8002aed1c60400416f65cb0bc0abf45e6d3e43f0547505fed4183c9a4d90787da428f4b16060589400028892061a11000006cda81e3440010492091612197b20918f19604973cd51458510003092c24800184d6164000c28b0380007045824000382920e1210000004ce74320940010e2b41c1e8ad8538c2b2200202c0c801040c400c48800000126e8fad98211d6c2fe76488020901080000059cb06a5c08c182b8f2415ada64836480420000016667b4bda200ad407e67103ed3c02c3900020544038c8084000002cd075dd60460c124824088917240824021000004b3960b365100551176a63106d8f01160ed380b4c295c5d194622d7e9812681d23d0fa5153e0ff17b23d7ada3016250000a2c480428042000001665e96d0a200b06276ad495432f25a00202c3a000241c104d8102000000cca3ec05440179c0cf3d80a140a08041460408000003371db3e11005e704c50a0084c2410558102000000cdfd6c42440179c0f34c00a160b0a04166040800000339da94cd1005e70434d0028542c2c105d8102000000ccd1a110440179c0d3ba60a180c1704186040800000336ec8bb11005e704b3168285c306010658102000000bfd757351005e703a33782868346410698102000000cc6020f9440179c1123460a190d1a
# 3/1745 rev 3 MAP_ITS_17_1745_10.3
0205001232f808000309cd8342fc9a94efb16f7d8b768d6fb160b99c000c1b441aab20465ce27b0616200005142c9018500840000029cdab9811831be7757237397f3c160700002022006640420000014eca07808c18a1a4d701130f2480a28400000107be3e71bdfb7b02763f7313a5f2c02c0a00004084008c880000010fd80c408c00f14389e912009a100000022e1e3902466a17006191ec0583c000101880389100000022dc876e13eb63681e7ff09010d0084000002af164ba0460c9109184e38b68e58161100004082010240420000015767bcb8230627d6c7703d9f20205b020400000058a2ba0899615400405060185820630204000000388cc701917d014160818081ac08100000016992fc21847b50010141c061a081cc08100000017afb170258840141a081c
# 3/2052 rev 3 MAP_ITS_20_2052_12.3
020500ffb03a08000309cd8342fc9a94efb2617d9306acafb164b99c000c20101aab1e4648e2792cf4200005147090045088000012ae75c04981c3fc0af425700c8b0d200010758610000842c19000082560e8000414b08400020b100d4220000004ab43ef77211deee423f1e00806211000000255a2f7a5208797761300f50401888800000120b8a97e07cdbd20e6a7c4200e444000000905b146b83ac1f207a9bd5100822021000000b05b242b411830e6f7c81f28f50900c90800000220af6ee48700c2b164fc27a3da35900101604400060c200424400000095784205742e3bd205e9e6f2404242000000882c6b8f61c030a55ccf0ea80084ecde1f20586c0002021202921000000241669b230e1e8425a1908269058640002029204a21000000855a3271aa0901774433c9e8a19741bfa20c68e211d4cb282c1e000140890291080000042ad05397784753c821a86f430cb7ae071091c6a88f22548160d0000a024816880420000056ad90b85d822d41344f6086dcbd3e210366a115fba3080ea34047072f80b088000503040e604080000015718dfd3c06c3ac0a0f060e040f6040800000157df5fefc1944540a0e060f04104021000001b00937ad811510e408dc1d26fe87d4687c9364585f014220e20002240420000006ae33bf0a022a223e379604126040800000103c179400f8cf40a130813041360408000001041e69b010e1aa0a120812041460210000003023a78e8118303f92e02854245010558084000000c09b5a490460c1049a80a140915041660408000001045f4e6c1096560a170a16041760408000001042e41a40f71aa0a160a1704186021000000302ce4e841183042f95828642c6010658084000000c0a3d0730460c0f49aa0a180b19041a60408000001573d9dc4c0663de0a1b0c1a041b6040800000157b79dcbc195c2c0a1a0c1b041c602100000035734de22411830176f202874347010758084000000d5ec978a30460c195c1e0a1c0d1d
# 3/2349 rev 5 MAP_ITS_23_2349_7.5
0205001225f4080003094d8342fc9a94efb2677d93368e6fb75cd60006125a15558ef699713ed5421000028a32480628400000210dd38b307adb8d50fd212fb05ab16030deb8169c6c0b08400010410082220000004816f339a186c76031b42312051a1000000255ab37dd109db78654f907a8b15841000103ac160001018901c908000004210c0d4f8e26a6b0146282d061e1af13b19a906239b1158290001842c108000c24401448800000121c5b01c831e898595f156200824400000090dee85fc19d45c2ca58a824093420000004ab50afe2213b4f0ca9f2cf4d80b04800040524011402100000110d8195a09810c4e83c5748003d127582c3200014084030c8084000002559df82ee00f0ea08dc9e10900850800000221b5120e930ef8b0c5ea73302c0a9080585c0002818805991000000255a06819e01b8ee88c2ddec901890800000220e3cd351232117c07112216961cccdfcc16168000c14081ac081000000217ed2e681e2ca8141c0e1a081cc0810000002193cfa7820f60c141a0e1c081ec0810000002adab420381ed9f41420101e0820c0810000002add6c085a2165c10010141e12200822c08100000060cb4dc40230682d5d0400405090508820930204000001847937b208c182bb86c142216240826c08100000060280d8c023060529f5050a0589820a3020400000181c8366608c1a37f895001014261828082a804200000160148e0e022a2434b5e1b2adb7bdf182858342c00588084000000c0dddc35045451bec288008082e804200000060c78e3b022a282e1d34004050c0706000c101080000058494b9be08a8876547d07c51a820fb0204000000ab7a2ffd287ce9140040510078f821030204000000ab83efa6c083d85050f84100
# 3/2394 rev 4 MAP_ITS_23_2394_9.4
0205001230ec080003094d8342fc9a94efb2677d93372d2fb95cd2000612b411558ef699713ed5421000028a2a480248042000002276537e41352fa0187e4eae20b232790161b0000208201a840420000011f6e775412e4d4c2411a3120112100000044ee66e9026a8940b8f2153a91e74a8160b0e8000105100e42200000047dfcd300485b4f096d6b4480e680420000072711f1330e7745db154609e8e8505fb5cdc8f1480082a4e2f20d442b039f41fb073c33ae82c3500008309018d080000072739316c8e7765da151d0fd0e8bc55115a30148a96cadc3520920e8647a51ce54ec42b0420003075829000184080211100000024f4269620717400728cb5100522200000049e5055560e127a0e55974480648400000213bf6b5249c49d2e83edad69c14947809678005251e02c2500010184024c8800000126a950af02bc0d836a839920622100000043f9e5cf020dd9f8cc4ee1619511c880b058000503240b44200000087f6cb00845234f196fdc18329f38dc16090000a0448148840000020ff594ba084c6a632a037bc4536e52109921c0773ce0b092000601241734200000189bad43cc0ae830155b0460e67a77e1cf18dd60b5c581595995a2a11d90010161c800041c081e80420000026657d178823063261b84844d2dd4332fbbb814200e1400204042000001673b12d4823061c4b3983d6ea00208b020400000099d0c3b40635d2050904088209302040000009cf748780a3a32050884090209b02040000009d69d88c894d4e4004050a0489820a302040000009ce35ff00776720509850a020ab02040000009db5d5d286eaab4004050b058a820b302040000009e12d10408a578050a860b00
# 3/2421 rev 3 MAP_ITS_24_2421_4.3
020500ffa9ca080003094d8342fc9a94efb2697d93464c6fb45cce000612ea0d558ed997713d5c091000028a2648028824000050a83ba1c42fcf8a22e087009109a0126f6242756da84fc6101980f4cc2083ff41236e31890ef08087c4e20c2b0980001015859000284880491090000024c6167cf07d31607f246d24034420000028540df9e22a37b710e244384d34b50953af8002f8b09dcc26311ef95821d7ec091d316c482f86843e5f109158340000812c2c80014204018888000001262c947503ef8c83f623992029201080000089815d9100fd2321ef762924dc7229605824000101880221010800000470b7d8404e63d909567a4480e4840000011304dad2c1f7c643cdec4749c95458c0b0280002041002422000000470dace3000f7882439e992041211000008cc18aa2c0479c3d7a240b1de1d41834360edb79060d0f02c2d0000c14402cc888000011e4d25a0093c110c8907848146864000020f8173670c4b30018d83c010d28c03c8a60434a30ac24800101960c400080e48186844000010f59d338046c080a39070871382b80ac0900018296088000c16081ac0810000001ccd781a07ea53050703868207302040000007378cb1a2116410010141a101c081ec0810000001fa73a1e07d27c050804878208302040000007f22b6d020758c141e12200822c081000000178e62a013b7c0142414220824c0810000001f3ca9d00ba20a05088509020ab020400000073a1c3a21e79fd0010142c102a082cc08100000015dd6f682085ac142a0e2c0
# 3/2422 rev 3 MAP_ITS_24_2422_4.3
02050012453c080003094d8342fc9a94efb2697d93464cafb45cce000612ec0d558edbb6713db4271000028a1648022804200000124e7184f87144432d02ac1ce82c22000040440208808400000239b7ff2c25d5b508b8dd1490085080000011de03e583e53c5acb595d0a660b07800010210072220000004737bf2b84d6b881167b9c120312100000023a8ef010644b72a905e574d41607000040620062440000008f085cb40f9e8f21eeb18c90149048000011c9174ac213e70b207d4e6d02c12000081040104848000011e10b6ee1c5110c5a5113c0812c0810000001d8abc640881760505018482053020400000092cce1fa077ace050482050206b0204000000766ce9001dda20141c061a081cc0810000001dc574e0087969050682070
# 3/2423 rev 3 MAP_ITS_24_2423_9.3
020500ffaf52080003094d8342fc9a94efb2697d93464cefb95cce000612ee0d558ee835713e2ed41000025826481468400000088b6f52463d9757153c45e9d4160f0000208200e4440000008f4296df0e2a86e1ecf15c9024d0800000111547408c7b0eae2a78bbd3702c1a000041440188880000011e7df0461c550dc3d9e2b92041a100000082284fc10020e5088f1d20037b3c00ecf5020ce582c110000818401048c800001242f185c81e4ab42d4ffd920092100000043c2b6a5c38aa1b933e488c0b420307422b0b80003075821000209880599100000023519e4202759e188fd9e3c90149048000021e0d77d61c530dc99dd44445a12783c7158210002042c560000c0c90085088000011bc63d1247523222237efe748ac2c800142562a4008228480628400000211fb6ca700ece3a374ee35c0ea6360233e403ad8e0ac19000182960e8000c16202a6424000008d429a420020e508ef1e201035810200000035e96c980f8d040a0e070d040e604080000009203260103b5e0a0d070e040f60408000000e6ffd6f05a50802840203c1041810200000036ed72c00bd3ee0a0f0810041160408000000eb13c5803eb2e028482444104981020000002e34dc6040ac3828442448104d0084000000acddda4045a8104b2a0a140a0c001420210000002e85bc2d045a80fc4ba0
# 3/2429 rev 1 MAP_ITS_24_2429_6.1
020500ffbb17080003094d8342fc9a94efb2697d93464e6fb65cc6000612fa04558f3b5e713fb33b028a16480228400000136f2ba4725000401215623f755b21ddebb582c2e0000404402c8880000012dfd6ca280750f1915e966412010a10000004dbd7290ba4001003e4b042b99a21c94b9082c32000040840308880000012e038c9a88784f2c15e966412019210000010dbdbc972940010e7bbda2c97bff1682f008f119b1d1e4bf4583cc268205a4fd783cf46d201906bc0b09800030310091220000004b749f29e800e8ff11252858202b0204000001b7f012348800208e5ae05030202020330204000001b7c1b276e8002876a3e40242828141014101d8102000000dbca595644001468448a0121414100a0c0810c0810000006dd8f4bc2200081c6944140e0a0e081a80420000076e0c2cde820008b3db3a477dcd350b15b57c58d1a163cc668245cabe041ae1fe87b16e1b02838082000388084000000dbce298244001084d33a
# 3/256 rev 1 HH02\256\9
02050012346c08000304c890c195c64d5b5c7300030100022ac7c7a8389ef572014534240324200000199b50cc1808f38b1e5c807c676f18f952ee11f1a1fea4e0861aa276811138fd611600587400030088072110000002b900ea3011e700353b04e7c88240424200000199b6dce6408f38b1d9c807c586f30f920ee31f141fea4e0561a9276791138fd5d1600587c0003010807a110000002b9246ebc11e700353b04e7c88240524200000199b8ad0b208f38b1c9c847c486f40f8eeee61f0e5fea4e0261a9276711130fd5916015884000301ac46000181040410880000015ca3f9a608f3801a9d8273e440808a110000002b96af7dc11e700353b04e7c88240b442000000571d7c37823ce006a762ad88446502c1a0001c144018888000001670131d7023ce0fb1a50ec56f84818884000000aa643d2c11e700373b156c422328160f0000e0c200e444000000b37d28a1c11e707d8d28762b7c240d44200000055295c5008f3801d9d4ab62111942b088000707585100068408041110000002cde6e1600479c1f634a1d8adf04028c880000011f325e3c08ec100c403d24802284000000b2a9bc23811e75bcd3166800a473afb2445871000084ac3c80004296204000216b11200010c585400018b92010a10000008cb09f0250479c4f0bafa075fce43e54f8233801a29443e34fa00292c21000083560e800041cb06400020f240934200000087fd26b5061a9f32c43e2a2a926300681960c4001020b07200081158410004092c45000384d6208001c28b0f4000e15587200070b0209203040800009a074bf208199c0509848c00099030408000099eb539a07ea64041440608100001344da7180fbcc80a150a1900152060810000134a89790104b38082c80c1020000268d30788209670142e1634002e40c10200002681d27e81f7990106101820400004d2864f603fb3202864306c006481820400004d3121060406ce020d202040800007416c37821a98414362a38003640810200001597e8201e667c107101020400002a5dd2003d2cf828745874007481020400003997e22c10bcc2083c80810200001d5b7bf8086261050f8b8f000f90204080000744ecb581e867c1081010204000039a9661c0f433e0a21181f002120408100000e8e3e2604313082112010408000076bdee5821998414463240004640410200001d64324a079d9f042440208100000eadb837043530828946884009480820400002c7fcb703cccf8213302040800007dd2f3d02627b4144e0844084ec0810200001e603ea6067a13051302118214201040800007e57e7c82627ac14520a48005240410200001e24bc76067a15042a40408100000fd8f057033d0a028ac3c9400ac81020400004c661fc504c4f602162020408000098a5be020981e3051688130016902040800007edc7df01a087410b901020400003da3c5140cfc2e0a2f1127002f20408100000fafd0c004c2f48218202040800007dab80b82617a814622450006240810200001ee6a120067e16043240208100000fd1f170033f0b828cc4ca400cc80820400004c9ea08204c2f4821a201040800007a92935819f868146a2854006a40410200001f5223660985e6
# 4/937 rev 4 MAP_ITS_09_937_23.4
0205000161d3080003094d8342fc9a94efb0737dcb36f7d9335cd20008075210558f5971713d6892028a6e48042840000022c6c0b9c40010d27c262b5fd6d04692a02de8f01164b04b19200010158b40001012c52000080c4065088800001211eeb9c08d0254c4483312202c64440000090a2f2a1829ec3405110e71014322200000485d4143c159243427882192008a11000006b2582bd90004166f902ba8f452c7d7501092facf54856168000608b041000313100b22220000048d5f923a1e8ca5858a0c364834884400002306464ad90004015d544352e75e02e51c00ba5b00b94722b044000405585c0002830802091100000234af1c50537d8501afde48906110880000160b608c9a000909aaa420642eb9312c3a000141d62c4000810b14200040a100e22220000048d120fe61db6b2859b0bb64826684400001313ec197d000469d62738cf7293720e568530ac12000182560b0000c28481448440000231cb93bf500045a40a182d2b4fb0598c482df0b41673182b04200070b58cc00040612069211000004c758cba940011ff68eba3edcad4c98f33af20b14400090d24255422000005944a82e6800200e6cc0947a720b2a8000a0e102a7222000004b458cb5700fbdc216caba692132a11000002ca44829e4001000f6b84bcd2e0594c0005078814b9110000025a2ff5bea07dee10b655d34908d9088000036c157ae9620008c64ecc118d7540c43c89530219c6a7182caa0002c4090919088000036c1572f5020008c9c8d981894d3c643b214f12197ca6082ca60002c44900c50084000006b0d9ac051005512547788092989d1a09680f09c2b25fc2058bc000609080b990108000005848c15d208a8812d0442a086588028901080000056a9a355022a219c7894545fb0c481848440000131da833c900047bd54a98fceaa0b26b1ee3a02c5900024549054d088000046256038520008d6c074e12219ce00d127027048a809736016328001a2c080cc08100000059f94c10800203a66b0503870b8203b02040000016a67288a0008317654140c1c300810c081000000581d541a800203de8c0504878c8204b02040000016401421a000830b5e014101e34081ec081000000635166592000819c394142020360820c0810000005af6c0d2800209931b0507880e0208b02040000018ce5949a800209931b0509088e8209302040000018c788fca80020670e50508888f020db020400000184f62b94800205d0f7050e090f820e30204000001859fb09c80020a3309050d8910020eb02040000018403a50280020a130d050f0990820f30204000001836da038800205f0f3050e8991020fb02040000018461186c8002038a5905100a11821030204000001866015ec80020c79a7050f8a120210b0204000001892d9084800203ae7005110a928211302040000018a7e0e6280020c559005108a930213b0204000001b08a2b91e80020838d405140b13821430204000001b0860bebe800207cb2c05138b140215a0108000001895212308002039e6605160a948016101080000018aa8103e80020c659a042d60210000003615c97dc500040f26540a2e162a042e60210000003616d972b1000410e1ac0a2d162b042f4021000000317bf219900040ce9ca0a30112c00302021000000318a12bb10004131e36086280420000005a8846b080020c3d82051907168019101080000016740257200080f19f810cd0084000000b1909a7d00041862f60a340f2e0034202100000030f4e6219000407a50a086a8042000000633066aa200081b237c146c205e006c40420000005aa9c31e8002093b21043740210000003087f37a10004079d060a3814300038202100000030d202e990004186afa0
@@ -54,12 +54,11 @@ import com.hawhamburg.micr0bu.ui.screens.LanguageSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SettingsScreen
import com.hawhamburg.micr0bu.ui.screens.RideSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UnitsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UseCaseAlertsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.V2xLogSettingsScreen
import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
import com.hawhamburg.micr0bu.viewmodel.RideSettingsViewModel
import com.hawhamburg.micr0bu.viewmodel.SensorViewModel
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
@@ -72,7 +71,6 @@ class MainActivity : AppCompatActivity() {
private val mqttViewModel: MqttViewModel by viewModels()
private val tripViewModel: TripRecordingViewModel by viewModels()
private val logViewModel: V2xLogViewModel by viewModels()
private val rideViewModel: RideSettingsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
@@ -95,18 +93,14 @@ class MainActivity : AppCompatActivity() {
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
val obuHardware by mqttViewModel.obuHardware.collectAsState()
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
val stationStatus by mqttViewModel.stationStatus.collectAsState()
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
val phoneMount by rideViewModel.phoneMount.collectAsState()
val fusionLogging by rideViewModel.fusionLogging.collectAsState()
val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
// Received hazards and live signal state, for the Dashboard's V2X summary cards.
// Both flows already expire their own entries on a clock, so nothing here has to
// decide when a hazard or a traffic light has gone stale.
val denmEvents by mqttViewModel.denmEvents.collectAsState()
val trafficLights by mqttViewModel.trafficLights.collectAsState()
val spatIntersections by mqttViewModel.spatIntersections.collectAsState()
val ownCamPosition by mqttViewModel.ownCamPosition.collectAsState()
val v2xLogState by logViewModel.state.collectAsState()
val v2xLogFiles by logViewModel.files.collectAsState()
@@ -169,8 +163,6 @@ class MainActivity : AppCompatActivity() {
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
esp32LinkState = esp32LinkState,
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
obuBatteryLow = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryLow == true,
obuBatteryCritical = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryCritical == true,
)
}
},
@@ -193,7 +185,7 @@ class MainActivity : AppCompatActivity() {
obuStationTypeWarning = obuStationTypeWarning,
obuStationType = obuStationType,
hazards = denmEvents,
signals = trafficLights,
signals = spatIntersections,
ownPosition = ownCamPosition,
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
onNavigateToSensors = {
@@ -308,7 +300,7 @@ class MainActivity : AppCompatActivity() {
onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) },
onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.route) },
onOpenSensors = { navController.navigate(Screen.SettingsSensors.route) },
onOpenRide = { navController.navigate(Screen.SettingsRide.route) },
onOpenUnits = { navController.navigate(Screen.SettingsUnits.route) },
onOpenConnection = { navController.navigate(Screen.SettingsConnection.route) },
onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) },
onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) },
@@ -333,8 +325,6 @@ class MainActivity : AppCompatActivity() {
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
outgoingMessage = outgoingMessage,
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
esp32RxPath = esp32RxPath,
onEsp32RxPathChange = mqttViewModel::setEsp32RxPath,
signOutgoing = signOutgoing,
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
onBack = { navController.popBackStack() },
@@ -361,13 +351,11 @@ class MainActivity : AppCompatActivity() {
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsRide.route) {
RideSettingsScreen(
phoneMount = phoneMount,
onPhoneMount = rideViewModel::setPhoneMount,
fusionLogging = fusionLogging,
onFusionLogging = rideViewModel::setFusionLogging,
onBack = { navController.popBackStack() },
composable(Screen.SettingsUnits.route) {
UnitsSettingsScreen(
useMetric = state.useMetric,
onUseMetric = viewModel::setUseMetric,
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsMqtt.route) {
@@ -58,20 +58,6 @@ object GnssTimeSource {
return ItsTime.onGnssTime(systemMs, lastErrorMs?.let { systemNow + it }, systemNow)
}
/**
* GNSS time of an instant given on the monotonic `elapsedRealtimeNanos` base, such as a fix's
* [GnssReading.elapsedRealtimeNanos]: GNSS time now, minus the instant's age.
*
* Prefer this to [correct] on a stored wall-clock stamp. The age comes from the monotonic
* clock, and the wall clock is only read now, inside [correct], where its error cancels out.
* A phone clock that is stepped between the fix and its transmission (automatic time catching
* up, or someone setting it) therefore cannot move the result.
*/
fun atElapsedRealtime(elapsedRealtimeNanos: Long): Long {
val ageMs = (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
return correct(System.currentTimeMillis() - ageMs)
}
private fun noteSource(gnssNow: Long?, systemNow: Long) {
val usingGnss = gnssNow != null
if (lastUsedGnss == usingGnss) return
@@ -1,49 +0,0 @@
package com.hawhamburg.micr0bu.data
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
private val Context.rideDataStore by preferencesDataStore(name = "ride_prefs")
/**
* Settings > Ride: where the phone rides ([PhoneMount]) and whether the V2X data logger also
* records the motion sensors and raw GPS for sensor fusion (see `docs/07-sensor-fusion-logging.md`).
*/
@Singleton
class RidePreferences @Inject constructor(
@ApplicationContext private val context: Context,
) {
private object Keys {
val PHONE_MOUNT = stringPreferencesKey("phone_mount")
val FUSION_LOGGING = booleanPreferencesKey("fusion_logging")
}
val phoneMountFlow: Flow<PhoneMount> = context.rideDataStore.data.map { prefs ->
PhoneMount.fromId(prefs[Keys.PHONE_MOUNT])
}
suspend fun setPhoneMount(mount: PhoneMount) {
context.rideDataStore.edit { it[Keys.PHONE_MOUNT] = mount.id }
}
/**
* Off by default: at 100 Hz the motion sensors add about 300 rows a second, tens of MB per
* hour, which only a fusion test ride needs.
*/
val fusionLoggingFlow: Flow<Boolean> = context.rideDataStore.data.map { prefs ->
prefs[Keys.FUSION_LOGGING] ?: false
}
suspend fun setFusionLogging(enabled: Boolean) {
context.rideDataStore.edit { it[Keys.FUSION_LOGGING] = enabled }
}
}
@@ -6,10 +6,6 @@ import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.SystemClock
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
@@ -19,35 +15,13 @@ import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
/**
* One sample of a three-axis sensor.
*
* @property timestamp wall-clock ms of the moment the sample was taken (not of its delivery), for
* logs and the UI, which compare it with other wall-clock stamps.
* @property elapsedRealtimeNanos the sample's own `SensorEvent.timestamp`, on the
* `SystemClock.elapsedRealtimeNanos` base. Monotonic: use it for intervals and for lining samples
* up with GNSS fixes, never [timestamp], which jumps whenever the phone's clock is set.
*/
data class ImuReading(
val x: Float,
val y: Float,
val z: Float,
val timestamp: Long = System.currentTimeMillis(),
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
val timestamp: Long = System.currentTimeMillis()
)
/**
* One location fix.
*
* @property timestamp wall-clock ms of the moment of the fix (not of its delivery), for in-app
* comparisons with other wall-clock stamps. What goes on air is GNSS time instead, from
* [GnssTimeSource.atElapsedRealtime] on [elapsedRealtimeNanos].
* @property elapsedRealtimeNanos `Location.getElapsedRealtimeNanos()`: the moment of the fix on the
* monotonic clock that sensor samples are also stamped with. Use it for intervals between fixes.
* @property speedAccuracyMps 1-sigma speed accuracy, null when the provider gives none.
* @property bearingAccuracyDeg 1-sigma bearing accuracy, null when the provider gives none.
* @property provider the location provider that produced the fix, e.g. "fused" or "gps".
*/
data class GnssReading(
val latitude: Double,
val longitude: Double,
@@ -55,11 +29,7 @@ data class GnssReading(
val speedMs: Float,
val bearingDeg: Float,
val accuracyM: Float,
val timestamp: Long = System.currentTimeMillis(),
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
val speedAccuracyMps: Float? = null,
val bearingAccuracyDeg: Float? = null,
val provider: String? = null,
val timestamp: Long = System.currentTimeMillis()
)
class SensorRepository(private val context: Context) {
@@ -67,30 +37,12 @@ class SensorRepository(private val context: Context) {
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val fusedLocation = LocationServices.getFusedLocationProviderClient(context)
/**
* @param samplingPeriodUs a `SensorManager.SENSOR_DELAY_*` constant or a period in µs. The
* default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
*/
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun accelerometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_ACCELEROMETER)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs, handler)
fun gyroscopeFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_GYROSCOPE)
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
/**
* Gravity in the device frame, m/s². Points up (it reads +9.81 on z with the phone flat, screen
* up), as the accelerometer does at rest.
*
* From the platform's `TYPE_GRAVITY` virtual sensor, which separates gravity from motion with
* the gyroscope. On a phone without it the raw accelerometer stands in, which still carries
* the bike's own accelerations and vibration.
*/
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs, handler)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun barometerFlow(): Flow<Float> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
if (sensor == null) {
@@ -123,37 +75,9 @@ class SensorRepository(private val context: Context) {
awaitClose { fusedLocation.removeLocationUpdates(callback) }
}
/**
* Fixes from the platform's `GPS_PROVIDER` alone, next to [gnssFlow]'s fused location: no Wi-Fi
* or cell positions mixed in and no smoothing by Google Play services, so a fusion filter sees
* the GNSS chip's own errors. As fast as the chip delivers (minimum time and distance 0); on
* most phones that is 1 Hz.
*/
@Suppress("MissingPermission")
fun gpsProviderFlow(): Flow<GnssReading> = callbackFlow {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val listener = LocationListener { loc -> trySend(loc.toReading()) }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, listener, context.mainLooper)
awaitClose { locationManager.removeUpdates(listener) }
}
/** "name (vendor), max N Hz" for the sensor of [type], or null if the phone has none. For log metadata. */
fun describeSensor(type: Int): String? = sensorManager.getDefaultSensor(type)?.let { s ->
val maxHz = if (s.minDelay > 0) ", max ${1_000_000 / s.minDelay} Hz" else ""
"${s.name} (${s.vendor})$maxHz"
}
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
/**
* @param handler where sensor callbacks run; null for the main thread. A high-rate consumer
* passes a background handler so 100 Hz callbacks neither wait on nor slow down the UI.
*/
private fun sensorFlow(
type: Int,
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
handler: Handler? = null,
): Flow<ImuReading> = callbackFlow {
private fun sensorFlow(type: Int): Flow<ImuReading> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(type)
if (sensor == null) {
close()
@@ -161,42 +85,20 @@ class SensorRepository(private val context: Context) {
}
val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
trySend(ImuReading(
x = event.values[0],
y = event.values[1],
z = event.values[2],
timestamp = wallClockMsAt(event.timestamp),
elapsedRealtimeNanos = event.timestamp,
))
trySend(ImuReading(event.values[0], event.values[1], event.values[2]))
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}
sensorManager.registerListener(listener, sensor, samplingPeriodUs, handler)
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
awaitClose { sensorManager.unregisterListener(listener) }
}
}
/**
* The wall-clock ms of an instant given on the `elapsedRealtimeNanos` base: now minus its age.
* Both clocks are read together, so a clock change only moves the result by the change itself.
*/
private fun wallClockMsAt(elapsedRealtimeNanos: Long): Long =
System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
private fun Location.toReading(): GnssReading {
// A fix without its own monotonic stamp (0, as some mock providers leave it) is taken as now.
val fixNanos = elapsedRealtimeNanos.takeIf { it > 0L } ?: SystemClock.elapsedRealtimeNanos()
return GnssReading(
latitude = latitude,
longitude = longitude,
altitude = altitude,
speedMs = speed,
bearingDeg = bearing,
accuracyM = accuracy,
timestamp = wallClockMsAt(fixNanos),
elapsedRealtimeNanos = fixNanos,
speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond else null,
bearingAccuracyDeg = if (hasBearingAccuracy()) bearingAccuracyDegrees else null,
provider = provider,
)
}
private fun Location.toReading() = GnssReading(
latitude = latitude,
longitude = longitude,
altitude = altitude,
speedMs = speed,
bearingDeg = bearing,
accuracyM = accuracy
)
@@ -21,7 +21,6 @@ import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.cam.CamParser
@@ -30,9 +29,6 @@ import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
import com.hawhamburg.micr0bu.domain.cam.OwnTxLoopback
import com.hawhamburg.micr0bu.domain.cam.StationType
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.MapEvent
import com.hawhamburg.micr0bu.domain.map.StoredMaps
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
@@ -201,21 +197,6 @@ class CamUseCaseRepository @Inject constructor(
*/
val decodedSpat: SharedFlow<SpatEvent> = _decodedSpat.asSharedFlow()
private val _decodedMap = MutableSharedFlow<MapEvent>(replay = 16, extraBufferCapacity = 16)
/**
* MAPEMs decoded from UPER, from the ESP32-C5 (BTP port 2003, since firmware d0fcb45) or the
* CiT One's `v2x/rx/mapem` topic: the lane geometry SPATEM's signal groups refer to. Replayed
* like [decodedSpat], since a MAPEM repeats only about once a second.
*
* The ESP32-C5 forwards only MAPEMs of up to 494 bytes (one link message); road MAPEMs are often
* bigger and then arrive only over the CiT One.
*/
val decodedMap: SharedFlow<MapEvent> = _decodedMap.asSharedFlow()
private val _storedMaps = MutableStateFlow<List<IntersectionGeometry>>(emptyList())
/** The intersections the app ships with ([StoredMaps]); empty until the asset has been read. */
val storedMaps: StateFlow<List<IntersectionGeometry>> = _storedMaps.asStateFlow()
private val _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
/**
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
@@ -226,17 +207,6 @@ class CamUseCaseRepository @Inject constructor(
val decodedDenm: SharedFlow<DenmEvent> = _decodedDenm.asSharedFlow()
init {
scope.launch {
runCatching {
context.assets.open(StoredMaps.ASSET_PATH).bufferedReader().use { StoredMaps.parse(it.readText()) }
}
.onSuccess {
_storedMaps.value = it
Log.d(TAG, "storedMaps: ${it.size} intersection revisions loaded")
}
.onFailure { Log.e(TAG, "storedMaps: cannot read ${StoredMaps.ASSET_PATH}", it) }
}
scope.launch {
mqttRepository.messages.collect { msg ->
when (msg.topic) {
@@ -272,7 +242,8 @@ class CamUseCaseRepository @Inject constructor(
source = "mqtt",
)
RAW_SPATEM_TOPIC -> handleSpatUper(envelope.payload, rssiDbm = null, source = "mqtt")
RAW_MAPEM_TOPIC -> handleMapUper(envelope.payload, rssiDbm = null, source = "mqtt")
// No MAPEM decoder yet; it is received for the V2X data logger only.
RAW_MAPEM_TOPIC -> Unit
else -> Log.w(TAG, "rawV2x: unexpected topic ${raw.topic}")
}
}
@@ -325,7 +296,6 @@ class CamUseCaseRepository @Inject constructor(
BtpPort.CAM -> handleCamFromSerial(v2x)
BtpPort.DENM -> handleDenmFromSerial(v2x)
BtpPort.SPATEM -> handleSpatFromSerial(v2x)
BtpPort.MAPEM -> handleMapUper(v2x.uper, v2x.rssiDbm, source = "serial")
// The firmware only forwards ports it was told to accept, so anything else
// means the two sides have drifted out of sync.
else -> Log.w(TAG, "unexpected BTP port ${v2x.btpPort} from firmware")
@@ -599,19 +569,6 @@ class CamUseCaseRepository @Inject constructor(
_decodedSpat.tryEmit(spat)
}
/** A MAPEM heard over the air: lane geometry for one or more intersections. */
private fun handleMapUper(uper: ByteArray, rssiDbm: Int?, source: String) {
val map = MapemUperCodec.decode(uper, System.currentTimeMillis(), rssiDbm)
if (map == null) {
Log.w(TAG, "handleMapUper[$source]: decode FAILED for ${uper.size}-byte MAPEM " +
"(rssi=$rssiDbm dBm) - first bytes: ${uper.toHexPreview()}")
return
}
Log.d(TAG, "handleMapUper[$source]: decoded station=${map.stationId} " +
"intersections=${map.intersections.joinToString { "${it.key} rev ${it.revision} (${it.lanes.size} lanes)" }}")
_decodedMap.tryEmit(map)
}
/**
* The bits of a received frame the decoders and their log lines need, independent of whether
* it came off the serial link or an MQTT topic. [rssiDbm] is null on the MQTT path: the
@@ -15,13 +15,6 @@ data class LogGnss(
val accuracyM: Double? = null,
/** Epoch ms the fix was taken, so a stale fix shows as one instead of passing for current. */
val fixMs: Long,
/** The fix's own monotonic time (`Location.getElapsedRealtimeNanos`); phone fixes only. */
val elapsedNs: Long? = null,
/** 1-sigma speed and bearing accuracy, where the provider gives them; phone fixes only. */
val speedAccuracyMps: Double? = null,
val bearingAccuracyDeg: Double? = null,
/** The location provider, e.g. `fused` or `gps`; phone fixes only. */
val provider: String? = null,
)
/** One received V2X message, ready to be written. */
@@ -52,18 +45,6 @@ class LogMessage(
/** One GNSS fix for the `gnss` table: the receiver's own track, independent of any message. */
class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss)
/**
* One motion sensor sample for the `imu` table (sensor fusion logging only). [sensor] is `accel`,
* `gyro` or `gravity`; [elapsedNs] the sample's own `SensorEvent.timestamp`.
*/
class LogImuSample(val sensor: String, val elapsedNs: Long, val tsMs: Long, val x: Float, val y: Float, val z: Float)
/**
* The phone's three clocks read together, for the `clock` table: what lines the monotonic sensor
* and fix times up with wall-clock and GNSS time afterwards. [gnssMs] is null without GNSS time.
*/
class LogClockSample(val elapsedNs: Long, val wallMs: Long, val gnssMs: Long?)
/**
* A V2X log: one self-contained SQLite file. Not Room, on purpose: a log is a file the developer
* pulls off the phone and opens in any SQLite tool or pandas, so it carries its own schema and
@@ -76,19 +57,12 @@ class LogClockSample(val elapsedNs: Long, val wallMs: Long, val gnssMs: Long?)
* Columns that do not apply to a row are NULL rather than invented: `rssi_dbm` is NULL for the
* CiT One, `obu_*` is NULL when no OBU position is available (always on the ESP32-C5, which has no
* GNSS), and the `sender_*` fields are NULL for messages the app has no decoder for.
*
* Schema 2 (2026-11-18) adds what sensor fusion needs, described in
* `docs/07-sensor-fusion-logging.md`: the monotonic time, accuracies and provider of each phone fix
* in `gnss`, and the `imu` and `clock` tables. Those two stay empty unless Settings > Ride >
* "Record motion sensors" was on when the log started.
*/
class V2xLogWriter(val file: File, meta: Map<String, String>) {
private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null)
private val insertMessage: SQLiteStatement
private val insertGnss: SQLiteStatement
private val insertImu: SQLiteStatement
private val insertClock: SQLiteStatement
init {
db.execSQL(
@@ -147,39 +121,11 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
speed_mps REAL,
heading_deg REAL,
accuracy_m REAL,
fix_ms INTEGER NOT NULL,
elapsed_ns INTEGER,
speed_accuracy_mps REAL,
bearing_accuracy_deg REAL,
provider TEXT
fix_ms INTEGER NOT NULL
)
""".trimIndent()
)
db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)")
// No index: about 300 rows a second, read back in order by replay, never searched on the phone.
db.execSQL(
"""
CREATE TABLE imu (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sensor TEXT NOT NULL,
elapsed_ns INTEGER NOT NULL,
ts_ms INTEGER NOT NULL,
x REAL NOT NULL,
y REAL NOT NULL,
z REAL NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE clock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
elapsed_ns INTEGER NOT NULL,
wall_ms INTEGER NOT NULL,
gnss_ms INTEGER
)
""".trimIndent()
)
// Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI.
db.execSQL(
"CREATE VIEW messages_v AS SELECT *, " +
@@ -198,14 +144,8 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
"obu_heading_deg, obu_fix_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertGnss = db.compileStatement(
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms, " +
"elapsed_ns, speed_accuracy_mps, bearing_accuracy_deg, provider) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertImu = db.compileStatement(
"INSERT INTO imu (sensor, elapsed_ns, ts_ms, x, y, z) VALUES (?,?,?,?,?,?)"
)
insertClock = db.compileStatement(
"INSERT INTO clock (elapsed_ns, wall_ms, gnss_ms) VALUES (?,?,?)"
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms) " +
"VALUES (?,?,?,?,?,?,?,?,?)"
)
}
@@ -213,20 +153,13 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value))
}
/** Writes all rows in one transaction. */
fun writeBatch(
messages: List<LogMessage>,
gnss: List<LogGnssSample>,
imu: List<LogImuSample> = emptyList(),
clock: List<LogClockSample> = emptyList(),
) {
if (messages.isEmpty() && gnss.isEmpty() && imu.isEmpty() && clock.isEmpty()) return
/** Writes [messages] and [gnss] in one transaction. */
fun writeBatch(messages: List<LogMessage>, gnss: List<LogGnssSample>) {
if (messages.isEmpty() && gnss.isEmpty()) return
db.beginTransaction()
try {
for (m in messages) bindAndRun(m)
for (g in gnss) bindAndRun(g)
for (i in imu) bindAndRun(i)
for (c in clock) bindAndRun(c)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
@@ -236,8 +169,6 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
fun close() {
runCatching { insertMessage.close() }
runCatching { insertGnss.close() }
runCatching { insertImu.close() }
runCatching { insertClock.close() }
runCatching { db.close() }
}
@@ -289,31 +220,6 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
s.bind(7, g.fix.headingDeg)
s.bind(8, g.fix.accuracyM)
s.bind(9, g.fix.fixMs)
s.bind(10, g.fix.elapsedNs)
s.bind(11, g.fix.speedAccuracyMps)
s.bind(12, g.fix.bearingAccuracyDeg)
s.bind(13, g.fix.provider)
s.executeInsert()
}
private fun bindAndRun(i: LogImuSample) {
val s = insertImu
s.clearBindings()
s.bind(1, i.sensor)
s.bind(2, i.elapsedNs)
s.bind(3, i.tsMs)
s.bind(4, i.x.toDouble())
s.bind(5, i.y.toDouble())
s.bind(6, i.z.toDouble())
s.executeInsert()
}
private fun bindAndRun(c: LogClockSample) {
val s = insertClock
s.clearBindings()
s.bind(1, c.elapsedNs)
s.bind(2, c.wallMs)
s.bind(3, c.gnssMs)
s.executeInsert()
}
@@ -324,6 +230,6 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
private fun SQLiteStatement.bind(i: Int, v: ByteArray?) { if (v != null) bindBlob(i, v) }
companion object {
const val SCHEMA_VERSION = 2
const val SCHEMA_VERSION = 1
}
}
@@ -1,16 +1,9 @@
package com.hawhamburg.micr0bu.data.log
import android.content.Context
import android.hardware.Sensor
import android.location.LocationManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.ImuReading
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.data.SensorRepository
import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository
import com.hawhamburg.micr0bu.data.mqtt.MessageDirection
@@ -27,10 +20,8 @@ import com.hawhamburg.micr0bu.data.transport.SerialFrameType
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import com.hawhamburg.micr0bu.domain.log.classifyItsPdu
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -40,18 +31,14 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File
import java.time.DateTimeException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -64,18 +51,9 @@ private const val PROCESSED_PREFIX = "v2x-uca/output/json/"
private const val OBU_GNSS_TOPIC = "v2x/rx/obu_gnss"
private const val SOURCE_ESP32 = "esp32"
private const val SOURCE_CIT_ONE = "cit_one"
/** The phone's fused location (Google Play services). */
private const val SOURCE_PHONE = "phone"
/** The phone's raw `GPS_PROVIDER` fixes; sensor fusion logging only. */
private const val SOURCE_PHONE_GPS = "phone_gps"
private const val SOURCE_OBU = "obu"
/** Motion sensor rate while sensor fusion logging is on: 10 000 us, 100 Hz. */
private const val IMU_PERIOD_US = 10_000
/** How often the three clocks are read together into the `clock` table. */
private const val CLOCK_INTERVAL_MS = 1_000L
/** How long the writer collects rows before it commits them. */
private const val FLUSH_INTERVAL_MS = 250L
@@ -91,13 +69,6 @@ data class V2xLogState(
/** Age of the newest phone / OBU fix at the time of the last update; null if none yet. */
val phoneFixAgeMs: Long? = null,
val obuFixAgeMs: Long? = null,
/** Whether this log records the motion sensors and raw GPS (Settings > Ride), and the mount it started with. */
val fusionLogging: Boolean = false,
val phoneMount: PhoneMount? = null,
/** Motion sensor rows written so far. */
val imuSamples: Long = 0L,
/** Age of the newest raw GPS_PROVIDER fix; null if none yet or not logging it. */
val phoneGpsFixAgeMs: Long? = null,
/** Set when the file could not be created or written. */
val error: String? = null,
)
@@ -120,19 +91,13 @@ data class V2xLogFile(val file: File, val sizeBytes: Long, val modifiedMs: Long,
* not publish `v2x/rx/mapem`). The OBU's position comes from `v2x/rx/obu_gnss`. The API carries
* no RSSI, so that column stays NULL.
*
* Every message is stored, including kinds the app does not decode here (VAM): the UPER bytes go
* Every message is stored, including kinds the app cannot decode (MAPEM, VAM): the UPER bytes go
* in the file untouched, and where a decoder exists a few fields are decoded alongside for
* convenience (for MAPEM, the first intersection's reference point and the intersections' names).
* A message is never skipped because decoding failed.
* convenience. A message is never skipped because decoding failed.
*
* What it can hear is bounded by the hardware, not by this class: the ESP32-C5 firmware forwards
* BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only
* messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One.
*
* With Settings > Ride > "Record motion sensors" on when the log starts, it also records what sensor
* fusion needs (`docs/07-sensor-fusion-logging.md`): accelerometer, gyroscope and gravity at 100 Hz
* into `imu`, the raw `GPS_PROVIDER` fixes next to the fused ones in `gnss`, and the three phone
* clocks once a second into `clock`. The phone mount is recorded in `meta` either way.
* What it can hear is bounded by the hardware, not by this class: the current ESP32-C5 firmware
* forwards only BTP ports 2001, 2002 and 2004 (see `gn_unwrap.c`), so MAPEM and VAM appear in an
* ESP32 log only once the firmware accepts ports 2003 and 2018.
*
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
* keeps the process alive and the CPU awake while a log runs; this class does the work.
@@ -144,7 +109,6 @@ class V2xLogger @Inject constructor(
private val esp32Link: Esp32Link,
private val camUseCaseRepository: CamUseCaseRepository,
private val camCodec: RealAsn1UperCodec,
private val ridePreferences: RidePreferences,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -161,22 +125,15 @@ class V2xLogger @Inject constructor(
private var rows = Channel<Any>(Channel.UNLIMITED)
@Volatile private var phoneFix: LogGnss? = null
@Volatile private var phoneGpsFix: LogGnss? = null
@Volatile private var obuFix: LogGnss? = null
fun start() {
if (session?.isActive == true) return
val startedMs = System.currentTimeMillis()
val hardware = mqttRepository.obuHardware.value
// Read once, at the start: a log is one mount and one mode, so changing either mid-log
// must not quietly mix two kinds of data in one file. DataStore answers in milliseconds.
val (mount, fusion) = runBlocking {
ridePreferences.phoneMountFlow.first() to ridePreferences.fusionLoggingFlow.first()
}
val sensors = SensorRepository(context)
val file = File(logDir, fileNameFor(startedMs, hardware, mount.takeIf { fusion }))
val file = File(logDir, fileNameFor(startedMs, hardware))
val writer = try {
V2xLogWriter(file, metaFor(startedMs, hardware, mount, fusion, sensors))
V2xLogWriter(file, metaFor(startedMs, hardware))
} catch (e: Exception) {
Log.e(TAG, "cannot create ${file.name}", e)
file.delete()
@@ -184,36 +141,22 @@ class V2xLogger @Inject constructor(
return
}
phoneFix = null
phoneGpsFix = null
obuFix = null
rows = Channel(Channel.UNLIMITED)
_state.value = V2xLogState(
active = true, fileName = file.name, startedMs = startedMs,
fusionLogging = fusion, phoneMount = mount,
)
_state.value = V2xLogState(active = true, fileName = file.name, startedMs = startedMs)
refreshFiles()
// Sensor callbacks at 100 Hz get a thread of their own, off the main thread.
val sensorThread = if (fusion) HandlerThread("V2xLogger-imu").apply { start() } else null
session = scope.launch {
val sources = mutableListOf(
val sources = listOf(
launch { collectEsp32() },
launch { collectCitOneRaw() },
launch { collectCitOneMessages() },
launch { collectPhoneGnss(sensors) },
launch { collectPhoneGnss() },
)
if (sensorThread != null) {
val handler = Handler(sensorThread.looper)
sources += launch { collectImu(sensors, handler) }
sources += launch { collectPhoneGps(sensors) }
sources += launch { collectClock() }
}
try {
runWriter(writer, file)
} finally {
sources.forEach { it.cancel() }
sensorThread?.quitSafely()
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
writer.close()
}
@@ -313,7 +256,8 @@ class V2xLogger @Inject constructor(
* can be started before the location permission is granted, and a single attempt would then
* leave every row without a phone position for the whole run.
*/
private suspend fun collectPhoneGnss(sensors: SensorRepository) {
private suspend fun collectPhoneGnss() {
val sensors = SensorRepository(context)
while (true) {
runCatching {
sensors.gnssFlow().collect { reading ->
@@ -326,50 +270,6 @@ class V2xLogger @Inject constructor(
}
}
/** Raw `GPS_PROVIDER` fixes, retried like [collectPhoneGnss] in case permission comes later. */
private suspend fun collectPhoneGps(sensors: SensorRepository) {
while (true) {
runCatching {
sensors.gpsProviderFlow().collect { reading ->
val fix = reading.toLogGnss()
phoneGpsFix = fix
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE_GPS, fix))
}
}
delay(5_000L)
}
}
/** Accelerometer, gyroscope and gravity at 100 Hz, each sample with its own monotonic time. */
private suspend fun collectImu(sensors: SensorRepository, handler: Handler) = coroutineScope {
launch { sensors.accelerometerFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("accel")) } }
launch { sensors.gyroscopeFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gyro")) } }
// Only from the real TYPE_GRAVITY sensor: gravityFlow's accelerometer stand-in would only
// repeat the accel rows under another name.
if (sensors.hasSensor(Sensor.TYPE_GRAVITY)) {
launch { sensors.gravityFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gravity")) } }
}
}
/**
* The monotonic, wall and GNSS clocks read back to back once a second. Sensor samples and fixes
* carry monotonic time, messages and OBU fixes wall time, and the transmit path GNSS time; these
* rows convert between them, and show the phone clock's error and any step in it.
*/
private suspend fun collectClock() {
while (true) {
val elapsedNs = SystemClock.elapsedRealtimeNanos()
val wallMs = System.currentTimeMillis()
val gnssMs = try {
SystemClock.currentGnssTimeClock().millis()
} catch (e: DateTimeException) {
null
}
rows.trySend(LogClockSample(elapsedNs, wallMs, gnssMs))
delay(CLOCK_INTERVAL_MS)
}
}
// ── Rows ──────────────────────────────────────────────────────────────────
private fun enqueueRaw(
@@ -420,15 +320,6 @@ class V2xLogger @Inject constructor(
Decoded(summary = "intersections=" + s.intersections.joinToString(",") { it.key } +
" movements=" + s.intersections.sumOf { it.movements.size })
}
ItsMessageKind.MAPEM -> MapemUperCodec.decode(uper, tsMs, rssiDbm)?.let { m ->
val first = m.intersections.first()
Decoded(
lat = first.refLatitude, lon = first.refLongitude,
summary = "intersections=" + m.intersections.joinToString(",") {
"${it.key}@${it.revision}" + (it.name?.let { n -> " '$n'" } ?: "")
} + " lanes=" + m.intersections.sumOf { it.lanes.size },
)
}
else -> null
}
}.getOrNull() ?: Decoded()
@@ -442,23 +333,20 @@ class V2xLogger @Inject constructor(
var failure: String? = null
val messages = ArrayList<LogMessage>()
val gnss = ArrayList<LogGnssSample>()
val imu = ArrayList<LogImuSample>()
val clock = ArrayList<LogClockSample>()
var imuTotal = 0L
while (true) {
// Block for the first row of a batch, give more a moment to arrive, then take
// whatever is queued. No timeout around receive: a cancelled receive can lose the
// element it was handing over, which a logger must not do.
val first = rows.receiveCatching().getOrNull() ?: break
add(first, messages, gnss, imu, clock)
add(first, messages, gnss)
delay(FLUSH_INTERVAL_MS)
while (true) {
val next = rows.tryReceive().getOrNull() ?: break
add(next, messages, gnss, imu, clock)
add(next, messages, gnss)
}
try {
writer.writeBatch(messages, gnss, imu, clock)
writer.writeBatch(messages, gnss)
} catch (e: Exception) {
// Disk full or the file went away. Say so on screen rather than logging into a void.
Log.e(TAG, "write failed", e)
@@ -468,8 +356,7 @@ class V2xLogger @Inject constructor(
}
for (m in messages) counts.merge(m.kind, 1, Int::plus)
total += messages.size
imuTotal += imu.size
messages.clear(); gnss.clear(); imu.clear(); clock.clear()
messages.clear(); gnss.clear()
val now = System.currentTimeMillis()
_state.update {
@@ -477,26 +364,16 @@ class V2xLogger @Inject constructor(
counts = counts.toMap(), total = total, fileBytes = file.length(),
phoneFixAgeMs = phoneFix?.let { f -> now - f.fixMs },
obuFixAgeMs = obuFix?.let { f -> now - f.fixMs },
imuSamples = imuTotal,
phoneGpsFixAgeMs = phoneGpsFix?.let { f -> now - f.fixMs },
)
}
}
_state.update { it.copy(fileBytes = file.length(), error = failure ?: it.error, active = it.active && failure == null) }
}
private fun add(
row: Any,
messages: MutableList<LogMessage>,
gnss: MutableList<LogGnssSample>,
imu: MutableList<LogImuSample>,
clock: MutableList<LogClockSample>,
) {
private fun add(row: Any, messages: MutableList<LogMessage>, gnss: MutableList<LogGnssSample>) {
when (row) {
is LogMessage -> messages += row
is LogGnssSample -> gnss += row
is LogImuSample -> imu += row
is LogClockSample -> clock += row
}
}
@@ -514,54 +391,23 @@ class V2xLogger @Inject constructor(
latitude = latitude, longitude = longitude, altitudeM = altitude,
speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(),
accuracyM = accuracyM.toDouble(), fixMs = timestamp,
elapsedNs = elapsedRealtimeNanos,
speedAccuracyMps = speedAccuracyMps?.toDouble(),
bearingAccuracyDeg = bearingAccuracyDeg?.toDouble(),
provider = provider,
)
private fun ImuReading.toLogImu(sensor: String) =
LogImuSample(sensor, elapsedRealtimeNanos, timestamp, x, y, z)
/** `v2x_log_<start>_<hardware>.db`, with `_imu-<mount>` when it records sensor fusion data. */
private fun fileNameFor(startedMs: Long, hardware: ObuHardware, fusionMount: PhoneMount?): String {
private fun fileNameFor(startedMs: Long, hardware: ObuHardware): String {
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(startedMs))
val mode = if (hardware == ObuHardware.ESP32_C5) "esp32" else "citone"
val fusion = fusionMount?.let { "_imu-${it.id}" }.orEmpty()
return "v2x_log_${stamp}_$mode$fusion.db"
return "v2x_log_${stamp}_$mode.db"
}
private fun metaFor(
startedMs: Long,
hardware: ObuHardware,
mount: PhoneMount,
fusion: Boolean,
sensors: SensorRepository,
): Map<String, String> {
val meta = linkedMapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"phone_mount" to mount.id,
"fusion_logging" to fusion.toString(),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5. gnss.source: phone = " +
"fused location, phone_gps = raw GPS_PROVIDER, obu = the CiT One's obu_gnss. " +
"elapsed_ns is SystemClock.elapsedRealtimeNanos; the clock table converts it to wall " +
"and GNSS time. See docs/07-sensor-fusion-logging.md.",
)
if (fusion) {
meta["imu_period_us"] = IMU_PERIOD_US.toString()
sensors.describeSensor(Sensor.TYPE_ACCELEROMETER)?.let { meta["sensor_accel"] = it }
sensors.describeSensor(Sensor.TYPE_GYROSCOPE)?.let { meta["sensor_gyro"] = it }
meta["sensor_gravity"] = sensors.describeSensor(Sensor.TYPE_GRAVITY) ?: "none (not logged)"
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
meta["gnss_hardware"] = "${lm.gnssHardwareModelName ?: "?"} (year ${lm.gnssYearOfHardware})"
}
return meta
}
private fun metaFor(startedMs: Long, hardware: ObuHardware) = mapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5.",
)
}
@@ -6,7 +6,6 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
@@ -39,7 +38,6 @@ class ObuHardwarePreferences @Inject constructor(
// ESP32-C5 only.
val ESP32_TRANSPORT = stringPreferencesKey("esp32_transport")
val OUTGOING_MESSAGE = stringPreferencesKey("outgoing_message")
val ESP32_RX_PATH = stringPreferencesKey("esp32_rx_path")
val SIGN_OUTGOING = booleanPreferencesKey("sign_outgoing")
}
@@ -60,15 +58,6 @@ class ObuHardwarePreferences @Inject constructor(
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_TRANSPORT] = transport.id }
}
/** Where received ITS messages come from on the ESP32-C5 path: V2X_RX (default) or the RAW_FRAME debug capture. */
val esp32RxPathFlow: Flow<Esp32RxPath> = context.obuHardwareDataStore.data.map { prefs ->
Esp32RxPath.entries.firstOrNull { it.id == prefs[Keys.ESP32_RX_PATH] } ?: Esp32RxPath.V2X_RX
}
suspend fun setEsp32RxPath(path: Esp32RxPath) {
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_RX_PATH] = path.id }
}
/** What the ESP32-C5 path transmits while recording: CAM (default) or VAM. */
val outgoingMessageFlow: Flow<OutgoingMessage> = context.obuHardwareDataStore.data.map { prefs ->
OutgoingMessage.entries.firstOrNull { it.id == prefs[Keys.OUTGOING_MESSAGE] } ?: OutgoingMessage.CAM
@@ -45,7 +45,7 @@ private const val TAG = "BleLinkTransport"
/**
* BLE GATT central for the micrOBU's station link: the Android counterpart of the firmware's
* `obu-firmware/main/simple_ble.cpp` (from Niklas Dathe's microbu-esp32c5) and of their Python
* `obu-firmware/main/simple_ble.cpp` (from the colleague's microbu-esp32c5) and of their Python
* `microbu_link/ble_transport.py`, which this follows step for step.
*
* ## The GATT layout (what the firmware actually implements)
@@ -94,7 +94,6 @@ class BleLinkTransport @Inject constructor(
private const val SCAN_TIMEOUT_MS = 15_000L
/** Long enough for the user to find and type the passkey in the system dialog. */
private const val BOND_TIMEOUT_MS = 60_000L
private const val KEY_LAST_ADDRESS = "last_address"
private const val GATT_OP_TIMEOUT_MS = 5_000L
/** After a working link dropped: try again soon. */
private const val RECONNECT_DELAY_MS = 1_000L
@@ -115,20 +114,6 @@ class BleLinkTransport @Inject constructor(
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
private val prefs = context.getSharedPreferences("ble_link", Context.MODE_PRIVATE)
/** Failed connections since the last good one, with several bonded micrOBUs; picks which one is next. */
private var connectAttempt = 0
/**
* Of the bonded micrOBUs, the one to try now: the address that last reached CONNECTED first, then
* the others in turn after each failed connection. Null when none is bonded.
*/
private fun pickBonded(bonded: List<BluetoothDevice>): BluetoothDevice? {
if (bonded.isEmpty()) return null
val last = prefs.getString(KEY_LAST_ADDRESS, null)
val ordered = bonded.sortedBy { if (it.address == last) 0 else 1 }
return ordered[connectAttempt % ordered.size]
}
private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
@@ -238,10 +223,7 @@ class BleLinkTransport @Inject constructor(
_state.value = Esp32LinkState.DEVICE_ATTACHED
// A bonded micrOBU is reused without scanning: its address is stable (public address), and
// this is what makes a reconnect after a dropout fast.
// Android may hold several bonded micrOBUs (a replaced board stays bonded): the one that
// worked last goes first, and each failed connection moves on to the next.
val bonded = adapter.bondedDevices.filter { it.name?.startsWith(NAME_PREFIX) == true }
val device = pickBonded(bonded)
val device = adapter.bondedDevices.firstOrNull { it.name?.startsWith(NAME_PREFIX) == true }
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
deviceName = device.name
_detail.value = null
@@ -250,7 +232,6 @@ class BleLinkTransport @Inject constructor(
connected = CompletableDeferred()
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
if (bonded.size > 1) connectAttempt++
return fail("Could not connect to ${device.name}")
}
@@ -296,8 +277,6 @@ class BleLinkTransport @Inject constructor(
if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
}
_state.value = Esp32LinkState.CONNECTED
connectAttempt = 0
prefs.edit().putString(KEY_LAST_ADDRESS, device.address).apply()
Log.i(TAG, "BLE station link ready: ${device.name}")
// Wait until the link drops (callback completes `connected` anew with false).
val dropped = CompletableDeferred<Boolean>()
@@ -335,7 +314,7 @@ class BleLinkTransport @Inject constructor(
* does not finish within [BOND_TIMEOUT_MS].
*
* The probe is a read of the STATUS characteristic, which needs an encrypted and authenticated
* link, as Niklas Dathe's Python transport does. Android answers a read the link is not
* link, as the colleague's Python transport does. Android answers a read the link is not
* secure enough for by encrypting, or by pairing and showing the passkey dialog, and then
* retries the read itself. While it pairs, the card says which passkey to type.
*/
@@ -39,21 +39,6 @@ enum class Esp32LinkState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED,
/** Which physical link the phone uses to reach the ESP32-C5 (Settings). */
enum class Esp32Transport(val id: String) { USB("usb"), BLE("ble") }
/**
* Where the app takes received ITS messages from (Settings > Connection > ESP32-C5 > Receive path).
*
* - [V2X_RX]: the MicrOBU extension (opcode 0x90). The board unwraps every received frame itself and
* sends the finished ITS message, signed or not. Small, always on, the default.
* - [RAW_FRAME]: the station-link `RAW_FRAME` debug capture of docs/station-link.pdf (opcode 0x85,
* switched on with `RAW_CAPTURE`). The board sends the whole 802.11 frame, possibly fragmented, and
* the app unwraps it with [GnUnwrap]. Spec-defined and not limited to 494 octets, but best effort:
* copies can be dropped when the link is busy, and it costs more bandwidth, especially over BLE.
*
* Both reach the rest of the app as the same [SerialFrameType.V2X_RX] frames, so nothing above this
* class changes with the setting. The board keeps sending `V2X_RX` regardless; the app uses one path.
*/
enum class Esp32RxPath(val id: String) { V2X_RX("v2x_rx"), RAW_FRAME("raw_frame") }
/** What the phone transmits while a trip records (Settings). */
enum class OutgoingMessage(val id: String) { CAM("cam"), VAM("vam") }
@@ -110,9 +95,6 @@ class Esp32Link @Inject constructor(
companion object {
private const val TAG = "Esp32Link"
private const val REPLY_TIMEOUT_MS = 3_000L
private const val STATUS_POLL_MS = 1_000L
/** RAW_CAPTURE mode: on (bit 0) and broadcast frames only (bit 1): every ITS-G5 frame, no unicast noise. */
private const val RAW_CAPTURE_ON_BROADCAST = 0x03
/** Applying a bundle verifies the chain and rebuilds the stack on the C5: seconds, not ms. */
private const val PROVISION_TIMEOUT_MS = 15_000L
private const val SEGMENT_SIZE = 240
@@ -132,7 +114,7 @@ class Esp32Link @Inject constructor(
const val ITS_AID_VAM = 638L
/** CAM SSP version 1, no special-vehicle permissions: what the demo ticket grants for ITS-AID 36. */
val SSP_CAM = byteArrayOf(0x01, 0x00, 0x00)
/** VRU SSP as the demo ticket grants for ITS-AID 638 (same as Niklas Dathe's VBS). */
/** VRU SSP as the demo ticket grants for ITS-AID 638 (same as the colleague's VBS). */
val SSP_VAM = byteArrayOf(0x01)
}
@@ -141,17 +123,6 @@ class Esp32Link @Inject constructor(
val transport: StateFlow<Esp32Transport> =
prefs.esp32TransportFlow.stateIn(scope, SharingStarted.Eagerly, Esp32Transport.USB)
/** Which received-message path is in use. See [Esp32RxPath]. */
val rxPath: StateFlow<Esp32RxPath> =
prefs.esp32RxPathFlow.stateIn(scope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
/** Fragments of RAW_FRAME (and any other large indication) in flight; reset with every session. */
private val reassembly = LinkReassembly()
/** RAW_FRAME bodies seen, unwrapped to an ITS message, and not an ITS message (the usual case on air). */
@Volatile private var rawSeen = 0L
@Volatile private var rawForwarded = 0L
val state: StateFlow<Esp32LinkState> = combine(transport, usb.state, ble.state) { t, u, b ->
if (t == Esp32Transport.USB) u else b
}.stateIn(scope, SharingStarted.Eagerly, Esp32LinkState.DISCONNECTED)
@@ -199,7 +170,6 @@ class Esp32Link @Inject constructor(
@Volatile private var lastPotiFixMs: Long? = null
init {
scope.launch { pollStatus() }
scope.launch { usb.incomingFrames.collect { onUsbFrame(it) } }
scope.launch { ble.incoming.collect { onLinkMessage(it) } }
scope.launch { usb.linkStatus.collect { if (it != null) _linkStatus.value = it } }
@@ -213,15 +183,12 @@ class Esp32Link @Inject constructor(
_linkStatus.value = null
pending.values.forEach { it.cancel() }
pending.clear()
reassembly.reset()
} else if (transport.value == Esp32Transport.BLE) {
_protocol.value = Esp32Protocol.STATION_LINK // BLE exists only on the current firmware
scope.launch { ensureConfigured(null) }
}
}
}
// A change of receive path in Settings takes effect at once on a configured station.
scope.launch { rxPath.collect { scope.launch { applyRxPath() } } }
scope.launch { ble.detail.collect { if (transport.value == Esp32Transport.BLE) _detail.value = it } }
// Switching transport in Settings closes the other one; connecting stays a user action.
scope.launch {
@@ -304,7 +271,7 @@ class Esp32Link @Inject constructor(
private suspend fun ensureConfigured(wanted: StationConfigure?): Boolean = sessionMutex.withLock {
val current = configured
if (current != null && (wanted == null || current == wanted)) return@withLock true
val config = wanted ?: StationConfigure(stationType = StationType.CYCLIST)
val config = wanted ?: StationConfigure(stationType = StationType.CYCLIST, mid = pseudonymManager.current().mac)
_detail.value = "Configuring the micrOBU"
val result = request(LinkOpcode.STATION_CONFIGURE, config.encode(), REPLY_TIMEOUT_MS)
if (result == null || !result.accepted) {
@@ -318,36 +285,9 @@ class Esp32Link @Inject constructor(
}
configured = config
_detail.value = null
scope.launch { applyRxPath() } // a (re)configured station starts with raw capture off
true
}
/**
* Switches the station's raw capture to match [rxPath]: on (receive only, broadcast frames) for
* [Esp32RxPath.RAW_FRAME], off for [Esp32RxPath.V2X_RX]. RAW_CAPTURE needs a started radio, so it
* is sent only once the station is configured; a station that restarted forgets it and is
* configured again, which sends it again.
*/
private suspend fun applyRxPath() {
if (_protocol.value != Esp32Protocol.STATION_LINK || state.value != Esp32LinkState.CONNECTED) return
if (configured == null) return
val mode = if (rxPath.value == Esp32RxPath.RAW_FRAME) RAW_CAPTURE_ON_BROADCAST else 0
val result = request(LinkOpcode.RAW_CAPTURE, byteArrayOf(mode.toByte()), REPLY_TIMEOUT_MS)
Log.i(TAG, "receive path ${rxPath.value}: RAW_CAPTURE mode $mode -> ${result?.let { LinkResultCode.name(it.code) } ?: "no reply"}")
if (result != null && !result.accepted && mode != 0) _detail.value = "Raw capture refused: ${LinkResultCode.name(result.code)}"
}
/** One RAW_FRAME: unwrap it to the ITS message inside and hand it on like a V2X_RX message. */
private fun onRawFrame(body: ByteArray) {
val raw = RawFrame.parse(body) ?: return
if (raw.ownTransmission) return
rawSeen++
val unwrapped = GnUnwrap.unwrap(raw.frame) ?: return
val v2xRx = GnUnwrap.toV2xRxBody(unwrapped, raw.rssiDbm) ?: return
rawForwarded++
_incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, v2xRx))
}
private suspend fun provisionDemoCredentials(): Boolean {
_detail.value = "Provisioning the demo credentials"
val bundle = runCatching { context.assets.open(DEMO_BUNDLE_ASSET).use { it.readBytes() } }.getOrElse {
@@ -428,14 +368,10 @@ class Esp32Link @Inject constructor(
}
private fun onLinkMessage(octets: ByteArray) {
// Fragments are put back together first (flags 1-3 of docs/station-link.pdf); a complete
// message, the usual case, passes straight through.
val message = reassembly.feed(LinkMessage.decode(octets) ?: return) ?: return
val message = LinkMessage.decode(octets) ?: return
when (message.opcode) {
LinkOpcode.V2X_RX ->
if (rxPath.value == Esp32RxPath.V2X_RX) _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
LinkOpcode.RAW_FRAME -> if (rxPath.value == Esp32RxPath.RAW_FRAME) onRawFrame(message.body)
LinkOpcode.CONFIRM -> {
LinkOpcode.V2X_RX -> _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
LinkOpcode.RESULT -> {
val result = LinkResult.decode(message.body) ?: return
val waiting = pending.remove(message.sequence)
if (waiting != null) {
@@ -451,37 +387,26 @@ class Esp32Link @Inject constructor(
noteRefusal("micrOBU refused a request: ${LinkResultCode.name(result.code)}")
}
}
LinkOpcode.STATUS -> {
val status = StationStatus.decode(message.body) ?: return
val first = _protocol.value != Esp32Protocol.STATION_LINK
_protocol.value = Esp32Protocol.STATION_LINK
_stationStatus.value = status
_linkStatus.value = EspLinkStatus(
status = 0,
oversizeDrops = 0,
txFailures = status.radioFailed.coerceAtMost(0xFFFF).toInt(),
rxCrcErrors = status.linkCrcErrors.coerceAtMost(0xFFFF).toInt(),
rxQueueDrops = status.radioDropped.coerceAtMost(0xFFFF).toInt(),
)
// Board reset (or first contact): configure now, so its receiver runs even before
// the first message is sent.
if (!status.configured) { configured = null; lastPotiMs = null; lastPotiFixMs = null }
if (first || !status.configured) scope.launch { ensureConfigured(null) }
}
}
}
/** Asks for the status snapshot once a second while connected (the board does not push it). */
private suspend fun pollStatus() {
while (true) {
delay(STATUS_POLL_MS)
if (state.value != Esp32LinkState.CONNECTED || _protocol.value == Esp32Protocol.LEGACY_SERIAL) continue
val result = request(LinkOpcode.STATUS_REQUEST, ByteArray(0), REPLY_TIMEOUT_MS) ?: continue
if (!result.accepted) continue
handleStatus(StationStatus.decode(result.detail) ?: continue)
}
}
private fun handleStatus(status: StationStatus) {
val first = _protocol.value != Esp32Protocol.STATION_LINK
_protocol.value = Esp32Protocol.STATION_LINK
_stationStatus.value = status
_linkStatus.value = EspLinkStatus(
status = 0,
oversizeDrops = 0,
txFailures = status.radioFailed.coerceAtMost(0xFFFF).toInt(),
rxCrcErrors = status.linkCrcErrors.coerceAtMost(0xFFFF).toInt(),
rxQueueDrops = status.radioDropped.coerceAtMost(0xFFFF).toInt(),
)
// Board reset (or first contact): configure now, so its receiver runs even before the first
// message is sent.
if (!status.configured) { configured = null; lastPotiMs = null; lastPotiFixMs = null }
if (first || !status.configured) scope.launch { ensureConfigured(null) }
}
private fun noteRefusal(line: String) {
val now = System.currentTimeMillis()
if (now - lastRefusalLogMs < 5_000) return
@@ -1,220 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Kotlin counterpart of obu-firmware's `gn_unwrap.c`: takes one received 802.11 data frame down
* through LLC/SNAP, GeoNetworking and BTP-B to the ITS message inside, signed or not.
*
* It exists so the app can consume the station's `RAW_FRAME` debug capture the way it consumes
* `V2X_RX` (which the board builds with the C version). The two are tested against each other on the
* same frames (`GnUnwrapTest`, corpus from the C code), so they accept and reject the same frames and
* return the same fields.
*
* What it does and does not do, as in the C version:
* - Plain Data frames only, QoS or not, no WDS; LLC/SNAP with the GeoNetworking ethertype 0x8947.
* - Single-hop broadcast (TSB subtype 0) and GeoBroadcast; BTP-B on ports 2001-2004 and 2018.
* - A secured packet (TS 103 097 / IEEE 1609.2 `signedData` or `unsecuredData`, protocolVersion 3) is
* unwrapped WITHOUT verifying the signature or certificate; the result says it was signed.
* Encrypted and legacy v1.2.1 envelopes are rejected.
* - The payload is exactly as long as the Common Header declares, not what is left of the frame.
*/
object GnUnwrap {
/** An unwrapped ITS message. [payload] is its UPER encoding. */
class Result(
val btpPort: Int,
val payload: ByteArray,
val hasGeoArea: Boolean,
val areaLatTenMicroDeg: Int,
val areaLonTenMicroDeg: Int,
val areaDistanceAMeters: Int,
/** The packet carried a signature envelope; it was not checked. */
val signedUnverified: Boolean,
/** The frame ended before the payload its headers declare; [payload] is only what arrived. */
val truncated: Boolean,
)
private const val GN_ETHERTYPE = 0x8947
private const val LLC_SNAP_HEADER_LEN = 8
private const val IEEE80211_HEADER_LEN = 24
private const val IEEE80211_QOS_CTRL_LEN = 2
private const val FC_TYPE_DATA = 2
private const val FC_QOS_SUBTYPE_BIT = 0x08
private const val GN_BASIC_HEADER_LEN = 4
private const val GN_COMMON_HEADER_LEN = 8
private const val BTP_B_HEADER_LEN = 4
private const val GN_SHB_EXT_HEADER_LEN = 28
private const val GN_GBC_EXT_HEADER_LEN = 44
private const val GBC_AREA_LAT_OFFSET = 28
private const val GBC_AREA_LON_OFFSET = 32
private const val GBC_AREA_DIST_A_OFFSET = 36
private const val GN_HEADER_TYPE_GBC = 4
private const val GN_HEADER_TYPE_TSB = 5
private const val GN_HEADER_SUBTYPE_SINGLE_HOP = 0
private const val GN_NEXT_HEADER_COMMON = 1
private const val GN_NEXT_HEADER_SECURED = 2
private const val GN_COMMON_NEXT_HEADER_BTP_B = 2
private const val GN_COMMON_PAYLOAD_LEN_OFFSET = 4
private const val IEEE1609DOT2_VERSION = 3
private const val CONTENT_TAG_UNSECURED_DATA = 0x80
private const val CONTENT_TAG_SIGNED_DATA = 0x81
private const val SIGNED_PAYLOAD_HAS_DATA = 0x40
private val BTP_PORTS = setOf(2001, 2002, 2003, 2004, 2018)
private val LLC_SNAP_PREFIX = intArrayOf(0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00)
private fun ByteArray.u8(i: Int) = this[i].toInt() and 0xFF
private fun ByteArray.be16(i: Int) = (u8(i) shl 8) or u8(i + 1)
private fun ByteArray.be32(i: Int) = (u8(i) shl 24) or (u8(i + 1) shl 16) or (u8(i + 2) shl 8) or u8(i + 3)
/** COER length determinant: returns (octets used, length), or null when it does not fit. */
private fun coerLength(f: ByteArray, at: Int, avail: Int): Pair<Int, Int>? {
if (avail < 1) return null
val first = f.u8(at)
if (first < 0x80) return 1 to first
val n = first and 0x7F
if (n < 1 || n > 2 || avail < 1 + n) return null
var v = 0
for (i in 1..n) v = (v shl 8) or f.u8(at + i)
return (1 + n) to v
}
/**
* Returns the Common Header offset inside the envelope, the end of the envelope's inner packet
* and whether it was signed; null for anything this does not handle.
*/
private fun unwrapSecured(f: ByteArray, offset: Int, frameLen: Int): Triple<Int, Int, Boolean>? {
val avail = frameLen - offset
if (avail < 2 || f.u8(offset) != IEEE1609DOT2_VERSION) return null
val i: Int
val signed: Boolean
if (f.u8(offset + 1) == CONTENT_TAG_SIGNED_DATA) {
if (avail < 6 ||
f.u8(offset + 2) >= 0x80 ||
(f.u8(offset + 3) and SIGNED_PAYLOAD_HAS_DATA) == 0 ||
f.u8(offset + 4) != IEEE1609DOT2_VERSION ||
f.u8(offset + 5) != CONTENT_TAG_UNSECURED_DATA
) return null
i = 6
signed = true
} else if (f.u8(offset + 1) == CONTENT_TAG_UNSECURED_DATA) {
i = 2
signed = false
} else {
return null
}
val (used, len) = coerLength(f, offset + i, avail - i) ?: return null
val innerStart = offset + i + used
return Triple(innerStart, offset + i + used + len, signed)
}
/** Unwraps one 802.11 frame; null when it is not an ITS message this handles (the common case on air). */
fun unwrap(frame: ByteArray): Result? {
val frameLen = frame.size
if (frameLen < IEEE80211_HEADER_LEN) return null
val fc0 = frame.u8(0)
val fc1 = frame.u8(1)
val type = (fc0 shr 2) and 0x03
val subtype = (fc0 shr 4) and 0x0F
val toDs = (fc1 and 0x01) != 0
val fromDs = (fc1 and 0x02) != 0
if (type != FC_TYPE_DATA || (toDs && fromDs)) return null
var offset = IEEE80211_HEADER_LEN
if ((subtype and FC_QOS_SUBTYPE_BIT) != 0) offset += IEEE80211_QOS_CTRL_LEN
if (frameLen < offset + LLC_SNAP_HEADER_LEN) return null
for (k in LLC_SNAP_PREFIX.indices) if (frame.u8(offset + k) != LLC_SNAP_PREFIX[k]) return null
if (frame.be16(offset + 6) != GN_ETHERTYPE) return null
offset += LLC_SNAP_HEADER_LEN
if (frameLen < offset + GN_BASIC_HEADER_LEN) return null
val basicNextHeader = frame.u8(offset) and 0x0F
offset += GN_BASIC_HEADER_LEN
var limit = frameLen
var envelopeEnd = -1
var signed = false
if (basicNextHeader == GN_NEXT_HEADER_SECURED) {
val (inner, end, isSigned) = unwrapSecured(frame, offset, frameLen) ?: return null
offset = inner
envelopeEnd = end
signed = isSigned
if (envelopeEnd < limit) limit = envelopeEnd
} else if (basicNextHeader != GN_NEXT_HEADER_COMMON) {
return null
}
if (limit < offset + GN_COMMON_HEADER_LEN) return null
val nextHeader = (frame.u8(offset) shr 4) and 0x0F
val headerType = (frame.u8(offset + 1) shr 4) and 0x0F
val headerSubtype = frame.u8(offset + 1) and 0x0F
val gnPayloadLen = frame.be16(offset + GN_COMMON_PAYLOAD_LEN_OFFSET)
if (nextHeader != GN_COMMON_NEXT_HEADER_BTP_B) return null
offset += GN_COMMON_HEADER_LEN
val extLen: Int
var isGbc = false
if (headerType == GN_HEADER_TYPE_TSB && headerSubtype == GN_HEADER_SUBTYPE_SINGLE_HOP) {
extLen = GN_SHB_EXT_HEADER_LEN
} else if (headerType == GN_HEADER_TYPE_GBC) {
extLen = GN_GBC_EXT_HEADER_LEN
isGbc = true
} else {
return null
}
if (limit < offset + extLen) return null
var areaLat = 0
var areaLon = 0
var areaDist = 0
if (isGbc) {
areaLat = frame.be32(offset + GBC_AREA_LAT_OFFSET)
areaLon = frame.be32(offset + GBC_AREA_LON_OFFSET)
areaDist = frame.be16(offset + GBC_AREA_DIST_A_OFFSET)
}
offset += extLen
if (limit < offset + BTP_B_HEADER_LEN) return null
val destPort = frame.be16(offset)
if (destPort !in BTP_PORTS) return null
if (gnPayloadLen <= BTP_B_HEADER_LEN) return null
val payloadStart = offset + BTP_B_HEADER_LEN
val payloadEnd = offset + gnPayloadLen
if (envelopeEnd >= 0 && payloadEnd > envelopeEnd) return null
val truncated = payloadEnd > frameLen
val payloadLen = (if (truncated) frameLen else payloadEnd) - payloadStart
if (payloadLen <= 0) return null
return Result(
btpPort = destPort,
payload = frame.copyOfRange(payloadStart, payloadStart + payloadLen),
hasGeoArea = isGbc,
areaLatTenMicroDeg = areaLat,
areaLonTenMicroDeg = areaLon,
areaDistanceAMeters = areaDist,
signedUnverified = signed,
truncated = truncated,
)
}
/**
* The `V2X_RX` body for [result] (the layout [V2xRxFrame.parse] reads and the firmware's
* `encode_v2x_rx` writes): `u16 port, i8 rssi, u8 flags (bit 0 GBC area, bit 1 signed), i32 lat,
* i32 lon, u16 distance_a, payload`. Null for a truncated message, which must not be forwarded.
*/
fun toV2xRxBody(result: Result, rssiDbm: Int): ByteArray? {
if (result.truncated || result.payload.isEmpty()) return null
val out = java.io.ByteArrayOutputStream(V2xRxFrame.PREFIX_SIZE + result.payload.size)
fun u8(v: Int) = out.write(v and 0xFF)
fun u16(v: Int) { u8(v); u8(v shr 8) }
fun i32(v: Int) { u16(v); u16(v shr 16) }
u16(result.btpPort)
u8(rssiDbm.coerceIn(-128, 127))
u8((if (result.hasGeoArea) 0x01 else 0) or (if (result.signedUnverified) 0x02 else 0))
i32(result.areaLatTenMicroDeg)
i32(result.areaLonTenMicroDeg)
u16(result.areaDistanceAMeters)
out.write(result.payload)
return out.toByteArray()
}
}
@@ -1,92 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Reassembles fragmented station-link messages (docs/station-link.pdf, "Fragmented messages").
*
* A body too large for one transport message is split in order, every fragment carrying the same
* opcode and sequence and `flags` 1 (first), 2 (middle) or 3 (last). Each fragment's body starts with
* `total_length u16` and `body_offset u16`, then the data. The complete body is handed on once the
* last fragment brings it to exactly `total_length`.
*
* Validation follows the spec: gaps, duplicates, wrong order and a changed total drop the stream;
* an unfinished stream is discarded after [IDLE_TIMEOUT_MS] of silence; at most [MAX_PENDING] streams
* are held; a complete body is at most [MAX_BODY] octets (the largest station-to-host indication).
*
* One instance per link session (USB and BLE keep separate streams in the spec; the app uses one
* transport at a time and starts a new instance when the session restarts).
*/
class LinkReassembly(private val nowMs: () -> Long = { System.currentTimeMillis() }) {
private class Stream(val opcode: Int, val sequence: Int, val total: Int, var lastMs: Long) {
val bytes = java.io.ByteArrayOutputStream()
}
private val streams = ArrayList<Stream>()
/** Fragments dropped for any validation reason since this instance was created. */
var dropped: Int = 0
private set
/**
* Feeds one received message. Returns it unchanged when it is complete (`flags` 0), the
* reassembled message (`flags` 0) when [message] was the last fragment, and null otherwise.
*/
fun feed(message: LinkMessage): LinkMessage? {
val now = nowMs()
streams.removeAll { now - it.lastMs > IDLE_TIMEOUT_MS }
if (message.flags == 0) {
// A complete message supersedes any unfinished stream with the same key.
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
return message
}
val flags = message.flags
val body = message.body
if (flags > FLAG_LAST || body.size <= FRAGMENT_HEADER) return drop(message)
fun u16(i: Int) = (body[i].toInt() and 0xFF) or ((body[i + 1].toInt() and 0xFF) shl 8)
val total = u16(0)
val offset = u16(2)
val length = body.size - FRAGMENT_HEADER
if (total == 0 || total > MAX_BODY || offset + length > total) return drop(message)
// the last fragment ends exactly at the declared total, and only the last one does
if ((flags == FLAG_LAST) != (offset + length == total)) return drop(message)
var stream = streams.firstOrNull { it.opcode == message.opcode && it.sequence == message.sequence }
if (flags == FLAG_FIRST) {
if (offset != 0) return drop(message)
stream?.let { streams.remove(it) } // a restarted stream replaces the old one
if (streams.size >= MAX_PENDING) return drop(message)
stream = Stream(message.opcode, message.sequence, total, now)
streams.add(stream)
} else if (stream == null) {
return drop(message) // a middle or last fragment without a first
}
if (stream.total != total || stream.bytes.size() != offset) {
streams.remove(stream) // changed total, a gap or a duplicate
return drop(message)
}
stream.bytes.write(body, FRAGMENT_HEADER, length)
stream.lastMs = now
if (flags != FLAG_LAST) return null
streams.remove(stream)
return LinkMessage(message.opcode, message.sequence, stream.bytes.toByteArray(), 0)
}
/** Forgets every unfinished stream (a new session, a reconnect). */
fun reset() = streams.clear()
private fun drop(message: LinkMessage): LinkMessage? {
dropped++
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
return null
}
companion object {
const val FLAG_FIRST = 1
const val FLAG_MIDDLE = 2
const val FLAG_LAST = 3
const val FRAGMENT_HEADER = 4
const val IDLE_TIMEOUT_MS = 2_000L
const val MAX_PENDING = 8
const val MAX_BODY = 65_535
}
}
@@ -1,55 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Body of the station-link `RAW_FRAME` (0x85, docs/station-link.pdf, "Raw capture"): a debug copy of
* a radio frame the station received (or, with the own-transmission option, sent).
*
* u32 counter, u8 flags (bit 0 own transmission, bit 1 UTC time stamp), i8 rssi,
* ITS5 record: "ITS5", u32 seconds, u32 microseconds, u16 frame_length, frame[frame_length]
*
* The frame is the 802.11 MPDU without its FCS. [GnUnwrap] turns it into the ITS message.
*/
data class RawFrame(
val counter: Long,
val ownTransmission: Boolean,
/** The record time is UTC (the station's clock was synchronised) rather than time since boot. */
val utcTime: Boolean,
val rssiDbm: Int,
val seconds: Long,
val microseconds: Long,
val frame: ByteArray,
) {
override fun equals(other: Any?): Boolean = other is RawFrame && counter == other.counter &&
ownTransmission == other.ownTransmission && utcTime == other.utcTime && rssiDbm == other.rssiDbm &&
seconds == other.seconds && microseconds == other.microseconds && frame.contentEquals(other.frame)
override fun hashCode(): Int = 31 * counter.hashCode() + frame.contentHashCode()
companion object {
/** `[counter 4][flags 1][rssi 1]` before the record, `["ITS5" 4][sec 4][usec 4][len 2]` in it. */
const val HEADER_SIZE = 6 + 14
private val MAGIC = byteArrayOf('I'.code.toByte(), 'T'.code.toByte(), 'S'.code.toByte(), '5'.code.toByte())
/** Returns null for a body that is not a well-formed RAW_FRAME (short, wrong magic, bad length). */
fun parse(body: ByteArray): RawFrame? {
if (body.size < HEADER_SIZE) return null
for (i in 0 until 4) if (body[6 + i] != MAGIC[i]) return null
fun u8(i: Int) = body[i].toInt() and 0xFF
fun u16(i: Int) = u8(i) or (u8(i + 1) shl 8)
fun u32(i: Int) = (u16(i).toLong()) or (u16(i + 2).toLong() shl 16)
val length = u16(18)
if (body.size != HEADER_SIZE + length) return null
val flags = u8(4)
return RawFrame(
counter = u32(0),
ownTransmission = (flags and 0x01) != 0,
utcTime = (flags and 0x02) != 0,
rssiDbm = body[5].toInt(),
seconds = u32(10),
microseconds = u32(14),
frame = body.copyOfRange(HEADER_SIZE, body.size),
)
}
}
}
@@ -137,7 +137,6 @@ object Crc16CcittFalse {
object BtpPort {
const val CAM = 2001
const val DENM = 2002
const val MAPEM = 2003
/**
* Watch the crossover: SPATEM is BTP port **2004** but ItsPduHeader messageID **4**, while
@@ -1,10 +1,10 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Phone side of the station-link message layer, version 1: the protocol of Niklas Dathe's
* Phone side of the station-link message layer, version 1: the protocol of the colleague's
* vanetza-idf ESP32-C5 firmware (microbu-esp32c5/station-link/README.md), which obu-firmware runs
* since 2026-09-23. Kotlin counterpart of `obu-firmware/main/link_protocol.hpp` and of the
* Niklas Dathe's Python `microbu_link/messages.py`; the unit test pins these encoders to bytes that
* colleague's Python `microbu_link/messages.py`; the unit test pins these encoders to bytes that
* Python module produced.
*
* Transport independent: over USB each message is the payload of one serial frame of type
@@ -12,12 +12,11 @@ package com.hawhamburg.micr0bu.data.transport
* message is one GATT value (see [BleLinkTransport]).
*
* Message: `[opcode:1][flags:1][sequence:2 LE][body]`, at most [LINK_MAX_MESSAGE] octets, all
* integers little-endian. The phone numbers its requests; the firmware answers with a CONFIRM
* carrying the same sequence (docs/station-link.pdf, obu-firmware/docs). The status snapshot is not
* pushed: the phone asks for it with STATUS_REQUEST once a second and finds it in CONFIRM.detail.
* integers little-endian. The phone numbers its requests; the firmware answers with a RESULT
* carrying the same sequence.
*
* Only what this app uses is implemented: configure, PoTi, BTP-DATA.request, credential
* provisioning, STATUS_REQUEST, CONFIRM, and the MicrOBU extension [LinkOpcode.V2X_RX]. The SF-SAP
* provisioning, RESULT, STATUS, and the MicrOBU extension [LinkOpcode.V2X_RX]. The SF-SAP
* identifier-change primitives are not used: the app owns its pseudonym (see
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager]) and reconfigures the station on a change.
*/
@@ -32,17 +31,14 @@ object LinkOpcode {
const val CREDENTIALS_PROVISION = 0x04
const val CREDENTIALS_ERASE = 0x05
const val STATUS_REQUEST = 0x0C
/** Debug path: body is one mode octet (bit 0 on, bit 1 broadcast only, bit 2 own transmissions); 0 switches it off. */
const val RAW_CAPTURE = 0x0D
const val CONFIRM = 0x80
const val RESULT = 0x80
const val BTP_DATA_INDICATION = 0x81
/** Raw 802.11 frame copy of the RAW_CAPTURE debug path, fragmented when large: see [RawFrame]. */
const val RAW_FRAME = 0x85
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
const val V2X_RX = 0x90
const val STATUS = 0x84
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). */
const val V2X_RX = 0x85
}
/** CONFIRM result codes: the stack's own first, then the link's. */
/** RESULT codes: vanetza_idf::Result first, then the link's own. */
object LinkResultCode {
const val ACCEPTED = 0
const val TIME_REGRESSION = 7
@@ -95,40 +91,36 @@ internal class LinkWriter {
/**
* STATION_CONFIGURE body. (Re)creates the GeoNetworking stack and security entity on the micrOBU.
*
* Without [mid] it is the 6-octet form of docs/station-link.pdf: the GN address derives from the
* authorization ticket (signed) or is drawn at random per configuration (unsigned). With [mid], the
* pseudonym MAC, it is the 16-octet form (address_configuration 0, AUTO), which the station still
* accepts: [mid] becomes both the GN_ADDR MID and the 802.11 source address, signed or not. A ride
* sends the rotating pseudonym's MAC, so the link-layer address rotates with the station ID; the bench
* CAM pinger sends its fixed MAC. A different [mid] is a different configuration, so the next message
* reconfigures the station. Radio mode, traffic class and lifetime are the station's (transmit and
* receive, DP2, 1 s).
* [mid] is the pseudonym MAC: with [addressConfiguration] 0 (AUTO) it becomes both the GN_ADDR MID
* and the 802.11 source address, as with the old CAM_TX_PV prefix.
*/
data class StationConfigure(
val stationType: Int,
val mid: ByteArray,
val security: Int = 1,
val addressConfiguration: Int = 0,
val beaconing: Int = 0,
val channelNumber: Int = 180,
val transmitPowerDbm: Int = 20,
val mid: ByteArray? = null,
/** 0 off, 1 receive only, 2 transmit and receive. */
val radio: Int = 2,
/** Raw GN traffic class octet: TC-ID 2, as the previous firmware's geonet.c. */
val defaultTrafficClass: Int = 2,
/** Raw GN lifetime octet: 1 s. */
val defaultLifetime: Int = 0x05,
) {
init { require(mid == null || mid.size == 6) }
init { require(mid.size == 6) }
fun encode(): ByteArray = if (mid == null) {
LinkWriter().u8(stationType).u16(channelNumber).u8(transmitPowerDbm).u8(security).u8(beaconing)
.toByteArray()
} else {
LinkWriter().u8(stationType).u8(security).u8(0).bytes(mid).u8(beaconing)
.u16(channelNumber).u8(transmitPowerDbm).u8(2).u8(2).u8(0x05)
.toByteArray()
}
fun encode(): ByteArray = LinkWriter()
.u8(stationType).u8(security).u8(addressConfiguration).bytes(mid).u8(beaconing)
.u16(channelNumber).u8(transmitPowerDbm).u8(radio).u8(defaultTrafficClass).u8(defaultLifetime)
.toByteArray()
override fun equals(other: Any?): Boolean = other is StationConfigure && encode().contentEquals(other.encode())
override fun hashCode(): Int = encode().contentHashCode()
}
/** CONFIRM detail of STATION_CONFIGURE. */
/** RESULT detail of STATION_CONFIGURE. */
data class StationInfo(val credentialsLoaded: Boolean, val tickets: Int) {
companion object {
fun decode(detail: ByteArray): StationInfo? =
@@ -220,11 +212,7 @@ data class LinkResult(val code: Int, val detail: ByteArray) {
}
}
/**
* Status snapshot, the CONFIRM.detail of STATUS_REQUEST (131 octets, docs/station-link.pdf). Counters
* are since the last configure. The board reports only the cell voltage ([batteryMv]); the warning
* and shutdown thresholds below mirror obu-firmware's Kconfig defaults (3.50 V and 3.30 V).
*/
/** STATUS body (103 octets), sent by the micrOBU every second. Counters are since the last configure. */
data class StationStatus(
val uptimeMs: Long,
val configured: Boolean,
@@ -247,16 +235,7 @@ data class StationStatus(
val linkMalformed: Long,
val potiUpdates: Long,
val itsTimeMs: Long,
/** Cell voltage in millivolts; 0 when the board does not report one (older firmware, no cell, no sensor). */
val batteryMv: Int = 0,
) {
/** The cell is below the warning threshold. */
val batteryLow: Boolean get() = batteryMv > 0 && batteryMv < BATTERY_WARN_MV
/** The cell is below the shutdown threshold: the board powers down unless this phone keeps it on USB. */
val batteryCritical: Boolean get() = batteryMv > 0 && batteryMv < BATTERY_SHUTDOWN_MV
/** Rough charge of a LiPo cell from its voltage, or null when not measured. An indicator, not a fuel gauge. */
val batteryPercent: Int? get() = if (batteryMv > 0) lipoPercent(batteryMv) else null
/** Signing refusals of every kind: no usable ticket, a pending id change, or a missing permission. */
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
@@ -265,33 +244,10 @@ data class StationStatus(
override fun hashCode(): Int = toString().hashCode()
companion object {
/** Octets of the status snapshot. */
const val SIZE = 131
const val BATTERY_WARN_MV = 3500
const val BATTERY_SHUTDOWN_MV = 3300
const val SIZE = 103
/** Open-circuit voltage (mV) to charge (%) of a single LiPo cell, interpolated linearly. */
private val LIPO_CURVE = arrayOf(
3300 to 0, 3500 to 5, 3690 to 10, 3730 to 20, 3770 to 30, 3800 to 40,
3840 to 50, 3870 to 60, 3950 to 70, 4020 to 80, 4110 to 90, 4200 to 100,
)
fun lipoPercent(millivolts: Int): Int {
if (millivolts <= LIPO_CURVE.first().first) return 0
if (millivolts >= LIPO_CURVE.last().first) return 100
for (i in 1 until LIPO_CURVE.size) {
val (v1, p1) = LIPO_CURVE[i]
if (millivolts <= v1) {
val (v0, p0) = LIPO_CURVE[i - 1]
return p0 + (p1 - p0) * (millivolts - v0) / (v1 - v0)
}
}
return 100
}
/** Accepts the 131-octet snapshot and any longer one (later fields are appended); shorter is malformed. */
fun decode(body: ByteArray): StationStatus? {
if (body.size < SIZE) return null
if (body.size != SIZE) return null
fun u8(i: Int) = body[i].toInt() and 0xFF
fun u32(i: Int) = (0 until 4).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
fun u64(i: Int) = (0 until 8).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
@@ -312,8 +268,6 @@ data class StationStatus(
// c + 56: link_rx_frames
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
itsTimeMs = u64(95),
// [103] cbr, dcc, heap and temperature fields the app does not use; [129] battery_mv u16
batteryMv = u8(129) or (u8(130) shl 8),
)
}
}
@@ -144,11 +144,8 @@ object CamUperCodec {
bw.putBits(0, 1) // extension bit: value is in the root list
bw.putBits(2, 2) // curvatureCalculationMode: unavailable(2)
// YawRateValue is positive to the LEFT (degSec-000-01ToLeft(1), TS 102 894-2), the opposite
// of Cam.yawRateDps (positive clockwise, i.e. to the right). Until 2026-11-18 neither side
// negated, so every CAM this phone sent turned the wrong way for a standard receiver.
val yawRateCentiDegS = cam.yawRateDps
?.let { (-it * 100.0).roundToInt().coerceIn(-32766, 32766) }
?.let { (it * 100.0).roundToInt().coerceIn(-32766, 32766) }
?: YAW_RATE_UNAVAILABLE
bw.putBits(yawRateCentiDegS - (-32766), 16)
// YawRateConfidence has NINE enumerands (degSec-000-01(0) .. unavailable(8), see
@@ -309,8 +306,7 @@ object CamUperCodec {
val yawRateRaw = br.getBitsInt(16) + (-32766)
br.getBits(4) // yawRateConfidence: 9 enumerands -> 4 bits, see the note in encode()
// Left-positive on air, clockwise-positive in Cam: negate, as encode() does.
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else -yawRateRaw / 100.0
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else yawRateRaw / 100.0
// Everything after yawRate is deliberately left unread: the 7 optional high-frequency
// fields, then lowFrequencyContainer (vehicleRole / exteriorLights / pathHistory), then
@@ -42,6 +42,9 @@ object DenmUperCodec {
private const val MESSAGE_ID_DENM = 1
private const val PROTOCOL_VERSION = 2
/** TimestampIts epoch: 2004-01-01T00:00:00Z in Unix epoch milliseconds. */
private const val TS_ITS_EPOCH_MS = 1_072_915_200_000L
/**
* Decodes a UPER DENM into a [DenmEvent].
*
@@ -144,8 +147,7 @@ object DenmUperCodec {
// on it; if any of it is ever needed, the unparsed optionals must be consumed in order
// first or every later read lands at the wrong bit offset.
// TimestampIts is TAI-based: back to UTC through the one conversion the transmit side uses.
val detectionTimeMs = ItsTime.epochMs(detectionTimeIts)
val detectionTimeMs = detectionTimeIts + TS_ITS_EPOCH_MS
return DenmEvent(
stationId = originatingStationId,
@@ -1,65 +1,30 @@
package com.hawhamburg.micr0bu.domain.asn1
/**
* ITS time, as used by every timestamp this app puts on the air or reads from it.
* ITS time, as used by every timestamp this app puts on the air.
*
* TimestampIts (ETSI TS 102 894-2 V2.5.1) is "the number of elapsed (TAI) milliseconds since the ITS
* Epoch", 2004-01-01T00:00:00.000 UTC, counted without interruption, so it is not altered by the leap
* seconds UTC inserts. It therefore runs ahead of UTC by the leap seconds inserted since 2004: 5 s since
* 2017-01-01 (the standard's own example: 2007-01-01T00:00:00.000 UTC is 94 694 401 000 ms, one leap
* second included). Three fields in a single transmitted frame come from it: the CAM's and VAM's
* generationDeltaTime (modulo 65536), the GeoNetworking Source Position Vector's TST (modulo 2^32) and,
* on the station-link path, the PoTi timestamp that sets the micrOBU's ITS clock, which the security
* entity stamps into every signature's generationTime and checks received messages against. A receiver
* compares them with its own TAI clock, so they all go through here and cannot drift apart.
*
* Until 2026-10 this was Unix time minus the epoch, without the leap seconds: the micrOBU's clock ran
* 5 s behind, so it rejected correctly timed VAMs from other stations as Invalid_Timestamp and restarted
* its stack whenever another source (the PC tools, which add the leap seconds) had set it correctly.
* TimestampIts (ETSI TS 102 894-2) counts milliseconds from 2004-01-01T00:00:00Z. Two fields in a
* single transmitted frame come from it: the CAM's generationDeltaTime (modulo 65536) and the
* GeoNetworking Source Position Vector's TST (modulo 2^32). A receiver can compare the two, so
* they must follow one rule. Both go through here so they cannot drift apart.
*
* **Which clock.** The input should be GNSS time, not the phone's wall clock. A phone with no SIM
* and no internet time has no automatic time source at all, and the bench phone was found 24
* minutes fast that way. `GnssTimeSource` moves a timestamp onto GNSS time, using [onGnssTime],
* before it gets here. Android reports GNSS time as UTC (Unix epoch ms), so the leap seconds are
* added here, not there.
* before it gets here.
*
* **Open question: leap seconds.** This is Unix time minus the 2004 epoch, with no leap-second
* term. If TimestampIts is read as TAI-based, the correct value is currently 5 s higher, for the
* five leap seconds inserted since 2004. Whichever reading turns out right, it is changed here and
* nowhere else. Settling it needs a frame from a third-party stack with a trusted clock, such as
* the RSU's CAM compared against GNSS time, and no such traffic was on air when this was written.
*/
object ItsTime {
/** 2004-01-01T00:00:00Z in Unix epoch milliseconds. */
const val EPOCH_MS = 1_072_915_200_000L
/**
* Unix epoch ms (UTC) from which each leap second inserted after the ITS epoch counts, from IERS via
* the IANA leap-seconds.list (TAI-UTC 32 s at the epoch, 37 s since 2017-01-01; the file of
* 2026-07 announces none before its expiry on 2027-06-28). A new leap second is added here when
* IERS Bulletin C announces one.
*/
private val LEAP_SECONDS_FROM_MS = longArrayOf(
1_136_073_600_000L, // 2006-01-01
1_230_768_000_000L, // 2009-01-01
1_341_100_800_000L, // 2012-07-01
1_435_708_800_000L, // 2015-07-01
1_483_228_800_000L, // 2017-01-01
)
/** Leap seconds inserted between the ITS epoch and the UTC instant [epochMs]. */
fun leapSecondsAt(epochMs: Long): Int = LEAP_SECONDS_FROM_MS.count { epochMs >= it }
/** TimestampIts for the UTC instant [epochMs] (Unix epoch ms), before any modulo is applied. */
fun timestampIts(epochMs: Long): Long = epochMs - EPOCH_MS + 1_000L * leapSecondsAt(epochMs)
/**
* The UTC instant (Unix epoch ms) of [timestampIts], the inverse of [timestampIts]. During an
* inserted leap second, which UTC cannot name, the first millisecond after it is returned.
*/
fun epochMs(timestampIts: Long): Long {
var leaps = 0
for ((index, from) in LEAP_SECONDS_FROM_MS.withIndex()) {
val itsAtFrom = timestampIts(from) // first TimestampIts after leap second index + 1
if (timestampIts >= itsAtFrom) leaps = index + 1
else if (timestampIts >= itsAtFrom - 1_000L) return from // inside the inserted second
}
return timestampIts + EPOCH_MS - 1_000L * leaps
}
/** TimestampIts for wall-clock [epochMs], before any modulo is applied. */
fun timestampIts(epochMs: Long): Long = epochMs - EPOCH_MS
/**
* Moves [systemMs], a reading of this phone's wall clock, onto GNSS time, using one pair of
@@ -1,298 +0,0 @@
package com.hawhamburg.micr0bu.domain.asn1
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.LaneConnection
import com.hawhamburg.micr0bu.domain.map.LaneNode
import com.hawhamburg.micr0bu.domain.map.LaneType
import com.hawhamburg.micr0bu.domain.map.MapEvent
import com.hawhamburg.micr0bu.domain.map.MapLane
import com.hawhamburg.micr0bu.domain.map.Maneuvers
import com.hawhamburg.micr0bu.domain.map.NodeOffset
import com.hawhamburg.micr0bu.domain.map.SpeedLimit
/**
* ASN.1 UPER **decoder** for MAPEM (ETSI TS 103 301 / SAE J2735 DSRC `MapData`), for messages
* received over the air on the ESP32-C5 path and from the CiT One's `v2x/rx/mapem` topic.
*
* Decode-only, like [SpatemUperCodec]: MAPEM is an RSU's message.
*
* ## Field widths
* From the ETSI modules in `asn1/` (`mapem_2_2_1.asn`, `dsrc_2_2_1.asn`, `cdd_2_2_1.asn`):
*
* - `Latitude` (-900000000..900000001) = 31 bits, `Longitude` (-1800000000..1800000001) = 32
* - `Elevation` (-4096..61439) = 16, `LaneWidth` (0..32767) = 15, `Velocity` (0..8191) = 13
* - `MsgCount` = 7, `LaneID` / `SignalGroupID` / `LaneConnectionID` / `RestrictionClassID` = 8,
* `ApproachID` = 4, `IntersectionID` / `RoadRegulatorID` = 16, `LayerID` (0..100) = 7
* - `Offset-B10..B16` = 10, 11, 12, 13, 14, 16 bits (offset by -2^(n-1)), the six XY node sizes
* - `DescriptiveName` IA5String (SIZE(1..63)): 6-bit length, then 7 bits per character
* - BIT STRINGs of fixed size are just their bits: `LaneDirection` 2, `LaneSharing` 10,
* `AllowedManeuvers` 12, the lane-type attributes 16, except `LaneAttributes-Vehicle`, which is
* `SIZE (8,...)` and so has an extension bit before its 8 bits
* - Extensible ENUMERATEDs are an extension bit plus the root index: `LayerType` 3,
* `SpeedLimitType` 4, `NodeAttributeXY` 4, `SegmentAttributeXY` (38 values) 6
* - `SEQUENCE (SIZE(lo..hi)) OF` counts are `n-lo` in ceil(log2(hi-lo+1)) bits: intersections 5,
* lanes 8, nodes (2..63) 6, connections 4, speed limits 4, node/segment attributes 3, overlays 3
*
* Traps, each of which silently shifts everything after it:
* - `LaneAttributes`, `Connection`, `ConnectingLane`, `IntersectionReferenceID` and
* `RegulatorySpeedLimit` are NOT extensible: no extension bit, unlike the SEQUENCEs around them.
* - `NodeOffsetPointXY` is a non-extensible CHOICE of 8 (3 bits), but `NodeListXY` and
* `LaneTypeAttributes` are extensible CHOICEs (extension bit first).
* - A lane's nodes start at the stop line and run outward, so an ingress lane is driven from its
* last node toward its first.
*
* ## Verification
* `MapemUperCodecTest` decodes every distinct MAPEM on record (17 from the 2026-03-18 drive, out of
* 7 916 received, 288 to 1348 bytes, plus the bench RSU's) and compares every decoded field with
* `asn1tools` decoding the same bytes against those modules.
*
* Returns null rather than guessing on an extension, a regional extension, a computed lane, or
* preempt priority data. A dropped MAPEM costs nothing - the next comes within a second - while a
* misread one would put a signal on the wrong lane.
*/
object MapemUperCodec {
private const val MESSAGE_ID_MAPEM = 5
private const val PROTOCOL_VERSION = 2
fun decode(bytes: ByteArray, receivedAtEpochMs: Long, rssiDbm: Int? = null): MapEvent? = try {
decodeOrNull(BitReader(bytes), receivedAtEpochMs, rssiDbm)
} catch (e: IndexOutOfBoundsException) {
null // truncated
}
private fun decodeOrNull(br: BitReader, receivedAtEpochMs: Long, rssiDbm: Int?): MapEvent? {
// ---- ItsPduHeader ----
if (br.getBitsInt(8) != PROTOCOL_VERSION) return null
if (br.getBitsInt(8) != MESSAGE_ID_MAPEM) return null
val stationId = br.getBits(32)
// ---- MapData: extension bit + 8 optionals ----
if (br.bit()) return null
val hasTimeStamp = br.bit()
val hasLayerType = br.bit()
val hasLayerId = br.bit()
val hasIntersections = br.bit()
br.getBits(4) // roadSegments, dataParameters, restrictionList, regional: after intersections
if (hasTimeStamp) br.getBits(20)
val revision = br.getBitsInt(7)
if (hasLayerType && !br.enumerated(3)) return null
if (hasLayerId) br.getBits(7)
if (!hasIntersections) return null // road segments only: nothing to join a SPATEM to
val count = br.getBitsInt(5) + 1
val intersections = ArrayList<IntersectionGeometry>(count)
repeat(count) { intersections.add(readIntersection(br) ?: return null) }
// What follows the intersections is not needed and nothing after it is read, so it is not
// walked either.
return MapEvent(stationId, revision, intersections, rssiDbm, receivedAtEpochMs)
}
private fun readIntersection(br: BitReader): IntersectionGeometry? {
if (br.bit()) return null
val hasName = br.bit()
val hasLaneWidth = br.bit()
val hasSpeedLimits = br.bit()
val hasPreempt = br.bit()
val hasRegional = br.bit()
val name = if (hasName) br.name() else null
val hasRegion = br.bit() // IntersectionReferenceID: not extensible
val region = if (hasRegion) br.getBitsInt(16) else null
val id = br.getBitsInt(16)
val revision = br.getBitsInt(7)
// Position3D: extensible, elevation + regional optional
if (br.bit()) return null
val hasElevation = br.bit()
if (br.bit()) return null // Position3D.regional
val lat = br.getBits(31) - 900_000_000L
val lon = br.getBits(32) - 1_800_000_000L
val elevation = if (hasElevation) br.getBitsInt(16) - 4096 else null
val laneWidth = if (hasLaneWidth) br.getBitsInt(15) else null
val speedLimits = if (hasSpeedLimits) br.speedLimits() ?: return null else emptyList()
val laneCount = br.getBitsInt(8) + 1
val lanes = ArrayList<MapLane>(laneCount)
repeat(laneCount) { lanes.add(readLane(br) ?: return null) }
if (hasPreempt || hasRegional) return null
return IntersectionGeometry(
region = region, id = id, revision = revision, name = name,
refLatitude = lat / 1e7, refLongitude = lon / 1e7, elevationDm = elevation,
laneWidthCm = laneWidth, speedLimits = speedLimits, lanes = lanes,
)
}
private fun readLane(br: BitReader): MapLane? {
if (br.bit()) return null
val hasName = br.bit()
val hasIngress = br.bit()
val hasEgress = br.bit()
val hasManeuvers = br.bit()
val hasConnects = br.bit()
val hasOverlays = br.bit()
val hasRegional = br.bit()
val laneId = br.getBitsInt(8)
val name = if (hasName) br.name() else null
val ingress = if (hasIngress) br.getBitsInt(4) else null
val egress = if (hasEgress) br.getBitsInt(4) else null
// LaneAttributes: NOT extensible, regional optional
val hasAttrRegional = br.bit()
val direction = br.getBitsInt(2)
val sharedWith = br.getBitsInt(10)
if (br.bit()) return null // LaneTypeAttributes extension
val type = LaneType.entries[br.getBitsInt(3)]
val typeAttributes = if (type == LaneType.VEHICLE) {
if (br.bit()) return null // LaneAttributes-Vehicle SIZE(8,...) extension
br.getBitsInt(8)
} else {
br.getBitsInt(16)
}
if (hasAttrRegional) return null
val maneuvers = if (hasManeuvers) Maneuvers(br.getBitsInt(12)) else null
// NodeListXY: extensible CHOICE { nodes, computed }
if (br.bit()) return null
if (br.getBitsInt(1) != 0) return null // ComputedLane
val nodeCount = br.getBitsInt(6) + 2
val nodes = ArrayList<LaneNode>(nodeCount)
repeat(nodeCount) { nodes.add(readNode(br) ?: return null) }
val connections = if (hasConnects) {
List(br.getBitsInt(4) + 1) { readConnection(br) }
} else emptyList()
val overlays = if (hasOverlays) List(br.getBitsInt(3) + 1) { br.getBitsInt(8) } else emptyList()
if (hasRegional) return null
return MapLane(
laneId = laneId, name = name, ingressApproach = ingress, egressApproach = egress,
isIngress = direction and 0b10 != 0, isEgress = direction and 0b01 != 0,
sharedWith = sharedWith, type = type, typeAttributes = typeAttributes,
maneuvers = maneuvers, nodes = nodes, connections = connections, overlays = overlays,
)
}
private fun readNode(br: BitReader): LaneNode? {
if (br.bit()) return null // NodeXY extension
val hasAttributes = br.bit()
val offset = when (br.getBitsInt(3)) {
0 -> br.xy(10)
1 -> br.xy(11)
2 -> br.xy(12)
3 -> br.xy(13)
4 -> br.xy(14)
5 -> br.xy(16)
6 -> {
val lon = br.getBits(32) - 1_800_000_000L
val lat = br.getBits(31) - 900_000_000L
NodeOffset.LatLon(latitude = lat.toInt(), longitude = lon.toInt())
}
else -> return null // regional
}
if (!hasAttributes) return LaneNode(offset)
// NodeAttributeSetXY: extensible, 7 optionals
if (br.bit()) return null
val hasLocal = br.bit()
val hasDisabled = br.bit()
val hasEnabled = br.bit()
val hasData = br.bit()
val hasDWidth = br.bit()
val hasDElevation = br.bit()
val hasRegional = br.bit()
val local = if (hasLocal) br.enumList(4) ?: return null else emptyList()
val disabled = if (hasDisabled) br.enumList(6) ?: return null else emptyList()
val enabled = if (hasEnabled) br.enumList(6) ?: return null else emptyList()
if (hasData && !br.skipLaneDataAttributes()) return null
val dWidth = if (hasDWidth) br.getBitsInt(10) - 512 else null
val dElevation = if (hasDElevation) br.getBitsInt(10) - 512 else null
if (hasRegional) return null
return LaneNode(offset, local, disabled, enabled, dWidth, dElevation)
}
private fun readConnection(br: BitReader): LaneConnection {
// Connection and ConnectingLane: neither is extensible
val hasRemote = br.bit()
val hasSignalGroup = br.bit()
val hasUserClass = br.bit()
val hasConnectionId = br.bit()
val hasManeuver = br.bit()
val toLane = br.getBitsInt(8)
val maneuver = if (hasManeuver) Maneuvers(br.getBitsInt(12)) else null
var remoteRegion: Int? = null
var remoteId: Int? = null
if (hasRemote) {
if (br.bit()) remoteRegion = br.getBitsInt(16)
remoteId = br.getBitsInt(16)
}
return LaneConnection(
toLane = toLane, maneuver = maneuver, remoteRegion = remoteRegion, remoteIntersection = remoteId,
signalGroup = if (hasSignalGroup) br.getBitsInt(8) else null,
userClass = if (hasUserClass) br.getBitsInt(8) else null,
connectionId = if (hasConnectionId) br.getBitsInt(8) else null,
)
}
// ---- primitives ----
private fun BitReader.bit(): Boolean = getBitsInt(1) == 1
private fun BitReader.xy(bits: Int): NodeOffset.Xy {
val half = 1 shl (bits - 1)
val x = getBitsInt(bits) - half
val y = getBitsInt(bits) - half
return NodeOffset.Xy(x, y)
}
/** DescriptiveName: IA5String (SIZE(1..63)). */
private fun BitReader.name(): String {
val length = getBitsInt(6) + 1
return String(CharArray(length) { getBitsInt(7).toChar() })
}
/** Reads an extensible ENUMERATED; false (value unusable) if it is an extension value. */
private fun BitReader.enumerated(rootBits: Int): Boolean {
if (bit()) return false
getBits(rootBits)
return true
}
/** SEQUENCE (SIZE(1..8)) OF an extensible ENUMERATED with [rootBits]-bit root indices. */
private fun BitReader.enumList(rootBits: Int): List<Int>? =
List(getBitsInt(3) + 1) {
if (bit()) return null
getBitsInt(rootBits)
}
/** SpeedLimitList ::= SEQUENCE (SIZE(1..9)) OF RegulatorySpeedLimit (not extensible). */
private fun BitReader.speedLimits(): List<SpeedLimit>? =
List(getBitsInt(4) + 1) {
if (bit()) return null // SpeedLimitType extension value
val type = getBitsInt(4)
SpeedLimit(type, getBitsInt(13))
}
/**
* Walks a LaneDataAttributeList: SEQUENCE (SIZE(1..8)) OF an extensible CHOICE of 7. Nothing
* here uses its content (none of the recorded MAPEMs carry one), but it sits between fields
* that are used.
*/
private fun BitReader.skipLaneDataAttributes(): Boolean {
repeat(getBitsInt(3) + 1) {
if (bit()) return false
when (getBitsInt(3)) {
0 -> getBits(9) // pathEndPointAngle DeltaAngle (-150..150)
1, 2, 3 -> getBits(8) // laneCrownPoint* RoadwayCrownAngle (-128..127)
4 -> getBits(9) // laneAngle MergeDivergeNodeAngle (-180..180)
5 -> if (speedLimits() == null) return false
else -> return false // regional
}
}
return true
}
}
@@ -28,10 +28,6 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
* A `SEQUENCE (SIZE(lo..hi)) OF` writes its count in `ceil(log2(hi-lo+1))` bits holding `n-lo`:
* intersections 1..32 gives 5 bits, movements 1..255 gives 8, events 1..16 gives 4.
*
* Names and advisory speeds are walked, not kept: a road RSU (Hamburg, 2026-11-23: 888-byte SPATEMs naming
* "Berliner Tor / Kolbergstrasse" and each movement, with a greenwave and an ecoDrive advice per event) sends
* both, and until then every one of its SPATEMs was refused.
*
* Two traps worth naming, both of which silently shift every later field:
* - `TimeChangeDetails` is **not** extensible, so it has 5 optional bits and no extension bit,
* unlike almost every other SEQUENCE here, which all carry one.
@@ -45,7 +41,7 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
* exactly, with no message hitting an unsupported branch.
*
* Returns null rather than guessing whenever an extension bit is set or an unsupported optional
* (regional extensions) appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
* appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
* the wrong light.
*/
object SpatemUperCodec {
@@ -77,7 +73,9 @@ object SpatemUperCodec {
val hasName = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
val minuteOfYear = if (hasTimeStamp) br.getBitsInt(20) else null
if (hasName) skipName(br)
// DescriptiveName is a variable-length IA5String. Nothing in 79k real messages uses it,
// and guessing its length would desynchronise everything after it.
if (hasName) return null
val intersectionCount = br.getBitsInt(5) + 1
if (intersectionCount > MAX_INTERSECTIONS) return null
@@ -104,7 +102,7 @@ object SpatemUperCodec {
val hasEnabledLanes = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (hasName) skipName(br)
if (hasName) return null
// IntersectionReferenceID - not extensible, one optional bit for region.
val region = if (br.getBitsInt(1) == 1) br.getBitsInt(16) else null
@@ -135,7 +133,7 @@ object SpatemUperCodec {
val hasName = br.getBitsInt(1) == 1
val hasManeuvers = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (hasName) skipName(br)
if (hasName) return null
val signalGroup = br.getBitsInt(8)
val eventCount = br.getBitsInt(4) + 1
@@ -164,8 +162,7 @@ object SpatemUperCodec {
if (hasConfidence) br.getBits(4)
if (hasNext) br.getBits(16)
}
if (hasSpeeds && !skipAdvisorySpeedList(br)) return null
if (hasRegionalEvent) return null
if (hasSpeeds || hasRegionalEvent) return null
events.add(SignalPhaseEvent(phase, minEnd, maxEnd, likely))
}
@@ -174,41 +171,6 @@ object SpatemUperCodec {
return SignalMovement(signalGroup, events)
}
/**
* `DescriptiveName` IA5String (SIZE(1..63)): 6-bit length holding n-1, then 7 bits per character.
* Not surfaced (a real RSU names its intersections and movements, the app does not show them here), but
* it has to be walked: it sits in front of fields that are.
*/
private fun skipName(br: BitReader) {
val length = br.getBitsInt(6) + 1
repeat(length) { br.getBits(7) }
}
/**
* Walks an `AdvisorySpeedList` (SIZE(1..16) OF AdvisorySpeed: the RSU's green wave and eco-drive advice)
* without keeping it; nothing consumes it yet. AdvisorySpeed is extensible with five optional fields
* (speed, confidence, distance, class, regional); `type` is an extensible ENUMERATED of four values.
* Returns false for an extension value or a regional extension, which this decoder cannot size.
*/
private fun skipAdvisorySpeedList(br: BitReader): Boolean {
repeat(br.getBitsInt(4) + 1) {
if (br.getBitsInt(1) != 0) return false // AdvisorySpeed extension
val hasSpeed = br.getBitsInt(1) == 1
val hasConfidence = br.getBitsInt(1) == 1
val hasDistance = br.getBitsInt(1) == 1
val hasClass = br.getBitsInt(1) == 1
val hasRegional = br.getBitsInt(1) == 1
if (br.getBitsInt(1) != 0) return false // AdvisorySpeedType extension value
br.getBits(2) // type: none, greenwave, ecoDrive, transit
if (hasSpeed) br.getBits(9) // SpeedAdvice (0..500)
if (hasConfidence) br.getBits(3) // SpeedConfidenceDSRC, 8 values, not extensible
if (hasDistance) br.getBits(14) // ZoneLength (0..10000)
if (hasClass) br.getBits(8) // RestrictionClassID (0..255)
if (hasRegional) return false
}
return true
}
/**
* Walks a `ManeuverAssistList` without keeping it. Nothing consumes queue lengths yet, but the
* list is variable-length, so it has to be parsed to find where the next field starts.
@@ -28,7 +28,7 @@ data class VamContent(
* UPER encoder for the VAM of ETSI TS 103 300-3 V2.3.1 (VAM-PDU-Descriptions major version 3,
* over the CDD of TS 102 894-2 V2.4.1), for a bicyclist in VRU profile 2.
*
* Covers the same field set as Niklas Dathe's reference VBS (microbu-esp32c5,
* Covers the same field set as the colleague's reference VBS (microbu-esp32c5,
* station-link/python/microbu_link/vbs.py, `VbsLite.assemble`), which encodes with asn1tools from
* the ETSI modules: header, basic container, the three mandatory fields of the high-frequency
* container, and optionally the low-frequency container with profile and size class. No cluster
@@ -14,20 +14,6 @@ object StationType {
* is 15 and not 12 - mapping by list position mislabels every RSU.
*/
const val ROAD_SIDE_UNIT = 15
/**
* The Use Case API's `stationType` string enum ("passengerCar") mapped to its ITS-G5 integer,
* per StationType in the ETSI CDD (CiT MQTT API v6, sections 2.1.1 and 2.2.3). Mapped by name,
* never by list position, because of the gap before [ROAD_SIDE_UNIT].
*/
private val BY_API_NAME = mapOf(
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
)
/** The ITS-G5 integer for an API station type name, or null for a blank or unknown name. */
fun fromApiName(name: String?): Int? = name?.takeIf { it.isNotBlank() }?.let { BY_API_NAME[it] }
}
/**
@@ -59,13 +45,8 @@ data class Cam(
val headingDeg: Double,
/**
* Yaw rate, degrees per second, where available (positive = turning clockwise, to the right,
* like [headingDeg] increasing). Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and
* `v2x-uca/output/json/cam` (remote).
*
* The CAM's YawRateValue and the CiT One's CAM topic count the other way, positive to the
* left, so `CamUperCodec` and `CamParser` flip the sign. The CiT One's `obu_gnss` topic is
* already positive to the right in practice, despite its document, so `ObuGnssParser` does not.
* Yaw rate, degrees per second, where available (positive = turning clockwise).
* Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and `v2x-uca/output/json/cam` (remote).
* A much more direct "is this road user turning" signal than heading-delta heuristics —
* see [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
*/
@@ -27,24 +27,17 @@ object CamParser {
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
val stationId = JsonFieldReader.firstLong(obj, "stationId", "stationID", "station_id") ?: return null
// The API sends the name ("passengerCar", CiT MQTT API v6 section 2.2.3); a number is still
// accepted. Until 2026-11-18 only a number was, so every real payload was dropped here.
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: StationType.fromApiName(obj.optString("stationType"))
?: return null
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: return null
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
// Positive to the left on this topic (CiT MQTT API v6, v2x-uca/output/json/cam), as in the CAM
// itself; negated into Cam.yawRateDps, which is positive clockwise.
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
?.let { -it }
val driveDirection = JsonFieldReader.firstInt(obj, "driveDirection", "drive_direction")
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength_m", "vehicleLength", "vehicle_length")
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth_m", "vehicleWidth", "vehicle_width")
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength", "vehicle_length")
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth", "vehicle_width")
val accel = JsonFieldReader.firstDouble(obj, "accelerationControl", "longitudinalAcceleration", "acceleration_mps2")
// Own/remote: prefer an explicit flag if the API provides one; otherwise compare
@@ -24,34 +24,16 @@ object ObuGnssParser {
*/
fun parseEgo(json: String, fallbackStationId: Long = 0L, timestamp: Long = System.currentTimeMillis()): Cam? {
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
// Identity and yaw rate are in `own_info`, kinematics in `gnss` (CiT MQTT API v6 Listing 2.1,
// and every logged payload). Until 2026-11-18 everything was read from `own_info`, which
// has no position, so every real message was dropped and the ego state never came from
// here. A flat payload with everything on the root is still accepted.
val obj = root.optJSONObject("own_info") ?: root
val gnss = root.optJSONObject("gnss") ?: obj
val stationId = JsonFieldReader.firstLong(obj, "stationID", "stationId", "station_id") ?: fallbackStationId
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: StationType.fromApiName(obj.optString("stationType"))
?: StationType.CYCLIST
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: StationType.CYCLIST
val (lat, lon) = JsonFieldReader.firstLatLon(gnss) ?: JsonFieldReader.firstLatLon(obj) ?: return null
// 91 / 181 is the API's "no 2D fix" marker, not a place.
if (lat > 90.0 || lon > 180.0) return null
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
// 163.82 m/s is the API's "invalid speed" marker; treated like a missing speed.
val speed = JsonFieldReader.firstDouble(gnss, "speed_mps", "speed", "speedMps")
?.takeIf { it < INVALID_SPEED_MPS } ?: 0.0
val heading = JsonFieldReader.firstDouble(gnss, "heading_deg", "heading", "headingDeg") ?: 0.0
val acceleration = JsonFieldReader.firstDouble(gnss, "acceleration_mpss")
// `yawRate_degps` is this topic's name (CiT MQTT API v6, Listing 2.1, own_info, and every
// logged payload). The document says positive to the left, but the CiT One sends it positive
// to the RIGHT: in the 2026-03-18 bacospat log, all 27 one-second windows of turning at over
// 4 m/s had it with the same sign as the clockwise heading change. That is already
// Cam.yawRateDps's convention, so it is taken as it is - unlike the CAM topic (CamParser),
// which the logs show is left-positive, as documented.
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_degps", "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
return Cam(
stationId = stationId,
@@ -61,17 +43,11 @@ object ObuGnssParser {
speedMps = speed,
headingDeg = JsonFieldReader.normaliseHeadingDeg(heading),
yawRateDps = yawRate,
vehicleLengthM = JsonFieldReader.firstDouble(obj, "vehicleLength_m"),
vehicleWidthM = JsonFieldReader.firstDouble(obj, "vehicleWidth_m"),
accelerationMps2 = acceleration,
timestamp = timestamp,
isOwn = true,
)
}
/** The API's "invalid speed calculation" value (CiT MQTT API v6 section 2.1.1). */
private const val INVALID_SPEED_MPS = 163.82
/** Just the stationID/stationType, for when only identity (not a full fix) is needed. */
fun parseOwnIdentity(json: String): Pair<Long, Int>? {
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
@@ -12,19 +12,18 @@ import kotlin.math.abs
*
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
*
* Position/speed/heading come straight from GNSS. Yaw rate comes from the gyroscope projected
* onto gravity ([com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]), so it is the rotation
* about the true vertical however the phone is mounted, rather than from GNSS heading deltas,
* which are noisy at low speed — same rationale already used for remote-vehicle turn detection
* in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
* Position/speed/heading come straight from GNSS. Yaw rate is derived from the gyroscope's
* z-axis reading (rotation about the vertical axis while the phone is roughly flat/mounted
* upright) rather than from GNSS heading deltas, which are noisy at low speed — same rationale
* already used for remote-vehicle turn detection in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
*/
object PhoneCamBuilder {
/**
* @param gnss latest phone GNSS fix, its timestamp already on the time base to transmit.
* @param yawRateDps yaw rate about the vertical, deg/s, in the convention of [Cam.yawRateDps]
* (positive = clockwise), from [com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator].
* Null encodes as the ASN.1 `unavailable` sentinel.
* @param gnss latest phone GNSS fix.
* @param gyroZRadPerSec latest gyroscope z-axis reading, rad/s (device frame). Positive per
* Android's convention is counter-clockwise around +Z; converted to the clockwise-positive
* yaw rate convention already used by [Cam.yawRateDps] to match OBU/remote CAM data.
* @param stationId the station ID to transmit under: the current pseudonym from
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager], or the bench pinger's fixed ID.
* Receivers track a station across successive CAMs by this ID, which is why it only ever
@@ -38,10 +37,12 @@ object PhoneCamBuilder {
*/
fun build(
gnss: GnssReading,
yawRateDps: Double?,
gyroZRadPerSec: Float?,
stationId: Long,
longitudinalAccelMps2: Double? = null,
): Cam {
val yawRateDps = gyroZRadPerSec?.let { -it * RAD_TO_DEG } // negate: CCW+ -> CW+ convention
return Cam(
stationId = stationId,
stationType = StationType.CYCLIST,
@@ -62,6 +63,8 @@ object PhoneCamBuilder {
return h
}
private const val RAD_TO_DEG = 180.0 / Math.PI
/**
* Gyro noise floor below which yaw rate is clamped to zero. Placeholder — initial
* engineering estimate pending real-world tuning, same disclaimer as
@@ -1,7 +1,6 @@
package com.hawhamburg.micr0bu.domain.denm
import com.hawhamburg.micr0bu.domain.cam.JsonFieldReader
import com.hawhamburg.micr0bu.domain.cam.StationType
import org.json.JSONObject
/**
@@ -124,6 +123,17 @@ object DenmParser {
*/
fun causeCodeName(causeCode: Int?): String? = causeCode?.let { NAME_BY_CAUSE_CODE[it] }
/**
* The Use Case API's `stationType` string enum mapped to its ITS-G5 integer, per StationType in
* the ETSI CDD. Note roadSideUnit is **15**, not 12 - the enumeration has a gap after tram(11),
* so mapping by list position would silently mislabel every RSU.
*/
private val STATION_TYPE_BY_NAME = mapOf(
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
)
/**
* Parses the API's RFC3339 timestamps ("2021-05-11T12:01:02+00:00") to epoch millis. The air
* path carries a binary TimestampIts instead, so the two transports arrive here in completely
@@ -177,7 +187,7 @@ object DenmParser {
val isTermination = obj.has("termination") && obj.optBoolean("termination", true)
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
?: StationType.fromApiName(obj.optString("stationType"))
?: STATION_TYPE_BY_NAME[obj.optString("stationType").takeIf { it.isNotBlank() }]
return DenmEvent(
stationId = stationId,
@@ -1,25 +0,0 @@
package com.hawhamburg.micr0bu.domain.fusion
/**
* Where the phone rides, as set in Settings > Ride.
*
* The sensor fusion filter treats the motion sensors differently per mount: on the handlebar the
* phone is fixed to the bike (but turns with the steering), in a bag on the bike it is mostly fixed
* but can shift, and in a pocket or backpack it moves with the rider's body, so shoulder checks look
* like turns. Every V2X log records the setting (`meta.phone_mount`), so a recorded ride says which
* mount it was.
*
* [id] is what is stored and logged; it must not change once logs exist.
*/
enum class PhoneMount(val id: String) {
HANDLEBAR("handlebar"),
BAG("bag"),
POCKET("pocket");
companion object {
val DEFAULT = HANDLEBAR
/** The mount stored under [id], or [DEFAULT] for a missing or unknown value. */
fun fromId(id: String?): PhoneMount = entries.firstOrNull { it.id == id } ?: DEFAULT
}
}
@@ -1,123 +0,0 @@
package com.hawhamburg.micr0bu.domain.fusion
import kotlin.math.sqrt
/**
* Yaw rate about the true vertical, whatever way up the phone is held.
*
* ## Why
* Yaw rate used to be the gyroscope's z axis alone. That is rotation about the screen's normal, so
* it is the yaw rate only with the phone lying flat, screen up. On a handlebar mount tilted towards
* the rider it is scaled down by the tilt and mixed with pitch and roll; with the phone upright,
* or loose in a bag, it is unrelated to the bike's turning at all.
*
* ## How
* Gravity (from `TYPE_GRAVITY`, in the device frame) gives the up direction. The rate about it is
* the gyroscope vector projected onto that unit vector: `ω · up`. That is the same number for any
* orientation of the phone, as long as the phone is held still relative to the bike.
*
* Samples are averaged over [windowNanos] ending at the newest gyroscope sample, rather than taking
* one raw sample: a single gyroscope sample on a bike is mostly vibration.
*
* A bike leans into a turn, and over a sustained turn `TYPE_GRAVITY` drifts toward the bike's own
* vertical. The result is then the turn rate scaled by the cosine of the lean, about 6 % low at
* 20° of lean. Small next to what the z-axis reading got wrong.
*
* All times are on the monotonic `SystemClock.elapsedRealtimeNanos` base (`SensorEvent.timestamp`),
* never the wall clock. Pure Kotlin, so it is tested apart from Android. Thread-safe: samples and
* reads may come from different threads.
*/
class YawRateEstimator(
private val windowNanos: Long = DEFAULT_WINDOW_NANOS,
private val staleNanos: Long = DEFAULT_STALE_NANOS,
) {
private val lock = Any()
private var upX = 0.0
private var upY = 0.0
private var upZ = 0.0
/** When the up direction was last measured; null until the first gravity sample. */
private var upAtNanos: Long? = null
private val times = LongArray(CAPACITY)
/** Rotation about up, rad/s, counter-clockwise seen from above (Android's sign convention). */
private val rates = DoubleArray(CAPACITY)
private var next = 0
private var count = 0
/** A gravity sample, m/s², device frame, pointing up. Ignored if too weak to give a direction. */
fun onGravity(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
val norm = sqrt(x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
if (norm < MIN_GRAVITY_MPS2) return // free fall or a broken sample: no direction to trust
synchronized(lock) {
upX = x / norm
upY = y / norm
upZ = z / norm
upAtNanos = elapsedRealtimeNanos
}
}
/**
* A gyroscope sample, rad/s, device frame. Dropped while the up direction is unknown or stale,
* since projecting onto an old up vector would report the phone's rotation since then as yaw.
*/
fun onGyro(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
synchronized(lock) {
val upAt = upAtNanos ?: return
if (elapsedRealtimeNanos - upAt > staleNanos) return
times[next] = elapsedRealtimeNanos
rates[next] = x * upX + y * upY + z * upZ
next = (next + 1) % CAPACITY
if (count < CAPACITY) count++
}
}
/**
* Mean yaw rate over the last [windowNanos] of samples, deg/s, positive = turning clockwise
* seen from above: the convention of [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps].
* Null when there is no sample newer than [staleNanos] before [nowElapsedRealtimeNanos].
*/
fun yawRateDps(nowElapsedRealtimeNanos: Long): Double? {
synchronized(lock) {
if (count == 0) return null
val newestIndex = (next - 1 + CAPACITY) % CAPACITY
val newest = times[newestIndex]
if (nowElapsedRealtimeNanos - newest > staleNanos) return null
var sum = 0.0
var n = 0
for (k in 0 until count) {
val i = (newestIndex - k + CAPACITY) % CAPACITY
if (newest - times[i] > windowNanos) break
sum += rates[i]
n++
}
// Negate: counter-clockwise positive (Android) -> clockwise positive (Cam.yawRateDps).
return -(sum / n) * RAD_TO_DEG
}
}
fun reset() {
synchronized(lock) {
upAtNanos = null
next = 0
count = 0
}
}
companion object {
/** 100 ms: five samples at `SENSOR_DELAY_GAME` (about 50 Hz). */
const val DEFAULT_WINDOW_NANOS = 100_000_000L
/** Older than this, a gyroscope or gravity sample no longer describes the present. */
const val DEFAULT_STALE_NANOS = 500_000_000L
/** Room for the window at up to a few hundred Hz. */
private const val CAPACITY = 128
/** Well below 9.81: gravity this weak means free fall or a bad sample, not a direction. */
private const val MIN_GRAVITY_MPS2 = 3.0
private const val RAD_TO_DEG = 180.0 / Math.PI
}
}
@@ -1,172 +0,0 @@
package com.hawhamburg.micr0bu.domain.map
import kotlin.math.PI
import kotlin.math.cos
/**
* Intersection geometry for one or more intersections, decoded from a MAPEM heard over the air
* (ETSI TS 103 301 / SAE J2735 DSRC `MapData`).
*
* MAPEM is SPATEM's static half: it says where each lane runs, which lanes it may be left for,
* and which signal group controls each of those connections. SPATEM then says what each signal
* group is showing. The two join on [IntersectionGeometry.key] and the signal group number; see
* [com.hawhamburg.micr0bu.domain.spat.TrafficLights].
*
* Repetition is about 1 Hz per intersection and the content rarely changes, so consumers keep the
* latest per [IntersectionGeometry.key].
*/
data class MapEvent(
/** Originating RSU's station ID, from the ItsPduHeader. */
val stationId: Long,
/** `MapData.msgIssueRevision`. */
val msgIssueRevision: Int,
val intersections: List<IntersectionGeometry>,
/** Received signal strength, dBm - ESP32-C5 path only. */
val rssiDbm: Int? = null,
/** Wall-clock ms this MAPEM was received. */
val timestamp: Long,
)
/** One intersection's lanes, all positioned relative to [refLatitude]/[refLongitude]. */
data class IntersectionGeometry(
/** `RoadRegulatorID`, when present. */
val region: Int?,
/** `IntersectionID` - only unique within [region]. */
val id: Int,
/** `MsgCount`; a SPATEM for this intersection carries the same number when it matches. */
val revision: Int,
val name: String?,
/** Reference point, degrees (`Latitude`/`Longitude` are 1/10 microdegree on the wire). */
val refLatitude: Double,
val refLongitude: Double,
/** Reference point elevation, decimetres, when present. */
val elevationDm: Int?,
/** Default lane width, centimetres, when present. */
val laneWidthCm: Int?,
/** `vehicleMaxSpeed` and friends, as (SpeedLimitType value, speed in 0.02 m/s units). */
val speedLimits: List<SpeedLimit>,
val lanes: List<MapLane>,
) {
/** Same scheme as [com.hawhamburg.micr0bu.domain.spat.IntersectionSignalState.key]. */
val key: String get() = "${region ?: -1}/$id"
fun lane(laneId: Int): MapLane? = lanes.firstOrNull { it.laneId == laneId }
}
data class SpeedLimit(
/** `SpeedLimitType` enumeration value (5 = vehicleMaxSpeed). */
val type: Int,
/** `Velocity`: 0.02 m/s units. */
val speed: Int,
) {
val metresPerSecond: Double get() = speed * 0.02
}
/** One `GenericLane`. */
data class MapLane(
val laneId: Int,
val name: String?,
val ingressApproach: Int?,
val egressApproach: Int?,
/** `LaneDirection` bit 0: traffic travels toward the stop line (into the intersection). */
val isIngress: Boolean,
/** `LaneDirection` bit 1: traffic travels away from the intersection. */
val isEgress: Boolean,
/** `LaneSharing`, 10 bits, bit 0 (overlappingLaneDescriptionProvided) as the MSB. */
val sharedWith: Int,
val type: LaneType,
/** The type's attribute BIT STRING (8 bits for vehicle lanes, 16 for the rest), MSB = bit 0. */
val typeAttributes: Int,
/** `AllowedManeuvers` for the lane as a whole, when present. */
val maneuvers: Maneuvers?,
/**
* The lane's centre line, starting at the stop line (the node nearest the intersection) and
* running outward. Each node is an offset from the previous one, the first from the
* intersection's reference point.
*/
val nodes: List<LaneNode>,
val connections: List<LaneConnection>,
/** `overlays`: lane IDs drawn over this one. */
val overlays: List<Int>,
)
/** `LaneTypeAttributes` CHOICE, in alternative order: the ordinal is the wire index. */
enum class LaneType { VEHICLE, CROSSWALK, BIKE_LANE, SIDEWALK, MEDIAN, STRIPING, TRACKED_VEHICLE, PARKING }
/** One `NodeXY`: where the node is, plus the attributes the decoder keeps. */
data class LaneNode(
val offset: NodeOffset,
/** `NodeAttributeXY` values (1 = stopLine), when present. */
val localAttributes: List<Int> = emptyList(),
/** `SegmentAttributeXY` values disabled / enabled from this node on. */
val disabled: List<Int> = emptyList(),
val enabled: List<Int> = emptyList(),
/** Lane width change from here on, centimetres. */
val dWidthCm: Int? = null,
/** Elevation change, centimetres. */
val dElevationCm: Int? = null,
)
sealed interface NodeOffset {
/** `node-XY1`..`node-XY6`: east ([xCm]) and north ([yCm]) of the previous node, centimetres. */
data class Xy(val xCm: Int, val yCm: Int) : NodeOffset
/** `node-LatLon`: an absolute position, 1/10 microdegree. */
data class LatLon(val latitude: Int, val longitude: Int) : NodeOffset
}
/** One `Connection`: this lane may be left for [toLane], under [signalGroup]'s light. */
data class LaneConnection(
val toLane: Int,
/** `connectingLane.maneuver`: which way this particular connection turns, when given. */
val maneuver: Maneuvers?,
/** Set when [toLane] belongs to another intersection: that intersection's (region, id). */
val remoteRegion: Int?,
val remoteIntersection: Int?,
/** `SignalGroupID` - the movement in a SPATEM for this intersection that controls it. */
val signalGroup: Int?,
val userClass: Int?,
val connectionId: Int?,
)
/** `AllowedManeuvers`, a 12-bit BIT STRING; [bits] holds it with bit 0 as the MSB (0x800). */
@JvmInline
value class Maneuvers(val bits: Int) {
private fun has(bit: Int) = bits and (0x800 ushr bit) != 0
val straight: Boolean get() = has(0)
val left: Boolean get() = has(1)
val right: Boolean get() = has(2)
val uTurn: Boolean get() = has(3)
val leftTurnOnRed: Boolean get() = has(4)
val rightTurnOnRed: Boolean get() = has(5)
}
/** A lane node as a position. */
data class MapPoint(val latitude: Double, val longitude: Double)
/**
* Absolute positions of [lane]'s nodes, stop line first.
*
* XY offsets are metres on a local plane tangent at the reference point (DSRC's definition), so a
* spherical approximation is exact enough at intersection scale: a 100 m lane is off by well
* under a millimetre.
*/
fun IntersectionGeometry.lanePoints(lane: MapLane): List<MapPoint> {
var lat = refLatitude
var lon = refLongitude
return lane.nodes.map { node ->
when (val o = node.offset) {
is NodeOffset.Xy -> {
lat += o.yCm / 100.0 / METRES_PER_DEGREE
lon += o.xCm / 100.0 / (METRES_PER_DEGREE * cos(refLatitude * PI / 180.0))
}
is NodeOffset.LatLon -> {
lat = o.latitude / 1e7
lon = o.longitude / 1e7
}
}
MapPoint(lat, lon)
}
}
/** Metres per degree of latitude on the WGS 84 equatorial-radius sphere. */
private const val METRES_PER_DEGREE = 6_378_137.0 * PI / 180.0
@@ -1,38 +0,0 @@
package com.hawhamburg.micr0bu.domain.map
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
/**
* Intersection geometry the app ships with (`assets/mapem/hamburg.txt`, built by
* `tools/mapem_bundle.py` from recorded MAPEMs), so a SPATEM can be placed on its lanes without
* waiting for, or ever receiving, the intersection's MAPEM.
*
* Which stored intersection a SPATEM belongs to is decided in
* [com.hawhamburg.micr0bu.domain.spat.TrafficLights.geometryFor].
*/
object StoredMaps {
const val ASSET_PATH = "mapem/hamburg.txt"
/**
* One UPER MAPEM per line as hex; blank lines and `#` comments are skipped, as is a line that
* does not decode, so one bad entry does not cost the rest.
*/
fun parse(text: String): List<IntersectionGeometry> =
text.lineSequence()
.map { it.trim() }
.filter { it.isNotEmpty() && !it.startsWith("#") }
.mapNotNull { hexToBytes(it) }
.flatMap { MapemUperCodec.decode(it, 0L)?.intersections.orEmpty() }
.toList()
private fun hexToBytes(hex: String): ByteArray? {
if (hex.length % 2 != 0) return null
return ByteArray(hex.length / 2) { i ->
val high = Character.digit(hex[2 * i], 16)
val low = Character.digit(hex[2 * i + 1], 16)
if (high < 0 || low < 0) return null
(high * 16 + low).toByte()
}
}
}
@@ -1,269 +0,0 @@
package com.hawhamburg.micr0bu.domain.spat
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.LaneConnection
import com.hawhamburg.micr0bu.domain.map.LaneType
import com.hawhamburg.micr0bu.domain.map.MapLane
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.map.Maneuvers
import com.hawhamburg.micr0bu.domain.map.lanePoints
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.hypot
/**
* A signalised intersection as a road user sees it: SPATEM's signal groups placed on MAPEM's lanes.
*
* MAPEM says "ingress lane 1 may be left straight ahead for lane 6, under signal group 1"; SPATEM
* says "signal group 1 is green for another 12 s". Joined, that is "North in, straight: green,
* 12 s" - and, with the rider's position and heading, which of those is the rider's own light.
*/
data class TrafficLight(
/** `region/id`, as [IntersectionSignalState.key] and [IntersectionGeometry.key]. */
val key: String,
/** The latest SPATEM for this intersection, if one has been heard. */
val signal: SpatIntersection?,
/** The latest MAPEM for it, if one has been heard. Without it, signal groups are bare numbers. */
val geometry: IntersectionGeometry?,
/** Every ingress lane that has a signalled connection, in MAPEM order. */
val approaches: List<ApproachSignals>,
/** The ingress lane the rider is on, when [geometry], a position and a heading say so. */
val ownApproach: OwnApproach?,
) {
/**
* The SPATEM's revision differs from the MAPEM's: the geometry the signal groups refer to has
* changed since this MAPEM, so the lane labels may be wrong until the new MAPEM arrives.
*/
val revisionMismatch: Boolean
get() = signal != null && geometry != null && signal.state.revision != geometry.revision
val name: String? get() = geometry?.name
}
/** One ingress lane and the light for each way out of it. */
data class ApproachSignals(
val lane: MapLane,
/** Where the lane's stop line is (its first node). */
val stopLine: MapPoint,
/** Travel direction into the intersection, degrees clockwise from north. */
val bearingDeg: Double,
val exits: List<LaneExit>,
) {
/**
* Exits grouped by signal group, each with every turn that group controls: the usual case is
* one group for straight-and-right and another for left, and a rider wants one light per group.
*/
val byGroup: List<Pair<Int?, List<LaneExit>>>
get() = exits.groupBy { it.connection.signalGroup }.toList()
}
/** One `Connection` with the turn it makes and the SPATEM movement that controls it. */
data class LaneExit(
val connection: LaneConnection,
val turn: Turn,
/** The movement for [LaneConnection.signalGroup] in the latest SPATEM, if it has one. */
val movement: SignalMovement?,
)
enum class Turn { STRAIGHT, LEFT, RIGHT, U_TURN, UNKNOWN }
data class OwnApproach(
val approach: ApproachSignals,
/** Along the lane from the rider to the stop line. */
val distanceToStopLineM: Double,
)
object TrafficLights {
/** Farther than this from the reference point, no lane is matched to the rider. */
const val MATCH_RADIUS_M = 200.0
/** A lane matches only if the rider is within this of its centre line. */
private const val MATCH_LATERAL_M = 6.0
/** ...and travelling within this of its direction, when moving fast enough for a heading. */
private const val MATCH_HEADING_DEG = 50.0
private const val MIN_SPEED_FOR_HEADING_MPS = 1.0
/**
* Joins [signal] and [geometry] (either may be null, not both) for a rider at [own], if known.
* [ownSpeedMps] below [MIN_SPEED_FOR_HEADING_MPS] means the heading is not trusted and the
* nearest lane wins on distance alone.
*/
fun join(
signal: SpatIntersection?,
geometry: IntersectionGeometry?,
own: MapPoint? = null,
ownHeadingDeg: Double? = null,
ownSpeedMps: Double? = null,
): TrafficLight {
val key = signal?.key ?: geometry?.key ?: error("join needs a SPATEM or a MAPEM")
if (geometry == null) return TrafficLight(key, signal, null, emptyList(), null)
val movements = signal?.state?.movements?.associateBy { it.signalGroup } ?: emptyMap()
val approaches = geometry.lanes
.filter { it.isIngress && it.connections.any { c -> c.signalGroup != null } }
.mapNotNull { lane ->
val points = geometry.lanePoints(lane)
if (points.size < 2) return@mapNotNull null
val bearing = bearing(geometry, points[1], points[0])
ApproachSignals(
lane = lane,
stopLine = points[0],
bearingDeg = bearing,
exits = lane.connections.filter { it.signalGroup != null }.map { c ->
LaneExit(c, turnOf(geometry, lane, c, bearing), movements[c.signalGroup])
},
)
}
val ownApproach = own?.let { match(geometry, approaches, it, ownHeadingDeg, ownSpeedMps) }
return TrafficLight(key, signal, geometry, approaches, ownApproach)
}
/**
* The turn a connection makes: its own `maneuver` when it names exactly one turn, else the
* lane's, else the angle between the ingress lane and the lane it leads to. Only about half the
* recorded connections carry a maneuver.
*/
internal fun turnOf(geometry: IntersectionGeometry, lane: MapLane, c: LaneConnection, inBearing: Double): Turn {
c.maneuver?.single()?.let { return it }
lane.maneuvers?.single()?.let { return it }
return geometricTurn(geometry, c, inBearing)
}
/** The turn from the angle between the ingress lane ([inBearing]) and where [c] leads. */
internal fun geometricTurn(geometry: IntersectionGeometry, c: LaneConnection, inBearing: Double): Turn {
if (c.remoteIntersection != null) return Turn.UNKNOWN
val target = geometry.lane(c.toLane) ?: return Turn.UNKNOWN
val points = geometry.lanePoints(target)
if (points.size < 2) return Turn.UNKNOWN
val delta = normalise(bearing(geometry, points[0], points[1]) - inBearing)
return when {
abs(delta) <= 35.0 -> Turn.STRAIGHT
delta in 35.0..150.0 -> Turn.RIGHT
delta in -150.0..-35.0 -> Turn.LEFT
else -> Turn.U_TURN
}
}
/**
* Which of the MAPEMs heard for one intersection a SPATEM refers to: the one with its revision,
* else the newest. Two revisions of one intersection can be on air at once (the 2026-03-18 drive
* heard 1/1 at revisions 2 and 3, with SPATEMs for both), and their signal groups differ.
*/
fun pickGeometry(candidates: List<IntersectionGeometry>, spatRevision: Int?): IntersectionGeometry? =
candidates.lastOrNull { it.revision == spatRevision } ?: candidates.lastOrNull()
/** A stored MAPEM is only used for a rider this close to its reference point. */
const val STORED_MAP_RADIUS_M = 2_000.0
/**
* The geometry for the intersection a SPATEM names, out of what was heard on air ([live],
* oldest first) and what the app ships with ([stored]).
*
* Both are matched on region and intersection id ([IntersectionGeometry.key]), never on the
* sending station: one intersection is heard under several station ids. In order:
*
* 1. a live MAPEM of the SPATEM's revision;
* 2. a stored one of that revision, within [STORED_MAP_RADIUS_M] of [own] when the position
* is known;
* 3. the newest live one of another revision (flagged by [TrafficLight.revisionMismatch]).
*
* A stored MAPEM of another revision is never used: it may be months old, and its signal groups
* could put the wrong light on a lane.
*/
fun geometryFor(
key: String,
spatRevision: Int,
live: List<IntersectionGeometry>,
stored: List<IntersectionGeometry>,
own: MapPoint? = null,
): IntersectionGeometry? {
val heard = pickGeometry(live.filter { it.key == key }, spatRevision)
if (heard?.revision == spatRevision) return heard
val shipped = stored.lastOrNull {
it.key == key && it.revision == spatRevision && (own == null || isNear(it, own))
}
return shipped ?: heard
}
private fun isNear(geometry: IntersectionGeometry, own: MapPoint): Boolean {
val (east, north) = geometry.toLocal(own)
return hypot(east, north) <= STORED_MAP_RADIUS_M
}
internal fun Maneuvers.single(): Turn? {
val turns = listOfNotNull(
Turn.STRAIGHT.takeIf { straight }, Turn.LEFT.takeIf { left },
Turn.RIGHT.takeIf { right }, Turn.U_TURN.takeIf { uTurn },
)
return turns.singleOrNull()
}
private fun match(
geometry: IntersectionGeometry,
approaches: List<ApproachSignals>,
own: MapPoint,
headingDeg: Double?,
speedMps: Double?,
): OwnApproach? {
val p = geometry.toLocal(own)
if (hypot(p.first, p.second) > MATCH_RADIUS_M) return null
val useHeading = headingDeg != null && (speedMps ?: 0.0) >= MIN_SPEED_FOR_HEADING_MPS
var best: Pair<OwnApproach, Double>? = null
for (approach in approaches) {
// A rider can only be on a lane they may use: crosswalks and sidewalks are not theirs.
if (approach.lane.type != LaneType.VEHICLE && approach.lane.type != LaneType.BIKE_LANE) continue
val points = geometry.lanePoints(approach.lane).map { geometry.toLocal(it) }
var along = 0.0
for (s in 0 until points.size - 1) {
val (ax, ay) = points[s]
val (bx, by) = points[s + 1]
val dx = bx - ax
val dy = by - ay
val length = hypot(dx, dy)
if (length < 0.01) continue
// Projection onto segment a->b (outward from the stop line)
val t = (((p.first - ax) * dx + (p.second - ay) * dy) / (length * length)).coerceIn(0.0, 1.0)
val lateral = hypot(p.first - (ax + t * dx), p.second - (ay + t * dy))
val beyondStopLine = s == 0 && t == 0.0 && ((p.first - ax) * dx + (p.second - ay) * dy) < 0
if (lateral <= MATCH_LATERAL_M && !beyondStopLine) {
// Travel on an ingress lane runs b->a, toward the stop line.
val travel = compassBearing(-dx, -dy)
val headingOk = !useHeading || abs(normalise(headingDeg!! - travel)) <= MATCH_HEADING_DEG
if (headingOk && (best == null || lateral < best.second)) {
best = OwnApproach(approach, along + t * length) to lateral
}
}
along += length
}
}
return best?.first
}
/** East/north metres from the reference point, on the same tangent plane as the XY offsets. */
private fun IntersectionGeometry.toLocal(p: MapPoint): Pair<Double, Double> =
Pair(
(p.longitude - refLongitude) * METRES_PER_DEGREE * cos(refLatitude * PI / 180.0),
(p.latitude - refLatitude) * METRES_PER_DEGREE,
)
private fun bearing(geometry: IntersectionGeometry, from: MapPoint, to: MapPoint): Double {
val a = geometry.toLocal(from)
val b = geometry.toLocal(to)
return compassBearing(b.first - a.first, b.second - a.second)
}
/** Degrees clockwise from north of the vector (east, north), in [0, 360). */
private fun compassBearing(east: Double, north: Double): Double =
(atan2(east, north) * 180.0 / PI + 360.0) % 360.0
/** Into (-180, 180]. */
private fun normalise(deg: Double): Double {
var d = deg % 360.0
if (d > 180.0) d -= 360.0
if (d <= -180.0) d += 360.0
return d
}
private const val METRES_PER_DEGREE = 6_378_137.0 * PI / 180.0
}
@@ -5,7 +5,7 @@ import kotlin.math.abs
/**
* When to send an individual VAM: ETSI TS 103 300-3 V2.3.1 clause 6.4, items 1 to 4, with the
* recommended values of Tables 16 and 17 — the same rules Niklas Dathe's reference VBS applies
* recommended values of Tables 16 and 17 — the same rules the colleague's reference VBS applies
* (microbu-esp32c5/station-link/python/microbu_link/vbs.py, `VbsLite.due`). No clustering, no
* redundancy mitigation, T_GenVam fixed at its minimum (no DCC input).
*
@@ -1,7 +1,6 @@
package com.hawhamburg.micr0bu.service
import android.content.Context
import android.hardware.SensorManager
import android.os.SystemClock
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.GnssTimeSource
@@ -14,7 +13,6 @@ import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -64,7 +62,7 @@ class CamPinger @Inject constructor(
private var job: Job? = null
@Volatile private var latestGnss: GnssReading? = null
private val yawRate = YawRateEstimator()
@Volatile private var latestGyroZ: Float? = null
@Volatile private var previousGnss: GnssReading? = null
private val _isActive = MutableStateFlow(false)
@@ -104,24 +102,16 @@ class CamPinger @Inject constructor(
private suspend fun runPingLoop() = coroutineScope {
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
yawRate.reset()
launch {
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch {
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
while (true) {
val gnss = latestGnss
_hasFix.value = gnss != null
if (gnss != null) {
val cam = PhoneCamBuilder.build(
// Stamped with the GNSS time of the fix itself; see GnssTimeSource.atElapsedRealtime.
gnss = gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos)),
yawRateDps = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos()),
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource.
gnss = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)),
gyroZRadPerSec = latestGyroZ,
stationId = OwnStationIds.BENCH_PING,
longitudinalAccelMps2 = longitudinalAccel(gnss),
)
@@ -150,7 +140,7 @@ class CamPinger @Inject constructor(
previousGnss = gnss
if (prev == null) return null
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec
@@ -1,8 +1,6 @@
package com.hawhamburg.micr0bu.service
import android.content.Context
import android.hardware.SensorManager
import android.os.SystemClock
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.GnssTimeSource
import com.hawhamburg.micr0bu.data.SensorRepository
@@ -18,7 +16,6 @@ import com.hawhamburg.micr0bu.domain.asn1.VamContent
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
import com.hawhamburg.micr0bu.domain.cam.CamTransmitConfig
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -76,9 +73,7 @@ class CamTransmitLoop @Inject constructor(
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@Volatile private var latestGnss: GnssReading? = null
private val yawRate = YawRateEstimator()
/** [SystemClock.elapsedRealtime] until which the elevated rate holds; monotonic, see [nowMs]. */
@Volatile private var latestGyroZ: Float? = null
@Volatile private var elevatedUntilMs: Long = 0L
/** Previous GNSS fix, kept only to derive along-track acceleration — see [longitudinalAccel]. */
@@ -94,7 +89,7 @@ class CamTransmitLoop @Inject constructor(
* denser updates through the maneuver, not just at the instant it was detected.
*/
fun onDetectedEvent() {
elevatedUntilMs = nowMs() + ELEVATED_HOLD_MS
elevatedUntilMs = System.currentTimeMillis() + ELEVATED_HOLD_MS
}
/**
@@ -123,15 +118,7 @@ class CamTransmitLoop @Inject constructor(
private suspend fun runTransmitLoop() = coroutineScope {
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
yawRate.reset()
launch {
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch {
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
}
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
launch { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
launch {
obuHardwarePrefs.outgoingMessageFlow.collect {
@@ -156,23 +143,25 @@ class CamTransmitLoop @Inject constructor(
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
// rotation fall cleanly between two frames instead of inside one.
val pseudonym = pseudonymManager.current()
val fix = onAirFix(gnss)
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the
// outgoing CAM is: acceleration below still differences wall-clock samples.
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
val bytes = codec.encodeCam(cam)
esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes,
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
}
private suspend fun sendVamIfDue(gnss: GnssReading) {
val now = nowMs()
val now = System.currentTimeMillis()
val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude,
gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble())
if (!vamRules.due(now, kinematics)) return
val pseudonym = pseudonymManager.current()
val fix = onAirFix(gnss)
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
// The CAM view of this fix is built only for its position vector, so the GN header of a VAM
// follows exactly the rules a CAM's does. It is not transmitted.
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
val withLowFrequency = vamRules.includeLowFrequency(now)
val bytes = VamUperCodec.encode(VamContent(
stationId = pseudonym.stationId,
@@ -209,31 +198,15 @@ class CamTransmitLoop @Inject constructor(
previousGnss = gnss
if (prev == null) return null
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble()
return dv / dtSec
}
/**
* [gnss] stamped with the GNSS time of the fix itself, for what goes on air: the fix's
* monotonic stamp moved onto GNSS time ([GnssTimeSource.atElapsedRealtime]). Neither the
* phone's clock setting nor a step of it between the fix and now can reach the result.
*/
private fun onAirFix(gnss: GnssReading): GnssReading =
gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos))
private fun currentYawRateDps(): Double? = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos())
/**
* The clock for this loop's own intervals (elevated-rate hold, VAM generation rules). Monotonic,
* so a phone clock that is set back cannot hold transmission off until it catches up again.
*/
private fun nowMs(): Long = SystemClock.elapsedRealtime()
private fun currentRateHz(gnss: GnssReading?): Double {
val now = nowMs()
val now = System.currentTimeMillis()
val inGeofence = gnss != null && config.geofences.any { fence ->
GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM
}
@@ -15,7 +15,6 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.GpsFixed
import androidx.compose.material.icons.filled.GpsOff
import androidx.compose.material.icons.filled.Sensors
@@ -39,10 +38,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -61,9 +58,6 @@ fun StatusTopBar(
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
esp32Bluetooth: Boolean = false,
/** The connected ESP32-C5 reports a low cell (amber) or a critical one (red). */
obuBatteryLow: Boolean = false,
obuBatteryCritical: Boolean = false,
) {
TopAppBar(
title = {
@@ -103,17 +97,6 @@ fun StatusTopBar(
)
Spacer(Modifier.width(8.dp))
if (isEsp32 && (obuBatteryLow || obuBatteryCritical)) {
Icon(
imageVector = Icons.Default.BatteryAlert,
contentDescription = stringResource(
if (obuBatteryCritical) R.string.status_battery_critical else R.string.status_battery_low,
),
tint = if (obuBatteryCritical) ErrorRed else AmberAcquiring,
modifier = Modifier.size(20.dp),
)
Spacer(Modifier.width(8.dp))
}
ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
}
},
@@ -46,7 +46,7 @@ sealed class Screen(val route: String, val labelRes: Int) {
data object SettingsLanguage : Screen("settings/language", R.string.settings_language)
data object SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance)
data object SettingsSensors : Screen("settings/sensors", R.string.settings_sensors)
data object SettingsRide : Screen("settings/ride", R.string.settings_ride)
data object SettingsUnits : Screen("settings/units", R.string.settings_units)
data object SettingsConnection : Screen("settings/connection", R.string.settings_connection)
data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts)
@@ -15,8 +15,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.BatteryFull
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material.icons.filled.Usb
@@ -315,39 +313,6 @@ fun ConnectionSetupScreen(
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
// The OBU's own cell (XIAO ESP32-C5 on its battery); absent from older firmware.
s.batteryPercent?.let { percent ->
val batteryColor = when {
s.batteryCritical -> Color(0xFFFF5252)
s.batteryLow -> UsbAmber
else -> MaterialTheme.colorScheme.onSurfaceVariant
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Icon(
if (s.batteryLow || s.batteryCritical) Icons.Default.BatteryAlert else Icons.Default.BatteryFull,
null,
tint = batteryColor,
modifier = Modifier.size(14.dp),
)
Text(
stringResource(R.string.conn_esp32_battery, s.batteryMv / 1000.0, percent),
style = MaterialTheme.typography.bodySmall,
color = batteryColor,
)
}
if (s.batteryLow || s.batteryCritical) {
Text(
stringResource(
if (s.batteryCritical) R.string.conn_esp32_battery_critical else R.string.conn_esp32_battery_low,
),
style = MaterialTheme.typography.bodySmall,
color = batteryColor,
)
}
}
}
}
@@ -65,10 +65,7 @@ import com.hawhamburg.micr0bu.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.denm.DenmParser
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
import com.hawhamburg.micr0bu.domain.spat.SignalMovement
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.Turn
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
import kotlinx.coroutines.delay
@@ -88,7 +85,7 @@ fun DashboardScreen(
obuStationTypeWarning: Boolean = false,
obuStationType: Int? = null,
hazards: List<DenmEvent> = emptyList(),
signals: List<TrafficLight> = emptyList(),
signals: List<SpatIntersection> = emptyList(),
ownPosition: Cam? = null,
onNavigateToConnection: () -> Unit,
onNavigateToSensors: () -> Unit,
@@ -412,18 +409,17 @@ fun DashboardScreen(
)
}
// The intersection whose ingress lane the rider is on (MAPEM geometry plus position and
// heading) comes first, nearest stop line first. Otherwise - no MAPEM heard, or not on one
// of its lanes - the one changing soonest, which is the one a rider approaching a junction
// most likely needs.
// Signals cannot be ranked by distance: SPATEM carries no position at all. The geometry
// that would place an intersection lives in MAPEM, which nothing on the air is currently
// sending. So the one shown is the one changing soonest, which is in any case the one a
// rider approaching a junction needs to see.
val nextSignal = remember(signals) {
val now = System.currentTimeMillis()
signals.filter { it.ownApproach != null }.minByOrNull { it.ownApproach!!.distanceToStopLineM }
?: signals.minByOrNull { it.signal?.secondsToNextChange(now) ?: Double.MAX_VALUE }
signals.minByOrNull { it.secondsToNextChange(now) ?: Double.MAX_VALUE }
}
nextSignal?.let { light ->
nextSignal?.let { signal ->
SignalCard(
light = light,
signal = signal,
additionalCount = signals.size - 1,
onClick = onNavigateToV2x,
)
@@ -642,16 +638,16 @@ private fun HazardCard(
}
/**
* The intersection that matters most: the one whose lane the rider is on, else the one changing
* soonest. With MAPEM geometry the card names the intersection and, once the rider is on one of
* its ingress lanes, shows that lane's lights - one chip per signal group, with the turns it
* controls - and the distance to the stop line. Without it, signal groups are bare numbers,
* since anything friendlier would claim knowledge that is not there.
* The signalised intersection changing soonest: its leading phase with a countdown, then every
* signal group as a coloured chip.
*
* Signal groups are bare numbers because that is all the app knows. Calling one "your lane" needs
* MAPEM geometry, and a friendlier label would claim knowledge that is not there.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SignalCard(
light: TrafficLight,
signal: SpatIntersection,
additionalCount: Int,
onClick: () -> Unit,
) {
@@ -666,28 +662,16 @@ private fun SignalCard(
}
}
val now = nowMs.longValue
val signal = light.signal ?: return
val own = light.ownApproach
// The rider's own light: the straight-ahead exit of their lane, else its first. Without a
// matched lane, the group changing soonest speaks for the intersection, as before.
val leading = own?.approach?.let { approach ->
(approach.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: approach.exits.firstOrNull())?.movement
} ?: signal.state.movements.minByOrNull { movement ->
val leading = signal.state.movements.minByOrNull { movement ->
movement.current?.secondsUntil(now)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
}
val phase = leading?.current?.phase
val tint = phaseTint(phase)
val countdown = leading?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
// One chip per signal group: the rider's lane's groups with their turn arrows, or every group.
val chips: List<Pair<String, SignalMovement?>> = own?.approach?.byGroup?.map { (_, exits) ->
exits.joinToString("") { it.turn.arrow() } to exits.first().movement
} ?: signal.state.movements.map { stringResource(R.string.v2x_spat_group, it.signalGroup) to it }
val hiddenGroups = chips.size - DASH_MAX_SIGNAL_GROUPS
val hiddenGroups = signal.state.movements.size - DASH_MAX_SIGNAL_GROUPS
val footer = listOfNotNull(
if (light.revisionMismatch) stringResource(R.string.dash_signal_map_outdated) else null,
if (hiddenGroups > 0) stringResource(R.string.dash_more_count, hiddenGroups) else null,
if (additionalCount > 0) stringResource(R.string.dash_signal_more, additionalCount) else null,
).joinToString(" · ")
@@ -706,23 +690,11 @@ private fun SignalCard(
Icon(Icons.Default.Traffic, null, tint = tint, modifier = Modifier.size(28.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
light.name ?: stringResource(R.string.dash_signal_title, light.key),
stringResource(R.string.dash_signal_title, signal.state.key),
style = MaterialTheme.typography.labelLarge,
color = tint,
fontWeight = FontWeight.SemiBold,
)
if (own != null) {
Text(
stringResource(
R.string.dash_signal_own_approach,
own.approach.lane.name
?: stringResource(R.string.v2x_lane_fallback, own.approach.lane.laneId),
own.distanceToStopLineM,
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
text = countdown
?.let { stringResource(R.string.dash_signal_countdown, phaseLabel(phase), it) }
@@ -735,12 +707,12 @@ private fun SignalCard(
// Wraps rather than scrolls: a horizontal scroller inside a scrolling dashboard
// is awkward to drive one-handed, and the chip row is short by construction.
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
chips.take(DASH_MAX_SIGNAL_GROUPS).forEach { (label, movement) ->
val groupTint = phaseTint(movement?.current?.phase)
signal.state.movements.take(DASH_MAX_SIGNAL_GROUPS).forEach { movement ->
val groupTint = phaseTint(movement.current?.phase)
val groupCountdown =
movement?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
movement.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
Text(
text = label +
text = stringResource(R.string.v2x_spat_group, movement.signalGroup) +
(groupCountdown?.let { " " + stringResource(R.string.v2x_spat_countdown, it) } ?: ""),
style = MaterialTheme.typography.bodySmall,
fontFamily = FontFamily.Monospace,
@@ -767,15 +739,6 @@ private fun SignalCard(
}
}
/** An arrow for a turn, as signs show it. */
private fun Turn.arrow(): String = when (this) {
Turn.STRAIGHT -> "↑"
Turn.LEFT -> "←"
Turn.RIGHT -> "→"
Turn.U_TURN -> "↶"
Turn.UNKNOWN -> "?"
}
/** Traffic-light colour for a phase: go is green, stop is red, anything in between is amber. */
@Composable
private fun phaseTint(phase: SignalPhase?): Color = when {
@@ -4,7 +4,6 @@ import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -48,11 +47,9 @@ import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttPrefs
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionConfig
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -71,7 +68,7 @@ fun SettingsScreen(
onOpenLanguage: () -> Unit,
onOpenAppearance: () -> Unit,
onOpenSensors: () -> Unit,
onOpenRide: () -> Unit,
onOpenUnits: () -> Unit,
onOpenConnection: () -> Unit,
onOpenMqtt: () -> Unit,
onOpenUseCaseAlerts: () -> Unit,
@@ -102,7 +99,7 @@ fun SettingsScreen(
RowDivider()
MenuRow(stringResource(R.string.settings_sensors), onOpenSensors)
RowDivider()
MenuRow(stringResource(R.string.settings_ride), onOpenRide)
MenuRow(stringResource(R.string.settings_units), onOpenUnits)
RowDivider()
MenuRow(stringResource(R.string.settings_connection), onOpenConnection)
RowDivider()
@@ -174,8 +171,6 @@ fun ConnectionSettingsScreen(
onEsp32TransportChange: (Esp32Transport) -> Unit = {},
outgoingMessage: OutgoingMessage = OutgoingMessage.CAM,
onOutgoingMessageChange: (OutgoingMessage) -> Unit = {},
esp32RxPath: Esp32RxPath = Esp32RxPath.V2X_RX,
onEsp32RxPathChange: (Esp32RxPath) -> Unit = {},
signOutgoing: Boolean = true,
onSignOutgoingChange: (Boolean) -> Unit = {},
onBack: () -> Unit,
@@ -253,21 +248,6 @@ fun ConnectionSettingsScreen(
onSecond = { onOutgoingMessageChange(OutgoingMessage.VAM) },
)
Divider()
TwoWayChoice(
label = stringResource(R.string.settings_esp32_rx_path),
first = stringResource(R.string.settings_esp32_rx_v2x),
second = stringResource(R.string.settings_esp32_rx_raw),
firstSelected = esp32RxPath == Esp32RxPath.V2X_RX,
onFirst = { onEsp32RxPathChange(Esp32RxPath.V2X_RX) },
onSecond = { onEsp32RxPathChange(Esp32RxPath.RAW_FRAME) },
)
Text(
stringResource(if (esp32RxPath == Esp32RxPath.V2X_RX) R.string.settings_esp32_rx_v2x_note else R.string.settings_esp32_rx_raw_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
Divider()
SettingToggleRow(
label = stringResource(R.string.settings_esp32_sign),
checked = signOutgoing,
@@ -387,51 +367,19 @@ fun SensorsSettingsScreen(
}
}
/**
* Settings > Ride. Replaced the old Units screen: the app is metric throughout, so that switch had
* nothing to switch. Where the phone rides, and whether the V2X data logger also records the motion
* sensors and raw GPS for sensor fusion (`docs/07-sensor-fusion-logging.md`).
*/
@Composable
fun RideSettingsScreen(
phoneMount: PhoneMount,
onPhoneMount: (PhoneMount) -> Unit,
fusionLogging: Boolean,
onFusionLogging: (Boolean) -> Unit,
fun UnitsSettingsScreen(
useMetric: Boolean,
onUseMetric: (Boolean) -> Unit,
onBack: () -> Unit,
) {
SubScreen(stringResource(R.string.settings_ride), onBack) {
Text(
stringResource(R.string.settings_ride_mount_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SubScreen(stringResource(R.string.settings_units), onBack) {
SectionCard {
Choice(
label = stringResource(R.string.settings_ride_mount),
options = PhoneMount.entries.map { it to stringResource(phoneMountLabel(it)) },
selected = phoneMount,
onSelect = onPhoneMount,
)
}
Text(
stringResource(R.string.settings_ride_fusion_log_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard {
SettingToggleRow(stringResource(R.string.settings_ride_fusion_log), fusionLogging, onFusionLogging)
SettingToggleRow(stringResource(R.string.settings_metric), useMetric, onUseMetric)
}
}
}
/** The display name of a [PhoneMount]; also used by the V2X logger screen. */
internal fun phoneMountLabel(mount: PhoneMount): Int = when (mount) {
PhoneMount.HANDLEBAR -> R.string.settings_ride_mount_handlebar
PhoneMount.BAG -> R.string.settings_ride_mount_bag
PhoneMount.POCKET -> R.string.settings_ride_mount_pocket
}
@Composable
fun MqttSettingsScreen(
mqttPrefs: MqttPrefs,
@@ -751,40 +699,6 @@ private fun TwoWayChoice(
}
}
/** [TwoWayChoice] for any number of options: a labelled row of outlined buttons, the selected one filled. */
@Composable
private fun <T> Choice(
label: String,
options: List<Pair<T, String>>,
selected: T,
onSelect: (T) -> Unit,
) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
Spacer(Modifier.height(6.dp))
Row(
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
for ((value, text) in options) {
val isSelected = value == selected
OutlinedButton(
onClick = { onSelect(value) },
modifier = Modifier.weight(1f),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
),
) { Text(text, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, maxLines = 1) }
}
}
}
@Composable
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@@ -31,11 +31,7 @@ import androidx.lifecycle.compose.LocalLifecycleOwner
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.map.lanePoints
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.Turn
import com.hawhamburg.micr0bu.domain.usecase.AlertLevel
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import org.osmdroid.config.Configuration
@@ -44,7 +40,6 @@ import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Polyline
/**
* V2X Monitor live map (Phase 03, Section 13) — the map body behind [V2xMapScreen], plotting the
@@ -54,9 +49,7 @@ import org.osmdroid.views.overlay.Polyline
* Marker vocabulary, one shape per message type so the map reads without a legend:
* - CAM — teardrop pin, tinted by that station's most severe active alert level
* - DENM — hazard warning triangle
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit. With the
* intersection's MAPEM it stands on the MAPEM's reference point and its lanes are drawn: each
* ingress lane in the colour of its straight-ahead light (else its first), egress lanes grey
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit
*
* Unlike [MapScreen] this has no phone-GNSS-only fallback: [own] always reflects whichever ego
* source [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository] currently trusts (obu_gnss /
@@ -76,7 +69,7 @@ fun V2xLiveMapView(
remotes: Map<Long, Cam>,
alerts: List<UseCaseAlert>,
denms: List<DenmEvent> = emptyList(),
lights: List<TrafficLight> = emptyList(),
spats: List<SpatIntersection> = emptyList(),
followOwn: Boolean = true,
onUserPanned: () -> Unit = {},
modifier: Modifier = Modifier,
@@ -99,7 +92,6 @@ fun V2xLiveMapView(
// tint applied would recolour every pin on the map.
val icons = remember(context) { MapIcons(context) }
val markers = remember { mutableMapOf<String, Marker>() }
val lanes = remember { mutableMapOf<String, Polyline>() }
val mapViewRef = remember { mutableStateOf<MapView?>(null) }
val lifecycleOwner = LocalLifecycleOwner.current
@@ -151,17 +143,14 @@ fun V2xLiveMapView(
update = { mv ->
val now = System.currentTimeMillis()
// Intersections we can actually place: at the MAPEM's reference point when its MAPEM
// has been heard, else at the sending RSU's own CAM position (SPATEM has no geometry).
val locatedSpats = lights.mapNotNull { light ->
val spat = light.signal ?: return@mapNotNull null
val at = light.geometry?.let { GeoPoint(it.refLatitude, it.refLongitude) }
?: remotes[spat.stationId]?.let { rsu -> GeoPoint(rsu.latitude, rsu.longitude) }
at?.let { Triple(light, spat, it) }
// Intersections we can actually place: SPATEM carries signal state but no geometry
// (that is MAPEM's job), so the only position available is the sending RSU's own CAM.
val locatedSpats = spats.mapNotNull { spat ->
remotes[spat.stationId]?.let { rsu -> spat to rsu }
}
// An RSU drawn as a traffic light must not also be drawn as a CAM pin underneath it:
// two markers on one point, the lower one unreachable.
val spatStationIds = locatedSpats.map { (_, spat, _) -> spat.stationId }.toSet()
val spatStationIds = locatedSpats.map { (spat, _) -> spat.stationId }.toSet()
val live = mutableSetOf<String>()
@@ -212,38 +201,13 @@ fun V2xLiveMapView(
}
}
val liveLanes = mutableSetOf<String>()
lights.forEach { light ->
val geometry = light.geometry ?: return@forEach
val signalled = light.approaches.associateBy { it.lane.laneId }
geometry.lanes.forEach lane@{ lane ->
val points = geometry.lanePoints(lane)
if (points.size < 2) return@lane
val key = "${light.key}#${lane.laneId}"
liveLanes += key
val approach = signalled[lane.laneId]
val exit = approach?.let { a -> a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull() }
val own = light.ownApproach?.approach?.lane?.laneId == lane.laneId
lanes.getOrPut(key) { Polyline(mv) }.apply {
setPoints(points.map { GeoPoint(it.latitude, it.longitude) })
outlinePaint.color = if (approach == null) LANE_GREY else exit?.movement?.current?.phase.toLaneColor()
outlinePaint.strokeWidth = if (approach == null) 4f else if (own) 14f else 9f
title = lane.name ?: context.getString(R.string.v2x_lane_fallback, lane.laneId)
}
}
}
lanes.keys.retainAll { it in liveLanes }
locatedSpats.forEach { (light, spat, at) ->
// On the rider's lane, that lane's light speaks for the intersection.
val phase = light.ownApproach?.approach?.let { a ->
(a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull())?.movement?.current?.phase
}?.toLamp() ?: spat.leadingPhase(now)
locatedSpats.forEach { (spat, rsu) ->
val phase = spat.leadingPhase(now)
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
position = at
position = GeoPoint(rsu.latitude, rsu.longitude)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = icons.signal(phase)
title = light.name ?: context.getString(
title = context.getString(
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
)
snippet = spat.state.movements.joinToString(" · ") { movement ->
@@ -261,8 +225,6 @@ fun V2xLiveMapView(
(key in live).also { kept -> if (!kept) markers[key]?.closeInfoWindow() }
}
mv.overlays.clear()
// Lanes first, so every marker draws over them.
lanes.values.forEach { mv.overlays.add(it) }
markers.entries
.sortedBy { (key, _) -> key.drawOrder() }
.forEach { (_, marker) -> mv.overlays.add(marker) }
@@ -293,7 +255,6 @@ fun V2xLiveMapView(
// guarantees no further update after it.
onRelease = {
markers.clear()
lanes.clear()
it.onDetach()
},
modifier = modifier.fillMaxSize(),
@@ -367,35 +328,25 @@ private enum class SignalLamp(val drawableRes: Int) {
/**
* The lamp to light for this intersection.
*
* Used when the rider is not on one of the intersection's ingress lanes (or no MAPEM is known):
* then no signal group is theirs, and this follows the rule the Dashboard's SignalCard uses — the
* group changing soonest speaks for the intersection — so it reads the same in both places.
* Without MAPEM there is no lane geometry, so there is no way to know which of an intersection's
* signal groups applies to the rider's own approach. This follows the rule the Dashboard's
* SignalCard already uses — the group changing soonest speaks for the intersection — so the same
* intersection reads the same way in both places rather than inventing a second convention.
*/
private fun SpatIntersection.leadingPhase(nowMs: Long): SignalLamp {
val leading = state.movements.minByOrNull { movement ->
movement.current?.secondsUntil(nowMs)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
}
return leading?.current?.phase.toLamp()
val phase = leading?.current?.phase
return when {
phase == null -> SignalLamp.DARK
phase.isGo -> SignalLamp.GREEN
phase.isStop -> SignalLamp.RED
phase.isTransition -> SignalLamp.AMBER
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
}
}
private fun SignalPhase?.toLamp(): SignalLamp = when {
this == null -> SignalLamp.DARK
isGo -> SignalLamp.GREEN
isStop -> SignalLamp.RED
isTransition -> SignalLamp.AMBER
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
}
/** Lane colour on the map: the traffic-light colours, with a lane whose group is silent dark grey. */
private fun SignalPhase?.toLaneColor(): Int = when (toLamp()) {
SignalLamp.GREEN -> 0xFF4CAF50.toInt()
SignalLamp.RED -> 0xFFE53935.toInt()
SignalLamp.AMBER -> 0xFFFFC107.toInt()
SignalLamp.DARK -> 0xFF546E7A.toInt()
}
private const val LANE_GREY = 0x9978909C.toInt()
/**
* Marker tint per severity, matching [UseCaseAlertPanel]'s colours so the same station reads the
* same way in both places. Stations with no active alert stay neutral grey-blue rather than green:
@@ -150,21 +150,6 @@ fun V2xLogSettingsScreen(
stringResource(R.string.v2xlog_obu_gnss),
if (isEsp32) stringResource(R.string.v2xlog_not_available) else fixAge(state.obuFixAgeMs),
)
Divider()
DisabledRow(
stringResource(R.string.v2xlog_fusion),
if (state.fusionLogging && state.phoneMount != null) {
stringResource(R.string.v2xlog_fusion_on, stringResource(phoneMountLabel(state.phoneMount)))
} else {
stringResource(R.string.v2xlog_fusion_off)
},
)
if (state.fusionLogging) {
Divider()
DisabledRow(stringResource(R.string.v2xlog_imu), state.imuSamples.toString())
Divider()
DisabledRow(stringResource(R.string.v2xlog_phone_gps), fixAge(state.phoneGpsFixAgeMs))
}
}
if (state.total == 0) {
Text(
@@ -61,17 +61,17 @@ fun V2xMapScreen(
val stations by viewModel.stationsInRange.collectAsState()
val alerts by viewModel.useCaseAlerts.collectAsState()
val denms by viewModel.denmEvents.collectAsState()
val lights by viewModel.trafficLights.collectAsState()
val spats by viewModel.spatIntersections.collectAsState()
// Follow is on until the rider touches the map, and comes back when they ask for it. Without
// the hand-over, every incoming CAM would drag the viewport back to the ego position and the
// map could not be panned at all while traffic is flowing.
var followOwn by remember { mutableStateOf(true) }
// SPATEM carries no geometry of its own, so an intersection can only be placed if its MAPEM or
// its RSU's CAM has been heard too. Saying so is better than silently dropping it: "the map shows two
// SPATEM carries no geometry of its own, so an intersection can only be placed if its RSU has
// also been heard over CAM. Saying so is better than silently dropping it: "the map shows two
// of the three lights I can see in the list" is otherwise an unexplained discrepancy.
val unlocatedSpats = lights.count { it.geometry == null && it.signal?.stationId !in stations.keys }
val unlocatedSpats = spats.count { it.stationId !in stations.keys }
Box(modifier = Modifier.fillMaxSize()) {
V2xLiveMapView(
@@ -79,7 +79,7 @@ fun V2xMapScreen(
remotes = stations,
alerts = alerts,
denms = denms,
lights = lights,
spats = spats,
followOwn = followOwn,
onUserPanned = { followOwn = false },
modifier = Modifier.fillMaxSize(),
@@ -125,7 +125,7 @@ fun V2xMapScreen(
MapCount(
icon = Icons.Default.Traffic,
tint = SignalGreenDot,
count = lights.size,
count = spats.size,
label = stringResource(R.string.v2x_map_legend_spat),
)
}
@@ -15,17 +15,12 @@ import com.hawhamburg.micr0bu.data.transport.TransportType
import com.hawhamburg.micr0bu.data.transport.UsbNetworkDetector
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.data.transport.StationStatus
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.denm.DenmParser
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
import com.hawhamburg.micr0bu.domain.denm.DenmUseCase
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
@@ -118,13 +113,6 @@ class MqttViewModel @Inject constructor(
viewModelScope.launch { obuHardwarePrefs.setOutgoingMessage(message) }
}
val esp32RxPath: StateFlow<Esp32RxPath> = obuHardwarePrefs.esp32RxPathFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
fun setEsp32RxPath(path: Esp32RxPath) {
viewModelScope.launch { obuHardwarePrefs.setEsp32RxPath(path) }
}
val signOutgoing: StateFlow<Boolean> = obuHardwarePrefs.signOutgoingFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
@@ -281,49 +269,6 @@ class MqttViewModel @Inject constructor(
.sortedByDescending { it.timestamp }
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/**
* Intersection geometry heard over MAPEM, oldest first. Kept per intersection AND revision:
* two revisions of one intersection can be on air at once, and a SPATEM's signal groups mean
* whatever its own revision's MAPEM says ([TrafficLights.pickGeometry]).
*/
private val mapGeometries: StateFlow<List<IntersectionGeometry>> = combine(
camUseCaseRepository.decodedMap
.runningFold(emptyMap<String, Pair<IntersectionGeometry, Long>>()) { acc, map ->
acc + map.intersections.associate { "${it.key}#${it.revision}" to (it to map.timestamp) }
},
tickerFlow(MAP_EXPIRY_TICK_MS),
) { byKey, _ ->
val now = System.currentTimeMillis()
byKey.values
.filter { (_, heardAt) -> now - heardAt <= MAP_TTL_MS }
.sortedBy { (_, heardAt) -> heardAt }
.map { (geometry, _) -> geometry }
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/**
* [spatIntersections] with each SPATEM's signal groups placed on its MAPEM's lanes, and the
* rider's own approach picked from their position and heading. The MAPEM is one heard on air or
* one the app ships with ([TrafficLights.geometryFor]). An intersection with neither is still
* listed, with no lanes: its signal groups stay bare numbers.
*/
val trafficLights: StateFlow<List<TrafficLight>> = combine(
spatIntersections,
mapGeometries,
camUseCaseRepository.storedMaps,
camUseCaseRepository.ownPosition,
) { spats, live, stored, own ->
val position = own?.let { MapPoint(it.latitude, it.longitude) }
spats.map { spat ->
TrafficLights.join(
signal = spat,
geometry = TrafficLights.geometryFor(spat.key, spat.state.revision, live, stored, position),
own = position,
ownHeadingDeg = own?.headingDeg,
ownSpeedMps = own?.speedMps,
)
}
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/** Emits immediately, then every [periodMs], purely to re-trigger a time-dependent combine. */
private fun tickerFlow(periodMs: Long): Flow<Long> = flow {
while (true) {
@@ -354,13 +299,6 @@ class MqttViewModel @Inject constructor(
const val SPAT_TTL_MS = 15_000L
const val SPAT_EXPIRY_TICK_MS = 2_000L
/**
* MAPEM repeats at about 1 Hz and its geometry is static, so a minute of silence is generous;
* a light is only ever shown while its SPATEM is live anyway.
*/
const val MAP_TTL_MS = 60_000L
const val MAP_EXPIRY_TICK_MS = 5_000L
/** RSU CAMs arrive at ~2 Hz, same as any other station, so the same window applies. */
const val RSU_TTL_MS = 15_000L
const val RSU_EXPIRY_TICK_MS = 2_000L
@@ -1,33 +0,0 @@
package com.hawhamburg.micr0bu.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Backs Settings > Ride. */
@HiltViewModel
class RideSettingsViewModel @Inject constructor(
private val prefs: RidePreferences,
) : ViewModel() {
val phoneMount: StateFlow<PhoneMount> =
prefs.phoneMountFlow.stateIn(viewModelScope, SharingStarted.Eagerly, PhoneMount.DEFAULT)
val fusionLogging: StateFlow<Boolean> =
prefs.fusionLoggingFlow.stateIn(viewModelScope, SharingStarted.Eagerly, false)
fun setPhoneMount(mount: PhoneMount) {
viewModelScope.launch { prefs.setPhoneMount(mount) }
}
fun setFusionLogging(enabled: Boolean) {
viewModelScope.launch { prefs.setFusionLogging(enabled) }
}
}
@@ -65,6 +65,7 @@ data class SensorUiState(
val barometerEnabled: Boolean = true,
val gnssEnabled: Boolean = true,
val developerMode: Boolean = true,
val useMetric: Boolean = true,
val darkTheme: Boolean = true,
)
@@ -294,5 +295,6 @@ class SensorViewModel(application: Application) : AndroidViewModel(application)
if (!v) _state.value = _state.value.copy(gnss = null)
}
fun setDeveloperMode(v: Boolean) { _state.value = _state.value.copy(developerMode = v) }
fun setUseMetric(v: Boolean) { _state.value = _state.value.copy(useMetric = v) }
fun setDarkTheme(v: Boolean) { _state.value = _state.value.copy(darkTheme = v) }
}
+6 -30
View File
@@ -44,9 +44,6 @@
<string name="dash_signal_phase_dark">Dunkel</string>
<string name="dash_signal_phase_unknown">Unbekannt</string>
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
<string name="dash_signal_own_approach">%1$s · %2$.0f m bis zur Haltelinie</string>
<string name="dash_signal_map_outdated">Fahrstreifenkarte veraltet</string>
<string name="v2x_lane_fallback">Fahrstreifen %1$d</string>
<string name="stat_pressure">Luftdruck</string>
<string name="stat_altitude">Höhe</string>
<string name="stat_heading">Richtung</string>
@@ -78,9 +75,9 @@
<string name="conn_bluetooth">Bluetooth</string>
<string name="conn_bluetooth_phase3">Bluetooth</string>
<string name="conn_bluetooth_phase3_desc">Bluetooth-Verbindung ist für Phase 03 geplant und noch nicht implementiert.</string>
<string name="conn_esp32_title">ESP32-C5</string>
<string name="conn_esp32_title">ESP32-C5 (USB Seriell)</string>
<string name="conn_esp32_phase3_desc">Die USB-Seriell-Verbindung zum ESP32-C5 ist für Phase 03 vorgesehen, aber noch nicht funktionsfähig - dafür muss zuerst das ESP32-Firmware-Protokoll nach Kotlin übersetzt werden.</string>
<string name="conn_esp32_state_disconnected">Nicht verbunden - Verbinden antippen (USB-C-Verbindung: ESP32-C5 zuerst an den nativen USB-C-Port anschließen).</string>
<string name="conn_esp32_state_disconnected">Nicht verbunden - ESP32-C5 an den nativen USB-C-Port anschließen und Verbinden antippen.</string>
<string name="conn_esp32_state_device_attached">Gerät erkannt, wird geöffnet…</string>
<string name="conn_esp32_state_permission_requested">Warte auf USB-Berechtigung…</string>
<string name="conn_esp32_state_connected">Verbunden</string>
@@ -169,14 +166,8 @@
<string name="settings_gyro">Gyroskop</string>
<string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_ride">Fahrt</string>
<string name="settings_ride_mount">Position des Telefons</string>
<string name="settings_ride_mount_handlebar">Lenker</string>
<string name="settings_ride_mount_bag">Tasche</string>
<string name="settings_ride_mount_pocket">Hosentasche</string>
<string name="settings_ride_mount_desc">Wo das Telefon mitfährt: in einer Lenkerhalterung, in einer Tasche am Fahrrad oder in einer Hosentasche bzw. einem Rucksack. Die Sensorfusion wertet die Bewegungssensoren je nach Position anders aus, und jedes V2X-Log hält sie fest.</string>
<string name="settings_ride_fusion_log">Bewegungssensoren aufzeichnen</string>
<string name="settings_ride_fusion_log_desc">Für Testfahrten zur Sensorfusion: Der V2X-Datenlogger zeichnet zusätzlich Beschleunigungssensor, Gyroskop und Schwerkraft mit 100 Hz auf, sowie rohe GPS-Positionen neben der fusionierten Position. Das sind einige zehn MB pro Stunde.</string>
<string name="settings_units">Einheiten</string>
<string name="settings_metric">Metrisch (m, km/h, hPa)</string>
<string name="settings_mqtt_section">MQTT-Broker</string>
<string name="settings_broker_ip">Broker-IP</string>
<string name="settings_port">Port</string>
@@ -329,12 +320,7 @@
<string name="v2x_spat_countdown">%1$.0f s</string>
<string name="settings_esp32_link">ESP32-C5-Verbindung</string>
<string name="settings_esp32_link_ble">Bluetooth</string>
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, zuerst das richtige in den Android-Bluetooth-Einstellungen koppeln. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
<string name="settings_esp32_rx_path">Empfangspfad</string>
<string name="settings_esp32_rx_v2x">V2X_RX</string>
<string name="settings_esp32_rx_raw">Rohframes</string>
<string name="settings_esp32_rx_v2x_note">Die Platine entpackt jedes empfangene Frame und sendet die fertige Nachricht, signiert oder nicht (MicrOBU-Erweiterung, bis 494 Byte). Klein und immer aktiv.</string>
<string name="settings_esp32_rx_raw_note">Debug: Die Platine sendet das ganze Funkframe (RAW_FRAME aus der Spezifikation, bei Bedarf fragmentiert) und die App entpackt es. Keine 494-Byte-Grenze, aber Frames können bei ausgelastetem Link verloren gehen und es braucht mehr Bandbreite, besonders über Bluetooth.</string>
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Die Platine wirbt nur, solange ihr USB-C-Port nicht benutzt wird. BLE teilt sich das Funk-Frontend mit ITS-G5; der Einfluss auf den 5,9-GHz-Empfang ist noch nicht gemessen.</string>
<string name="settings_esp32_message">Senden während der Aufzeichnung</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
@@ -344,18 +330,13 @@
<string name="conn_esp32_via_ble">über Bluetooth (Passkey 123456 beim ersten Koppeln)</string>
<string name="conn_esp32_cancel">Abbrechen</string>
<string name="conn_esp32_signing">Signieren %1$s · Tickets %2$d · signiert %3$d · abgelehnt %4$d · gesendet %5$d</string>
<string name="conn_esp32_battery">Akku %1$.2f V · etwa %2$d %%</string>
<string name="conn_esp32_battery_low">Akku schwach: OBU bald laden.</string>
<string name="conn_esp32_battery_critical">Akku kritisch: Das OBU schaltet sich ab, sofern es nicht per USB versorgt wird.</string>
<string name="status_battery_low">OBU-Akku schwach</string>
<string name="status_battery_critical">OBU-Akku kritisch</string>
<string name="conn_esp32_signing_on">an</string>
<string name="conn_esp32_signing_off">aus</string>
<string name="v2xlog_title">V2X-Datenlogger</string>
<string name="v2xlog_desc">Zeichnet jede empfangene V2X-Nachricht (CAM, DENM, SPATEM, MAPEM, VAM) in einer Datenbankdatei auf, mit Zeitstempel, der GNSS-Position des Telefons und, wenn vorhanden, der GNSS-Position der OBU und der Signalstärke (RSSI).</string>
<string name="v2xlog_mode_esp32">ESP32-C5: protokolliert, was das Board über die Verbindung weiterleitet, mit RSSI. Das Board hat kein GNSS, daher gibt es keine OBU-Position.</string>
<string name="v2xlog_mode_cit">CiT One: protokolliert die MQTT-Topics. Die API liefert keine RSSI; die OBU-Position stammt aus v2x/rx/obu_gnss.</string>
<string name="v2xlog_esp32_firmware_note">Die Platine leitet CAM, DENM, SPATEM, MAPEM und VAM weiter. Auf dem Empfangspfad V2X_RX passt eine Nachricht über 494 Byte nicht in eine Link-Nachricht und wird verworfen; der Pfad Rohframes kennt diese Grenze nicht. Der Logger speichert auf beiden Pfaden die dekodierte Nachricht, nicht das Funkframe.</string>
<string name="v2xlog_esp32_firmware_note">Die aktuelle ESP32-C5-Firmware leitet nur CAM, DENM und SPATEM weiter; MAPEM und VAM erscheinen erst, wenn die Firmware sie annimmt.</string>
<string name="v2xlog_start">Aufzeichnung starten</string>
<string name="v2xlog_stop">Aufzeichnung beenden</string>
<string name="v2xlog_error">Aufzeichnung fehlgeschlagen: %1$s</string>
@@ -364,11 +345,6 @@
<string name="v2xlog_total_val">%1$d Nachrichten · %2$s</string>
<string name="v2xlog_phone_gnss">Telefon-GNSS</string>
<string name="v2xlog_obu_gnss">OBU-GNSS</string>
<string name="v2xlog_fusion">Daten für Sensorfusion</string>
<string name="v2xlog_fusion_off">aus (Einstellungen > Fahrt)</string>
<string name="v2xlog_fusion_on">an · Telefon: %1$s</string>
<string name="v2xlog_imu">Bewegungssensor-Messwerte</string>
<string name="v2xlog_phone_gps">Telefon-GPS (roh)</string>
<string name="v2xlog_fix_age">Fix vor %1$d s</string>
<string name="v2xlog_no_fix">kein Fix</string>
<string name="v2xlog_not_available">nicht verfügbar</string>
+6 -30
View File
@@ -45,9 +45,6 @@
<string name="dash_signal_phase_dark">Dark</string>
<string name="dash_signal_phase_unknown">Unknown</string>
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
<string name="dash_signal_own_approach">%1$s · %2$.0f m to the stop line</string>
<string name="dash_signal_map_outdated">Lane map out of date</string>
<string name="v2x_lane_fallback">Lane %1$d</string>
<string name="stat_pressure">Pressure</string>
<string name="stat_altitude">Altitude</string>
<string name="stat_heading">Heading</string>
@@ -79,9 +76,9 @@
<string name="conn_bluetooth">Bluetooth</string>
<string name="conn_bluetooth_phase3">Bluetooth</string>
<string name="conn_bluetooth_phase3_desc">Bluetooth connection is planned for Phase 03 and is not yet implemented.</string>
<string name="conn_esp32_title">ESP32-C5</string>
<string name="conn_esp32_title">ESP32-C5 (USB Serial)</string>
<string name="conn_esp32_phase3_desc">USB-serial connection to the ESP32-C5 is scaffolded for Phase 03 but not yet functional - it needs the ESP32 firmware protocol translated to Kotlin first.</string>
<string name="conn_esp32_state_disconnected">Not connected - tap Connect (USB-C link: plug the ESP32-C5 into the native USB-C port first).</string>
<string name="conn_esp32_state_disconnected">Not connected - plug the ESP32-C5 into the native USB-C port and tap Connect.</string>
<string name="conn_esp32_state_device_attached">Device detected, opening…</string>
<string name="conn_esp32_state_permission_requested">Waiting for USB permission…</string>
<string name="conn_esp32_state_connected">Connected</string>
@@ -170,14 +167,8 @@
<string name="settings_gyro">Gyroscope</string>
<string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_ride">Ride</string>
<string name="settings_ride_mount">Phone position</string>
<string name="settings_ride_mount_handlebar">Handlebar</string>
<string name="settings_ride_mount_bag">Bag</string>
<string name="settings_ride_mount_pocket">Pocket</string>
<string name="settings_ride_mount_desc">Where the phone rides: on a handlebar mount, in a bag on the bike, or in a pocket or backpack. Sensor fusion reads the motion sensors differently for each, and every V2X log records it.</string>
<string name="settings_ride_fusion_log">Record motion sensors</string>
<string name="settings_ride_fusion_log_desc">For sensor fusion test rides: the V2X data logger also records accelerometer, gyroscope and gravity at 100 Hz, and raw GPS fixes next to the fused location. Adds tens of MB per hour.</string>
<string name="settings_units">Units</string>
<string name="settings_metric">Metric (m, km/h, hPa)</string>
<string name="settings_mqtt_section">MQTT Broker</string>
<string name="settings_broker_ip">Broker IP</string>
<string name="settings_port">Port</string>
@@ -336,12 +327,7 @@
<string name="trip_review_title">Trip Review</string>
<string name="settings_esp32_link">ESP32-C5 link</string>
<string name="settings_esp32_link_ble">Bluetooth</string>
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. With several micrOBUs nearby, pair the right one in Android\'s Bluetooth settings first. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
<string name="settings_esp32_rx_path">Receive path</string>
<string name="settings_esp32_rx_v2x">V2X_RX</string>
<string name="settings_esp32_rx_raw">Raw frames</string>
<string name="settings_esp32_rx_v2x_note">The board unpacks every received frame and sends the finished message, signed or not (MicrOBU extension, up to 494 bytes). Small and always on.</string>
<string name="settings_esp32_rx_raw_note">Debug: the board sends the whole radio frame (the spec\'s RAW_FRAME, fragmented if large) and the app unpacks it. No 494-byte limit, but frames can be lost when the link is busy and it needs more bandwidth, especially over Bluetooth.</string>
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. The board only advertises while nothing uses its USB-C port. BLE shares the radio front end with ITS-G5; its effect on 5.9 GHz reception has not been measured yet.</string>
<string name="settings_esp32_message">Transmit while recording</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
@@ -351,18 +337,13 @@
<string name="conn_esp32_via_ble">via Bluetooth (passkey 123456 on first pairing)</string>
<string name="conn_esp32_cancel">Cancel</string>
<string name="conn_esp32_signing">Signing %1$s · tickets %2$d · signed %3$d · refused %4$d · on air %5$d</string>
<string name="conn_esp32_battery">Battery %1$.2f V · about %2$d %%</string>
<string name="conn_esp32_battery_low">Low battery: charge the OBU soon.</string>
<string name="conn_esp32_battery_critical">Battery critical: the OBU shuts down unless it stays on USB.</string>
<string name="status_battery_low">OBU battery low</string>
<string name="status_battery_critical">OBU battery critical</string>
<string name="conn_esp32_signing_on">on</string>
<string name="conn_esp32_signing_off">off</string>
<string name="v2xlog_title">V2X data logger</string>
<string name="v2xlog_desc">Records every V2X message received (CAM, DENM, SPATEM, MAPEM, VAM) into a database file, with a timestamp, the phone GNSS fix and, where available, the OBU GNSS fix and the signal strength (RSSI).</string>
<string name="v2xlog_mode_esp32">ESP32-C5: logging what the board forwards over the link, with RSSI. The board has no GNSS, so there is no OBU position.</string>
<string name="v2xlog_mode_cit">CiT One: logging the MQTT topics. The API carries no RSSI; the OBU position comes from v2x/rx/obu_gnss.</string>
<string name="v2xlog_esp32_firmware_note">The board forwards CAM, DENM, SPATEM, MAPEM and VAM. On the V2X_RX receive path a message over 494 bytes does not fit one link message and is dropped; the Raw frames path has no such limit. The logger stores the decoded message, not the radio frame, on either path.</string>
<string name="v2xlog_esp32_firmware_note">The current ESP32-C5 firmware forwards only CAM, DENM and SPATEM, so MAPEM and VAM appear only once the firmware accepts them.</string>
<string name="v2xlog_start">Start logging</string>
<string name="v2xlog_stop">Stop logging</string>
<string name="v2xlog_error">Logging failed: %1$s</string>
@@ -371,11 +352,6 @@
<string name="v2xlog_total_val">%1$d messages · %2$s</string>
<string name="v2xlog_phone_gnss">Phone GNSS</string>
<string name="v2xlog_obu_gnss">OBU GNSS</string>
<string name="v2xlog_fusion">Sensor fusion data</string>
<string name="v2xlog_fusion_off">off (Settings > Ride)</string>
<string name="v2xlog_fusion_on">on · phone on %1$s</string>
<string name="v2xlog_imu">Motion sensor samples</string>
<string name="v2xlog_phone_gps">Phone GPS (raw)</string>
<string name="v2xlog_fix_age">fix %1$d s ago</string>
<string name="v2xlog_no_fix">no fix</string>
<string name="v2xlog_not_available">not available</string>
@@ -31,12 +31,9 @@ class CamEncodeGoldenTest {
/**
* asn1tools-verified encoding of [referenceCam]. The trap this pins down: `YawRateConfidence`
* has nine enumerands (0..8), so it needs 4 bits and `unavailable` is 8 - not 3 bits and 7.
* generationDeltaTime 19080 is TimestampIts mod 65536 with the 5 leap seconds since 2004 (TAI,
* TS 102 894-2 V2.5.1); regenerated 2026-10 through asn1tools from the earlier UTC-based vector
* (14080), every other bit unchanged.
*/
private val expectedHex =
"0202000f423f4a88402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337feebfff6000000"
"0202000f423f3700402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337feebfff6000000"
private val referenceCam = Cam(
stationId = 999_999L,
@@ -61,29 +58,6 @@ class CamEncodeGoldenTest {
assertEquals(expectedHex, encoded)
}
/**
* [referenceCam] turning right at 12.34 deg/s, encoded by asn1tools with `yawRateValue` -1234:
* YawRateValue is positive to the LEFT (TS 102 894-2), while [Cam.yawRateDps] is positive
* clockwise. Only the yawRate bits differ from [expectedHex]. Generated 2026-11-18 by decoding
* [expectedHex] with asn1tools (cam_1_4_1 + cdd_1_3_1_1), setting the value, and re-encoding.
*/
private val rightTurnHex =
"0202000f423f4a88402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337fee9ecb2000000"
@Test
fun `a right turn goes on air as a negative YawRateValue`() {
val encoded = CamUperCodec.encode(referenceCam.copy(yawRateDps = 12.34))
.joinToString("") { "%02x".format(it) }
assertEquals(rightTurnHex, encoded)
}
@Test
fun `a negative YawRateValue from the air is a right turn`() {
val bytes = rightTurnHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
val cam = requireNotNull(CamUperCodec.decode(bytes, referenceCam.timestamp))
assertEquals(12.34, cam.yawRateDps!!, 1e-9)
}
@Test
fun `own decoder agrees with the encoder on every field it reads`() {
// Self-consistency is necessary but NOT sufficient - see the class KDoc. This guards the
@@ -104,7 +104,7 @@ class CamTxPvSerialTest {
assertTrue(pv.pai)
// The GN TST and the CAM's generationDeltaTime must follow one time rule.
assertEquals(ItsTime.timestampIts(cam.timestamp), pv.tstMs)
assertEquals(716_121_577_779L, pv.tstMs) // TAI: Unix ms - ITS epoch + 5 leap seconds
assertEquals(716_121_572_779L, pv.tstMs)
}
@Test
@@ -1,110 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.cam.CamParser
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.cam.StationType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The two CiT One JSON parsers against payloads shaped exactly like the ones the CiT One really
* sends (keys, nesting and types copied from the logged runs, values changed). Both parsers used to
* return null for every one of them: `obu_gnss` keeps its position under `gnss`, not `own_info`,
* and the CAM topic sends `stationType` as a name.
*/
class CitOneJsonParsersTest {
private val obuGnss = """
{ "type": "v2xgw-owninfo", "obu_timestamp_sec": 1773834329.0660601,
"gnss": { "latitude": 53.5551, "longitude": 10.0222, "altitude_m": 60.5, "speed_mps": 5.25,
"time_utc": "2026-03-18T11:45:29Z", "heading_deg": 87.5, "acceleration_mpss": -0.25,
"curvature": { "radiusOfCurve_m": 3276.0, "confidence": 100.0 },
"positionError_stdDev": { "posErrSemiMajorAxisLen_m": 0.446, "posErrSemiMinorAxisLen_m": 0.446,
"posErrSemiMajorAxisOrientation_deg": 0.0, "altitudeErr_m": 0.609, "headingErr_deg": 361.0,
"groundSpeedErr_mps": 0.077, "verticalSpeedErr_mps": -1.0, "DOP": -4.45e-25 },
"satInfo": { "fix": "3d", "numSatUsed": 14,
"numSatVisible": { "gps": 0, "gbas": 0, "sbas": 0, "gnss": 0 } } },
"own_info": { "stationID": 319450879, "stationType": 5, "vehicleRole": 0, "vehicleWidth_m": 1.8,
"vehicleLength_m": 4.26, "yawRate_degps": 6.5, "isBreaking": false },
"pathHistory": { "refLatitude": 53.5551, "refLongitude": 10.0222, "refAltitude": 60.5,
"pathPoints": [ { "deltaLatitude": -3.5e-06, "deltaLongitude": 1.31e-05,
"deltaAltitude_m": -5.0, "pathDeltaTime_ms": 834 } ] } }
""".trimIndent()
private val processedCam = """
{"heading_deg":1.2,"pathHistory":{"path":{"coordinates":[[10.0258218,53.5526996,52.6],
[10.0258295,53.5524988,51.6]],"type":"LineString"}},"position":{"coordinates":[10.0258076,53.5528397,52.6],
"type":"Point"},"positionError_stdDev":{"altitudeErr_m":10.0,"groundSpeedErr_mps":0.105,"headingErr_deg":0.5,
"posErrSemiMajorAxisLen_m":1.57,"posErrSemiMajorAxisOrientation_deg":5.4,"posErrSemiMinorAxisLen_m":1.56},
"speed_mps":7.25,"stationId":3124041003,"stationType":"passengerCar","type":"v2x-cam",
"vehicleLength_m":4.9,"vehicleRole":"default","vehicleWidth_m":1.8,"yawRate_dps":-1.43}
""".trimIndent()
@Test
fun `obu_gnss - kinematics from gnss, identity and yaw rate from own_info`() {
val ego = ObuGnssParser.parseEgo(obuGnss, timestamp = 1_000L)!!
assertEquals(319450879L, ego.stationId)
assertEquals(StationType.PASSENGER_CAR, ego.stationType)
assertEquals(53.5551, ego.latitude, 1e-9)
assertEquals(10.0222, ego.longitude, 1e-9)
assertEquals(5.25, ego.speedMps, 1e-9)
assertEquals(87.5, ego.headingDeg, 1e-9)
assertEquals(-0.25, ego.accelerationMps2!!, 1e-9)
// Right-positive on this topic in practice, as Cam.yawRateDps is: taken as it is.
assertEquals(6.5, ego.yawRateDps!!, 1e-9)
assertEquals(4.26, ego.vehicleLengthM!!, 1e-9)
assertEquals(1.8, ego.vehicleWidthM!!, 1e-9)
assertTrue(ego.isOwn)
}
@Test
fun `obu_gnss - the no-fix marker is not a position`() {
val noFix = obuGnss.replace("\"latitude\": 53.5551", "\"latitude\": 91.0")
.replace("\"longitude\": 10.0222", "\"longitude\": 181.0")
assertNull(ObuGnssParser.parseEgo(noFix))
}
@Test
fun `obu_gnss - the invalid speed marker reads as no speed`() {
val badSpeed = obuGnss.replace("\"speed_mps\": 5.25", "\"speed_mps\": 163.82")
assertEquals(0.0, ObuGnssParser.parseEgo(badSpeed)!!.speedMps, 0.0)
}
@Test
fun `CAM topic - station type name, vehicle size and a left-positive yaw rate`() {
val cam = CamParser.parse(processedCam, ownStationId = null)!!
assertEquals(3124041003L, cam.stationId)
assertEquals(StationType.PASSENGER_CAR, cam.stationType)
assertEquals(53.5528397, cam.latitude, 1e-9)
assertEquals(10.0258076, cam.longitude, 1e-9)
assertEquals(7.25, cam.speedMps, 1e-9)
assertEquals(1.2, cam.headingDeg, 1e-9)
// -1.43 on this left-positive topic is 1.43 deg/s to the right: +1.43 in Cam.yawRateDps.
assertEquals(1.43, cam.yawRateDps!!, 1e-9)
assertEquals(4.9, cam.vehicleLengthM!!, 1e-9)
assertEquals(1.8, cam.vehicleWidthM!!, 1e-9)
assertFalse(cam.isOwn)
}
@Test
fun `CAM topic - own CAM recognised by the station id learned from obu_gnss`() {
assertTrue(CamParser.parse(processedCam, ownStationId = 3124041003L)!!.isOwn)
}
@Test
fun `CAM topic - an unknown station type name is still rejected`() {
assertNull(CamParser.parse(processedCam.replace("passengerCar", "spaceship"), ownStationId = null))
}
@Test
fun `station type names map by name, with the gap before roadSideUnit`() {
assertEquals(2, StationType.fromApiName("cyclist"))
assertEquals(11, StationType.fromApiName("tram"))
assertEquals(15, StationType.fromApiName("roadSideUnit"))
assertNull(StationType.fromApiName(""))
assertNull(StationType.fromApiName(null))
}
}
@@ -145,7 +145,7 @@ class DenmAirReceiveTest {
// detectionTime is a 42-bit TimestampIts counted from the 2004 ITS epoch. Getting either
// the width or the epoch wrong lands the hazard decades away, so the absolute value is
// asserted rather than a range.
assertEquals(1_786_979_455_563L, denm.detectionTimeMs) // TimestampIts is TAI: 5 leap seconds less in UTC
assertEquals(1_786_979_460_563L, denm.detectionTimeMs)
// Carried through from the GeoNetworking header and the serial prefix, not the payload.
assertEquals(1000, denm.relevanceRadiusM)
@@ -164,7 +164,7 @@ class DenmAirReceiveTest {
assertNull("a terminating DENM carries no SituationContainer", termDenm.causeCode)
assertEquals(4_194_380_752L, termDenm.stationId)
assertEquals(6, termDenm.sequenceNumber)
assertEquals(1_786_980_048_703L, termDenm.detectionTimeMs)
assertEquals(1_786_980_053_703L, termDenm.detectionTimeMs)
// The whole point of keying dedup on actionID: the termination must land on the same key as
// the event it ends, so filtering terminations actually removes that hazard from the map
@@ -1,131 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.GnUnwrap
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The Kotlin port of `gn_unwrap.c` against the firmware's own code.
*
* `gn_unwrap_corpus.tsv` is written by `make corpus` in obu-firmware/test/host: frames from the recorded
* captures (unsigned and signed, single-hop and GeoBroadcast, CAM, DENM, MAPEM, SPATEM), copies cut at
* several lengths, copies with flipped bytes, and a few rejected frames, each with the verdict and the
* fields that `gn_unwrap_its` returns. Every line must come out the same here: same accept or reject,
* same port, flags, destination area, truncation and payload bytes.
*/
class GnUnwrapTest {
private class Line(
val frame: ByteArray, val accepted: Boolean, val port: Int, val flags: Int,
val lat: Int, val lon: Int, val dist: Int, val truncated: Boolean, val payload: ByteArray,
)
private fun String.hex(): ByteArray = ByteArray(length / 2) { substring(2 * it, 2 * it + 2).toInt(16).toByte() }
private fun corpus(): List<Line> {
val text = javaClass.classLoader!!.getResourceAsStream("gn_unwrap_corpus.tsv")!!.bufferedReader().readText()
return text.lines().filter { it.isNotBlank() }.map { l ->
val f = l.split("\t")
assertEquals("fields in: ${l.take(60)}", 9, f.size)
Line(f[0].hex(), f[1] == "A", f[2].toInt(), f[3].toInt(), f[4].toInt(), f[5].toInt(), f[6].toInt(),
f[7] == "1", f[8].hex())
}
}
@Test
fun `every corpus frame gets the verdict and fields of the C code`() {
val lines = corpus()
assertTrue("corpus too small: ${lines.size}", lines.size > 400)
var accepted = 0
var rejected = 0
for ((n, line) in lines.withIndex()) {
val r = GnUnwrap.unwrap(line.frame)
if (!line.accepted) {
assertNull("line $n: C rejects, Kotlin accepted", r)
rejected++
continue
}
assertNotNull("line $n: C accepts, Kotlin rejected", r)
r!!
assertEquals("line $n port", line.port, r.btpPort)
assertEquals("line $n area flag", line.flags and 1 != 0, r.hasGeoArea)
assertEquals("line $n signed flag", line.flags and 2 != 0, r.signedUnverified)
assertEquals("line $n area lat", line.lat, r.areaLatTenMicroDeg)
assertEquals("line $n area lon", line.lon, r.areaLonTenMicroDeg)
assertEquals("line $n area dist", line.dist, r.areaDistanceAMeters)
assertEquals("line $n truncated", line.truncated, r.truncated)
assertArrayEquals("line $n payload", line.payload, r.payload)
accepted++
}
// the corpus has both kinds in quantity: the test means something only if it does
assertTrue("accepted $accepted", accepted > 100)
assertTrue("rejected $rejected", rejected > 100)
}
@Test
fun `the corpus covers every message kind and both security shapes`() {
val seen = corpus().filter { it.accepted && !it.truncated }.map { Triple(it.port, it.flags and 2 != 0, it.flags and 1 != 0) }.toSet()
assertTrue(seen.contains(Triple(2001, false, false))) // unsigned single-hop CAM
assertTrue(seen.contains(Triple(2001, true, false))) // signed CAM
assertTrue(seen.any { it.first == 2002 && it.third }) // GeoBroadcast DENM
assertTrue(seen.any { it.first == 2003 }) // MAPEM
assertTrue(seen.any { it.first == 2004 }) // SPATEM
}
@Test
fun `a frame for a port that is not an ITS message port is rejected, VAM 2018 is accepted`() {
val cam = corpus().first { it.accepted && !it.truncated && it.port == 2001 && it.flags == 0 }
val vam = patchBtpPort(cam.frame, 2018)
assertEquals(2018, GnUnwrap.unwrap(vam)!!.btpPort)
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 1234)))
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 2005)))
}
/** The BTP-B destination port sits right after the GN headers: find it by the known payload start. */
private fun patchBtpPort(frame: ByteArray, port: Int): ByteArray {
val r = GnUnwrap.unwrap(frame)!!
val start = frame.indices.first { i -> i + r.payload.size <= frame.size && (r.payload.indices).all { frame[i + it] == r.payload[it] } }
val copy = frame.copyOf()
copy[start - 4] = (port shr 8).toByte() // BTP-B header: port u16 BE, port info u16 BE
copy[start - 3] = port.toByte()
return copy
}
@Test
fun `short and garbage input is rejected without an exception`() {
assertNull(GnUnwrap.unwrap(ByteArray(0)))
assertNull(GnUnwrap.unwrap(ByteArray(23)))
assertNull(GnUnwrap.unwrap(ByteArray(200)))
assertNull(GnUnwrap.unwrap(ByteArray(200) { 0xFF.toByte() }))
// every prefix of a real frame: never throws
val frame = corpus().first { it.accepted && !it.truncated && it.flags and 2 != 0 }.frame
for (n in 0..frame.size) GnUnwrap.unwrap(frame.copyOf(n))
}
@Test
fun `the V2X_RX body is the one V2xRxFrame reads and the firmware writes`() {
val line = corpus().first { it.accepted && !it.truncated && it.port == 2002 && it.flags and 1 != 0 }
val r = GnUnwrap.unwrap(line.frame)!!
val body = GnUnwrap.toV2xRxBody(r, -61)!!
assertEquals(V2xRxFrame.PREFIX_SIZE + r.payload.size, body.size)
val parsed = V2xRxFrame.parse(body)!!
assertEquals(2002, parsed.btpPort)
assertEquals(-61, parsed.rssiDbm)
assertNotNull(parsed.geoArea)
assertEquals(line.lat / 1e7, parsed.geoArea!!.latitude, 1e-9)
assertEquals(line.dist, parsed.geoArea!!.radiusMeters)
assertArrayEquals(r.payload, parsed.uper)
// flags: bit 0 area, bit 1 signed
assertEquals(0x01 or (if (r.signedUnverified) 0x02 else 0), body[3].toInt())
// a truncated message is not forwarded
val cut = corpus().firstOrNull { it.accepted && it.truncated }
if (cut != null) assertNull(GnUnwrap.toV2xRxBody(GnUnwrap.unwrap(cut.frame)!!, -50))
assertEquals(127, GnUnwrap.toV2xRxBody(r, 500)!![2].toInt()) // clamped like the firmware
assertEquals(-128, GnUnwrap.toV2xRxBody(r, -500)!![2].toInt())
}
}
@@ -1,63 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.CamUperCodec
import com.hawhamburg.micr0bu.domain.asn1.ItsTime
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.Instant
/**
* TimestampIts is TAI-based (ETSI TS 102 894-2 V2.5.1): it runs ahead of UTC by the leap seconds
* inserted since the ITS epoch. Values from the standard's own example and the IANA leap-seconds.list.
*/
class ItsTimeLeapSecondTest {
private fun utc(text: String) = Instant.parse(text).toEpochMilli()
@Test
fun `the ITS epoch is zero`() {
assertEquals(0L, ItsTime.timestampIts(utc("2004-01-01T00:00:00Z")))
}
@Test
fun `the standard's example 2007-01-01 includes one leap second`() {
assertEquals(94_694_401_000L, ItsTime.timestampIts(utc("2007-01-01T00:00:00Z")))
}
@Test
fun `today TimestampIts is 5 s ahead of Unix time minus the epoch`() {
val now = utc("2026-10-02T16:00:00Z")
assertEquals(now - ItsTime.EPOCH_MS + 5_000L, ItsTime.timestampIts(now))
// the value the micrOBU station-link reference (vbs.py its_timestamp_ms) produces for the same instant
assertEquals(718_041_605_000L, ItsTime.timestampIts(now))
}
@Test
fun `the leap second of 2017 counts from 2017-01-01 on`() {
assertEquals(4, ItsTime.leapSecondsAt(utc("2016-12-31T23:59:59.999Z")))
assertEquals(5, ItsTime.leapSecondsAt(utc("2017-01-01T00:00:00Z")))
// the inserted second 23:59:60 lies between: two UTC instants 1 ms apart are 1001 ms apart in TAI
assertEquals(1_001L, ItsTime.timestampIts(utc("2017-01-01T00:00:00Z")) -
ItsTime.timestampIts(utc("2016-12-31T23:59:59.999Z")))
}
@Test
fun `back to UTC is the inverse, also across every leap second`() {
for (t in listOf("2004-01-01T00:00:00Z", "2005-12-31T23:59:59.999Z", "2006-01-01T00:00:00Z",
"2012-06-30T23:59:59.500Z", "2012-07-01T00:00:00.001Z", "2017-01-01T00:00:00Z", "2026-10-02T16:00:00.123Z")) {
assertEquals(t, utc(t), ItsTime.epochMs(ItsTime.timestampIts(utc(t))))
}
}
@Test
fun `a TimestampIts inside an inserted leap second maps to the end of it`() {
val its = ItsTime.timestampIts(utc("2017-01-01T00:00:00Z")) - 400L // 2016-12-31T23:59:60.600
assertEquals(utc("2017-01-01T00:00:00Z"), ItsTime.epochMs(its))
}
@Test
fun `generationDeltaTime follows TimestampIts`() {
val now = utc("2026-10-02T16:00:00Z")
assertEquals(Math.floorMod(718_041_605_000L, 65_536L).toInt(), CamUperCodec.generationDeltaTime(now))
}
}
@@ -1,200 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.LinkMessage
import com.hawhamburg.micr0bu.data.transport.LinkReassembly
import com.hawhamburg.micr0bu.data.transport.RawFrame
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** Fragment reassembly as docs/station-link.pdf specifies it, and the RAW_FRAME record parser. */
class LinkReassemblyTest {
private var clock = 0L
private val reassembly = LinkReassembly { clock }
private fun fragment(flags: Int, seq: Int, total: Int, offset: Int, data: ByteArray, opcode: Int = LinkOpcode_RAW_FRAME) =
LinkMessage(
opcode, seq,
byteArrayOf(total.toByte(), (total shr 8).toByte(), offset.toByte(), (offset shr 8).toByte()) + data,
flags,
)
private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
@Test
fun `a complete message passes through unchanged`() {
val m = LinkMessage(0x81, 5, bytes(1, 2, 3))
assertArrayEquals(bytes(1, 2, 3), reassembly.feed(m)!!.body)
}
@Test
fun `three fragments in order become one message with flags 0`() {
assertNull(reassembly.feed(fragment(1, 9, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 9, 6, 2, bytes(3, 4))))
val whole = reassembly.feed(fragment(3, 9, 6, 4, bytes(5, 6)))!!
assertArrayEquals(bytes(1, 2, 3, 4, 5, 6), whole.body)
assertEquals(0, whole.flags)
assertEquals(9, whole.sequence)
assertEquals(LinkOpcode_RAW_FRAME, whole.opcode)
}
@Test
fun `a gap, a duplicate and a changed total drop the stream`() {
assertNull(reassembly.feed(fragment(1, 1, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 1, 6, 4, bytes(5, 6)))) // skipped the middle
assertNull(reassembly.feed(fragment(3, 1, 6, 2, bytes(3, 4)))) // the stream is gone: nothing completes
assertNull(reassembly.feed(fragment(1, 2, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 2, 6, 0, bytes(1, 2)))) // the same offset twice
assertNull(reassembly.feed(fragment(1, 3, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 3, 8, 2, bytes(3, 4)))) // total changed
assertNull(reassembly.feed(fragment(2, 4, 6, 2, bytes(3, 4)))) // a middle without a first
assertTrue(reassembly.dropped >= 4)
}
@Test
fun `an unfinished stream is discarded after two seconds of silence`() {
assertNull(reassembly.feed(fragment(1, 7, 4, 0, bytes(1, 2))))
clock += 2_500
assertNull(reassembly.feed(fragment(3, 7, 4, 2, bytes(3, 4)))) // the first fragment is gone
assertNull(reassembly.feed(fragment(1, 8, 4, 0, bytes(1, 2))))
clock += 1_500 // still inside the window
assertNotNull(reassembly.feed(fragment(3, 8, 4, 2, bytes(3, 4))))
}
@Test
fun `at most eight streams are held and the ninth is refused`() {
for (s in 1..8) assertNull(reassembly.feed(fragment(1, s, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(1, 9, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 9, 4, 2, bytes(3, 4)))) // refused, so nothing to complete
assertNotNull(reassembly.feed(fragment(3, 1, 4, 2, bytes(3, 4)))) // the held ones still finish
}
@Test
fun `an indication of 65535 octets is the largest, more is refused, a message of 2000 octets works`() {
val big = ByteArray(2000) { it.toByte() }
val chunk = 500
var out: LinkMessage? = null
var offset = 0
while (offset < big.size) {
val n = minOf(chunk, big.size - offset)
val flags = if (offset == 0) 1 else if (offset + n == big.size) 3 else 2
out = reassembly.feed(fragment(flags, 11, big.size, offset, big.copyOfRange(offset, offset + n)))
offset += n
}
assertArrayEquals(big, out!!.body)
assertNull(reassembly.feed(fragment(1, 12, 65_536 + 4, 0, bytes(1, 2))))
}
@Test
fun `different opcodes with the same sequence are separate streams`() {
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(1, 2), opcode = 0x85)))
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(9, 9), opcode = 0x81)))
val a = reassembly.feed(fragment(3, 5, 4, 2, bytes(3, 4), opcode = 0x85))!!
val b = reassembly.feed(fragment(3, 5, 4, 2, bytes(8, 8), opcode = 0x81))!!
assertArrayEquals(bytes(1, 2, 3, 4), a.body)
assertArrayEquals(bytes(9, 9, 8, 8), b.body)
}
// ---- large V2X_RX, fragmented by the firmware ---------------------------------------------
private fun hexBytes(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
/**
* `v2x_rx_fragments.tsv` is written by `test_v2x_fragments --dump` in obu-firmware/test/host: the first 888-byte
* SPATEM and 1198-byte MAPEM of the CiT node's 2026-11-23 recording, as the firmware's own code splits them for
* serial / BLE MTU 517 (512-octet messages) and BLE MTU 247 (244). Each line: port, UPER size, limit, V2X_RX body,
* then the link messages in order. The app must put back exactly that body and read the message out of it.
*/
@Test
fun `the firmware's fragments of a large V2X_RX reassemble to the body and parse`() {
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
assertEquals(4, lines.size)
for (line in lines) {
val f = line.split('\t')
val port = f[0].toInt()
val size = f[1].toInt()
val limit = f[2].toInt()
val body = hexBytes(f[3])
val wires = f.drop(4).map { hexBytes(it) }
assertTrue("$port/$size at $limit: needs fragments", wires.size >= 2)
var whole: LinkMessage? = null
wires.forEachIndexed { i, wire ->
assertTrue("$port/$size at $limit: a message of ${wire.size} octets exceeds $limit", wire.size <= limit)
val message = LinkMessage.decode(wire)!!
assertEquals(0x90, message.opcode)
assertEquals(if (i == 0) 1 else if (i == wires.size - 1) 3 else 2, message.flags)
whole = reassembly.feed(message)
if (i < wires.size - 1) assertNull(whole)
}
assertEquals(0x90, whole!!.opcode)
assertEquals(0, whole!!.flags)
assertArrayEquals(body, whole!!.body)
val v2x = V2xRxFrame.parse(whole!!.body)!!
assertEquals(port, v2x.btpPort)
assertEquals(size, v2x.uper.size)
assertEquals(if (port == 2003) 5 else 4, v2x.uper[1].toInt() and 0xFF) // ItsPduHeader.messageId: MAPEM 5, SPATEM 4
}
}
@Test
fun `losing one fragment of a large V2X_RX costs that message only`() {
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
val f = lines.first { it.split('\t')[2] == "512" && it.split('\t')[0] == "2003" }.split('\t')
val wires = f.drop(4).map { hexBytes(it) }
// the first message loses its middle fragment; the same message again, in full, still completes afterwards
val lost = wires.mapIndexedNotNull { i, w -> if (i == 1) null else LinkMessage.decode(w)!! }
for (m in lost) assertNull(reassembly.feed(m))
val next = wires.map { w -> LinkMessage.decode(w)!!.let { LinkMessage(it.opcode, it.sequence + 1, it.body, it.flags) } }
var whole: LinkMessage? = null
for (m in next) whole = reassembly.feed(m)
assertArrayEquals(hexBytes(f[3]), whole!!.body)
}
// ---- RAW_FRAME record ------------------------------------------------------------------
private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray {
val h = java.io.ByteArrayOutputStream()
fun u8(v: Int) = h.write(v and 0xFF)
fun u16(v: Int) { u8(v); u8(v shr 8) }
fun u32(v: Long) { u16(v.toInt()); u16((v shr 16).toInt()) }
u32(42); u8(flags); u8(rssi)
h.write("ITS5".toByteArray())
u32(1_900_000_000L); u32(123_456); u16(frame.size)
h.write(frame)
return h.toByteArray()
}
@Test
fun `a RAW_FRAME body parses into its fields and frame`() {
val frame = ByteArray(30) { (it * 3).toByte() }
val r = RawFrame.parse(rawBody(frame))!!
assertEquals(42L, r.counter)
assertTrue(r.utcTime)
assertFalse(r.ownTransmission)
assertEquals(-61, r.rssiDbm)
assertEquals(1_900_000_000L, r.seconds)
assertEquals(123_456L, r.microseconds)
assertArrayEquals(frame, r.frame)
assertTrue(RawFrame.parse(rawBody(frame, flags = 0x01))!!.ownTransmission)
}
@Test
fun `a malformed RAW_FRAME is refused`() {
val good = rawBody(ByteArray(10))
assertNull(RawFrame.parse(good.copyOf(19))) // shorter than the header
assertNull(RawFrame.parse(good.copyOf(good.size - 1))) // length field says more
assertNull(RawFrame.parse(good + byteArrayOf(0))) // or less
val bad = good.copyOf(); bad[6] = 'X'.code.toByte()
assertNull(RawFrame.parse(bad)) // wrong magic
}
private companion object {
const val LinkOpcode_RAW_FRAME = 0x85
}
}
@@ -1,139 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.map.LaneType
import com.hawhamburg.micr0bu.domain.map.MapEvent
import com.hawhamburg.micr0bu.domain.map.NodeOffset
import com.hawhamburg.micr0bu.domain.map.lanePoints
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* [MapemUperCodec] against every distinct MAPEM on record, field by field.
*
* `src/test/resources/mapem/corpus.txt` holds each MAPEM's bytes followed by every field as
* `asn1tools` decodes it with the ETSI modules in `asn1/` (written by `tools/mapem_corpus.py`):
* 17 distinct MAPEMs from the 2026-03-18 drive (7 916 received, 288 to 1348 bytes) and the bench
* RSU's, captured by the ESP32-C5 on 2026-10-28. [dump] renders the decoder's output in the same
* text, so any field this decoder reads at the wrong width or in the wrong place shows up as a
* differing line - and since UPER has no padding, as a cascade of them.
*/
class MapemUperCodecTest {
private class Sample(val hex: String, val expected: List<String>)
private val corpus: List<Sample> by lazy {
val text = javaClass.classLoader!!.getResource("mapem/corpus.txt")!!.readText()
val samples = ArrayList<Sample>()
var hex: String? = null
val lines = ArrayList<String>()
fun flush() { hex?.let { samples.add(Sample(it, lines.toList())) }; lines.clear() }
for (line in text.lines()) {
when {
line.startsWith("#hex ") -> { flush(); hex = line.removePrefix("#hex ") }
line.startsWith("#") || line.isBlank() -> {}
else -> lines.add(line)
}
}
flush()
samples
}
private fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun Int?.orNone(): String = this?.toString() ?: "None"
/** Same text as `tools/mapem_corpus.py`'s dump(). */
private fun dump(m: MapEvent): List<String> {
val out = mutableListOf("station=${m.stationId} rev=${m.msgIssueRevision}")
for (i in m.intersections) {
val lat = Math.round(i.refLatitude * 1e7)
val lon = Math.round(i.refLongitude * 1e7)
out += "I key=${i.key} rev=${i.revision} name=${i.name ?: "None"} ref=$lat,$lon " +
"elev=${i.elevationDm.orNone()} width=${i.laneWidthCm.orNone()} " +
"speeds=${i.speedLimits.joinToString(",") { "${it.type}:${it.speed}" }}"
for (lane in i.lanes) {
val dir = (if (lane.isIngress) 2 else 0) or (if (lane.isEgress) 1 else 0)
out += "L id=${lane.laneId} name=${lane.name ?: "None"} in=${lane.ingressApproach.orNone()} " +
"eg=${lane.egressApproach.orNone()} dir=$dir share=${lane.sharedWith} " +
"type=${lane.type.ordinal} attr=${lane.typeAttributes} man=${lane.maneuvers?.bits.orNone()}"
for (node in lane.nodes) {
val pos = when (val o = node.offset) {
is NodeOffset.Xy -> "xy=${o.xCm},${o.yCm}"
is NodeOffset.LatLon -> "ll=${o.latitude},${o.longitude}"
}
out += "N $pos local=${node.localAttributes.joinToString(",")} " +
"dis=${node.disabled.joinToString(",")} en=${node.enabled.joinToString(",")} " +
"dw=${node.dWidthCm.orNone()} de=${node.dElevationCm.orNone()}"
}
for (c in lane.connections) {
val remote = c.remoteIntersection?.let { "${c.remoteRegion ?: -1}/$it" } ?: "None"
out += "C to=${c.toLane} man=${c.maneuver?.bits.orNone()} remote=$remote " +
"sg=${c.signalGroup.orNone()} uc=${c.userClass.orNone()} cid=${c.connectionId.orNone()}"
}
if (lane.overlays.isNotEmpty()) out += "O " + lane.overlays.joinToString(",")
}
}
return out
}
@Test
fun `every recorded MAPEM decodes to exactly what asn1tools reads`() {
assertEquals("corpus size", 18, corpus.size)
corpus.forEachIndexed { n, sample ->
val decoded = MapemUperCodec.decode(sample.hex.hexToBytes(), receivedAtEpochMs = 0L)
assertNotNull("MAPEM #$n (${sample.hex.length / 2} bytes) did not decode", decoded)
val actual = dump(decoded!!)
val first = sample.expected.indices.firstOrNull { it >= actual.size || actual[it] != sample.expected[it] }
if (first != null || actual.size != sample.expected.size) {
val at = first ?: sample.expected.size
throw AssertionError(
"MAPEM #$n differs at line ${at + 1}:\n asn1tools: ${sample.expected.getOrNull(at)}\n" +
" decoder: ${actual.getOrNull(at)}",
)
}
}
}
@Test
fun `bench RSU MAPEM - test crossroads geometry`() {
val bench = corpus.single { it.expected.any { line -> "MicrOBU test crossroads" in line } }
val map = MapemUperCodec.decode(bench.hex.hexToBytes(), 0L, rssiDbm = -58)!!
assertEquals(-58, map.rssiDbm)
val i = map.intersections.single()
assertEquals("-1/23", i.key)
assertEquals(53.554698, i.refLatitude, 1e-9)
assertEquals(10.022548, i.refLongitude, 1e-9)
assertEquals(8, i.lanes.size)
val northIn = i.lane(1)!!
assertEquals("North in", northIn.name)
assertTrue(northIn.isIngress && !northIn.isEgress)
assertEquals(LaneType.VEHICLE, northIn.type)
// Straight to lane 6 (South out), left to 4 (East out), right to 8 (West out), all group 1
val byTarget = northIn.connections.associateBy { it.toLane }
assertTrue(byTarget.getValue(6).maneuver!!.straight)
assertTrue(byTarget.getValue(4).maneuver!!.left)
assertTrue(byTarget.getValue(8).maneuver!!.right)
assertEquals(setOf(1), northIn.connections.map { it.signalGroup }.toSet())
// First node 12 m north (and 1.75 m west) of the reference point: the stop line.
val points = i.lanePoints(northIn)
assertEquals(12.0, (points[0].latitude - i.refLatitude) * 111_319.49, 0.01)
assertEquals(72.0, (points[1].latitude - i.refLatitude) * 111_319.49, 0.01)
}
@Test
fun `wrong message, wrong version and truncation give null`() {
val bytes = corpus.first().hex.hexToBytes()
assertNull(MapemUperCodec.decode(bytes.copyOf().also { it[1] = 4 }, 0L)) // a SPATEM id
assertNull(MapemUperCodec.decode(bytes.copyOf().also { it[0] = 1 }, 0L)) // protocol version 1
for (n in 0 until bytes.size - 1) {
// UPER has no end marker: a cut inside the last few bits may still decode, but must not throw
MapemUperCodec.decode(bytes.copyOf(n), 0L)
}
}
}
@@ -1,25 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import org.junit.Assert.assertEquals
import org.junit.Test
/** The stored and logged ids of [PhoneMount] are a file format: logs on disk carry them. */
class PhoneMountTest {
@Test
fun `ids are the ones written to settings and logs`() {
assertEquals(listOf("handlebar", "bag", "pocket"), PhoneMount.entries.map { it.id })
}
@Test
fun `every id reads back as its mount`() {
PhoneMount.entries.forEach { assertEquals(it, PhoneMount.fromId(it.id)) }
}
@Test
fun `a missing or unknown id falls back to the handlebar`() {
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId(null))
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId("roof"))
}
}
@@ -153,34 +153,6 @@ class SpatemUperCodecTest {
assertNull(SignalPhaseEvent(SignalPhase.DARK, null, null, null).secondsUntil(topOfHour))
}
@Test
fun `decodes a road RSU SPATEM with names and advisory speeds`() {
// 888 bytes from the Berliner Tor RSU (2026-11-23): intersection and movement names, and a greenwave
// plus an ecoDrive AdvisorySpeed on every event. Before names and speeds were walked, every one of
// its SPATEMs was refused and the V2X screens stayed empty. Expected values: asn1tools, ETSI modules.
val bytes = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim().hexToBytes()
assertEquals(888, bytes.size)
val spat = SpatemUperCodec.decode(bytes, receivedAt)
assertNotNull(spat)
spat!!
assertEquals(1_095_348_116L, spat.stationId)
assertEquals(470_408, spat.minuteOfYear)
val i = spat.intersections.single()
assertEquals("-1/23", i.key)
assertEquals(2, i.revision)
assertEquals(470_408, i.moy)
assertEquals(59_719, i.timeStampMs)
assertEquals(listOf(1, 2, 3, 4, 5), i.movements.map { it.signalGroup })
i.movements.forEach { assertEquals(8, it.events.size) }
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5562, 5562, 5562), i.movements[0].events.first())
assertEquals(SignalPhase.PERMISSIVE_CLEARANCE, i.movements[0].events.last().phase)
assertEquals(6522, i.movements[0].events.last().minEndTimeDs)
assertEquals(SignalPhase.PROTECTED_MOVEMENT_ALLOWED, i.movements[2].events.first().phase)
assertEquals(SignalPhase.PERMISSIVE_MOVEMENT_ALLOWED, i.movements[3].events.first().phase)
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5802, 5802, 5802), i.movements[4].events.first())
assertEquals(6762, i.movements[4].events.last().minEndTimeDs)
}
@Test
fun `does not decode another message type as SPATEM`() {
// protocolVersion 2, messageId 2 (CAM) - the header guard must reject it outright.
@@ -12,7 +12,6 @@ import com.hawhamburg.micr0bu.data.transport.StationStatus
import com.hawhamburg.micr0bu.data.transport.credentialsSegment
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
@@ -22,7 +21,7 @@ import org.junit.Test
* Pins the phone side of the station-link message layer.
*
* ## Where the expected bytes come from
* Niklas Dathe's Python implementation of the same protocol, microbu-esp32c5
* The colleague's Python implementation of the same protocol, microbu-esp32c5
* station-link/python/microbu_link/messages.py (`encode_message` over each body's `encode`),
* run with the same field values. That module is what their phone emulator drives the firmware
* with, so an agreement here is agreement with a second, independent implementation.
@@ -34,26 +33,11 @@ class StationLinkTest {
@Test
fun `STATION_CONFIGURE matches the Python encoder`() {
// station_type 2, channel 180 (0x00b4), 20 dBm, security on, beaconing off: the 6-octet body of docs/station-link.pdf
val body = StationConfigure(stationType = 2).encode()
assertEquals(
"0100070002b400140100",
LinkMessage(LinkOpcode.STATION_CONFIGURE, 7, body).encode().hex(),
)
}
@Test
fun `STATION_CONFIGURE with a MAC is the 16-octet form that names the address`() {
// type 2, security on, address_configuration 0 (AUTO), the MAC, no beaconing, channel 180, 20 dBm, TX+RX, DP2, 1 s
val body = StationConfigure(stationType = 2, mid = "021122334455".hexToBytes()).encode()
assertEquals(
"0100070002010002112233445500b40014020205",
LinkMessage(LinkOpcode.STATION_CONFIGURE, 7, body).encode().hex(),
)
// another MAC is another configuration (the station is reconfigured), the same MAC is the same one
assertEquals(StationConfigure(2, mid = "021122334455".hexToBytes()), StationConfigure(2, mid = "021122334455".hexToBytes()))
assertFalse(StationConfigure(2, mid = "021122334455".hexToBytes()) == StationConfigure(2, mid = "021122334466".hexToBytes()))
assertFalse(StationConfigure(2, mid = "021122334455".hexToBytes()) == StationConfigure(2))
}
@Test
@@ -86,22 +70,17 @@ class StationLinkTest {
assertEquals("04000a00b702f00003ababab", LinkMessage(LinkOpcode.CREDENTIALS_PROVISION, 10, body).encode().hex())
}
/** The first 103 octets of the Python-encoder STATUS snapshot: counters up to its_time_ms. */
private val statusHead = (
"40e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
"190000001a0000001b0000001c000000fbb2b7ffa6000000"
).hexToBytes()
/** A 131-octet snapshot: [statusHead], 26 octets of CBR, DCC, heap and temperature, then the cell voltage. */
private fun status131(batteryMv: Int): ByteArray =
statusHead + ByteArray(26) + byteArrayOf(batteryMv.toByte(), (batteryMv shr 8).toByte())
@Test
fun `STATUS snapshot decodes field by field`() {
val body = status131(3871)
assertEquals(StationStatus.SIZE, body.size)
val status = StationStatus.decode(body)!!
fun `STATUS from the Python encoder decodes field by field`() {
val message = LinkMessage.decode(
("8400341240e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
"190000001a0000001b0000001c000000fbb2b7ffa6000000").hexToBytes(),
)
assertNotNull(message)
assertEquals(LinkOpcode.STATUS, message!!.opcode)
assertEquals(0x1234, message.sequence)
val status = StationStatus.decode(message.body)!!
assertEquals(123_456L, status.uptimeMs)
assertTrue(status.configured)
assertArrayEquals("b80b49387a4c12eb".hexToBytes(), status.identifier)
@@ -126,57 +105,12 @@ class StationLinkTest {
}
@Test
fun `a STATUS shorter than 131 octets is refused, a longer one is accepted`() {
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE - 1)))
assertNull(StationStatus.decode(statusHead))
assertNotNull(StationStatus.decode(status131(3871) + ByteArray(4)))
fun `a STATUS of the wrong length is refused, as the Python decoder does`() {
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1)))
}
@Test
fun `the battery voltage at octet 129 is decoded`() {
val status = StationStatus.decode(status131(3871))!!
assertEquals(3871, status.batteryMv)
assertFalse(status.batteryLow)
assertFalse(status.batteryCritical)
assertEquals(60, status.batteryPercent)
}
@Test
fun `low and critical follow the voltage thresholds`() {
val low = StationStatus.decode(status131(3400))!!
assertTrue(low.batteryLow)
assertFalse(low.batteryCritical)
val critical = StationStatus.decode(status131(3290))!!
assertTrue(critical.batteryLow)
assertTrue(critical.batteryCritical)
assertEquals(0, critical.batteryPercent)
}
@Test
fun `no voltage means no battery`() {
val status = StationStatus.decode(status131(0))!!
assertFalse(status.batteryLow)
assertFalse(status.batteryCritical)
assertNull(status.batteryPercent)
}
@Test
fun `LiPo percent is monotonic, clamped and anchored`() {
assertEquals(0, StationStatus.lipoPercent(3000))
assertEquals(0, StationStatus.lipoPercent(3300))
assertEquals(5, StationStatus.lipoPercent(3500))
assertEquals(100, StationStatus.lipoPercent(4200))
assertEquals(100, StationStatus.lipoPercent(4300))
var last = -1
for (mv in 3000..4300 step 10) {
val p = StationStatus.lipoPercent(mv)
assertTrue("$mv mV -> $p% went down", p >= last)
last = p
}
}
@Test
fun `CONFIRM of STATION_CONFIGURE carries the credential state`() {
fun `RESULT of STATION_CONFIGURE carries the credential state`() {
val message = LinkMessage.decode("8000070000120800021122334455b80b49387a4c12eb0101".hexToBytes())!!
val result = LinkResult.decode(message.body)!!
assertTrue(result.accepted)
@@ -1,105 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.map.StoredMaps
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
/** The bundled intersections, and which of them a SPATEM is matched to. */
class StoredMapsTest {
private val stored by lazy { StoredMaps.parse(File("src/main/assets/${StoredMaps.ASSET_PATH}").readText()) }
private val one by lazy { stored.last { it.key == "3/2349" } }
private val here by lazy { MapPoint(one.refLatitude, one.refLongitude) }
private fun pick(
key: String = one.key,
revision: Int = one.revision,
live: List<com.hawhamburg.micr0bu.domain.map.IntersectionGeometry> = emptyList(),
own: MapPoint? = here,
) = TrafficLights.geometryFor(key, revision, live, stored, own)
@Test
fun `bundle holds the recorded Hamburg intersections and the bench RSU, one per revision`() {
// Lower bounds: tools/mapem_bundle.py adds to the list.
assertTrue(stored.size >= 17)
assertTrue(stored.count { it.region != null } >= 16)
assertEquals(stored.size, stored.map { it.key to it.revision }.toSet().size)
}
@Test
fun `the bench RSU's SPATEM joins its stored intersection`() {
val hex = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim()
val spat = SpatemUperCodec.decode(hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray(), 0L)!!
val state = spat.intersections.single()
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)!!
assertEquals("-1/23", matched.key)
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
assertTrue(light.approaches.isNotEmpty())
assertFalse(light.revisionMismatch)
}
@Test
fun `every recorded intersection joins the SPATEM recorded for it`() {
val samples = javaClass.classLoader!!.getResource("mapem/spat_samples.txt")!!.readText()
.lines().filter { it.isNotBlank() }.associate { line ->
val (key, revision, hex) = line.split(" ")
(key to revision.toInt()) to hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
}
// Entries added later may have no recorded SPATEM; the original 16 all do.
val sampled = stored.filter { it.region != null && (it.key to it.revision) in samples }
assertTrue(sampled.size >= 16)
for (geometry in sampled) {
val spat = SpatemUperCodec.decode(samples.getValue(geometry.key to geometry.revision), 0L)!!
val state = spat.intersections.single { it.key == geometry.key && it.revision == geometry.revision }
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)
assertSame(geometry, matched)
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
assertTrue("no approaches for ${geometry.key}", light.approaches.isNotEmpty())
assertFalse(light.revisionMismatch)
}
}
@Test
fun `matched on region and id together`() {
assertSame(one, pick())
assertNull(pick(key = "4/2349"))
assertNull(pick(key = "-1/2349"))
}
@Test
fun `a stored map of another revision is not used`() {
assertNull(pick(revision = one.revision + 1))
}
@Test
fun `a stored map far from the rider is not used, an unknown position does not block it`() {
// 0.03 deg of latitude is 3.3 km, beyond the radius; 0.01 deg is 1.1 km, inside it.
assertNull(pick(own = MapPoint(one.refLatitude + 0.03, one.refLongitude)))
assertSame(one, pick(own = MapPoint(one.refLatitude + 0.01, one.refLongitude)))
assertSame(one, pick(own = null))
}
@Test
fun `a live map of the same revision wins over the stored one`() {
val live = one.copy(name = "live")
assertSame(live, pick(live = listOf(live)))
}
@Test
fun `the stored map wins over a live one of another revision`() {
val live = one.copy(revision = one.revision + 1)
assertSame(one, pick(live = listOf(live)))
// And with nothing stored for the SPATEM's revision, the live one is still the fallback.
assertSame(live, pick(revision = one.revision + 2, live = listOf(live)))
}
}
@@ -1,156 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
import com.hawhamburg.micr0bu.domain.spat.TrafficLights.single
import com.hawhamburg.micr0bu.domain.spat.Turn
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.PI
import kotlin.math.cos
/**
* [TrafficLights.join] on recorded messages only: every MAPEM in `mapem/corpus.txt` with a SPATEM
* of the same intersection and revision from `mapem/spat_samples.txt` (both written by
* `tools/mapem_corpus.py`): 16 road intersections from the 2026-03-18 drive and the bench RSU's
* test crossroads from the 2026-10-28 ESP32-C5 capture.
*/
class TrafficLightsTest {
private fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun resource(name: String) = javaClass.classLoader!!.getResource(name)!!.readText()
/** Every intersection geometry in the corpus, in order. */
private val maps: List<IntersectionGeometry> by lazy {
resource("mapem/corpus.txt").lines().filter { it.startsWith("#hex ") }.flatMap {
MapemUperCodec.decode(it.removePrefix("#hex ").hexToBytes(), 0L)!!.intersections
}
}
/** (key, revision) -> the recorded SPATEM's state for that intersection. */
private val spats: Map<Pair<String, Int>, SpatIntersection> by lazy {
resource("mapem/spat_samples.txt").lines().filter { it.isNotBlank() }.associate { line ->
val (key, revision, hex) = line.split(" ")
val spat = SpatemUperCodec.decode(hex.hexToBytes(), 0L)
assertNotNull("recorded SPATEM for $key rev $revision does not decode", spat)
val state = spat!!.intersections.single { it.key == key && it.revision == revision.toInt() }
(key to revision.toInt()) to SpatIntersection(state, spat.stationId, null, 0L)
}
}
private val bench by lazy { maps.single { it.key == "-1/23" } }
private val benchSpat by lazy { spats.getValue("-1/23" to 1) }
/** [north] / [east] metres from the bench intersection's reference point. */
private fun benchPoint(north: Double, east: Double) = MapPoint(
bench.refLatitude + north / 111_319.49,
bench.refLongitude + east / (111_319.49 * cos(bench.refLatitude * PI / 180)),
)
@Test
fun `bench crossroads - four approaches, three exits each, all on SPATEM groups`() {
val light = TrafficLights.join(benchSpat, bench)
assertEquals("MicrOBU test crossroads", light.name)
assertFalse(light.revisionMismatch)
assertEquals(listOf("North in", "East in", "South in", "West in"), light.approaches.map { it.lane.name })
for (approach in light.approaches) {
assertEquals(setOf(Turn.STRAIGHT, Turn.LEFT, Turn.RIGHT), approach.exits.map { it.turn }.toSet())
approach.exits.forEach { assertNotNull("group ${it.connection.signalGroup} not in SPATEM", it.movement) }
}
// North in drives south (180 deg) toward a stop line 12 m north of the reference point.
val north = light.approaches.first()
assertEquals(180.0, north.bearingDeg, 2.0)
assertEquals(listOf(1), north.byGroup.map { it.first })
assertEquals(benchSpat.state.movements.first { it.signalGroup == 1 }, north.exits.first().movement)
assertEquals(270.0, light.approaches[1].bearingDeg, 2.0) // East in drives west
}
@Test
fun `bench crossroads - the rider's approach from position and heading`() {
// 40 m north, on the North-in lane (1.75 m west of the centre line), riding south
val riding = TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.75), ownHeadingDeg = 180.0, ownSpeedMps = 5.0)
assertEquals("North in", riding.ownApproach?.approach?.lane?.name)
assertEquals(28.0, riding.ownApproach!!.distanceToStopLineM, 0.1)
// Same place, riding north: that is the North-out lane's direction, an egress lane, no light
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.75), 0.0, 5.0).ownApproach)
// Standing still: heading is not trusted, the nearest ingress lane wins
assertEquals("North in",
TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.0), 0.0, 0.0).ownApproach?.approach?.lane?.name)
// West of the intersection, riding east: West in
assertEquals("West in",
TrafficLights.join(benchSpat, bench, benchPoint(-1.75, -30.0), 90.0, 4.0).ownApproach?.approach?.lane?.name)
// Inside the intersection, past the stop line: no approach
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(5.0, -1.75), 180.0, 5.0).ownApproach)
// Far away
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(400.0, -1.75), 180.0, 5.0).ownApproach)
}
@Test
fun `recorded road intersections - every signalled exit finds its SPATEM movement`() {
var exits = 0
val missing = mutableListOf<String>()
for (map in maps.distinctBy { it.key to it.revision }) {
val spat = spats[map.key to map.revision]
assertNotNull("no recorded SPATEM for ${map.key} rev ${map.revision}", spat)
val light = TrafficLights.join(spat, map)
assertFalse(light.revisionMismatch)
assertTrue("${map.key}: no signalled approach", light.approaches.isNotEmpty())
for (approach in light.approaches) for (exit in approach.exits) {
exits++
if (exit.movement == null) missing += "${map.key} lane ${approach.lane.laneId} group ${exit.connection.signalGroup}"
}
}
println("TrafficLightsTest: $exits signalled exits, unmatched: $missing")
// The one gap on record: 3/165's MAPEM names a group 65 that its SPATEMs never carry.
assertTrue("only 3/165 group 65 may be missing, got $missing", missing.all { it.startsWith("3/165 ") && it.endsWith(" group 65") })
assertTrue("exits checked: $exits", exits > 300)
}
@Test
fun `geometric turn agrees with the maneuver wherever a recorded connection carries one`() {
var compared = 0
val disagreements = mutableListOf<String>()
for (map in maps.distinctBy { it.key to it.revision }) {
for (approach in TrafficLights.join(null, map).approaches) for (exit in approach.exits) {
val stated = exit.connection.maneuver?.single() ?: continue
if (stated == Turn.U_TURN) continue
compared++
val geometric = TrafficLights.geometricTurn(map, exit.connection, approach.bearingDeg)
if (geometric != stated) disagreements += "${map.key} ${approach.lane.laneId}->${exit.connection.toLane}: $stated vs $geometric"
}
}
println("TrafficLightsTest: geometric turn vs stated maneuver: ${compared - disagreements.size}/$compared agree; $disagreements")
// The fallback only decides connections without a maneuver; it has to be right nearly always.
assertTrue("compared $compared", compared > 100)
assertTrue("${disagreements.size}/$compared disagree: ${disagreements.take(10)}", disagreements.size * 20 <= compared)
}
@Test
fun `two revisions on air - the SPATEM's revision picks the MAPEM`() {
val both = maps.filter { it.key == "1/1" }.distinctBy { it.revision }
assertEquals(listOf(2, 3), both.map { it.revision }.sorted())
assertEquals(2, TrafficLights.pickGeometry(both, 2)?.revision)
assertEquals(3, TrafficLights.pickGeometry(both, 3)?.revision)
assertEquals(both.last(), TrafficLights.pickGeometry(both, 9))
// The wrong pairing is flagged
assertTrue(TrafficLights.join(spats.getValue("1/1" to 2), both.single { it.revision == 3 }).revisionMismatch)
}
@Test
fun `SPATEM without MAPEM still gives a light, just without lanes`() {
val light = TrafficLights.join(benchSpat, null)
assertEquals("-1/23", light.key)
assertTrue(light.approaches.isEmpty())
assertNull(light.ownApproach)
}
}
@@ -11,11 +11,9 @@ import org.junit.Test
* ## Where the expected bytes come from
* asn1tools 0.167, compiling the ETSI modules vanetza-idf ships (asn1/release2:
* TS102894-2v241-CDD.asn, TS103300-3v231/VAM-PDU-Descriptions.asn and its motorcyclist container),
* encoding the same values as a Python dict: the same toolchain Niklas Dathe's reference VBS
* encoding the same values as a Python dict: the same toolchain the colleague's reference VBS
* (microbu-esp32c5/station-link/python/microbu_link/vbs.py) builds its VAMs with. Station
* 0x12345678, fix at Unix ms 1790170000123 (generationDeltaTime 50819: TimestampIts mod 65536 with the
* 5 leap seconds since 2004, TAI per TS 102 894-2 V2.5.1; regenerated 2026-10 through asn1tools from the
* earlier UTC-based vectors with 45819, every other bit unchanged), 53.5546667 N
* 0x12345678, fix at Unix ms 1790170000123 (generationDeltaTime 45819), 53.5546667 N
* 10.0223889 E, 5.43 m/s, heading 123.4 deg, -1.26 m/s^2; every confidence and the altitude
* unavailable, as the encoder sends them.
*/
@@ -38,7 +36,7 @@ class VamUperCodecTest {
@Test
fun `VAM with the low-frequency container matches asn1tools`() {
assertEquals(
"031012345678c683400aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f322220",
"031012345678b2fb400aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f322220",
VamUperCodec.encode(content(includeLowFrequency = true)).hex(),
)
}
@@ -46,7 +44,7 @@ class VamUperCodecTest {
@Test
fun `VAM without the low-frequency container matches asn1tools`() {
assertEquals(
"031012345678c683000aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f30",
"031012345678b2fb000aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f30",
VamUperCodec.encode(content(includeLowFrequency = false)).hex(),
)
}
@@ -54,7 +52,7 @@ class VamUperCodecTest {
@Test
fun `unknown accuracy encodes the confidence ellipse as unavailable`() {
assertEquals(
"031012345678c683000aac85a15b8a18ec8fffffff08eddd0f8002697e087ff24f30",
"031012345678b2fb000aac85a15b8a18ec8fffffff08eddd0f8002697e087ff24f30",
VamUperCodec.encode(content(includeLowFrequency = false, accuracyM = null)).hex(),
)
}
@@ -1,121 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import kotlin.math.cos
import kotlin.math.sin
/**
* The yaw rate must be the rotation about the true vertical whatever way up the phone is, which is
* what the old z-axis reading got wrong for anything but a phone lying flat, screen up.
*/
class YawRateEstimatorTest {
private val g = 9.81f
private val ms = 1_000_000L
private val radToDeg = 180.0 / Math.PI
/** Feeds [up] (a unit vector, device frame) as gravity and a pure yaw of [ccwRadPerSec] about it. */
private fun YawRateEstimator.yawAbout(up: DoubleArray, ccwRadPerSec: Double, startNanos: Long, samples: Int = 5) {
onGravity((up[0] * g).toFloat(), (up[1] * g).toFloat(), (up[2] * g).toFloat(), startNanos)
for (i in 0 until samples) {
onGyro(
(up[0] * ccwRadPerSec).toFloat(),
(up[1] * ccwRadPerSec).toFloat(),
(up[2] * ccwRadPerSec).toFloat(),
startNanos + i * 20 * ms,
)
}
}
@Test
fun `flat phone, left turn, is negative in the clockwise-positive convention`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
// 0.5 rad/s counter-clockwise = turning left = -28.6 deg/s clockwise-positive, as the old z-axis path gave.
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
}
@Test
fun `handlebar tilt does not shrink the yaw rate`() {
// Phone tilted 50 deg toward the rider about its x axis: up is (0, sin 50, cos 50) in the device frame.
val tilt = Math.toRadians(50.0)
val up = doubleArrayOf(0.0, sin(tilt), cos(tilt))
val est = YawRateEstimator()
est.yawAbout(up, 0.5, 0L)
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
// The z axis alone would have read only cos 50 = 64 % of it.
assertEquals(0.643, up[2], 1e-3)
}
@Test
fun `upright phone, where the z axis reads nothing, still gives the yaw rate`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 1.0, 0.0), -0.3, 0L)
assertEquals(0.3 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
}
@Test
fun `rotation about a horizontal axis is not yaw`() {
// Flat phone pitching about its x axis, as on a bump: no yaw at all.
val est = YawRateEstimator()
est.onGravity(0f, 0f, g, 0L)
for (i in 0 until 5) est.onGyro(1.0f, 0f, 0f, i * 20 * ms)
assertEquals(0.0, est.yawRateDps(80 * ms)!!, 1e-9)
}
@Test
fun `averages over the window ending at the newest sample`() {
val est = YawRateEstimator(windowNanos = 100 * ms)
est.onGravity(0f, 0f, g, 0L)
est.onGyro(0f, 0f, 10f, 0L) // 300 ms before the newest: outside the window
est.onGyro(0f, 0f, 0.2f, 220 * ms)
est.onGyro(0f, 0f, 0.4f, 260 * ms)
est.onGyro(0f, 0f, 0.6f, 300 * ms)
assertEquals(-0.4 * radToDeg, est.yawRateDps(300 * ms)!!, 1e-3)
}
@Test
fun `no yaw rate before gravity is known`() {
val est = YawRateEstimator()
est.onGyro(0f, 0f, 0.5f, 0L)
assertNull(est.yawRateDps(0L))
}
@Test
fun `no yaw rate once the gyroscope has gone quiet`() {
val est = YawRateEstimator(staleNanos = 500 * ms)
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
assertNotNull(est.yawRateDps(500 * ms))
assertNull(est.yawRateDps(600 * ms))
}
@Test
fun `gyroscope samples are dropped against a stale up direction`() {
val est = YawRateEstimator(staleNanos = 500 * ms)
est.onGravity(0f, 0f, g, 0L)
est.onGyro(0f, 0f, 0.5f, 900 * ms)
assertNull(est.yawRateDps(900 * ms))
}
@Test
fun `a gravity sample too weak to give a direction is ignored`() {
val est = YawRateEstimator()
est.onGravity(0f, 0f, 0.5f, 0L)
est.onGyro(0f, 0f, 0.5f, 0L)
assertNull(est.yawRateDps(0L))
}
@Test
fun `reset forgets the up direction and the samples`() {
val est = YawRateEstimator()
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
est.reset()
assertNull(est.yawRateDps(80 * ms))
est.onGyro(0f, 0f, 0.5f, 100 * ms)
assertNull(est.yawRateDps(100 * ms))
}
}
@@ -1,37 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.cam.CamParser
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps] is positive clockwise. The CiT One's CAM topic
* is positive to the left (documented, and 316 of 316 turning samples in the logged runs), so
* [CamParser] flips it. Its `obu_gnss` topic is documented as left-positive too, but the logs show
* it positive to the right (27 of 27), so [ObuGnssParser] keeps it.
*/
class YawRateJsonSignTest {
@Test
fun `CAM topic - positive is a left turn, so it becomes negative`() {
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02,
"yawRate_dps": 15.0}"""
assertEquals(-15.0, CamParser.parse(json, ownStationId = null)!!.yawRateDps!!, 1e-9)
}
@Test
fun `CAM topic - a missing yaw rate stays unavailable`() {
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02}"""
assertNull(CamParser.parse(json, ownStationId = null)!!.yawRateDps)
}
@Test
fun `obu_gnss - yawRate_degps is read as it is, since the CiT One sends it right-positive`() {
// own_info as in Listing 2.1, with the position placed where this parser reads it.
val json = """{"own_info": {"stationID": 1345678, "stationType": 2,
"latitude": 53.55, "longitude": 10.02, "yawRate_degps": -7.5}}"""
assertEquals(-7.5, ObuGnssParser.parseEgo(json)!!.yawRateDps!!, 1e-9)
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -1,17 +0,0 @@
-1/23 1 020418ff6ed745a2a1018000b8104005a2a1d3d501001143710e390e390e3fa238876c876c876fc00850dc413641364137e88e20af20af20aff0
1/1 2 020400ff3b6241ae52018800080008202001ae527c060220100020004002001c8080000003203000200100050018
1/1 3 020400122a7441ae53018800080008302001ae53104e0f201646703e803f203ed724381fb820081fe390dc12481270125de88e092e09420938f467058205cd05af6a4382c882ee02df350dc18c419f01979c4006001a007101322b81f401f901f6b91dc0fdc10040ff1c86e09240938092ef447049704a1049c7a2b82c102e682d7b51dc1644177016f9a86e0c620cf80cbce0000480d915c0e880e9c0e9d68ee0762076c076cb4370492049c04977a23824b8250824e3d15c152c173415a588ee0ab40bb80af0c437064006c2065e680032408c8ce0744074e074eb48703b103b603b65a1b8249024e024bbd11c125c12841271e8ce0a960b9a0ad2c487055a05dc0578621b83200361032f34800f00400112056437040b0415041072238208020d020ab915c119411bc11a9c8ee08e808fc08f2e437058c059605917a2382c882cd82cb3d15c179817c017adec009002600a003400d803800e903321b8203020a82083511c102c10681055a8ae08c008de08d4e477046f047e0479721b82c382cb02c8bd11c1630166c1659e8ae0bc20be00bd6f700080030010006001c008002800b20764370406041504106a238205820d020ab519c118011bc11a9c90e08de08fc08f2e4370587059605917a2382c602cd82cb3d19c178417c017ade0002904321b8205820a82083911c104010681055c8ce08ca08de08d4e4870474047e0479721b82c602cb02c8bd11c1644166c1659e8ce0bcc0be00bd6f00024824d0dc100410181019c8ce087a08840884e4370569056e056e7a3382d282d502d53c001520a34370401040b04067233823282378235390dc1644166c1659e8ce0bea0bfe0bf4f0005882cd0dc1004102c1019c8ce08f2090608fce43705a505af05aa7a33830e831383113c001720c343703fc041004066a3382170221021c390dc156815b81591e8ce0b180b400b2cf00060834d0dc101810541041a8ce0870088e0884e43705640573056e7a3382cb02d282d03c001e20e3437040b041004107233823c823f023f3d0dc169416a816a9e8ce0c260c3a0c30f0007c83cd0dc102c10681041c8ce08de08fc08e8e437059b05aa05a07a3382ff830703023c00202103437040b041a041072338223822b0226390dc15cc160815e1e8ce0b5e0b7c0b68f00084
1900/2396 3 02040000302941ae6701883b604ae0302001ae67949c1120164371bda1bda1bda7a238def8def8defbd19c728872887289e90e396239623962f4371d9c1d9c1d9c7a238ed08ed08ed0bd19c799079907991e400d803800e901321b8ded0ded0ded3d11c6f7c6f7c6f7de8ae394439443944f4771cb11cb11cb17a1b8ece0ece0ece3d11c768476847685e8ae3cc83cc83cc8f2007801f009880dd1dc6f046f046f05c86e398039b239a8e4471cc51cde1cd9722b8ead8eba0eb7b91dc75a8760c75f9c86e3d043d363d2cf4471e871ea01e9b7a2b8f8e8f9b0f98bc402000dc811d21c6f046f046f05c86e398039b239a8e4471cc51cde1cd972338ead8eba0eb7b921c75a8760c75f9c86e3d043d363d2cf4471e871ea01e9b7a338f8e8f9b0f98bc4021008881590dc6f686f686f69c88e37be37be37bee4571cac1cac1cac7a3b8e5d8e5d8e5dbd0dc767076847671e88e3b423b4c3b42f4571e6e1e731e6e788046012903321b8ded0ded0ded3911c6f7c6f7c6f7dc8ce395839583958f4871cbb1cbb1cbb7a1b8ece0ed08ece3d11c768476987685e8ce3cdc3ce63cdcf0009081dd21c6f046f046f05c86e397639b239a8e4471cc01cde1cd972338eab0eba0eb7b921c7594760c75f9c86e3cfa3d363d2cf4471e821ea01e9b7a338f8c0f9b0f98bc402700d8821d1dc6f046f046f05c86e397639b239a8e4471cc01cde1cd9722b8eab0eba0eb7b91dc7594760c75f9c86e3cfa3d363d2cf4471e821ea01e9b7a2b8f8c0f9b0f98bcc02800a403800e4824018002b20a005000a882cd0dc73007378733dc8ce3a703aac3a8ee4371e641e821e7372338f6e0f7d0f75bc002c20c34671bb71bb71bb77a1b8e678e678e67bd19c75e475e475e5e86e3d223d223d22f000b4834d0dc73147350733dc8ce3a7a3a983a8ef4371e691e781e737a338f708f780f75bc002e20e34671bb71bb71bb77a1b8e678e678e67bd19c75e475e475e5e86e3d223d223d22f000bc83cd0dc6f686f686f69c8ce38fe38fe38fef4371d971d9c1d9c7a338f1e0f208f20bc403000c4840024003221134371bda1bda1bda72338e3f8e3f8e3fbd0dc767076707671e8ce3c823c823c82f000cc848d0dc731473787365c8ce3a8e3ac03ab6e4371e731e8c1e877a338f7a8f870f84bc403400d40
3/120 1 0204000177d341ae480188001803c0102001ae48e320032010062002000900148080184006001c80c00c4001000881000c40030010
3/121 4 0204001233b441ae520188001803c8402001ae527d6b032016467032f0424039d2a43819f021981d6150dc0ed812ac1091088e077609600852846703f705dc04fb3a43820302f582851d0dc120c19a0161d020008004404c8ae065e0848073a5477033e043303ac2a1b81db025582122111c0eec12c010a508ae07ee0bb809f67477040605eb050a3a1b8241833402c3a04003001480d919c0cbc10900e74a90e067c08660758543703b604ab0424422381dd82580214a119c0fdc177013ece90e080c0bd60a1474370483066805874080080031021a1b81a6821201d89919c0dfc11580f8ce86e08200b0409f69467044205b9052d48801800680
3/165 1 020400ffef5d41ae68018800180528102001ae6841f20c20134671c8e1cca1cb63a1b8e790ee70ea61d19c75bc7be87800e86e3bf6404c3e58800004808d15c7238732872d8e86e39e43b9c3a9874571d6f1efa1e003a1b8efd90130f96204002001880cd0dc72b0738c733d28ce39943b1a3a4864371d9c1eb91e2d4a338eee8fd70f7fa4800c003400e20434371cac1cf21cd94a2b8e6a0ed08e97190dc76847b3478dd28ae3bce3f983e2690003c814d0dc72b073c8736528ce39a83b423a5c64371da11ecd1e374a338ef38fe60f89a48010004401620634571c8e1cca1cb63a1b8e768ee48ea39d15c75bc7bd47800e86e3bec40423e44820048013005081cd19c7238732872d8e86e39da3b923a8e74671d6f1ef51e003a1b8efb10108f912040040014820d15c7238732872d8e86e39e43b9c3a9874571d6f1efa1e003a1b8efd90130f9620001520934671c7a1cbb1ca22a1b8e768ee70ea61d19c756c7bc077b0c86e3bec40383e3080001c828d0dc72c473b4736528ce399e3b2e3a4864371da61ec31e374a338eee8fd98f84a4000820b34371d1a1d921d4752338ebf0f2a8ee7250dc7a087e047be968ce3dc2407e3ebca1002800b20c34371ca71ce81ccf4a338e650ec90e92190dc76707af878b528ce3bb03f663dfe91005c01820d34371d241d8d1d5152338ebf0f258ee7250dc7a307ddc7be968ce3dc240563ea8a1006401a
3/1745 3 0204001232f841ae52018800183688302001ae5284e303201646703a20429041f524381d8821c0217290dc106812ac1285688e083e0960094cb46704ec05dc05d25a43827d82f582f0ad0dc15a4198c1965820008004404c8ce074e0852083ea48703b60438042e521b820f82558250ad11c109012c0129968ce09e20bb80ba4b487050005eb05e15a1b82b70331832cb04003001080cd0dc0f1410a410a568ce082008fc08fcc437050505aa05aa623382a802ff82ffb0400b0034810d0dc0f1410a410a568ce07da08b608b6b437050a058705876a33829902dc82dcb4400c0038
3/2052 3 020400ffb03a41ae58018800184020302001ae583e860c201643709ff8a228a09da2385024513c5076d15c288a291628b388ee146314a91477c4370acc8b6c8aead2238568c5b8c577e915c2bbe2e3e2c37420038010404c86e13ff14451413b4470a048a278a0eda2b85114522c516711dc28c6295228ef886e159916d915d5a4470ad18b718aefd22b8577c5c7c586e88009002800b203645709e689f589ebe23b84fac50244fd710dc2952298e2967c88e14b314d114bde4570ab38b948ac2c23b856145d1c568e10dc2c9a301e2cd720003102323384f344fac4f5f121c27d6281227eb886e14a914c714b3e4470a598a688a5ef2338559c5ca45616121c2b0a2e8e2b47086e164d180f166b910010005205646709eb89fa89f5e24384fd4504c502710dc293e29a2298fa88e14a914db14d1d4670aae8b998ac7c243855ec5d4456b610dc2c4a30322ceb2400100020019031a3384f344fac4f5f10dc2902293e2917c8ce156716f7158f84370b0d8bd58b21d0801c0079039a3384f344fac4f5f10dc2902293e2917c8ce156716f7158f84370b0d8bd58b21d00020410686e13f5143b1409b4670a278a4a8a31e21b8563c5bb4572e519c2bd22ea22c4b420098024412686e13f5143b1409b4670a278a4a8a31e21b8563c5bb4572e519c2bd22ea22c4b4200a002a414686e141314591431c4670a318a5e8a4ae21b856645c5457ce519c2bbe2ef22caf4200b002e416686e141314591431c4670a318a5e8a4ae21b856645c5457ce519c2bbe2ef22caf4200c003241868ce13eb141d1409c4370a458a5e8a54ea33856145c5456de50dc2c4a2f6a2caf4200d003641a68ce13eb141d1409c4370a458a5e8a54ea33856145c5456de50dc2c4a2f6a2caf4200e003a0
3/2349 5 0204001225f441ae65018800184968502001ae657ef30e201645719b41a6819eb3a3b8ce18d3b8cfd1d0dc698c6d386a69288e34d036a6353e94571aea1c7f1bad4a3b8d7c8e470dde250dc6e7875a8718520002101322b8cd50d340cf3191dc66e469dc67d4c86e34b2369c353494471a5e1b531a9f4a2b8d700e3f8dd4251dc6bbc72386edd286e37283ad438c290001c80d90dc6798698c68b1488e33d634d03462a4571a451afe1a90523b8d2a0d868d4fa90dc6c7070946edd688e364238543778b4571b801cc01c1b50801000490232338cd50d340cf31921c66e469dc67d4c86e34b2369c353494471a5e1b531a9f4a338d700e3f8dd42521c6bbc72386edd286e37283ad438c2910018005205646719b41a6819eb3a438ce18d3b8cfd1d0dc698c6d386a69288e34d036a6353e94671aea1c7f1bad4a438d7c8e470dde250dc6e7875a8718522001000640cc86e33cc34c63458a44719eb1a681a31522b8d228d7f0d48291dc69506c346a7d486e3638384a376eb4471b211c2a1bbc5a2b8dc00e600e0da8000a207343719dc1a681a2c4a338d098d4f8d31a90dc6c5c6f2c6e3d88ce369c3804378cc1003400e208343719e11a681a2c4a338d098d4d0d2f290dc6c5c6f186e2988ce369237f03778c1003c020209343719e11a681a314a338d1d8d638d45ad0dc6c5c6fcc6edd68ce36ec38a4382cc00040828d19c66f869a067d4e86e34bc3728352a74671af41cc01bb2421b8dca0ef60e2920001120b346719821a6819b41a1b8d2f0dca0d481d19c6ae073006dc4e86e37283bd8389a81004801320c346719be1a6819f53a1b8d2f0dca0d4a9d19c6bbc73006ec9086e371e3bd838a4800050834d19c660869a066d0686e34bc3728352074671ab81cc01b713a1b8dca0ef60e26a0000b20e346719be1a6819f53a1b8d2f0dca0d4a9d19c6bd073006ec9086e37283bd838a480003083cd0dc678469a068c548ce3480358e3520b4371b171bf31bbc5a338dbb0e290e0db0001f
3/2394 4 0204001230ec41ae65018800184ad0402001ae65ce4f0b20164671a181acc1a7c42438d138d6d8d45a10dc6b1c6dec6cad488e359837003660a4671b671cac1c4352438dbb0e5d8e29290dc706c758073dd62002000a404c86e346c358e355ca4471a3b1acc1ab3522b8d4f8d980d8bad1dc6ab86cfc6c99686e370038ae387cc4471b851c5c1c43622b8df48e600e53b0400c003880d90dc68ec6b1c6ab9488e348035983566a4571aa41b301b175a3b8d598d9f8d932d0dc6e14715c70f9888e371438b83886c4571bee1cc51ca760800e004102321b8d250d638d63ad11c693c6b306b3168ae3502366a35fca4771a901b441b0d521b8da98e2e0e12ad11c6d60718470a968ae3714399438b8a00018815919c689c6b30693ce90e346c35b634bc74371aa41bf31afe3a238d548dfc0d819d19c6c5c7490701d090e364c3a66382c84371b9e1e501d06408006001103322b8d138d660d279d1dc68d86b6c6978e86e354837e635fc74471aa91bf81b033a2b8d8b8e920e03a11dc6c9874cc7059086e373c3ca03a0c80000481cd19c67d46b30689c886e352a37f035fc74671ae51d241be43a1b8dc28f280e7e20000a208346719f51acc1a27221b8d4a8dfc0d7f1d19c6b9474906f90e86e370a3ca039f881004401220934371a401acc1ab352338d4f8d980d8bad0dc6e147170710d88ce37d2398a394ec0004c828d0dc68c46b306ab928ce34c635fc35c0a4371b801c2a1c0c62338dd90e308e1f30001420b34371a401acc1ab352338d520d980d8bad0dc6e287170710d88ce37dc398a394ec00054830d0dc69006b306ae148ce34ee360635deb4371b8a1c2f1c1b62338de08e330e29300016
3/2421 3 020400ffa9ca41ae58018800184ba8302001ae58ac220920164670aa50afa0ad75243855a05848573290dc2d282f442ddd688e169e17ac16f8b4670c170d020c995a438613068886542d0dc3304378c350d620008004404c8ce154a15f415a494870ab40b090ae14a1b85a785e885be2d11c2d502f582e0568ce182e1a041928b4870c260d110ca35a1b866306f186a1ac4003001080d915c2a942be82b4928ee1568161215c294370b4f0bd10b7c5a2385aa05eb05c0ad15c305c3408325168ee184c1a221946b4370cc60de30d4358000a408c86e159a164e15f4a4470ad20b2c0aff522b859b05dc05b1ad1dc2d142f1c2dc9686e187e19be1914c4470c440ce40c8f622b865406ba8679b04006001c815915c2a942be82b5d48ee1568161215cca4370b4a0bd10b775a2385a785eb05be2d15c305c3408326568ee184c1a221950b4370cc10de30d43588010004903321b85668593857d2911c2b482cb02bfd48ae166c177016c6b4770b450bc70b725a1b861f866f86453111c31103390323d88ae19501aea19e6c1002800b20734370ac80b270aff5233857f85af059b2d0dc30ac32283189a8ce18c419821932d1003401620834370ad20b270aff5a33859b05c585b1b10dc312432dc323da8ce195a1a3619e6d1003801520934370ad20b270aff5a33858985b405a02d0dc30fc325031b1a8ce190019aa195ad1003c01020a34670a7d0ad70aa0421b85a505fa05b92919c2f9434803175286e19641c8e1a5ea100440120
3/2422 3 02040012453c41ae5b018800184bb0302001ae5b0fa80320164370d390d4d0d486223869f06a906a6b119c377839f839e5690e1bda1d1a1d10b4370e650f0a0f006223873507878782b119c3c1440ec40c5620008004404c86e1a7c1aa41a86c4470d430d570d48623386f18741873a2d21c37c83a483a0d686e1cd41e141df6c4470e6f0f0f0f0062338787881d88162c4003001080cd19c349434e434bd686e1bf81cca1cb6c4670e4c0ef10eb05a1b8791880e87ee2c40090034810d19c33e0343033f4686e1bd01c701c52c4670e100eba0e51521b878787f307beac400a0038
3/2423 3 020400ffaf5241ae5c018800184bb8302001ae5cb68a0a20164670fc810220ff55a4387eb881888022d0dc41b443e442a5888e20e421fc215cc46710f4122a11b75a438881891c88e32d0dc46784c0449c162002000a404c8ae1f9020441feab4770fd7103110045a1b8836887c8854b111c41c843f842b988ae21e82454236eb4771103123911c65a1b88cf098089382c000620364670fb910220ff55a4387e4081888022d0dc416443d04291688e20bc21f22152b46710e5122511b25243887a091a08e0a90dc46284bdc4999620038006408c8ae1f7220441feab4770fc8103110045a1b882c887a08522d11c417843e442a568ae21ca244a2364a47710f4123411c1521b88c5097b89332c4008004c81590dc3fd440744075a88e1ff420442044d457105910b31090623b88340861084fb10dc44ac476846dd888e226023be2378c457118a1270122a60001240cc86e1fea203a203ad4470ffa102210226a2b882c88598848311dc41a04308427d886e225623b4236ec447113011df11bc622b88c50938091530400a002c904000001420734370fff102210226a33882008390839350dc44c046784679a8ce22e223dc23dcd1003400e20834670f8710220fdc4a1b8820088688522919c42cc48e44665286e22d8263e24c2a1003c01020934370ffa102210226a33881608318831b50dc44c0463c463da8ce22ba23a023a0d1004401220a34370ffa102210226a33881608318831b50dc44c0463c463da8ce22ba23a023a0d000300
3/2429 1 020400ffbb1741ae68018800184be8102001ae6842870420134671d471da11d97621b8ef38f208f1bb119c7b0c7db47d65886e3ec6401a3ff2d1000400220334671d471da11d97621b8ef38f208f1bb119c7b0c7db47d51886e3ec6401a3fe8d0000c810d0dc75807684768588ae3b923c143c14d4371ee11f361f366a2b8fa50fcf8fcfb840040014814d0dc75a876847671a8ae3b383ba63b9cd4371ec81eff1efa722b8f7d0f988f96384006001c808d15c751c7684765d886e3bce3c823c6ec4571ec31f6d1f54621b8fb190068ffa340008
3/256 1 02040012346c41ae52018800180800102001ae527bf719206646703ca03ed03e36a4381ec81fe01f9350dc122012ac1285c88e091a0960094ce467058705dc05a5724382cb02f582da390dc19281a7c19a1c60008004001800840ec8ce077607c607b2d48703ca03f203e86a1b823f0253024e3911c120c12ac1285c8ce0af00bae0b36d487058705e605aa6a1b8320034f8331b88005001800720d645703bb03e303d96a3b81e501f901f4350dc11f812981271c88e090609560942e457057805d7059b6a3b82c382f302d5350dc19001a7c198dc0004100b21b81fe02058205b911c100410401041c8ae085c08e808acc477043d04830465621b82aa82cd82beb911c156816801609c8ae0b0e0c080b86d3002400a002c00c202643703fc040b040b72238200820802083915c10b811d0115988ee087a090608cac4370555059b057d722382ad02d002c13915c161c1810170da4006801c007904321b81fb82058205b911c0ff010401041c8ae085208e808acc477043804830465621b82a802cd82beb911c155416801609c8ae0b040c080b86d20040011004883990dc0fdc102c102dc88e07f808200820e457042904740456623b821c02418232b10dc1540166c15f5c88e0aaa0b400b04e4570582060405c369802600a002a00b101b21b81fe02058205b911c100410401041c8ce085c08e808acc487043d04830465621b82aa82cd82beb911c156816801609c8ce0b0e0c080b86d0005c824d0dc0fdc10401019c8ae08ca08fc08e8e437059105aa05a0722b82ff830e83073c001820a343703f204060401722b8223822d822b390dc15cc161c1609e8ae0b900bb80baef0006482cd0dc0fa010681019a8ae083e08a2087ad437054b057d0569722b82c102da02d038001a20c343703ed041504066a2b8237824b8244390dc166c170c16d1c8ae0c3a0c8a0c6ce0006c854d0dc0fc8107c102da8ae08c0091a08f2e437058c05b905a5722b82fd03138309b8001c216343703ed041504016a2b82148228821eb50dc155415f415a5c8ae0b220b720b4ae0007485cd0dc0fb4107c102da8ae083e08a2087ad437054b057d0569722b82bc02d782cdb8001e218343703f70410040b722b822d823a0237b90dc161c1680166dc8ae0bd60c080bfef0007c864d0dc0fb4107c102da8ae083e08a2087ad437054b057d0569722b82bc02d782cdb8002021a343703f2041f040b6a2b82300246823cb90dc163016e41695c8ae0bf40c4e0c26e00084810d15c0f140fdc0f79886e087a094c08dec457055005d2059b6a1b82e403408313b04022008c814d15c0f140fdc0f79886e087a094c08dec457055005d2059b6a1b82e403408313b0002420f0060009484001800262110060009c8480180028213345703d403f703ed6a1b82260253023f3115c157c174816a9a86e0bae0d020c6cc000a4850d15c0eb00f780f15886e0898096a08fcc457053705e1058c621b82eb835c031db0002a0
4/937 4 0204000161d341ae53018800201d48402001ae53853215201005000048080184002000c80c0144004004c81000c8005002000a20500310018007206003100240142070030002c82000c000c2090031003401520a0061003800f20b0031004001120c0060004883400c001620e0062005c01800b483c00c8019006802e2100062006c01c00bc84400c801d007802c2120061007c020213006100840222140032008c02400c0854018802500980292160063009c02800a802b
@@ -1 +0,0 @@
02044149af94472d8803872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c10200396c474a3823310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966670b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966670ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e000018028191859796cd3bb2f241537f241cb4e7d1d009d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966570b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966570ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e01001c02819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb33856485648564bc5c28b804b388a700966770add0add0add78b851700967114e012cc6e179a179a179af170a2e012ce229c025991c2f5c2f5c2f5de2e145c0259c453804b333861886188618bc5c28b804b388a700966770c450c450c4578b851700967114e012cc6e1a6a1a6a1a6af170a2e012ce229c025991c34fc34fc34fde2e145c0259c453804b03c06002805031f2f7ecc597967e7d3920e5a73e8e808ecae159215921592f170a2e012ce229c02599dc2b742b742b75e2e145c0259c453804b31b85e685e685e6bc5c28b804b388a700966470bd70bd70bd778b851700967114e012ccae186218621862f170a2e012ce229c02599dc311431143115e2e145c0259c453804b31b869a869a869abc5c28b804b388a700966470d3f0d3f0d3f78b851700967114e012c0f0100140140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b85aa85aa85aabc5c28b804b388a700966470b5f0b5f0b5f78b851700967114e012ccce177217721772f170a2e012ce229c02599dc2f342f342f35e2e145c0259c453804b31b865e865e865ebc5c28b804b388a700966470cc70cc70cc778b851700967114e012ccce1a421a421a42f170a2e012ce229c02599dc34d434d434d5e2e145c0259c453804b0bc0800400503c0a00480500
@@ -1,4 +0,0 @@
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
+47 -85
View File
@@ -1,24 +1,21 @@
# 06 – Signed ITS messages, VAM and the BLE link (2026-09-23, firmware part updated 2026-11-10)
# 06 – Signed ITS messages, VAM and the BLE link (2026-09-23)
What changed when the ESP32-C5 OBU moved onto Niklas Dathe's station, how the pieces
fit together, how it was verified, and what is still open. Since 2026-11-10 the firmware is built on
Niklas Dathe's newer `microbu-firmware` layout (link spec revision 2, `obu-firmware/docs/station-link.tex`);
the parts below that describe the earlier vanetza-idf port say so. Hardware checks still to do are in
What changed when the ESP32-C5 OBU moved onto the colleague's vanetza-idf station, how the pieces
fit together, how it was verified, and what is still open. Hardware checks still to do are in
`TODO.md` ("Signed-TX firmware ...").
## Summary
- **Signing lives on the ESP32-C5.** The authorization ticket's private key is in the board's NVS;
the station's security entity signs every secured message there (IEEE 1609.2 / ETSI TS 103 097,
vanetza-idf's security entity signs every secured message there (IEEE 1609.2 / ETSI TS 103 097,
ECDSA NIST P-256). The phone never holds a key and never signs.
- **The phone decides what to send and when.** It builds CAM or VAM (UPER) from its own GNSS/IMU,
hands each message to the board with the flag "signed" or "unsigned", and keeps the board's clock
and position current.
- **Two links, one protocol.** USB-C (native USB Serial/JTAG) or Bluetooth LE, chosen in Settings.
Both carry Niklas Dathe's station-link protocol (revision 2 of the spec adds the MicrOBU extensions: `V2X_RX`, unsigned sending, battery guard).
Both carry the colleague's station-link protocol v1 plus one MicrOBU extension for reception.
- **Reception is unchanged for the app.** Every ITS message heard on air reaches the phone, signed
or not, verifiable or not, exactly as with the previous firmware. Since 2026-11-11 the app can instead take the spec's
`RAW_FRAME` debug capture and unwrap it itself (Settings > Receive path); both paths stay in the firmware.
or not, verifiable or not, exactly as with the previous firmware.
- **Demo PKI, not the EU trust list.** Signed messages carry a throwaway chain. Receivers that
verify against the EU trust list drop them; unsigned sending remains available.
@@ -38,104 +35,67 @@ the parts below that describe the earlier vanetza-idf port say so. Hardware chec
## Firmware (obu-firmware)
obu-firmware is Niklas Dathe's `microbu-firmware` (commit e4e4bd8, HAW GitLab, not part of this
repository; nothing is pushed there) with the MicrOBU additions: `main/`, `components/microbu_v2x`,
`components/vanetza` and the patched `external/vanetza` are copied in unchanged, so obu-firmware builds
from a plain clone. It builds with **ESP-IDF 6.0.2 only**: the raw-TX path uses private Wi-Fi driver
structures that `microbu_v2x` pins to that version. Setup and flashing: `obu-firmware/FLASHING.md`.
Design notes and every deviation from Niklas Dathe's code (`MicrOBU:` in the sources):
`obu-firmware/NOTES.md`. The earlier port (vanetza-idf, 2026-09-23) and the previous C firmware are in
git history (`1c3a66e`, `7285fa1`).
obu-firmware is now a port of `microbu-esp32c5/firmware`, from the colleague's own repository
(not part of this one; nothing is pushed there). The C-ITS library it needs is copied into this
repository as `obu-firmware/external/vanetza-idf` (their commit cf4b99f, unchanged), so
obu-firmware builds from a plain clone. It builds
with **ESP-IDF 6.0.2 only**: the raw-TX path uses private Wi-Fi driver structures that vanetza-idf
pins to that version. The previous C firmware (IDF 6.1) is backed up as a full flash image in
`firmware-backups/` (gitignored, restore command in its README.txt); its sources stay on disk,
unbuilt. Setup and flashing: `obu-firmware/FLASHING.md`. Design notes and every deviation from the
colleague's code (`MicrOBU:` in the sources): `obu-firmware/NOTES.md`.
Main changes against Niklas Dathe's firmware:
Main changes against the colleague's firmware:
- **Raw receive path kept.** The stack decapsulates strictly and would drop unsigned frames (the
bench car) and anything not signed under the demo root (every RSU). Every received frame also
goes through `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (**0x90**; 0x85 is the
spec's RAW_FRAME), whose body is the old `SERIAL_MSG_V2X_RX` payload.
- **Unsigned sending kept.** Niklas Dathe's station refuses unsecured requests; here they go out
with `geonet.c`'s header and a random MAC per configuration.
- **Production board: Seeed XIAO ESP32-C5** (8 MB flash, a single native USB-C port) running from a LiPo
on its BAT pads. The log travels as LOG frames on the USB link (no UART adapter needed).
- **Battery:** the XIAO's divider (GPIO6, enabled by GPIO26) is read every 5 s and reported in STATUS
(`battery_mv`, octets 129-130); the app shows the voltage, a rough percentage and a low (3.50 V) /
critical (3.30 V) warning on the ESP32-C5 card and in the top bar. Below 3.30 V with no phone on USB
the board deep-sleeps, because the prototype cell has no protection board. See `obu-firmware/FLASHING.md`.
- **ATT MTU 517** so that a 494-octet V2X_RX (a 512-octet link message) is not split.
- **BLE and ITS-G5** share one RF front end. Niklas Dathe's TX guard (`CONFIG_MICROBU_TX_BLE_GUARD`)
holds a frame out of the BLE connection-event windows; the earlier "pause advertising while USB is
in use" is gone.
- **Raw receive path kept.** vanetza-idf decapsulates strictly and would drop unsigned frames (the
bench car) and anything not signed under the demo root (every RSU). Every captured frame also
goes through the previous firmware's `gn_unwrap.c` and reaches the phone as link opcode
`V2X_RX` (0x85), whose body is the old `SERIAL_MSG_V2X_RX` payload.
- **Unsigned sending kept.** The colleague's station refuses unsecured requests; here they go out
with the previous firmware's `geonet.c` header.
- **Console on UART0** (CH343, COM3 on the bench); the native USB port carries only link frames.
- **BLE pauses advertising while USB is in use** (BLE and ITS-G5 share one RF front end).
- **NVS 80 KB instead of 24 KB**, app at 0x20000. At 24 KB the BLE bond could not be stored and the
phone had to pair on every connection.
- Fixes carried over from the bench: radio queue drained before the first PoTi; 2.4 KB RX buffer off
the Wi-Fi task stack; serial writes skipped when no USB host is present; manual country policy.
- Fixes found on the bench: radio queue drained before the first PoTi (no RX, ~177 queue drops
before); station loop waited 0 ticks at 100 Hz and starved the idle task; 2.4 KB RX buffer moved
off the Wi-Fi task stack; no silent truncation of BLE notifications; ATT MTU 517; serial writes
skipped when no USB host is present.
## Link protocol
Station-link, revision 2 (`obu-firmware/docs/station-link.tex`; revision 1 is Niklas Dathe's): `[opcode][flags][sequence LE][body]`,
little-endian, at most 512 octets (bodies above that are fragmented by the spec; this app never needs it). Over USB each message is one `0xAA55` frame of type `0x10`
Station-link v1 (colleague's repository, `station-link/README.md`): `[opcode][flags][sequence LE][body]`,
little-endian, at most 512 octets. Over USB each message is one `0xAA55` frame of type `0x10`
(the old framing and CRC). Over BLE each message is one GATT value on service
`0000C175-BA5E-4C17-8000-00805F9B34FB` (the README describes a different, Nordic-UART layout; the
firmware is what counts; the current spec table lists the same UUIDs).
firmware is what counts).
| Direction | Message | Used for |
|---|---|---|
| phone → board | `STATION_CONFIGURE` | station type, channel 180, 20 dBm; the 16-octet form also names the MAC (pseudonym); starts the radio |
| phone → board | `STATION_CONFIGURE` | pseudonym MAC, station type, channel 180, 20 dBm; starts the radio |
| phone → board | `CREDENTIALS_PROVISION` | the demo bundle, once, when the board reports no ticket |
| phone → board | `POTI_UPDATE` | position and ITS time, once per new GNSS fix |
| phone → board | `BTP_DATA_REQUEST` | one CAM (port 2001, psid 36) or VAM (port 2018, psid 638), signed or not |
| phone → board | `STATUS_REQUEST` | once a second; the answer is the heartbeat |
| board → phone | `CONFIRM` | answer to a request; for `STATUS_REQUEST` its detail is the 131-octet snapshot: counters, tickets, signed/refused counts, battery |
| board → phone | `V2X_RX` (0x90, MicrOBU) | every ITS message heard on air |
| board → phone | `RAW_FRAME` (0x85, spec) | debug copy of each radio frame, only while `RAW_CAPTURE` is on; the app can use it instead of `V2X_RX` (Settings > Receive path) |
| board → phone | `RESULT` | answer to a request |
| board → phone | `STATUS` | every second: counters, tickets, signed/refused counts |
| board → phone | `V2X_RX` (0x85, MicrOBU) | every ITS message heard on air |
The app side is `Esp32Link.kt` (session), `StationLink.kt` (codec, pinned by unit tests to bytes
from Niklas Dathe's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
A board still on the previous C firmware is recognised by its old heartbeat and keeps working for
CAM over USB. The pseudonym's MAC goes to the board in the 16-octet STATION_CONFIGURE (which Niklas Dathe's
spec retires but the station still decodes, and revision 2 documents): a ride rotates it with the station ID, the bench CAM
pinger keeps one fixed MAC, and a new MAC reconfigures the station. Without one a signed station takes its address from the
ticket and an unsigned one draws a random MAC per configuration. With one, signed and unsigned frames both leave from it.
Data flow of a received frame, with both paths:
```mermaid
flowchart TB
subgraph Board[ESP32-C5 board]
Air[ITS-G5 frame] --> Radio[Radio, promiscuous RX]
Radio --> Stack[Vanetza: decap, verify]
Radio --> Unwrap[gn_unwrap.c]
Radio -->|RAW_CAPTURE on| Tap[Raw capture tap]
Stack -->|verified| Ind[BTP_DATA_INDICATION]
Unwrap --> Rx[V2X_RX 0x90]
Tap --> RawF[RAW_FRAME 0x85, fragmented]
end
Ind & Rx & RawF --> Link[USB or BLE link]
subgraph Phone[Android app]
Link --> Re[LinkReassembly]
Re --> Sel{Receive path}
Sel -->|V2X_RX| Dec[V2xRxFrame]
Sel -->|Raw frames| Pr[RawFrame, then GnUnwrap]
Pr --> Dec
Dec --> Cod[CAM, DENM, SPATEM, MAPEM, VAM codecs]
Cod --> UI[Use cases, V2X screens, logger]
end
```
The app also **reassembles fragmented link messages** (flags 1-3 of the spec) and has two receive paths: `V2X_RX`
(default) and `RAW_FRAME`, which it unwraps itself with `GnUnwrap.kt`; see the README for the comparison.
from the colleague's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
A board still on the previous firmware is recognised by its old heartbeat and keeps working for
CAM over USB.
## Redundancy and recovery
| Situation | What notices | What happens |
|---|---|---|
| USB link dead (board hung, cable) | app watchdog: no frame for 3.5 s (the app polls `STATUS` every second) | link marked ERROR on the card |
| USB link dead (board hung, cable) | app watchdog: no frame for 3.5 s (the board's `STATUS` comes every second) | link marked ERROR on the card |
| USB unplugged | Android detach broadcast | port closed; Connect again after re-plugging |
| BLE link lost | BLE supervision timeout (4 s) | app reconnects by itself: 1 s after a drop, then backing off to 30 s if attempts fail |
| Board reset / power cycle | first `STATUS` reply says "not configured" | app reconfigures (and re-provisions if needed) without user action |
| Board reset / power cycle | first `STATUS` says "not configured" | app reconfigures (and re-provisions if needed) without user action |
| App closed and reopened | new session | app configures the board again; BLE reconnects with the stored bond, no passkey (confirmed) |
| Phone clock or GNSS time jumping | app tracks the board's clock | PoTi never moves it backwards (except a real correction of ≥ 60 s), so the board does not restart its stack |
| Board firmware wedged | ESP task watchdog (30 s) | the phone sees it as a dead link (above) |
| Board firmware wedged | ESP task watchdog (30 s, logs on COM3) | the phone sees it as a dead link (above) |
## App changes
@@ -151,14 +111,14 @@ The app also **reassembles fragmented link messages** (flags 1-3 of the spec) an
## Credentials (demo PKI)
`app/src/main/assets/demo-chain.vcr`, generated 2026-09-23 with Niklas Dathe's `vidf_issue`: root
`app/src/main/assets/demo-chain.vcr`, generated 2026-09-23 with the colleague's `vidf_issue`: root
`6E7D0374FB021901` → AA `B3312F29844299E0` → AT `B80B49387A4C12EB` (two years; psid 36 SSP `010000`,
psid 638 SSP `01`). It is throwaway and not EU-registered; its private key ships with the app on
purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs.
purpose. The colleague's own demo chain only grants psid 638 and cannot sign CAMs.
## Verification
- **Unit tests** (103): VAM bytes against asn1tools, station-link messages against Niklas Dathe's
- **Unit tests** (103): VAM bytes against asn1tools, station-link messages against the colleague's
Python encoder, VAM generation rules.
- **Signatures on air**: `obu-firmware/test/verify_signed_pcap.py` checks a pcap with asn1tools
and OpenSSL, sharing no code with the firmware. Pinger capture of 2026-09-23: 12/12 signed CAMs,
@@ -166,7 +126,7 @@ purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs
- **Third-party stack**: the CiT One receives the signed CAMs (~1 Hz on `v2x/rx/cam`), so its
stack unwraps our envelope. Its MQTT interface exposes no security information, and it forwards
unsigned and unknown-root messages alike, so it cannot tell whether it verified the signature.
- **V2X2MAP (COM10)**: now Niklas Dathe's v2x2map 0.3.0 bridge from source with a new
- **V2X2MAP (COM10)**: now the colleague's v2x2map 0.3.0 bridge from source with a new
`verify.py` and `--trust demo-chain.vcr`; it shows "signature verified", "SIGNATURE INVALID" or
"not verified" per packet. Signed CAMs and signed VAMs verified live; a one-bit change in a
signed CAM comes out invalid. Launcher: `micrOBU_workspace/v2x-obu-esp32c5/start-v2x2map-signed.bat`.
@@ -176,4 +136,6 @@ purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs
- BLE/ITS-G5 coexistence is not measured: does an active BLE connection cost 5.9 GHz reception?
- `time_regression` standing still indoors for several minutes, and board reset recovery over BLE,
after the last fixes.
- The signature's generationTime follows the app's UTC-based `ItsTime`; the colleague's VBS adds
the 5 leap seconds (TAI). Which is right is the open question in `ItsTime.kt`.
- Real EU PKI enrolment/authorisation (TS 102 941) instead of the demo chain.
-131
View File
@@ -1,131 +0,0 @@
# 07 – Sensor fusion, phase 0 and 1: inputs and logging (2026-11-18)
The goal is a GNSS/IMU fusion filter on the phone that gives the CAM and VAM a fresh position at
every send, plus a better heading, yaw rate and acceleration, on any phone mount. Phase 0 fixed the
inputs the transmit path already had. Phase 1 records everything the filter needs, so the filter can
be built and tuned offline against real rides before it touches what goes on air. Hardware checks
still to do are in `TODO.md` ("Sensor fusion ...").
## Phases
| Phase | What | State |
|---|---|---|
| 0 | Correct inputs: yaw rate about the vertical, fix times on GNSS time, monotonic clock for intervals | done (727c911, sign fix 6fa91d1) |
| 1 | Logging: motion sensors, both phone GNSS sources, clocks, phone mount | done, rides pending |
| 2 | Filter core: 5-state EKF (position, heading, speed, gyro bias), pure Kotlin, replayed on phase 1 logs | next |
| 3 | Any mount: forward-axis estimate, rigidity check, mount-dependent noise | after 2 |
| 4 | Offline tuning: GNSS outage drift, heading vs. course over ground, innovation statistics | with 2 and 3 |
| 5 | Into CAM/VAM, the confidence ellipse and the use-case engine, behind a switch | last |
## Phase 0 in short
- **Yaw rate** is the gyroscope projected onto gravity (`domain/fusion/YawRateEstimator`), the
rotation about the true vertical however the phone is held, averaged over 100 ms, at
`SENSOR_DELAY_GAME`. The gyroscope's z axis alone was only right with the phone flat, screen up.
- **Time on air** is the GNSS time of the fix itself: its monotonic age
(`Location.getElapsedRealtimeNanos`) taken off GNSS time now (`GnssTimeSource.atElapsedRealtime`).
The phone's clock setting, or a step of it, cannot reach the CAM or GN timestamps.
- **Intervals** (elevated CAM rate, VAM generation rules, acceleration from GNSS speed) use the
monotonic clock, so setting the phone clock back cannot hold VAMs off.
- **Yaw rate sign**: the CAM's YawRateValue is positive to the left; the app's `Cam.yawRateDps` is
positive to the right. `CamUperCodec` and `CamParser` flip it; the CiT One's `obu_gnss` sends it
right-positive already (checked against logged rides), so `ObuGnssParser` does not.
## Settings > Ride
Replaces the old Units screen (the app is metric throughout; that switch did nothing).
- **Phone position**: Handlebar, Bag (on the bike) or Pocket (also a backpack). Stored in
`RidePreferences` as `handlebar` / `bag` / `pocket` and written into every V2X log as
`meta.phone_mount`. The filter will use it to choose how much to trust the gyroscope: fixed to the
bike on the handlebar (but turning with the steering), mostly fixed in a bag, moving with the
rider's body in a pocket. It is a manual setting; detecting the mount from the sensors is phase 3
work, and these labelled logs are what it would be built and checked on.
- **Record motion sensors**: off by default. When on at the moment a V2X log starts, that log also
records the data below. It adds about 300 rows a second, tens of MB per hour.
Both are read once when a log starts, so one file is always one mount and one mode. Changing them
mid-log takes effect from the next log.
## What a fusion log contains
Settings > Developer > V2X data logger, with Record motion sensors on. File name
`v2x_log_<start>_<hardware>_imu-<mount>.db` (without the suffix when it is off). Schema version 2
(`meta.schema_version`, `PRAGMA user_version`); version 1 logs have no `imu` or `clock` table and
none of the new `gnss` columns.
### `imu` (new)
| Column | |
|---|---|
| `sensor` | `accel` (m/s², gravity included), `gyro` (rad/s), `gravity` (m/s², `TYPE_GRAVITY`, points up) |
| `elapsed_ns` | the sample's own `SensorEvent.timestamp`, on `SystemClock.elapsedRealtimeNanos` |
| `ts_ms` | the same instant as wall-clock epoch ms, for browsing only |
| `x`, `y`, `z` | device frame: x right, y up the screen, z out of the screen |
Requested at 100 Hz (`meta.imu_period_us` = 10000), on a background thread of its own. `gravity` is
only logged when the phone has a real `TYPE_GRAVITY` sensor (the Pixel 9 Pro does); the sensors'
names, vendors and maximum rates are in `meta.sensor_*`.
### `gnss` (new columns)
| Column | |
|---|---|
| `source` | `phone` = fused location (Google Play services, as before), `phone_gps` = raw `GPS_PROVIDER` (new, fusion logging only), `obu` = the CiT One's `obu_gnss` |
| `elapsed_ns` | the fix's own monotonic time; phone sources only. What fusion lines fixes up with sensor samples on |
| `speed_accuracy_mps`, `bearing_accuracy_deg` | 1-sigma, where the provider gives them |
| `provider` | `fused` or `gps` |
`fix_ms` is the fix's instant as wall-clock ms and `ts_ms` when the app received it, so
`ts_ms - fix_ms` is the delivery delay. The fused and the raw source are logged side by side because
the Pixel's fused location includes Google's city-street corrections while the raw one is the chip
alone and not pre-filtered; the rides decide which one the filter uses. `meta.gnss_hardware` names
the GNSS chip.
### `clock` (new)
Once a second, the three phone clocks read back to back: `elapsed_ns` (monotonic), `wall_ms` (the
phone clock), `gnss_ms` (`SystemClock.currentGnssTimeClock`, NULL without GNSS time). Sensor samples
and phone fixes carry monotonic time, received messages and OBU fixes wall time, and the transmit
path GNSS time; these rows convert between them, and show the phone clock's error and any step in it.
## Checking a log
```
py -3.11 tools/fusion_log_check.py v2x_log_..._imu-handlebar.db
```
Read-only, standard library only. Per file it prints the metadata, each sensor's sample count, rate,
interval distribution, gaps and magnitude, each GNSS source's rate, accuracy, delivery delay and
whether its fixes fall inside the sensor recording, the distance between the fused and raw fixes
(and the OBU's, on the CiT One), and the phone clock's error and steps. It ends with PASS, WARN or
FAIL lines, and exits with 1 if anything failed:
- FAIL: logging was off, no `imu`/`clock` table, a sensor missing, a sensor gap over 1 s, a phone
source missing, phone fixes without `elapsed_ns`.
- WARN: a sensor rate outside 80–130 Hz, gaps over 100 ms, an accelerometer or gravity magnitude far
from g, a GNSS gap over 5 s, fixes with no gyroscope sample within 20 ms, no GNSS time, a phone
clock step, a log that was not stopped cleanly.
Tested against synthetic logs built from `V2xLogWriter`'s own table definitions (a clean ride, an
injected 300 ms gyroscope gap, a 14-minute clock step, logging off, fixes without monotonic time);
not yet against a real ride.
## Test rides
Recorded per mount (handlebar, bag, pocket), 20–30 minutes each, with Record motion sensors on and the
phone mount set before pressing Start. Each ride should include left and right turns, a roundabout,
stops of at least 10 s (the filter estimates the gyroscope offset while standing), and if possible a
bridge or underpass for a real GNSS outage. The list to tick off is in `TODO.md`.
## Code
| | |
|---|---|
| `domain/fusion/PhoneMount.kt` | the mount setting and its stored ids |
| `data/RidePreferences.kt`, `viewmodel/RideSettingsViewModel.kt` | Settings > Ride storage and screen state |
| `ui/screens/SettingsScreen.kt` (`RideSettingsScreen`) | the screen |
| `data/SensorRepository.kt` | `gpsProviderFlow`, sensor flows on a chosen thread, `describeSensor` |
| `data/log/V2xLogger.kt`, `data/log/V2xLogWriter.kt` | the logging and the schema |
| `ui/screens/V2xLogSettingsScreen.kt` | shows mount, motion sensor row count and raw GPS fix age while logging |
| `tools/fusion_log_check.py` | the check above |
-113
View File
@@ -1,113 +0,0 @@
# Large SPATEM / MAPEM reception (2026-11-23)
Why a road RSU's SPATEMs and MAPEMs did not reach the phone's V2X screens, in two independent places, and what was
changed. Interface changes are in `obu-firmware/docs/station-link.tex` (revision 3).
## Symptom
A MAPEM and a SPATEM compiled to sit below 494 bytes arrived on the phone; larger ones did not. Later, with the
firmware fixed, the phone *logger* showed the RSU's large messages but the app's V2X screens stayed empty.
The "larger" test messages were far above the limit: **888 bytes (SPATEM) and 1198 bytes (MAPEM)**, from the
Berliner Tor RSU (station 1095348116, intersection 23, 6 lanes, 5 signal groups). The small pair were 377 B (MAPEM)
and 58 B (SPATEM). The test therefore showed that nothing is fragmented on that path, not where a cutoff sits.
## Problem 1: the firmware dropped everything over 494 bytes
**It did receive them.** The radio captures frames up to 2346 bytes, and the firmware's own `gn_unwrap.c`, replayed
on the PC over the CiT node's pcap (`its5_20261123_150746.pcap`, 27 367 frames), accepts all of them: 1727 MAPEMs
of 1198 B and 3384 SPATEMs of 888 B. They are valid: asn1tools decodes every distinct one and re-encodes it
byte-identically.
**The firmware then threw them away.** `V2X_RX` (opcode 0x90, MicrOBU's own) was designed as one link message. A link
message is at most 512 octets (the largest GATT value), minus 4 header and 14 prefix octets leaves **494 bytes** of
ITS payload. `Station::forward_raw` called `v2x_rx_fits()`, and for a longer message only incremented
`raw_oversize_` and returned. The fragmenting code (`LinkService::send_fragmented`, used for `RAW_FRAME`, PKI and
indications) existed and the app already reassembled any fragmented opcode, but the gate in front of it meant a
`V2X_RX` was never offered to it.
**Why nobody noticed:**
- It was a known, documented limit (`gn_unwrap.h`, `NOTES.md`, TODO.md: "road MAPEMs over 494 bytes are still dropped as
oversize (no fragmentation)"), but every earlier bench run used the bench RSU, whose messages are 58 and 295 bytes.
- The drop was silent where the phone could see it. The counter lived only in the firmware, STATUS has a fixed
131-octet layout with no field for it, and the only trace was one LOG line per 10 s on the USB log, which a phone on
BLE never gets.
- Comparing the phone log with a second receiver (the node's pcap) is what exposed it: 0 of 1537 large MAPEMs and
0 of 3004 large SPATEMs reached the phone, against 98.5 % and 96.5 % of the small ones.
**What the 2026-11-23 COM10 read did and did not show.** An early check of COM10's log concluded the board "never saw
a large message". That was wrong. `tools/station_status_watch.py` prints only the first few V2X_RX lines unless asked,
and opening the port reset the board. It showed nothing about large messages either way.
### Fix (obu-firmware)
- `v2x_rx.hpp`: `v2x_rx_plan()` decides `single` (up to 494 B, byte-identical to before), `fragmented` (up to
`v2x_rx_max_forward` = 2300 B), `covered_by_raw` (large and `RAW_CAPTURE` on) or `drop`.
- `link_fragment.hpp` (new, host-testable): `split_fragments()` is the one fragmenter. `LinkService::send_fragmented`
uses it, with the same bytes on the wire as before.
- Best effort, never blocking: fragments of a large `V2X_RX` go out on serial through the non-blocking
`try_write`, no retry, no wait. The first failed fragment ends that message; the app drops the incomplete stream
(2 s idle, or the next first fragment). A transport that would need more than 8 fragments (ATT MTU 23) skips the
message.
- `serial::try_write` now writes nothing when no USB host is connected.
- Counters `raw_fragmented_`, `raw_fragment_failed_`, `raw_covered_`, `raw_oversize_`, in the throttled LOG line.
STATUS is unchanged.
- The app's V2X_RX / Raw frames switch is untouched. While `RAW_CAPTURE` is on a large message is not sent a second
time as V2X_RX.
- TX path untouched.
### Result on air (COM10, BLE, 17:08-17:20)
`tools/rx_size_compare.py` on the new phone log and node pcap: MAPEM 1198 B 92.9 % of what the node heard, SPATEM
888 B 81.7 %, CAMs 92.5-99.3 %, `radio_dropped` 0, no BLE disconnects.
## Problem 2: the app's SPATEM decoder refused the RSU's messages
**Why the logger had them and the screens did not.** Both read the same `V2X_RX` frames from `Esp32Link`. They differ
in what they do with the bytes:
- `V2xLogger` stores the raw UPER payload and classifies it from the ITS PDU header. Decoding only fills convenience
columns (position, speed, a summary), inside `runCatching`, so a decoder that fails leaves them NULL and the row is
stored anyway.
- `CamUseCaseRepository.handleSpatUper` hands the bytes to `SpatemUperCodec.decode`; on `null` it logs
"decode FAILED" and emits nothing, so no SPAT reached the traffic-light screens.
**Why the decoder returned null.** `SpatemUperCodec` returned null whenever it met an optional it could not size.
The RSU's SPATEM uses two such fields on every intersection:
- `name` / `movementName` (`DescriptiveName`, IA5String SIZE(1..63)): "Berliner Tor / Kolbergstrasse" and one per
movement.
- `speeds` (`AdvisorySpeedList`) on every event: a greenwave and an ecoDrive advice per phase. This, with the names
and the 8 events per movement, is why the message is 888 bytes and not ~58.
The decoder's header comment said it had been validated against 79 042 SPATEMs from the 2026-03-18 drive; those
messages simply carried neither field. The gap was latent: until the firmware forwarded large messages, an 888-byte
SPATEM never reached the app, so the decoder never met one.
The MAPEM decoded correctly all along (it already reads names); the traffic-light screens need the SPATEM as well.
### Fix (app)
`SpatemUperCodec` now walks, without keeping, `DescriptiveName` (6-bit length n-1, then 7 bits per character) and
`AdvisorySpeedList` (4-bit count n-1; per entry: extension bit, five optional bits, type = extension bit plus 2 bits,
speed 9 bits, confidence 3 bits, distance 14 bits, class 8 bits). Regional extensions and extension values still
return null. Widths come from `dsrc_2_2_1.asn`.
## Verification
| Check | Result |
|---|---|
| Firmware host suite (`make check` in `obu-firmware/test/host`): chain, replay with asn1tools, 2 M-iteration fuzz, battery, firmware | pass; the firmware unit tests grew from 40 to 46 |
| `test_v2x_fragments`: the node pcap through unwrap, plan, fragments, two independent reassemblers, at link limits 512 and 244, with a lost fragment | 5111 large messages, 0 failures |
| App `LinkReassemblyTest` on the firmware's own fragments (`v2x_rx_fragments.tsv`) | pass |
| `SpatemUperCodec` against asn1tools on every distinct SPATEM of the new phone log | 718 of 718 equal field for field, 3590 movements |
| App unit suite | 197 tests, 0 failures |
| ESP-IDF 6.0.2 image build | 0x1f7aa0 bytes, 34 % of the app partition free |
## Files changed
Firmware: `v2x_rx.hpp`, `link_fragment.hpp` (new), `link_service.cpp/.hpp`, `station.cpp/.hpp`, `serial_link.cpp`,
`gn_unwrap.h` (comment), `NOTES.md`, `README.md`, `docs/station-link.tex`. Tests: `test_firmware.cpp`,
`test_v2x_fragments.cpp` (new), `Makefile`. App: `SpatemUperCodec.kt`, `SpatemUperCodecTest.kt`,
`LinkReassemblyTest.kt`, resources `v2x_rx_fragments.tsv`, `spatem_road_rsu_888.hex`. Tool: `tools/rx_size_compare.py`.
## Still open
- The V2X screens on the phone with the rebuilt app (this document was written before that check).
- MAPEM / SPATEM loss on BLE rises with size (58-byte SPATEM 96.5 % on 2026-11-23 earlier, 888-byte SPATEM 81.7 % now): a lost fragment loses
the message. If the screens need better, options are a smaller fragment cadence or a loss counter in the app
(`LinkReassembly.dropped`).
- Advisory speeds are walked, not used; a GLOSA display could read them.
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,4 +1,4 @@
# OBU transmit firmware
# OBU transmit firmware - Phase 2 (in progress: HLN-SV DENM beacon)
Build and flash steps are under "Build and flash" below. (`docs/04-transmit-setup.md`,
referenced here and in the sources, is not in the repo.)
+41 -18
View File
@@ -1,41 +1,64 @@
cmake_minimum_required(VERSION 3.22)
# ESP32-C5 station on the microbu_v2x and Vanetza components.
# Verify the vendored radio source before configuration.
set(_otm_upstream "${CMAKE_CURRENT_LIST_DIR}/components/microbu_v2x/third_party/otm/main/tx_custom.c")
# obu-firmware: the ESP32-C5 half of the MicrOBU station, on the vanetza-idf C-ITS stack.
#
# Since 2026-09-23 this is a port of the colleague's standalone VRU station
# (microbu-esp32c5/firmware, in their own repository, not part of this one). From it:
# BTP/GeoNetworking and the TS 103 097 security entity (vanetza-idf), the station-link message
# layer over native USB Serial/JTAG and BLE GATT, the NVS credential store, and the C5 radio adapter.
# Added here for this project: the raw receive path of the previous firmware (gn_unwrap.c, forwarded
# as link opcode V2X_RX) so unsigned and non-demo-signed traffic still reaches the phone, the
# unsigned transmit path of the previous firmware (geonet.c), and BLE pausing while USB is in use.
# See NOTES.md.
#
# ESP-IDF 6.0.2 exactly: the C5 radio's private Wi-Fi driver ABI (otm_tx_custom.c) is pinned to it
# by vanetza-idf's radio_c5.cmake and has only been validated there. The previous C firmware was
# built with IDF 6.1; see FLASHING.md for the export script of each.
#
# vanetza-idf lives in external/vanetza-idf, copied from the colleague's repository (their
# external/vanetza-idf at commit cf4b99f, unchanged; see its PROVENANCE.md). Override with
# -DVANETZA_IDF_DIR=... to build against another checkout.
if(NOT VANETZA_IDF_DIR)
set(VANETZA_IDF_DIR "${CMAKE_CURRENT_LIST_DIR}/external/vanetza-idf")
endif()
if(NOT EXISTS "${VANETZA_IDF_DIR}/idf_component.yml")
message(FATAL_ERROR "vanetza-idf not found at ${VANETZA_IDF_DIR}: obu-firmware/external/vanetza-idf "
"is part of this repository; check it is complete, or pass "
"-DVANETZA_IDF_DIR=<path to a vanetza-idf checkout>")
endif()
# Provenance guard for main/otm_tx_custom.c, copied unchanged from microbu-esp32c5/firmware/CMakeLists.txt:
# this checked-in copy is what microbu::C5Radio::request() links against for every transmission.
# Fail configure if either the pinned upstream or this file drifts from the reviewed revision.
set(_otm_upstream "${VANETZA_IDF_DIR}/ports/esp_idf/third_party/otm/main/tx_custom.c")
if(EXISTS "${_otm_upstream}")
file(READ "${_otm_upstream}" _otm_upstream_text)
string(REPLACE "\r\n" "\n" _otm_upstream_text "${_otm_upstream_text}")
string(SHA256 _otm_upstream_hash "${_otm_upstream_text}")
if(NOT _otm_upstream_hash STREQUAL "cb1dccfef96912ca59275e8a9102f41f56925b94a19d4a4629082aaeb779be1b")
message(FATAL_ERROR "The vendored OpenTrafficMap radio source differs from its pinned SHA256")
message(FATAL_ERROR "OpenTrafficMap upstream tx_custom.c differs from the reviewed source revision (674e3412) -- review before updating main/otm_tx_custom.c and this hash")
endif()
endif()
set(_otm_checked_in "${CMAKE_CURRENT_LIST_DIR}/main/otm_tx_custom.c")
file(READ "${_otm_checked_in}" _otm_checked_in_text)
string(REPLACE "\r\n" "\n" _otm_checked_in_text "${_otm_checked_in_text}")
string(SHA256 _otm_checked_in_hash "${_otm_checked_in_text}")
if(NOT _otm_checked_in_hash STREQUAL "db32dd6e2a50decf7add4fc09ea14ee1f060bf07a047c5c7bd3cdc2b1190b019")
message(FATAL_ERROR "The application radio source differs from its pinned SHA256")
if(NOT _otm_checked_in_hash STREQUAL "114693af99ce3866cfc767066d484e45822eaf15335d94a03626b60ac5777277")
message(FATAL_ERROR "main/otm_tx_custom.c differs from the reviewed copy -- review the change, then update this hash")
endif()
list(APPEND EXTRA_COMPONENT_DIRS "${VANETZA_IDF_DIR}")
set(SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
set(COMPONENTS main)
set(MICROBU_CRYPTO_ADAPTER_COMPONENT "" CACHE STRING
"Optional ESP IDF component implementing the selected external Vanetza crypto backend")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(microbu_firmware)
include("${CMAKE_CURRENT_LIST_DIR}/cmake/no_efuse_writes.cmake")
project(obu_firmware)
add_compile_options(-Wno-error -Wno-cpp -Wno-error=implicit-function-declaration)
foreach(_stack vanetza microbu_v2x)
idf_component_get_property(_stack_lib ${_stack} COMPONENT_LIB)
if(_stack_lib)
target_compile_options(${_stack_lib} PRIVATE -Wno-error=implicit-function-declaration -Wno-error=cpp)
endif()
endforeach()
idf_component_get_property(vanetza_lib vanetza-idf COMPONENT_LIB)
if(vanetza_lib)
target_compile_options(${vanetza_lib} PRIVATE -Wno-error=implicit-function-declaration -Wno-error=cpp)
endif()
# GCC 15's stricter -Warray-bounds false-positives on NimBLE's fixed-size bond-store arrays
# (upstream Apache Mynewt code, not ours); demote to a warning so the component still builds.
# (upstream Apache Mynewt code); demote to a warning so the component still builds.
idf_component_get_property(bt_lib bt COMPONENT_LIB)
if(bt_lib)
target_compile_options(${bt_lib} PRIVATE -Wno-error=array-bounds)
endif()
+154 -124
View File
@@ -1,150 +1,180 @@
# obu-firmware: build and flash
# obu-firmware — setup & flashing notes
**Board: Seeed XIAO ESP32-C5.** One USB-C port, the chip's native USB Serial/JTAG (VID/PID
0x303A/0x1001); no UART bridge. 8 MB flash. The same port flashes the board, carries the phone's
station link and carries the log (as LOG frames, type 0x7F), so the PC and the phone take turns on
it. Over BLE the phone does not need the cable.
## Two toolchains - use a dedicated terminal for each
## Toolchain
Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly
(`C:\Espressif\frameworks\esp-idf-v6.0.2`): it is the vanetza-idf port (see
NOTES.md), and vanetza-idf's `radio_c5.cmake` refuses any other version because
the raw TX path pokes private Wi-Fi driver structures only validated there. The
previous C firmware used the receiver firmware's IDF **6.1**; the separate
`obu-cam-transmistter` project builds against the global ESP-IDF **5.5.4**.
Exporting two of them in one PowerShell window fails: the second export
inherits the first's `IDF_PYTHON_ENV_PATH` and reports every Python dependency
as unmet. Don't run `install.bat` to "fix" that - open a fresh terminal, or
clear the state with `$env:IDF_PYTHON_ENV_PATH = $null; $env:IDF_PATH = $null`.
ESP-IDF **6.0.2** exactly (`C:\Espressif\frameworks\esp-idf-v6.0.2`): `components/microbu_v2x`
pins the C5 radio's private Wi-Fi driver ABI to it. Not the receiver firmware's 6.1, not
`obu-cam-transmistter`'s 5.5.4. Exporting two IDFs in one PowerShell window fails; open a fresh
window, or clear `$env:IDF_PYTHON_ENV_PATH` and `$env:IDF_PATH` first.
The build is self-contained: the C-ITS library comes from
`obu-firmware/external/vanetza-idf`, a copy of `external/vanetza-idf` from the
colleague's microbu-esp32c5 repository (their commit cf4b99f, unchanged). Pass
`-DVANETZA_IDF_DIR=<path>` to `idf.py` to build against another checkout. The
first build downloads `espressif/esp-boost` into `managed_components/`.
Nothing is fetched from or pushed to the colleague's repository (HAW GitLab,
urban-mobility-lab/microbu/microbu-esp32c5). To take a newer vanetza-idf from
it, copy their `external/vanetza-idf` over this folder, rebuild and test, and
commit it here. The rest of their tree (their own VAM firmware, PKI tooling,
station-link Python tools, the V2X2MAP bridge) is not part of this repository.
## Every new PowerShell session
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
$env:IDF_TOOLS_PATH = "C:\Espressif"
C:\Espressif\frameworks\esp-idf-v6.0.2\export.ps1
idf.py --version # v6.0.2
```
## Build & flash
Flash over the board's **UART-bridge port** (CH343; COM3 for the production OBU
on the bench), not the native port the phone uses.
```powershell
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
idf.py set-target esp32c5 # once per clean build folder
idf.py build # first build ~20 min; downloads espressif/esp-boost into managed_components/
idf.py set-target esp32c5 # only needed once per clean build folder
idf.py build
idf.py -p COM3 -b 921600 flash monitor
```
## Flash
Swap `COM3` for whatever port the ESP32-C5's bridge enumerates as (Device Manager →
Ports). `monitor` opens the serial console after flashing — `Ctrl+]` to exit.
Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the
partition table may differ from what the board has.
Use a full `flash` (bootloader + partition table + app), never `app-flash`: the partition table is
not Niklas Dathe's (80 KB NVS, app at 0x20000).
### First flash onto a board with the previous firmware
The partition table changed with the port (NVS 24 KB → 80 KB, app 0x10000 →
0x20000), and the old NVS is full of Wi-Fi settings the previous firmware left
behind. Erase the whole new NVS range once, then do a full flash:
```powershell
idf.py -p COM6 flash
python -m esptool --chip esp32c5 -p COM3 -b 921600 erase-region 0x9000 0x15000
idf.py -p COM3 -b 921600 flash
```
**If the running firmware has taken the USB port down** (or the board holds an unrelated image),
auto-reset fails with "No serial data received". Unplug, hold BOOT, plug in, release. If the flasher
stub then fails to start (seen 2026-11-10 with esptool 5.4 on this board), flash without it, from
`build/`:
Without the erase, the board cannot store the BLE bond and the phone has to pair
on every connection (2026-09-23). After it:
```powershell
python -m esptool --chip esp32c5 -p COM6 --no-stub --before=no-reset --after=hard-reset write-flash "@flash_args"
```
- the boot log shows `0 bonded phone(s) in NVS`, `BLE advertising started as
'micrOBU-XXXX'` and `station task ready`; the radio stays off until the app
connects;
- on the first Connect the app provisions the demo credentials once (the card
says "Provisioning the demo credentials"); they stay in NVS from then on;
- a phone that was paired with the board before must forget `micrOBU-XXXX` in
Android's Bluetooth settings and pair again (passkey 123456).
A board left in download mode comes back after unplugging and replugging without BOOT.
Erasing NVS later (e.g. after a partition change) has the same effects.
**Before flashing a board you did not flash yourself, read its app descriptor**
(`esptool read-flash 0x10000 0x100`; `esp_app_desc_t` starts at 0x20): project name `microbu_firmware`
is this firmware, `obu_firmware` an older MicrOBU one, `arduino-lib-builder` an Arduino sketch.
Back the flash up first to `firmware-backups/` (gitignored).
## Going back to the previous firmware
### First flash onto a board with other firmware
The previous, unsigned C firmware (frame types 0x01-0x05, CAM over USB only)
can come back two ways. The app detects it and falls back to its protocol.
Erase the NVS range once, so no old Wi-Fi or BLE data sits in the new 80 KB NVS:
```powershell
python -m esptool --chip esp32c5 -p COM6 erase-region 0x9000 0x15000
```
Then: the boot log shows `BLE advertising started as 'micrOBU-XXXX'` and `station task ready`; the
radio stays off until the app (or `tools/station_status_watch.py --configure`) sends
STATION_CONFIGURE; the app provisions the demo credentials on the first Connect. A phone that was
paired before must forget `micrOBU-XXXX` in Android's Bluetooth settings and pair again (passkey
123456, `CONFIG_MICROBU_BLE_PASSKEY`).
### Pairing, bonds and several boards
- The name is `micrOBU-` plus the last two octets of the board's BLE address (`micrOBU-66AA` is the production
XIAO on COM10, `10:BD:A3:CF:66:AA`). The board keeps **one** bond in NVS and refuses to replace it.
- **With no bond the app connects to the first micrOBU it hears.** On a bench with several (2026-11-11: 4AFA, 3FAA,
A25E and 66AA all at -49 to -55 dBm) that is not necessarily yours, and it can bond with the wrong board. Pair the
right one first in Android's Bluetooth settings (Pair new device, passkey 123456); the app then prefers a
bonded micrOBU. Forget a wrong bond there too.
- If the phone has lost its bond but the board still holds one, the phone connects and drops again after about 3 s.
Erase the board's NVS (`python -m esptool --chip esp32c5 -p COMx erase-region 0x9000 0x15000`) and pair again.
- The bond survives a reflash that keeps the NVS and a reset of the board (checked 2026-11-11).
## Look at the board from the PC
```powershell
py -3.11 tools/station_status_watch.py COM6 30 --configure --rx
```
prints the log, the STATUS snapshot once a second (uptime, signing and radio counters, heap,
battery) and the first V2X_RX messages heard on air. DTR/RTS stay low in the script because toggling
them resets the board. **Opening the port resets the board** (USB Serial/JTAG), so a phone on BLE is dropped.
```powershell
py -3.11 tools/station_tx_test.py COMx --seconds 60 --mac 02:aa:bb:cc:dd:01 # signed CAMs from a named MAC
py -3.11 tools/station_tx_test.py COMx --seconds 60 --unsigned # unsigned, a random MAC
```
plays the phone over USB (configure, position, a CAM request per second) and reads the station's own raw capture, so it
prints the 802.11 source address and whether each frame is signed, plus how many frames the radio submitted and
completed. Pair it with a second board listening on the air to count what arrives.
## Production OBU checklist (board with the cell connected)
1. **Before touching the board:** read its app descriptor and back its flash up (see above). Check the
cell polarity with a multimeter before it goes on the BAT pads; the slide switch can stay off while
flashing, USB powers the board.
2. Erase the NVS range, then a full `idf.py -p COMx flash` (or the `--no-stub` recipe if the stub
fails). Unplug and replug the cable **without** BOOT afterwards.
3. `py -3.11 tools/station_status_watch.py COMx 20 --configure --rx`: expect `BLE advertising started as
'micrOBU-XXXX'`, a STATUS line every second, `configured=1` after the configure, and `battery=` close
to the multimeter reading on the cell. The firmware has no calibration trim any more: if the two differ
by more than about 50 mV, note both values (a `CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` option of the
earlier port can be added back).
4. Switch the cell on, unplug USB, check the board keeps running (LED pulses on RX, the phone connects
over BLE). Then work down `TODO.md` ("obu-firmware on Niklas Dathe's microbu-firmware").
5. **Know the shutdown rule before leaving it unattended:** with the cell below 3.30 V, no phone on USB
and more than 60 s after boot, the board deep-sleeps and only wakes every 5 minutes to check; it runs
again from 3.60 V (charge it over USB). A board that "went dead" on a flat cell is this, not a crash.
6. Install the app built from this commit on the phone: the app and firmware of 2026-11-10 only talk
to each other (CONFIRM/STATUS_REQUEST, V2X_RX 0x90). The phone must forget an old `micrOBU-XXXX`
bond and pair again (passkey 123456), because the NVS was erased.
## Battery and pins (XIAO ESP32-C5)
The prototype runs on a 3.7 V LiPo on the BAT pads (cell `+` through a slide switch to **BAT+**,
`−` to **BAT−**); the board's charger charges it from USB. Check the polarity with a multimeter
first: reversed, it destroys the board. **The cell has no protection board**, so only the firmware
stops an over-discharge, and nothing stops a short.
| Pin | GPIO | Used for |
|---|---|---|
| on-board | GPIO6 | `BAT_VOLT_PIN`: BAT+ through the board's own 100 kΩ / 100 kΩ divider (ADC1); nothing to wire |
| on-board | GPIO26 | `BAT_VOLT_PIN_EN`: load switch for that divider, high only while measuring; nothing to wire |
| native USB | GPIO13 / GPIO14 | USB D− / D+ |
| (user LED) | GPIO27 | yellow LED, active low: pulses on TX/RX (`CONFIG_MICROBU_STATUS_LED`) |
Only the cell's `+` and `−` go to the BAT pads; the cell's two extra wires (temperature / ID) stay unconnected, the firmware does not use them. The voltage measurement needs no further wiring. `BatteryMonitor` (`battery_monitor.cpp`) reports the calibrated cell voltage as `battery_mv` in
STATUS (octets 129-130, 0 = no cell or no sensor). `BatteryPolicy` (`battery_policy.hpp`, host-tested
in `test/host`) adds the protection, every 5 s: the smoothed voltage below 3.30 V for 30 s, more than
60 s after boot and with **no frame from a phone on USB in the last 5 s**, puts the board into deep
sleep; it wakes every 300 s, measures, and runs again from 3.60 V. A phone on USB powers the board,
so no shutdown happens then. Thresholds: `menuconfig -> micrOBU firmware`. The app shows
low/critical from the same voltage and its own thresholds. The first XIAO build read 0 mV because the divider had
no time to settle at `CONFIG_FREERTOS_HZ=100` (fixed 2026-11-11, see NOTES.md); it now reads 4.14-4.16 V on a charging
cell. There is no calibration trim and no multimeter reference on the glued-in cell: the plateau at full charge
should sit near the charger's 4.20 V.
- **Image:** `firmware-backups/` in the repository root (gitignored, on the lab
laptop only) holds a full-flash image of the COM3 board as it was before the
port, with the esptool command in its README.txt. It restores the old
partition table and NVS too.
- **Source:** commit `7285fa1` is the last one before the port. Check it out in
a separate worktree and build it with the receiver firmware's IDF 6.1
(`its-g5-receiver-firmware\esp-idf\export.ps1`). Erase the NVS range as above
first, then `flash` (full, since the partition table differs); erasing after
flashing would wipe the start of the old app, which sits at 0x10000.
## If the build fails
`idf.py fullclean`, then build again. A "provided by component(s) ... not in the requirements list"
error means a header moved to another IDF component: add it to `REQUIRES` in `main/CMakeLists.txt`.
- **"includes X.h, provided by Y component(s)... not in the requirements
list"** — IDF 5.x split the old monolithic `driver` component apart
(`esp_driver_gpio`, `esp_driver_uart`, etc.). Add the named component to
`REQUIRES` in `main/CMakeLists.txt` and rebuild. Already fixed once for
`esp_driver_gpio` + `esp_driver_uart` — if a new header comes up, same fix.
- Otherwise, start clean before re-building:
```powershell
idf.py fullclean
idf.py build
```
## Going back
## Connecting the phone (ESP32-C5-WIFI6-KIT)
`firmware-backups/` (gitignored, on the lab laptop) holds full or 4 MB images of the boards as they
were before they were reflashed. Restore with
`python -m esptool --chip esp32c5 -p COM<N> write-flash 0 <image>`. The previous C firmware is in
git history (last commit before the port: `7285fa1`; the vanetza-idf port: `1c3a66e`).
The board has two USB-C ports — use the right one:
- **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this
is where the phone plugs in via USB-OTG. The station link
(`serial_link.cpp`: station-link messages as frame type 0x10 in the 0xAA55
framing) runs over the ESP32-C5's native USB Serial/JTAG peripheral on this port, enumerating as a CDC-ACM device under Espressif's
VID/PID (0x303A/0x1001).
- **UART-bridge port** (labeled for flashing) — this is what you use for
`idf.py flash monitor` from your PC. Leave the phone unplugged from this
one; it only carries `idf.py`'s flashing protocol and the ESP_LOG console.
The app recognizes the ESP32-C5's VID/PID via a custom probe table in
`UsbSerialTransport.kt` (the default `usb-serial-for-android` prober doesn't
know Espressif's device IDs). If the phone doesn't detect anything when
plugged into the native port, first confirm with a tool like "USB Device
Info" (or `adb shell dumpsys usb` from a PC) that Android sees a USB device
at all — that isolates a bad/charge-only OTG cable from an app-side issue.
## Bring-up checklist (phone <-> ESP32-C5 link)
Work down this list — each step isolates the layer below it.
1. **Flash and install together.** The app detects the firmware generation by
its heartbeat and speaks either protocol, but only an app from 2026-09-23 on
knows the station-link protocol; messages are at most 512 octets on both
sides.
2. **Does Android see the device at all?** Plug the phone into the **native**
USB-C port, hit Connect, and read logcat for `UsbSerialTransport`. It logs
every attached device *and* each device's interfaces. Empty list = cable /
OTG / wrong port, below the app entirely.
3. **Did the right interface get claimed?** The C5's USB Serial/JTAG is a
composite device — expect CDC control (class 2) + CDC data (class 10) +
vendor-specific JTAG (class 255) in that dump. Compare against the `ports=`
count on the `matched device` line.
4. **Is the link alive?** The firmware sends a STATUS at 1 Hz regardless of
radio traffic, and the app marks the link ERROR after ~3.5 s of silence.
Connected-and-staying-connected means device→host actually works. The board
starts its radio only after the app's STATION_CONFIGURE, so nothing is
received before Connect.
5. **If it connects but no V2X_RX ever arrives** — suspect DTR. The app now
asserts DTR/RTS on open (`openDevice()` in `UsbSerialTransport.kt`), because
`CdcAcmSerialDriver` doesn't do it by default and the ESP32's USB Serial/JTAG
endpoint may gate TX on the host opening the CDC line. **This is still
unverified on real hardware** — test it both ways (with the `setDTR(true)`
call and with it commented out) and record the answer in `serial_link.h`
next to the VID/PID note, so nobody has to guess again.
6. **Watch the counters, not just "Sent: N".** The CAM Pinger card shows
consecutive write failures (phone side) and the firmware's tx-failure /
RX-queue-drop / CRC-error totals from the heartbeat; the connection card
shows tickets, signed and refused counts. A rising `tx fail` means messages
reach the ESP32 but the radio refuses them — a radio problem, not a link
problem. A rising `refused` with signing on usually means no ticket (NVS
erased: reconnect so the app provisions again).
## Connecting over Bluetooth instead
Settings > Connection > ESP32-C5 > link: Bluetooth, then Connect. The board
advertises as `micrOBU-XXXX` (last two bytes of its BT MAC; `micrOBU-4AFA` on
COM3), but only while nothing uses its native USB port. Android asks to pair
the first time: passkey **123456** (fixed in `simple_ble.cpp`). The bond is kept
on both sides; the board keeps one bond, so pairing a second phone or a PC
replaces the first. Log lines on the console start with `cits_ble:`.
## Notes
- No `git submodule update` needed here — obu-firmware has no pinned
submodule of its own, unlike its-g5-receiver-firmware.
- Don't use the global "ESP-IDF 5.5 PowerShell" shortcut or the receiver
firmware's 6.1 checkout — export from `esp-idf-v6.0.2`, the version the
vanetza-idf radio's undocumented driver internals were verified against.
- The console (ESP_LOG, boot messages, panics) stays on the UART-bridge port.
Opening it resets the board; do that only while nothing else depends on the
session.
+59 -128
View File
@@ -1,142 +1,73 @@
# obu-firmware
The production OBU firmware: the ESP32-C5 half of the MicrOBU station (Seeed XIAO ESP32-C5).
## Since 2026-09-23: signed ITS on vanetza-idf
## Since 2026-11-10: Niklas Dathe's microbu-firmware architecture
This firmware is a port of the colleague's standalone ESP32-C5 VRU station
(`microbu-esp32c5/firmware`, in their own repository; only its `external/vanetza-idf` is copied
here, to `obu-firmware/external/vanetza-idf`).
From it: the vanetza-idf C-ITS stack (BTP, GeoNetworking, the TS 103 097 security entity with
credentials in NVS), the station-link protocol v1 (`link_protocol.*`, `link_service.*`) over the
native USB port (`serial_link.*`, frame type 0x10 in the same 0xAA55 framing as before) and over BLE
GATT (`simple_ble.*`), and the radio adapter (`c5_radio.*`, `otm_tx_custom.c`). Build with ESP-IDF
**6.0.2**; see FLASHING.md.
This tree is the current station firmware written by Niklas Dathe (`microbu-firmware`, HAW GitLab
urban-mobility-lab/microbu/microbu-firmware, commit e4e4bd8) with the MicrOBU additions below. The
earlier port of their older `microbu-esp32c5` (vanetza-idf, 2026-09-23) is gone.
The phone builds CAM or VAM, configures the station, provisions credentials, sends PoTi and hands
each message over as a BTP-DATA.request; the firmware adds GN/BTP, signs with the authorization
ticket, and transmits. The phone side is `Esp32Link.kt` in the app.
Layout:
Changed or added for this project (search for `MicrOBU:` in the sources):
| Path | What |
| --- | --- |
| `main/` | station and link service: `station.cpp`, `link_*`, `serial_link.cpp`, `simple_ble.cpp`, `c5_radio.cpp`, board controls, battery |
| `components/microbu_v2x/` | station wrapper, security entity, device PKI client (unchanged from Niklas Dathe's firmware) |
| `components/vanetza/` | ESP-IDF component around Vanetza (unchanged) |
| `external/vanetza/` | patched upstream Vanetza source (unchanged, see its `UPSTREAM`) |
| `docs/station-link.tex` | the link interface reference this firmware and the app implement: **revision 2**, Niklas Dathe's revision 1 plus our extensions (the original PDF is `microbu-firmware/docs/station-link.pdf`; build ours with `pdflatex`, no LaTeX is installed on the lab laptop) |
| `cmake/no_efuse_writes.cmake` | build guard: nothing in this firmware may program eFuses |
| `test/host/` | PC tests (`make` in that folder): the MicrOBU C code (`gn_unwrap.c`, `geonet.c`), the battery policy and, with `make firmware`, 40 unit tests of the link codec, V2X_RX and the policies |
- **Reception stays as it was.** vanetza-idf decapsulates with `itsGnSnDecapResultHandling =
STRICT`, so it drops unsigned traffic (the bench sim car) and everything signed under a root other
than the provisioned demo root (every RSU). Every captured frame therefore also goes through the
previous firmware's `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (0x85), whose body
is exactly the old `SERIAL_MSG_V2X_RX` payload (`Station::forward_raw`). The app's receive side is
unchanged.
- **Unsigned transmission is still possible.** The colleague's station refuses unsecured requests.
Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
messages" setting decides per message.
- **Console on UART0.** ESP_LOG stays on the CH343 bridge port (COM3 on the bench); the native port
carries only link frames. The colleague's single-port board routes the log into LOG frames there
(`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
- **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
(TODO.md).
- A serial write no longer stalls the station task when no USB host is present (BLE-only use).
- A notification longer than the ATT MTU is dropped instead of silently truncated.
- The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack
(the previous firmware's commit 04b0076 fixed the same risk).
- Manual country policy and the TX-power read-back from the previous firmware's radio bring-up.
- The activity LED (GPIO27 on the colleague's XIAO board) is off unless configured.
Take a newer release from Niklas Dathe by copying `firmware/{main,components,cmake}` and
`external/vanetza` over these folders and re-applying the `MicrOBU:` changes (search the sources
for that word). Nothing is fetched from or pushed to their repository.
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
valid two years, permissions psid 36 SSP `010000` and psid 638 SSP `01`). The colleague's own demo
chain only grants psid 638 and so cannot sign CAMs. Not EU-registered: receivers that verify against
the EU trust list drop what it signs.
Board: `CONFIG_MICROBU_BOARD_XIAO_C5` (sdkconfig.defaults). Their default is `mainboard-v5`, the
custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
Time: the signature's generationTime comes from the PoTi timestamp, which follows the app's
`ItsTime` convention (UTC-based, no leap seconds). The colleague's VBS adds the 5 leap seconds.
Which one is right is the open question documented in `ItsTime.kt`.
### MicrOBU additions (search for `MicrOBU`)
## Earlier notes (Phase 2, superseded)
- **Reception of everything on air: `V2X_RX`, opcode `0x90`.** The stack decapsulates strictly, so it
drops unsigned traffic (the bench sim car) and everything signed under a root other than the
provisioned one (every RSU). Every received data frame therefore also goes through `gn_unwrap.c`
(`Station::forward_raw`) and reaches the phone as `V2X_RX`. Body: `u16 port, i8 rssi, u8 flags
(bit0 GBC area, bit1 signed), i32 lat, i32 lon, u16 distance_a, ITS payload`. `0x85` is the spec's
`RAW_FRAME` debug capture and `0x86` is reserved by Niklas Dathe, hence `0x90`. BTP ports 2001
CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM, 2018 VAM pass. A message up to 494 bytes is one link
message, unchanged. Since 2026-11-23 a larger one (a road SPATEM or MAPEM, 555-1243 bytes; up to
`v2x_rx_max_forward` = 2300) goes out in link fragments (`link_fragment.hpp`, flags 1/2/3 as the spec
defines them), best effort: no retry and no waiting, a fragment no transport takes ends that message
(the app drops the incomplete stream) and `raw_fragment_failed_` counts it, and the serial fragments use
the non-blocking `try_write` so a stalled USB host cannot hold the station task that drains the radio queue.
A transport that would need more than 8 fragments (ATT MTU 23) skips the message. While `RAW_CAPTURE` is on
the app reads `RAW_FRAME`, so a large message is not sent a second time as `V2X_RX` (`raw_covered_`).
Before this change a message over 494 bytes was dropped and counted (the 2026-11-23 bench run lost every
888-byte SPATEM and 1198-byte MAPEM that way).
- **Unsigned transmission.** Niklas Dathe's station signs everything. A request with GN security
profile 1 (or 0 while the station is configured `security = 0`) goes out unsigned with
`geonet.c`'s header and the position of the last PoTi (`Station::unsecured_request`), from a
random locally administered MAC drawn at every STATION_CONFIGURE, or the MAC the phone names in the 16-octet STATION_CONFIGURE (address_configuration 0), which also sets the address of signed frames: a ride rotates it with the pseudonym, the CAM pinger keeps one. The app's "Sign outgoing
messages" setting decides per message. It bypasses the BLE collision guard's queue but not the
guard itself.
- **Radio polled from configure on**, not from the first PoTi, so the 16-frame queue never overflows
while the phone has not sent a fix yet.
- **Radio bring-up** from the previous C firmware: manual country policy (5 GHz channels on), TX
power read-back logged, 2.4 KB receive buffer static instead of on the Wi-Fi task's stack, frames
too short to be GN packets ignored rather than counted as lost.
- **Battery guard.** Niklas Dathe's firmware only reports `battery_mv` in STATUS. A XIAO cell has no
protection board, so `battery_policy.hpp` (smoothing, warning hysteresis, shutdown) deep-sleeps the
board below 3.30 V for 30 s when no phone is on USB, re-checks every 5 min, and runs again from
3.60 V. Thresholds: `menuconfig -> micrOBU firmware`.
- **Battery reading fix** (`battery_monitor.cpp`, found on the XIAO 2026-11-11: `battery_mv` was 0). At
`CONFIG_FREERTOS_HZ=100` `vTaskDelay(pdMS_TO_TICKS(5))` is zero ticks, so the switched divider never
settled before the ADC read it and every sample fell below the 2.5 V validity floor. It is now a 5 ms
busy wait, and GPIO26 is set up with `gpio_config`. Worth telling Niklas Dathe: his mainboard-v5 has no
switched divider and is not affected. With the fix the XIAO reads 4153-4156 mV on a charging cell.
- **Serial link**: no write attempt while no USB host is connected; `last_frame_ms()` tells the battery
guard whether a phone is powering the board.
- **Partition table**: 80 KB NVS (Niklas Dathe's 24 KB filled up and BLE bonds stopped persisting),
app at `0x20000`. A plain app-only flash of an older layout is wrong: flash everything.
- **Flash size 8 MB** (XIAO), TX power ceiling 20 dBm (`radio_policy.hpp` admits 20 dBm on channel 180).
- **ATT MTU 517** (`CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU`, Niklas Dathe's 512): the app asks for 517 and a 494-octet
V2X_RX is a 512-octet link message, which needs a value of 512, i.e. an MTU of 515. At 512 such a message was
split into fragments the app did not reassemble then (it does now, `LinkReassembly`).
- **Link-layer address.** A signed station without a named MAC uses the address derived from its ticket; with the
16-octet STATION_CONFIGURE the phone names it (see "Unsigned transmission"). The CAM and VAM station ID still
rotates in the app; the app now rotates the MAC with it on a ride and keeps one fixed for the bench pinger.
### OBU transmit firmware - Phase 2 (in progress: HLN-SV DENM beacon)
### Link spec revision 2
Started. See `docs/04-transmit-setup.md` in the project root for build/flash
steps and how to validate this against your own sniffer.
`docs/station-link.tex` is revision 2 of the interface reference: Niklas Dathe's revision 1 (microbu-firmware
e4e4bd8, kept unchanged as `microbu-firmware/docs/station-link.pdf`) plus a section "MicrOBU extensions": `V2X_RX`
(0x90), unsigned transmission (security profile 0x01, or 0x00 with `security` 0; random MAC per configure),
the battery shutdown rule, no USB writes without a host, and a revision history. The wire format of
revision 1 is unchanged, so a revision 1 host still works. Build the PDF with `pdflatex station-link.tex`
(twice) and commit it with the `.tex`; the LaTeX build files next to it are ignored. The section "Naming the MAC"
documents the 16-octet STATION_CONFIGURE, which revision 1 retires but the station still decodes.
Implements one profile so far: **HLN-SV** (aftermarket stationary recovery
vehicle), causeCode 94 (stationaryVehicle), subCauseCode 0, active while the
hazard-light GPIO is grounded. No location/alacarte containers.
### Dropped from the earlier MicrOBU version, and why
- `main/main.c` - entry point, the `phy_11p_set`/`phy_change_channel(5900,...)`
register hack, GPIO polling, TX loop
- `main/denm.c` / `.h` - ASN.1 UPER encoding of a minimal DENM
- `main/geonet.c` / `.h` - GeoNetworking Basic/Common/SHB headers + BTP-B
- `main/dot11p.c` / `.h` - 802.11 OCB (QoS Data, broadcast) frame + LLC/SNAP
The first port (2026-09-23) carried a few things that Niklas Dathe's current firmware makes unnecessary:
- **Bench listener** (`CONFIG_MICROBU_BENCH_LISTEN`): his `RAW_CAPTURE` / `RAW_FRAME` does the same over the link.
- **BLE pauses advertising while USB is in use**: his TX guard now holds each frame out of the BLE connection-event windows.
- **Battery flags at STATUS octets 103-105**: his layout puts channel-load fields there; the app derives low (3.50 V)
and critical (3.30 V) from `battery_mv` at octet 129.
- **The ETSI test channel** and the UART0 console: the log travels as LOG frames on the USB link.
- **`CONFIG_MICROBU_BATTERY_SCALE_PERMILLE`**: his battery code has no trim. The XIAO's reading was never compared
with a multimeter on the glued-in cell; the app shows 4.14-4.16 V on a charging cell, close to the charger's 4.20 V.
### What Niklas Dathe's latest firmware added over his earlier one
The station grew from about 580 to 1,360 lines. From his commit messages (not all of it read line by line): ITS clock
slewing, a TX guard against BLE collisions, stale-request refusal (`generated_at_ms`), a pending queue that replaces an
unsent VAM with a newer one, Adaptive DCC with channel-busy-ratio measurement, declared radio operating points from
EN 302 571 measurements, robust CCA counters and TX retry, heap diagnostics, asn1c tables kept in flash, BLE with no
eFuse-based gates, an on-device TS 102 941 client (enrolment and authorisation relayed by the phone, trust bootstrap and
update), the `RAW_CAPTURE` debug path, fragmentation of link messages, the XIAO and `mainboard-v5` boards, and the
battery reading.
### Both receive paths stay
`V2X_RX` (ours) and `RAW_FRAME` / `RAW_CAPTURE` (Niklas Dathe's, in the spec) both stay in the firmware, and the app has a switch
(Settings > Connection > ESP32-C5 > Receive path) that chooses which one it consumes. The firmware does not know which: it
always sends `V2X_RX`, and sends `RAW_FRAME` while `RAW_CAPTURE` is on (the app turns it on, mode 0x03, only in raw mode). In raw
mode the app unwraps the frame itself with `GnUnwrap.kt`, a port of `gn_unwrap.c` that `GnUnwrapTest` checks against the C code
on a corpus (`make corpus` in `test/host` writes `app/src/test/resources/gn_unwrap_corpus.tsv`). The app also reassembles
fragmented link messages as the spec defines them, so a raw frame or an indication above one link message works.
### Measured on the bench, 2026-11-11
Production XIAO on COM10, Pixel 9 Pro on BLE, COM3 board as an on-air listener (details and open points in `TODO.md`):
the simulated car's CAMs reach the app; signed CAMs from the phone (tickets 1) and unsigned ones are heard by the
listener; over USB with BLE off 95.7 % of 300 signed CAMs were heard and over BLE with the screen on 95.7 % of 188, so
the BLE link adds no measurable loss; the BLE bond survives a board reset. `tools/station_tx_test.py` plays the phone
over USB and reads the station's own raw capture, which shows the 802.11 source address of what leaves the radio.
### What the new firmware changes for the phone
See `docs/station-link.tex` (revision history at its end). In short: `RESULT`/`STATUS` became `CONFIRM` (0x80) with the 131-octet
status in `CONFIRM.detail` of `STATUS_REQUEST`; STATION_CONFIGURE is 6 octets (type, channel, power,
security, beaconing; no MAC unless the 16-octet form names one, else the address derives from the ticket); BTP-DATA.request carries
`generated_at_ms` (requests older than 1 s are refused); request bodies up to 1536 and indications up
to 65535 octets are fragmented; logs travel as LOG frames (0x7F) on the USB link, so a XIAO needs no
UART adapter any more.
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain with psid 36 (CAM) and 638 (VAM).
Not EU-registered: receivers that verify against the EU trust list drop what it signs.
Time: TimestampIts counts TAI milliseconds since 2004 (TS 102 894-2), 5 leap seconds ahead of UTC;
the app's `ItsTime` follows that.
Known gaps, tracked as TODOs in the source: no real GNSS (lat/long hardcoded
0), no real time source (detectionTime/referenceTime hardcoded 0, decodes as
2004-01-01), fixed (non-rotating) pseudonym MAC, SHB instead of GeoBroadcast
(no multi-hop forwarding), unsecured (no IEEE 1609.2 signing).
-155
View File
@@ -1,155 +0,0 @@
# obu-firmware (micrOBU ESP32-C5)
The firmware of the production MicrOBU: the ESP32-C5 half of the station, on the Seeed XIAO ESP32-C5.
It is the station firmware written by **Niklas Dathe** (`microbu-firmware`, HAW GitLab
urban-mobility-lab/microbu/microbu-firmware, commit e4e4bd8) with the MicrOBU additions listed in
[NOTES.md](NOTES.md). The phone builds CAM and VAM messages; this firmware adds BTP and
GeoNetworking, signs, transmits over ITS-G5, and hands every received ITS message back to the phone.
```mermaid
flowchart LR
App[Android app: facilities and HMI] <-->|USB or encrypted BLE| Link[Station link]
App -->|STATUS_REQUEST, 1 Hz| Link
Link -->|CONFIRM with status| App
Link <--> Wrapper[microbu_v2x]
Wrapper <--> GN[Vanetza BTP and GeoNetworking]
Wrapper <--> Security[Security and device PKI client]
Security <--> NVS[NVS credentials and keys]
GN <--> Radio[ESP32-C5 ITS-G5 radio]
Radio -->|every data frame| Raw[gn_unwrap.c, MicrOBU]
Raw -->|V2X_RX 0x90, signed or not| Link
Link -->|unsigned request| Geo[geonet.c, MicrOBU]
Geo --> Radio
Battery[Battery guard, MicrOBU] -.->|deep sleep below 3.30 V| Radio
```
```yaml
target: ESP32-C5
SDK: ESP-IDF-6.0.2 # exactly; the radio driver ABI is pinned to it
board: Seeed-XIAO-ESP32-C5 # 8 MB flash, one native USB-C port
other_board: mainboard-v5 # the custom PCB, menuconfig -> micrOBU firmware -> Board
runtime:
main/: station-and-link-service
components/microbu_v2x: station-wrapper-and-security # Niklas Dathe, unchanged
components/vanetza: ESP-IDF-component # Niklas Dathe, unchanged
external/vanetza: patched-upstream-source # see external/vanetza/UPSTREAM
link:
spec: docs/station-link.tex (revision 2; revision 1 is Niklas Dathe's)
transports: USB Serial/JTAG (0xAA55 frames) and BLE GATT (service 0000c175-...)
max_message: 512 octets, fragmented above that by the spec
microbu_extensions:
V2X_RX: opcode 0x90, every ITS message heard on air, verified or not
receive_paths: V2X_RX and the spec's RAW_FRAME both stay; the app chooses (Settings > Receive path), RAW_CAPTURE mode 3 turns raw on
unsigned_tx: security profile 1, or 0 with station security 0
radio: polled from STATION_CONFIGURE on
battery_guard: deep sleep below 3.30 V, no phone on USB, runs again from 3.60 V
flash_layout:
nvs: 80 KB at 0x9000
app: 3 MB at 0x20000
telemetry:
battery: calibrated-divider-voltage # GPIO6, enabled by GPIO26, only + and - are wired
temperature: unavailable
charger_source: unavailable
keys:
backend: ESP32-PSA
storage: NVS
NVS_encryption: only-if-flash-encryption-already-active
eFuse_writes: forbidden # cmake/no_efuse_writes.cmake
```
## Build and flash
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
$env:IDF_TOOLS_PATH = "C:\Espressif"
C:\Espressif\frameworks\esp-idf-v6.0.2\export.ps1
cd obu-firmware
idf.py set-target esp32c5 # once per clean build folder
idf.py build
idf.py -p COMx flash # full flash, never app-flash: the partition table is ours
```
```text
menuconfig -> micrOBU firmware -> Board, battery thresholds, BLE passkey, TX BLE guard, status LED
```
Everything else (the `--no-stub` fallback, reading a board's app descriptor before flashing, the
production checklist with the cell, battery and pins): [FLASHING.md](FLASHING.md).
## Using it
The log arrives as `LOG` frames (type 0x7F) on the USB link, so a XIAO needs no UART adapter. To see
the board from the PC:
```powershell
py -3.11 tools/station_status_watch.py COMx 30 --configure --rx
py -3.11 tools/station_tx_test.py COMx --seconds 60 --mac 02:aa:bb:cc:dd:01 # plays the phone, reads the raw own-TX capture
```
It prints the log, the 131-octet STATUS once a second (uptime, signing and radio counters, heap,
battery) and the first V2X_RX messages. Status exchange: the host sends `STATUS_REQUEST` every
1000 ms; `CONFIRM.detail` contains the snapshot.
Received messages reach the phone on two paths that both stay in the firmware: `V2X_RX` (ours, always on, already unwrapped, one message up to 494 octets, fragmented above that up to 2300) and `RAW_FRAME` (the spec's debug capture, on after `RAW_CAPTURE`, the whole radio frame, fragmented when large). The Android app has a switch for which one it consumes. The board always sends `V2X_RX` for a message that fits one link message (up to 494 octets), also while the raw capture is on; a larger one (a road SPATEM or MAPEM) goes out as fragmented `V2X_RX`, except while `RAW_CAPTURE` is on, when the `RAW_FRAME` copy carries it and it is not sent twice. `RAW_CAPTURE` modes are bits: 0x01 on, 0x02 broadcast only, 0x04 own transmissions too (the app uses 0x03; the bench tests use 0x05 to read back the station's own frames). See [NOTES.md](NOTES.md).
```mermaid
flowchart LR
Air[ITS-G5 frame on air] --> Radio[C5 radio, promiscuous RX]
Radio --> Stack[Vanetza stack: decap and verify]
Radio --> Unwrap[gn_unwrap.c: 802.11, LLC, GN, BTP, signature envelope]
Radio -->|only while RAW_CAPTURE is on| Cap[Raw capture tap: ITS5 record]
Stack -->|verified only| Ind[BTP_DATA_INDICATION 0x81]
Unwrap -->|signed or not, fragmented above 494 octets, not when RAW_CAPTURE is on| Rx[V2X_RX 0x90, MicrOBU]
Cap -->|fragmented if large| Raw[RAW_FRAME 0x85, spec]
Ind --> Link[Station link: USB or BLE]
Rx --> Link
Raw --> Link
Link --> App[Android app]
App -->|Receive path: V2X_RX| UseA[uses V2X_RX, ignores RAW_FRAME]
App -->|Receive path: Raw frames| UseB[reassembles, unwraps with GnUnwrap, ignores V2X_RX]
```
## BLE pairing
```yaml
# as documented for Niklas Dathe's BLE code, which this firmware does not modify
BLE_pairing:
compile_time: CONFIG_MICROBU_BLE_PASSKEY
default: 123456
disable_value: 0
unprovisioned_station: USB-only
bond_storage: NVS # 80 KB, so the bond persists
owner: first-bond-only
remote_bond_replacement: refused
hardware_security: existing-state-only
generate_hardware_keys: forbidden
```
The passkey is public, so the link is encrypted but not protected against an active attacker during
the first pairing. A phone that was paired before must forget `micrOBU-XXXX` in Android's Bluetooth
settings after the board's NVS was erased. BLE and ITS-G5 share one RF front end: the firmware holds a
frame out of the BLE connection-event windows (`CONFIG_MICROBU_TX_BLE_GUARD`; calibrated for a 20 ms connection interval only). The bond is one per board and survives a reset; with several micrOBUs nearby pair the right one in Android first (FLASHING.md).
## Tests
```powershell
$env:PATH = "C:\msys64\ucrt64\bin;C:\msys64\usr\bin;$env:PATH"
cd obu-firmware\test\host
make firmware # 40 unit tests: link codec, STATUS, reassembly, V2X_RX, policies. PASS or FAIL per test
make # everything: chain, replay of recorded frames, fuzz, battery, firmware
```
These run on the PC and cannot test the radio, BLE, NVS or USB. The board-side tests (link conformance, transmit soak, reset and fuzz, run overnight on the spare board) are in [test/bench](test/bench/README.md), described in [docs/overnight-bench-test.pdf](docs/overnight-bench-test.pdf). What still needs a board, a phone or a
second ESP32-C5 is listed in [../TODO.md](../TODO.md). More: [test/host/README.md](test/host/README.md).
## More
| | |
|---|---|
| [NOTES.md](NOTES.md) | Every MicrOBU addition and why, what changed for the phone |
| [FLASHING.md](FLASHING.md) | Toolchain, flashing, bring-up checklist, battery and pins |
| [docs/station-link.pdf](docs/station-link.pdf) | The link interface reference, revision 2 (source: `station-link.tex`) |
| [external/vanetza/LICENSE.md](external/vanetza/LICENSE.md) | Vanetza licence |
| [external/vanetza/UPSTREAM](external/vanetza/UPSTREAM) | Upstream revision of the vendored Vanetza |
| [ESP32-C5 flash encryption](https://docs.espressif.com/projects/esp-idf/en/v6.0.2/esp32c5/security/flash-encryption.html) | Existing hardware state only; this firmware never enables it |
-15
View File
@@ -1,15 +0,0 @@
# Reject SDK features that can program permanent chip state or auto-create hardware keys.
foreach(_microbu_option
CONFIG_SECURE_BOOT
CONFIG_SECURE_FLASH_ENC_ENABLED
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
CONFIG_BOOTLOADER_ANTI_ROLLBACK_ENABLE
CONFIG_SECURE_DISABLE_ROM_DL_MODE
CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE
CONFIG_NVS_ENCRYPTION
CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC
CONFIG_ESP_TEE)
if(${_microbu_option})
message(FATAL_ERROR "${_microbu_option} is forbidden: this firmware must not program eFuses or auto-provision hardware keys")
endif()
endforeach()
@@ -1,166 +0,0 @@
# micrOBU V2X runtime on the Vanetza component (LGPL-3.0-or-later).
cmake_minimum_required(VERSION 3.22)
set(V2X_PORT "${CMAKE_CURRENT_LIST_DIR}")
if(ESP_PLATFORM)
# IDF dependency discovery evaluates this file before Kconfig is available.
idf_component_register(SRCS "${V2X_PORT}/src/access.cpp"
INCLUDE_DIRS "${V2X_PORT}/include"
REQUIRES vanetza mbedtls ${MICROBU_CRYPTO_ADAPTER_COMPONENT}
PRIV_REQUIRES esp_wifi esp_phy esp_event nvs_flash)
if(CMAKE_BUILD_EARLY_EXPANSION)
return()
endif()
if(NOT CONFIG_COMPILER_CXX_EXCEPTIONS OR NOT CONFIG_COMPILER_CXX_RTTI)
message(FATAL_ERROR "microbu_v2x requires CONFIG_COMPILER_CXX_EXCEPTIONS=y and CONFIG_COMPILER_CXX_RTTI=y")
endif()
set(V2X_TARGET ${COMPONENT_LIB})
set(V2X_NETWORK ${CONFIG_MICROBU_V2X_NETWORK})
set(V2X_CAM ${CONFIG_MICROBU_V2X_CAM})
set(V2X_DENM ${CONFIG_MICROBU_V2X_DENM})
set(V2X_VAM ${CONFIG_MICROBU_V2X_VAM})
set(V2X_HIL ${CONFIG_MICROBU_V2X_HIL})
set(V2X_SECURITY ${CONFIG_MICROBU_V2X_SECURITY})
set(V2X_SECURITY_VERIFY ${CONFIG_MICROBU_V2X_SECURITY_VERIFY})
set(V2X_PKI ${CONFIG_MICROBU_V2X_PKI})
set(V2X_NVS_CREDENTIALS ${CONFIG_MICROBU_V2X_NVS_CREDENTIALS})
else()
project(microbu_v2x LANGUAGES C CXX)
option(V2X_NETWORK "GeoNetworking router, BTP and DCC" ON)
option(V2X_CAM "Release 2 CAM codec/endpoint" ON)
option(V2X_DENM "Release 2 DENM codec/endpoint" ON)
option(V2X_VAM "Release 2 VAM codec/endpoint" ON)
set(V2X_HIL OFF)
option(V2X_SECURITY "TS 103 097 signing security entity and TS 102 723-8 identifier-change service" ON)
option(V2X_SECURITY_VERIFY "SN-DECAP verification of received secured packets (IEEE 1609.2 clause 5.2, TS 103 097 clause 7.1)" ON)
option(V2X_PKI "TS 102 941 enrolment/authorization request-response core" OFF)
set(V2X_MBEDTLS_ROOT "" CACHE PATH
"Host only: mbedTLS (>= 3.6 or 4.x/TF-PSA-Crypto) source tree; builds the PSA backend for testing against OpenSSL")
set(VANETZA_SOURCE_DIR "" CACHE PATH
"Host only: an already patched Vanetza tree (default: build it from external/vanetza and ../vanetza/patches)")
add_subdirectory("${V2X_PORT}/../vanetza" "${CMAKE_BINARY_DIR}/vanetza")
add_library(microbu_v2x STATIC src/access.cpp)
add_library(Microbu::v2x ALIAS microbu_v2x)
set(V2X_TARGET microbu_v2x)
target_include_directories(${V2X_TARGET} PUBLIC include)
target_link_libraries(${V2X_TARGET} PUBLIC vanetza)
endif()
target_compile_features(${V2X_TARGET} PUBLIC cxx_std_17)
set_target_properties(${V2X_TARGET} PROPERTIES C_STANDARD 11 CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
if(V2X_SECURITY AND NOT V2X_NETWORK)
message(FATAL_ERROR "The security entity serves the GeoNetworking layer: V2X_SECURITY requires V2X_NETWORK")
endif()
if(V2X_SECURITY_VERIFY AND NOT V2X_SECURITY)
message(FATAL_ERROR "V2X_SECURITY_VERIFY requires V2X_SECURITY")
endif()
if(V2X_PKI AND NOT V2X_SECURITY)
message(FATAL_ERROR "V2X_PKI requires V2X_SECURITY")
endif()
target_compile_definitions(${V2X_TARGET} PUBLIC
V2X_NETWORK=$<BOOL:${V2X_NETWORK}> V2X_CAM=$<BOOL:${V2X_CAM}>
V2X_DENM=$<BOOL:${V2X_DENM}> V2X_VAM=$<BOOL:${V2X_VAM}> V2X_HIL=$<BOOL:${V2X_HIL}>
V2X_SECURITY=$<BOOL:${V2X_SECURITY}> V2X_SECURITY_VERIFY=$<BOOL:${V2X_SECURITY_VERIFY}>
V2X_PKI=$<BOOL:${V2X_PKI}>)
set(_sources "${V2X_PORT}/src/its_g5_frame.cpp")
if(V2X_NETWORK)
list(APPEND _sources "${V2X_PORT}/src/stack.cpp" "${V2X_PORT}/src/management.cpp")
if(NOT ESP_PLATFORM)
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
target_link_libraries(${V2X_TARGET} PRIVATE OpenSSL::Crypto)
endif()
endif()
if(V2X_CAM OR V2X_DENM OR V2X_VAM)
list(APPEND _sources "${V2X_PORT}/src/facilities.cpp")
endif()
if(V2X_HIL)
list(APPEND _sources "${V2X_PORT}/src/hil.cpp")
endif()
if(V2X_SECURITY)
list(APPEND _sources "${V2X_PORT}/src/ecc.cpp" "${V2X_PORT}/src/security_module.cpp"
"${V2X_PORT}/src/security.cpp" "${V2X_PORT}/src/identity_manager.cpp"
"${V2X_PORT}/src/sign_header_policy.cpp" "${V2X_PORT}/src/credentials.cpp")
if(ESP_PLATFORM)
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp" "${V2X_PORT}/src/security_backend.cpp"
"${V2X_PORT}/src/local_security.cpp")
if(CONFIG_MICROBU_V2X_CRYPTO_SE051 OR CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM)
if(NOT MICROBU_CRYPTO_ADAPTER_COMPONENT)
message(FATAL_ERROR "External security module selected: set MICROBU_CRYPTO_ADAPTER_COMPONENT to a real adapter component")
endif()
endif()
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
if(V2X_NVS_CREDENTIALS)
# CredentialStore on nvs_flash (credentials.hpp); the application initialises NVS
list(APPEND _sources "${V2X_PORT}/src/nvs_credential_store.cpp")
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_NVS_CREDENTIALS=1)
endif()
else()
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_OPENSSL=1)
target_compile_definitions(${V2X_TARGET} PRIVATE OPENSSL_API_COMPAT=0x10101000L)
if(V2X_MBEDTLS_ROOT)
set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE)
set(ENABLE_TESTING OFF CACHE BOOL "" FORCE)
set(MBEDTLS_FATAL_WARNINGS OFF CACHE BOOL "" FORCE)
set(GEN_FILES OFF CACHE BOOL "" FORCE)
# ESP-IDF's mbedTLS fork includes "mbedtls/bignum.h"/"mbedtls/ecp.h" wrappers that only
# its own port directory provides (they wrap the TF-PSA-Crypto private headers and add
# hardware-acceleration hooks). Recreate the plain wrappers so the same tree builds here.
set(_v2x_mbedtls_shim "${CMAKE_BINARY_DIR}/mbedtls-shim/mbedtls")
foreach(_hdr bignum ecp)
if(EXISTS "${V2X_MBEDTLS_ROOT}/tf-psa-crypto/drivers/builtin/include/mbedtls/private/${_hdr}.h"
AND NOT EXISTS "${V2X_MBEDTLS_ROOT}/include/mbedtls/${_hdr}.h")
file(WRITE "${_v2x_mbedtls_shim}/${_hdr}.h"
"#pragma once
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
#include \"mbedtls/private/${_hdr}.h\"
")
endif()
endforeach()
if(EXISTS "${_v2x_mbedtls_shim}")
file(WRITE "${CMAKE_BINARY_DIR}/mbedtls-shim/sdkconfig.h" "#pragma once
")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I${CMAKE_BINARY_DIR}/mbedtls-shim")
endif()
add_subdirectory("${V2X_MBEDTLS_ROOT}" "${CMAKE_BINARY_DIR}/mbedtls" EXCLUDE_FROM_ALL)
if(TARGET tfpsacrypto)
set(_v2x_psa tfpsacrypto) # mbedTLS 4.x
else()
set(_v2x_psa mbedcrypto) # mbedTLS 3.x
endif()
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp")
target_link_libraries(${V2X_TARGET} PUBLIC ${_v2x_psa})
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
endif()
endif()
if(V2X_PKI)
list(APPEND _sources "${V2X_PORT}/src/pki.cpp" "${V2X_PORT}/src/trust_update.cpp")
if(ESP_PLATFORM OR V2X_MBEDTLS_ROOT)
list(APPEND _sources "${V2X_PORT}/src/ecies_mbedtls.cpp")
endif()
if(NOT ESP_PLATFORM)
list(APPEND _sources "${V2X_PORT}/src/ecies_openssl.cpp")
endif()
endif()
endif()
list(REMOVE_DUPLICATES _sources)
target_sources(${V2X_TARGET} PRIVATE ${_sources})
if(ESP_PLATFORM AND CONFIG_MICROBU_V2X_RADIO_C5)
include("${V2X_PORT}/radio_c5.cmake")
endif()
if(ESP_PLATFORM AND CONFIG_IDF_TARGET_ESP32C5)
# ROM UART0 clock repair for warm resets (see the source); kept by an undefined-symbol reference.
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/esp32c5_rom_uart_clock.c")
target_link_libraries(${V2X_TARGET} INTERFACE "-u v2x_esp32c5_rom_uart_clock_link")
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_compile_options(${V2X_TARGET} PRIVATE -ffunction-sections -fdata-sections
-Wno-error=deprecated-declarations)
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15)
target_compile_options(${V2X_TARGET} PRIVATE -Wno-error=deprecated-variadic-comma-omission)
endif()
endif()
if(ESP_PLATFORM)
target_compile_options(${V2X_TARGET} PRIVATE
$<$<COMPILE_LANGUAGE:C>:-Wno-error=unused-function>
$<$<COMPILE_LANGUAGE:C>:-Wno-error=maybe-uninitialized>)
endif()
@@ -1,98 +0,0 @@
menu "micrOBU V2X stack (Vanetza)"
choice MICROBU_V2X_PROFILE
prompt "Stack entry point"
default MICROBU_V2X_PROFILE_NETWORK
config MICROBU_V2X_PROFILE_ACCESS
bool "Access: AL_DATA / IN-SAP"
config MICROBU_V2X_PROFILE_NETWORK
bool "Network: BTP-DATA / NF-SAP"
config MICROBU_V2X_PROFILE_FACILITIES
bool "Facilities endpoints (CAM, DENM, VAM)"
endchoice
config MICROBU_V2X_NETWORK
bool
default y if !MICROBU_V2X_PROFILE_ACCESS
config MICROBU_V2X_CAM
bool "Release 2 CAM codec and endpoint"
default y if MICROBU_V2X_PROFILE_FACILITIES
depends on MICROBU_V2X_NETWORK
config MICROBU_V2X_DENM
bool "Release 2 DENM codec and endpoint"
default y if MICROBU_V2X_PROFILE_FACILITIES
depends on MICROBU_V2X_NETWORK
config MICROBU_V2X_VAM
bool "Release 2 VAM codec and endpoint"
default y if MICROBU_V2X_PROFILE_FACILITIES
depends on MICROBU_V2X_NETWORK
config MICROBU_V2X_SECURITY
bool "TS 103 097 signing security entity and identifier-change service"
default y
depends on MICROBU_V2X_NETWORK
help
SN-SAP security entity: signs outgoing GeoNetworking packets with
authorization tickets the application provisions (TS 103 097
V2.2.1, IEEE Std 1609.2) on the mbedTLS PSA backend and runs the
TS 102 723-8 clause 6.3 identifier-change two-phase commit that
the GN core, access adapter and facilities subscribe to. Without
it a stack with itsGnSecurity enabled fails closed.
choice MICROBU_V2X_CRYPTO
prompt "Security module"
depends on MICROBU_V2X_SECURITY
default MICROBU_V2X_CRYPTO_ESP32
help
Where the station's private keys live and are used
(security_module.hpp). Hashing, verification and point
decompression run on the ESP32 PSA backend unless the V2X HSM
takes them as well.
config MICROBU_V2X_CRYPTO_ESP32
bool "Software on the ESP32 (keys in NVS, PSA crypto)"
config MICROBU_V2X_CRYPTO_SE051
bool "SE051 over I2C (requires an adapter component)"
config MICROBU_V2X_CRYPTO_V2X_HSM
bool "V2X HSM for keys and public operations (requires an adapter component)"
endchoice
config MICROBU_V2X_SECURITY_VERIFY
bool "SN-DECAP verification of received secured packets"
default y
depends on MICROBU_V2X_SECURITY
help
Verify received EtsiTs103097Data-Signed packets (IEEE 1609.2
clause 5.2 with the TS 103 097 clause 7.1 profile checks, the
certificate chain to the provisioned trust anchors, generation
time plausibility and replay detection). Without it SN-DECAP
reports Configuration_Problem and a strict GeoNetworking receiver
drops every secured packet.
config MICROBU_V2X_NVS_CREDENTIALS
bool "Credential store on NVS"
default y
depends on MICROBU_V2X_SECURITY
help
NvsCredentialStore keeps the station's provisioned credentials
(root and CA certificates, authorization tickets with their
private keys, credentials.hpp bundle) as one blob in the
nvs_flash component's storage. The application initialises NVS
and decides on NVS encryption; without this option the
application supplies its own CredentialStore.
config MICROBU_V2X_PKI
bool "TS 102 941 enrolment and authorization request-response core"
default n
depends on MICROBU_V2X_SECURITY
help
Builds and parses EtsiTs102941Data enrolment/authorization
requests and responses (TS 102 941 V2.2.1 clause 6.2.3). The
transport to the EA/AA and credential storage are supplied by the
application.
choice MICROBU_V2X_RADIO
prompt "Access adapter"
default MICROBU_V2X_RADIO_EXTERNAL
config MICROBU_V2X_RADIO_EXTERNAL
bool "Application-provided access adapter"
config MICROBU_V2X_RADIO_C5
bool "Experimental integrated ESP32-C5 ITS-G5 radio"
depends on IDF_TARGET_ESP32C5
help
Uses OpenTrafficMap's private driver transmit path. Only the
pinned ESP-IDF version is accepted. Hardware/RF and DCC
qualification remain separate acceptance requirements.
endchoice
endmenu
@@ -1,102 +0,0 @@
#pragma once
#include <microbu_v2x/security.hpp>
#include <optional>
#include <string>
#include <vector>
/** A station's provisioned credentials and how they are kept.
*
* TS 102 940 V2.1.1 clause 6 (trust model: root CA, EA/AA, tickets) and TS 102 941
* V2.2.1 (credential life cycle) leave the obtaining and keeping of certificates to
* the station; TS 102 723-8 has no primitive for it. The security entity takes
* them as a TrustConfiguration and a CertificatePool (security.hpp). This header
* fixes the octets in between. Certificates are COER EtsiTs103097Certificate
* values (TS 103 097 V2.2.1 clause 6).
*
* Credentials is the laboratory provisioning bundle, which carries the private
* scalar of each ticket's verification key (IEEE Std 1609.2 clause 6.4.36 curves).
* Format (this library's definition, version 1): the ASCII magic "VCR1" followed
* by records [type: 1 octet][length: 2 octets, big-endian][payload]. Types: 1 root
* CA certificate, 2 subordinate CA certificate (AA/EA), 3 ticket certificate, 4
* ticket private key ([curve: 1 octet, 1 = NIST P-256, 2 = brainpoolP256r1, 3 =
* brainpoolP384r1][scalar]) which follows its ticket certificate. The keys travel
* in the clear, so the transport must be a trusted one. import_keys() moves them
* into the security module.
*
* StoredCredentials is what the station keeps: the same certificates, and for each
* ticket the KeyId of its key in the security module instead of the key. Format
* "VCS1" with the record types 1 to 3 above and 5, the KeyId (4 octets, big-endian),
* which follows its ticket certificate. Decoding fails closed on any deviation.
*/
namespace microbu_v2x::security {
struct Credentials {
struct Ticket {
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
PrivateKey key; // private scalar of verifyKeyIndicator
};
std::vector<ByteBuffer> roots; // clause 7.2.3, self-signed
std::vector<ByteBuffer> authorities; // clause 7.2.4, issued by a root or another CA
std::vector<Ticket> tickets; // clause 7.2.1, with keys
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
};
struct StoredCredentials {
struct Ticket {
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
KeyId key; // the verification key in the security module
};
std::vector<ByteBuffer> roots;
std::vector<ByteBuffer> authorities;
std::vector<Ticket> tickets;
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
};
/// bundle octets of the credentials (formats above)
ByteBuffer encode(const Credentials&);
ByteBuffer encode(const StoredCredentials&);
/// parse a bundle; false (and an untouched output) when the octets are not a well-formed bundle
bool decode(const ByteBuffer& bundle, Credentials& out);
bool decode(const ByteBuffer& bundle, StoredCredentials& out);
/** Import every ticket key of a provisioning bundle into the module, paired with the verification key of its
* certificate. None, with every key of this call destroyed again, when a ticket certificate does not decode or
* its key does not belong to it. Throws what the module throws. */
std::optional<StoredCredentials> import_keys(const Credentials&, SecurityModule&);
/** Result of feeding credentials into the trust configuration and the pool: how many
* of each were accepted and the first refusal (Result::accepted when everything was). */
struct ApplyReport {
std::size_t roots = 0, authorities = 0, tickets = 0;
Result result = Result::accepted;
};
/** Add every root, then every authority, then every ticket, each through the checks of
* TrustConfiguration::add_* and CertificatePool::add (TS 103 097 profiles, key/certificate
* match); stops at the first refusal so that a broken item is not silently skipped. */
ApplyReport apply(const StoredCredentials&, TrustConfiguration&, CertificatePool&);
/** Storage the application chooses: keeps one set. load() returns Result::rejected
* when nothing is stored and Result::invalid_argument when the stored octets do not
* decode; save() replaces what was there; erase() removes it. */
class CredentialStore {
public:
virtual ~CredentialStore() = default;
virtual Result save(const StoredCredentials&) = 0;
virtual Result load(StoredCredentials&) = 0;
virtual Result erase() = 0;
};
/// a bundle in one file (hosts, or an ESP-IDF VFS the application mounted)
class FileCredentialStore final : public CredentialStore {
public:
explicit FileCredentialStore(std::string path) : path_(std::move(path)) {}
Result save(const StoredCredentials&) override;
Result load(StoredCredentials&) override;
Result erase() override;
private:
std::string path_;
};
} // namespace microbu_v2x::security
@@ -1,28 +0,0 @@
#pragma once
#include <microbu_v2x/credentials.hpp>
#include <string>
/** CredentialStore on ESP-IDF non-volatile storage (the nvs_flash component).
*
* The stored credentials (credentials.hpp: certificates and KeyIds, no private
* keys) as one NVS blob under a namespace and key of the application's choosing.
* The application initialises NVS itself (nvs_flash_init or nvs_flash_secure_init)
* before using the store. Built with
* CONFIG_MICROBU_V2X_NVS_CREDENTIALS (default on with the security entity).
*/
namespace microbu_v2x::security {
class NvsCredentialStore final : public CredentialStore {
public:
/// namespace_name up to 15 characters, key up to 15 characters (NVS limits)
explicit NvsCredentialStore(std::string namespace_name = "microbu_v2x", std::string key = "credentials") :
namespace_(std::move(namespace_name)), key_(std::move(key)) {}
Result save(const StoredCredentials&) override;
Result load(StoredCredentials&) override;
Result erase() override;
private:
std::string namespace_;
std::string key_;
};
} // namespace microbu_v2x::security
@@ -1,58 +0,0 @@
#pragma once
#include <cstdint>
namespace microbu_v2x::pki {
// ETSI TS 103 601 V2.1.1 clauses 5.1.2 and 5.1.4.
// Times use a monotonic millisecond clock. N1 includes the initial attempt.
struct RetryPolicy {
std::uint64_t interval_ms = 60000;
std::uint64_t lifetime_ms = 190000;
std::uint32_t attempts = 3;
std::uint64_t minimum_response_ms = 55000;
std::uint64_t authority_context_ms = 3600000;
bool valid() const {
return attempts && interval_ms >= minimum_response_ms && interval_ms && lifetime_ms &&
(lifetime_ms - 1) / attempts >= interval_ms && authority_context_ms >= lifetime_ms;
}
};
class RetrySchedule {
public:
bool begin(std::uint64_t now, RetryPolicy policy = {}) {
stop();
if (!policy.valid()) return false;
policy_ = policy;
start_ = last_ = now;
attempts_ = 1;
active_ = true;
return true;
}
bool poll(std::uint64_t now) {
if (active_ && (now < last_ || now - start_ >= policy_.lifetime_ms ||
(attempts_ == policy_.attempts && now - last_ >= policy_.interval_ms))) stop();
return active_;
}
bool repeat(std::uint64_t now) {
if (!poll(now) || now - last_ < policy_.interval_ms || attempts_ >= policy_.attempts) return false;
last_ = now;
++attempts_;
return true;
}
void stop() { active_ = false; }
bool active() const { return active_; }
std::uint32_t attempts() const { return attempts_; }
private:
RetryPolicy policy_;
std::uint64_t start_ = 0;
std::uint64_t last_ = 0;
std::uint32_t attempts_ = 0;
bool active_ = false;
};
} // namespace microbu_v2x::pki
@@ -1,382 +0,0 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <microbu_v2x/id_change.hpp>
#include <microbu_v2x/security_module.hpp>
#include <vanetza/common/clock.hpp>
#include <vanetza/common/its_aid.hpp>
#include <vanetza/common/position_provider.hpp>
#include <vanetza/common/runtime.hpp>
#include <vanetza/security/backend.hpp>
#include <vanetza/security/hashed_id.hpp>
#include <vanetza/security/security_entity.hpp>
#include <vanetza/security/v3/certificate.hpp>
#include <vanetza/security/v3/certificate_provider.hpp>
#include <vanetza/security/v3/certificate_validator.hpp>
#include <vanetza/security/v3/issuer_memory_lookup.hpp>
#include <vanetza/security/v3/location_checker.hpp>
#include <vanetza/security/v3/revocation_lookup.hpp>
#include <vanetza/security/v3/sign_header_policy.hpp>
#include <vanetza/security/v3/trust_store.hpp>
#include <chrono>
#include <deque>
#include <functional>
#include <memory>
#include <vector>
/** Signing security entity for the SN-SAP.
*
* Standards: TS 103 097 V2.2.1 (secured message and certificate formats,
* clause 5.2 SignedData constraints, clause 7 profiles), IEEE Std 1609.2
* (hashing and ECDSA, clause 5.3), TS 102 940 V2.1.1 (trust model: root CA ->
* AA -> authorization ticket, clause 6.5 identity management), TS 102 941
* V2.2.1 (credential life cycle), TS 102 723-8 V2.0.0/V1.1.1 (SN-SAP
* primitives), TS 103 300-3 V2.3.1 clause 6.5 (VAM signing and certificate
* attachment). Verification of received messages (SN-DECAP) follows IEEE Std
* 1609.2 clause 5.2 as TS 103 097 clause 5.2 requires, with the profile checks of
* clause 7.1 and the chain checks of TS 102 940 clause 6; it is built when
* V2X_SECURITY_VERIFY is set (default with the security feature), otherwise
* SN-DECAP reports Configuration_Problem.
*/
namespace microbu_v2x::security {
using vanetza::ByteBuffer;
using vanetza::security::HashedId8;
using vanetza::security::PrivateKey;
using vanetza::security::v3::Certificate;
// IEEE Std 1609.2 Duration: a year is 31556952 seconds.
// Bounds outside Time32 are invalid rather than wrapping into the past.
vanetza::security::v3::StartAndEndValidity validity_bounds(const Certificate&);
/** SN-ENCAP.request context_information values understood by this entity
* (TS 102 723-8 V1.1.1 Table 24: opaque octets "used in selecting properties
* of the underlying security protocol"; the standard leaves the content to the
* implementation, these values are this library's definition). */
namespace context {
/// VAM generated for a VRU cluster: TS 103 300-3 V2.3.1 clause 6.5.3 500 ms certificate cadence
inline const ByteBuffer vam_cluster {0x01};
}
/** Authorization tickets owned by this station, each with the KeyId of its private key in the security module.
*
* TS 103 097 V2.2.1 clause 7.2.1 (AT profile), TS 102 940 V2.1.1 clause 6.5
* ("multiple authorization tickets ... to be used ... over its life time").
* Tickets come from the station's TS 102 941 client (key generated in the
* module) or from laboratory provisioning (key imported into the module,
* credentials.hpp). The pool never holds a private key: own_private_key() of
* the upstream CertificateProvider contract throws, and SN-ENCAP signs through
* SecurityModule::sign_digest with own_key().
*/
class CertificatePool : public vanetza::security::v3::BaseCertificateProvider {
public:
/// An authorization ticket (TS 103 097 V2.2.1 clause 7.2.1 profile) and the module key of its verifyKeyIndicator.
struct Ticket {
Certificate certificate;
KeyId key;
HashedId8 digest; // HashedId8 per TS 103 097 clause 6 / IEEE 1609.2 clause 6.4.3
};
explicit CertificatePool(SecurityModule&);
/** Add a ticket. Fails closed (Result::invalid_argument) when the certificate
* does not decode, is not an authorization ticket (clause 7.2.1: issuer
* sha256AndDigest/sha384AndDigest, appPermissions present, no
* certIssuePermissions), or the module holds no key with the certificate's
* verification key. Duplicate digests are rejected. */
Result add(const ByteBuffer& coer_certificate, KeyId);
Result add(Certificate, KeyId);
/// pool bookkeeping for the application's provisioning and persistence
std::size_t size() const { return tickets_.size(); }
bool empty() const { return tickets_.empty(); }
const std::vector<Ticket>& tickets() const { return tickets_; }
/// currently selected ticket, nullptr when the pool is empty
const Ticket* current() const;
/// next different ticket valid at now (round robin), nullptr when none
const Ticket* next_valid(vanetza::Clock::time_point now) const;
/// make the ticket with this digest current (identifier change COMMIT)
Result select(const HashedId8&);
/// drop tickets whose validity ended before now, never the current one; returns count
std::size_t prune(vanetza::Clock::time_point now);
/// the module that holds the ticket keys
SecurityModule& module() { return module_; }
/// module key of the current ticket; std::logic_error when empty
KeyId own_key() const;
// v3::CertificateProvider: the current ticket; std::logic_error when empty
const Certificate& own_certificate() override;
/// std::logic_error: private keys stay in the security module
const PrivateKey& own_private_key() override;
private:
SecurityModule& module_;
std::vector<Ticket> tickets_;
std::size_t current_ = 0;
};
/** Trust anchors and issuing authorities supplied by the application.
* TS 102 940 V2.1.1 clause 6.1 (root CA, AA), TS 103 097 clauses 7.2.3/7.2.4;
* TS 102 941 V2.2.1 clause 6.3 CTL/CRL retrieval is not part of this library. */
class TrustConfiguration {
public:
/// self-signed root CA certificate (clause 7.2.3) -> trust store and issuer lookup
Result add_root(const ByteBuffer& coer_certificate);
Result add_root(const Certificate&);
/// AA or other subordinate CA certificate (clause 7.2.4) -> issuer lookup; a certificate
/// already known is Result::rejected (nothing changes), a non-CA one invalid_argument
Result add_authority(const ByteBuffer& coer_certificate);
Result add_authority(const Certificate&);
const vanetza::security::v3::TrustStore& roots() const { return roots_; }
const vanetza::security::v3::IssuerMemoryLookup& issuers() const { return issuers_; }
/// every CA certificate added, in the order added (views into the issuer lookup, which holds the one copy)
std::vector<const Certificate*> authorities() const;
/// the CA certificate whose digest ends in this HashedId3 (P2P certificate distribution), or nullptr
const Certificate* authority(const vanetza::security::HashedId3& id) const;
/** TS 102 941 V2.2.1 clause 6.3.3/6.3.6: a certificate the named issuer has revoked
* (the RCA's CRL lists the CA certificates it no longer trusts). The validator walks
* every chain link against this list (IEEE Std 1609.2 clause 5.2: a revoked
* certificate anywhere in the chain invalidates it), so a revoked AA takes all its
* tickets with it; the station's own tickets included (it stops signing). */
void revoke(const HashedId8& issuer, const HashedId8& certificate);
/// forget every revocation recorded for this issuer (a fresh CRL replaces the old one)
void clear_revocations(const HashedId8& issuer);
const vanetza::security::v3::RevocationLookup& revocations() const { return revocations_; }
private:
vanetza::security::v3::TrustStore roots_;
vanetza::security::v3::IssuerMemoryLookup issuers_;
// Digests only : a decoded certificate costs about 3.5 kB of heap on the ESP32-C5, and a second copy
// of every CA certificate here left the Wi-Fi driver without TX buffers. issuers_ holds the certificate.
std::vector<HashedId8> authority_digests_;
vanetza::security::v3::RevocationMemoryLookup revocations_;
};
/** IEEE Std 1609.2 clause 5.3.1 certificate signature: Hash(Hash(toBeSigned) || Hash(issuer
* certificate)) with the hash algorithm of the IssuerIdentifier choice (sha256AndDigest /
* sha384AndDigest, or the algorithm named in the self choice with the empty string as
* issuer hash), verified with the issuer's verification key; issuer == nullptr means
* self-signed. TS 103 097 V2.2.1 clause 6 admits NIST P-256, brainpoolP256r1 (SHA-256)
* and brainpoolP384r1 (SHA-384). */
bool verify_certificate_signature(vanetza::security::Backend&, const Certificate& subject, const Certificate* issuer);
/** IEEE Std 1609.2-2025 clause 5.1.2 permission consistency of a certificate chain, chain[0]
* the end entity and the last element the anchor: every appPermissions entry of the end
* entity is covered by a PsidGroupPermissions group of each ancestor whose chain-length
* window (6.4.28) reaches down to the end entity and whose eeType admits it, the SSP
* inside the group's range (6.4.29/6.4.30 SspRange, BitmapSspRange: a 1 bit of the mask
* fixes the subordinate's bit; an omitted SSP needs "all"); every subordinate CA's ranges
* nest inside its issuer's. Unknown CHOICE alternatives are critical (5.2.6): false.
* Used by the receive-side chain validator and by the issuing tools before they write. */
bool chain_permissions_consistent(const std::vector<const Certificate*>& chain);
/** IEEE Std 1609.2-2025 clause 6.4.17: no part of the subject's region may lie outside the
* issuer's. No issuer region: true; issuer region but none on the subject: false;
* geometric issuer regions by the upstream geometry; identifiedRegion issuer (6.4.21 to
* 6.4.24): identifier containment for an identifiedRegion subject, the
* permissive_identified_region policy for a geometric subject (no border database). */
bool region_within(const Certificate& subject, const Certificate& issuer, bool permissive_identified_region);
/** Receive-side parameters that TS 103 097 leaves to the station. generationTime
* plausibility: IEEE Std 1609.2 clause 5.2.3.2 lists it among the relevance checks
* without fixing values; the defaults are a 3 s clock tolerance into the future and the
* 5 min window the TS 103 096-2 test purposes apply to generation times (the CAM/DENM
* services apply their own, tighter freshness rules on top). Replay: a message whose
* (signer digest, generationTime) pair was already accepted is DUPLICATE_MESSAGE
* (TS 102 723-8 Table 27 report). */
struct VerificationPolicy {
std::chrono::seconds generation_time_future_tolerance {3};
std::chrono::seconds generation_time_max_age {300};
std::size_t replay_window = 256; // remembered accepted (signer, time) pairs, 0 disables
std::size_t verified_chain_cache = 64; // authorization tickets whose chain signature was verified
std::size_t certificate_cache_limit = 32; // learned certificates kept (the cache is emptied beyond it)
std::size_t learned_authority_limit = 8; // AA certificates learned through P2P distribution
bool permissive_identified_region = true; // identifiedRegion without a country database: accept (see docs)
};
/** TS 103 097 V2.2.1 clause 5.2 and 7.1.1 to 7.1.3 structural checks of a received
* signed message, before any cryptography: protocolVersion 3 on both levels, hashId
* consistent with the signature choice, generationTime present, p2pcdLearningRequest and
* missingCrlIdentifier absent, per ITS-AID: CAM without expiryTime, generationLocation
* and encryptionKey; DENM with generationLocation and with a certificate as signer,
* without expiryTime and encryptionKey; signer digest or certificate (not self).
* Returns Success when the structure is admissible, otherwise the report to give. */
vanetza::security::VerificationReport check_profile(const vanetza::security::v3::SecuredMessage&);
/** Header fields and signer identifier per message profile.
*
* TS 103 097 V2.2.1 clause 5.2: psid and generationTime always present,
* p2pcdLearningRequest and missingCrlIdentifier always absent.
* - CAM (ITS-AID 36, TS 102 965 Table A.1): clause 7.1.1 - digest by default,
* certificate once one second after its last inclusion, immediately after a
* CAM from an unknown AT (request_certificate) or an inline P2PCD request for
* our AT, inlineP2pcdRequest for unknown certificates, requestedCertificate
* for known CA certificates; no other header fields.
* - DENM (37): clause 7.1.2 - certificate always, generationLocation present.
* - VAM (638): TS 103 300-3 V2.3.1 clause 6.5.3 - individual VAM: certificate
* if >= 1 s since the last certificate attached to a VAM or a new CAM signer
* was observed (report_new_cam_signer), else digest; cluster VAM (SN-ENCAP
* context_information == context::vam_cluster): certificate if >= 500 ms,
* else digest.
* - other ITS-AIDs, including GN-MGMT beacons (141): clause 7.1.3 generic
* profile, which constrains only clause 5.2; this library includes the
* certificate once per second per ITS-AID and the digest otherwise.
*/
class Ts103097SignHeaderPolicy : public vanetza::security::v3::SignHeaderPolicy {
public:
Ts103097SignHeaderPolicy(const vanetza::Runtime&, vanetza::PositionProvider&, CertificatePool&,
const TrustConfiguration&);
~Ts103097SignHeaderPolicy() override;
void prepare_header(const vanetza::security::SignRequest&, vanetza::security::v3::SecuredMessage&) override;
void request_unrecognized_certificate(HashedId8) override;
void request_certificate() override;
void enqueue_p2p_request(vanetza::security::HashedId3) override;
void discard_p2p_request(vanetza::security::HashedId3) override;
/// TS 103 300-3 clause 6.5.3 item 2: a CAM was received from a not previously seen signer
void report_new_cam_signer();
/// after an identifier change the new ticket has never been announced: attach it next
void reset_after_identifier_change();
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
/** SN-LOG-SECURITY-EVENT.request (TS 102 723-8 V1.1.1 Table 22). Events are
* kept in a bounded log the application can drain for misbehaviour reporting. */
struct SecurityEvent {
enum class Type : std::uint8_t {
TIME_CONSISTENCY_FAILED, LOCATION_CONSISTENCY_FAILED, ID_CONSISTENCY_FAILED,
DISALLOWED_MESSAGE_CONTENT, DISALLOWED_MESSAGE_FREQUENCY, REPLAY_DETECTION_TIME,
REPLAY_DETECTION_LOCATION, MOVEMENT_PLAUSIBILITY, APPEARANCE_PLAUSIBILITY,
LOCATION_PLAUSIBILITY_SENSOR, LOCATION_PLAUSIBILITY_MAP, LOCATION_PLAUSIBILITY_CONTRADICTION,
APPLICATION_SPECIFIC
};
struct Location { std::int32_t latitude; std::int32_t longitude; };
struct Evidence { std::uint8_t type; ByteBuffer content; }; // event_evidence_type/content
Type event_type;
std::vector<HashedId8> neighbour_id_list;
std::uint32_t event_time; // INTEGER 0..2^32-1, shall be in the past
std::optional<Location> event_location;
std::vector<Evidence> event_evidence_list;
};
/// The steps of the signature in SN-ENCAP, reported to a SignObserver.
enum class SignStep : std::uint8_t {
header, ///< header fields and signer choice (Ts103097SignHeaderPolicy::prepare_header)
ticket, ///< the current ticket is valid for signing this ITS-AID (validity, permissions, region)
digest, ///< IEEE Std 1609.2 clause 5.3.1 hash of the to-be-signed data and the signer
signature, ///< ECDSA signature in the security module
};
/// Instrumentation of SN-ENCAP (power markers): begin() and end() bracket each SignStep in order.
class SignObserver {
public:
virtual ~SignObserver() = default;
virtual void begin(SignStep) = 0;
virtual void end(SignStep) = 0;
};
class IdentityManager;
/** The security entity: SN-ENCAP/SN-DECAP plus the identifier-change service.
* Runtime, position provider, backend, pool and trust configuration are
* owned by the application and must outlive the entity. SN-ENCAP signs with
* the pool's security module; the backend serves hashing, verification and
* point decompression. All calls come from the one task that also drives the
* stack. */
class SecurityEntity : public vanetza::security::SecurityEntity {
public:
SecurityEntity(vanetza::Runtime&, vanetza::PositionProvider&, vanetza::security::Backend&, CertificatePool&,
const TrustConfiguration&);
~SecurityEntity() override;
/** SN-ENCAP.request/.confirm (TS 102 723-8 V1.1.1 Tables 24/25; TS 103 836-4-1 V2.2.1
* Table 34). Refused (SignConfirmError::No_Certificate) when the pool is empty, the current
* ticket is not valid for the ITS-AID, or an identifier change is between PREPARE and COMMIT
* (clause 6.3.1.3: messages with old identifiers shall be avoided). */
vanetza::security::EncapConfirm encapsulate_packet(vanetza::security::EncapRequest&&) override;
/** SN-DECAP.request/.confirm (Tables 26/27). With V2X_SECURITY_VERIFY: check_profile(),
* then IEEE Std 1609.2 clause 5.2 verification (signer lookup in the learned-certificate
* cache or the inline certificate, authorization ticket validity, permissions for the
* ITS-AID, chain to a trust anchor with verified certificate signatures, region, message
* signature), generationTime plausibility and replay detection per VerificationPolicy;
* a CAM/DENM from an unknown station or with an unknown AA drives the P2P certificate
* distribution of TS 103 097 clause 7.1.1 through the header policy, and an AA carried
* in requestedCertificate is learned once its signature chains to a trust anchor.
* Without V2X_SECURITY_VERIFY: unsigned messages report UNSIGNED_MESSAGE, signed ones
* Configuration_Problem, never success; a receiver with
* itsGnSnDecapResultHandling = STRICT drops them either way. */
vanetza::security::DecapConfirm decapsulate_packet(vanetza::security::DecapRequest&&) override;
void set_verification_policy(const VerificationPolicy&);
/// report the signing steps of SN-ENCAP to the observer (nullptr: none); it must outlive the entity
void observe_signing(SignObserver*);
const VerificationPolicy& verification_policy() const;
/// authorities learned through P2P certificate distribution (requestedCertificate), verified
const std::deque<Certificate>& learned_authorities() const;
/// SN-LOG-SECURITY-EVENT.request (Table 22); .confirm has no parameters (Table 23)
void log_security_event(SecurityEvent);
/// take all logged events, oldest first
std::deque<SecurityEvent> drain_security_events();
void set_security_event_capacity(std::size_t);
/** Outcome counters. The GN router reports GN-DATA.confirm before SN-ENCAP runs
* (TS 103 836-4-1 clause 10.3.10.2 step 2 happens at transmission), so a refused
* encapsulation is visible here and in the absence of a packet, not in Stack::request. */
struct Statistics { unsigned signed_messages = 0, refused_no_ticket = 0, refused_change_pending = 0,
refused_permission = 0, failed = 0;
// SN-DECAP outcomes (V2X_SECURITY_VERIFY)
unsigned verified = 0, rejected_profile = 0, rejected_signer = 0, rejected_certificate = 0,
rejected_signature = 0, rejected_time = 0, replayed = 0, learned_authorities = 0; };
const Statistics& statistics() const;
IdChangeService& id_change();
const IdChangeService& id_change() const;
IdentityManager& identity_manager();
Ts103097SignHeaderPolicy& header_policy();
vanetza::security::v3::DefaultCertificateValidator& validator();
CertificatePool& certificates();
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
/** TS 102 723-8 V1.1.1 clause 6.3 implementation: subscriptions, the two-phase commit
* (clause 6.3.1.3, Figures 11 to 13), locks with automatic release (clause 6.3.2,
* Table 18) and deferred triggers (clause 6.3.3). New identifier = HashedId8 of the
* next authorization ticket in the pool (TS 102 940 V2.1.1 clause 6.5). */
class IdentityManager : public IdChangeService {
public:
IdentityManager(vanetza::Runtime&, CertificatePool&);
~IdentityManager() override; // DEREG to every subscriber (Figure 15)
SubscriptionHandle subscribe(IdChangeHook, ByteBuffer subscriber_data = {}) override;
Result unsubscribe(SubscriptionHandle) override;
Result trigger() override;
LockHandle lock(std::uint8_t duration_seconds) override;
Result unlock(LockHandle) override;
Identifier current_identifier() const override;
bool change_pending() const override;
/** Time allowed for all PREPARE (or COMMIT) responses before the change is aborted
* (or the COMMIT is closed). Not specified by TS 102 723-8; library default 500 ms. */
void set_response_timeout(vanetza::Clock::duration);
/// invoked after a successful COMMIT with the new identifier
void on_committed(std::function<void(const Identifier&)>);
struct Statistics { unsigned committed = 0, aborted = 0, timed_out = 0, commit_failures = 0; };
const Statistics& statistics() const;
bool locked() const;
private:
class Impl;
std::shared_ptr<Impl> impl_; // responders keep a weak reference across the manager's lifetime
};
} // namespace microbu_v2x::security
@@ -1,26 +0,0 @@
#pragma once
#include <microbu_v2x/security_module.hpp>
#include <vanetza/security/backend.hpp>
#include <memory>
// The station's cryptography behind two interfaces, chosen at build time (Kconfig "Security module"):
// SecurityModule (security_module.hpp) every private key and the signatures made with it
// vanetza::security::Backend hashing, verification and point decompression of public data
// The station never sees which implementation is behind either.
namespace microbu_v2x {
std::unique_ptr<vanetza::security::Backend> make_security_backend();
std::unique_ptr<security::SecurityModule> make_security_module();
const char* security_module_name();
// An external adapter component implements these factories. Each must return a working implementation or throw;
// a missing adapter never falls back to software. make_external_security_backend() is needed only when the
// adapter takes the public operations as well (V2X HSM).
std::unique_ptr<security::SecurityModule> make_external_security_module();
std::unique_ptr<vanetza::security::Backend> make_external_security_backend();
/// NVS location of the keys of the local software module (the station's credential checkpoint copies it).
constexpr const char* local_key_namespace = "v2x_keys";
constexpr const char* local_key_name = "keys";
} // namespace microbu_v2x
@@ -1,125 +0,0 @@
#pragma once
#include <vanetza/common/byte_buffer.hpp>
#include <vanetza/security/backend.hpp>
#include <vanetza/security/key_type.hpp>
#include <vanetza/security/private_key.hpp>
#include <vanetza/security/public_key.hpp>
#include <vanetza/security/signature.hpp>
#include <cstdint>
#include <map>
#include <optional>
/** The station's security module: the only place that holds private keys.
*
* Everything that the micrOBU hardware puts into its secure element (SE051 on the
* prototype mainboard) or a later V2X HSM is behind SecurityModule: generation
* and import of key pairs, keeping them across resets, and the ECDSA signature
* over a digest (IEEE Std 1609.2 clause 5.3.1). Callers hold a KeyId, never a
* private key value; the operations follow the key management and asymmetric
* signature functions of the PSA Certified Crypto API (psa_generate_key,
* psa_import_key, psa_export_public_key, psa_sign_hash, psa_destroy_key), which
* a secure element integrates as an opaque key location.
*
* Operations on public data stay with vanetza::security::Backend on the
* application processor: hashing, verification and point decompression.
* Ephemeral ECIES keys and the AES-CCM session key of a TS 102 941 request
* (pki.hpp) are short-lived and stay there too.
*/
namespace microbu_v2x::security {
using vanetza::ByteBuffer;
using vanetza::security::KeyType;
using vanetza::security::PrivateKey;
using vanetza::security::PublicKey;
using vanetza::security::Signature;
/// A key held by a SecurityModule. A stored KeyId stays valid across resets until the key is destroyed.
struct KeyId {
std::uint32_t value = 0; // 0 is no key
explicit operator bool() const { return value != 0; }
friend bool operator==(KeyId a, KeyId b) { return a.value == b.value; }
friend bool operator!=(KeyId a, KeyId b) { return a.value != b.value; }
friend bool operator<(KeyId a, KeyId b) { return a.value < b.value; }
};
/// A key pair outside a security module: an authority's key in the issuing tools, an ephemeral ECIES key, or a
/// laboratory ticket key on its way into the module. Public key uncompressed.
struct KeyPair {
PrivateKey priv;
PublicKey pub;
};
class SecurityModule {
public:
virtual ~SecurityModule() = default;
/// New key pair on the curve, kept in the module; throws std::runtime_error when the module cannot create it.
virtual KeyId generate_key(KeyType) = 0;
/// Laboratory provisioning of a key pair created outside the station (VCR1 bundle, issuing tools). None when
/// the two halves do not belong together; throws std::runtime_error when the module cannot store the key.
virtual std::optional<KeyId> import_key(const KeyPair&) = 0;
/// The public half (uncompressed), none for a KeyId the module does not hold.
virtual std::optional<PublicKey> public_key(KeyId) const = 0;
/// ECDSA with the curve of the key over a digest of the curve's length; throws std::runtime_error for a KeyId
/// the module does not hold or a failed operation.
virtual Signature sign_digest(KeyId, const ByteBuffer& digest) = 0;
/// Removes the key for good; false when the module holds no such key.
virtual bool destroy_key(KeyId) = 0;
};
/// True when both keys are the same point on the same curve, in compressed or uncompressed form.
bool same_public_key(const PublicKey&, const PublicKey&);
/// Creates key pairs for SoftwareSecurityModule (the platform's random generator).
class KeyGenerator {
public:
virtual ~KeyGenerator() = default;
virtual KeyPair generate_key(KeyType) = 0;
};
/// Where SoftwareSecurityModule keeps its keys between resets: one blob, written as a whole.
class KeyStorage {
public:
virtual ~KeyStorage() = default;
/// false when nothing is stored
virtual bool load(ByteBuffer&) = 0;
virtual bool save(const ByteBuffer&) = 0;
};
class MemoryKeyStorage final : public KeyStorage {
public:
bool load(ByteBuffer& out) override;
bool save(const ByteBuffer& blob) override;
private:
ByteBuffer blob_;
};
/** SecurityModule in software on the application processor: the stand-in for the SE051 until its adapter
* exists. Signs through a Backend and keeps the keys in a KeyStorage, whose protection at rest is the
* platform's (NVS encryption on the ESP32-C5). Storage format: "MSM1", next KeyId (4 octets), then per key
* [KeyId: 4][curve: 1][private scalar][public x][public y], all big-endian. */
class SoftwareSecurityModule final : public SecurityModule {
public:
/// Loads the stored keys; throws std::runtime_error when the stored blob does not decode.
SoftwareSecurityModule(vanetza::security::Backend&, KeyGenerator&, KeyStorage&);
~SoftwareSecurityModule() override;
SoftwareSecurityModule(const SoftwareSecurityModule&) = delete;
SoftwareSecurityModule& operator=(const SoftwareSecurityModule&) = delete;
KeyId generate_key(KeyType) override;
std::optional<KeyId> import_key(const KeyPair&) override;
std::optional<PublicKey> public_key(KeyId) const override;
Signature sign_digest(KeyId, const ByteBuffer& digest) override;
bool destroy_key(KeyId) override;
private:
KeyId keep(KeyPair);
void persist();
vanetza::security::Backend& backend_;
KeyGenerator& generator_;
KeyStorage& storage_;
std::map<KeyId, KeyPair> keys_;
std::uint32_t next_ = 1;
};
} // namespace microbu_v2x::security
@@ -1,20 +0,0 @@
#pragma once
#include <microbu_v2x/pki.hpp>
#include <microbu_v2x/credentials.hpp>
namespace microbu_v2x::pki {
// TS 102 941 clauses 6.3.1 to 6.3.6. One complete authenticated transaction.
struct TrustSnapshot {
ByteBuffer tlm, rca, ectl, ctl, crl;
Time32 deadline = 0;
};
ByteBuffer encode_snapshot(const TrustSnapshot&);
bool decode_snapshot(const ByteBuffer&, TrustSnapshot&);
// Initial bootstrap requires the independently pinned TLM. Later TLM changes
// require a successor authenticated by the previously accepted ECTL.
bool validate_update(vanetza::security::Backend&, vanetza::Clock::time_point,
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
const TrustSnapshot& proposed, TrustSnapshot& accepted);
bool snapshot_credentials(vanetza::security::Backend&, const TrustSnapshot&,
microbu_v2x::security::StoredCredentials&, microbu_v2x::security::TrustConfiguration* = nullptr);
}
@@ -1,97 +0,0 @@
#include <microbu_v2x/access.hpp>
#include <cmath>
#include <utility>
#if V2X_NETWORK
#include <vanetza/access/data_rates.hpp>
#include <vanetza/dcc/limeric.hpp>
#include <vanetza/dcc/limeric_budget.hpp>
#include <vanetza/dcc/profile.hpp>
#include <vanetza/dcc/transmission.hpp>
#include <array>
#include <chrono>
#endif
namespace microbu_v2x {
Result validate(const AlDataRequest& request, std::size_t maximum) {
if (request.data.empty() || request.data.size() > maximum || request.priority > 7 ||
!std::isfinite(request.transmit_power_dbm) || request.bandwidth_mhz == 0)
return Result::invalid_argument;
return Result::accepted;
}
#if V2X_NETWORK
namespace {
// EN 303 797 V2.1.1 clause 4.6.2's Ton limit; a single
// frame at or below this duration also cannot alone exceed the 3 % duty cycle at Toff>=25 ms.
constexpr vanetza::Clock::duration max_ton = std::chrono::milliseconds(4);
// Index by OfdmMcs; mirrors the rate table in C5Radio::request/transmit_burst.
constexpr std::array<const vanetza::access::DataRateG5*, 8> g5_rates {
&vanetza::access::G5_3Mbps, &vanetza::access::G5_4dot5Mbps, &vanetza::access::G5_6Mbps,
&vanetza::access::G5_9Mbps, &vanetza::access::G5_12Mbps, &vanetza::access::G5_18bps,
&vanetza::access::G5_24Mbps, &vanetza::access::G5_27Mbps,
};
// Airtime-only use of Transmission::channel_occupancy(); profile is immaterial here since no
// FlowControl queueing is involved, only the data-rate/length formula.
vanetza::Clock::duration request_airtime(const AlDataRequest& request) {
vanetza::dcc::TransmissionLite transmission(vanetza::dcc::Profile::DP2, request.data.size());
const auto index = static_cast<unsigned>(request.mcs);
transmission.m_data_rate = index < g5_rates.size() ? g5_rates[index] : nullptr;
return transmission.channel_occupancy();
}
// TS 102 687 V1.2.1 Table 3 defaults, with cbr_target overridden to the project's Release-2
// value.
vanetza::dcc::Limeric::Parameters limeric_parameters(vanetza::dcc::ChannelLoad cbr_target) {
vanetza::dcc::Limeric::Parameters parameters;
parameters.cbr_target = cbr_target;
return parameters;
}
} // namespace
class AccessStack::Dcc {
public:
Dcc(vanetza::Runtime& rt, vanetza::dcc::ChannelLoad target) :
limeric(rt, limeric_parameters(target)),
budget(limeric, rt)
{
// TS 102 687 V1.2.1 Annex B: the gate-opening time depends on the current permitted
// duty cycle, so it must be recalculated whenever the Adaptive approach updates delta.
limeric.on_duty_cycle_change = [this](const vanetza::dcc::Limeric*, vanetza::Clock::time_point) {
budget.update();
};
}
vanetza::dcc::Limeric limeric;
vanetza::dcc::LimericBudget budget;
};
void AccessStack::enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target) {
dcc_ = std::make_unique<Dcc>(runtime, cbr_target);
}
void AccessStack::report_channel_load(vanetza::dcc::ChannelLoad load) {
if (dcc_) dcc_->limeric.update_cbr(load);
}
vanetza::UnitInterval AccessStack::permitted_duty_cycle() const {
return dcc_ ? dcc_->limeric.permitted_duty_cycle() : vanetza::UnitInterval(1.0);
}
#endif
AccessStack::AccessStack(Access& access, std::size_t maximum) :
access_(access), maximum_gnpdu_(maximum) {}
AccessStack::~AccessStack() = default;
Result AccessStack::request(AlDataRequest request) {
auto result = validate(request, maximum_gnpdu_);
if (result != Result::accepted) return result;
#if V2X_NETWORK
if (dcc_) {
const auto ton = request_airtime(request);
if (ton <= vanetza::Clock::duration::zero() || ton > max_ton) return Result::invalid_argument;
if (dcc_->budget.delay() > vanetza::Clock::duration::zero()) return Result::resource_limit;
result = access_.request(std::move(request));
if (result == Result::accepted) dcc_->budget.notify(ton);
return result;
}
#endif
return access_.request(std::move(request));
}
}
@@ -1,174 +0,0 @@
#include <microbu_v2x/credentials.hpp>
#include <vanetza/security/v3/certificate.hpp>
#include <cstdio>
#include <fstream>
#include <iterator>
namespace microbu_v2x::security {
using vanetza::security::KeyType;
namespace {
constexpr std::uint8_t bundle_magic[4] = {'V', 'C', 'R', '1'};
constexpr std::uint8_t stored_magic[4] = {'V', 'C', 'S', '1'};
enum Record : std::uint8_t { root = 1, authority = 2, ticket = 3, ticket_key = 4, ticket_key_id = 5 };
std::uint8_t curve_code(KeyType type) {
switch (type) {
case KeyType::NistP256: return 1;
case KeyType::BrainpoolP256r1: return 2;
case KeyType::BrainpoolP384r1: return 3;
default: return 0;
}
}
KeyType curve_type(std::uint8_t code) {
switch (code) {
case 1: return KeyType::NistP256;
case 2: return KeyType::BrainpoolP256r1;
case 3: return KeyType::BrainpoolP384r1;
default: return KeyType::Unspecified;
}
}
void put(ByteBuffer& out, std::uint8_t type, const ByteBuffer& payload) {
out.push_back(type);
out.push_back(static_cast<std::uint8_t>(payload.size() >> 8));
out.push_back(static_cast<std::uint8_t>(payload.size()));
out.insert(out.end(), payload.begin(), payload.end());
}
ByteBuffer key_record(const PrivateKey& key) {
ByteBuffer out {curve_code(key.type)};
out.insert(out.end(), key.key.begin(), key.key.end());
return out;
}
ByteBuffer key_record(KeyId key) {
return {static_cast<std::uint8_t>(key.value >> 24), static_cast<std::uint8_t>(key.value >> 16),
static_cast<std::uint8_t>(key.value >> 8), static_cast<std::uint8_t>(key.value)};
}
bool read_key(const ByteBuffer& payload, PrivateKey& key) {
const KeyType curve = curve_type(payload[0]);
if (curve == KeyType::Unspecified || payload.size() - 1 != vanetza::security::key_length(curve)) return false;
key.type = curve;
key.key.assign(payload.begin() + 1, payload.end());
return true;
}
bool read_key(const ByteBuffer& payload, KeyId& key) {
if (payload.size() != 4) return false;
key.value = std::uint32_t(payload[0]) << 24 | std::uint32_t(payload[1]) << 16 | std::uint32_t(payload[2]) << 8 | payload[3];
return bool(key);
}
/// Both formats: magic, then roots, authorities and tickets, each ticket certificate followed by its key record.
template <class Set>
ByteBuffer encode_set(const Set& set, const std::uint8_t (&magic)[4], std::uint8_t key_type) {
ByteBuffer out(std::begin(magic), std::end(magic));
for (const auto& coer : set.roots) put(out, Record::root, coer);
for (const auto& coer : set.authorities) put(out, Record::authority, coer);
for (const auto& t : set.tickets) {
put(out, Record::ticket, t.certificate);
put(out, key_type, key_record(t.key));
}
return out;
}
template <class Set>
bool decode_set(const ByteBuffer& bundle, const std::uint8_t (&magic)[4], std::uint8_t key_type, Set& out) {
if (bundle.size() < sizeof(magic) || !std::equal(std::begin(magic), std::end(magic), bundle.begin())) return false;
Set parsed;
bool key_pending = false; // a ticket certificate awaits its key record
std::size_t at = sizeof(magic);
while (at < bundle.size()) {
if (bundle.size() - at < 3) return false;
const std::uint8_t type = bundle[at];
const std::size_t length = (static_cast<std::size_t>(bundle[at + 1]) << 8) | bundle[at + 2];
at += 3;
if (bundle.size() - at < length || length == 0) return false;
ByteBuffer payload(bundle.begin() + at, bundle.begin() + at + length);
at += length;
if (key_pending != (type == key_type)) return false;
if (type == Record::root) {
parsed.roots.push_back(std::move(payload));
} else if (type == Record::authority) {
parsed.authorities.push_back(std::move(payload));
} else if (type == Record::ticket) {
parsed.tickets.push_back({std::move(payload), {}});
key_pending = true;
} else if (type == key_type) {
if (!read_key(payload, parsed.tickets.back().key)) return false;
key_pending = false;
} else {
return false;
}
}
if (key_pending) return false;
out = std::move(parsed);
return true;
}
} // namespace
ByteBuffer encode(const Credentials& credentials) { return encode_set(credentials, bundle_magic, Record::ticket_key); }
ByteBuffer encode(const StoredCredentials& credentials) {
return encode_set(credentials, stored_magic, Record::ticket_key_id);
}
bool decode(const ByteBuffer& bundle, Credentials& out) {
return decode_set(bundle, bundle_magic, Record::ticket_key, out);
}
bool decode(const ByteBuffer& bundle, StoredCredentials& out) {
return decode_set(bundle, stored_magic, Record::ticket_key_id, out);
}
std::optional<StoredCredentials> import_keys(const Credentials& credentials, SecurityModule& module) {
StoredCredentials stored {credentials.roots, credentials.authorities, {}};
const auto undo = [&]() -> std::optional<StoredCredentials> {
for (const auto& t : stored.tickets) module.destroy_key(t.key);
return std::nullopt;
};
for (const auto& t : credentials.tickets) {
vanetza::security::v3::Certificate certificate;
if (!certificate.decode(t.certificate)) return undo();
const auto verification_key = vanetza::security::v3::get_public_key(*certificate.content());
if (!verification_key) return undo();
const auto key = module.import_key(KeyPair {t.key, *verification_key});
if (!key) return undo();
stored.tickets.push_back({t.certificate, *key});
}
return stored;
}
ApplyReport apply(const StoredCredentials& credentials, TrustConfiguration& trust, CertificatePool& pool) {
ApplyReport report;
for (const auto& coer : credentials.roots) {
if ((report.result = trust.add_root(coer)) != Result::accepted) return report;
++report.roots;
}
for (const auto& coer : credentials.authorities) {
if ((report.result = trust.add_authority(coer)) != Result::accepted) return report;
++report.authorities;
}
for (const auto& t : credentials.tickets) {
if ((report.result = pool.add(t.certificate, t.key)) != Result::accepted) return report;
++report.tickets;
}
return report;
}
Result FileCredentialStore::save(const StoredCredentials& credentials) {
const ByteBuffer bundle = encode(credentials);
std::ofstream out(path_, std::ios::binary | std::ios::trunc);
out.write(reinterpret_cast<const char*>(bundle.data()), bundle.size());
return out ? Result::accepted : Result::rejected;
}
Result FileCredentialStore::load(StoredCredentials& credentials) {
std::ifstream in(path_, std::ios::binary);
if (!in) return Result::rejected;
const ByteBuffer bundle(std::istreambuf_iterator<char>(in), {});
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
}
Result FileCredentialStore::erase() {
return std::remove(path_.c_str()) == 0 ? Result::accepted : Result::rejected;
}
} // namespace microbu_v2x::security
@@ -1,56 +0,0 @@
#include "local_security.hpp"
#include <microbu_v2x/backend_mbedtls.hpp>
#include <microbu_v2x/security_backend.hpp>
#include <nvs.h>
namespace microbu_v2x {
namespace {
/// One NVS blob for the keys of the local software module.
class NvsKeyStorage final : public security::KeyStorage {
public:
bool load(vanetza::ByteBuffer& out) override {
nvs_handle_t handle;
if (nvs_open(local_key_namespace, NVS_READONLY, &handle) != ESP_OK) return false;
std::size_t size = 0;
bool ok = nvs_get_blob(handle, local_key_name, nullptr, &size) == ESP_OK && size > 0;
if (ok) {
out.resize(size);
ok = nvs_get_blob(handle, local_key_name, out.data(), &size) == ESP_OK;
}
nvs_close(handle);
return ok;
}
bool save(const vanetza::ByteBuffer& blob) override {
nvs_handle_t handle;
if (nvs_open(local_key_namespace, NVS_READWRITE, &handle) != ESP_OK) return false;
const bool ok = nvs_set_blob(handle, local_key_name, blob.data(), blob.size()) == ESP_OK &&
nvs_commit(handle) == ESP_OK;
nvs_close(handle);
return ok;
}
};
/// The SE051's role in software on the ESP32-C5: keys in NVS, signatures through PSA.
class LocalSecurityModule final : public security::SecurityModule {
public:
security::KeyId generate_key(security::KeyType type) override { return module_.generate_key(type); }
std::optional<security::KeyId> import_key(const security::KeyPair& pair) override { return module_.import_key(pair); }
std::optional<security::PublicKey> public_key(security::KeyId id) const override { return module_.public_key(id); }
security::Signature sign_digest(security::KeyId id, const vanetza::ByteBuffer& digest) override {
return module_.sign_digest(id, digest);
}
bool destroy_key(security::KeyId id) override { return module_.destroy_key(id); }
private:
BackendMbedTls psa_;
NvsKeyStorage storage_;
security::SoftwareSecurityModule module_ {psa_, psa_, storage_};
};
} // namespace
std::unique_ptr<vanetza::security::Backend> make_local_security_backend() { return std::make_unique<BackendMbedTls>(); }
std::unique_ptr<security::SecurityModule> make_local_security_module() { return std::make_unique<LocalSecurityModule>(); }
} // namespace microbu_v2x
@@ -1,11 +0,0 @@
#pragma once
#include <microbu_v2x/security_module.hpp>
#include <vanetza/security/backend.hpp>
#include <memory>
// The implementations on the ESP32 itself (local_security.cpp): PSA crypto for the public operations, and the
// software security module with its keys in NVS.
namespace microbu_v2x {
std::unique_ptr<vanetza::security::Backend> make_local_security_backend();
std::unique_ptr<security::SecurityModule> make_local_security_module();
} // namespace microbu_v2x
@@ -1,996 +0,0 @@
// TS 102 941 V2.2.1 enrolment/authorization messages on the upstream
// EtsiTs103097Data wrapper. See pki.hpp for the clause map.
#include <microbu_v2x/pki.hpp>
#include <microbu_v2x/ecc.hpp>
#include <microbu_v2x/security.hpp>
#include <vanetza/asn1/asn1c_wrapper.hpp>
#include <vanetza/asn1/security/EtsiTs102941Data.h>
#include <vanetza/asn1/security/CtlCommand.h>
#include <vanetza/asn1/security/CtlEntry.h>
#include <vanetza/asn1/security/EtsiTs103097Certificate.h>
#include <vanetza/asn1/security/InnerAtRequest.h>
#include <vanetza/asn1/security/InnerEcRequest.h>
#include <vanetza/asn1/security/PublicEncryptionKey.h>
#include <vanetza/asn1/security/PublicVerificationKey.h>
#include <vanetza/asn1/security/SharedAtRequest.h>
#include <vanetza/asn1/security/ValidityPeriod.h>
#include <vanetza/security/sha.hpp>
#include <vanetza/security/v2/basic_elements.hpp>
#include <vanetza/security/v3/asn1_conversions.hpp>
#include <vanetza/security/v3/hash.hpp>
#include <vanetza/security/v3/secured_message.hpp>
#include <algorithm>
#include <cstring>
#include <map>
namespace microbu_v2x::pki {
using namespace vanetza;
using namespace vanetza::security;
using SecuredData = v3::SecuredMessage; // EtsiTs103097Data wrapper
namespace {
constexpr std::size_t aes_key_length = 16;
constexpr std::size_t nonce_length = 12;
constexpr std::size_t tag_length = 16;
ByteBuffer octets(const OCTET_STRING_t& s) { return ByteBuffer(s.buf, s.buf + s.size); }
// EccP256CurvePoint -> PublicKey (x-only points carry no usable y and are refused)
std::optional<PublicKey> point_to_key(const Vanetza_Security_EccP256CurvePoint& point, KeyType type) {
PublicKey key;
key.type = type;
switch (point.present) {
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
key.compression = KeyCompression::Y0; key.x = octets(point.choice.compressed_y_0); break;
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
key.compression = KeyCompression::Y1; key.x = octets(point.choice.compressed_y_1); break;
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
key.compression = KeyCompression::NoCompression;
key.x = octets(point.choice.uncompressedP256.x); key.y = octets(point.choice.uncompressedP256.y); break;
default: return std::nullopt;
}
if (key.x.size() != 32) return std::nullopt;
return key;
}
// uncompressed form for backends that need y (ECDH peer key)
std::optional<PublicKey> uncompressed(const PublicKey& key) {
if (key.compression == KeyCompression::NoCompression) return key;
auto point = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
if (!point) return std::nullopt;
PublicKey out = key;
out.compression = KeyCompression::NoCompression;
out.y = point->y;
return out;
}
PublicKey compressed(const PublicKey& key) {
if (key.compression != KeyCompression::NoCompression || key.y.empty()) return key;
PublicKey out = key;
out.compression = (key.y.back() & 1) ? KeyCompression::Y1 : KeyCompression::Y0;
out.y.clear();
return out;
}
void fill_point(Vanetza_Security_EccP256CurvePoint& point, const PublicKey& key) {
point = v3::to_asn1(make_ecc_point(compressed(key)));
}
void fill_verification_key(Vanetza_Security_PublicVerificationKey& out, const PublicKey& key) {
if (key.type == KeyType::BrainpoolP256r1) {
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1;
fill_point(out.choice.ecdsaBrainpoolP256r1, key);
} else {
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256;
fill_point(out.choice.ecdsaNistP256, key);
}
}
void fill_encryption_key(Vanetza_Security_PublicEncryptionKey& out, const PublicKey& key) {
out.supportedSymmAlg = Vanetza_Security_SymmAlgorithm_aes128Ccm;
if (key.type == KeyType::BrainpoolP256r1) {
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesBrainpoolP256r1;
fill_point(out.publicKey.choice.eciesBrainpoolP256r1, key);
} else {
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256;
fill_point(out.publicKey.choice.eciesNistP256, key);
}
}
void fill_permissions(Vanetza_Security_CertificateSubjectAttributes& attributes, const Permissions& permissions) {
if (permissions.empty()) return;
attributes.appPermissions = v3::asn1::allocate<Vanetza_Security_SequenceOfPsidSsp>();
for (const auto& permission : permissions) {
auto* entry = v3::asn1::allocate<Vanetza_Security_PsidSsp>();
entry->psid = permission.first;
if (!permission.second.empty()) {
entry->ssp = v3::asn1::allocate<Vanetza_Security_ServiceSpecificPermissions>();
entry->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
v3::assign(&entry->ssp->choice.bitmapSsp, permission.second);
}
ASN_SEQUENCE_ADD(attributes.appPermissions, entry);
}
}
// IEEE 1609.2 clause 5.3.1: Hash(Hash(tbsData) || Hash(signer certificate or empty string))
ByteBuffer message_digest(Backend& backend, HashAlgorithm hash, const ByteBuffer& tbs, const Certificate* signer) {
if (signer) return v3::calculate_message_hash(backend, hash, tbs, *signer);
ByteBuffer concat = backend.calculate_hash(hash, tbs);
const ByteBuffer empty = backend.calculate_hash(hash, ByteBuffer {});
concat.insert(concat.end(), empty.begin(), empty.end());
return backend.calculate_hash(hash, concat);
}
// Fill the common header of a signed structure (TS 102 941: psid 623, generationTime only).
void prepare_signed(SecuredData& data, HashAlgorithm hash, Clock::time_point now, const Certificate* signer) {
data.set_hash_id(hash);
data.set_its_aid(aid::SCR);
data.set_generation_time(v2::convert_time64(now));
if (signer) {
const auto digest = signer->calculate_digest();
if (digest) data.set_signer_identifier(*digest); else data.set_signer_identifier_self();
} else {
data.set_signer_identifier_self();
}
}
std::optional<ByteBuffer> finish_signed(Backend& backend, SecuredData& data, HashAlgorithm hash, const Signer& sign,
const Certificate* signer) {
try {
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
data.set_signature(sign(digest));
return data.encode();
} catch (const std::exception&) {
return std::nullopt;
}
}
ByteBuffer psk_id_input(const std::array<std::uint8_t, aes_key_length>& key) {
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_SymmetricEncryptionKey> wrapper(asn_DEF_Vanetza_Security_SymmetricEncryptionKey);
wrapper->present = Vanetza_Security_SymmetricEncryptionKey_PR_aes128Ccm;
OCTET_STRING_fromBuf(&wrapper->choice.aes128Ccm, reinterpret_cast<const char*>(key.data()), key.size());
return wrapper.encode();
}
std::array<std::uint8_t, 16> left16(const ByteBuffer& in) {
std::array<std::uint8_t, 16> out {};
std::copy_n(in.begin(), std::min<std::size_t>(16, in.size()), out.begin());
return out;
}
// InnerEcResponse / InnerAtResponse share the layout: requestHash, responseCode, certificate OPTIONAL
template<class Inner>
Result read_inner_response(const Inner& inner, const RequestContext& context, std::uint8_t& code,
std::optional<Certificate>& certificate) {
certificate.reset();
if (inner.requestHash.size != 16 || std::memcmp(inner.requestHash.buf, context.request_hash.data(), 16) != 0)
return Result::rejected; // the response answers another request
code = static_cast<std::uint8_t>(inner.responseCode);
if (inner.certificate) {
// asn1c forward-declares a distinct struct tag for this member; the object it points to is
// decoded with asn_DEF_Vanetza_Security_EtsiTs103097Certificate, i.e. an EtsiTs103097Certificate_t.
Certificate cert(*reinterpret_cast<const Vanetza_Security_EtsiTs103097Certificate_t*>(inner.certificate));
if (!cert.validate()) return Result::rejected;
certificate = std::move(cert);
} else if (code == 0) {
return Result::rejected; // clause 6.2.3.2.2: a positive response returns a certificate
}
return Result::accepted;
}
// Decrypt, verify the authority signature and hand back the EtsiTs102941Data
std::optional<ByteBuffer> open_response(Backend& backend, EciesBackend& ecies, const RequestContext& context,
const Certificate& authority, const ByteBuffer& encoded) {
auto signed_bytes = decrypt_with_psk(ecies, context.aes_key, encoded);
if (!signed_bytes) return std::nullopt;
return verify_signed(backend, *signed_bytes, nullptr, &authority, aid::SCR);
}
} // namespace
ByteBuffer kdf2_sha256(Backend& backend, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length) {
ByteBuffer derived;
for (std::uint32_t counter = 1; derived.size() < length; ++counter) {
ByteBuffer input = shared_secret;
input.push_back(static_cast<std::uint8_t>(counter >> 24));
input.push_back(static_cast<std::uint8_t>(counter >> 16));
input.push_back(static_cast<std::uint8_t>(counter >> 8));
input.push_back(static_cast<std::uint8_t>(counter));
input.insert(input.end(), kdp.begin(), kdp.end());
const auto block = backend.calculate_hash(HashAlgorithm::SHA256, input);
derived.insert(derived.end(), block.begin(), block.end());
}
derived.resize(length);
return derived;
}
std::optional<EncryptedKey> ecies_encrypt_key(Backend& backend, EciesBackend& ecies, const PublicKey& recipient,
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key) {
const auto peer = uncompressed(recipient);
if (!peer || (peer->type != KeyType::NistP256 && peer->type != KeyType::BrainpoolP256r1)) return std::nullopt;
try {
const KeyPair ephemeral = ecies.generate_key(peer->type);
const auto secret = ecies.ecdh_x(ephemeral.priv, *peer);
if (!secret) return std::nullopt;
// K1 (16 octets, key encryption) || K2 (32 octets, MAC key)
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
EncryptedKey out;
out.v = ephemeral.pub;
ByteBuffer c(aes_key_length);
for (std::size_t i = 0; i < aes_key_length; ++i) c[i] = k[i] ^ aes_key[i];
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
if (tag.size() < tag_length) return std::nullopt;
out.c = left16(c);
out.t = left16(tag);
return out;
} catch (const std::exception&) {
return std::nullopt;
}
}
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(Backend& backend, EciesBackend& ecies,
const PrivateKey& recipient, const ByteBuffer& p1,
const EncryptedKey& encrypted) {
const auto peer = uncompressed(encrypted.v);
if (!peer) return std::nullopt;
try {
const auto secret = ecies.ecdh_x(recipient, *peer);
if (!secret) return std::nullopt;
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
const ByteBuffer c(encrypted.c.begin(), encrypted.c.end());
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
if (tag.size() < tag_length) return std::nullopt;
// constant-time comparison of the truncated tag
unsigned diff = 0;
for (std::size_t i = 0; i < tag_length; ++i) diff |= tag[i] ^ encrypted.t[i];
if (diff != 0) return std::nullopt;
std::array<std::uint8_t, 16> key {};
for (std::size_t i = 0; i < aes_key_length; ++i) key[i] = k[i] ^ encrypted.c[i];
return key;
} catch (const std::exception&) {
return std::nullopt;
}
}
// ---- building blocks -------------------------------------------------------
Signer module_signer(security::SecurityModule& module, security::KeyId key) {
return [&module, key](const ByteBuffer& digest) { return module.sign_digest(key, digest); };
}
Signer key_signer(Backend& backend, PrivateKey key) {
return [&backend, key = std::move(key)](const ByteBuffer& digest) { return backend.sign_digest(key, digest); };
}
SigningKey signing_key(Backend& backend, const KeyPair& pair) { return {pair.pub, key_signer(backend, pair.priv)}; }
std::optional<ByteBuffer> sign_data(Backend& backend, Clock::time_point now, HashAlgorithm hash, const ByteBuffer& payload,
const Signer& sign, const Certificate* signer) {
SecuredData data = SecuredData::with_signed_data();
prepare_signed(data, hash, now, signer);
data.set_payload(payload);
return finish_signed(backend, data, hash, sign, signer);
}
std::optional<ByteBuffer> sign_external(Backend& backend, Clock::time_point now, const ByteBuffer& external_payload,
const Signer& sign, const Certificate& signer) {
SecuredData data = SecuredData::with_signed_data_hash();
prepare_signed(data, HashAlgorithm::SHA256, now, &signer);
data.set_external_payload_hash(calculate_sha256_digest(external_payload.data(), external_payload.size()));
return finish_signed(backend, data, HashAlgorithm::SHA256, sign, &signer);
}
std::optional<ByteBuffer> encrypt_for(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key) {
const auto encryption_key = v3::get_public_encryption_key(*recipient.content());
const auto recipient_id = recipient.calculate_digest();
if (!encryption_key || !recipient_id) return std::nullopt;
try {
const ByteBuffer random = ecies.random(aes_key_length + nonce_length);
std::array<std::uint8_t, nonce_length> nonce {};
std::copy_n(random.begin(), aes_key_length, aes_key.begin());
std::copy_n(random.begin() + aes_key_length, nonce_length, nonce.begin());
ByteBuffer ciphertext;
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
// P1 = SHA-256 of the recipient certificate (IEEE 1609.2 clause 5.3.5, certRecipInfo)
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
const auto wrapped = ecies_encrypt_key(backend, ecies, *encryption_key, p1, aes_key);
if (!wrapped) return std::nullopt;
SecuredData data = SecuredData::with_encrypted_data();
data.set_aes_ccm_ciphertext(ciphertext, nonce);
data.set_cert_recip_info(*recipient_id, wrapped->c, wrapped->t, compressed(wrapped->v));
return data.encode();
} catch (const std::exception&) {
return std::nullopt;
}
}
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
const ByteBuffer& plaintext) {
try {
const ByteBuffer random = ecies.random(nonce_length);
std::array<std::uint8_t, nonce_length> nonce {};
std::copy_n(random.begin(), nonce_length, nonce.begin());
ByteBuffer ciphertext;
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
SecuredData data = SecuredData::with_encrypted_data();
data.set_aes_ccm_ciphertext(ciphertext, nonce);
// pskRecipInfo = HashedId8 of the COER SymmetricEncryptionKey (IEEE 1609.2 clause 6.3.43)
const ByteBuffer key_encoding = psk_id_input(aes_key);
const HashedId8 psk_id = create_hashed_id8(calculate_sha256_digest(key_encoding.data(), key_encoding.size()));
auto* recipient = v3::asn1::allocate<Vanetza_Security_RecipientInfo>();
recipient->present = Vanetza_Security_RecipientInfo_PR_pskRecipInfo;
OCTET_STRING_fromBuf(&recipient->choice.pskRecipInfo, reinterpret_cast<const char*>(psk_id.data()), psk_id.size());
ASN_SEQUENCE_ADD(&data->content->choice.encryptedData.recipients.list, recipient);
return data.encode();
} catch (const std::exception&) {
return std::nullopt;
}
}
std::optional<ByteBuffer> decrypt_as_recipient(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
const PrivateKey& encryption_key, const ByteBuffer& encoded,
std::array<std::uint8_t, 16>* aes_key_out) {
SecuredData data;
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
const auto own_id = recipient.calculate_digest();
if (!own_id) return std::nullopt;
const auto& recipients = data->content->choice.encryptedData.recipients.list;
for (int i = 0; i < recipients.count; ++i) {
const auto* info = recipients.array[i];
if (!info || info->present != Vanetza_Security_RecipientInfo_PR_certRecipInfo) continue;
const auto& cert_info = info->choice.certRecipInfo;
if (cert_info.recipientId.size != 8 || std::memcmp(cert_info.recipientId.buf, own_id->data(), 8) != 0) continue;
const Vanetza_Security_EciesP256EncryptedKey* ecies_key = nullptr;
KeyType type = KeyType::NistP256;
if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesNistP256) {
ecies_key = &cert_info.encKey.choice.eciesNistP256;
} else if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesBrainpoolP256r1) {
ecies_key = &cert_info.encKey.choice.eciesBrainpoolP256r1;
type = KeyType::BrainpoolP256r1;
} else {
continue;
}
if (ecies_key->c.size != 16 || ecies_key->t.size != 16) continue;
EncryptedKey wrapped;
auto v = point_to_key(ecies_key->v, type);
if (!v) continue;
wrapped.v = *v;
std::copy_n(ecies_key->c.buf, 16, wrapped.c.begin());
std::copy_n(ecies_key->t.buf, 16, wrapped.t.begin());
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
const auto aes_key = ecies_decrypt_key(backend, ecies, encryption_key, p1, wrapped);
if (!aes_key) return std::nullopt;
ByteBuffer ciphertext;
std::array<std::uint8_t, nonce_length> nonce {};
data.get_aes_ccm_ciphertext(ciphertext, nonce);
ByteBuffer plaintext;
if (!ecies.aes_ccm_decrypt(*aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
if (aes_key_out) *aes_key_out = *aes_key;
return plaintext;
}
return std::nullopt;
}
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
const ByteBuffer& encoded) {
SecuredData data;
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
if (!data.check_psk_match(aes_key)) return std::nullopt; // response is not for this request
ByteBuffer ciphertext;
std::array<std::uint8_t, nonce_length> nonce {};
data.get_aes_ccm_ciphertext(ciphertext, nonce);
ByteBuffer plaintext;
if (!ecies.aes_ccm_decrypt(aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
return plaintext;
}
std::optional<ByteBuffer> verify_signed(Backend& backend, const ByteBuffer& encoded, const PublicKey* self_key,
const Certificate* signer, ItsAid expected_psid) {
SecuredData data;
if (!data.decode(encoded) || data.encode() != encoded || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
if (data.its_aid() != expected_psid || !data.generation_time()) return std::nullopt;
const auto hash = data.hash_id();
const auto signature = data.signature();
if (hash == HashAlgorithm::Unspecified || !signature) return std::nullopt;
const auto* signed_data = data->content->choice.signedData;
// TS 102 941 V2.2.1 clause 6.2: management messages use only PSID and generationTime.
const auto& header = signed_data->tbsData->headerInfo;
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions)
return std::nullopt;
PublicKey key;
if (signer) {
const auto digest = signer->calculate_digest();
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_digest || !digest ||
signed_data->signer.choice.digest.size != 8 ||
std::memcmp(signed_data->signer.choice.digest.buf, digest->data(), 8) != 0) return std::nullopt;
const auto signer_key = v3::get_public_key(*signer->content());
if (!signer_key) return std::nullopt;
key = *signer_key;
} else {
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_self || !self_key) return std::nullopt;
key = *self_key;
}
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
if (!backend.verify_digest(key, digest, *signature)) return std::nullopt;
auto payload = data.payload();
const auto& packet = boost::get<CohesivePacket>(payload);
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
return ByteBuffer(view.begin(), view.end());
}
// ---- TS 102 941 clause 6.2.3.2 --------------------------------------------------
bool validate_issued_certificate(Backend& backend, const Certificate& certificate, const Certificate& issuer,
const PublicKey& requested_key, Clock::time_point now, const Permissions& expected,
bool enrolment) {
try {
if (certificate->version != 3 || certificate->type != Vanetza_Security_CertificateType_explicit ||
certificate->toBeSigned.certIssuePermissions || !certificate->toBeSigned.appPermissions ||
!certificate.valid_at_timepoint(now) || !issuer.valid_at_timepoint(now)) return false;
const auto id = certificate->toBeSigned.id.present;
if ((enrolment && id != Vanetza_Security_CertificateId_PR_name) ||
(!enrolment && id != Vanetza_Security_CertificateId_PR_none)) return false;
const auto digest = issuer.calculate_digest();
const auto referenced = certificate.issuer_digest();
if (!digest || !referenced || *digest != *referenced ||
!security::verify_certificate_signature(backend, certificate, &issuer) ||
!security::chain_permissions_consistent({&certificate, &issuer}) ||
!security::region_within(certificate, issuer, true)) return false;
const auto subject_time = microbu_v2x::security::validity_bounds(certificate);
const auto assurance = certificate.assurance_level();
const auto issuer_assurance = issuer.assurance_level();
if (assurance) {
if (!issuer_assurance) return false;
const auto level = (*assurance >> 5) & 7;
const auto issuer_level = (*issuer_assurance >> 5) & 7;
if (level > issuer_level || (level == issuer_level &&
((*assurance >> 2) & 7) > ((*issuer_assurance >> 2) & 7))) return false;
}
const auto issuer_time = microbu_v2x::security::validity_bounds(issuer);
if (subject_time.start_validity < issuer_time.start_validity || subject_time.end_validity > issuer_time.end_validity)
return false;
if (certificate->toBeSigned.appPermissions->list.count != static_cast<int>(expected.size())) return false;
for (const auto& permission : expected) {
if (!certificate.valid_for_application(permission.first) ||
v3::get_app_permissions(*certificate.content(), permission.first) != permission.second) return false;
}
const auto public_key = v3::get_public_key(*certificate.content());
return public_key && security::same_public_key(*public_key, requested_key);
} catch (const std::exception&) {
return false;
}
}
Result build_enrolment_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
const EnrolmentRequestParameters& params, const Certificate& ea, ByteBuffer& encoded,
RequestContext& context) {
if (params.its_id.empty() || !params.verification_key.sign || !params.outer_signer) return Result::invalid_argument;
if (!v3::get_public_encryption_key(*ea.content())) return Result::invalid_argument;
// 1. InnerEcRequest (certificateFormat ts103097v131 = 1)
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest> inner(asn_DEF_Vanetza_Security_InnerEcRequest);
v3::assign(&inner->itsId, params.its_id);
inner->certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
fill_verification_key(inner->publicKeys.verificationKey, params.verification_key.pub);
fill_permissions(inner->requestedSubjectAttributes, params.app_permissions);
if (!inner.validate()) return Result::invalid_argument;
// 2. InnerEcRequestSignedForPop: self-signed with the new verification key
auto pop = sign_data(backend, now, params.hash, inner.encode(), params.verification_key.sign, nullptr);
if (!pop) return Result::security_unavailable;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
mgmt->version = Vanetza_Security_Version_v1;
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentRequest;
void* target = &mgmt->content.choice.enrolmentRequest;
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *pop)) return Result::security_unavailable;
// 3. Outer EtsiTs103097Data-Signed: self (canonical key) or digest of the current EC
auto outer = sign_data(backend, now, params.hash, mgmt.encode(), params.outer_signer, params.current_ec);
if (!outer) return Result::security_unavailable;
// 4. EtsiTs103097Data-Encrypted for the EA
auto encrypted = encrypt_for(backend, ecies, ea, *outer, context.aes_key);
if (!encrypted) return Result::security_unavailable;
encoded = std::move(*encrypted);
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
return Result::accepted;
}
Result parse_enrolment_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& ea,
const ByteBuffer& encoded, EnrolmentResponse& out) {
auto mgmt_bytes = open_response(backend, ecies, context, ea, encoded);
if (!mgmt_bytes) return Result::rejected;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentResponse) return Result::rejected;
return read_inner_response(mgmt->content.choice.enrolmentResponse, context, out.response_code, out.certificate);
}
// ---- TS 102 941 clause 6.2.3.3 --------------------------------------------------
Result build_authorization_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
const AuthorizationRequestParameters& params, const Certificate& ea,
const Certificate& aa, ByteBuffer& encoded, RequestContext& context) {
if (!params.ec || !params.ec_signer || !params.verification_key.sign || params.app_permissions.empty())
return Result::invalid_argument;
if (params.hash != HashAlgorithm::SHA256) return Result::unsupported; // extDataHash carries sha256HashedData
if (!v3::get_public_encryption_key(*aa.content()) || (params.privacy && !v3::get_public_encryption_key(*ea.content())))
return Result::invalid_argument;
const auto ea_id = ea.calculate_digest();
if (!ea_id) return Result::invalid_argument;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
mgmt->version = Vanetza_Security_Version_v1;
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_authorizationRequest;
auto& inner = mgmt->content.choice.authorizationRequest;
// publicKeys: new verification key and optional encryption key
fill_verification_key(inner.publicKeys.verificationKey, params.verification_key.pub);
if (params.encryption_key) {
inner.publicKeys.encryptionKey = v3::asn1::allocate<Vanetza_Security_PublicEncryptionKey>();
fill_encryption_key(*inner.publicKeys.encryptionKey, *params.encryption_key);
}
// hmacKey: 32 random octets; keyTag = leftmost 16 octets of HMAC-SHA256(hmacKey, OER(publicKeys))
ByteBuffer hmac_key;
try { hmac_key = ecies.random(32); } catch (const std::exception&) { return Result::security_unavailable; }
if (hmac_key.size() != 32) return Result::security_unavailable;
v3::assign(&inner.hmacKey, hmac_key);
ByteBuffer tag_input = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicVerificationKey, &inner.publicKeys.verificationKey);
if (inner.publicKeys.encryptionKey) {
const auto enc = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicEncryptionKey, inner.publicKeys.encryptionKey);
tag_input.insert(tag_input.end(), enc.begin(), enc.end());
}
const auto key_tag = ecies.hmac_sha256(hmac_key, tag_input);
if (key_tag.size() < 16) return Result::security_unavailable;
// SharedAtRequest
auto& shared = inner.sharedAtRequest;
OCTET_STRING_fromBuf(&shared.eaId, reinterpret_cast<const char*>(ea_id->data()), ea_id->size());
OCTET_STRING_fromBuf(&shared.keyTag, reinterpret_cast<const char*>(key_tag.data()), 16);
shared.certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
fill_permissions(shared.requestedSubjectAttributes, params.app_permissions);
if (params.validity_period) {
shared.requestedSubjectAttributes.validityPeriod = v3::asn1::allocate<Vanetza_Security_ValidityPeriod>();
shared.requestedSubjectAttributes.validityPeriod->start = v2::convert_time32(params.validity_period->first);
shared.requestedSubjectAttributes.validityPeriod->duration.present = Vanetza_Security_Duration_PR_hours;
shared.requestedSubjectAttributes.validityPeriod->duration.choice.hours = params.validity_period->second;
}
// EC signature over the SharedAtRequest (external payload), signer = digest of the EC
const ByteBuffer shared_encoded = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_SharedAtRequest, &shared);
auto ec_signed = sign_external(backend, now, shared_encoded, params.ec_signer, *params.ec);
if (!ec_signed) return Result::security_unavailable;
ByteBuffer ec_signature_bytes;
if (params.privacy) {
std::array<std::uint8_t, 16> throwaway {};
auto encrypted = encrypt_for(backend, ecies, ea, *ec_signed, throwaway);
if (!encrypted) return Result::security_unavailable;
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_encryptedEcSignature;
void* target = &inner.ecSignature.choice.encryptedEcSignature;
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *encrypted)) return Result::security_unavailable;
} else {
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_ecSignature;
void* target = &inner.ecSignature.choice.ecSignature;
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *ec_signed)) return Result::security_unavailable;
}
if (!mgmt.validate()) return Result::security_unavailable;
ByteBuffer plaintext = mgmt.encode();
if (params.include_pop) {
auto pop = sign_data(backend, now, params.hash, plaintext, params.verification_key.sign, nullptr);
if (!pop) return Result::security_unavailable;
plaintext = std::move(*pop);
} else {
// EtsiTs103097Data unsecured envelope around the EtsiTs102941Data
SecuredData envelope;
envelope->protocolVersion = 3;
envelope->content = v3::asn1::allocate<Vanetza_Security_Ieee1609Dot2Content>();
envelope->content->present = Vanetza_Security_Ieee1609Dot2Content_PR_unsecuredData;
v3::assign(&envelope->content->choice.unsecuredData, plaintext);
plaintext = envelope.encode();
}
auto encrypted = encrypt_for(backend, ecies, aa, plaintext, context.aes_key);
if (!encrypted) return Result::security_unavailable;
encoded = std::move(*encrypted);
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
return Result::accepted;
}
Result parse_authorization_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& aa,
const ByteBuffer& encoded, AuthorizationResponse& out) {
auto mgmt_bytes = open_response(backend, ecies, context, aa, encoded);
if (!mgmt_bytes) return Result::rejected;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_authorizationResponse) return Result::rejected;
return read_inner_response(mgmt->content.choice.authorizationResponse, context, out.response_code, out.certificate);
}
// ---- TS 102 941 clause 6.3: RCA trust list and revocation list -----------------------
namespace {
void set_url(Vanetza_Security_Url_t& url, const std::string& text) {
OCTET_STRING_fromBuf(&url, text.data(), text.size());
}
std::string get_url(const Vanetza_Security_Url_t& url) {
return std::string(reinterpret_cast<const char*>(url.buf), url.size);
}
void set_hashed_id8(Vanetza_Security_HashedId8_t& target, const HashedId8& id) {
OCTET_STRING_fromBuf(&target, reinterpret_cast<const char*>(id.data()), id.size());
}
std::optional<HashedId8> get_hashed_id8(const Vanetza_Security_HashedId8_t& source) {
if (source.size != 8) return std::nullopt;
HashedId8 id;
std::copy_n(source.buf, 8, id.begin());
return id;
}
// the certificate structure of an entry, decoded from COER into the inline member
bool put_certificate(Vanetza_Security_EtsiTs103097Certificate_t& target, const ByteBuffer& coer) {
void* into = &target;
return vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &into, coer);
}
// TS 102 941 clauses 6.3.3 and 6.3.4. CTLs carry the issuer certificate.
std::optional<ByteBuffer> sign_list(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
ItsAid psid, const ByteBuffer& mgmt) {
if (!rca.valid_for_application(psid)) return std::nullopt; // TS 103 097 clause 7.2.3: CRL/CTL appPermissions
SecuredData data = SecuredData::with_signed_data();
const auto hash = rca->issuer.present == Vanetza_Security_IssuerIdentifier_PR_self &&
rca->issuer.choice.self == Vanetza_Security_HashAlgorithm_sha384 ? HashAlgorithm::SHA384 : HashAlgorithm::SHA256;
data.set_hash_id(hash);
data.set_its_aid(psid);
data.set_generation_time(v2::convert_time64(now));
if (psid == aid::CRL) {
const auto id = rca.calculate_digest();
if (!id) return std::nullopt;
data.set_signer_identifier(*id);
} else data.set_signer_identifier(rca);
data.set_payload(mgmt);
return finish_signed(backend, data, hash, key_signer(backend, rca_key), &rca);
}
// the EtsiTs102941Data of a list message that verifies as signed by rca with the given psid
std::optional<ByteBuffer> open_list(Backend& backend, const ByteBuffer& message, const Certificate& rca, ItsAid psid) {
SecuredData data;
if (!data.decode(message) || data.encode() != message || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
if (data.its_aid() != psid || !data.generation_time() ||
(data.hash_id() != HashAlgorithm::SHA256 && data.hash_id() != HashAlgorithm::SHA384)) return std::nullopt;
if (!rca.valid_for_application(psid)) return std::nullopt;
const auto* signed_data = data->content->choice.signedData;
const auto& header = signed_data->tbsData->headerInfo;
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions) return std::nullopt;
const auto& signer = signed_data->signer;
if (signer.present == Vanetza_Security_SignerIdentifier_PR_certificate) {
if (signer.choice.certificate.list.count != 1) return std::nullopt;
const ByteBuffer inline_cert = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate,
signer.choice.certificate.list.array[0]);
if (inline_cert != rca.encode()) return std::nullopt;
} else if (psid == aid::CRL && signer.present == Vanetza_Security_SignerIdentifier_PR_digest) {
const auto id = rca.calculate_digest();
if (!id || signer.choice.digest.size != id->size() ||
!std::equal(id->begin(), id->end(), signer.choice.digest.buf)) return std::nullopt;
} else return std::nullopt;
const auto signature = data.signature();
const auto key = v3::get_public_key(*rca.content());
if (!signature || !key) return std::nullopt;
const auto digest = message_digest(backend, data.hash_id(), data.signing_payload(), &rca);
try {
if (!backend.verify_digest(*key, digest, *signature)) return std::nullopt;
} catch (const std::exception&) {
return std::nullopt;
}
auto payload = data.payload();
const auto& packet = boost::get<CohesivePacket>(payload);
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
return ByteBuffer(view.begin(), view.end());
}
} // namespace
std::optional<ByteBuffer> build_rca_ctl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
const TrustListEntries& entries, Time32 next_update, std::uint8_t ctl_sequence) {
if (entries.dc.empty()) return std::nullopt;
for (const auto& dc : entries.dc) if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
mgmt->version = Vanetza_Security_Version_v1;
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
auto& ctl = mgmt->content.choice.certificateTrustListRca;
ctl.version = 1; // clause 6.3.4: CtlFormat version 1
ctl.nextUpdate = next_update;
ctl.isFullCtl = 1;
ctl.ctlSequence = ctl_sequence;
const auto add = [&](Vanetza_Security_CtlEntry_PR kind) -> Vanetza_Security_CtlEntry_t& {
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
command->present = Vanetza_Security_CtlCommand_PR_add;
command->choice.add.present = kind;
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
return command->choice.add;
};
for (const auto& ea : entries.ea) {
auto& entry = add(Vanetza_Security_CtlEntry_PR_ea).choice.ea;
if (!put_certificate(entry.eaCertificate, ea.certificate)) return std::nullopt;
set_url(entry.aaAccessPoint, ea.access_point);
if (!ea.its_access_point.empty()) {
entry.itsAccessPoint = vanetza::asn1::allocate<Vanetza_Security_Url_t>();
set_url(*entry.itsAccessPoint, ea.its_access_point);
}
}
for (const auto& aa : entries.aa) {
auto& entry = add(Vanetza_Security_CtlEntry_PR_aa).choice.aa;
if (!put_certificate(entry.aaCertificate, aa.certificate)) return std::nullopt;
set_url(entry.accessPoint, aa.access_point);
}
for (const auto& dc : entries.dc) {
auto& entry = add(Vanetza_Security_CtlEntry_PR_dc).choice.dc;
set_url(entry.url, dc.url);
for (const auto& id : dc.certificates) {
auto* item = vanetza::asn1::allocate<Vanetza_Security_HashedId8_t>();
set_hashed_id8(*item, id);
ASN_SEQUENCE_ADD(&entry.cert, item);
}
}
if (!mgmt.validate()) return std::nullopt;
return sign_list(backend, now, rca, rca_key, aid::CTL, mgmt.encode());
}
std::optional<RcaTrustListUpdate> build_rca_ctl_update(Backend& backend, Clock::time_point now,
const Certificate& rca, const PrivateKey& key, const ByteBuffer& previous_full,
const TrustListEntries& entries, Time32 next_update) {
const auto previous = parse_rca_ctl(backend, previous_full, rca);
if (!previous || !previous->full || next_update <= v2::convert_time32(now)) return std::nullopt;
const auto sequence = static_cast<std::uint8_t>(previous->sequence + 1);
const auto full = build_rca_ctl(backend, now, rca, key, entries, next_update, sequence);
if (!full || !parse_rca_ctl(backend, *full, rca)) return std::nullopt;
const auto old_payload = open_list(backend, previous_full, rca, aid::CTL);
const auto new_payload = open_list(backend, *full, rca, aid::CTL);
if (!old_payload || !new_payload) return std::nullopt;
using Management = vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data>;
Management old_list(asn_DEF_Vanetza_Security_EtsiTs102941Data), new_list(asn_DEF_Vanetza_Security_EtsiTs102941Data),
delta(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!old_list.decode(*old_payload) || !new_list.decode(*new_payload)) return std::nullopt;
delta->version = Vanetza_Security_Version_v1;
delta->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
auto& out = delta->content.choice.certificateTrustListRca;
out.version = 1; out.nextUpdate = next_update; out.isFullCtl = 0; out.ctlSequence = sequence;
// A certificate entry is identified by HashedId8. A DC entry is identified by URL.
auto entry_key = [](const Vanetza_Security_CtlEntry_t& entry) -> ByteBuffer {
Certificate certificate;
switch (entry.present) {
case Vanetza_Security_CtlEntry_PR_ea: certificate = Certificate(entry.choice.ea.eaCertificate); break;
case Vanetza_Security_CtlEntry_PR_aa: certificate = Certificate(entry.choice.aa.aaCertificate); break;
case Vanetza_Security_CtlEntry_PR_dc: {
const auto url = get_url(entry.choice.dc.url);
ByteBuffer result {1}; result.insert(result.end(), url.begin(), url.end()); return result;
}
default: return {};
}
const auto id = certificate.calculate_digest();
if (!id) return {};
ByteBuffer result {0}; result.insert(result.end(), id->begin(), id->end()); return result;
};
using Commands = std::map<ByteBuffer, const Vanetza_Security_CtlCommand_t*>;
Commands old_entries, new_entries;
auto collect = [&](const Vanetza_Security_CtlFormat_t& list, Commands& result) {
for (int i = 0; i < list.ctlCommands.list.count; ++i) {
const auto* command = list.ctlCommands.list.array[i];
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return false;
const auto id = entry_key(command->choice.add);
if (id.empty() || !result.emplace(id, command).second) return false;
}
return true;
};
if (!collect(old_list->content.choice.certificateTrustListRca, old_entries) ||
!collect(new_list->content.choice.certificateTrustListRca, new_entries)) return std::nullopt;
for (const auto& item : new_entries) {
const auto found = old_entries.find(item.first);
if (found != old_entries.end() && vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &found->second->choice.add) ==
vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &item.second->choice.add)) continue;
auto* command = static_cast<Vanetza_Security_CtlCommand_t*>(vanetza::asn1::copy(asn_DEF_Vanetza_Security_CtlCommand, item.second));
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
}
for (const auto& item : old_entries) {
if (new_entries.count(item.first)) continue;
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
command->present = Vanetza_Security_CtlCommand_PR_delete;
auto& removed = command->choice.Delete;
if (item.first[0] == 0) {
removed.present = Vanetza_Security_CtlDelete_PR_cert;
HashedId8 id; std::copy(item.first.begin() + 1, item.first.end(), id.begin());
set_hashed_id8(removed.choice.cert, id);
} else {
removed.present = Vanetza_Security_CtlDelete_PR_dc;
set_url(removed.choice.dc, std::string(item.first.begin() + 1, item.first.end()));
}
}
if (!delta.validate()) return std::nullopt;
const auto signed_delta = sign_list(backend, now, rca, key, aid::CTL, delta.encode());
if (!signed_delta || !parse_rca_ctl(backend, *signed_delta, rca)) return std::nullopt;
return RcaTrustListUpdate {*full, *signed_delta, sequence};
}
std::optional<ByteBuffer> build_crl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
const std::vector<HashedId8>& revoked, Time32 this_update, Time32 next_update) {
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
mgmt->version = Vanetza_Security_Version_v1;
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList;
auto& crl = mgmt->content.choice.certificateRevocationList;
crl.version = 1;
crl.thisUpdate = this_update;
crl.nextUpdate = next_update;
for (const auto& id : revoked) {
auto* entry = vanetza::asn1::allocate<Vanetza_Security_CrlEntry_t>();
set_hashed_id8(*entry, id);
ASN_SEQUENCE_ADD(&crl.entries, entry);
}
if (!mgmt.validate()) return std::nullopt;
return sign_list(backend, now, rca, rca_key, aid::CRL, mgmt.encode());
}
std::optional<RcaTrustList> parse_rca_ctl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
if (v3::get_app_permissions(*rca.content(), aid::CTL) != ByteBuffer({1, 0x38})) return std::nullopt;
const auto mgmt_bytes = open_list(backend, message, rca, aid::CTL);
if (!mgmt_bytes) return std::nullopt;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca) return std::nullopt;
const auto& ctl = mgmt->content.choice.certificateTrustListRca;
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
RcaTrustList list;
list.sequence = static_cast<std::uint8_t>(ctl.ctlSequence);
list.next_update = static_cast<Time32>(ctl.nextUpdate);
list.full = ctl.isFullCtl != 0;
const auto rca_digest = rca.calculate_digest();
if (!rca_digest) return std::nullopt;
const auto issued_by_rca = [&](const Vanetza_Security_EtsiTs103097Certificate_t& raw, Certificate& out) {
out = Certificate(raw);
const auto issuer = out.issuer_digest();
return issuer && *issuer == *rca_digest && out.is_ca_certificate() &&
microbu_v2x::security::verify_certificate_signature(backend, out, &rca);
};
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
const auto* command = ctl.ctlCommands.list.array[i];
if (!command) return std::nullopt;
if (command->present == Vanetza_Security_CtlCommand_PR_add) {
const auto& entry = command->choice.add;
Certificate certificate;
switch (entry.present) {
case Vanetza_Security_CtlEntry_PR_ea:
if (!issued_by_rca(entry.choice.ea.eaCertificate, certificate)) return std::nullopt;
list.ea.push_back(std::move(certificate));
break;
case Vanetza_Security_CtlEntry_PR_aa:
if (!issued_by_rca(entry.choice.aa.aaCertificate, certificate)) return std::nullopt;
list.aa.push_back(std::move(certificate));
break;
case Vanetza_Security_CtlEntry_PR_dc: {
TrustListEntries::DistributionCentre dc;
dc.url = get_url(entry.choice.dc.url);
for (int k = 0; k < entry.choice.dc.cert.list.count; ++k) {
const auto id = entry.choice.dc.cert.list.array[k] ? get_hashed_id8(*entry.choice.dc.cert.list.array[k]) : std::nullopt;
if (!id) return std::nullopt;
dc.certificates.push_back(*id);
}
if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
list.dc.push_back(std::move(dc));
break;
}
default:
return std::nullopt; // clause 6.3.2: an RCA CTL carries no RCA or TLM entries
}
} else if (command->present == Vanetza_Security_CtlCommand_PR_delete) {
if (list.full) return std::nullopt; // clause 6.3.4: a FullCtl has add commands only
const auto& del = command->choice.Delete;
if (del.present == Vanetza_Security_CtlDelete_PR_cert) {
const auto id = get_hashed_id8(del.choice.cert);
if (!id) return std::nullopt;
list.deleted.push_back(*id);
} else if (del.present == Vanetza_Security_CtlDelete_PR_dc) {
list.deleted_dc.push_back(get_url(del.choice.dc));
} else {
return std::nullopt;
}
} else {
return std::nullopt;
}
}
if (list.full && list.dc.empty()) return std::nullopt;
return list;
}
std::optional<ByteBuffer> build_tlm_ctl(Backend& backend, Clock::time_point now,
const Certificate& tlm, const PrivateKey& key, const std::vector<Certificate>& roots,
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence) {
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
mgmt->version = Vanetza_Security_Version_v1;
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm;
auto& ctl = mgmt->content.choice.certificateTrustListTlm;
ctl.version = 1; ctl.nextUpdate = next_update; ctl.isFullCtl = 1; ctl.ctlSequence = sequence;
for (const auto& cert : roots) {
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
command->present = Vanetza_Security_CtlCommand_PR_add;
command->choice.add.present = Vanetza_Security_CtlEntry_PR_rca;
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
if (!put_certificate(command->choice.add.choice.rca.selfsignedRootCa, cert.encode())) return std::nullopt;
}
for (const auto& cert : successors) {
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
command->present = Vanetza_Security_CtlCommand_PR_add;
command->choice.add.present = Vanetza_Security_CtlEntry_PR_tlm;
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
auto& entry = command->choice.add.choice.tlm;
if (!put_certificate(entry.selfSignedTLMCertificate, cert.encode())) return std::nullopt;
set_url(entry.accessPoint, "https://cpoc.example.test/L0");
}
if (!mgmt.validate()) return std::nullopt;
return sign_list(backend, now, tlm, key, aid::CTL, mgmt.encode());
}
std::optional<TlmTrustList> parse_tlm_ctl(Backend& backend, const ByteBuffer& message, const Certificate& tlm) {
const auto permissions = v3::get_app_permissions(*tlm.content(), aid::CTL);
if (permissions.size() != 2 || permissions[0] != 1 || permissions[1] != 0xc8 ||
!microbu_v2x::security::verify_certificate_signature(backend, tlm, nullptr)) return std::nullopt;
const auto bytes = open_list(backend, message, tlm, aid::CTL);
if (!bytes) return std::nullopt;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!mgmt.decode(*bytes) || mgmt.encode() != *bytes || mgmt->version != Vanetza_Security_Version_v1 ||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm) return std::nullopt;
const auto& ctl = mgmt->content.choice.certificateTrustListTlm;
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
TlmTrustList result;
result.sequence = ctl.ctlSequence; result.next_update = ctl.nextUpdate; result.full = ctl.isFullCtl;
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
const auto* command = ctl.ctlCommands.list.array[i];
// This client requests full lists. Never apply a delta without its complete base.
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return std::nullopt;
const auto& entry = command->choice.add;
if (entry.present == Vanetza_Security_CtlEntry_PR_rca) {
Certificate cert(entry.choice.rca.selfsignedRootCa);
if ((cert->issuer.present != Vanetza_Security_IssuerIdentifier_PR_self || !cert.is_ca_certificate()) || !microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
result.roots.push_back(std::move(cert));
} else if (entry.present == Vanetza_Security_CtlEntry_PR_tlm) {
Certificate cert(entry.choice.tlm.selfSignedTLMCertificate);
const auto p = v3::get_app_permissions(*cert.content(), aid::CTL);
if (p.size() != 2 || p[0] != 1 || p[1] != 0xc8 ||
!microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
result.tlms.push_back(std::move(cert));
} else if (entry.present != Vanetza_Security_CtlEntry_PR_dc) return std::nullopt;
}
return result;
}
std::optional<RevocationList> parse_crl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
if (v3::get_app_permissions(*rca.content(), aid::CRL) != ByteBuffer({1})) return std::nullopt;
const auto mgmt_bytes = open_list(backend, message, rca, aid::CRL);
if (!mgmt_bytes) return std::nullopt;
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList) return std::nullopt;
const auto& crl = mgmt->content.choice.certificateRevocationList;
if (crl.version != 1) return std::nullopt;
RevocationList list;
list.this_update = static_cast<Time32>(crl.thisUpdate);
list.next_update = static_cast<Time32>(crl.nextUpdate);
for (int i = 0; i < crl.entries.list.count; ++i) {
const auto id = crl.entries.list.array[i] ? get_hashed_id8(*crl.entries.list.array[i]) : std::nullopt;
if (!id) return std::nullopt;
list.revoked.push_back(*id);
}
return list;
}
std::size_t apply(const RcaTrustList& list, microbu_v2x::security::TrustConfiguration& trust) {
std::size_t added = 0;
for (const auto* entries : {&list.ea, &list.aa}) {
for (const auto& certificate : *entries) {
if (trust.add_authority(certificate) == Result::accepted) ++added;
}
}
return added;
}
std::size_t apply(const RevocationList& list, const Certificate& rca, microbu_v2x::security::TrustConfiguration& trust) {
const auto issuer = rca.calculate_digest();
if (!issuer) return 0;
trust.clear_revocations(*issuer);
for (const auto& id : list.revoked) trust.revoke(*issuer, id);
return list.revoked.size();
}
} // namespace microbu_v2x::pki
File diff suppressed because it is too large Load Diff
@@ -1,40 +0,0 @@
#include <microbu_v2x/security_backend.hpp>
#include "local_security.hpp"
#include <sdkconfig.h>
#include <stdexcept>
namespace microbu_v2x {
namespace {
template <class T>
std::unique_ptr<T> required(std::unique_ptr<T> made, const char* what) {
if (!made) throw std::runtime_error(what);
return made;
}
} // namespace
std::unique_ptr<vanetza::security::Backend> make_security_backend() {
#if CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
return required(make_external_security_backend(), "security adapter returned no backend");
#else
return make_local_security_backend();
#endif
}
std::unique_ptr<security::SecurityModule> make_security_module() {
#if CONFIG_MICROBU_V2X_CRYPTO_SE051 || CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
return required(make_external_security_module(), "security adapter returned no security module");
#else
return make_local_security_module();
#endif
}
const char* security_module_name() {
#if CONFIG_MICROBU_V2X_CRYPTO_SE051
return "se051";
#elif CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
return "v2x-hsm";
#else
return "esp32-software";
#endif
}
} // namespace microbu_v2x
@@ -1,205 +0,0 @@
#include <microbu_v2x/security_module.hpp>
#include <microbu_v2x/ecc.hpp>
#include <vanetza/security/v3/hash.hpp>
#include <algorithm>
#include <stdexcept>
namespace microbu_v2x::security {
using vanetza::security::KeyCompression;
using vanetza::security::key_length;
namespace {
constexpr std::uint8_t magic[4] = {'M', 'S', 'M', '1'};
void wipe(ByteBuffer& secret) {
volatile std::uint8_t* target = secret.data();
for (std::size_t n = secret.size(); n--;) *target++ = 0;
secret.clear();
}
std::uint8_t curve_code(KeyType type) {
switch (type) {
case KeyType::NistP256: return 1;
case KeyType::BrainpoolP256r1: return 2;
case KeyType::BrainpoolP384r1: return 3;
default: return 0;
}
}
KeyType curve_type(std::uint8_t code) {
switch (code) {
case 1: return KeyType::NistP256;
case 2: return KeyType::BrainpoolP256r1;
case 3: return KeyType::BrainpoolP384r1;
default: return KeyType::Unspecified;
}
}
void put_u32(ByteBuffer& out, std::uint32_t value) {
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<std::uint8_t>(value >> shift));
}
std::uint32_t get_u32(const ByteBuffer& in, std::size_t at) {
return std::uint32_t(in[at]) << 24 | std::uint32_t(in[at + 1]) << 16 | std::uint32_t(in[at + 2]) << 8 | in[at + 3];
}
bool well_formed(const KeyPair& pair) {
const auto type = pair.priv.type;
const auto n = key_length(type);
return curve_code(type) != 0 && pair.pub.type == type && pair.priv.key.size() == n &&
pair.pub.compression == KeyCompression::NoCompression && pair.pub.x.size() == n && pair.pub.y.size() == n;
}
/// The two halves belong together when a signature with the private key verifies with the public key.
bool halves_match(vanetza::security::Backend& backend, const KeyPair& pair) {
const ByteBuffer probe = backend.calculate_hash(vanetza::security::v3::specified_hash_algorithm(pair.priv.type),
pair.pub.x);
return backend.verify_digest(pair.pub, probe, backend.sign_digest(pair.priv, probe));
}
ByteBuffer encode_keys(std::uint32_t next, const std::map<KeyId, KeyPair>& keys) {
ByteBuffer out(std::begin(magic), std::end(magic));
put_u32(out, next);
for (const auto& [id, pair] : keys) {
put_u32(out, id.value);
out.push_back(curve_code(pair.priv.type));
for (const auto* part : {&pair.priv.key, &pair.pub.x, &pair.pub.y}) out.insert(out.end(), part->begin(), part->end());
}
return out;
}
bool decode_keys(const ByteBuffer& in, std::uint32_t& next, std::map<KeyId, KeyPair>& keys) {
if (in.size() < 8 || !std::equal(std::begin(magic), std::end(magic), in.begin())) return false;
next = get_u32(in, 4);
for (std::size_t at = 8; at < in.size();) {
if (in.size() - at < 5) return false;
const KeyId id {get_u32(in, at)};
const KeyType type = curve_type(in[at + 4]);
at += 5;
const auto n = key_length(type);
if (!id || id.value >= next || type == KeyType::Unspecified || in.size() - at < 3 * n || keys.count(id)) return false;
KeyPair pair;
pair.priv.type = pair.pub.type = type;
pair.pub.compression = KeyCompression::NoCompression;
pair.priv.key.assign(in.begin() + at, in.begin() + at + n);
pair.pub.x.assign(in.begin() + at + n, in.begin() + at + 2 * n);
pair.pub.y.assign(in.begin() + at + 2 * n, in.begin() + at + 3 * n);
at += 3 * n;
keys.emplace(id, std::move(pair));
}
return true;
}
/// x and y of a public key in uncompressed form, none when a compressed point is not on its curve.
std::optional<PublicKey> uncompressed(const PublicKey& key) {
if (key.compression == KeyCompression::NoCompression) return key;
const bool odd = key.compression == KeyCompression::Y1;
if (!odd && key.compression != KeyCompression::Y0) return std::nullopt;
const auto point = ecc::decompress(key.type, key.x, odd);
if (!point) return std::nullopt;
PublicKey out;
out.type = key.type;
out.compression = KeyCompression::NoCompression;
out.x = point->x;
out.y = point->y;
return out;
}
} // namespace
bool same_public_key(const PublicKey& a, const PublicKey& b) {
if (a.type != b.type || a.type == KeyType::Unspecified) return false;
const auto ua = uncompressed(a), ub = uncompressed(b);
return ua && ub && ua->x == ub->x && ua->y == ub->y;
}
bool MemoryKeyStorage::load(ByteBuffer& out) {
if (blob_.empty()) return false;
out = blob_;
return true;
}
bool MemoryKeyStorage::save(const ByteBuffer& blob) {
wipe(blob_);
blob_ = blob;
return true;
}
SoftwareSecurityModule::SoftwareSecurityModule(vanetza::security::Backend& backend, KeyGenerator& generator,
KeyStorage& storage) :
backend_(backend), generator_(generator), storage_(storage) {
ByteBuffer stored;
if (!storage_.load(stored)) return;
const bool decoded = decode_keys(stored, next_, keys_);
wipe(stored);
if (!decoded) throw std::runtime_error("stored security module keys do not decode");
}
SoftwareSecurityModule::~SoftwareSecurityModule() {
for (auto& entry : keys_) wipe(entry.second.priv.key);
}
KeyId SoftwareSecurityModule::generate_key(KeyType type) {
KeyPair pair = generator_.generate_key(type);
if (!well_formed(pair)) throw std::runtime_error("key generation returned no usable key pair");
return keep(std::move(pair));
}
std::optional<KeyId> SoftwareSecurityModule::import_key(const KeyPair& pair) {
const auto pub = uncompressed(pair.pub);
if (!pub) return std::nullopt;
KeyPair copy {pair.priv, *pub};
try {
if (!well_formed(copy) || !halves_match(backend_, copy)) {
wipe(copy.priv.key);
return std::nullopt;
}
} catch (const std::exception&) {
wipe(copy.priv.key);
return std::nullopt;
}
return keep(std::move(copy));
}
std::optional<PublicKey> SoftwareSecurityModule::public_key(KeyId id) const {
const auto found = keys_.find(id);
if (found == keys_.end()) return std::nullopt;
return found->second.pub;
}
Signature SoftwareSecurityModule::sign_digest(KeyId id, const ByteBuffer& digest) {
const auto found = keys_.find(id);
if (found == keys_.end()) throw std::runtime_error("security module holds no such key");
return backend_.sign_digest(found->second.priv, digest);
}
bool SoftwareSecurityModule::destroy_key(KeyId id) {
const auto found = keys_.find(id);
if (found == keys_.end()) return false;
wipe(found->second.priv.key);
keys_.erase(found);
persist();
return true;
}
KeyId SoftwareSecurityModule::keep(KeyPair pair) {
if (next_ == 0) throw std::runtime_error("security module key identifiers exhausted");
const KeyId id {next_++};
keys_.emplace(id, std::move(pair));
try {
persist();
} catch (...) {
wipe(keys_[id].priv.key);
keys_.erase(id);
throw;
}
return id;
}
void SoftwareSecurityModule::persist() {
ByteBuffer blob = encode_keys(next_, keys_);
const bool saved = storage_.save(blob);
wipe(blob);
if (!saved) throw std::runtime_error("security module keys not stored");
}
} // namespace microbu_v2x::security

Some files were not shown because too many files have changed in this diff Show More