Files
MicrOBU/README.md
T
Ashin Walpola 1c3a66e4da Update the README for BLE, signed messages and traffic lights per lane
The README predated the vanetza-idf port. It now describes the ESP32-C5 as
the XIAO running a signing ITS station, the station-link protocol over
USB-C and Bluetooth LE (GATT layout, pairing, reconnect, USB priority),
the raw receive path and its five BTP ports, phone-built CAM or VAM sent
signed or unsigned, traffic lights per lane from SPATEM and MAPEM, the
V2X data logger and the battery display. Architecture, verification,
documentation links, getting started and the known limitations follow
the current code; the version is the build's versionName, 0.1.0.
2026-11-03 15:09:54 +01:00

211 lines
20 KiB
Markdown

# MicrOBU Android App
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.
**Platform:** Android (Kotlin) / **Min SDK:** 29 (Android 10) / **Target SDK:** 36 / **Version:** 0.1.0 (`versionName`, 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.
## 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/`) |
|---|---|---|
| What it is | Complete V2X on-board unit | Seeed XIAO ESP32-C5 running a vanetza-idf 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 |
| 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.
## 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.
**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. Each message carries a rotating pseudonym (station ID and MAC change together) and ITS time in TAI.
**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.
**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.
**CSV export**; every sensor sample written to a timestamped CSV in real time. Trip exports additionally include the V2X messages received and their RSSI. Shareable via the standard Android share sheet.
## Architecture
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
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope
data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport
data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager
data/log/ V2xLogger, V2xLogWriter (the V2X data logger)
data/db/ Room database (sessions, trips, V2X messages)
data/ SensorRepository, GnssTimeSource, TripRepository, CsvExporter, TripExporter
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
service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService
obu-firmware/ ESP32-C5 OBU: vanetza-idf station (signing, BTP, GeoNetworking), station link over
USB and BLE, raw receive path (gn_unwrap.c), battery monitor; host tests in test/
obu-firmware/external/vanetza-idf/ the C-ITS library the firmware builds against (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
```
The `domain/` packages contain no Android imports. That is what makes the 132-test JVM suite possible without an emulator or instrumentation.
## Connectivity
| 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 |
| Wi-Fi | CiT One | Developer builds only |
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 v1** (from the colleague's `microbu-esp32c5` station): `[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 with `RESULT`, sends `STATUS` every second, and forwards every ITS message it hears as `V2X_RX` (0x85, 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 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.
- **USB takes priority**: the board stops advertising while its USB link is in use (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s), because BLE and ITS-G5 share the C5's single RF front end.
- **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.
## Verification
The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path, which is the highest-risk code in the project. Round-trip tests through the project's own codecs structurally cannot catch a shared mistake about a field's bit width, and this project shipped exactly that bug three times (`CurvatureCalculationMode`, the GeoNetworking reserved bytes, `yawRateConfidence`). Phone and ESP32 agreed with each other and with nothing else.
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.
- **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 the colleague'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`.
## Documentation
| Document | Audience |
|---|---|
| [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/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 the colleague'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 |
| [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 |
## Key dependencies
| Library | Purpose |
|---|---|
| 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 |
| 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
1. Open in Android Studio and build the `app` module. Gradle 8.10.2.
2. Connect a device running Android 10+ (API 29).
3. Choose your hardware in Settings > OBU Hardware.
**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.
**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: both cap a link message at 512 octets, and the app speaks the station-link protocol (it still falls back to the previous firmware's frames for CAM over USB).
## 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. 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. Received signatures are not verified on the ESP32-C5 path.
- **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.
- **Station IDs rotate**, so they cannot identify a physical unit over time.
- **No backend, no login.** Everything is on-device.
## 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.
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/`.
**Owner:** HAW Hamburg