Compare commits

..
Author SHA1 Message Date
Ashin Walpola 73d4477f1e Move the capture tooling into the repo
live_capture.py and dump_pcap.py were untracked files inside the third-party
its-g5-receiver-firmware checkout, so the tools every on-air measurement depends
on were versioned nowhere and would vanish with a fresh clone of that project.
They are ours rather than that project's, so they now live in capture/, with the
setup notes rewritten as its README: which port the sniffer speaks on and why,
how to capture, how to check a capture, and how to flash the sniffer board.

live_capture.py carries the fix made on 2026-09-14. The sniffer's console
converts LF to CRLF on its way out, and that applies to every 0x0a byte of the
binary pcap stream, not only to log text, so every inserted CR shifts the rest
of the stream. A 787 KB capture parsed cleanly for only 82 of about 2000
records, and DENMs turned up on nonsense BTP ports because their payloads carry
0x0a often. undo_crlf() reverses it on the raw stream before any framing, which
is exact; afterwards a capture parsed to EOF and DENMs read as port 2002.
Captures taken before that date are truncated at their first corrupted record,
so anything measured from them is worth re-checking.

capture/recordings/ is gitignored, since captures are data rather than source.
The host tests now read both that directory and the older one in the receiver
checkout, so no capture has to be moved while it is being written.

dump_pcap.py reads the same console and still needs the same treatment; that is
recorded in TODO.md.
2026-09-14 13:38:38 +02:00
Ashin Walpola 277c6b20f4 Record the on-air verification and how to run the bench beacon
Both firmware fixes are now confirmed over the air, with the sniffer board
capturing and asn1tools judging the result.

GN lifetime: our station transmits 0x05 (1 s), the value both bench stations
use, where the August captures show 0x83 (3200 s) for the same frames. 397 CAMs
from station 999999 decode and re-encode byte-identically, so the whole
transmit chain is right on the wire, not only in the host tests.

yawRateConfidence: the bench beacon, flashed to a spare board, sends CAMs that
decode and re-encode byte-identically as well (72 of 72 from station
0x0BADC0DE). NOTES.md now says how to flash that beacon and how to check what
it sends, including that it shares the phone pinger's MAC and the two are told
apart by station ID.

The new firmware also runs on the OBU with the phone attached: CAM, DENM and
SPATEM from the bench stations all keep decoding in the app now that messages
are cut to the length their header declares.

Signed reception stays open. The CiT One transmits unsigned and nothing else
here signs, so it needs real roadside traffic, the CiT One switched to signed
mode, or a replay firmware on a spare board.

Two bench facts worth not rediscovering are recorded too: opening COM3's
console resets the OBU and drops the phone's USB link, and every capture taken
before today is truncated at its first corrupted record, because the receiver's
console inserts a CR before every 0x0a byte of the binary pcap stream.
live_capture.py now undoes that, a change that lives in the receiver repo and
is not part of this commit.
2026-09-14 13:33:47 +02:00
6508 changed files with 3589 additions and 794897 deletions
+2 -41
View File
@@ -47,44 +47,5 @@ sdkconfig.old
# and remove them on close, so they are transient and machine-local.
~$*
# Full-flash images read back off the bench boards before reflashing them (16 MB each).
# Restore with: esptool --chip esp32c5 -p COM<N> write-flash 0 <image>
/firmware-backups/
# ESP-IDF component manager downloads (espressif/esp-boost for obu-firmware's vanetza-idf), ~125 MB.
# 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
# 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.
/microbu-esp32c5/
# 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*
# Captures are large data files, not source (see capture/README.md).
/capture/recordings/
-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 -167
View File
@@ -2,88 +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.
**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.
@@ -95,90 +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
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 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
@@ -186,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`.
@@ -204,14 +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/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 |
@@ -221,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
@@ -238,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
+41 -460
View File
@@ -5,428 +5,44 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware
### 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.
Settings > Developer > V2X data logger. 110 unit tests pass. ESP32-C5 path checked on the Pixel 9 Pro on
2026-10-02 (see the ticked item); the rest has not run on a device.
- [x] **ESP32-C5 (done 2026-10-02, simulated car + RSU on air):** 153 CAMs and 60 SPATEMs in 30 s, RSSI -56..-36 dBm,
phone GNSS on every row, `obu_*` NULL, file integrity ok. MAPEM 0 as expected (firmware drops port 2003). Original steps: start a log, let the simulated car's CAMs arrive, stop. Pull the `.db` from
`files/v2x_logs/` and check `messages`: `msg_type='CAM'`, `source='esp32'`, `rssi_dbm` filled,
`phone_lat/lon` filled, `obu_*` NULL, `payload` decodes with `asn1tools`.
- [ ] **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.
### 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
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
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
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()`
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.
`Esp32Link` now sends a PoTi only for a newer fix (or a >= 60 s real clock correction).
3. BLE reconnect loop: GATT operations with a 5 s timeout ran during Android's pairing, cut it off
and restarted it on every attempt. Encryption/pairing is now settled first (60 s), retries back
off to 30 s, and every failure reason is logged and shown; the board logs encryption changes.
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
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
(task watchdog: IDLE starved). Now waits at least one tick.
6. The phone clock is ~14 min fast; GnssTimeSource fell back to it whenever GNSS time blinked out
indoors, so every transmitted timestamp (CAM generationDeltaTime too) jumped 14 min back and
forth. It now keeps the last measured error.
Watch COM3 (`idf.py -p COM3 monitor`, or `readlog.py`-style with DTR/RTS low) during these; it only
resets the board, the phone is on the other port.
- [x] **USB session.** Settings > Connection > ESP32-C5: link USB-C, transmit CAM, signing on.
Phone on the native port, Connect. Expected: the card shows "Provisioning the demo credentials"
once, then Connected and `Signing on · tickets 1 · signed N` with N rising while recording.
COM3: `radio on channel 180, transmit and receive`, `tx power: … dBm`,
`credentials provisioned: 1 roots, 1 authorities, 1 tickets`, and no `radio refused a frame`.
Confirmed by the user 2026-09-23: connects, signing works.
- [x] **Reception intact.** Same session, sim car (COM8) beaconing: its CAMs (station 195936478) on
the V2X map at ~3 Hz as before. Then put a DENM and a SPATEM on air: both show up (they come
through the raw V2X_RX path; the vanetza stack drops them because they are not demo-signed).
Confirmed 2026-09-23: sim car and the RSU's CAM/SPATEM/MAPEM arrive; DENM not yet re-tested.
- [x] **Signed CAM on air** (2026-09-23, CAM pinger over BLE, signing on). Recorded 25 s through
the V2X2MAP bridge's `/api/record` (`micrOBU_workspace/v2x-obu-esp32c5/signed-cam-check.pcap`)
and checked with the new `obu-firmware/test/verify_signed_pcap.py` (asn1tools + OpenSSL, no
vanetza code): 12/12 secured CAMs, station 999999, psid 36, signer = full certificate of the
demo AT `B80B49387A4C12EB`, **all signatures valid**, COER canonical, and the bundle's chain
(AT <- AA <- root) verifies. The CiT One (192.168.40.201) also receives them (~1 Hz on
`v2x/rx/cam`), i.e. a third-party stack unwraps our 1609.2 envelope; its MQTT API exposes no
security fields, and it forwards unsigned and unknown-root messages alike, so it cannot say
whether it verified them. The same capture showed generationTime wobbling by seconds, with
`time_regression` still firing: fixed in Esp32Link (the PoTi never moves the micrOBU's clock
back except for a >= 60 s correction). Re-check: no "restarted its stack" lines in logcat.
- [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
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
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.
- [x] **RX without recording.** Connect only (no recording, no pinger): sim-car CAMs appear and
the RX-queue drop counter stays at 0 or near it.
Confirmed 2026-09-23: messages come in on connect alone.
- [ ] **No time_regression.** Record for a few minutes standing still indoors: no "refused" line on
the card, and COM3 never logs `ITS time moved back`.
- [x] **BLE after the NVS fix.** First forget micrOBU-4AFA in Android's Bluetooth settings (the
phone still holds the bond the board lost). Then Connect, passkey 123456 once; a second
Connect after an app restart must not prompt again, and COM3's next boot must say
`1 bonded phone(s) in NVS`.
Confirmed 2026-09-23: pairs once, reconnects after an app restart.
- [x] **BLE.** Link Bluetooth, unplug USB, Connect. Android asks to pair with micrOBU-4AFA:
passkey 123456. Expected: Connected, CAMs keep going, sim-car CAMs keep arriving.
While USB is plugged in and in use, the phone's BLE scan must not see micrOBU-4AFA
(COM3: `USB link in use: BLE advertising paused`). If it loops again, the card now says why;
"refused this phone's stored pairing" means forget micrOBU-4AFA in Android and pair again.
COM3 shows `encryption change status=...` for the board's side.
Confirmed 2026-09-23: CAMs and VAMs out, reception in, over BLE.
- [ ] **BLE/ITS-G5 coexistence (the unmeasured risk from the hardware review).** With BLE
connected, count the sim car's CAMs received per minute and ours at the sniffer; compare
with the same over USB. A clear drop, or reception stopping altogether, means the coex
arbiter takes the radio off 5900 MHz (our channel is set behind the driver's back with
`phy_change_channel`). Then BLE cannot be used while receiving, or needs a longer connection
interval.
- [ ] **Board reset recovery over BLE.** Press RST mid-session: the app reconnects by itself and
reconfigures on the first STATUS saying `not configured`, with no manual Connect. (Over USB a
reset re-enumerates the port and needs a manual Connect, as before.)
### Confirm the RX queue drop counter explains the bench-session frame drops / map flicker (added 2026-09-22)
Investigated the user's report of "OBU mode keeps dropping a few frames" and "v2x screen comes
and goes" while bench-testing against `obu-cam-transmistter`. Found a real, previously invisible
drop path: `obu-firmware/main/main.c`'s `wifi_promisc_rx_cb()` calls `xQueueSend(s_rx_queue, ...,
0)` (queue depth 8) without checking the return value, so a burst of promiscuously-captured
frames arriving faster than `rx_forward_task` can drain them (each drain can legitimately block up
to ~400ms under USB/UART contention) silently vanishes. None of the existing `EspLinkStatus`
counters (`oversizeDrops`/`txFailures`/`rxCrcErrors`) caught this class of drop.
This plausibly also explains the map symptom: `UseCaseDetectionEngine.pruneStale()` drops a remote
station's marker after `staleRemoteMs` (3 s) with no CAM update. Measured 2026-09-22 via
`tools/cit_one_rx_watch.py --host 192.168.40.201` against `obu-cam-transmistter`'s bench beacon
(stationID 195936478 / 0x0BADC0DE): **75 CAMs in 25 s, ~3 Hz**, not the 1 Hz this note assumed
earlier — faster than assumed means more promiscuous captures per second and a shorter fuse on
`staleRemoteMs`, both of which make the queue-overflow theory more likely, not less.
Fixed to be **visible**, not yet fixed to **not drop**: added a `rxQueueDrops` counter, checked
`xQueueSend`'s return value (`main.c`), wired it through the STATUS heartbeat as a new trailing
`uint16` field (`serial_link.c/.h`, `SerialFrame.kt`'s `EspLinkStatus`), and surfaced it on the
CAM Pinger card (`MqttTopicViewerScreen.kt`, string `mqtt_cam_pinger_fw_counters`). Host build
untouched (serial_link.c/main.c aren't in the host test's standard-headers-only set); IDF build
verification is the remaining pre-flash check. Deliberately did NOT bump `s_rx_queue`'s depth from
8 — no real burst-size data yet, and guessing a bigger number against an unmeasured memory budget
is exactly the kind of assumption [[microbu-hw-review]] flags as needing verification first, not
capacity that's cheap to reason your way into.
Needs: a phone attached to the production OBU's native USB port, watching the CAM Pinger card,
while `obu-cam-transmistter` (or real traffic) beacons.
- [x] `idf.py build` succeeds (obu-firmware, IDF 6.1) — clean, both changed files compiled with no
warnings, 17% flash free.
- [x] Reflashed the production OBU on **COM3** 2026-09-22 (hash verified). Boot log confirms the
new build (`21e0149-dirty`, compiled Sep 22 2026 14:14:09), clean boot, OCB @ 5900 MHz
TX/RX armed, `serial_link up ... 1 Hz heartbeat`, no panic. Incidentally answers part of the
"measure the OBU's actual transmit power" item below: this boot logged
`tx power: 72 quarter-dBm = 18.00 dBm (20.00 requested)` — the driver **is** clamping below
the requested 20 dBm at 5900 MHz, as that item suspected but had not measured.
- [x] 25 s of steady-state console (no phone attached, `obu-cam-transmistter` beaconing nearby):
silent — no crash, no `oversize`/`rx queue full`/`crc` warnings. Inconclusive on its own
(successful forwards aren't logged, and nothing was attached to trigger the ~400 ms UART
stalls the theory needs), but at least rules out a crash-on-boot regression.
- [x] Confirmed the wider bench RF path independently via the CiT One OBU broker
(`py -3.11 tools/cit_one_rx_watch.py --host 192.168.40.201`): heard `obu-cam-transmistter`'s
beacon cleanly, 75/25 s, GN source `14:00:02:00:00:00:00:01`, position in the expected
St. Georg route area. This is a *different* receiver from the production OBU though — it
shows the beacon is genuinely on air, not that COM3 forwards every one of it without drops.
- [x] **Confirmed on real hardware, 2026-09-22.** Installed the updated debug APK (previous build
on the phone was from 2026-09-15, predating this fix entirely) on the Pixel 9 Pro (adb over
Wi-Fi), relaunched against the freshly-reflashed COM3, and read `rx queue drop` via `adb
logcat -s UsbSerialTransport`. The counter mechanism works end-to-end and **the bug is
real**: `rxQueueDrops` was 0 at the last flash (14:22), read as 89 at first reconnect
(14:48, ~26 min later), and 90 at a second reconnect (14:52). No `oversizeDrops`,
`txFailures`, or `rxCrcErrors` moved at all, and zero `decode FAILED` lines — this queue is
the only place frames are going missing.
Nuance: over a clean ~4.5 min window in between (14:48→14:52) with `obu-cam-transmistter`
actively beaconing at a measured **~3.33 Hz** (matches the CiT One's 75/25 s independently)
and 490+ CAMs decoding cleanly with steady cadence and no gaps, the counter did **not**
move — it only ticked at connect/reconnect moments. So this is a low-rate, bursty drop (matches
the user's own "a few frames" framing), not a continuous overflow under steady single-station
traffic; it may be specific to WiFi/PHY activity around association or reconnect rather than
raw beacon rate. Worth a longer, quieter-boot capture before sizing a `s_rx_queue` bump.
Did **not** independently confirm the map-flicker connection this session — that needs eyes
on the app's V2X screen while watching this same counter live, not just logcat.
### On-device check of the full-screen V2X live map (added 2026-09-15)
The live map moved out of the V2X Monitor's view-mode row into its own full-screen destination
(`V2xMapScreen`, route `v2x_map`), reached from the map button in that screen's header. Markers are
now cached and reused across updates instead of being rebuilt on every incoming message, and
SPATEM intersections are drawn as traffic lights at the position of the RSU's own CAM. All of that
compiles and the unit tests pass, but none of it has been seen with live traffic.
Needs: the phone with the app, plus a CAM/DENM/SPATEM source - either the CiT One, or the OBU
ESP32-C5 with a second board or a real RSU transmitting.
- [ ] Both hardware modes: tap the map button, confirm the map fills the screen (no status bar, no
bottom nav) and the back button returns to the V2X Monitor.
- [ ] Panning stays smooth while CAMs are arriving - this is what the marker reuse is for. Compare
against the old behaviour if it still judders.
- [ ] Touching the map stops it recentring; the location FAB resumes follow and lights up.
- [ ] A DENM shows the warning triangle, and a SPATEM intersection shows a traffic light with the
lamp matching the Dashboard's SignalCard for the same intersection.
- [ ] Near a real RSU: confirm the RSU is drawn once, as a traffic light, not as a CAM pin with a
light on top of it. If the RSU sends SPATEM but no CAM, the "signals not shown" note should
appear instead - worth knowing which of the two the HAW RSUs actually do.
### Over-the-air check of the GN lifetime fix (added 2026-09-11)
`geonet.c` now writes GN lifetime `0x05` (1 s) instead of `0x83`, which decoded to 3200 s. Changed
in both `obu-firmware` and `obu-cam-transmistter`. Both still build (IDF 6.1 / 5.5.4), and the
compiled `geonet_wrap_shb` stores the new byte, but it has not been seen on air yet. Nothing else
compiled `geonet_wrap_shb` stores the new byte. Confirmed on air 2026-09-14. Nothing else
reads this byte (`gn_unwrap.c` ignores it, the app never sees GN headers), so the app does not
need updating alongside the firmware.
Needs: the phone with the app, the OBU ESP32-C5, and a **second** ESP32-C5 running
`its-g5-receiver-firmware` to capture with.
- [ ] Flash `obu-firmware` (see `obu-firmware/FLASHING.md`).
- [ ] Connect the phone, let it send CAMs, and confirm the CAM Pinger's `tx fail` counter stays 0.
- [ ] Capture with the receiver into `its-g5-receiver-firmware/recordings/`.
- [ ] Run `python obu-firmware/test/pcap_gn_tally.py its-g5-receiver-firmware/recordings/<capture>.pcap`.
The rows for the phone's pseudonym MACs must show SHB, port 2001, lifetime `0x05`, exactly
like every other station's CAMs.
- [ ] While the phone is connected: real-station CAMs/DENMs still reach the app (RX path unchanged).
- [x] Flash `obu-firmware` (done 2026-09-14 on COM3; flash backed up first to
`Documents/micrOBU_workspace/firmware-backups/COM3-2026-09-14-before-secured-rx.bin`).
- [x] Capture with the receiver (COM8) into `its-g5-receiver-firmware/recordings/`.
- [x] `pcap_gn_tally.py` on capture_20260914_132126.pcap: our station sends SHB, port 2001,
lifetime `0x05`, same as both bench stations. It was `0x83` in the August captures.
- [x] Real-station CAMs/DENMs/SPATEM still reach the app (logcat: `handleCamUper`,
`handleDenmUper`, `handleSpatUper` all decoding, 2026-09-14).
- [x] Our own CAMs decode on air: 397 frames from station 999999 decode with asn1tools and
re-encode byte-identically.
- [ ] Confirm the CAM Pinger card's `tx fail` / oversize / CRC counters are 0 (needs a look at the
phone; not readable from the PC).
Partial check possible with one board and no phone: flash it, `idf.py -p COMx monitor`, and look
for `OCB @ 5900 MHz - TX/RX armed`. That proves the new build boots and brings the radio up, not
that it transmits correctly.
### Measure the OBU's actual transmit power (added 2026-09-14)
Nothing in this project has ever measured it. `main.c` asks for 20 dBm
(`esp_wifi_set_max_tx_power(80)`, 0.25 dBm units) and the build's ceiling is the same
(`CONFIG_ESP_PHY_MAX_TX_POWER=20`), but a request is a ceiling, not a guarantee: the driver clamps
it to its own calibrated table, and 5900 MHz is above the range this chip is rated for, so the
table actually in use is channel 177's. The firmware now reads the value back and logs it at boot,
which records what the driver admits to, not what leaves the antenna.
- [ ] Flash and `idf.py -p COM3 monitor`, then note the `tx power:` line. A value below 80 means
the driver clamped the request, which the code alone cannot tell you.
- [ ] Relative check with the second ESP32-C5 on `its-g5-receiver-firmware`: capture at a measured
distance in a straight line, read the RSSI the receive path already reports, and record
distance and RSSI together. This gives a comparable number between builds and antennas,
which is what matters for range work, without any lab equipment.
- [ ] Only a spectrum analyser or a calibrated reference receiver gives real radiated power. Worth
it only if the range result looks wrong, or if the thesis needs an absolute figure.
For context: ETSI allows up to 33 dBm EIRP on the ITS band, and production OBUs sit around
20 to 23 dBm, so the requested figure is in the right region if the PA really keys it there.
### obu-cam-transmistter yawRateConfidence fix (added 2026-09-11)
Its `cam.c` (compiled into that firmware) wrote `yawRateConfidence` as 3 bits / 7 instead of
4 bits / unavailable(8), the bug the app fixed on 2026-08-20. Fixed in it and in obu-firmware's
reference copy; asn1tools now decodes the CAM and re-encodes it byte-identically, and it builds on
IDF 5.5.4. No board runs this firmware right now (the production OBU runs obu-firmware), so this
only matters if it is flashed again:
IDF 5.5.4. Since 2026-09-14 the spare board on COM10 runs it as a bench beacon:
- [ ] After flashing it: capture, run `pcap_gn_tally.py`, and decode the CAM payload with
asn1tools (`py -3.11`, modules in `asn1/`).
- [x] Done 2026-09-14: flashed on COM10 and captured on COM8. All 72 CAMs from station
195936478 (0x0BADC0DE) decode with asn1tools and re-encode byte-identically, so the
4-bit yawRateConfidence is right on air. COM10 now runs this beacon rather than
obu-firmware - reflash it if the spare is needed as an OBU again.
### Signed-message reception and exact payloads (added 2026-09-11)
@@ -434,69 +50,21 @@ obu-firmware's `gn_unwrap.c` now unwraps TS 103 097 signed packets (signature no
reported as V2X_RX flags bit1) and cuts every message to the length its header declares, dropping
the 8 bytes the chip's RX appends to each frame, which were forwarded to the phone until now.
Verified on the host (`obu-firmware/test/host`: chain, replay of all recordings against asn1tools,
50M-iteration fuzz) and built on IDF 6.1, but not flashed: the production OBU still runs the
2026-09-10 build. Needs the OBU with this build, the phone, and signed traffic - real vehicles or
50M-iteration fuzz) and flashed to the production OBU on 2026-09-14. The remaining gap is signed
traffic to receive: real vehicles or
RSUs, since the bench CiT One sends unsigned. A second ESP32 running the receiver firmware is
optional, but shows what was on air at the time.
- [ ] Flash obu-firmware (this also carries the GN lifetime fix above).
- [x] Flash obu-firmware (done 2026-09-14, COM3).
- [x] Unsigned bench traffic still decodes in the app, with messages now cut to their declared
length (CAM, DENM and SPATEM all decoding in logcat after the flash).
- [ ] Near signed traffic: signed CAMs/DENMs appear in the app, and a simultaneous capture shows
them on air (`pcap_gn_tally.py` lists them as `secured`).
- [ ] Unsigned bench traffic still decodes in the app as before (messages now arrive 8 bytes
shorter).
- [ ] The heartbeat's oversize counter still counts over-long messages (e.g. road SPATEMs).
### CiT One custom CAM injection over `v2x/tx/v2/cam` (added 2026-09-14)
The haw-002 unit now runs the special firmware: Cohda's own CAM transmission disabled, and a
V2X-Gateway build that accepts a `SendV2XMessage` (schemas.consider-innovation.de/its-s/
v2x_interface.proto) carrying a UPER CAM on `v2x/tx/v2/cam`. `tools/cit_one_cam_tx.py` builds
and publishes those from a PC; its `--self-test` passes offline, proving only that the bytes
match `CamEncodeGoldenTest.kt` and that the protobuf wrapper round-trips. Nothing about what
the OBU does with them is established.
Reach the broker over Wi-Fi or Ethernet for now - the USB-peripheral-mode link needs the phone
to be USB host on a `172.25.1.0/24` interface with no DHCP server, which Android cannot
configure from inside an app.
Needs: the CiT One haw-002 on the same network as a PC, and a second ESP32-C5 running
`its-g5-receiver-firmware` sniffing G5CC (`-c 5900`) to capture with.
Bench run 2026-09-14, PC -> haw-002 (192.168.3.201), captured on the RSU (192.168.3.202,
**not** .2.202 - that address does not route). `tools/cit_one_rx_watch.py` decodes what a unit
hears. Result: the injection path works end to end, with one blocker found.
- [x] Publishes without the broker refusing the topic. 1.00 Hz, confirmed by subscribing to
`v2x/tx/v2/cam` on the OBU itself.
- [x] The RSU hears our CAMs on air, 1.00 Hz, matching what we publish.
- [x] `ItsPduHeader` **is** expected in the payload - we send it included and it decodes.
- [x] BTP destination port 2001. GN source address `08:00:26:93:92:01:91:dc`, the OBU's.
- [x] **Our CAM content goes out intact**: position, speed (417), heading (639), width (7) and
length (18) arrive byte-exact. The gateway does not touch the content.
- [x] **The gateway overwrites `stationID`** with the OBU's own (999999 -> 4033890855, which
matches `own_info.stationID` on `v2x/rx/obu_gnss`). This is what the "OBU owns identity"
decision wants, so `--follow-obu-identity` is not needed on this unit.
- [x] ~~BLOCKER: Cohda's own CAM is still transmitting.~~ Fixed 2026-09-14 by disabling CAM in
a second conf file: the RSU now hears only our stream, 0 CAMs with the stack's
unavailable dimensions over 30 s. Note the stack restart gave the unit a new identity
(stationID 4033890855 -> 2553426533, GN source `08:00:26:...` -> `08:00:a2:...`), which is
expected under `ItsGnLocalAddrConfMethod = 2` (anonymous, random at boot).
- [x] Re-checked: 41 published / 41 heard over 40 s, 1.02 Hz both ends, inter-arrival a steady
1.0 s. 100% delivery, no gateway rate limiting. An earlier 0.40 Hz sample was the stack
still settling after the restart and did not persist.
Two topics the v6 API does not document, found by subscribing to `#` on haw-002:
- `v2x/loopback/cam` - a `RecvV2XMessage` (btpHeader.type=2) carrying each CAM the unit
transmits, 1:1 with what we publish and **after** the gateway's stationID rewrite. This is the
TX confirmation we were going to ask consider it for: it makes "did my CAM go out, and under
which identity" answerable on the transmitting unit alone, without an RSU or a second ESP32.
- `v2x/rx/obuinfo` at 10 Hz - the protobuf `OwnStationInfo` (binary twin of `obu_gnss`;
field 2 decodes to the same stationID, field 10 to the same heading). Output only, so it is
not the content-feed input we speculated about.
- [ ] Wire `v2x/loopback/cam` into `cit_one_rx_watch.py` as a local TX check.
- [ ] Sanity-check the rate: `--rate 4` should produce 4 CAMs/s on air, since `ItsDCCEnabled = 0`
on this unit.
them on air (`pcap_gn_tally.py` lists them as `secured`). NOT possible at this bench: the
CiT One transmits unsigned (`ItsGnSecurity = 0`) and nothing else here signs. Needs a drive
past real RSUs, the CiT One switched to signed mode if its API allows, or a replay firmware
on a spare board that re-transmits the recorded signed frames.
- [ ] The heartbeat's oversize counter still counts over-long messages. Not exercised at the
bench: the SPATEMs here are ~340 bytes on air, far below the cap.
## Set up host testing
@@ -533,6 +101,19 @@ Suggested order after the host tests exist:
Dropped: building vanetza as a GN/BTP oracle. Real captures (`pcap_gn_tally.py`), the host
round-trip test and `asn1tools` for UPER cover what it would have checked.
## Follow-ups found 2026-09-14
- [x] **Capture tooling moved into this repo** (`capture/`), with the CR-insertion fix. The
sniffer's console inserts a CR before every LF, which also hits every 0x0a byte of the binary
pcap stream, shifting pcap record headers and frames. A 787 KB capture parsed cleanly for
only 82 of ~2000 records, and DENMs showed up on nonsense BTP ports. `undo_crlf()` reverses
it on the raw stream before framing; afterwards a capture parsed to EOF and DENMs read as
port 2002. **Every capture taken before 2026-09-14 is truncated at its first corrupted
record** - re-measure anything derived from them.
- [ ] `capture/dump_pcap.py` reads the same console and still needs the same treatment.
- [ ] **Do not open COM3's console while the phone is attached.** Opening it toggles DTR/RTS on the
CH343 and resets the OBU, which drops the phone's USB link and needs a manual Connect.
## Follow-ups found 2026-09-11
- [ ] **App: show the signed flag.** `V2xRxFrame.parse` in `SerialFrame.kt` only reads bit0 of
+1 -17
View File
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Networking (MQTT / tile downloads) -->
<uses-permission android:name="android.permission.INTERNET" />
@@ -11,15 +10,6 @@
<!-- Location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- BLE link to the ESP32-C5 (BleLinkTransport). Android 12+ asks for scan/connect at runtime;
older versions use the legacy pair plus location, which is requested anyway. -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation"
tools:targetApi="s" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Phase A: foreground service (trip recording) -->
@@ -72,12 +62,6 @@
android:foregroundServiceType="location"
android:exported="false" />
<!-- Developer V2X data logger: keeps the process and GNSS alive while a log records. -->
<service
android:name=".service.V2xLogService"
android:foregroundServiceType="location"
android:exported="false" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
Binary file not shown.
@@ -26,12 +26,10 @@ import androidx.core.view.WindowCompat
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.ui.components.StatusTopBar
import com.hawhamburg.micr0bu.ui.navigation.BottomNavBar
@@ -42,7 +40,6 @@ import com.hawhamburg.micr0bu.ui.screens.MqttTopicViewerScreen
import com.hawhamburg.micr0bu.ui.screens.RecordingScreen
import com.hawhamburg.micr0bu.ui.screens.SensorScreen
import com.hawhamburg.micr0bu.ui.screens.SessionLogScreen
import com.hawhamburg.micr0bu.ui.screens.V2xMapScreen
import com.hawhamburg.micr0bu.ui.screens.MapScreen
import com.hawhamburg.micr0bu.ui.screens.TripHistoryScreen
import com.hawhamburg.micr0bu.ui.screens.TripReviewScreen
@@ -56,12 +53,10 @@ import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UnitsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.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.SensorViewModel
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
@@ -70,7 +65,6 @@ class MainActivity : AppCompatActivity() {
private val viewModel: SensorViewModel by viewModels()
private val mqttViewModel: MqttViewModel by viewModels()
private val tripViewModel: TripRecordingViewModel by viewModels()
private val logViewModel: V2xLogViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
@@ -92,20 +86,13 @@ class MainActivity : AppCompatActivity() {
val showBatteryOptPrompt by tripViewModel.showBatteryOptPrompt.collectAsState()
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 esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
val usbSerialState by mqttViewModel.usbSerialState.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()
MicrOBUTheme(darkTheme = state.darkTheme) {
val view = LocalView.current
@@ -117,13 +104,6 @@ class MainActivity : AppCompatActivity() {
}
val navController = rememberNavController()
// The V2X live map is a full-bleed destination: the app's own chrome would eat a
// third of the display on the one screen whose entire job is showing where things
// are relative to each other. It carries its own floating back button, and system
// back still works, so nothing becomes unreachable.
val currentBackStackEntry by navController.currentBackStackEntryAsState()
val isFullBleed = currentBackStackEntry?.destination?.route == Screen.V2xMap.route
val locationLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
@@ -139,17 +119,11 @@ class MainActivity : AppCompatActivity() {
LaunchedEffect(Unit) {
viewModel.startImuStreams()
// Bluetooth scan/connect ride along with location (Android 12+): the ESP32-C5
// can be reached over BLE, and a denial only matters if that is selected, where
// BleLinkTransport then says so instead of silently finding nothing.
val bluetooth = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
} else emptyArray()
locationLauncher.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
) + bluetooth
)
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
@@ -158,19 +132,14 @@ class MainActivity : AppCompatActivity() {
Scaffold(
topBar = {
if (!isFullBleed) {
StatusTopBar(
state = state,
mqttConnectionState = mqttConnectionState,
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,
)
}
StatusTopBar(
state = state,
mqttConnectionState = mqttConnectionState,
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
usbSerialState = usbSerialState,
)
},
bottomBar = { if (!isFullBleed) BottomNavBar(navController) },
bottomBar = { BottomNavBar(navController) },
) { innerPadding ->
NavHost(
navController = navController,
@@ -183,13 +152,12 @@ class MainActivity : AppCompatActivity() {
mqttConnectionState = mqttConnectionState,
activeTransport = activeTransport,
obuHardware = obuHardware,
esp32LinkState = esp32LinkState,
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
usbSerialState = usbSerialState,
usbCableConnected = usbConnected,
obuStationTypeWarning = obuStationTypeWarning,
obuStationType = obuStationType,
hazards = denmEvents,
signals = trafficLights,
signals = spatIntersections,
ownPosition = ownCamPosition,
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
onNavigateToSensors = {
@@ -223,7 +191,7 @@ class MainActivity : AppCompatActivity() {
state = state,
mqttConnectionState = mqttConnectionState,
obuConnected = if (obuHardware == ObuHardware.ESP32_C5)
esp32LinkState == Esp32LinkState.CONNECTED
usbSerialState == UsbSerialState.CONNECTED
else
mqttConnectionState == MqttConnectionState.CONNECTED,
tripServiceState = tripServiceState,
@@ -285,19 +253,7 @@ class MainActivity : AppCompatActivity() {
}
composable(Screen.MqttViewer.route) {
MqttTopicViewerScreen(
viewModel = mqttViewModel,
onOpenMap = { navController.navigate(Screen.V2xMap.route) },
)
}
composable(Screen.V2xMap.route) {
// Activity-scoped instance, like Connection below: a hiltViewModel()
// here would be scoped to this NavBackStackEntry and torn down on the
// way back out, taking the shared transport with it.
V2xMapScreen(
viewModel = mqttViewModel,
onBack = { navController.popBackStack() },
)
MqttTopicViewerScreen(viewModel = mqttViewModel)
}
composable(Screen.Settings.route) {
SettingsScreen(
@@ -325,14 +281,6 @@ class MainActivity : AppCompatActivity() {
onMqttPrefsChange = mqttViewModel::updatePrefs,
obuHardware = obuHardware,
onObuHardwareChange = mqttViewModel::setObuHardware,
esp32Transport = esp32Transport,
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
outgoingMessage = outgoingMessage,
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
esp32RxPath = esp32RxPath,
onEsp32RxPathChange = mqttViewModel::setEsp32RxPath,
signOutgoing = signOutgoing,
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
onBack = { navController.popBackStack() },
)
}
@@ -376,21 +324,9 @@ class MainActivity : AppCompatActivity() {
state = state,
onDeveloperMode = viewModel::setDeveloperMode,
onOpenSensorMonitor = { navController.navigate(Screen.Sensors.route) },
onOpenV2xLogger = { navController.navigate(Screen.SettingsV2xLog.route) },
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsV2xLog.route) {
V2xLogSettingsScreen(
state = v2xLogState,
files = v2xLogFiles,
obuHardware = obuHardware,
onStart = logViewModel::start,
onStop = logViewModel::stop,
onDelete = logViewModel::delete,
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsAbout.route) {
AboutSettingsScreen(onBack = { navController.popBackStack() })
}
@@ -21,13 +21,7 @@ import java.time.DateTimeException
* [SystemClock.currentGnssTimeClock] (API 29, this app's minSdk) is a UTC clock the platform keeps
* synchronised from GNSS fixes. One reading of it taken alongside the wall clock gives the wall
* clock's error, which is then applied to the fix's own timestamp. When GNSS time is unavailable,
* the last error measured is kept, because the wall clock's error changes slowly while GNSS time
* comes and goes indoors. Only before any GNSS time since the app started is the wall clock used
* unchanged.
*
* Keeping it matters: with the bench phone 14 minutes fast (2026-09-23), dropping back to the raw
* wall clock whenever GNSS time blinked out made every transmitted timestamp jump 14 minutes back
* and forth, and the micrOBU restarted its stack at each jump back (time_regression).
* typically indoors before any satellite fix since boot, the wall clock is used unchanged.
*
* Which clock is in use is logged whenever it changes, with the measured error, so a capture shows
* where a given run's timestamps came from.
@@ -42,9 +36,6 @@ object GnssTimeSource {
/** Whether the last correction used GNSS time; null before the first. For change-only logging. */
@Volatile private var lastUsedGnss: Boolean? = null
/** GNSS time minus wall clock at the last reading of both; null until GNSS time was first seen. */
@Volatile private var lastErrorMs: Long? = null
/** [systemMs], a wall-clock reading, moved onto GNSS time where GNSS time is available. */
fun correct(systemMs: Long): Long {
val systemNow = System.currentTimeMillis()
@@ -53,23 +44,8 @@ object GnssTimeSource {
} catch (e: DateTimeException) {
null
}
if (gnssNow != null) lastErrorMs = gnssNow - systemNow
noteSource(gnssNow, systemNow)
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)
return ItsTime.onGnssTime(systemMs, gnssNow, systemNow)
}
private fun noteSource(gnssNow: Long?, systemNow: Long) {
@@ -79,9 +55,6 @@ object GnssTimeSource {
if (gnssNow != null) {
Log.i(TAG, "transmit timestamps now on GNSS time; phone clock is " +
"${"%+.1f".format((systemNow - gnssNow) / 1000.0)} s off")
} else if (lastErrorMs != null) {
Log.i(TAG, "GNSS time unavailable, keeping the last measured phone clock error of " +
"${"%+.1f".format(-lastErrorMs!! / 1000.0)} s")
} else {
Log.w(TAG, "GNSS time unavailable, transmit timestamps fall back to the phone clock, " +
"which has no automatic time source without a SIM or internet")
@@ -6,7 +6,6 @@ import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Location
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
@@ -16,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,
@@ -52,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) {
@@ -64,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): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
fun accelerometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_ACCELEROMETER)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs)
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): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
fun barometerFlow(): Flow<Float> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
if (sensor == null) {
@@ -122,10 +77,7 @@ class SensorRepository(private val context: Context) {
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
private fun sensorFlow(
type: Int,
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
): Flow<ImuReading> = callbackFlow {
private fun sensorFlow(type: Int): Flow<ImuReading> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(type)
if (sensor == null) {
close()
@@ -133,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)
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
)
@@ -9,7 +9,6 @@ import com.hawhamburg.micr0bu.data.mqtt.MqttRepository
import com.hawhamburg.micr0bu.data.mqtt.ObuHardwarePreferences
import com.hawhamburg.micr0bu.data.mqtt.RAW_CAM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_DENM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_MAPEM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_SPATEM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RecvV2xMessage
import com.hawhamburg.micr0bu.data.mqtt.UseCaseAlertPreferences
@@ -17,11 +16,10 @@ import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.BtpPort
import com.hawhamburg.micr0bu.data.transport.SerialFrameType
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.data.transport.UsbSerialTransport
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,7 +28,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.MapEvent
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
@@ -105,7 +102,7 @@ private const val RAW_PREFERRED_WINDOW_MS = 5_000L
class CamUseCaseRepository @Inject constructor(
private val mqttRepository: MqttRepository,
private val prefs: UseCaseAlertPreferences,
private val esp32Link: Esp32Link,
private val usbSerialTransport: UsbSerialTransport,
private val camCodec: RealAsn1UperCodec,
private val obuHardwarePrefs: ObuHardwarePreferences,
private val pseudonymManager: PseudonymManager,
@@ -199,17 +196,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 _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
/**
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
@@ -255,7 +241,6 @@ 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")
else -> Log.w(TAG, "rawV2x: unexpected topic ${raw.topic}")
}
}
@@ -300,15 +285,14 @@ class CamUseCaseRepository @Inject constructor(
// this only ever sees CAM UPER bytes. No-op stream on the CiT One path (the transport
// just never emits CAM_RX frames if nothing's plugged in over serial).
scope.launch {
esp32Link.incomingFrames.collect { frame ->
usbSerialTransport.incomingFrames.collect { frame ->
if (frame.type != SerialFrameType.V2X_RX) return@collect
if (esp32Link.state.value != Esp32LinkState.CONNECTED) return@collect
if (usbSerialTransport.state.value != UsbSerialState.CONNECTED) return@collect
val v2x = V2xRxFrame.parse(frame.payload) ?: return@collect
when (v2x.btpPort) {
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")
@@ -320,10 +304,10 @@ class CamUseCaseRepository @Inject constructor(
// last-seen positions and their alerts linger on the map and in the use-case panel after
// an unplug, which reads as live traffic - the worst kind of stale on a safety display.
scope.launch {
esp32Link.state.collect { state ->
usbSerialTransport.state.collect { state ->
// ESP32-only: on the CiT One path this transport is permanently DISCONNECTED and
// resetting here would wipe perfectly good MQTT-derived state.
if (currentHardware == ObuHardware.ESP32_C5 && state != Esp32LinkState.CONNECTED) {
if (currentHardware == ObuHardware.ESP32_C5 && state != UsbSerialState.CONNECTED) {
engine.reset()
_rsuStations.value = emptyMap()
}
@@ -582,19 +566,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
@@ -1,235 +0,0 @@
package com.hawhamburg.micr0bu.data.log
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteStatement
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import java.io.File
/** One GNSS fix, as stored next to a logged message. Phone and OBU fixes share this shape. */
data class LogGnss(
val latitude: Double,
val longitude: Double,
val altitudeM: Double? = null,
val speedMps: Double? = null,
val headingDeg: Double? = null,
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,
)
/** One received V2X message, ready to be written. */
class LogMessage(
val tsMs: Long,
/** `esp32` or `cit_one`: which link delivered it. */
val source: String,
/** `raw` (UPER bytes in [payload]) or `processed` (the Use Case app's JSON in [payloadText]). */
val channel: String,
val kind: ItsMessageKind,
val messageId: Int?,
val btpPort: Int?,
val stationId: Long?,
val isOwn: Boolean?,
val rssiDbm: Int?,
val geoRadiusM: Int?,
val senderLat: Double?,
val senderLon: Double?,
val senderSpeedMps: Double?,
val senderHeadingDeg: Double?,
val summary: String?,
val payload: ByteArray?,
val payloadText: String?,
val phone: LogGnss?,
val obu: LogGnss?,
)
/** 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)
/**
* 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
* needs no migration path or app-side entity classes. The app never reads one back.
*
* Not thread-safe; [V2xLogger] drives it from one writer coroutine. Each [writeBatch] is one
* transaction on the default rollback journal, so a killed process leaves a file that is
* complete up to the last batch, and a single file with no `-wal` sidecar to forget when sharing.
*
* 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.
*/
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
init {
db.execSQL(
"""
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts_ms INTEGER NOT NULL,
source TEXT NOT NULL,
channel TEXT NOT NULL,
msg_type TEXT NOT NULL,
message_id INTEGER,
btp_port INTEGER,
station_id INTEGER,
is_own INTEGER,
rssi_dbm INTEGER,
geo_radius_m INTEGER,
sender_lat REAL,
sender_lon REAL,
sender_speed_mps REAL,
sender_heading_deg REAL,
summary TEXT,
payload BLOB,
payload_text TEXT,
phone_lat REAL,
phone_lon REAL,
phone_alt_m REAL,
phone_speed_mps REAL,
phone_heading_deg REAL,
phone_accuracy_m REAL,
phone_fix_ms INTEGER,
obu_lat REAL,
obu_lon REAL,
obu_alt_m REAL,
obu_speed_mps REAL,
obu_heading_deg REAL,
obu_fix_ms INTEGER
)
""".trimIndent()
)
db.execSQL("CREATE INDEX idx_messages_ts ON messages(ts_ms)")
db.execSQL("CREATE INDEX idx_messages_type ON messages(msg_type)")
db.execSQL(
"""
CREATE TABLE gnss (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts_ms INTEGER NOT NULL,
source TEXT NOT NULL,
lat REAL NOT NULL,
lon REAL NOT NULL,
alt_m REAL,
speed_mps REAL,
heading_deg REAL,
accuracy_m REAL,
fix_ms INTEGER NOT NULL
)
""".trimIndent()
)
db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)")
// Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI.
db.execSQL(
"CREATE VIEW messages_v AS SELECT *, " +
"strftime('%Y-%m-%d %H:%M:%f', ts_ms / 1000.0, 'unixepoch') AS ts_utc FROM messages"
)
db.execSQL("PRAGMA user_version = $SCHEMA_VERSION")
for ((k, v) in meta) setMeta(k, v)
setMeta("schema_version", SCHEMA_VERSION.toString())
insertMessage = db.compileStatement(
"INSERT INTO messages (ts_ms, source, channel, msg_type, message_id, btp_port, station_id, " +
"is_own, rssi_dbm, geo_radius_m, sender_lat, sender_lon, sender_speed_mps, " +
"sender_heading_deg, summary, payload, payload_text, " +
"phone_lat, phone_lon, phone_alt_m, phone_speed_mps, phone_heading_deg, " +
"phone_accuracy_m, phone_fix_ms, obu_lat, obu_lon, obu_alt_m, obu_speed_mps, " +
"obu_heading_deg, obu_fix_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertGnss = db.compileStatement(
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms) " +
"VALUES (?,?,?,?,?,?,?,?,?)"
)
}
fun setMeta(key: String, value: String) {
db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value))
}
/** Writes [messages] and [gnss] in one transaction. */
fun writeBatch(messages: List<LogMessage>, gnss: List<LogGnssSample>) {
if (messages.isEmpty() && gnss.isEmpty()) return
db.beginTransaction()
try {
for (m in messages) bindAndRun(m)
for (g in gnss) bindAndRun(g)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
}
fun close() {
runCatching { insertMessage.close() }
runCatching { insertGnss.close() }
runCatching { db.close() }
}
private fun bindAndRun(m: LogMessage) {
val s = insertMessage
s.clearBindings()
s.bind(1, m.tsMs)
s.bind(2, m.source)
s.bind(3, m.channel)
s.bind(4, m.kind.label)
s.bind(5, m.messageId?.toLong())
s.bind(6, m.btpPort?.toLong())
s.bind(7, m.stationId)
s.bind(8, m.isOwn?.let { if (it) 1L else 0L })
s.bind(9, m.rssiDbm?.toLong())
s.bind(10, m.geoRadiusM?.toLong())
s.bind(11, m.senderLat)
s.bind(12, m.senderLon)
s.bind(13, m.senderSpeedMps)
s.bind(14, m.senderHeadingDeg)
s.bind(15, m.summary)
s.bind(16, m.payload)
s.bind(17, m.payloadText)
s.bind(18, m.phone?.latitude)
s.bind(19, m.phone?.longitude)
s.bind(20, m.phone?.altitudeM)
s.bind(21, m.phone?.speedMps)
s.bind(22, m.phone?.headingDeg)
s.bind(23, m.phone?.accuracyM)
s.bind(24, m.phone?.fixMs)
s.bind(25, m.obu?.latitude)
s.bind(26, m.obu?.longitude)
s.bind(27, m.obu?.altitudeM)
s.bind(28, m.obu?.speedMps)
s.bind(29, m.obu?.headingDeg)
s.bind(30, m.obu?.fixMs)
s.executeInsert()
}
private fun bindAndRun(g: LogGnssSample) {
val s = insertGnss
s.clearBindings()
s.bind(1, g.tsMs)
s.bind(2, g.source)
s.bind(3, g.fix.latitude)
s.bind(4, g.fix.longitude)
s.bind(5, g.fix.altitudeM)
s.bind(6, g.fix.speedMps)
s.bind(7, g.fix.headingDeg)
s.bind(8, g.fix.accuracyM)
s.bind(9, g.fix.fixMs)
s.executeInsert()
}
// clearBindings() leaves every parameter NULL, so a null value is simply not bound.
private fun SQLiteStatement.bind(i: Int, v: Long?) { if (v != null) bindLong(i, v) }
private fun SQLiteStatement.bind(i: Int, v: Double?) { if (v != null) bindDouble(i, v) }
private fun SQLiteStatement.bind(i: Int, v: String?) { if (v != null) bindString(i, v) }
private fun SQLiteStatement.bind(i: Int, v: ByteArray?) { if (v != null) bindBlob(i, v) }
companion object {
const val SCHEMA_VERSION = 1
}
}
@@ -1,424 +0,0 @@
package com.hawhamburg.micr0bu.data.log
import android.content.Context
import android.os.Build
import android.util.Log
import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.SensorRepository
import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository
import com.hawhamburg.micr0bu.data.mqtt.MessageDirection
import com.hawhamburg.micr0bu.data.mqtt.MqttRepository
import com.hawhamburg.micr0bu.data.mqtt.RAW_CAM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_DENM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_MAPEM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RAW_SPATEM_TOPIC
import com.hawhamburg.micr0bu.data.mqtt.RecvV2xMessage
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.ObuHardware
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.log.ItsMessageKind
import com.hawhamburg.micr0bu.domain.log.classifyItsPdu
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
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.withTimeoutOrNull
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "V2xLogger"
private const val LOG_DIR = "v2x_logs"
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"
private const val SOURCE_PHONE = "phone"
private const val SOURCE_OBU = "obu"
/** How long the writer collects rows before it commits them. */
private const val FLUSH_INTERVAL_MS = 250L
/** What the logging screen shows about the log in progress. */
data class V2xLogState(
val active: Boolean = false,
val fileName: String? = null,
val startedMs: Long = 0L,
/** Rows written so far, by kind. Kinds never heard are absent. */
val counts: Map<ItsMessageKind, Int> = emptyMap(),
val total: Int = 0,
val fileBytes: Long = 0L,
/** 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,
/** Set when the file could not be created or written. */
val error: String? = null,
)
/** A log file on the device. */
data class V2xLogFile(val file: File, val sizeBytes: Long, val modifiedMs: Long, val active: Boolean) {
val name: String get() = file.name
}
/**
* Developer-tool logger: records every V2X message the phone receives, with a timestamp, the
* phone's GNSS fix, the OBU's GNSS fix where there is one, and RSSI where the hardware reports it,
* into one SQLite file per run (see [V2xLogWriter] for the schema).
*
* Works on both hardware paths and listens to whichever is selected:
* - **ESP32-C5**: the V2X_RX frames from [Esp32Link], with the firmware's RSSI. No OBU position,
* since that board has no GNSS.
* - **CiT One**: the raw `v2x/rx` protobuf topics over MQTT, and the Use Case app's processed
* `v2x-uca/output/json` topics as a second channel (the only source of MAPEM when the OBU does
* 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
* 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.
*
* 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.
*
* 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.
*/
@Singleton
class V2xLogger @Inject constructor(
@ApplicationContext private val context: Context,
private val mqttRepository: MqttRepository,
private val esp32Link: Esp32Link,
private val camUseCaseRepository: CamUseCaseRepository,
private val camCodec: RealAsn1UperCodec,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _state = MutableStateFlow(V2xLogState())
val state: StateFlow<V2xLogState> = _state.asStateFlow()
private val _files = MutableStateFlow<List<V2xLogFile>>(emptyList())
/** Logs on the device, newest first. Call [refreshFiles] after anything that changes the folder. */
val files: StateFlow<List<V2xLogFile>> = _files.asStateFlow()
private val logDir: File get() = File(context.filesDir, LOG_DIR).apply { mkdirs() }
private var session: Job? = null
private var rows = Channel<Any>(Channel.UNLIMITED)
@Volatile private var phoneFix: LogGnss? = null
@Volatile private var obuFix: LogGnss? = null
fun start() {
if (session?.isActive == true) return
val startedMs = System.currentTimeMillis()
val hardware = mqttRepository.obuHardware.value
val file = File(logDir, fileNameFor(startedMs, hardware))
val writer = try {
V2xLogWriter(file, metaFor(startedMs, hardware))
} catch (e: Exception) {
Log.e(TAG, "cannot create ${file.name}", e)
file.delete()
_state.value = V2xLogState(error = e.message ?: e.javaClass.simpleName)
return
}
phoneFix = null
obuFix = null
rows = Channel(Channel.UNLIMITED)
_state.value = V2xLogState(active = true, fileName = file.name, startedMs = startedMs)
refreshFiles()
session = scope.launch {
val sources = listOf(
launch { collectEsp32() },
launch { collectCitOneRaw() },
launch { collectCitOneMessages() },
launch { collectPhoneGnss() },
)
try {
runWriter(writer, file)
} finally {
sources.forEach { it.cancel() }
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
writer.close()
}
}
}
/** Stops the log and waits for the last rows to reach the file. */
suspend fun stop() {
val running = session ?: return
// Closing the channel lets the writer drain everything already queued before it ends.
rows.close()
withTimeoutOrNull(5_000L) { running.join() } ?: running.cancelAndJoin()
session = null
_state.update { it.copy(active = false) }
refreshFiles()
}
fun delete(log: V2xLogFile): Boolean {
if (log.active) return false
val ok = log.file.delete()
refreshFiles()
return ok
}
fun refreshFiles() {
val activeName = _state.value.fileName.takeIf { _state.value.active }
_files.value = logDir.listFiles { f -> f.isFile && f.extension == "db" }
.orEmpty()
.map { V2xLogFile(it, it.length(), it.lastModified(), it.name == activeName) }
.sortedByDescending { it.modifiedMs }
}
// ── Sources ───────────────────────────────────────────────────────────────
private suspend fun collectEsp32() {
esp32Link.incomingFrames.collect { frame ->
if (frame.type != SerialFrameType.V2X_RX) return@collect
if (mqttRepository.obuHardware.value != ObuHardware.ESP32_C5) return@collect
if (esp32Link.state.value != Esp32LinkState.CONNECTED) return@collect
val v2x = V2xRxFrame.parse(frame.payload) ?: return@collect
enqueueRaw(
source = SOURCE_ESP32, uper = v2x.uper, btpPort = v2x.btpPort,
rssiDbm = v2x.rssiDbm, geoRadiusM = v2x.geoArea?.radiusMeters,
)
}
}
private suspend fun collectCitOneRaw() {
mqttRepository.rawV2x.collect { raw ->
if (mqttRepository.obuHardware.value != ObuHardware.CIT_ONE) return@collect
val envelope = RecvV2xMessage.parse(raw.bytes)
if (envelope == null) {
Log.w(TAG, "unparseable RecvV2XMessage on ${raw.topic}, ${raw.bytes.size} bytes")
return@collect
}
enqueueRaw(
source = SOURCE_CIT_ONE, uper = envelope.payload,
// The envelope's own port when it has one; the topic says the same thing otherwise.
btpPort = envelope.destinationPort ?: portOfRawTopic(raw.topic),
rssiDbm = null, geoRadiusM = envelope.destAreaRadiusM,
tsMs = raw.timestamp,
)
}
}
private suspend fun collectCitOneMessages() {
mqttRepository.messages.collect { msg ->
if (msg.direction != MessageDirection.RX) return@collect
if (mqttRepository.obuHardware.value != ObuHardware.CIT_ONE) return@collect
if (msg.topic == OBU_GNSS_TOPIC) {
val ego = ObuGnssParser.parseEgo(msg.payload, timestamp = msg.timestamp) ?: return@collect
val fix = LogGnss(
latitude = ego.latitude, longitude = ego.longitude,
speedMps = ego.speedMps, headingDeg = ego.headingDeg, fixMs = msg.timestamp,
)
obuFix = fix
rows.trySend(LogGnssSample(msg.timestamp, SOURCE_OBU, fix))
return@collect
}
if (!msg.topic.startsWith(PROCESSED_PREFIX)) return@collect
val kind = ItsMessageKind.fromProcessedTopicName(msg.topic.removePrefix(PROCESSED_PREFIX))
?: return@collect
rows.trySend(
LogMessage(
tsMs = msg.timestamp, source = SOURCE_CIT_ONE, channel = "processed", kind = kind,
messageId = null, btpPort = null, stationId = null, isOwn = null, rssiDbm = null,
geoRadiusM = null, senderLat = null, senderLon = null, senderSpeedMps = null,
senderHeadingDeg = null, summary = null, payload = null, payloadText = msg.payload,
phone = phoneFix, obu = obuFix,
)
)
}
}
/**
* Phone GNSS, re-subscribed in a loop for the same reason [CamUseCaseRepository] does: a log
* can be started before the location permission is granted, and a single attempt would then
* leave every row without a phone position for the whole run.
*/
private suspend fun collectPhoneGnss() {
val sensors = SensorRepository(context)
while (true) {
runCatching {
sensors.gnssFlow().collect { reading ->
val fix = reading.toLogGnss()
phoneFix = fix
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE, fix))
}
}
delay(5_000L)
}
}
// ── Rows ──────────────────────────────────────────────────────────────────
private fun enqueueRaw(
source: String,
uper: ByteArray,
btpPort: Int?,
rssiDbm: Int?,
geoRadiusM: Int?,
tsMs: Long = System.currentTimeMillis(),
) {
val cls = classifyItsPdu(uper, btpPort)
val decoded = decode(cls.kind, uper, rssiDbm, geoRadiusM, tsMs)
rows.trySend(
LogMessage(
tsMs = tsMs, source = source, channel = "raw", kind = cls.kind,
messageId = cls.messageId, btpPort = btpPort, stationId = cls.stationId,
isOwn = cls.stationId?.let { camUseCaseRepository.isOwnStationId(it) },
rssiDbm = rssiDbm, geoRadiusM = geoRadiusM,
senderLat = decoded.lat, senderLon = decoded.lon,
senderSpeedMps = decoded.speedMps, senderHeadingDeg = decoded.headingDeg,
summary = decoded.summary, payload = uper, payloadText = null,
phone = phoneFix, obu = obuFix,
)
)
}
private class Decoded(
val lat: Double? = null, val lon: Double? = null,
val speedMps: Double? = null, val headingDeg: Double? = null,
val summary: String? = null,
)
/** Decoded convenience fields for the kinds the app can decode. A failure just leaves them NULL. */
private fun decode(kind: ItsMessageKind, uper: ByteArray, rssiDbm: Int?, geoRadiusM: Int?, tsMs: Long): Decoded =
runCatching {
when (kind) {
ItsMessageKind.CAM -> camCodec.decodeCam(uper, tsMs)?.let {
Decoded(it.latitude, it.longitude, it.speedMps, it.headingDeg, "stationType=${it.stationType}")
}
ItsMessageKind.DENM -> DenmUperCodec.decode(uper, tsMs, rssiDbm, geoRadiusM)?.let {
Decoded(
it.latitude, it.longitude,
summary = "seq=${it.sequenceNumber} cause=${it.causeCode}/${it.subCauseCode}" +
if (it.isTermination) " termination" else "",
)
}
ItsMessageKind.SPATEM -> SpatemUperCodec.decode(uper, tsMs, rssiDbm)?.let { s ->
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()
// ── Writer ────────────────────────────────────────────────────────────────
/** Drains [rows] into [writer] in short batches, until the channel is closed and empty. */
private suspend fun runWriter(writer: V2xLogWriter, file: File) {
val counts = HashMap<ItsMessageKind, Int>()
var total = 0
var failure: String? = null
val messages = ArrayList<LogMessage>()
val gnss = ArrayList<LogGnssSample>()
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)
delay(FLUSH_INTERVAL_MS)
while (true) {
val next = rows.tryReceive().getOrNull() ?: break
add(next, messages, gnss)
}
try {
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)
failure = e.message ?: e.javaClass.simpleName
rows.close()
break
}
for (m in messages) counts.merge(m.kind, 1, Int::plus)
total += messages.size
messages.clear(); gnss.clear()
val now = System.currentTimeMillis()
_state.update {
it.copy(
counts = counts.toMap(), total = total, fileBytes = file.length(),
phoneFixAgeMs = phoneFix?.let { f -> now - f.fixMs },
obuFixAgeMs = obuFix?.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>) {
when (row) {
is LogMessage -> messages += row
is LogGnssSample -> gnss += row
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
private fun portOfRawTopic(topic: String): Int? = when (topic) {
RAW_CAM_TOPIC -> 2001
RAW_DENM_TOPIC -> 2002
RAW_MAPEM_TOPIC -> 2003
RAW_SPATEM_TOPIC -> 2004
else -> null
}
private fun GnssReading.toLogGnss() = LogGnss(
latitude = latitude, longitude = longitude, altitudeM = altitude,
speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(),
accuracyM = accuracyM.toDouble(), fixMs = timestamp,
)
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"
return "v2x_log_${stamp}_$mode.db"
}
private fun metaFor(startedMs: Long, hardware: ObuHardware) = mapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5.",
)
}
@@ -48,9 +48,6 @@ private val SUBSCRIBED_TOPICS = listOf(
RAW_CAM_TOPIC,
RAW_DENM_TOPIC,
RAW_SPATEM_TOPIC,
// Nothing decodes MAPEM yet; subscribed so the V2X data logger records it. An OBU product
// configuration that does not publish it simply never delivers anything here.
RAW_MAPEM_TOPIC,
// Kept subscribed as a fallback for an OBU whose product configuration does not publish the
// raw topics, and because the Use Case app is still the only source of its own alert output.
"v2x-uca/output/json/cam",
@@ -64,9 +61,8 @@ private val SUBSCRIBED_TOPICS = listOf(
const val RAW_CAM_TOPIC = "v2x/rx/cam"
const val RAW_DENM_TOPIC = "v2x/rx/denm"
const val RAW_SPATEM_TOPIC = "v2x/rx/spatem"
const val RAW_MAPEM_TOPIC = "v2x/rx/mapem"
private val RAW_V2X_TOPICS = setOf(RAW_CAM_TOPIC, RAW_DENM_TOPIC, RAW_SPATEM_TOPIC, RAW_MAPEM_TOPIC)
private val RAW_V2X_TOPICS = setOf(RAW_CAM_TOPIC, RAW_DENM_TOPIC, RAW_SPATEM_TOPIC)
/**
* A message straight off a `v2x/rx` topic, before the protobuf envelope is opened.
@@ -1,15 +1,11 @@
package com.hawhamburg.micr0bu.data.mqtt
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
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
import com.hawhamburg.micr0bu.domain.cam.Pseudonym
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
@@ -36,11 +32,6 @@ class ObuHardwarePreferences @Inject constructor(
val OWN_STATION_ID = longPreferencesKey("own_station_id")
val OWN_MAC = stringPreferencesKey("own_mac")
val OWN_PSEUDONYM_CREATED_MS = longPreferencesKey("own_pseudonym_created_ms")
// 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")
}
val obuHardwareFlow: Flow<ObuHardware> = context.obuHardwareDataStore.data.map { prefs ->
@@ -51,46 +42,6 @@ class ObuHardwarePreferences @Inject constructor(
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.OBU_HARDWARE] = hardware.id }
}
/** How the phone reaches the ESP32-C5: its native USB-C port (default) or BLE. */
val esp32TransportFlow: Flow<Esp32Transport> = context.obuHardwareDataStore.data.map { prefs ->
Esp32Transport.entries.firstOrNull { it.id == prefs[Keys.ESP32_TRANSPORT] } ?: Esp32Transport.USB
}
suspend fun setEsp32Transport(transport: Esp32Transport) {
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
}
suspend fun setOutgoingMessage(message: OutgoingMessage) {
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.OUTGOING_MESSAGE] = message.id }
}
/**
* Whether outgoing messages are signed (TS 103 097, demo PKI). Default on. Off sends them
* unsigned exactly as the previous firmware did, which verifying receivers may prefer to a
* signature they cannot chain to the EU trust list.
*/
val signOutgoingFlow: Flow<Boolean> = context.obuHardwareDataStore.data.map { prefs ->
prefs[Keys.SIGN_OUTGOING] ?: true
}
suspend fun setSignOutgoing(sign: Boolean) {
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.SIGN_OUTGOING] = sign }
}
/**
* The transmit pseudonym last saved by [savePseudonym], or null if there is none.
*
@@ -1,487 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
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
* `microbu_link/ble_transport.py`, which this follows step for step.
*
* ## The GATT layout (what the firmware actually implements)
* The station-link README describes a Nordic-UART-shaped service with fragmentation. The firmware
* does something else, and the firmware is what counts here: a custom service
* `0000C175-BA5E-4C17-8000-00805F9B34FB` with one characteristic per primitive, and each GATT value
* is one complete link message, never fragmented. Requests are written with response to the
* characteristic of their opcode ([writeTarget]); replies, STATUS and V2X_RX arrive as
* notifications. A message may be up to 512 octets, so the ATT MTU must be raised to 517 first:
* the firmware refuses to notify a message that does not fit rather than send it cut short.
*
* ## Pairing
* Every characteristic needs an encrypted, authenticated link. The firmware uses LE Secure
* Connections with a fixed passkey, [PASSKEY] (DisplayOnly). Android shows its own pairing dialog
* the first time; the user types the passkey there, and the bond is kept on both sides. The
* passkey is public, so this gives encryption but no protection against an active attacker
* during that first pairing; acceptable for the demo PKI this carries.
*
* ## RF
* BLE shares the C5's single RF front end with 5.9 GHz ITS-G5. The firmware stops advertising
* while the USB link is in use; whether an active BLE connection disturbs ITS-G5 has not been
* measured yet (TODO.md, "Waiting on hardware").
*
* Like [UsbSerialTransport], an app-scoped singleton: only an explicit disconnect or the process
* dying closes it, never a screen or ViewModel going away.
*/
@Singleton
class BleLinkTransport @Inject constructor(
@ApplicationContext private val context: Context,
) {
companion object {
const val PASSKEY = "123456"
const val NAME_PREFIX = "micrOBU"
private val SERVICE: UUID = UUID.fromString("0000c175-ba5e-4c17-8000-00805f9b34fb")
private val BTP_REQUEST: UUID = UUID.fromString("0000c176-ba5e-4c17-8000-00805f9b34fb")
private val BTP_INDICATION: UUID = UUID.fromString("0000c177-ba5e-4c17-8000-00805f9b34fb")
private val POTI: UUID = UUID.fromString("0000c178-ba5e-4c17-8000-00805f9b34fb")
/** Read-encrypted, returns nothing useful: only used to find out whether the link is secure. */
private val STATUS_CHAR: UUID = UUID.fromString("0000c179-ba5e-4c17-8000-00805f9b34fb")
private val ID_EVENT: UUID = UUID.fromString("0000c17a-ba5e-4c17-8000-00805f9b34fb")
private val CONFIG: UUID = UUID.fromString("0000c17b-ba5e-4c17-8000-00805f9b34fb")
private val RESULT: UUID = UUID.fromString("0000c17c-ba5e-4c17-8000-00805f9b34fb")
private val CCCD: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
private const val REQUESTED_MTU = 517
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
/** After failed attempts: 2, 4, 8, 16, then every 30 s, so a broken pairing does not spin. */
private const val RETRY_BASE_MS = 2_000L
private const val RETRY_MAX_MS = 30_000L
/** ATT status codes Android reports when the link lacks the encryption a characteristic needs. */
private val AUTH_FAILURES = setOf(5, 8, 15, 137)
/** Which characteristic a phone -> micrOBU message is written to, by opcode (as ble_transport.py). */
fun writeTarget(opcode: Int): UUID = when (opcode) {
LinkOpcode.BTP_DATA_REQUEST -> BTP_REQUEST
LinkOpcode.POTI_UPDATE -> POTI
0x08 /* SF_IDCHANGE_EVENT_RESPONSE */ -> ID_EVENT
else -> CONFIG
}
}
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()
/** Why the last attempt failed, or what the user has to do (e.g. type the passkey); null when fine. */
private val _detail = MutableStateFlow<String?>(null)
val detail: StateFlow<String?> = _detail.asStateFlow()
private val _incoming = MutableSharedFlow<ByteArray>(extraBufferCapacity = 256)
/** Every link message the micrOBU notifies, one GATT value each. */
val incoming: SharedFlow<ByteArray> = _incoming.asSharedFlow()
/** Name of the connected micrOBU, e.g. "micrOBU-4AF8". */
@Volatile var deviceName: String? = null
private set
@Volatile private var gatt: BluetoothGatt? = null
/** Whether the current GATT connection is up, as the last connection-state callback said. */
@Volatile private var linkUp = false
@Volatile private var wanted = false
private var sessionJob: Job? = null
/** One GATT operation at a time: Android drops a second one issued before the first completes. */
private val gattMutex = Mutex()
@Volatile private var pendingOp: CompletableDeferred<Int>? = null
@Volatile private var connected: CompletableDeferred<Boolean>? = null
@Volatile private var mtuDone: CompletableDeferred<Int>? = null
@Volatile private var servicesDone: CompletableDeferred<Boolean>? = null
fun hasPermissions(): Boolean {
val needed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
listOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
} else {
listOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
return needed.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
}
/** Scans for (or reuses the bond with) a micrOBU, pairs if needed, and opens the link. No-op if already under way. */
fun connect() {
if (sessionJob?.isActive == true) return
wanted = true
sessionJob = scope.launch {
var failures = 0
while (wanted) {
val ok = try {
session()
} catch (e: CancellationException) {
throw e // disconnect(): not a failure to report
} catch (e: Exception) {
fail("BLE session failed: ${e.message}")
}
closeGatt()
if (!wanted) break
failures = if (ok) 0 else failures + 1
_state.value = if (ok) Esp32LinkState.DEVICE_ATTACHED else Esp32LinkState.ERROR
delay(if (ok) RECONNECT_DELAY_MS
else minOf(RETRY_MAX_MS, RETRY_BASE_MS shl (failures - 1).coerceAtMost(4)))
}
_state.value = Esp32LinkState.DISCONNECTED
}
}
fun disconnect() {
wanted = false
sessionJob?.cancel()
sessionJob = null
closeGatt()
_state.value = Esp32LinkState.DISCONNECTED
_detail.value = null
}
/**
* Writes one complete link message to the characteristic of its opcode, with response.
* Suspends until the micrOBU acknowledged the write; false when not connected or it failed.
*/
@SuppressLint("MissingPermission")
suspend fun send(message: ByteArray): Boolean {
val g = gatt ?: return false
if (_state.value != Esp32LinkState.CONNECTED || message.isEmpty()) return false
val characteristic = g.getService(SERVICE)?.getCharacteristic(writeTarget(message[0].toInt() and 0xFF))
?: return false
return gattOp {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
g.writeCharacteristic(characteristic, message, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) ==
BluetoothGatt.GATT_SUCCESS
} else {
@Suppress("DEPRECATION")
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
@Suppress("DEPRECATION")
characteristic.value = message
@Suppress("DEPRECATION")
g.writeCharacteristic(characteristic)
}
} == BluetoothGatt.GATT_SUCCESS
}
/** One connection lifetime. Returns true if it reached CONNECTED before ending. */
@SuppressLint("MissingPermission")
private suspend fun session(): Boolean {
if (!hasPermissions()) {
wanted = false
return fail("Bluetooth permission not granted (Android Settings > Apps > MicrOBU > Permissions)")
}
val adapter = bluetoothManager?.adapter
if (adapter == null || !adapter.isEnabled) return fail("Bluetooth is off")
_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)
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
deviceName = device.name
_detail.value = null
Log.i(TAG, "connecting to ${device.name} ${device.address} (bond state ${device.bondState})")
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}")
}
val g = gatt ?: return false
// Services first: discovery needs no encryption, and the encryption probe below needs the
// STATUS characteristic.
servicesDone = CompletableDeferred()
g.discoverServices()
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS) { servicesDone!!.await() } != true) {
return fail("Service discovery on ${device.name} timed out")
}
if (g.getService(SERVICE) == null) {
return fail("${device.name} does not offer the station-link service (old firmware?)")
}
// Encryption before anything else. Every characteristic needs an encrypted, authenticated
// link; the board asks for security as soon as a phone connects. A phone it has a bond with
// encrypts with the stored key. Otherwise Android pairs, with its passkey dialog, which takes
// as long as the user takes. A GATT operation with a short timeout during that cuts the
// pairing off, the link drops, and the next attempt starts pairing again: a loop.
val wasBonded = device.bondState == BluetoothDevice.BOND_BONDED
if (!awaitEncryption(g, device)) {
if (!linkUp) return fail("${device.name} dropped the link while pairing")
return fail(
if (wasBonded) "${device.name} refused this phone's stored pairing. In Android's Bluetooth " +
"settings, forget ${device.name}, then Connect again (passkey $PASSKEY)."
else "Pairing with ${device.name} failed or timed out (passkey $PASSKEY)"
)
}
_state.value = Esp32LinkState.DEVICE_ATTACHED
_detail.value = null
mtuDone = CompletableDeferred()
g.requestMtu(REQUESTED_MTU)
val mtu = withTimeoutOrNull(GATT_OP_TIMEOUT_MS) { mtuDone!!.await() } ?: 23
Log.i(TAG, "ATT MTU $mtu")
if (mtu < LINK_MAX_MESSAGE + 3) {
// The board drops a notification that does not fit rather than truncate it (simple_ble.cpp).
Log.w(TAG, "MTU $mtu is below ${LINK_MAX_MESSAGE + 3}: large V2X_RX messages will not arrive")
}
for (uuid in listOf(RESULT, BTP_INDICATION, ID_EVENT)) {
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>()
connected = dropped
dropped.await()
Log.w(TAG, "BLE link to ${device.name} lost")
return true
}
@SuppressLint("MissingPermission")
private suspend fun scan(): BluetoothDevice? {
val scanner = bluetoothManager?.adapter?.bluetoothLeScanner ?: return null
val found = CompletableDeferred<BluetoothDevice>()
val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
val name = result.scanRecord?.deviceName ?: result.device.name
val offersService = result.scanRecord?.serviceUuids?.any { it.uuid == SERVICE } == true
if (offersService || name?.startsWith(NAME_PREFIX) == true) found.complete(result.device)
}
override fun onScanFailed(errorCode: Int) {
Log.w(TAG, "BLE scan failed: $errorCode")
}
}
val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
scanner.startScan(null, settings, scanCallback)
return try {
withTimeoutOrNull(SCAN_TIMEOUT_MS) { found.await() }
} finally {
runCatching { scanner.stopScan(scanCallback) }
}
}
/**
* Returns once the link is encrypted, pairing first if needed; false if that fails or the user
* 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
* 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.
*/
@SuppressLint("MissingPermission")
private suspend fun awaitEncryption(g: BluetoothGatt, device: BluetoothDevice): Boolean {
val status = g.getService(SERVICE)?.getCharacteristic(STATUS_CHAR) ?: return false
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
val changed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
} else {
@Suppress("DEPRECATION") intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
}
if (changed?.address != device.address) return
val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
Log.i(TAG, "bond state of ${device.name}: $state")
if (state == BluetoothDevice.BOND_BONDING) {
_state.value = Esp32LinkState.PERMISSION_REQUESTED
_detail.value = "Pair with ${device.name}: enter passkey $PASSKEY"
}
}
}
register(receiver)
try {
if (device.bondState == BluetoothDevice.BOND_BONDING) {
_state.value = Esp32LinkState.PERMISSION_REQUESTED
_detail.value = "Pair with ${device.name}: enter passkey $PASSKEY"
}
// Up to two reads: the first can come back with an authentication error at the moment
// pairing completes, before Android's own retry.
repeat(2) { attempt ->
val result = gattOp(BOND_TIMEOUT_MS) { g.readCharacteristic(status) }
Log.i(TAG, "encryption probe ${attempt + 1}: status $result, bond state ${device.bondState}")
if (result == BluetoothGatt.GATT_SUCCESS) return true
if (result !in AUTH_FAILURES) return false
}
return false
} finally {
runCatching { context.unregisterReceiver(receiver) }
}
}
private fun register(receiver: BroadcastReceiver) {
val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
} else {
@Suppress("UnspecifiedRegisterReceiverFlag") context.registerReceiver(receiver, filter)
}
}
/** Logs [reason], shows it on the connection card, and ends the attempt. */
private fun fail(reason: String): Boolean {
Log.w(TAG, reason)
_detail.value = reason
return false
}
@SuppressLint("MissingPermission")
private suspend fun enableNotifications(g: BluetoothGatt, uuid: UUID): Boolean {
val characteristic = g.getService(SERVICE)?.getCharacteristic(uuid) ?: return false
if (!g.setCharacteristicNotification(characteristic, true)) return false
val cccd = characteristic.getDescriptor(CCCD) ?: return false
val value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
return gattOp {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
g.writeDescriptor(cccd, value) == BluetoothGatt.GATT_SUCCESS
} else {
@Suppress("DEPRECATION") cccd.value = value
@Suppress("DEPRECATION") g.writeDescriptor(cccd)
}
} == BluetoothGatt.GATT_SUCCESS
}
/** Starts one GATT operation and waits for its callback's status; -1 if it could not start or timed out. */
private suspend fun gattOp(timeoutMs: Long = GATT_OP_TIMEOUT_MS, start: () -> Boolean): Int = gattMutex.withLock {
val op = CompletableDeferred<Int>()
pendingOp = op
if (!start()) {
pendingOp = null
return@withLock -1
}
withTimeoutOrNull(timeoutMs) { op.await() } ?: -1
}
@SuppressLint("MissingPermission")
private fun closeGatt() {
gatt?.let { runCatching { it.disconnect(); it.close() } }
gatt = null
pendingOp?.complete(-1)
connected?.complete(false)
}
private val callback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
Log.i(TAG, "connection state $newState (status $status)")
when (newState) {
BluetoothProfile.STATE_CONNECTED -> {
linkUp = true
connected?.complete(true)
}
BluetoothProfile.STATE_DISCONNECTED -> {
linkUp = false
connected?.complete(false)
pendingOp?.complete(-1)
if (_state.value == Esp32LinkState.CONNECTED) _state.value = Esp32LinkState.ERROR
}
}
}
override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {
mtuDone?.complete(mtu)
}
override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
servicesDone?.complete(status == BluetoothGatt.GATT_SUCCESS)
}
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
pendingOp?.complete(status)
}
override fun onCharacteristicWrite(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
pendingOp?.complete(status)
}
// API 33+ calls this overload; older versions the deprecated one below.
override fun onCharacteristicRead(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic,
value: ByteArray, status: Int) {
pendingOp?.complete(status)
}
@Deprecated("Deprecated in API 33")
override fun onCharacteristicRead(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
pendingOp?.complete(status)
}
// API 33+ delivers the value here and no longer calls the deprecated overload below.
override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray) {
_incoming.tryEmit(value.copyOf())
}
@Deprecated("Deprecated in API 33")
override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
@Suppress("DEPRECATION")
characteristic.value?.let { _incoming.tryEmit(it.copyOf()) }
}
}
}
@@ -1,497 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
import android.content.Context
import android.os.SystemClock
import android.util.Log
import com.hawhamburg.micr0bu.data.cam.PseudonymManager
import com.hawhamburg.micr0bu.data.mqtt.ObuHardwarePreferences
import com.hawhamburg.micr0bu.domain.asn1.ItsTime
import com.hawhamburg.micr0bu.domain.cam.StationType
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.roundToInt
/** Connection lifecycle of the ESP32-C5 link, over either transport. */
enum class Esp32LinkState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED, CONNECTED, ERROR }
/** 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") }
/**
* What the board on the other end speaks. The phone cannot ask, so it listens: the previous
* obu-firmware sends a [SerialFrameType.STATUS] heartbeat, the current one a station-link STATUS.
*/
enum class Esp32Protocol { UNKNOWN, LEGACY_SERIAL, STATION_LINK }
/** One ITS message for the air, with what the micrOBU needs to know about the sender. */
class OutgoingIts(
val kind: OutgoingMessage,
val uper: ByteArray,
/** Pseudonym MAC, station type and position; its [GnPositionVector.tstMs] is the fix time. */
val positionVector: GnPositionVector,
/** Android horizontal accuracy, metres (68 %); null when unknown. */
val accuracyM: Float?,
val signed: Boolean,
)
/**
* The one entry point the app uses to talk to the ESP32-C5: picks USB ([UsbSerialTransport]) or
* BLE ([BleLinkTransport]) from the setting, works out which firmware protocol is on the other end,
* and runs the station-link session the current firmware needs.
*
* ## Station-link session (obu-firmware since 2026-09-23)
* The firmware keeps no state the phone depends on, except what it stores itself (credentials in
* NVS), so the phone sets it up each time it sees it unconfigured:
* 1. STATION_CONFIGURE, with the current pseudonym MAC as the GN address and 802.11 source. This
* also starts the radio, which until then neither transmits nor receives.
* 2. If the answer reports no authorization ticket, CREDENTIALS_PROVISION of the demo bundle in
* `assets/demo-chain.vcr` (a disposable chain, not EU-registered: receivers that verify against
* the EU trust list will drop what it signs). The firmware keeps it in NVS from then on.
* 3. Per message: POTI_UPDATE (the fix, which also sets the micrOBU's ITS clock for the signature
* time), then BTP_DATA_REQUEST, secured or unsecured per the "Sign outgoing messages" setting.
* A pseudonym change reconfigures with the new MAC before the next message goes out. A STATUS
* saying "not configured" (the board reset) starts again at 1.
*
* ## Legacy firmware
* A board still on the previous obu-firmware (0xAA55 frames 0x01-0x05, no signing, USB only)
* keeps working for CAM exactly as before. VAM needs the current firmware.
*
* Everything received is surfaced the old way, as [DecodedFrame]s of [SerialFrameType.V2X_RX], so
* the receive side of the app did not change.
*/
@Singleton
class Esp32Link @Inject constructor(
@ApplicationContext private val context: Context,
private val usb: UsbSerialTransport,
private val ble: BleLinkTransport,
private val prefs: ObuHardwarePreferences,
private val pseudonymManager: PseudonymManager,
) {
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
private const val DEMO_BUNDLE_ASSET = "demo-chain.vcr"
/**
* A PoTi this far behind the last one sent is a real correction of the phone's clock (e.g.
* GNSS time taking over from a wrong system clock), not a repeated fix; it goes through
* and the micrOBU restarts its stack at the new time once.
*/
private const val CLOCK_STEP_BACK_MS = 60_000L
/** How long a refusal stays on the connection card. */
private const val DETAIL_HOLD_MS = 10_000L
const val BTP_PORT_CAM = 2001
const val BTP_PORT_VAM = 2018
const val ITS_AID_CAM = 36L
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). */
val SSP_VAM = byteArrayOf(0x01)
}
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
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)
private val _protocol = MutableStateFlow(Esp32Protocol.UNKNOWN)
val protocol: StateFlow<Esp32Protocol> = _protocol.asStateFlow()
private val _incomingFrames = MutableSharedFlow<DecodedFrame>(extraBufferCapacity = 256)
/** Received ITS messages ([SerialFrameType.V2X_RX]) and, from legacy firmware, its heartbeats. */
val incomingFrames: SharedFlow<DecodedFrame> = _incomingFrames.asSharedFlow()
private val _linkStatus = MutableStateFlow<EspLinkStatus?>(null)
/** Heartbeat counters in the old shape, from either firmware; null before the first one. */
val linkStatus: StateFlow<EspLinkStatus?> = _linkStatus.asStateFlow()
private val _stationStatus = MutableStateFlow<StationStatus?>(null)
/** Full station-link STATUS (signing counters, tickets); null with legacy firmware. */
val stationStatus: StateFlow<StationStatus?> = _stationStatus.asStateFlow()
private val _detail = MutableStateFlow<String?>(null)
/** One line for the UI about the session: pairing, provisioning, or why it is stuck. */
val detail: StateFlow<String?> = _detail.asStateFlow()
private val _consecutiveWriteFailures = MutableStateFlow(0)
val consecutiveWriteFailures: StateFlow<Int> = _consecutiveWriteFailures.asStateFlow()
private val _refusedRequests = MutableStateFlow(0)
/** BTP_DATA_REQUESTs the micrOBU answered with anything but accepted (e.g. no ticket). */
val refusedRequests: StateFlow<Int> = _refusedRequests.asStateFlow()
private val sequence = AtomicInteger(0)
private val pending = ConcurrentHashMap<Int, CompletableDeferred<LinkResult>>()
private val sessionMutex = Mutex()
/** The STATION_CONFIGURE the micrOBU is known to run, or null when it has to be sent again. */
@Volatile private var configured: StationConfigure? = null
@Volatile private var lastRefusalLogMs = 0L
/**
* Timestamp of the last POTI_UPDATE sent in this session, or null when the micrOBU's ITS clock
* has to be set again (new session, board reset).
*/
@Volatile private var lastPotiMs: Long? = null
/** [SystemClock.elapsedRealtime] when [lastPotiMs] was sent: with it, where the micrOBU's clock stands now. */
@Volatile private var lastPotiElapsedMs = 0L
/** The fix time (before any clamping) of the last PoTi sent, to send each fix only once. */
@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 } }
// A new connection, on either transport, starts a new session.
scope.launch {
state.collect { s ->
if (s != Esp32LinkState.CONNECTED) {
configured = null; lastPotiMs = null; lastPotiFixMs = null
_protocol.value = Esp32Protocol.UNKNOWN
_stationStatus.value = null
_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 {
transport.collect { t ->
if (t == Esp32Transport.USB) ble.disconnect() else usb.disconnect()
_detail.value = null
}
}
}
fun connect() {
if (transport.value == Esp32Transport.USB) usb.connect() else ble.connect()
}
fun disconnect() {
usb.disconnect()
ble.disconnect()
}
/**
* Hands one message to the micrOBU for transmission. False when it could not be handed over
* (no link, legacy firmware asked for a VAM, session setup failed); the next message retries.
* Acceptance by the micrOBU is not awaited: a refusal shows up in [refusedRequests].
*/
suspend fun send(its: OutgoingIts): Boolean = withContext(Dispatchers.IO) {
val ok = when (_protocol.value) {
Esp32Protocol.LEGACY_SERIAL -> {
if (its.kind == OutgoingMessage.CAM) {
usb.sendCamTx(its.uper, its.positionVector)
} else {
noteRefusal("VAM needs the current obu-firmware; this board runs the previous one")
false
}
}
Esp32Protocol.STATION_LINK -> sendStationLink(its)
Esp32Protocol.UNKNOWN -> false // no heartbeat yet: nothing to address
}
if (ok) _consecutiveWriteFailures.value = 0 else _consecutiveWriteFailures.value++
ok
}
private suspend fun sendStationLink(its: OutgoingIts): Boolean {
val pv = its.positionVector
if (!ensureConfigured(StationConfigure(stationType = pv.stationType, mid = pv.mac))) return false
// The micrOBU's ITS clock must never be sent backwards: past 1 s it answers
// time_regression and rebuilds its whole stack. Two things tried to. The transmit loops
// re-send the latest GNSS fix every tick while fused location pauses, so an old fix time
// arrived again and again while the micrOBU's clock ran on. And the GNSS-corrected fix
// times themselves wobble by seconds indoors (measured 2026-09-23: -2.1 s, +4.9 s between
// consecutive CAMs). So a fix goes over once, and its timestamp is never below where the
// micrOBU's clock stands now, except for a real correction of the phone clock.
val poti = potiFor(its)
if (poti.timestampMs != lastPotiFixMs) {
val last = lastPotiMs
val microbuNow = last?.let { it + (SystemClock.elapsedRealtime() - lastPotiElapsedMs) }
val timestamp = when {
microbuNow == null -> poti.timestampMs
poti.timestampMs < microbuNow - CLOCK_STEP_BACK_MS -> poti.timestampMs
else -> maxOf(poti.timestampMs, microbuNow)
}
if (!write(LinkOpcode.POTI_UPDATE, poti.copy(timestampMs = timestamp).encode())) return false
lastPotiFixMs = poti.timestampMs
lastPotiMs = timestamp
lastPotiElapsedMs = SystemClock.elapsedRealtime()
}
val request = BtpDataRequest(
destinationPort = if (its.kind == OutgoingMessage.CAM) BTP_PORT_CAM else BTP_PORT_VAM,
itsAid = if (its.kind == OutgoingMessage.CAM) ITS_AID_CAM else ITS_AID_VAM,
securityProfile = if (its.signed) LinkSecurityProfile.SECURED else LinkSecurityProfile.UNSECURED,
permissions = if (its.kind == OutgoingMessage.CAM) SSP_CAM else SSP_VAM,
flSdu = its.uper,
)
return write(LinkOpcode.BTP_DATA_REQUEST, request.encode())
}
/**
* Makes sure the micrOBU runs [wanted] (or, when null, any configuration: used right after a
* BLE connect or a board reset, to start its receiver before the first message goes out).
*/
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)
_detail.value = "Configuring the micrOBU"
val result = request(LinkOpcode.STATION_CONFIGURE, config.encode(), REPLY_TIMEOUT_MS)
if (result == null || !result.accepted) {
_detail.value = "micrOBU did not accept the configuration (${result?.let { LinkResultCode.name(it.code) } ?: "no reply"})"
return@withLock false
}
val info = StationInfo.decode(result.detail)
Log.i(TAG, "station configured: $info")
if (info == null || !info.credentialsLoaded || info.tickets == 0) {
if (!provisionDemoCredentials()) return@withLock false
}
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 {
_detail.value = "Demo credential bundle missing from the app"
return false
}
var offset = 0
while (offset < bundle.size) {
val segment = bundle.copyOfRange(offset, minOf(bundle.size, offset + SEGMENT_SIZE))
val last = offset + segment.size == bundle.size
val result = request(LinkOpcode.CREDENTIALS_PROVISION, credentialsSegment(bundle.size, offset, segment),
if (last) PROVISION_TIMEOUT_MS else REPLY_TIMEOUT_MS)
if (result == null || !result.accepted) {
_detail.value = "micrOBU refused the demo credentials (${result?.let { LinkResultCode.name(it.code) } ?: "no reply"})"
return false
}
if (last) {
val d = result.detail
Log.i(TAG, "demo credentials provisioned: " +
if (d.size == 3) "${d[0]} root(s), ${d[1]} authorit(ies), ${d[2]} ticket(s)" else "no report")
}
offset += segment.size
}
return true
}
private fun potiFor(its: OutgoingIts): PotiUpdate {
val pv = its.positionVector
// Semi-axes of the 95 % ellipse from Android's 68 % radius (circular error), as GnPositionVector's PAI bound.
val semiCm = its.accuracyM?.takeIf { it > 0f && it.isFinite() }
?.let { (it * 1.62f * 100).roundToInt().coerceAtMost(65_535) } ?: 0
return PotiUpdate(
timestampMs = fullTimestampIts(pv.tstMs),
latTenMicroDeg = pv.latTenMicroDeg,
lonTenMicroDeg = pv.lonTenMicroDeg,
semiMajorCm = semiCm,
semiMinorCm = semiCm,
speedCms = pv.speedCms.coerceAtLeast(0),
headingDeciDeg = pv.headingDeciDeg,
pai = pv.pai,
)
}
/** [GnPositionVector.tstMs] is already the full TimestampIts; guard against a reduced one anyway. */
private fun fullTimestampIts(tstMs: Long): Long {
if (tstMs > 0xFFFF_FFFFL) return tstMs
val now = ItsTime.timestampIts(System.currentTimeMillis())
return now - ((now - tstMs) and 0xFFFF_FFFFL)
}
private suspend fun request(opcode: Int, body: ByteArray, timeoutMs: Long): LinkResult? {
val seq = nextSequence()
val reply = CompletableDeferred<LinkResult>()
pending[seq] = reply
return try {
if (!writeMessage(LinkMessage(opcode, seq, body).encode())) null
else withTimeoutOrNull(timeoutMs) { reply.await() }
} finally {
pending.remove(seq)
}
}
private suspend fun write(opcode: Int, body: ByteArray): Boolean =
writeMessage(LinkMessage(opcode, nextSequence(), body).encode())
private suspend fun writeMessage(message: ByteArray): Boolean =
if (transport.value == Esp32Transport.USB) usb.sendFrame(SERIAL_FRAME_LINK, message)
else ble.send(message)
private fun nextSequence(): Int = sequence.incrementAndGet() and 0xFFFF
private fun onUsbFrame(frame: DecodedFrame) {
when (frame.type) {
SerialFrameType.STATUS -> _protocol.value = Esp32Protocol.LEGACY_SERIAL
SerialFrameType.V2X_RX -> _incomingFrames.tryEmit(frame)
SERIAL_FRAME_LINK -> onLinkMessage(frame.payload)
}
}
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
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 -> {
val result = LinkResult.decode(message.body) ?: return
val waiting = pending.remove(message.sequence)
if (waiting != null) {
waiting.complete(result)
} else if (result.code == LinkResultCode.TIME_REGRESSION) {
// Only sent for a deliberate clock correction (see CLOCK_STEP_BACK_MS): the
// micrOBU accepted the new time and restarted its stack. Not a refusal.
Log.i(TAG, "micrOBU followed a step back of the phone's clock and restarted its stack")
} else if (!result.accepted) {
// A POTI_UPDATE or BTP_DATA_REQUEST the micrOBU refused (they are not awaited).
_refusedRequests.value++
if (result.code == LinkResultCode.NOT_CONFIGURED) { configured = null; lastPotiMs = null; lastPotiFixMs = null }
noteRefusal("micrOBU refused a request: ${LinkResultCode.name(result.code)}")
}
}
}
}
/** 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
lastRefusalLogMs = now
Log.w(TAG, line)
_detail.value = line
// A refusal is news, not a state: it leaves the card again unless something replaced it.
scope.launch {
delay(DETAIL_HOLD_MS)
_detail.compareAndSet(line, null)
}
}
}
@@ -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),
)
}
}
}
@@ -57,9 +57,8 @@ const val SERIAL_LINK_MAX_PAYLOAD = 512
/**
* Decoded [SerialFrameType.STATUS] payload: `[status:1][oversizeDrops:2 LE][txFailures:2 LE]
* [rxCrcErrors:2 LE][capabilities:1][rxQueueDrops:2 LE]` (10 bytes; the last two fields are an
* optional tail — see [capabilities] and [rxQueueDrops]). Counters are free-running totals since
* firmware boot and saturate at 0xFFFF rather than wrapping.
* [rxCrcErrors:2 LE]` (7 bytes). Counters are free-running totals since firmware boot and
* saturate at 0xFFFF rather than wrapping.
*
* Exists so the phone can tell "link alive, no traffic" from "link dead", and so firmware-side
* drops — which otherwise only reach `ESP_LOGW` on the flashing port that the phone isn't
@@ -80,15 +79,6 @@ data class EspLinkStatus(
* the phone needs from such firmware: it accepts nothing beyond the original messages.
*/
val capabilities: Int = 0,
/**
* Promiscuously-captured frames the firmware's `wifi_promisc_rx_cb` had to drop because its
* RX queue (8 deep) was still full of frames `rx_forward_task` hadn't finished forwarding —
* bytes 8-9 of the payload. 0 for firmware that predates this field (payload of 7 or 8 bytes),
* which is the honest answer: such firmware drops these frames identically, it just never
* counted them. A nonzero, growing value here — as opposed to [oversizeDrops] — points at
* bursty RX outrunning the forward task rather than any one frame being too large.
*/
val rxQueueDrops: Int = 0,
) {
/** True when the firmware accepts [SerialFrameType.CAM_TX_PV]. */
val supportsCamTxPv: Boolean get() = capabilities and CAP_CAM_TX_PV != 0
@@ -109,7 +99,6 @@ data class EspLinkStatus(
txFailures = u16(3),
rxCrcErrors = u16(5),
capabilities = if (payload.size > PAYLOAD_SIZE) payload[7].toInt() and 0xFF else 0,
rxQueueDrops = if (payload.size >= 10) u16(8) else 0,
)
}
}
@@ -137,7 +126,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,320 +0,0 @@
package com.hawhamburg.micr0bu.data.transport
/**
* Phone side of the station-link message layer, version 1: the protocol of Niklas Dathe'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
* Python module produced.
*
* Transport independent: over USB each message is the payload of one serial frame of type
* [SERIAL_FRAME_LINK] (same 0xAA55 framing as before, see [SerialFrameEncoder]); over BLE each
* 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.
*
* 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
* 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.
*/
const val SERIAL_FRAME_LINK = 0x10
const val LINK_MAX_MESSAGE = 512
const val LINK_HEADER_SIZE = 4
object LinkOpcode {
const val STATION_CONFIGURE = 0x01
const val POTI_UPDATE = 0x02
const val BTP_DATA_REQUEST = 0x03
const val CREDENTIALS_PROVISION = 0x04
const val CREDENTIALS_ERASE = 0x05
const val STATUS_REQUEST = 0x0C
/** Debug path: body is one mode octet (bit 0 on, bit 1 broadcast only, bit 2 own transmissions); 0 switches it off. */
const val RAW_CAPTURE = 0x0D
const val CONFIRM = 0x80
const val BTP_DATA_INDICATION = 0x81
/** Raw 802.11 frame copy of the RAW_CAPTURE debug path, fragmented when large: see [RawFrame]. */
const val RAW_FRAME = 0x85
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
const val V2X_RX = 0x90
}
/** CONFIRM result codes: the stack's own first, then the link's. */
object LinkResultCode {
const val ACCEPTED = 0
const val TIME_REGRESSION = 7
const val NOT_CONFIGURED = 0x12
fun name(code: Int): String = when (code) {
0 -> "accepted"; 1 -> "invalid_argument"; 2 -> "unsupported"; 3 -> "wrong_entry_point"
4 -> "security_unavailable"; 5 -> "resource_limit"; 6 -> "rejected"; 7 -> "time_regression"
8 -> "identity_change_pending"; 0x10 -> "unknown_opcode"; 0x11 -> "malformed"
0x12 -> "not_configured"; 0x13 -> "busy"; 0x14 -> "no_credentials"
else -> "code_$code"
}
}
/** GN security profile of a BTP-DATA.request (TS 103 300-3 Table 4). */
object LinkSecurityProfile {
const val STATION_DEFAULT = 0
const val UNSECURED = 1
const val SECURED = 2
}
class LinkMessage(val opcode: Int, val sequence: Int, val body: ByteArray, val flags: Int = 0) {
fun encode(): ByteArray {
require(LINK_HEADER_SIZE + body.size <= LINK_MAX_MESSAGE) {
"link message 0x%02x too long: %d".format(opcode, LINK_HEADER_SIZE + body.size)
}
return byteArrayOf(opcode.toByte(), flags.toByte(), sequence.toByte(), (sequence shr 8).toByte()) + body
}
companion object {
fun decode(octets: ByteArray): LinkMessage? {
if (octets.size < LINK_HEADER_SIZE || octets.size > LINK_MAX_MESSAGE) return null
val sequence = (octets[2].toInt() and 0xFF) or ((octets[3].toInt() and 0xFF) shl 8)
return LinkMessage(octets[0].toInt() and 0xFF, sequence,
octets.copyOfRange(LINK_HEADER_SIZE, octets.size), octets[1].toInt() and 0xFF)
}
}
}
internal class LinkWriter {
private val out = java.io.ByteArrayOutputStream()
fun u8(v: Int) = apply { out.write(v and 0xFF) }
fun u16(v: Int) = apply { u8(v); u8(v shr 8) }
fun u32(v: Long) = apply { for (i in 0 until 4) u8((v ushr (8 * i)).toInt()) }
fun i32(v: Int) = u32(v.toLong())
fun u64(v: Long) = apply { for (i in 0 until 8) u8((v ushr (8 * i)).toInt()) }
fun bytes(b: ByteArray) = apply { out.write(b) }
fun toByteArray(): ByteArray = out.toByteArray()
}
/**
* 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).
*/
data class StationConfigure(
val stationType: Int,
val security: Int = 1,
val beaconing: Int = 0,
val channelNumber: Int = 180,
val transmitPowerDbm: Int = 20,
val mid: ByteArray? = null,
) {
init { require(mid == null || 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()
}
override fun equals(other: Any?): Boolean = other is StationConfigure && encode().contentEquals(other.encode())
override fun hashCode(): Int = encode().contentHashCode()
}
/** CONFIRM detail of STATION_CONFIGURE. */
data class StationInfo(val credentialsLoaded: Boolean, val tickets: Int) {
companion object {
fun decode(detail: ByteArray): StationInfo? =
if (detail.size != 18) null
else StationInfo(detail[16].toInt() != 0, detail[17].toInt() and 0xFF)
}
}
/**
* POTI_UPDATE body (EN 302 890-2 minimum data set). [timestampMs] is TimestampIts under
* [com.hawhamburg.micr0bu.domain.asn1.ItsTime]'s convention; it also sets the micrOBU's ITS clock,
* which the security entity stamps into every signed message's generationTime.
*/
data class PotiUpdate(
val timestampMs: Long,
val latTenMicroDeg: Int,
val lonTenMicroDeg: Int,
val semiMajorCm: Int = 0,
val semiMinorCm: Int = 0,
val orientationDeciDeg: Int = 0,
val altitudeCm: Int? = null,
val speedCms: Int? = null,
val headingDeciDeg: Int? = null,
val pai: Boolean = false,
) {
fun encode(): ByteArray {
val flags = (if (altitudeCm != null) 1 else 0) or (if (speedCms != null) 2 else 0) or
(if (headingDeciDeg != null) 4 else 0) or (if (pai) 8 else 0)
return LinkWriter().u64(timestampMs).i32(latTenMicroDeg).i32(lonTenMicroDeg)
.u16(semiMajorCm).u16(semiMinorCm).u16(orientationDeciDeg).u8(flags)
.i32(altitudeCm ?: 0).u16(speedCms ?: 0).u16(headingDeciDeg ?: 0)
.toByteArray()
}
}
/**
* BTP_DATA_REQUEST body for a BTP-B single-hop broadcast, the only shape this app sends (CAM, VAM).
* [permissions] is the SSP the authorization ticket must carry for [itsAid].
*/
data class BtpDataRequest(
val destinationPort: Int,
val itsAid: Long,
val securityProfile: Int,
val permissions: ByteArray,
val flSdu: ByteArray,
/** Raw GN lifetime octet; 0xFF = station default. */
val maximumPacketLifetime: Int = 0xFF,
) {
fun encode(): ByteArray = LinkWriter()
.u8(1) // BTP-B
.u16(destinationPort)
.u16(0) // destination port info
.u8(1) // SHB
.u8(1) // communication profile ITS-G5
.u8(securityProfile)
.u8(0xFF) // traffic class: station default
.u8(maximumPacketLifetime)
.u8(0) // hop limit: station default
.u16(0).u16(0) // no repetition
.u32(itsAid)
.u8(permissions.size).bytes(permissions)
.u8(0) // no SN-ENCAP context
.u16(flSdu.size).bytes(flSdu)
.toByteArray()
override fun equals(other: Any?): Boolean = other is BtpDataRequest && encode().contentEquals(other.encode())
override fun hashCode(): Int = encode().contentHashCode()
}
/** One CREDENTIALS_PROVISION segment of a `VCR1` bundle. */
fun credentialsSegment(totalLength: Int, offset: Int, segment: ByteArray): ByteArray {
require(segment.size <= 255)
return LinkWriter().u16(totalLength).u16(offset).u8(segment.size).bytes(segment).toByteArray()
}
data class LinkResult(val code: Int, val detail: ByteArray) {
val accepted: Boolean get() = code == LinkResultCode.ACCEPTED
override fun toString(): String = "LinkResult(${LinkResultCode.name(code)}, ${detail.size} B detail)"
override fun equals(other: Any?): Boolean = other is LinkResult && code == other.code && detail.contentEquals(other.detail)
override fun hashCode(): Int = 31 * code + detail.contentHashCode()
companion object {
fun decode(body: ByteArray): LinkResult? {
if (body.size < 2) return null
val length = body[1].toInt() and 0xFF
if (body.size != 2 + length) return null
return LinkResult(body[0].toInt() and 0xFF, body.copyOfRange(2, body.size))
}
}
}
/**
* 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).
*/
data class StationStatus(
val uptimeMs: Long,
val configured: Boolean,
val identifier: ByteArray,
val tickets: Int,
val signedMessages: Long,
val refusedNoTicket: Long,
val refusedChangePending: Long,
val refusedPermission: Long,
val signFailed: Long,
val verified: Long,
val rejected: Long,
val requestsAccepted: Long,
val requestsRefused: Long,
val radioSubmitted: Long,
val radioFailed: Long,
val radioReceived: Long,
val radioDropped: Long,
val linkCrcErrors: Long,
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
override fun equals(other: Any?): Boolean = other is StationStatus && toString() == other.toString() &&
identifier.contentEquals(other.identifier)
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
/** 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
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)) }
// [0] uptime u32, [4] configured, [5] gn_address 8, [13] identifier 8, [21] change_pending,
// [22] tickets, [23] 18 x u32 counters, [95] its_time u64
val c = 23
return StationStatus(
uptimeMs = u32(0),
configured = u8(4) != 0,
identifier = body.copyOfRange(13, 21),
tickets = u8(22),
signedMessages = u32(c), refusedNoTicket = u32(c + 4), refusedChangePending = u32(c + 8),
refusedPermission = u32(c + 12), signFailed = u32(c + 16), verified = u32(c + 20),
rejected = u32(c + 24), requestsAccepted = u32(c + 28), requestsRefused = u32(c + 32),
// c + 36: indications (the stack's own verified deliveries; the app uses V2X_RX)
radioSubmitted = u32(c + 40), radioFailed = u32(c + 44), radioReceived = u32(c + 48),
radioDropped = u32(c + 52),
// 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),
)
}
}
}
@@ -35,6 +35,9 @@ import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
/** Connection lifecycle for the ESP32-C5 USB-serial link. */
enum class UsbSerialState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED, CONNECTED, ERROR }
private const val ACTION_USB_PERMISSION = "com.hawhamburg.micr0bu.USB_SERIAL_PERMISSION"
private const val TAG = "UsbSerialTransport"
@@ -60,11 +63,6 @@ private const val TAG = "UsbSerialTransport"
* Baud rate is not applicable here — USB Serial/JTAG has no baud concept; `setParameters` below
* is a no-op the library requires anyway for API-shape reasons but the value is otherwise unused.
*
* Since 2026-09-23 the rest of the app does not use this class directly but [Esp32Link], which
* picks this or [BleLinkTransport] and speaks either the previous firmware's frames (0x01-0x05,
* [sendCamTx]) or the current firmware's station-link messages (frame type [SERIAL_FRAME_LINK],
* [sendFrame]) over it.
*
* ## Ownership
* This is a `@Singleton` shared by the UI ([com.hawhamburg.micr0bu.viewmodel.MqttViewModel]), the
* foreground [com.hawhamburg.micr0bu.service.TripRecordingService]'s
@@ -113,8 +111,8 @@ class UsbSerialTransport @Inject constructor(
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
private val _state = MutableStateFlow(UsbSerialState.DISCONNECTED)
val state: StateFlow<UsbSerialState> = _state.asStateFlow()
private val _incomingFrames = MutableSharedFlow<DecodedFrame>(extraBufferCapacity = 256)
/** Every valid frame the ESP32 sends (CAM_RX and STATUS) — callers filter by [DecodedFrame.type]. */
@@ -152,7 +150,7 @@ class UsbSerialTransport @Inject constructor(
} else {
Log.w(TAG, "usbReceiver: permission denied or device null " +
"(granted=$granted, device=$device)")
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
}
}
UsbManager.ACTION_USB_DEVICE_DETACHED -> {
@@ -176,7 +174,7 @@ class UsbSerialTransport @Inject constructor(
* repeatedly (e.g. from a "retry" UI action) — no-ops if already connected.
*/
fun connect() {
if (_state.value == Esp32LinkState.CONNECTED) {
if (_state.value == UsbSerialState.CONNECTED) {
Log.i(TAG, "connect(): already connected, no-op")
return
}
@@ -199,7 +197,7 @@ class UsbSerialTransport @Inject constructor(
"(see device list logged above) - either nothing is attached at the Android " +
"USB level, or it's attached but its VID/PID doesn't match any entry in " +
"customProber's table")
_state.value = Esp32LinkState.DISCONNECTED
_state.value = UsbSerialState.DISCONNECTED
return
}
if (espDriver == null) {
@@ -213,14 +211,14 @@ class UsbSerialTransport @Inject constructor(
Log.i(TAG, "connect(): matched device vid=0x${device.vendorId.toString(16)} " +
"pid=0x${device.productId.toString(16)} name=${device.deviceName} " +
"ports=${driver.ports.size}")
_state.value = Esp32LinkState.DEVICE_ATTACHED
_state.value = UsbSerialState.DEVICE_ATTACHED
if (usbManager.hasPermission(device)) {
Log.i(TAG, "connect(): permission already granted, opening directly")
openDevice(device)
} else {
Log.i(TAG, "connect(): requesting USB permission from user")
_state.value = Esp32LinkState.PERMISSION_REQUESTED
_state.value = UsbSerialState.PERMISSION_REQUESTED
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0
val permissionIntent = PendingIntent.getBroadcast(
context, 0, Intent(ACTION_USB_PERMISSION).setPackage(context.packageName), flags,
@@ -271,14 +269,14 @@ class UsbSerialTransport @Inject constructor(
if (driver == null || driver.ports.isEmpty()) {
Log.w(TAG, "openDevice(): probeDevice returned null or no ports for " +
"vid=0x${device.vendorId.toString(16)} pid=0x${device.productId.toString(16)}")
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
return
}
val connection = usbManager.openDevice(device)
if (connection == null) {
Log.w(TAG, "openDevice(): usbManager.openDevice() returned null - permission not " +
"actually granted, or Android couldn't claim the device")
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
return
}
@@ -289,7 +287,7 @@ class UsbSerialTransport @Inject constructor(
} catch (e: Exception) {
Log.e(TAG, "openDevice(): port.open()/setParameters() threw", e)
runCatching { newPort.close() }
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
return
}
@@ -332,15 +330,13 @@ class UsbSerialTransport @Inject constructor(
prev.txFailures != status.txFailures ||
prev.rxCrcErrors != status.rxCrcErrors ||
prev.status != status.status ||
prev.capabilities != status.capabilities ||
prev.rxQueueDrops != status.rxQueueDrops
prev.capabilities != status.capabilities
) {
Log.i(TAG, "ESP32 counters: status=${status.status} " +
"oversizeDrops=${status.oversizeDrops} " +
"txFailures=${status.txFailures} " +
"rxCrcErrors=${status.rxCrcErrors} " +
"capabilities=${status.capabilities} " +
"rxQueueDrops=${status.rxQueueDrops}")
"capabilities=${status.capabilities}")
}
_linkStatus.value = status
}
@@ -351,7 +347,7 @@ class UsbSerialTransport @Inject constructor(
override fun onRunError(e: Exception) {
Log.e(TAG, "SerialInputOutputManager.onRunError()", e)
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
}
})
ioManager = manager
@@ -364,13 +360,13 @@ class UsbSerialTransport @Inject constructor(
_consecutiveWriteFailures.value = 0
_linkStatus.value = null
lastFrameAtMs = SystemClock.elapsedRealtime()
_state.value = Esp32LinkState.CONNECTED
_state.value = UsbSerialState.CONNECTED
startWatchdog()
}
}
/**
* Flips the link to [Esp32LinkState.ERROR] once the firmware's 1 Hz STATUS heartbeat has been
* Flips the link to [UsbSerialState.ERROR] once the firmware's 1 Hz STATUS heartbeat has been
* missing for [LINK_TIMEOUT_MS]. Without this, "connected" only ever means "the port opened
* at some point in the past" — which on a bench is exactly the wrong thing to believe.
*/
@@ -379,14 +375,14 @@ class UsbSerialTransport @Inject constructor(
watchdogJob = scope.launch {
while (isActive) {
delay(WATCHDOG_POLL_MS)
if (_state.value != Esp32LinkState.CONNECTED) continue
if (_state.value != UsbSerialState.CONNECTED) continue
val silentFor = SystemClock.elapsedRealtime() - lastFrameAtMs
if (silentFor > LINK_TIMEOUT_MS) {
Log.w(TAG, "watchdog: no frame from ESP32 for ${silentFor}ms (heartbeat " +
"expected at 1 Hz) - marking link ERROR. Either the firmware is wedged/" +
"not running, or the host->device direction opened but device->host " +
"never did (see the DTR note in openDevice()).")
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
}
}
}
@@ -447,29 +443,7 @@ class UsbSerialTransport @Inject constructor(
} catch (e: Exception) {
val failures = _consecutiveWriteFailures.updateAndGet { it + 1 }
Log.w(TAG, "sendCamTx(): write failed (consecutive failures: $failures)", e)
_state.value = Esp32LinkState.ERROR
false
}
}
/**
* Writes one frame of any [type] (the station-link messages go as [SERIAL_FRAME_LINK]). Same
* failure accounting as [sendCamTx]. Blocking, 200 ms timeout: call from a background dispatcher.
*/
fun sendFrame(type: Int, payload: ByteArray): Boolean {
val p = port
if (p == null) {
_consecutiveWriteFailures.update { it + 1 }
return false
}
return try {
p.write(SerialFrameEncoder.encode(type, payload), /* timeout ms */ 200)
_consecutiveWriteFailures.value = 0
true
} catch (e: Exception) {
val failures = _consecutiveWriteFailures.updateAndGet { it + 1 }
Log.w(TAG, "sendFrame(0x${type.toString(16)}): write failed (consecutive failures: $failures)", e)
_state.value = Esp32LinkState.ERROR
_state.value = UsbSerialState.ERROR
false
}
}
@@ -485,7 +459,7 @@ class UsbSerialTransport @Inject constructor(
openDeviceName = null
_linkStatus.value = null
_consecutiveWriteFailures.value = 0
_state.value = Esp32LinkState.DISCONNECTED
_state.value = UsbSerialState.DISCONNECTED
}
}
@@ -8,7 +8,7 @@ import javax.inject.Singleton
* UPER (Unaligned Packed Encoding Rules) codec for CAM, used on the ESP32-C5 hardware path
* (Phase 03, Section 13): the phone builds outgoing CAM itself
* ([com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder]) and UPER-encodes it before handing bytes
* to [com.hawhamburg.micr0bu.data.transport.Esp32Link], and UPER-decodes whatever the
* to [com.hawhamburg.micr0bu.data.transport.UsbSerialTransport], and UPER-decodes whatever the
* ESP32-C5 forwards back on receive (already stripped of 802.11/GeoNetworking/BTP framing by
* the firmware's `gn_unwrap.c` — this only ever sees CAM UPER bytes, never raw radio frames).
*
@@ -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
}
}
@@ -1,145 +0,0 @@
package com.hawhamburg.micr0bu.domain.asn1
import com.hawhamburg.micr0bu.domain.cam.StationType
import kotlin.math.roundToInt
import kotlin.math.roundToLong
/**
* One VAM's content, in the units the phone has. Everything optional here is encoded as the ASN.1
* "unavailable" value when null, never as a made-up number.
*/
data class VamContent(
val stationId: Long,
/** Wall-clock epoch ms of the fix, GNSS-corrected; the generationDeltaTime source. */
val timestamp: Long,
val latitude: Double,
val longitude: Double,
/** Android horizontal accuracy, metres (68 %). Null or 0: unknown. */
val accuracyM: Float?,
val speedMps: Double,
val headingDeg: Double,
/** Along-track acceleration, m/s². */
val accelerationMps2: Double? = null,
/** Include the low-frequency container (profile and size class). */
val includeLowFrequency: Boolean,
)
/**
* 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,
* 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
* or motion-prediction containers. The unit test cross-checks the bytes against asn1tools.
*
* Transmit only for now: the app neither decodes received VAMs nor shows them.
*/
object VamUperCodec {
const val PROTOCOL_VERSION = 3
const val MESSAGE_ID_VAM = 16
/** VruSubProfileBicyclist.bicyclist */
private const val SUBPROFILE_BICYCLIST = 1
/** VruSizeClass.low */
private const val SIZE_CLASS_LOW = 1
/** VruProfileAndSubprofile CHOICE index of bicyclistAndLightVruVehicle (root: 4 alternatives). */
private const val PROFILE_BICYCLIST_INDEX = 1
private const val SEMI_AXIS_OUT_OF_RANGE = 4094
private const val SEMI_AXIS_UNAVAILABLE = 4095
private const val WGS84_ANGLE_UNAVAILABLE = 3601
private const val ANGLE_CONFIDENCE_UNAVAILABLE = 127
private const val SPEED_OUT_OF_RANGE = 16382
private const val SPEED_CONFIDENCE_UNAVAILABLE = 127
private const val ACCEL_UNAVAILABLE = 161
private const val ACCEL_CONFIDENCE_UNAVAILABLE = 102
private const val ALTITUDE_UNAVAILABLE = 800001
private const val ALTITUDE_CONFIDENCE_UNAVAILABLE = 15
/**
* Android's accuracy is a 68 % radius; the confidence ellipse is 95 %. For a circular 2-D error
* the ratio is about 1.62, the same factor [com.hawhamburg.micr0bu.data.transport.GnPositionVector]
* uses for its PAI bound.
*/
private const val ACCURACY_68_TO_95 = 1.62
private const val ENCODE_BUFFER_BYTES = 64
fun encode(vam: VamContent): ByteArray {
val w = BitWriter(ENCODE_BUFFER_BYTES)
// VAM ::= SEQUENCE { header, vam } -- not extensible
// ItsPduHeader
w.putBits(PROTOCOL_VERSION, 8)
w.putBits(MESSAGE_ID_VAM, 8)
w.putBits(vam.stationId and 0xFFFFFFFFL, 32)
// VruAwareness ::= SEQUENCE { generationDeltaTime, vamParameters }
w.putBits(CamUperCodec.generationDeltaTime(vam.timestamp), 16)
// VamParameters ::= SEQUENCE { basic, hf, lf OPT, clusterInfo OPT, clusterOp OPT, motion OPT, ... }
w.putBits(0, 1) // extension bit
w.putBits(if (vam.includeLowFrequency) 0b1000 else 0b0000, 4)
// BasicContainer ::= SEQUENCE { stationType, referencePosition, ... }
w.putBits(0, 1)
w.putBits(StationType.CYCLIST, 8)
// ReferencePositionWithConfidence ::= SEQUENCE { latitude, longitude, ellipse, altitude }
w.putBits(latitude(vam.latitude) + 900_000_000L, 31)
w.putBits(longitude(vam.longitude) + 1_800_000_000L, 32)
val semiAxis = semiAxisCm(vam.accuracyM)
w.putBits(semiAxis, 12) // semiMajorAxisLength
w.putBits(semiAxis, 12) // semiMinorAxisLength
// Circular error: the orientation of the major axis says nothing, so it is unavailable.
w.putBits(WGS84_ANGLE_UNAVAILABLE, 12)
// Altitude: GnssReading carries no "has altitude" flag, so an honest unavailable.
w.putBits(ALTITUDE_UNAVAILABLE + 100_000, 20)
w.putBits(ALTITUDE_CONFIDENCE_UNAVAILABLE, 4)
// VruHighFrequencyContainer ::= SEQUENCE { heading, speed, longitudinalAcceleration, 11 OPTIONAL, ... }
w.putBits(0, 1)
w.putBits(0, 11)
w.putBits(headingDeciDeg(vam.headingDeg), 12)
w.putBits(ANGLE_CONFIDENCE_UNAVAILABLE - 1, 7) // Wgs84AngleConfidence (1..127)
w.putBits(speedCms(vam.speedMps), 14)
w.putBits(SPEED_CONFIDENCE_UNAVAILABLE - 1, 7) // SpeedConfidence (1..127)
w.putBits(accelDeciMps2(vam.accelerationMps2) + 160, 9)
w.putBits(ACCEL_CONFIDENCE_UNAVAILABLE, 7)
if (vam.includeLowFrequency) {
// VruLowFrequencyContainer ::= SEQUENCE { profileAndSubprofile, sizeClass OPT, exteriorLights OPT, ... }
w.putBits(0, 1)
w.putBits(0b10, 2)
// VruProfileAndSubprofile ::= CHOICE { pedestrian, bicyclistAndLightVruVehicle, motorcyclist, animal, ... }
w.putBits(0, 1)
w.putBits(PROFILE_BICYCLIST_INDEX, 2)
w.putBits(SUBPROFILE_BICYCLIST, 4)
w.putBits(SIZE_CLASS_LOW, 4)
}
return w.toByteArray()
}
private fun latitude(deg: Double): Long =
if (deg.isFinite()) (deg * 1e7).roundToLong().coerceIn(-900_000_000L, 900_000_000L) else 900_000_001L
private fun longitude(deg: Double): Long =
if (deg.isFinite()) (deg * 1e7).roundToLong().coerceIn(-1_799_999_999L, 1_800_000_000L) else 1_800_000_001L
private fun semiAxisCm(accuracyM: Float?): Int {
if (accuracyM == null || !accuracyM.isFinite() || accuracyM <= 0f) return SEMI_AXIS_UNAVAILABLE
val cm = (accuracyM * ACCURACY_68_TO_95 * 100).roundToInt()
return if (cm >= SEMI_AXIS_OUT_OF_RANGE) SEMI_AXIS_OUT_OF_RANGE else cm.coerceAtLeast(1)
}
private fun headingDeciDeg(deg: Double): Int =
if (deg.isFinite()) Math.floorMod((deg * 10).roundToInt(), 3600) else WGS84_ANGLE_UNAVAILABLE
private fun speedCms(mps: Double): Int =
if (mps.isFinite()) (mps * 100).roundToInt().coerceIn(0, SPEED_OUT_OF_RANGE) else 16383
private fun accelDeciMps2(mps2: Double?): Int =
if (mps2 == null || !mps2.isFinite()) ACCEL_UNAVAILABLE else (mps2 * 10).roundToInt().coerceIn(-160, 160)
}
@@ -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
@@ -10,21 +10,20 @@ import kotlin.math.abs
* This class only does the sensor-fusion-into-CAM-fields part, independent of the wire protocol
* to the ESP32-C5. Live flow, driven by [com.hawhamburg.micr0bu.service.CamTransmitLoop]:
*
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `UsbSerialTransport` (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,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,79 +0,0 @@
package com.hawhamburg.micr0bu.domain.log
/**
* Which ITS message a received PDU is, for the V2X data logger.
*
* The logger records every message it hears, including ones the app has no decoder for (MAPEM,
* VAM), so classification cannot depend on a codec. It reads the two things every ETSI ITS PDU
* has in common instead: the `ItsPduHeader` at the start of the UPER bytes
* (`protocolVersion` 8 bits, `messageID` 8 bits, `stationID` 32 bits, none of it extensible, so
* it sits byte-aligned at the front), and the BTP destination port the transport reports.
*
* messageID is the primary source. The port is the fallback for a payload too short to carry a
* header. Mind the crossover: SPATEM is messageID 4 on port 2004 but MAPEM is messageID 5 on port
* 2003; the two numbering schemes are unrelated.
*/
enum class ItsMessageKind(val label: String, val messageId: Int, val btpPort: Int?) {
DENM("DENM", 1, 2002),
CAM("CAM", 2, 2001),
SPATEM("SPATEM", 4, 2004),
MAPEM("MAPEM", 5, 2003),
CPM("CPM", 14, null),
VAM("VAM", 16, 2018),
OTHER("OTHER", -1, null);
companion object {
/** The five kinds the logger counts and shows on screen. */
val TRACKED = listOf(CAM, DENM, SPATEM, MAPEM, VAM)
fun fromMessageId(id: Int): ItsMessageKind? = entries.firstOrNull { it.messageId == id && it != OTHER }
fun fromBtpPort(port: Int): ItsMessageKind? = entries.firstOrNull { it.btpPort == port }
/** Matches the `v2x-uca/output/json/<name>` suffix, for the CiT One's processed topics. */
fun fromProcessedTopicName(name: String): ItsMessageKind? = when (name) {
"cam" -> CAM
"denm" -> DENM
"spat" -> SPATEM
"map" -> MAPEM
"cpm" -> CPM
else -> null
}
}
}
/** The fixed 6-byte header at the start of every ETSI ITS PDU. */
data class ItsPduHeader(val protocolVersion: Int, val messageId: Int, val stationId: Long) {
companion object {
const val SIZE = 6
/** Null when [uper] is too short to hold a header. */
fun parse(uper: ByteArray): ItsPduHeader? {
if (uper.size < SIZE) return null
var station = 0L
for (i in 2 until SIZE) station = (station shl 8) or (uper[i].toLong() and 0xFF)
return ItsPduHeader(
protocolVersion = uper[0].toInt() and 0xFF,
messageId = uper[1].toInt() and 0xFF,
stationId = station,
)
}
}
}
/** What [classifyItsPdu] worked out about one received PDU. */
data class ItsClassification(val kind: ItsMessageKind, val messageId: Int?, val stationId: Long?)
/**
* Classifies [uper], preferring its header's messageID over [btpPort].
*
* A message whose id and port disagree is classified by the id, since the id is what the sender
* actually put in the PDU; the port is only where it happened to arrive.
*/
fun classifyItsPdu(uper: ByteArray, btpPort: Int?): ItsClassification {
val header = ItsPduHeader.parse(uper)
val kind = header?.let { ItsMessageKind.fromMessageId(it.messageId) }
?: btpPort?.let { ItsMessageKind.fromBtpPort(it) }
?: ItsMessageKind.OTHER
return ItsClassification(kind, header?.messageId, header?.stationId)
}
@@ -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,231 +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()
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
}
@@ -1,60 +0,0 @@
package com.hawhamburg.micr0bu.domain.vam
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
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
* (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).
*
* Pure and clock-free (callers pass times in ms), so it can be tested without Android.
*/
class VamGenerationRules {
data class Kinematics(val latitude: Double, val longitude: Double, val speedMps: Double, val headingDeg: Double)
private var last: Kinematics? = null
private var lastAtMs = 0L
private var lastLowFrequencyAtMs: Long? = null
/** True if a VAM is due at [nowMs] for the VRU now at [now]. */
fun due(nowMs: Long, now: Kinematics): Boolean {
val previous = last ?: return true
val elapsed = nowMs - lastAtMs
if (elapsed < T_GEN_VAM_MIN_MS) return false
if (elapsed > T_GEN_VAM_MAX_MS) return true // item 1
if (GeoMath.haversineMeters(now.latitude, now.longitude, previous.latitude, previous.longitude) >
MIN_POSITION_CHANGE_M) return true // item 2
if (abs(now.speedMps - previous.speedMps) > MIN_SPEED_CHANGE_MPS) return true // item 3
val headingDelta = abs(((now.headingDeg - previous.headingDeg + 180.0) % 360.0 + 360.0) % 360.0 - 180.0)
return headingDelta > MIN_ORIENTATION_CHANGE_DEG // item 4
}
/** True if the VAM sent at [nowMs] carries the low-frequency container (first VAM, then every T_GenVamLFMin). */
fun includeLowFrequency(nowMs: Long): Boolean =
lastLowFrequencyAtMs.let { it == null || nowMs - it >= T_GEN_VAM_LF_MIN_MS }
/** Records that a VAM went out at [nowMs] for [sent], with or without the low-frequency container. */
fun onSent(nowMs: Long, sent: Kinematics, withLowFrequency: Boolean) {
last = sent
lastAtMs = nowMs
if (withLowFrequency) lastLowFrequencyAtMs = nowMs
}
fun reset() {
last = null
lastAtMs = 0L
lastLowFrequencyAtMs = null
}
companion object {
const val T_GEN_VAM_MIN_MS = 100L
const val T_GEN_VAM_MAX_MS = 5_000L
const val T_GEN_VAM_LF_MIN_MS = 2_000L
const val MIN_POSITION_CHANGE_M = 4.0
const val MIN_SPEED_CHANGE_MPS = 0.5
const val MIN_ORIENTATION_CHANGE_DEG = 4.0
}
}
@@ -1,20 +1,15 @@
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
import com.hawhamburg.micr0bu.data.transport.GnPositionVector
import com.hawhamburg.micr0bu.data.mqtt.ObuHardwarePreferences
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.OutgoingIts
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.data.transport.UsbSerialTransport
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
@@ -26,7 +21,6 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
@@ -55,8 +49,7 @@ import javax.inject.Singleton
@Singleton
class CamPinger @Inject constructor(
@ApplicationContext private val context: Context,
private val esp32Link: Esp32Link,
private val prefs: ObuHardwarePreferences,
private val usbSerialTransport: UsbSerialTransport,
private val codec: RealAsn1UperCodec,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@@ -64,7 +57,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 +97,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),
)
@@ -129,8 +114,7 @@ class CamPinger @Inject constructor(
// Fixed bench identity on every layer, the link-layer address included, so a ping
// stays recognisable in a capture and never rotates.
val pv = GnPositionVector.fromCam(cam, gnss.accuracyM, OwnStationIds.BENCH_PING_MAC)
val signed = prefs.signOutgoingFlow.first()
if (esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes, pv, gnss.accuracyM, signed))) {
if (usbSerialTransport.sendCamTx(bytes, pv)) {
_sentCount.update { it + 1 }
}
}
@@ -150,7 +134,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,26 +1,18 @@
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
import com.hawhamburg.micr0bu.data.cam.PseudonymManager
import com.hawhamburg.micr0bu.data.mqtt.ObuHardwarePreferences
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.data.transport.GnPositionVector
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingIts
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.data.transport.UsbSerialTransport
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
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
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -53,19 +45,12 @@ import javax.inject.Singleton
* [com.hawhamburg.micr0bu.domain.detection.EventDetector] stream that already drives trip event
* logging). Both rate figures are placeholders pending real-world tuning, per
* [CamTransmitConfig]'s own disclaimer.
*
* ## CAM or VAM
* Settings chooses what goes out ([OutgoingMessage]). CAM follows the rate policy above. VAM is
* checked every [VAM_TICK_MS] against the generation rules of TS 103 300-3 clause 6.4
* ([VamGenerationRules]) and sent when one fires, from the same GNSS fix, pseudonym and position
* vector a CAM would use. Whether either is signed is the "Sign outgoing messages" setting; the
* micrOBU does the signing ([Esp32Link]).
*/
@Singleton
class CamTransmitLoop @Inject constructor(
@ApplicationContext private val context: Context,
private val obuHardwarePrefs: ObuHardwarePreferences,
private val esp32Link: Esp32Link,
private val usbSerialTransport: UsbSerialTransport,
private val codec: RealAsn1UperCodec,
private val pseudonymManager: PseudonymManager,
) {
@@ -76,25 +61,19 @@ 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]. */
@Volatile private var previousGnss: GnssReading? = null
@Volatile private var outgoing: OutgoingMessage = OutgoingMessage.CAM
@Volatile private var signOutgoing: Boolean = true
private val vamRules = VamGenerationRules()
/**
* Call when a braking/turning/stopping event fires during an active trip — bumps the CAM
* rate to [CamTransmitConfig.elevatedRateHz] for [ELEVATED_HOLD_MS] so nearby stations get
* 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
}
/**
@@ -106,7 +85,6 @@ class CamTransmitLoop @Inject constructor(
if (job?.isActive == true) return
elevatedUntilMs = 0L
previousGnss = null
vamRules.reset()
job = scope.launch {
obuHardwarePrefs.obuHardwareFlow.collectLatest { hardware ->
if (hardware != ObuHardware.ESP32_C5) return@collectLatest
@@ -123,73 +101,25 @@ 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 { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
launch {
obuHardwarePrefs.outgoingMessageFlow.collect {
if (it != outgoing) vamRules.reset()
outgoing = it
}
}
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
while (true) {
val gnss = latestGnss
if (gnss != null) {
when (outgoing) {
OutgoingMessage.CAM -> sendCam(gnss)
OutgoingMessage.VAM -> sendVamIfDue(gnss)
}
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
// rotation fall cleanly between two frames instead of inside one.
val pseudonym = pseudonymManager.current()
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the
// outgoing CAM is: acceleration below still differences wall-clock samples.
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
val bytes = codec.encodeCam(cam)
usbSerialTransport.sendCamTx(bytes, GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac))
}
delay(if (outgoing == OutgoingMessage.VAM) VAM_TICK_MS else (1000.0 / currentRateHz(gnss)).toLong())
delay((1000.0 / currentRateHz(gnss)).toLong())
}
}
private suspend fun sendCam(gnss: GnssReading) {
// 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))
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 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)
// 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 withLowFrequency = vamRules.includeLowFrequency(now)
val bytes = VamUperCodec.encode(VamContent(
stationId = pseudonym.stationId,
timestamp = cam.timestamp,
latitude = cam.latitude,
longitude = cam.longitude,
accuracyM = gnss.accuracyM,
speedMps = cam.speedMps,
headingDeg = cam.headingDeg,
accelerationMps2 = cam.accelerationMps2,
includeLowFrequency = withLowFrequency,
))
val handedOver = esp32Link.send(OutgoingIts(OutgoingMessage.VAM, bytes,
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
if (handedOver) vamRules.onSent(now, kinematics, withLowFrequency)
}
/**
* Along-track acceleration in m/s², from the change in GNSS speed since the previous fix.
*
@@ -209,31 +139,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
}
@@ -244,9 +158,6 @@ class CamTransmitLoop @Inject constructor(
companion object {
private const val ELEVATED_HOLD_MS = 5_000L
/** How often VAM generation rules are checked: T_GenVamMin, TS 103 300-3 Table 16. */
private const val VAM_TICK_MS = VamGenerationRules.T_GEN_VAM_MIN_MS
/** Below this gap, GNSS speed noise divided by a tiny dt produces absurd accelerations. */
private const val MIN_ACCEL_DT_SEC = 0.2
@@ -1,135 +0,0 @@
package com.hawhamburg.micr0bu.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.hawhamburg.micr0bu.MainActivity
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.log.V2xLogger
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* Keeps the process alive, and the CPU awake, while [V2xLogger] records.
*
* The logger does the work; this exists only because a log is most useful on a drive, with the
* screen off, and a process with no foreground service is one the system may kill and whose GNSS
* callbacks it throttles. Same shape as [TripRecordingService], which does this for trips.
*
* Stops itself when the logger stops, including when the logger stops on a write failure.
*/
@AndroidEntryPoint
class V2xLogService : Service() {
@Inject lateinit var logger: V2xLogger
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.Default + job)
private var watchJob: Job? = null
private var wakeLock: PowerManager.WakeLock? = null
override fun onCreate() {
super.onCreate()
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
NotificationChannel(CHANNEL_ID, "V2X logging", NotificationManager.IMPORTANCE_LOW).apply {
description = "Shown while the developer V2X data logger is recording"
}
)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> begin()
ACTION_STOP -> end()
}
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
wakeLock?.let { if (it.isHeld) it.release() }
job.cancel()
super.onDestroy()
}
private fun begin() {
// Foreground first: Android allows five seconds from startForegroundService.
startForeground(NOTIFICATION_ID, notification(0), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
wakeLock = (getSystemService(POWER_SERVICE) as PowerManager)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "micr0bu:V2xLog")
.also { it.acquire() }
logger.start()
if (!logger.state.value.active) { // the file could not be created; the screen shows why
end()
return
}
watchJob?.cancel()
watchJob = scope.launch {
logger.state.collect { state ->
if (!state.active) {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
} else {
(getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
.notify(NOTIFICATION_ID, notification(state.total))
}
}
}
}
private fun end() {
scope.launch {
logger.stop()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
private fun notification(messages: Int) =
NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Logging V2X messages")
.setContentText("$messages messages recorded")
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setContentIntent(
PendingIntent.getActivity(
this, 0,
Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
},
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
)
.build()
companion object {
const val ACTION_START = "com.hawhamburg.micr0bu.V2X_LOG_START"
const val ACTION_STOP = "com.hawhamburg.micr0bu.V2X_LOG_STOP"
private const val NOTIFICATION_ID = 9002
private const val CHANNEL_ID = "v2x_logging"
fun start(context: Context) = ContextCompat.startForegroundService(
context, Intent(context, V2xLogService::class.java).setAction(ACTION_START)
)
fun stop(context: Context) {
context.startService(Intent(context, V2xLogService::class.java).setAction(ACTION_STOP))
}
}
}
@@ -15,14 +15,11 @@ 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
import androidx.compose.material.icons.filled.SensorsOff
import androidx.compose.material.icons.filled.Usb
import androidx.compose.material.icons.filled.BluetoothDisabled
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.UsbOff
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material.icons.filled.WifiOff
@@ -39,12 +36,10 @@ 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.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
private val GreenActive = Color(0xFF4CAF50)
@@ -58,12 +53,7 @@ fun StatusTopBar(
state: SensorUiState,
mqttConnectionState: MqttConnectionState,
isEsp32: Boolean = false,
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,
usbSerialState: UsbSerialState = UsbSerialState.DISCONNECTED,
) {
TopAppBar(
title = {
@@ -103,18 +93,7 @@ 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)
ObuStatusIcon(mqttConnectionState, isEsp32, usbSerialState)
}
},
colors = TopAppBarDefaults.topAppBarColors(
@@ -127,21 +106,20 @@ fun StatusTopBar(
* OBU link indicator. Which transport it reflects depends on the selected hardware: the CiT One
* reaches the phone over MQTT (Wi-Fi / USB-C tethering), the ESP32-C5 over a USB-serial link with
* no broker at all - so on that path [mqttConnectionState] is permanently DISCONNECTED and would
* report the OBU as offline while CAMs were streaming in. Uses a USB or Bluetooth glyph there
* rather than the Wi-Fi one, since that is literally what the connection is.
* report the OBU as offline while CAMs were streaming in. Uses a USB glyph there rather than the
* Wi-Fi one, since that is literally what the connection is.
*/
@Composable
private fun ObuStatusIcon(
mqttState: MqttConnectionState,
isEsp32: Boolean,
esp32LinkState: Esp32LinkState,
esp32Bluetooth: Boolean,
usbSerialState: UsbSerialState,
) {
val state = if (isEsp32) esp32LinkState.asConnectionState() else mqttState
val linkUp = state == MqttConnectionState.CONNECTED || state == MqttConnectionState.CONNECTING
val state = if (isEsp32) usbSerialState.asConnectionState() else mqttState
val icon = when {
isEsp32 && esp32Bluetooth -> if (linkUp) Icons.Default.Bluetooth else Icons.Default.BluetoothDisabled
isEsp32 -> if (linkUp) Icons.Default.Usb else Icons.Default.UsbOff
isEsp32 && state == MqttConnectionState.CONNECTED -> Icons.Default.Usb
isEsp32 && state == MqttConnectionState.CONNECTING -> Icons.Default.Usb
isEsp32 -> Icons.Default.UsbOff
state == MqttConnectionState.CONNECTED ||
state == MqttConnectionState.CONNECTING -> Icons.Default.Wifi
else -> Icons.Default.WifiOff
@@ -216,10 +194,10 @@ private fun RecordingPulse() {
* Maps the ESP32-C5 serial link's lifecycle onto the MQTT connection vocabulary this bar's colour
* and pulse logic already speaks, so one indicator serves both transports.
*/
private fun Esp32LinkState.asConnectionState(): MqttConnectionState = when (this) {
Esp32LinkState.CONNECTED -> MqttConnectionState.CONNECTED
Esp32LinkState.DEVICE_ATTACHED,
Esp32LinkState.PERMISSION_REQUESTED -> MqttConnectionState.CONNECTING
Esp32LinkState.ERROR -> MqttConnectionState.ERROR
Esp32LinkState.DISCONNECTED -> MqttConnectionState.DISCONNECTED
private fun UsbSerialState.asConnectionState(): MqttConnectionState = when (this) {
UsbSerialState.CONNECTED -> MqttConnectionState.CONNECTED
UsbSerialState.DEVICE_ATTACHED,
UsbSerialState.PERMISSION_REQUESTED -> MqttConnectionState.CONNECTING
UsbSerialState.ERROR -> MqttConnectionState.ERROR
UsbSerialState.DISCONNECTED -> MqttConnectionState.DISCONNECTED
}
@@ -34,8 +34,6 @@ sealed class Screen(val route: String, val labelRes: Int) {
data object Connection : Screen("connection", R.string.nav_connection)
data object Map : Screen("map", R.string.map_title)
data object MqttViewer : Screen("mqtt_viewer", R.string.nav_v2x)
/** Full-screen V2X live map, opened from the V2X Monitor's map button. */
data object V2xMap : Screen("v2x_map", R.string.v2x_map_title)
// Phase A — Trip Recording
data object TripHistory : Screen("trip_history", R.string.nav_trips)
@@ -51,7 +49,6 @@ sealed class Screen(val route: String, val labelRes: Int) {
data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts)
data object SettingsDeveloper : Screen("settings/developer", R.string.settings_developer)
data object SettingsV2xLog : Screen("settings/developer/v2x_log", R.string.v2xlog_title)
data object SettingsAbout : Screen("settings/about", R.string.settings_about)
}
@@ -86,7 +83,6 @@ private fun Screen.ownsRoute(route: String?): Boolean {
route == Screen.Map.route ||
route == Screen.Sensors.route
Screen.Record -> route == Screen.Log.route
Screen.MqttViewer -> route == Screen.V2xMap.route
else -> false
}
}
@@ -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
@@ -46,9 +44,7 @@ import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.TransportType
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import androidx.compose.material.icons.filled.Bluetooth
import com.hawhamburg.micr0bu.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
private val UsbGreen = Color(0xFF4CAF50)
@@ -69,11 +65,7 @@ fun ConnectionSetupScreen(
val activeTransport by viewModel.activeTransport.collectAsState()
val mqttPrefs by viewModel.mqttPrefs.collectAsState()
val obuHardware by viewModel.obuHardware.collectAsState()
val esp32LinkState by viewModel.esp32LinkState.collectAsState()
val esp32Transport by viewModel.esp32Transport.collectAsState()
val esp32Detail by viewModel.esp32Detail.collectAsState()
val stationStatus by viewModel.stationStatus.collectAsState()
val signOutgoing by viewModel.signOutgoing.collectAsState()
val usbSerialState by viewModel.usbSerialState.collectAsState()
val isConnected = connectionState == MqttConnectionState.CONNECTED
val isConnecting = connectionState == MqttConnectionState.CONNECTING
@@ -237,22 +229,22 @@ fun ConnectionSetupScreen(
}
} else {
// ── ESP32-C5 real connection card (Phase 03) ────────────────────────
// Backed by Esp32Link: USB (UsbSerialTransport, native USB Serial/JTAG CDC-ACM - see
// its KDoc for the VID/PID and native-vs-UART-bridge port note) or BLE (BleLinkTransport).
val isEspConnected = esp32LinkState == Esp32LinkState.CONNECTED
val isEspBusy = esp32LinkState == Esp32LinkState.DEVICE_ATTACHED ||
esp32LinkState == Esp32LinkState.PERMISSION_REQUESTED
// Backed by UsbSerialTransport (native USB Serial/JTAG CDC-ACM link) - see that
// class's KDoc for the VID/PID (0x303A/0x1001) and native-vs-UART-bridge port note.
val isEspConnected = usbSerialState == UsbSerialState.CONNECTED
val isEspBusy = usbSerialState == UsbSerialState.DEVICE_ATTACHED ||
usbSerialState == UsbSerialState.PERMISSION_REQUESTED
val espContainerColor = when {
isEspConnected -> UsbGreenBg
isEspBusy -> UsbAmberBg
else -> UsbGrayBg
}
val (espColor, espStateLabel) = when (esp32LinkState) {
Esp32LinkState.CONNECTED -> UsbGreen to stringResource(R.string.conn_esp32_state_connected)
Esp32LinkState.DEVICE_ATTACHED -> UsbAmber to stringResource(R.string.conn_esp32_state_device_attached)
Esp32LinkState.PERMISSION_REQUESTED -> UsbAmber to stringResource(R.string.conn_esp32_state_permission_requested)
Esp32LinkState.ERROR -> Color(0xFFFF5252) to stringResource(R.string.conn_esp32_state_error)
Esp32LinkState.DISCONNECTED -> UsbGray to stringResource(R.string.conn_esp32_state_disconnected)
val (espColor, espStateLabel) = when (usbSerialState) {
UsbSerialState.CONNECTED -> UsbGreen to stringResource(R.string.conn_esp32_state_connected)
UsbSerialState.DEVICE_ATTACHED -> UsbAmber to stringResource(R.string.conn_esp32_state_device_attached)
UsbSerialState.PERMISSION_REQUESTED -> UsbAmber to stringResource(R.string.conn_esp32_state_permission_requested)
UsbSerialState.ERROR -> Color(0xFFFF5252) to stringResource(R.string.conn_esp32_state_error)
UsbSerialState.DISCONNECTED -> UsbGray to stringResource(R.string.conn_esp32_state_disconnected)
}
Card(
@@ -265,7 +257,7 @@ fun ConnectionSetupScreen(
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(
if (esp32Transport == Esp32Transport.BLE) Icons.Default.Bluetooth else Icons.Default.Usb,
Icons.Default.Usb,
contentDescription = null,
tint = espColor,
modifier = Modifier.size(20.dp),
@@ -293,69 +285,11 @@ fun ConnectionSetupScreen(
Text(espStateLabel, style = MaterialTheme.typography.bodySmall, color = espColor)
}
Text(
stringResource(
if (esp32Transport == Esp32Transport.BLE) R.string.conn_esp32_via_ble else R.string.conn_esp32_via_usb
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
// Pairing passkey, provisioning progress, or why the micrOBU refused something.
esp32Detail?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = UsbAmber)
}
if (isEspConnected) {
stationStatus?.let { s ->
Text(
stringResource(
R.string.conn_esp32_signing,
if (signOutgoing) stringResource(R.string.conn_esp32_signing_on) else stringResource(R.string.conn_esp32_signing_off),
s.tickets, s.signedMessages, s.signRefused, s.radioSubmitted,
),
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,
)
}
}
}
}
Spacer(Modifier.height(12.dp))
if (isEspConnected || isEspBusy) {
if (isEspConnected) {
OutlinedButton(
onClick = { viewModel.disconnectEsp32() },
onClick = { viewModel.disconnectUsbSerial() },
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.outlinedButtonColors(
contentColor = Color(0xFFFF5252),
@@ -363,13 +297,13 @@ fun ConnectionSetupScreen(
) {
Icon(Icons.Default.LinkOff, null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
// While connecting (BLE retries until it succeeds) this cancels the attempt.
Text(stringResource(if (isEspConnected) R.string.conn_disconnect else R.string.conn_esp32_cancel))
Text(stringResource(R.string.conn_disconnect))
}
} else {
Button(
onClick = { viewModel.connectEsp32() },
onClick = { viewModel.connectUsbSerial() },
modifier = Modifier.fillMaxWidth(),
enabled = !isEspBusy,
) {
Icon(Icons.Default.Link, null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
@@ -60,15 +60,12 @@ import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.TransportType
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.UsbSerialState
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
@@ -81,14 +78,12 @@ fun DashboardScreen(
mqttConnectionState: MqttConnectionState,
activeTransport: TransportType = TransportType.USB_C,
obuHardware: ObuHardware = ObuHardware.CIT_ONE,
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
esp32Bluetooth: Boolean = false,
usbSerialState: UsbSerialState = UsbSerialState.DISCONNECTED,
usbCableConnected: Boolean = false,
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,
@@ -286,14 +281,14 @@ fun DashboardScreen(
// even once the serial link is actually up.
val isEsp32 = obuHardware == ObuHardware.ESP32_C5
val mqttConnected = mqttConnectionState == MqttConnectionState.CONNECTED
val obuConnected = if (isEsp32) esp32LinkState == Esp32LinkState.CONNECTED else mqttConnected
val transportIcon = if (isEsp32 && esp32Bluetooth) Icons.Default.Bluetooth else when (activeTransport) {
val obuConnected = if (isEsp32) usbSerialState == UsbSerialState.CONNECTED else mqttConnected
val transportIcon = when (activeTransport) {
TransportType.USB_C -> Icons.Default.Usb
TransportType.USB_SERIAL -> Icons.Default.Usb
TransportType.WIFI -> Icons.Default.Wifi
TransportType.BLUETOOTH -> Icons.Default.Bluetooth
}
val transportInactiveIcon = if (isEsp32 && esp32Bluetooth) Icons.Default.BluetoothDisabled else when (activeTransport) {
val transportInactiveIcon = when (activeTransport) {
TransportType.USB_C -> Icons.Default.Usb
TransportType.USB_SERIAL -> Icons.Default.Usb
TransportType.WIFI -> Icons.Default.WifiOff
@@ -329,12 +324,12 @@ fun DashboardScreen(
)
Text(
text = if (isEsp32) {
when (esp32LinkState) {
Esp32LinkState.CONNECTED -> stringResource(R.string.conn_esp32_state_connected)
Esp32LinkState.DEVICE_ATTACHED -> stringResource(R.string.conn_esp32_state_device_attached)
Esp32LinkState.PERMISSION_REQUESTED -> stringResource(R.string.conn_esp32_state_permission_requested)
Esp32LinkState.ERROR -> stringResource(R.string.conn_esp32_state_error)
Esp32LinkState.DISCONNECTED -> stringResource(R.string.dash_tap_to_connect)
when (usbSerialState) {
UsbSerialState.CONNECTED -> stringResource(R.string.conn_esp32_state_connected)
UsbSerialState.DEVICE_ATTACHED -> stringResource(R.string.conn_esp32_state_device_attached)
UsbSerialState.PERMISSION_REQUESTED -> stringResource(R.string.conn_esp32_state_permission_requested)
UsbSerialState.ERROR -> stringResource(R.string.conn_esp32_state_error)
UsbSerialState.DISCONNECTED -> stringResource(R.string.dash_tap_to_connect)
}
} else when (mqttConnectionState) {
MqttConnectionState.CONNECTED -> stringResource(R.string.dash_mqtt_connected)
@@ -367,16 +362,15 @@ fun DashboardScreen(
TransportChip(
label = stringResource(R.string.dash_transport_usb_serial),
icon = Icons.Default.Usb,
active = !esp32Bluetooth,
active = activeTransport == TransportType.USB_SERIAL,
hasCable = usbCableConnected,
)
}
TransportChip(
label = stringResource(R.string.dash_transport_bt),
icon = Icons.Default.Bluetooth,
active = isEsp32 && esp32Bluetooth,
// Only the ESP32-C5 has a BLE link; the CiT One has none.
dimmed = !isEsp32,
active = activeTransport == TransportType.BLUETOOTH,
dimmed = true, // Phase 03 — production BT transport still under discussion
)
}
}
@@ -412,18 +406,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 +635,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 +659,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 +687,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 +704,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 +736,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 {
@@ -29,11 +29,9 @@ import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material.icons.filled.Map
import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material.icons.filled.VerticalAlignBottom
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
@@ -47,7 +45,6 @@ import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
@@ -72,7 +69,7 @@ import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.mqtt.MqttMessage
import com.hawhamburg.micr0bu.data.transport.EspLinkStatus
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.domain.cam.CamParser
import com.hawhamburg.micr0bu.domain.cam.StationType
import com.hawhamburg.micr0bu.domain.denm.DenmParser
@@ -90,15 +87,11 @@ import java.util.Date
import java.util.Locale
/**
* View toggle for [TopicListPane]: decoded CAM/DENM traffic (LIST) or the raw MQTT topic list
* (TOPICS, CiT One only - there is no broker on the ESP32-C5 path).
*
* The live map used to be a third mode here. It is now its own full-screen destination
* ([V2xMapScreen]), reached from the map button in this screen's header: sharing the screen with
* the alert panel and the TX cards left the map about a third of a phone display tall, which is
* not enough to see where anything is relative to anything else.
* View toggle for [TopicListPane]: decoded CAM/DENM traffic (LIST), the raw MQTT topic list
* (TOPICS, CiT One only - there is no broker on the ESP32-C5 path), or the V2X live map
* (MAP, Section 13).
*/
private enum class TopicViewMode { LIST, TOPICS }
private enum class TopicViewMode { LIST, TOPICS, MAP }
private val timeFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
@@ -123,7 +116,6 @@ private val WarningRedBg = Color(0xFF3A0A0A)
@Composable
fun MqttTopicViewerScreen(
viewModel: MqttViewModel = hiltViewModel(),
onOpenMap: () -> Unit = {},
) {
val connectionState by viewModel.connectionState.collectAsState()
val topicMessages by viewModel.topicMessages.collectAsState()
@@ -138,7 +130,7 @@ fun MqttTopicViewerScreen(
val ownCamPosition by viewModel.ownCamPosition.collectAsState()
// Engine road users PLUS roadside units - the engine deliberately does not track RSUs.
val remoteCamPositions by viewModel.stationsInRange.collectAsState()
val esp32LinkState by viewModel.esp32LinkState.collectAsState()
val usbSerialState by viewModel.usbSerialState.collectAsState()
val camPingerActive by viewModel.camPingerActive.collectAsState()
val camPingerSentCount by viewModel.camPingerSentCount.collectAsState()
val camPingerHasFix by viewModel.camPingerHasFix.collectAsState()
@@ -163,36 +155,10 @@ fun MqttTopicViewerScreen(
// DISCONNECTED and using it here made the screen report "offline" while CAMs streamed in over
// serial. Everything on this screen that means "is the OBU link up?" follows the serial link
// instead when that hardware is selected.
val effectiveState = if (isEsp32) esp32LinkState.asConnectionState() else connectionState
val effectiveState = if (isEsp32) usbSerialState.asConnectionState() else connectionState
val isConnected = effectiveState == MqttConnectionState.CONNECTED
val isConnecting = effectiveState == MqttConnectionState.CONNECTING
// Disconnecting drops live V2X data and any running log until the OBU is connected again, and
// the icon sits next to the map button, so a stray tap must not do it. Connecting needs no
// confirmation: it cannot lose anything.
var confirmDisconnect by rememberSaveable { mutableStateOf(false) }
if (confirmDisconnect) {
AlertDialog(
onDismissRequest = { confirmDisconnect = false },
title = { Text(stringResource(R.string.mqtt_disconnect_confirm_title)) },
text = { Text(stringResource(R.string.mqtt_disconnect_confirm_text)) },
confirmButton = {
TextButton(onClick = {
confirmDisconnect = false
// Route to whichever transport this hardware actually uses.
if (isEsp32) viewModel.disconnectEsp32() else viewModel.disconnect()
}) {
Text(stringResource(R.string.mqtt_disconnect), color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { confirmDisconnect = false }) {
Text(stringResource(R.string.log_cancel))
}
},
)
}
Column(modifier = Modifier.fillMaxSize()) {
// ── Inline header — replaces the removed inner TopAppBar ──────────────
@@ -227,24 +193,17 @@ fun MqttTopicViewerScreen(
Spacer(Modifier.weight(1f))
}
// Full-screen live map. In the header rather than in the view-mode row below, so it
// is reachable from the message detail pane too and does not move around as the
// available view modes change with the selected hardware.
IconButton(onClick = onOpenMap) {
Icon(
Icons.Default.Map,
contentDescription = stringResource(R.string.v2x_map_title),
tint = MaterialTheme.colorScheme.primary,
)
}
ConnectionChip(effectiveState)
Spacer(Modifier.width(2.dp))
IconButton(
onClick = {
if (isConnected || isConnecting) confirmDisconnect = true
else if (isEsp32) viewModel.connectEsp32()
else viewModel.connect()
// Route to whichever transport this hardware actually uses.
if (isEsp32) {
if (isConnected || isConnecting) viewModel.disconnectUsbSerial()
else viewModel.connectUsbSerial()
} else {
if (isConnected || isConnecting) viewModel.disconnect() else viewModel.connect()
}
},
colors = IconButtonDefaults.iconButtonColors(
contentColor = if (isConnected) ErrorRed else ConnectedGreen,
@@ -277,7 +236,7 @@ fun MqttTopicViewerScreen(
isEsp32 = isEsp32,
denmEvents = denmEvents,
spatIntersections = spatIntersections,
esp32LinkState = esp32LinkState,
usbSerialState = usbSerialState,
camPingerActive = camPingerActive,
camPingerSentCount = camPingerSentCount,
camPingerHasFix = camPingerHasFix,
@@ -318,7 +277,7 @@ private fun TopicListPane(
isEsp32: Boolean = false,
denmEvents: List<com.hawhamburg.micr0bu.domain.denm.DenmEvent> = emptyList(),
spatIntersections: List<com.hawhamburg.micr0bu.domain.spat.SpatIntersection> = emptyList(),
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
usbSerialState: UsbSerialState = UsbSerialState.DISCONNECTED,
camPingerActive: Boolean = false,
camPingerSentCount: Int = 0,
camPingerHasFix: Boolean = false,
@@ -362,7 +321,7 @@ private fun TopicListPane(
// ── CAM Pinger card — ESP32-C5-only manual bench test, mirrors the DENM card above ──
if (showCamPinger) {
CamPingerCard(
usbConnected = esp32LinkState == Esp32LinkState.CONNECTED,
usbConnected = usbSerialState == UsbSerialState.CONNECTED,
pingerActive = camPingerActive,
sentCount = camPingerSentCount,
hasFix = camPingerHasFix,
@@ -376,38 +335,49 @@ private fun TopicListPane(
HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
}
// ── List / Topics toggle ──────────────────────────────────────────────
// ── List / Topics / Map toggle ────────────────────────────────────────────────────
// Decoded traffic is the default on BOTH hardware paths: what a tester wants to see is
// the road users and hazards, not the transport that carried them. The raw MQTT topic
// list stays one tap away on the CiT One path (Section 13 asks for the map "in addition
// to", not instead of, the topic list).
//
// The whole row is hidden on the ESP32-C5 path: there is no broker there, `topics` is
// permanently empty, and a toggle offering a single choice is just noise.
if (!isEsp32) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
ViewModeButton(
label = stringResource(R.string.mqtt_view_list),
selected = viewMode == TopicViewMode.LIST,
) { viewMode = TopicViewMode.LIST }
// to", not instead of, the topic list). It is hidden on the ESP32-C5 path, where there is
// no broker and `topics` is permanently empty.
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
ViewModeButton(
label = stringResource(R.string.mqtt_view_list),
selected = viewMode == TopicViewMode.LIST,
) { viewMode = TopicViewMode.LIST }
if (!isEsp32) {
ViewModeButton(
label = stringResource(R.string.mqtt_view_topics),
selected = viewMode == TopicViewMode.TOPICS,
) { viewMode = TopicViewMode.TOPICS }
}
ViewModeButton(
label = stringResource(R.string.mqtt_view_map),
selected = viewMode == TopicViewMode.MAP,
) { viewMode = TopicViewMode.MAP }
}
// ── Decoded traffic / raw topics ──────────────────────────────────────
// ── Decoded traffic / raw topics / live map ───────────────────────────
// TOPICS can still be the saved selection from a CiT One session after switching hardware
// to the ESP32-C5, where that button no longer exists - fall back to the decoded list
// rather than stranding the user on a pane they can't navigate away from.
val shownMode = if (viewMode == TopicViewMode.TOPICS && isEsp32) TopicViewMode.LIST else viewMode
if (shownMode == TopicViewMode.LIST) {
if (shownMode == TopicViewMode.MAP) {
V2xLiveMapView(
own = ownCamPosition,
remotes = remoteCamPositions,
alerts = useCaseAlerts,
denms = denmEvents,
modifier = Modifier.fillMaxSize(),
)
} else if (shownMode == TopicViewMode.LIST) {
ReceivedCamPane(
own = ownCamPosition,
remotes = remoteCamPositions,
@@ -1243,12 +1213,11 @@ private fun CamPingerCard(
Text(
stringResource(
R.string.mqtt_cam_pinger_fw_counters,
s.txFailures, s.oversizeDrops, s.rxCrcErrors, s.rxQueueDrops,
s.txFailures, s.oversizeDrops, s.rxCrcErrors,
),
style = MaterialTheme.typography.labelSmall,
color = if (s.txFailures > 0 || s.oversizeDrops > 0 || s.rxCrcErrors > 0 ||
s.rxQueueDrops > 0
) ErrorRed else MaterialTheme.colorScheme.onSurfaceVariant,
color = if (s.txFailures > 0 || s.oversizeDrops > 0 || s.rxCrcErrors > 0)
ErrorRed else MaterialTheme.colorScheme.onSurfaceVariant,
fontFamily = FontFamily.Monospace,
)
}
@@ -1497,10 +1466,10 @@ private fun prettyPrintJson(raw: String): String {
* connection UI on this screen already speaks, so one indicator can serve both transports rather
* than duplicating the chip and its colours per hardware type.
*/
private fun Esp32LinkState.asConnectionState(): MqttConnectionState = when (this) {
Esp32LinkState.CONNECTED -> MqttConnectionState.CONNECTED
Esp32LinkState.DEVICE_ATTACHED,
Esp32LinkState.PERMISSION_REQUESTED -> MqttConnectionState.CONNECTING
Esp32LinkState.ERROR -> MqttConnectionState.ERROR
Esp32LinkState.DISCONNECTED -> MqttConnectionState.DISCONNECTED
private fun UsbSerialState.asConnectionState(): MqttConnectionState = when (this) {
UsbSerialState.CONNECTED -> MqttConnectionState.CONNECTED
UsbSerialState.DEVICE_ATTACHED,
UsbSerialState.PERMISSION_REQUESTED -> MqttConnectionState.CONNECTING
UsbSerialState.ERROR -> MqttConnectionState.ERROR
UsbSerialState.DISCONNECTED -> MqttConnectionState.DISCONNECTED
}
@@ -47,10 +47,7 @@ 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.usecase.UseCaseDetectionConfig
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -138,7 +135,7 @@ private fun MenuRow(label: String, onClick: () -> Unit) {
// ── Sub-screen shell ────────────────────────────────────────────────────────
@Composable
internal fun SubScreen(title: String, onBack: () -> Unit, content: @Composable () -> Unit) {
private fun SubScreen(title: String, onBack: () -> Unit, content: @Composable () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
@@ -168,21 +165,13 @@ fun ConnectionSettingsScreen(
onMqttPrefsChange: (MqttPrefs) -> Unit,
obuHardware: ObuHardware = ObuHardware.CIT_ONE,
onObuHardwareChange: (ObuHardware) -> Unit = {},
esp32Transport: Esp32Transport = Esp32Transport.USB,
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,
) {
SubScreen(stringResource(R.string.settings_connection), onBack) {
SectionCard {
// OBU Hardware selector — CiT One / ESP32-C5 (Phase 03, Section 13). The transport
// cards below apply to the CiT One; the ESP32-C5 has its own card (USB-C or BLE,
// CAM or VAM, signing).
// OBU Hardware selector — CiT One / ESP32-C5 (Phase 03, Section 13). Everything
// below (transport, USB-C options) only really applies to CiT One; ESP32-C5 uses
// USB Serial exclusively and has no transport choice to make here.
Text(
stringResource(R.string.settings_obu_hardware),
style = MaterialTheme.typography.labelSmall,
@@ -223,63 +212,6 @@ fun ConnectionSettingsScreen(
}
}
if (obuHardware == ObuHardware.ESP32_C5) {
SectionCard {
TwoWayChoice(
label = stringResource(R.string.settings_esp32_link),
first = stringResource(R.string.settings_transport_usbc),
second = stringResource(R.string.settings_esp32_link_ble),
firstSelected = esp32Transport == Esp32Transport.USB,
onFirst = { onEsp32TransportChange(Esp32Transport.USB) },
onSecond = { onEsp32TransportChange(Esp32Transport.BLE) },
)
if (esp32Transport == Esp32Transport.BLE) {
Text(
stringResource(R.string.settings_esp32_link_ble_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
}
Divider()
TwoWayChoice(
label = stringResource(R.string.settings_esp32_message),
first = stringResource(R.string.settings_esp32_message_cam),
second = stringResource(R.string.settings_esp32_message_vam),
firstSelected = outgoingMessage == OutgoingMessage.CAM,
onFirst = { onOutgoingMessageChange(OutgoingMessage.CAM) },
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,
onCheckedChange = onSignOutgoingChange,
)
Text(
stringResource(R.string.settings_esp32_sign_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
}
}
if (obuHardware == ObuHardware.CIT_ONE) {
SectionCard {
// Active transport selector
@@ -466,7 +398,6 @@ fun DeveloperSettingsScreen(
state: SensorUiState,
onDeveloperMode: (Boolean) -> Unit,
onOpenSensorMonitor: () -> Unit,
onOpenV2xLogger: () -> Unit,
onBack: () -> Unit,
) {
SubScreen(stringResource(R.string.settings_developer), onBack) {
@@ -476,9 +407,6 @@ fun DeveloperSettingsScreen(
// Sensor Monitor lives here rather than in the bottom nav: a live phone-sensor feed is
// a bench-diagnosis tool, not something a rider needs mid-ride.
MenuRow(stringResource(R.string.sensor_monitor_title), onOpenSensorMonitor)
Divider()
// Records every received V2X message to a database file, on either OBU hardware.
MenuRow(stringResource(R.string.v2xlog_title), onOpenV2xLogger)
if (state.developerMode) {
Divider()
DisabledRow(stringResource(R.string.settings_wifi), stringResource(R.string.settings_wifi_val))
@@ -503,7 +431,7 @@ fun AboutSettingsScreen(onBack: () -> Unit) {
// ── Internal components ─────────────────────────────────────────────────────
@Composable
internal fun SectionCard(content: @Composable () -> Unit) {
private fun SectionCard(content: @Composable () -> Unit) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
@@ -683,45 +611,11 @@ private fun LanguageSection() {
}
}
/** A labelled pair of outlined buttons, the selected one filled — the style of the OBU hardware picker. */
@Composable
private fun TwoWayChoice(
label: String,
first: String,
second: String,
firstSelected: Boolean,
onFirst: () -> Unit,
onSecond: () -> 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 ((text, selected, onClick) in listOf(Triple(first, firstSelected, onFirst), Triple(second, !firstSelected, onSecond))) {
OutlinedButton(
onClick = onClick,
modifier = Modifier.weight(1f),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
contentColor = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
),
) { Text(text, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal) }
}
}
}
@Composable
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@Composable
internal fun Divider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
private fun Divider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@Composable
private fun SettingToggleRow(
@@ -745,7 +639,7 @@ private fun SettingToggleRow(
}
@Composable
internal fun DisabledRow(label: String, value: String) {
private fun DisabledRow(label: String, value: String) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 10.dp),
horizontalArrangement = Arrangement.SpaceBetween,
@@ -1,13 +1,12 @@
package com.hawhamburg.micr0bu.ui.screens
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.MotionEvent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.GpsOff
@@ -31,44 +30,25 @@ 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
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
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
* ego bike's own position, every currently-tracked remote road user's last-known CAM position,
* every live hazard (DENM) and every signalised intersection heard over SPATEM.
* V2X Monitor live map view (Phase 03, Section 13) — plots the ego bike's own position plus
* every currently-tracked remote road user's last-known CAM position, in addition to (not
* replacing) the raw topic list already on this screen. Reuses the same osmdroid pattern as
* [MapScreen]; unlike that screen, this one has no phone-GNSS-only fallback because [own] here
* always reflects whichever ego source [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository]
* currently trusts (obu_gnss / phone GNSS / CAM-topic-own — see that class's KDoc).
*
* 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
*
* 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 /
* phone GNSS / CAM-topic-own — see that class's KDoc).
*
* **Markers are reused across updates, not rebuilt.** CAMs arrive at up to 10 Hz per station, and
* every arrival recomposes this view; the previous version cleared the overlay list and rebuilt
* every Marker — decoding and mutating a fresh Drawable per marker per update — which is what
* made panning stutter under live traffic. Drawables are now loaded once per level/phase and
* shared (osmdroid sets the icon's bounds on each draw, so sharing one instance across markers is
* safe), and Marker objects are cached by key. The overlay list is still reordered each update,
* which costs nothing: it moves existing references, it does not allocate.
* Remote markers are colored by that station's most severe active alert level, if any, so a
* glance at the map shows not just "who's nearby" but "who's a warning right now" — the same
* severity coloring already used by [UseCaseAlertPanel].
*/
@Composable
fun V2xLiveMapView(
@@ -76,9 +56,6 @@ fun V2xLiveMapView(
remotes: Map<Long, Cam>,
alerts: List<UseCaseAlert>,
denms: List<DenmEvent> = emptyList(),
lights: List<TrafficLight> = emptyList(),
followOwn: Boolean = true,
onUserPanned: () -> Unit = {},
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
@@ -94,18 +71,8 @@ fun V2xLiveMapView(
.mapValues { (_, a) -> a.maxByOrNull { it.alertLevel.ordinal }?.alertLevel }
}
// Loaded once and shared by every marker that needs them. mutate() on the remote pin is still
// essential: without it all four tinted copies would share one ConstantState and the last
// 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
// Tracks whether the last update already recentred for this follow session, so re-enabling
// follow animates once instead of fighting the rider's own panning on every frame.
val wasFollowing = remember { mutableStateOf(false) }
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
@@ -122,280 +89,109 @@ fun V2xLiveMapView(
}
}
AndroidView(
factory = { ctx ->
initOsmForV2xMap(ctx)
MapView(ctx).apply {
setTileSource(TileSourceFactory.MAPNIK)
setMultiTouchControls(true)
// Raster tiles are authored for ~160 dpi; without this they are upscaled by the
// display density and labels come out soft on a modern phone.
isTilesScaledToDpi = true
// The floating +/- buttons sit exactly where the rider's thumb lands and
// duplicate pinch-zoom. Pinch and double-tap still work.
zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
setMinZoomLevel(4.0)
setMaxZoomLevel(20.0)
controller.setZoom(17.0)
controller.setCenter(ownGeoPoint)
// Any touch means the rider is driving the map; follow-own hands over to them
// until they ask for it back. false: the MapView's own gesture handling still
// runs, this only observes.
setOnTouchListener { _, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) onUserPanned()
false
Column(modifier = modifier.fillMaxSize()) {
Text(
text = stringResource(R.string.v2x_map_remote_count, remotes.size),
style = MaterialTheme.typography.labelMedium,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
AndroidView(
factory = { ctx ->
initOsmForV2xMap(ctx)
MapView(ctx).apply {
setTileSource(TileSourceFactory.MAPNIK)
setMultiTouchControls(true)
controller.setZoom(17.0)
controller.setCenter(ownGeoPoint)
mapViewRef.value = this
}
mapViewRef.value = this
}
},
update = { mv ->
val now = System.currentTimeMillis()
},
update = { mv ->
mv.overlays.clear()
// 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) }
}
// 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 live = mutableSetOf<String>()
// Own position: a centred "you are here" dot, not a pin. Own position is a fact about
// the viewer rather than one of the tracked objects, and when both used osmdroid's
// identical default pin the two were indistinguishable at a glance.
markers.marker(mv, KEY_OWN, live).apply {
position = ownGeoPoint
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
icon = icons.own
title = context.getString(R.string.v2x_map_own_label)
}
remotes.forEach { (stationId, cam) ->
if (stationId in spatStationIds) return@forEach
val level = alertByStation[stationId]
val label = when (level) {
AlertLevel.WARNING -> context.getString(R.string.v2x_map_remote_warning, stationId)
AlertLevel.AWARENESS -> context.getString(R.string.v2x_map_remote_awareness, stationId)
AlertLevel.INFO -> context.getString(R.string.v2x_map_remote_info, stationId)
null -> context.getString(R.string.v2x_map_remote_plain, stationId)
}
// Teardrop pin anchored at its tip, tinted by severity, so severity no longer
// depends on tapping the marker to read its label.
markers.marker(mv, "$KEY_CAM$stationId", live).apply {
position = GeoPoint(cam.latitude, cam.longitude)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = icons.remotePin(level)
title = label
}
}
// Hazards and signals are added after the vehicle pins, so they draw on top: a hazard
// hidden behind a CAM pin defeats the point of showing it.
denms.forEach { denm ->
markers.marker(mv, "$KEY_DENM${denm.dedupKey}", live).apply {
position = GeoPoint(denm.latitude, denm.longitude)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = icons.denm
title = denm.causeCode?.let {
context.getString(
R.string.v2x_map_denm_labeled,
it,
denm.subCauseCode ?: 0,
denm.stationId,
)
} ?: context.getString(R.string.v2x_map_denm_plain, denm.stationId)
}
}
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)
// Own position: a centred "you are here" dot, not a pin. Own position is a fact
// about the viewer rather than one of the tracked objects, and when both used
// osmdroid's identical default pin the two were indistinguishable at a glance.
mv.overlays.add(
Marker(mv).apply {
position = ownGeoPoint
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
icon = ContextCompat.getDrawable(context, R.drawable.ic_map_own)
title = context.getString(R.string.v2x_map_own_label)
}
}
}
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)
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
position = at
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = icons.signal(phase)
title = light.name ?: context.getString(
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
remotes.forEach { (stationId, cam) ->
val level = alertByStation[stationId]
val label = when (level) {
AlertLevel.WARNING -> context.getString(R.string.v2x_map_remote_warning, stationId)
AlertLevel.AWARENESS -> context.getString(R.string.v2x_map_remote_awareness, stationId)
AlertLevel.INFO -> context.getString(R.string.v2x_map_remote_info, stationId)
null -> context.getString(R.string.v2x_map_remote_plain, stationId)
}
// Teardrop pin anchored at its tip, tinted by severity. Now that these are
// custom drawables, per-instance tinting is possible - severity no longer
// depends on tapping the marker to read its label. mutate() is essential:
// without it every marker shares one ConstantState and the last tint applied
// would recolour all of them.
val pin = ContextCompat.getDrawable(context, R.drawable.ic_map_remote_station)
?.mutate()
?.apply { setTint(level.toMarkerColor()) }
mv.overlays.add(
Marker(mv).apply {
position = GeoPoint(cam.latitude, cam.longitude)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = pin
title = label
}
)
snippet = spat.state.movements.joinToString(" · ") { movement ->
val seconds = movement.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
context.getString(R.string.v2x_spat_group, movement.signalGroup) +
(seconds?.let { " " + context.getString(R.string.v2x_spat_countdown, it) } ?: "")
}
}
}
// Drop markers for stations, hazards and intersections that have expired, then rebuild
// the overlay list in draw order from the cached Markers. Reordering moves references;
// nothing here allocates a Marker or decodes a Drawable.
markers.keys.retainAll { key ->
(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) }
// DENM hazard pins, added last so they draw on top of vehicle markers - a hazard
// hidden behind a CAM pin defeats the point of showing it.
denms.forEach { denm ->
mv.overlays.add(
Marker(mv).apply {
position = GeoPoint(denm.latitude, denm.longitude)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = ContextCompat.getDrawable(context, R.drawable.ic_denm_warning)
title = denm.causeCode?.let {
context.getString(
R.string.v2x_map_denm_labeled,
it,
denm.subCauseCode ?: 0,
denm.stationId,
)
} ?: context.getString(R.string.v2x_map_denm_plain, denm.stationId)
}
)
}
// setCenter, not animateTo: an animation restarted on every CAM never finishes, which
// is exactly the judder this used to show under live traffic. The one animated move is
// the rider re-enabling follow, where the travel is worth seeing.
if (followOwn) {
if (wasFollowing.value) mv.controller.setCenter(ownGeoPoint)
else mv.controller.animateTo(ownGeoPoint)
}
wasFollowing.value = followOwn
mv.invalidate()
},
// osmdroid's onDetach() permanently tears the MapView down: afterwards its
// MapViewRepository holds a null MapView, so constructing a Marker against it throws
// NullPointerException from deep inside InfoWindow's constructor.
//
// This used to run in the DisposableEffect's onDispose, which is NOT safe: that effect
// is keyed on the lifecycle owner and disposes independently of this AndroidView, so
// the update block above could still run against an already-detached MapView and
// rebuild its markers. It crashed the app on 2026-08-17 once DENMs started arriving,
// because every incoming message recomposes this view and there are far more updates
// to land in that window than there used to be.
//
// onRelease is the callback that actually means "this View is gone": Compose
// guarantees no further update after it.
onRelease = {
markers.clear()
lanes.clear()
it.onDetach()
},
modifier = modifier.fillMaxSize(),
)
}
// ── Marker cache ──────────────────────────────────────────────────────────────
private const val KEY_OWN = "own"
private const val KEY_CAM = "cam:"
private const val KEY_DENM = "denm:"
private const val KEY_SPAT = "spat:"
/** Draw order: own dot at the bottom, then vehicles, with hazards and signals on top. */
private fun String.drawOrder(): Int = when {
this == KEY_OWN -> 0
startsWith(KEY_CAM) -> 1
startsWith(KEY_DENM) -> 2
else -> 3
}
/**
* The cached [Marker] for [key], created against [mv] on first use, recording the key in [live]
* so the caller can drop whatever it did not ask for this update.
*/
private fun MutableMap<String, Marker>.marker(
mv: MapView,
key: String,
live: MutableSet<String>,
): Marker {
live += key
return getOrPut(key) { Marker(mv) }
}
/**
* Marker artwork, loaded once per composition rather than per update.
*
* The remote pin is drawn white and tinted per severity here; [mutate] is what keeps the four
* tinted copies independent, since without it they would share one ConstantState and the last
* tint applied would recolour all of them.
*/
private class MapIcons(context: Context) {
val own: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_map_own)
val denm: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_denm_warning)
private val pins: Map<AlertLevel?, Drawable?> =
(listOf(null) + AlertLevel.entries).associateWith { level ->
ContextCompat.getDrawable(context, R.drawable.ic_map_remote_station)
?.mutate()
?.apply { setTint(level.toMarkerColor()) }
}
private val signals: Map<SignalLamp, Drawable?> = SignalLamp.entries.associateWith { lamp ->
ContextCompat.getDrawable(context, lamp.drawableRes)
mv.controller.animateTo(ownGeoPoint)
mv.invalidate()
},
// osmdroid's onDetach() permanently tears the MapView down: afterwards its
// MapViewRepository holds a null MapView, so constructing a Marker against it throws
// NullPointerException from deep inside InfoWindow's constructor.
//
// This used to run in the DisposableEffect's onDispose, which is NOT safe: that effect
// is keyed on the lifecycle owner and disposes independently of this AndroidView, so
// the update block above could still run against an already-detached MapView and
// rebuild its markers. It crashed the app on 2026-08-17 once DENMs started arriving,
// because every incoming message recomposes this view and there are far more updates
// to land in that window than there used to be.
//
// onRelease is the callback that actually means "this View is gone": Compose
// guarantees no further update after it.
onRelease = { it.onDetach() },
modifier = Modifier.fillMaxSize(),
)
}
fun remotePin(level: AlertLevel?): Drawable? = pins[level]
fun signal(lamp: SignalLamp): Drawable? = signals[lamp]
}
// ── Signal phase → lamp ───────────────────────────────────────────────────────
/** Which lamp of the traffic-light marker is lit. */
private enum class SignalLamp(val drawableRes: Int) {
RED(R.drawable.ic_map_spat_red),
AMBER(R.drawable.ic_map_spat_amber),
GREEN(R.drawable.ic_map_spat_green),
DARK(R.drawable.ic_map_spat_dark),
}
/**
* 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.
*/
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()
}
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:
@@ -432,10 +228,5 @@ private fun initOsmForV2xMap(context: Context) {
Configuration.getInstance().apply {
load(context, context.getSharedPreferences("osmdroid", Context.MODE_PRIVATE))
userAgentValue = context.packageName
// Panning off the edge of the cache is what makes a raster map feel slow: the default
// 600 MB cap is plenty, but the default 2 download threads are not when a pan exposes a
// screenful of new tiles at once.
tileDownloadThreads = 6.toShort()
tileFileSystemThreads = 6.toShort()
}
}
@@ -1,247 +0,0 @@
package com.hawhamburg.micr0bu.ui.screens
import android.content.Context
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FiberManualRecord
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.log.V2xLogFile
import com.hawhamburg.micr0bu.data.log.V2xLogState
import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
private val modifiedFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
/**
* Settings > Developer > V2X data logger.
*
* Start and stop one log at a time, watch what it is catching, and share or delete the finished
* files. What is recorded, and from where, is described on [com.hawhamburg.micr0bu.data.log.V2xLogger].
*/
@Composable
fun V2xLogSettingsScreen(
state: V2xLogState,
files: List<V2xLogFile>,
obuHardware: ObuHardware,
onStart: () -> Unit,
onStop: () -> Unit,
onDelete: (V2xLogFile) -> Unit,
onBack: () -> Unit,
) {
val context = LocalContext.current
var pendingDelete by remember { mutableStateOf<V2xLogFile?>(null) }
val isEsp32 = obuHardware == ObuHardware.ESP32_C5
pendingDelete?.let { log ->
AlertDialog(
onDismissRequest = { pendingDelete = null },
title = { Text(stringResource(R.string.v2xlog_delete_title)) },
text = { Text(stringResource(R.string.v2xlog_delete_text, log.name)) },
confirmButton = {
TextButton(onClick = { onDelete(log); pendingDelete = null }) {
Text(stringResource(R.string.log_delete_confirm), color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { pendingDelete = null }) { Text(stringResource(R.string.log_cancel)) }
},
)
}
SubScreen(stringResource(R.string.v2xlog_title), onBack) {
Text(
stringResource(R.string.v2xlog_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard {
Spacer(Modifier.height(8.dp))
Text(
stringResource(if (isEsp32) R.string.v2xlog_mode_esp32 else R.string.v2xlog_mode_cit),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
// Said up front, not discovered later as two rows of zeros: the firmware decides this.
if (isEsp32) {
Spacer(Modifier.height(4.dp))
Text(
stringResource(R.string.v2xlog_esp32_firmware_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.height(12.dp))
Button(
onClick = if (state.active) onStop else onStart,
modifier = Modifier.fillMaxWidth(),
colors = if (state.active) ButtonDefaults.buttonColors(containerColor = Color(0xFFB3261E))
else ButtonDefaults.buttonColors(),
) {
Icon(
if (state.active) Icons.Default.Stop else Icons.Default.FiberManualRecord,
contentDescription = null,
)
Spacer(Modifier.padding(horizontal = 4.dp))
Text(stringResource(if (state.active) R.string.v2xlog_stop else R.string.v2xlog_start))
}
state.error?.let {
Spacer(Modifier.height(8.dp))
Text(
stringResource(R.string.v2xlog_error, it),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
Spacer(Modifier.height(12.dp))
}
if (state.active) {
SectionCard {
DisabledRow(stringResource(R.string.v2xlog_file), state.fileName.orEmpty())
Divider()
DisabledRow(
stringResource(R.string.v2xlog_total),
stringResource(R.string.v2xlog_total_val, state.total, formatBytes(state.fileBytes)),
)
ItsMessageKind.TRACKED.forEach { kind ->
Divider()
DisabledRow(kind.label, (state.counts[kind] ?: 0).toString())
}
Divider()
DisabledRow(stringResource(R.string.v2xlog_phone_gnss), fixAge(state.phoneFixAgeMs))
Divider()
DisabledRow(
stringResource(R.string.v2xlog_obu_gnss),
if (isEsp32) stringResource(R.string.v2xlog_not_available) else fixAge(state.obuFixAgeMs),
)
}
if (state.total == 0) {
Text(
stringResource(R.string.v2xlog_waiting),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Text(
stringResource(R.string.v2xlog_files_title, files.size),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (files.isEmpty()) {
Text(
stringResource(R.string.v2xlog_none),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
SectionCard {
files.forEachIndexed { i, log ->
if (i > 0) Divider()
LogFileRow(
log = log,
onShare = { shareLog(context, log) },
onDelete = { pendingDelete = log },
)
}
}
}
}
}
@Composable
private fun LogFileRow(log: V2xLogFile, onShare: () -> Unit, onDelete: () -> Unit) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
log.name,
style = MaterialTheme.typography.bodySmall,
fontFamily = FontFamily.Monospace,
fontWeight = FontWeight.SemiBold,
)
Text(
"${modifiedFormat.format(Date(log.modifiedMs))} · ${formatBytes(log.sizeBytes)}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// The file being written is open and incomplete; sharing or deleting it would hand over a
// half-written database or pull it out from under the writer.
IconButton(onClick = onShare, enabled = !log.active) {
Icon(Icons.Default.Share, contentDescription = stringResource(R.string.v2xlog_share_cd))
}
IconButton(onClick = onDelete, enabled = !log.active) {
Icon(
Icons.Default.Delete,
contentDescription = stringResource(R.string.v2xlog_delete_cd),
tint = if (log.active) LocalContentColorDisabled() else MaterialTheme.colorScheme.error,
)
}
}
}
@Composable
private fun LocalContentColorDisabled(): Color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
@Composable
private fun fixAge(ageMs: Long?): String =
if (ageMs == null) stringResource(R.string.v2xlog_no_fix)
else stringResource(R.string.v2xlog_fix_age, (ageMs / 1000).toInt())
private fun formatBytes(bytes: Long): String = when {
bytes < 1024 -> "$bytes B"
bytes < 1024 * 1024 -> "%.1f kB".format(Locale.US, bytes / 1024.0)
else -> "%.1f MB".format(Locale.US, bytes / (1024.0 * 1024.0))
}
private fun shareLog(context: Context, log: V2xLogFile) {
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", log.file)
val intent = Intent(Intent.ACTION_SEND).apply {
type = "application/vnd.sqlite3"
putExtra(Intent.EXTRA_STREAM, uri)
putExtra(Intent.EXTRA_SUBJECT, "MicrOBU V2X log - ${log.name}")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(Intent.createChooser(intent, context.getString(R.string.v2xlog_share_chooser)))
}
@@ -1,203 +0,0 @@
package com.hawhamburg.micr0bu.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MyLocation
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.Traffic
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
/**
* Full-screen V2X live map — the map and nothing else, reached from the map button on the V2X
* Monitor screen.
*
* Identical on both hardware paths. Everything drawn here comes from
* [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository], which already merges the CiT One's MQTT
* feed and the ESP32-C5's serial feed into one set of flows, so this screen never has to know
* which OBU is connected.
*
* The chrome is deliberately minimal and floats over the map rather than boxing it in: a back
* button, a live count per message type, and a recentre button. The counts double as the map's
* legend — each one carries the same icon family as the marker it counts.
*/
@Composable
fun V2xMapScreen(
viewModel: MqttViewModel,
onBack: () -> Unit,
) {
val ownCamPosition by viewModel.ownCamPosition.collectAsState()
// Road users from the detection engine PLUS roadside units, which it deliberately does not
// track - an RSU is what carries the traffic lights below.
val stations by viewModel.stationsInRange.collectAsState()
val alerts by viewModel.useCaseAlerts.collectAsState()
val denms by viewModel.denmEvents.collectAsState()
val lights by viewModel.trafficLights.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
// 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 }
Box(modifier = Modifier.fillMaxSize()) {
V2xLiveMapView(
own = ownCamPosition,
remotes = stations,
alerts = alerts,
denms = denms,
lights = lights,
followOwn = followOwn,
onUserPanned = { followOwn = false },
modifier = Modifier.fillMaxSize(),
)
// ── Floating header: back + live counts, which double as the legend ──
Row(
modifier = Modifier
.align(Alignment.TopStart)
.fillMaxWidth()
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
MapChrome {
IconButton(onClick = onBack, modifier = Modifier.size(36.dp)) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.v2x_map_back),
)
}
}
Spacer(Modifier.width(8.dp))
MapChrome {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
MapCount(
icon = Icons.Default.Place,
tint = CamPinBlue,
count = stations.size,
label = stringResource(R.string.v2x_map_legend_cam),
)
MapCount(
icon = Icons.Default.Warning,
tint = HazardAmber,
count = denms.size,
label = stringResource(R.string.v2x_map_legend_denm),
)
MapCount(
icon = Icons.Default.Traffic,
tint = SignalGreenDot,
count = lights.size,
label = stringResource(R.string.v2x_map_legend_spat),
)
}
}
}
if (unlocatedSpats > 0) {
MapChrome(
modifier = Modifier
.align(Alignment.BottomStart)
.padding(12.dp),
) {
Text(
text = stringResource(R.string.v2x_map_spat_unlocated, unlocatedSpats),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
// Recentre: lit while following, so the button also reports which mode the map is in.
FloatingActionButton(
onClick = { followOwn = true },
containerColor = if (followOwn) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp),
) {
Icon(
Icons.Default.MyLocation,
contentDescription = stringResource(R.string.v2x_map_follow),
tint = if (followOwn) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/** A translucent pill for anything floating over the map, so chrome stays readable over tiles. */
@Composable
private fun MapChrome(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.88f),
tonalElevation = 3.dp,
shadowElevation = 2.dp,
modifier = modifier,
) { content() }
}
@Composable
private fun MapCount(icon: ImageVector, tint: Color, count: Int, label: String) {
Row(
horizontalArrangement = Arrangement.spacedBy(3.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(16.dp))
Text(
text = count.toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
)
}
}
// Legend tints, matching the marker artwork rather than the theme: these name the drawables on
// the map, so they must not shift with light/dark mode the way theme colours do.
private val CamPinBlue = Color(0xFF78909C)
private val HazardAmber = Color(0xFFFFC107)
private val SignalGreenDot = Color(0xFF4CAF50)
@@ -13,19 +13,11 @@ import com.hawhamburg.micr0bu.data.transport.EspLinkStatus
import com.hawhamburg.micr0bu.data.transport.ObuHardware
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.data.transport.UsbSerialState
import com.hawhamburg.micr0bu.data.transport.UsbSerialTransport
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
@@ -53,7 +45,7 @@ class MqttViewModel @Inject constructor(
private val usbDetector: UsbNetworkDetector,
private val camUseCaseRepository: CamUseCaseRepository,
private val obuHardwarePrefs: ObuHardwarePreferences,
private val esp32Link: Esp32Link,
private val usbSerialTransport: UsbSerialTransport,
private val camPinger: CamPinger,
) : ViewModel() {
@@ -88,49 +80,14 @@ class MqttViewModel @Inject constructor(
/** Auto-detected OBU gateway IP on the USB interface. */
val detectedObuIp: StateFlow<String?> = usbDetector.detectedGatewayIp
/** ESP32-C5 link state, over USB or BLE per [esp32Transport] — see [Esp32Link]. */
val esp32LinkState: StateFlow<Esp32LinkState> = esp32Link.state
/** ESP32-C5 USB-serial link state (Phase 03) — see [UsbSerialTransport]. */
val usbSerialState: StateFlow<UsbSerialState> = usbSerialTransport.state
/** Latest firmware heartbeat + drop counters, null until the first STATUS frame arrives. */
val espLinkStatus: StateFlow<EspLinkStatus?> = esp32Link.linkStatus
val espLinkStatus: StateFlow<EspLinkStatus?> = usbSerialTransport.linkStatus
/** Non-zero means CAMs are being built and dropped — see [Esp32Link.send]. */
val camSendFailures: StateFlow<Int> = esp32Link.consecutiveWriteFailures
/** Signing and radio counters of the current obu-firmware; null with the previous firmware. */
val stationStatus: StateFlow<StationStatus?> = esp32Link.stationStatus
/** One line about the link session (pairing passkey, provisioning, refusals); null when quiet. */
val esp32Detail: StateFlow<String?> = esp32Link.detail
// ── ESP32-C5 settings ─────────────────────────────────────────────────────
val esp32Transport: StateFlow<Esp32Transport> = esp32Link.transport
fun setEsp32Transport(transport: Esp32Transport) {
viewModelScope.launch { obuHardwarePrefs.setEsp32Transport(transport) }
}
val outgoingMessage: StateFlow<OutgoingMessage> = obuHardwarePrefs.outgoingMessageFlow
.stateIn(viewModelScope, SharingStarted.Eagerly, OutgoingMessage.CAM)
fun setOutgoingMessage(message: OutgoingMessage) {
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)
fun setSignOutgoing(sign: Boolean) {
viewModelScope.launch { obuHardwarePrefs.setSignOutgoing(sign) }
}
/** Non-zero means CAMs are being built and dropped — see [UsbSerialTransport.sendCamTx]. */
val camSendFailures: StateFlow<Int> = usbSerialTransport.consecutiveWriteFailures
// ── ESP32-C5 CAM pinger (manual bench test, Phase 03) ─────────────────────
// The ESP32-C5-path equivalent of the CiT One's manual DENM trigger below — a fixed-
@@ -281,47 +238,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. An intersection whose MAPEM has
* not been heard (yet) is still listed, with no lanes: its signal groups stay bare numbers.
*/
val trafficLights: StateFlow<List<TrafficLight>> = combine(
spatIntersections,
mapGeometries,
camUseCaseRepository.ownPosition,
) { spats, geometries, own ->
val byKey = geometries.groupBy { it.key }
spats.map { spat ->
TrafficLights.join(
signal = spat,
geometry = TrafficLights.pickGeometry(byKey[spat.key].orEmpty(), spat.state.revision),
own = own?.let { MapPoint(it.latitude, it.longitude) },
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) {
@@ -352,13 +268,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
@@ -443,10 +352,10 @@ class MqttViewModel @Inject constructor(
fun connect() = repo.connect()
fun disconnect() = repo.disconnect()
/** Connect/disconnect the ESP32-C5 link (USB or BLE per [esp32Transport]) — separate from
* [connect]/[disconnect], which drive the CiT One's MQTT-over-USB-C/Wi-Fi path. */
fun connectEsp32() = esp32Link.connect()
fun disconnectEsp32() = esp32Link.disconnect()
/** Connect/disconnect the ESP32-C5 USB-serial link — separate from [connect]/[disconnect],
* which drive the CiT One's MQTT-over-USB-C/Wi-Fi path. See [ConnectionSetupScreen]. */
fun connectUsbSerial() = usbSerialTransport.connect()
fun disconnectUsbSerial() = usbSerialTransport.disconnect()
fun selectTopic(topic: String?) { _selectedTopic.value = topic }
fun setAutoScroll(enabled: Boolean) { _autoScroll.value = enabled }
@@ -480,7 +389,7 @@ class MqttViewModel @Inject constructor(
super.onCleared()
repo.disconnect()
camPinger.stop()
// Deliberately NOT esp32Link.disconnect(): the link is an app-scoped
// Deliberately NOT usbSerialTransport.disconnect(): the transport is an app-scoped
// @Singleton also held by the foreground TripRecordingService (via CamTransmitLoop).
// Closing it here would tear the port down when the Activity goes away — e.g. swiping
// the app from Recents mid-recording — leaving the still-running service beaconing into
@@ -1,45 +0,0 @@
package com.hawhamburg.micr0bu.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.hawhamburg.micr0bu.data.log.V2xLogFile
import com.hawhamburg.micr0bu.data.log.V2xLogState
import com.hawhamburg.micr0bu.data.log.V2xLogger
import com.hawhamburg.micr0bu.service.V2xLogService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Backs Settings > Developer > V2X data logger. */
@HiltViewModel
class V2xLogViewModel @Inject constructor(
application: Application,
private val logger: V2xLogger,
) : AndroidViewModel(application) {
val state: StateFlow<V2xLogState> = logger.state
val files: StateFlow<List<V2xLogFile>> = logger.files
init {
logger.refreshFiles()
// The running file grows between state updates, so keep the list's sizes current while a
// log is on screen.
viewModelScope.launch {
while (true) {
delay(2_000L)
if (logger.state.value.active) logger.refreshFiles()
}
}
}
fun start() = V2xLogService.start(getApplication())
fun stop() = V2xLogService.stop(getApplication())
fun delete(log: V2xLogFile) {
logger.delete(log)
}
}
@@ -1,38 +0,0 @@
<!--
Live-map marker for a signalised intersection heard over SPATEM: a traffic light housing with
the lamp for the intersection's leading phase lit and the other two dimmed.
One drawable per lit lamp rather than one drawable tinted at runtime: setTint recolours every
path in a vector, so a single shared asset could not keep the unlit lamps dark while colouring
the lit one - the whole light would turn one flat colour and stop reading as a traffic light.
Anchored at the bottom in V2xLiveMapView, so the housing sits above the intersection rather
than covering it.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="30dp"
android:height="30dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- White outline first, so the marker stays legible over dark map features. -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4.4,0.8H19.6V23.2H4.4z" />
<!-- Housing. -->
<path
android:fillColor="#FF263238"
android:pathData="M5.8,2.0H18.2V22.0H5.8z" />
<!-- Lamps, top to bottom: red, amber, green. -->
<path
android:fillColor="#FF5A2220"
android:pathData="M12,6.6m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FFFFC107"
android:pathData="M12,12.0m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF1E4D2B"
android:pathData="M12,17.4m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
</vector>
@@ -1,38 +0,0 @@
<!--
Live-map marker for a signalised intersection heard over SPATEM: a traffic light housing with
the lamp for the intersection's leading phase lit and the other two dimmed.
One drawable per lit lamp rather than one drawable tinted at runtime: setTint recolours every
path in a vector, so a single shared asset could not keep the unlit lamps dark while colouring
the lit one - the whole light would turn one flat colour and stop reading as a traffic light.
Anchored at the bottom in V2xLiveMapView, so the housing sits above the intersection rather
than covering it.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="30dp"
android:height="30dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- White outline first, so the marker stays legible over dark map features. -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4.4,0.8H19.6V23.2H4.4z" />
<!-- Housing. -->
<path
android:fillColor="#FF263238"
android:pathData="M5.8,2.0H18.2V22.0H5.8z" />
<!-- Lamps, top to bottom: red, amber, green. -->
<path
android:fillColor="#FF5A2220"
android:pathData="M12,6.6m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF4A2E1C"
android:pathData="M12,12.0m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF1E4D2B"
android:pathData="M12,17.4m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
</vector>
@@ -1,38 +0,0 @@
<!--
Live-map marker for a signalised intersection heard over SPATEM: a traffic light housing with
the lamp for the intersection's leading phase lit and the other two dimmed.
One drawable per lit lamp rather than one drawable tinted at runtime: setTint recolours every
path in a vector, so a single shared asset could not keep the unlit lamps dark while colouring
the lit one - the whole light would turn one flat colour and stop reading as a traffic light.
Anchored at the bottom in V2xLiveMapView, so the housing sits above the intersection rather
than covering it.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="30dp"
android:height="30dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- White outline first, so the marker stays legible over dark map features. -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4.4,0.8H19.6V23.2H4.4z" />
<!-- Housing. -->
<path
android:fillColor="#FF263238"
android:pathData="M5.8,2.0H18.2V22.0H5.8z" />
<!-- Lamps, top to bottom: red, amber, green. -->
<path
android:fillColor="#FF5A2220"
android:pathData="M12,6.6m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF4A2E1C"
android:pathData="M12,12.0m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF4CAF50"
android:pathData="M12,17.4m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
</vector>
@@ -1,38 +0,0 @@
<!--
Live-map marker for a signalised intersection heard over SPATEM: a traffic light housing with
the lamp for the intersection's leading phase lit and the other two dimmed.
One drawable per lit lamp rather than one drawable tinted at runtime: setTint recolours every
path in a vector, so a single shared asset could not keep the unlit lamps dark while colouring
the lit one - the whole light would turn one flat colour and stop reading as a traffic light.
Anchored at the bottom in V2xLiveMapView, so the housing sits above the intersection rather
than covering it.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="30dp"
android:height="30dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- White outline first, so the marker stays legible over dark map features. -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M4.4,0.8H19.6V23.2H4.4z" />
<!-- Housing. -->
<path
android:fillColor="#FF263238"
android:pathData="M5.8,2.0H18.2V22.0H5.8z" />
<!-- Lamps, top to bottom: red, amber, green. -->
<path
android:fillColor="#FFFF5252"
android:pathData="M12,6.6m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF4A2E1C"
android:pathData="M12,12.0m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
<path
android:fillColor="#FF1E4D2B"
android:pathData="M12,17.4m-2.6,0a2.6,2.6 0 1,0 5.2,0a2.6,2.6 0 1,0 -5.2,0" />
</vector>
+5 -63
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>
@@ -145,18 +142,12 @@
<string name="gnss_no_fix">Noch kein GPS-Signal - gehen Sie ins Freie</string>
<string name="map_title">Standortkarte</string>
<string name="map_location_label">Aktueller Standort</string>
<string name="v2x_map_remote_count">%1$d erfasste externe Verkehrsteilnehmer</string>
<string name="v2x_map_own_label">Eigen (Ego)</string>
<string name="v2x_map_remote_plain">Extern #%1$d</string>
<string name="v2x_map_remote_info">Extern #%1$d · Info</string>
<string name="v2x_map_remote_awareness">Extern #%1$d · Aufmerksamkeit</string>
<string name="v2x_map_remote_warning">Extern #%1$d · Warnung</string>
<string name="v2x_map_title">V2X-Live-Karte</string>
<string name="v2x_map_back">Zurück</string>
<string name="v2x_map_follow">Auf eigene Position zentrieren</string>
<string name="v2x_map_legend_cam">Verkehrsteilnehmer (CAM)</string>
<string name="v2x_map_legend_denm">Gefahren (DENM)</string>
<string name="v2x_map_legend_spat">Signale (SPATEM)</string>
<string name="v2x_map_spat_unlocated">%1$d Signal(e) nicht dargestellt - Senderposition unbekannt</string>
<!-- Settings -->
<string name="settings_title">Einstellungen</string>
@@ -192,7 +183,7 @@
<string name="settings_obu_hardware">OBU-Hardware</string>
<string name="settings_obu_hardware_cit_one">CiT One</string>
<string name="settings_obu_hardware_esp32">ESP32-C5</string>
<string name="settings_obu_hardware_esp32_note">Das Smartphone erstellt CAM oder VAM und übergibt sie per USB-C oder Bluetooth an den ESP32-C5; der ESP32 ergänzt GeoNetworking, signiert (optional) und sendet über ITS-G5. Auf diesem Pfad gibt es keinen MQTT-Broker und keine DENM-Use-Case-Engine - siehe den CAM-Pinger im V2X-Monitor für ein manuelles Testwerkzeug.</string>
<string name="settings_obu_hardware_esp32_note">Der ESP32-C5 arbeitet als „dummer" Transceiver: CAM wird auf dem Smartphone erstellt und kodiert, über USB-Seriell an den ESP32 gesendet und über ITS-G5 gesendet. Auf diesem Pfad gibt es keinen MQTT-Broker und keine DENM-Use-Case-Engine - siehe den CAM-Pinger im V2X-Monitor für ein manuelles Testwerkzeug.</string>
<string name="settings_usb_transport">Aktiver Transport</string>
<string name="settings_transport_usbc">USB-C</string>
<string name="settings_transport_wifi">WLAN</string>
@@ -206,6 +197,7 @@
<string name="mqtt_no_topics">Noch keine Nachrichten</string>
<string name="mqtt_view_list">Liste</string>
<string name="mqtt_view_topics">Topics</string>
<string name="mqtt_view_map">Karte</string>
<string name="mqtt_no_topics_hint">Mit der OBU verbinden und auf V2X-Verkehr warten</string>
<string name="mqtt_no_messages">Noch keine Nachrichten zu diesem Thema</string>
@@ -321,54 +313,4 @@
<string name="v2x_spat_rx_title">Kreuzung %1$s · Station %2$d</string>
<string name="v2x_spat_group">SG%1$d</string>
<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_message">Senden während der Aufzeichnung</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
<string name="settings_esp32_sign">Ausgehende Nachrichten signieren</string>
<string name="settings_esp32_sign_note">Signiert mit einer Demo-PKI, nicht der EU-Vertrauensliste: Empfänger, die dagegen prüfen, verwerfen diese Nachrichten. Aus sendet sie wie bisher unsigniert.</string>
<string name="conn_esp32_via_usb">über USB-C (nativer Port)</string>
<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_start">Aufzeichnung starten</string>
<string name="v2xlog_stop">Aufzeichnung beenden</string>
<string name="v2xlog_error">Aufzeichnung fehlgeschlagen: %1$s</string>
<string name="v2xlog_file">Datei</string>
<string name="v2xlog_total">Aufgezeichnet</string>
<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_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>
<string name="v2xlog_waiting">Warte auf Nachrichten. Ist die OBU noch nicht verbunden, verbinde sie auf dem Verbindungsbildschirm.</string>
<string name="v2xlog_files_title">Logdateien (%1$d)</string>
<string name="v2xlog_none">Noch keine Logs</string>
<string name="v2xlog_share_cd">Log teilen</string>
<string name="v2xlog_delete_cd">Log löschen</string>
<string name="v2xlog_share_chooser">V2X-Log teilen</string>
<string name="v2xlog_delete_title">Log löschen?</string>
<string name="v2xlog_delete_text">%1$s wird dauerhaft vom Gerät entfernt.</string>
<string name="mqtt_disconnect_confirm_title">OBU trennen?</string>
<string name="mqtt_disconnect_confirm_text">Die V2X-Livedaten stoppen, und ein laufendes V2X-Log erhält nichts, bis du wieder verbindest.</string>
</resources>
+6 -64
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>
@@ -146,18 +143,12 @@
<string name="gnss_no_fix">No GPS fix yet - move to an open area</string>
<string name="map_title">Location Map</string>
<string name="map_location_label">Current Location</string>
<string name="v2x_map_remote_count">%1$d tracked remote road user(s)</string>
<string name="v2x_map_own_label">Own (ego)</string>
<string name="v2x_map_remote_plain">Remote #%1$d</string>
<string name="v2x_map_remote_info">Remote #%1$d · Info</string>
<string name="v2x_map_remote_awareness">Remote #%1$d · Awareness</string>
<string name="v2x_map_remote_warning">Remote #%1$d · Warning</string>
<string name="v2x_map_title">V2X Live Map</string>
<string name="v2x_map_back">Back</string>
<string name="v2x_map_follow">Centre on own position</string>
<string name="v2x_map_legend_cam">Road users (CAM)</string>
<string name="v2x_map_legend_denm">Hazards (DENM)</string>
<string name="v2x_map_legend_spat">Signals (SPATEM)</string>
<string name="v2x_map_spat_unlocated">%1$d signal(s) not shown - sender position unknown</string>
<!-- Settings -->
<string name="settings_title">Settings</string>
@@ -193,7 +184,7 @@
<string name="settings_obu_hardware">OBU Hardware</string>
<string name="settings_obu_hardware_cit_one">CiT One</string>
<string name="settings_obu_hardware_esp32">ESP32-C5</string>
<string name="settings_obu_hardware_esp32_note">The phone builds CAM or VAM and hands it to the ESP32-C5 over USB-C or Bluetooth; the ESP32 adds GeoNetworking, signs it (optional) and broadcasts it over ITS-G5. No MQTT broker or DENM use-case engine on this path - see the V2X Monitor screen\'s CAM Pinger for a manual test tool.</string>
<string name="settings_obu_hardware_esp32_note">ESP32-C5 acts as a "dumb" transceiver: CAM is built and encoded on the phone, sent to the ESP32 over USB serial, and broadcast over ITS-G5. No MQTT broker or DENM use-case engine on this path - see the V2X Monitor screen\'s CAM Pinger for a manual test tool.</string>
<string name="settings_usb_transport">Active transport</string>
<string name="settings_transport_usbc">USB-C</string>
<string name="settings_transport_wifi">Wi-Fi</string>
@@ -207,6 +198,7 @@
<string name="mqtt_no_topics">No messages yet</string>
<string name="mqtt_view_list">List</string>
<string name="mqtt_view_topics">Topics</string>
<string name="mqtt_view_map">Map</string>
<string name="mqtt_no_topics_hint">Connect to the OBU and wait for V2X traffic</string>
<string name="mqtt_no_messages">No messages on this topic yet</string>
@@ -267,7 +259,7 @@
<string name="mqtt_cam_pinger_active">Pinging - 1 CAM/s over the serial link</string>
<string name="mqtt_cam_pinger_sent_count">Sent: %1$d</string>
<string name="mqtt_cam_pinger_send_failures">Write failures: %1$d consecutive - CAMs are not reaching the ESP32</string>
<string name="mqtt_cam_pinger_fw_counters">ESP32: tx fail %1$d · oversize %2$d · crc err %3$d · rx queue drop %4$d</string>
<string name="mqtt_cam_pinger_fw_counters">ESP32: tx fail %1$d · oversize %2$d · crc err %3$d</string>
<string name="mqtt_cam_pinger_loopback">Own TX heard back: %1$d frames · %2$d dBm</string>
<string name="mqtt_cam_pinger_loopback_no_rssi">Own TX heard back: %1$d frames</string>
<string name="mqtt_start_pinger">Start Pinger</string>
@@ -328,54 +320,4 @@
<!-- Phase A: Trip Review screen -->
<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_message">Transmit while recording</string>
<string name="settings_esp32_message_cam">CAM</string>
<string name="settings_esp32_message_vam">VAM</string>
<string name="settings_esp32_sign">Sign outgoing messages</string>
<string name="settings_esp32_sign_note">Signed with a demo PKI, not the EU trust list: receivers that verify against it will drop these messages. Off sends them unsigned, as before.</string>
<string name="conn_esp32_via_usb">via USB-C (native port)</string>
<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_start">Start logging</string>
<string name="v2xlog_stop">Stop logging</string>
<string name="v2xlog_error">Logging failed: %1$s</string>
<string name="v2xlog_file">File</string>
<string name="v2xlog_total">Recorded</string>
<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_fix_age">fix %1$d s ago</string>
<string name="v2xlog_no_fix">no fix</string>
<string name="v2xlog_not_available">not available</string>
<string name="v2xlog_waiting">Waiting for messages. If the OBU is not connected yet, connect it on the Connection screen.</string>
<string name="v2xlog_files_title">Log files (%1$d)</string>
<string name="v2xlog_none">No logs yet</string>
<string name="v2xlog_share_cd">Share log</string>
<string name="v2xlog_delete_cd">Delete log</string>
<string name="v2xlog_share_chooser">Share V2X log</string>
<string name="v2xlog_delete_title">Delete log?</string>
<string name="v2xlog_delete_text">This permanently removes %1$s from the device.</string>
<string name="mqtt_disconnect_confirm_title">Disconnect the OBU?</string>
<string name="mqtt_disconnect_confirm_text">Live V2X data stops, and a running V2X log gets nothing, until you connect again.</string>
</resources>
-2
View File
@@ -2,6 +2,4 @@
<paths>
<!-- Covers context.cacheDir — used for CSV exports -->
<cache-path name="shared_csv" path="." />
<!-- V2X data logs (V2xLogger), shared from Settings > Developer -->
<files-path name="v2x_logs" path="v2x_logs/" />
</paths>
@@ -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
@@ -166,21 +166,6 @@ class CamTxPvSerialTest {
assertFalse(EspLinkStatus.parse("0000000000000002".hexToBytes())!!.supportsCamTxPv)
}
@Test
fun `firmware that predates the rx queue drop counter reports zero`() {
// 8-byte heartbeat (status + counters + capabilities, no rx queue drops tail).
val status = EspLinkStatus.parse("0000000000000001".hexToBytes())!!
assertEquals(0, status.rxQueueDrops)
}
@Test
fun `rx queue drops are read little-endian from the 10-byte payload`() {
// status=0, oversize=0, txFail=0, rxCrc=0, capabilities=0x01, rxQueueDrops=0x0102 (LE: 02 01)
val status = EspLinkStatus.parse("00000000000000010201".hexToBytes())!!
assertEquals(0x0102, status.rxQueueDrops)
assertTrue(status.supportsCamTxPv)
}
private val mac = "024d49435230".hexToBytes()
private fun vectorAt(tstMs: Long) = GnPositionVector(
@@ -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,73 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import com.hawhamburg.micr0bu.domain.log.ItsPduHeader
import com.hawhamburg.micr0bu.domain.log.classifyItsPdu
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* Pins how the V2X data logger names a message it may have no decoder for. The CAM fixture is the
* golden UPER frame from [CamEncodeGoldenTest] (protocolVersion 2, messageID 2, stationID 999999);
* the others only need a valid ItsPduHeader, which is all the classifier reads.
*/
class ItsMessageKindTest {
private fun String.hexToBytes() = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private val goldenCam =
"0202000f423f3700402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337feebfff6000000".hexToBytes()
/** An ItsPduHeader with [messageId] and stationID 0x01020304, then a stand-in body. */
private fun pdu(messageId: Int) =
byteArrayOf(2, messageId.toByte(), 1, 2, 3, 4, 0x55, 0x66)
@Test fun `header of the golden CAM is read`() {
val h = ItsPduHeader.parse(goldenCam)!!
assertEquals(2, h.protocolVersion)
assertEquals(2, h.messageId)
assertEquals(999_999L, h.stationId)
}
@Test fun `station id above 2^31 is not sign-extended`() {
val h = ItsPduHeader.parse(byteArrayOf(2, 2, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFE.toByte()))!!
assertEquals(0xFFFFFFFEL, h.stationId)
}
@Test fun `every tracked kind is recognised by messageID alone`() {
assertEquals(ItsMessageKind.DENM, classifyItsPdu(pdu(1), null).kind)
assertEquals(ItsMessageKind.CAM, classifyItsPdu(pdu(2), null).kind)
assertEquals(ItsMessageKind.SPATEM, classifyItsPdu(pdu(4), null).kind)
assertEquals(ItsMessageKind.MAPEM, classifyItsPdu(pdu(5), null).kind)
assertEquals(ItsMessageKind.VAM, classifyItsPdu(pdu(16), null).kind)
}
@Test fun `messageID wins over the BTP port, and the SPATEM-MAPEM numbers are not swapped`() {
// SPATEM is port 2004 but messageID 4; MAPEM is port 2003 but messageID 5.
assertEquals(ItsMessageKind.SPATEM, classifyItsPdu(pdu(4), 2004).kind)
assertEquals(ItsMessageKind.MAPEM, classifyItsPdu(pdu(5), 2003).kind)
// A PDU that disagrees with the port it arrived on is what its header says it is.
assertEquals(ItsMessageKind.MAPEM, classifyItsPdu(pdu(5), 2004).kind)
}
@Test fun `a PDU too short for a header falls back to the BTP port`() {
val c = classifyItsPdu(byteArrayOf(2, 5), 2018)
assertEquals(ItsMessageKind.VAM, c.kind)
assertNull(c.messageId)
assertNull(c.stationId)
}
@Test fun `an unknown messageID is kept as OTHER with its id`() {
val c = classifyItsPdu(pdu(99), null)
assertEquals(ItsMessageKind.OTHER, c.kind)
assertEquals(99, c.messageId)
assertEquals(0x01020304L, c.stationId)
}
@Test fun `processed topic names map to kinds`() {
assertEquals(ItsMessageKind.MAPEM, ItsMessageKind.fromProcessedTopicName("map"))
assertEquals(ItsMessageKind.SPATEM, ItsMessageKind.fromProcessedTopicName("spat"))
assertNull(ItsMessageKind.fromProcessedTopicName("unknown"))
}
}
@@ -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,144 +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 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)
}
// ---- 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,185 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.BtpDataRequest
import com.hawhamburg.micr0bu.data.transport.LinkMessage
import com.hawhamburg.micr0bu.data.transport.LinkOpcode
import com.hawhamburg.micr0bu.data.transport.LinkResult
import com.hawhamburg.micr0bu.data.transport.LinkSecurityProfile
import com.hawhamburg.micr0bu.data.transport.PotiUpdate
import com.hawhamburg.micr0bu.data.transport.StationConfigure
import com.hawhamburg.micr0bu.data.transport.StationInfo
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
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
* 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.
*/
class StationLinkTest {
private fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
@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
fun `POTI_UPDATE matches the Python encoder`() {
val body = PotiUpdate(
timestampMs = 717_254_800_123L, latTenMicroDeg = 535_546_667, lonTenMicroDeg = 100_223_889,
semiMajorCm = 486, semiMinorCm = 486, speedCms = 543, headingDeciDeg = 1234, pai = true,
).encode()
assertEquals(
"02000800fbb2b7ffa60000002bcbeb1f914bf905e601e60100000e000000001f02d204",
LinkMessage(LinkOpcode.POTI_UPDATE, 8, body).encode().hex(),
)
}
@Test
fun `BTP_DATA_REQUEST for a signed CAM matches the Python encoder`() {
val body = BtpDataRequest(
destinationPort = 2001, itsAid = 36, securityProfile = LinkSecurityProfile.SECURED,
permissions = "010000".hexToBytes(), flSdu = "0102030405".hexToBytes(),
).encode()
assertEquals(
"0300090001d1070000010102ffff000000000024000000030100000005000102030405",
LinkMessage(LinkOpcode.BTP_DATA_REQUEST, 9, body).encode().hex(),
)
}
@Test
fun `CREDENTIALS_PROVISION segment matches the Python encoder`() {
val body = credentialsSegment(totalLength = 695, offset = 240, segment = ByteArray(3) { 0xAB.toByte() })
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)!!
assertEquals(123_456L, status.uptimeMs)
assertTrue(status.configured)
assertArrayEquals("b80b49387a4c12eb".hexToBytes(), status.identifier)
assertEquals(1, status.tickets)
assertEquals(11L, status.signedMessages)
assertEquals(12L, status.refusedNoTicket)
assertEquals(13L, status.refusedChangePending)
assertEquals(14L, status.refusedPermission)
assertEquals(15L, status.signFailed)
assertEquals(16L, status.verified)
assertEquals(17L, status.rejected)
assertEquals(18L, status.requestsAccepted)
assertEquals(19L, status.requestsRefused)
assertEquals(21L, status.radioSubmitted)
assertEquals(22L, status.radioFailed)
assertEquals(23L, status.radioReceived)
assertEquals(24L, status.radioDropped)
assertEquals(26L, status.linkCrcErrors)
assertEquals(27L, status.linkMalformed)
assertEquals(28L, status.potiUpdates)
assertEquals(717_254_800_123L, status.itsTimeMs)
}
@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)))
}
@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`() {
val message = LinkMessage.decode("8000070000120800021122334455b80b49387a4c12eb0101".hexToBytes())!!
val result = LinkResult.decode(message.body)!!
assertTrue(result.accepted)
assertEquals(StationInfo(credentialsLoaded = true, tickets = 1), StationInfo.decode(result.detail))
}
}
@@ -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)
}
}
@@ -1,60 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules.Kinematics
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** TS 103 300-3 clause 6.4 items 1 to 4, with the Table 16/17 values. */
class VamGenerationRulesTest {
private val here = Kinematics(53.5546667, 10.0223889, speedMps = 3.0, headingDeg = 90.0)
private fun sentAt(ms: Long, k: Kinematics = here) = VamGenerationRules().apply { onSent(ms, k, withLowFrequency = true) }
@Test
fun `the first VAM is always due`() {
assertTrue(VamGenerationRules().due(0, here))
}
@Test
fun `nothing is due within T_GenVamMin even after a big jump`() {
assertFalse(sentAt(1_000).due(1_050, here.copy(latitude = here.latitude + 0.001)))
}
@Test
fun `a stationary VRU gets one VAM every T_GenVamMax`() {
val rules = sentAt(1_000)
assertFalse(rules.due(5_900, here))
assertTrue(rules.due(6_001, here))
}
@Test
fun `position, speed and heading changes trigger past their thresholds only`() {
val rules = sentAt(1_000)
// ~3.3 m north: under 4 m. ~5.6 m: over.
assertFalse(rules.due(2_000, here.copy(latitude = here.latitude + 0.00003)))
assertTrue(rules.due(2_000, here.copy(latitude = here.latitude + 0.00005)))
assertFalse(rules.due(2_000, here.copy(speedMps = 3.4)))
assertTrue(rules.due(2_000, here.copy(speedMps = 3.6)))
assertFalse(rules.due(2_000, here.copy(headingDeg = 93.0)))
assertTrue(rules.due(2_000, here.copy(headingDeg = 95.0)))
}
@Test
fun `heading change is measured the short way round north`() {
val rules = sentAt(1_000, here.copy(headingDeg = 358.0))
assertFalse(rules.due(2_000, here.copy(headingDeg = 1.0))) // 3 degrees across north
assertTrue(rules.due(2_000, here.copy(headingDeg = 3.0))) // 5 degrees
}
@Test
fun `the low-frequency container goes with the first VAM, then every T_GenVamLFMin`() {
val rules = VamGenerationRules()
assertTrue(rules.includeLowFrequency(0))
rules.onSent(0, here, withLowFrequency = true)
assertFalse(rules.includeLowFrequency(1_999))
assertTrue(rules.includeLowFrequency(2_000))
}
}
@@ -1,61 +0,0 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.asn1.VamContent
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Pins the VAM encoder against bytes this code did not produce.
*
* ## 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
* (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
* 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.
*/
class VamUperCodecTest {
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
private fun content(includeLowFrequency: Boolean, accuracyM: Float? = 3.0f) = VamContent(
stationId = 0x12345678,
timestamp = 1_790_170_000_123L,
latitude = 53.5546667,
longitude = 10.0223889,
accuracyM = accuracyM,
speedMps = 5.43,
headingDeg = 123.4,
accelerationMps2 = -1.26,
includeLowFrequency = includeLowFrequency,
)
@Test
fun `VAM with the low-frequency container matches asn1tools`() {
assertEquals(
"031012345678c683400aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f322220",
VamUperCodec.encode(content(includeLowFrequency = true)).hex(),
)
}
@Test
fun `VAM without the low-frequency container matches asn1tools`() {
assertEquals(
"031012345678c683000aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f30",
VamUperCodec.encode(content(includeLowFrequency = false)).hex(),
)
}
@Test
fun `unknown accuracy encodes the confidence ellipse as unavailable`() {
assertEquals(
"031012345678c683000aac85a15b8a18ec8fffffff08eddd0f8002697e087ff24f30",
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
+102
View File
@@ -0,0 +1,102 @@
# Sniffer board and capture tooling
How to put an ESP32-C5 on the ITS-G5 channel as a passive sniffer, pull its captures onto this
PC, and check what is on air. The sniffer firmware itself is the third-party
`its-g5-receiver-firmware` checkout beside this repo; only the tooling and these notes are ours.
| File | What it does |
|---|---|
| `live_capture.py` | Streams the device's captures into a growing `.pcap` while it runs. The usual choice. |
| `dump_pcap.py` | Pulls one capture out of the device's in-memory buffer after the fact. |
| `../obu-firmware/test/pcap_gn_tally.py` | Tallies GeoNetworking headers per station over a `.pcap`. |
One-time: `pip install pyserial` (present in Python 3.11 on the bench PC, so `py -3.11` works).
## Which port
The sniffer firmware's console, and with it the pcap stream, goes out **UART0** - the board's
USB-bridge port (a CH343, its own COM number), not the native USB-C port. A board with only one
USB-C port cannot be used as a sniffer for this reason. On the bench this has been COM5 and, after
a re-enumeration, COM8.
## Live capture (preferred)
```powershell
cd capture
py -3.11 live_capture.py COM8
```
It writes `recordings/capture_<timestamp>.pcap` next to itself, flushing after every packet, so
the file can be read while it grows. Stop it with Ctrl+C. Use `-o <dir>` to write elsewhere;
`recordings/` is gitignored, since captures are large and are data rather than source. Captures
taken before 2026-09-14 are still in `its-g5-receiver-firmware/recordings/`; the host tests read
both directories.
### The CR insertion, and why captures used to be corrupt
ESP-IDF's newlib console converts LF to CRLF on its way out, and that applies to every `0x0a` byte
of the **binary** pcap stream, not only to log text. Each inserted CR shifts everything after it,
so pcap record headers and captured frames alike come out corrupt, and the file stops being
parseable at the first occurrence.
Measured on 2026-09-14: a 787 KB capture parsed cleanly for only 82 of about 2000 records, and
DENMs appeared on nonsense BTP ports because their payloads contain `0x0a` often. `undo_crlf()` in
`live_capture.py` reverses it on the raw stream before any framing, which is exact; afterwards a
capture parsed to EOF and DENMs read as port 2002 again.
**Captures taken before 2026-09-14 are truncated at their first corrupted record.** Anything
measured from them is worth re-checking. `dump_pcap.py` reads the same console and has not been
given the same treatment yet.
## Checking a capture
```powershell
py -3.11 ..\obu-firmware\test\pcap_gn_tally.py recordings\capture_<timestamp>.pcap
```
One row per station, packet type, BTP port and GN lifetime. For the messages themselves, decode
the payloads with `asn1tools` against the modules in `../asn1/` and re-encode them: identical bytes
mean the message was read exactly, wrong bytes mean it was not. `obu-firmware/test/check_replay.py`
does this over a whole capture.
## Flashing the sniffer firmware
From the receiver checkout, with its **pinned** ESP-IDF (not the global 5.5.4 install):
```powershell
cd its-g5-receiver-firmware
git submodule update --init --recursive
.\esp-idf\install.bat
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\esp-idf\export.ps1
idf.py set-target esp32c5
idf.py -p COM8 -b 921600 flash
```
Its `sdkconfig` for a bare board (nothing wired) needs SPI Ethernet off, and the pcap destination
set to Memory, both under `idf.py menuconfig`. Wired variants have ready-made configs in that
checkout: `sdkconfig.proto-w5500`, `sdkconfig.proto-enc28j60`, `sdkconfig.proto-spi-eppp`.
To reflash a board that already has a built image, without a toolchain terminal:
```powershell
cd its-g5-receiver-firmware\build
C:\Espressif\python_env\idf5.5_py3.11_env\Scripts\python.exe -m esptool --chip esp32c5 -p COM8 -b 921600 write_flash --flash_mode dio --flash_freq 80m --flash_size 16MB 0x2000 bootloader/bootloader.bin 0x8000 partition_table/partition-table.bin 0x1e000 ota_data_initial.bin 0x20000 its-g5-receiver-firmware.bin
```
## Pulling a capture after the fact
Only for the Memory destination, and the buffer is small (`SNIFFER_PCAP_MEMORY_SIZE`, 4096 bytes
by default) - a smoke test, not a session. In the device console (`idf.py -p COM8 monitor`, exit
with Ctrl+T then Ctrl+X):
```
sniffer -P
sniffer --stop
```
Then, with the port free:
```powershell
py -3.11 dump_pcap.py COM8
```
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""
Pulls a capture off the ITS-G5 receiver's in-memory pcap buffer over the existing USB serial
connection and saves it as a real .pcap file on this machine.
Requires the firmware to be built with:
Example Configuration -> Select destination to store pcap file -> Memory
Usage (typical):
1. Close idf.py monitor (only one program can hold the COM port at a time).
2. Run a capture on the device: `sniffer -P` ... let it run ... `sniffer --stop`
3. python dump_pcap.py COM5
The device has no access to this computer's filesystem, so it can't write here directly. Instead,
`pcap --dump` streams the raw pcap bytes back over the same serial link, wrapped in plain-text
markers ("===PCAP-DUMP-START:<len>===" ... raw bytes ... "===PCAP-DUMP-END==="). This script finds
those markers and writes just the raw bytes out as a .pcap file.
Install dependency once: pip install pyserial
"""
import argparse
import datetime
import re
import sys
try:
import serial
except ImportError:
print("Missing dependency. Install it with: pip install pyserial", file=sys.stderr)
sys.exit(1)
START_RE = re.compile(rb"===PCAP-DUMP-START:(\d+)===\n")
END_MARKER = b"\n===PCAP-DUMP-END===\n"
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("port", help="Serial port the device is on, e.g. COM5")
parser.add_argument("-b", "--baud", type=int, default=115200, help="Baud rate (default: 115200)")
parser.add_argument("-o", "--outdir", default="recordings", help="Output directory (default: ./recordings)")
parser.add_argument("-t", "--timeout", type=float, default=15.0, help="Seconds to wait for the dump to start")
args = parser.parse_args()
import os
os.makedirs(args.outdir, exist_ok=True)
print(f"Opening {args.port} @ {args.baud}...")
with serial.Serial(args.port, args.baud, timeout=1) as ser:
# Nudge the console in case there's stale input, then request the dump.
ser.reset_input_buffer()
ser.write(b"\r\n")
ser.write(b"pcap -f dump --dump\r\n")
print("Waiting for dump to start...")
buf = b""
match = None
deadline = datetime.datetime.now() + datetime.timedelta(seconds=args.timeout)
while datetime.datetime.now() < deadline:
chunk = ser.read(256)
if chunk:
buf += chunk
match = START_RE.search(buf)
if match:
break
if not match:
print("Timed out waiting for '===PCAP-DUMP-START:...===' marker.\n"
"Check that: the firmware is built with the Memory pcap destination, a capture was\n"
"actually taken ('sniffer -P' then 'sniffer --stop'), and no other program (like\n"
"idf.py monitor) is holding the serial port open.", file=sys.stderr)
sys.exit(1)
length = int(match.group(1))
print(f"Dump starting, {length} bytes expected.")
# Anything after the marker in our buffer is already part of the payload.
payload = buf[match.end():]
remaining = length - len(payload)
while remaining > 0:
chunk = ser.read(min(remaining, 4096))
if not chunk:
print(f"Serial read timed out with {remaining} bytes still missing.", file=sys.stderr)
sys.exit(1)
payload += chunk
remaining -= len(chunk)
# Drain (and sanity-check) the trailing end marker, but don't fail hard if it's not exact.
tail = ser.read(len(END_MARKER))
if tail != END_MARKER:
print("Warning: end marker didn't match exactly - payload may still be fine.", file=sys.stderr)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
outpath = os.path.join(args.outdir, f"capture_{timestamp}.pcap")
with open(outpath, "wb") as f:
f.write(payload)
print(f"Saved {len(payload)} bytes to {outpath}")
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""
Continuously listens on the ITS-G5 receiver's serial console and writes every captured packet into a
live-growing .pcap file, with no console commands needed on the device side.
The firmware streams every packet it captures out over the same serial connection the console runs on,
automatically, as soon as the sniffer is running (which happens on boot by default). Each packet is framed
with plain-text markers so this script can pull the binary pcap bytes out of the stream even though
regular log lines are interleaved with it:
===PCAP-LIVE-HEADER:<len>===\\n<24 raw bytes>\\n (sent once, the pcap global header)
===PCAP-LIVE-PKT:<len>===\\n<raw bytes>\\n (sent once per captured packet)
Usage:
python live_capture.py COM5
Runs until you press Ctrl+C. Writes to recordings/capture_<timestamp>.pcap, flushing after every packet
so you can open the file in Wireshark while it's still being written (use "File > Open" again, or
Wireshark's own "Follow" won't auto-refresh but re-opening will show the latest packets).
Install dependency once: pip install pyserial
"""
import argparse
import datetime
import os
import re
import sys
import time
try:
import serial
except ImportError:
print("Missing dependency. Install it with: pip install pyserial", file=sys.stderr)
sys.exit(1)
# \r? because the ESP console emits CRLF: on Windows the markers arrive as
# "===PCAP-LIVE-PKT:310===\r\n", which never matched a bare \n and left the capture silently
# empty while the device was streaming perfectly well.
HEADER_RE = re.compile(rb"===PCAP-LIVE-HEADER:(\d+)===\r?\n")
PKT_RE = re.compile(rb"===PCAP-LIVE-PKT:(\d+)===\r?\n")
LINKTYPE_ETHERNET = 1
LINKTYPE_IEEE802_11_RADIOTAP = 127
def mac_str(b):
return ":".join(f"{x:02x}" for x in b)
def build_default_pcap_header(link_type):
"""Synthesizes the same 24-byte global pcap header the firmware would have sent, for when we
connect after the device's one-time header already went out (see the race note in main())."""
header = bytearray(24)
header[0:4] = bytes([0xD4, 0xC3, 0xB2, 0xA1]) # magic (LE bytes of 0xA1B2C3D4)
header[4:6] = (2).to_bytes(2, "little") # major version
header[6:8] = (4).to_bytes(2, "little") # minor version
header[16:20] = (0x40000).to_bytes(4, "little") # snaplen
header[20:24] = link_type.to_bytes(4, "little")
return bytes(header)
def summarize_packet(link_type, record_bytes, index):
"""Best-effort human-readable one-line summary of a captured packet, for live feedback.
record_bytes is the raw 16-byte pcap record header followed by the captured frame."""
seconds = int.from_bytes(record_bytes[0:4], "little")
microseconds = int.from_bytes(record_bytes[4:8], "little")
cap_len = int.from_bytes(record_bytes[8:12], "little")
frame = record_bytes[16:]
ts = f"{seconds}.{microseconds:06d}"
if link_type == LINKTYPE_IEEE802_11_RADIOTAP and len(frame) >= 24:
radiotap_len = int.from_bytes(frame[2:4], "little")
rssi = frame[8] - 256 if frame[8] >= 128 else frame[8]
station_id = int.from_bytes(frame[16:24], "little")
mac_frame = frame[radiotap_len:]
if len(mac_frame) >= 16:
dst = mac_str(mac_frame[4:10])
src = mac_str(mac_frame[10:16])
else:
dst = src = "?"
station = f"{station_id:012x}" if station_id else "unknown"
return (f"#{index:<5} [{ts}] len={cap_len:<5} rssi={rssi:>4}dBm "
f"station={station} {src} -> {dst}")
if link_type == LINKTYPE_ETHERNET and len(frame) >= 14:
dst = mac_str(frame[0:6])
src = mac_str(frame[6:12])
ethertype = int.from_bytes(frame[12:14], "big")
return f"#{index:<5} [{ts}] len={cap_len:<5} eth {src} -> {dst} type=0x{ethertype:04x}"
return f"#{index:<5} [{ts}] len={cap_len:<5} (unrecognized frame format)"
def undo_crlf(chunk, state):
"""Undo the CR the device console inserts before every LF.
ESP-IDF's newlib console converts LF to CRLF on its way out, and that happens to every 0x0A
byte of the binary pcap stream too, not only to log text. Each inserted CR shifts everything
after it, so pcap record headers and captured frames alike come out corrupt. This is the
"byte inserted mid-frame" seen in older recordings; with DENM traffic on air it wrecks most
of a capture (measured 2026-09-14: a 787 KB file parsed cleanly for only 82 records).
Dropping one CR immediately before each LF undoes it exactly, provided it is done on the raw
stream before any framing and a trailing CR is carried across read boundaries. CR and LF are
written as byte values here so the transformation cannot be confused with an escape.
"""
CR, LF = bytes([13]), bytes([10])
if state["pending_cr"]:
chunk = CR + chunk
state["pending_cr"] = False
if chunk.endswith(CR):
chunk = chunk[:-1]
state["pending_cr"] = True
return chunk.replace(CR + LF, LF)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("port", help="Serial port the device is on, e.g. COM5")
parser.add_argument("-b", "--baud", type=int, default=115200, help="Baud rate (default: 115200)")
parser.add_argument("-o", "--outdir", default="recordings", help="Output directory (default: ./recordings)")
args = parser.parse_args()
os.makedirs(args.outdir, exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
outpath = os.path.join(args.outdir, f"capture_{timestamp}.pcap")
print(f"Opening {args.port} @ {args.baud}...")
print(f"Writing live capture to {outpath}")
print("Press Ctrl+C to stop.")
header_written = False
link_type = None
packet_count = 0
buf = b""
total_bytes = 0
last_status = time.monotonic()
printed_raw_preview = False
crlf_state = {"pending_cr": False}
with serial.Serial(args.port, args.baud, timeout=1) as ser, open(outpath, "wb") as outfile:
def read_bytes(n):
return undo_crlf(ser.read(n), crlf_state)
try:
while True:
chunk = read_bytes(256)
if chunk:
buf += chunk
total_bytes += len(chunk)
now = time.monotonic()
if now - last_status >= 2:
last_status = now
print(f"[diagnostic] {total_bytes} raw bytes received so far, "
f"{packet_count} packets recognized, header_written={header_written}")
if total_bytes > 0 and not printed_raw_preview and not header_written and not PKT_RE.search(buf):
# We're getting bytes but none of them look like our markers - show a preview
# so we can tell whether this is plain log text (markers just haven't shown up
# yet), garbage (baud/port mismatch), or something else entirely.
preview = buf[:200]
print(f"[diagnostic] no markers matched yet - raw preview: {preview!r}")
printed_raw_preview = True
elif total_bytes == 0:
print("[diagnostic] zero bytes received from the port at all - this points at "
"the wrong COM port, another program holding the port, or a port that "
"isn't actually wired to the console/sniffer output.")
# The device only sends the global header once, right when the sniffer first starts
# (typically within a second or two of boot). If this script connects even slightly
# late - very likely right after a fresh flash, since esptool itself resets the board -
# that header is already gone before we ever see it. Rather than blocking forever
# waiting for a header that's never coming, look for whichever marker shows up first.
header_match = None if header_written else HEADER_RE.search(buf)
pkt_match = PKT_RE.search(buf)
if header_match and (not pkt_match or header_match.start() < pkt_match.start()):
length = int(header_match.group(1))
buf = buf[header_match.end():]
while len(buf) < length:
buf += read_bytes(length - len(buf))
header_bytes = buf[:length]
outfile.write(header_bytes)
outfile.flush()
buf = buf[length:]
header_written = True
if length >= 24:
link_type = int.from_bytes(header_bytes[20:24], "little")
print(f"Got pcap global header (link type {link_type}) - device is streaming.\n")
continue
if not header_written and pkt_match:
link_type = LINKTYPE_IEEE802_11_RADIOTAP
outfile.write(build_default_pcap_header(link_type))
outfile.flush()
header_written = True
print("Note: missed the device's one-time pcap header (it was likely sent before "
"this script connected, e.g. right after a flash/reset) - assuming WLAN "
"radiotap capture and writing a default header instead.\n")
# fall through and process pkt_match below, don't discard this packet
if not pkt_match:
# Keep the buffer from growing unbounded while waiting for a marker, but don't
# discard anything - a marker could be split across reads.
if len(buf) > 65536:
buf = buf[-4096:]
continue
length = int(pkt_match.group(1))
buf = buf[pkt_match.end():]
while len(buf) < length:
buf += read_bytes(length - len(buf))
record_bytes = buf[:length]
outfile.write(record_bytes)
outfile.flush()
buf = buf[length:]
packet_count += 1
print(summarize_packet(link_type, record_bytes, packet_count))
except KeyboardInterrupt:
print(f"\nStopped. {packet_count} packets saved to {outpath}")
if __name__ == "__main__":
main()
-179
View File
@@ -1,179 +0,0 @@
# 06 – Signed ITS messages, VAM and the BLE link (2026-09-23, firmware part updated 2026-11-10)
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
`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,
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).
- **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.
- **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.
## Who does what
| | Phone (app) | ESP32-C5 (obu-firmware) |
|---|---|---|
| CAM / VAM content and UPER encoding | yes | – |
| Send cadence (CAM 1 Hz baseline; VAM per TS 103 300-3 clause 6.4) | yes | – |
| Pseudonym (station ID + MAC, rotated together) | yes | uses the MAC it is configured with |
| Time and position (PoTi) | yes, per new GNSS fix | keeps an ITS clock from it |
| GeoNetworking + BTP headers | – | yes |
| Signing (TS 103 097), certificate handling | – | yes |
| Credentials | ships the demo bundle, provisions it once | stores it in NVS |
| 802.11p radio at 5 900 MHz | – | yes |
| Reception: unwrap GN/BTP, forward | decodes CAM / DENM / SPATEM | yes (all frames) |
## 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`).
Main changes against Niklas Dathe'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.
- **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.
## 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`
(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).
| 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 | `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) |
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.
## 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 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 |
| 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) |
## App changes
- Settings > Connection > ESP32-C5: **link** USB-C / Bluetooth, **transmit** CAM / VAM, **sign
outgoing messages** (on by default). The connection card, top bar and dashboard show the link in
use, the pairing passkey when needed, and signing counters.
- VAM encoder (`VamUperCodec.kt`, TS 103 300-3 V2.3.1, checked against asn1tools) and the VAM
generation rules (`VamGenerationRules.kt`).
- `GnssTimeSource` keeps the last measured phone-clock error while GNSS time drops out indoors. The
bench phone's clock was 14 minutes fast; falling back to it made every transmitted timestamp
jump by 14 minutes.
- Bluetooth permissions (Android 12+) requested at start-up.
## Credentials (demo PKI)
`app/src/main/assets/demo-chain.vcr`, generated 2026-09-23 with Niklas Dathe'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.
## Verification
- **Unit tests** (103): VAM bytes against asn1tools, station-link messages against Niklas Dathe'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,
psid 36, signer the demo AT, all signatures valid, chain valid.
- **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
`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`.
## Open
- 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.
- Real EU PKI enrolment/authorisation (TS 102 941) instead of the demo chain.
File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 660 KiB

+51 -124
View File
@@ -1,7 +1,7 @@
# 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.)
Started. See `docs/04-transmit-setup.md` in the project root for build/flash
steps and how to validate this against your own sniffer.
## Toolchain: use a dedicated terminal (ESP-IDF 5.5.4)
@@ -29,123 +29,6 @@ referenced an older source path under `micrOBU_workspace/v2x-obu-esp32c5/`,
which makes `idf.py fullclean` refuse to run). If that error reappears, delete
`build/` manually rather than fighting it.
## Build and flash
The firmware needs no button, phone or serial connection to start. On every power-up or reset,
`app_main` sets up the radio and starts `tx_task`, which starts driving the simulated route and
sending CAMs on 5900 MHz. A board flashed with this image starts beaconing on its own as soon as it
gets power.
In a fresh PowerShell window:
```powershell
$env:IDF_PYTHON_ENV_PATH = $null; $env:IDF_PATH = $null
. C:\Espressif\frameworks\esp-idf-v5.5.4\export.ps1
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-cam-transmistter
```
1. **Check what the board is running before you flash it.** Both this project and `obu-firmware`
name their image `obu_firmware.bin`, so the file name tells you nothing. Read the app
descriptor instead (replace `COMx` with the board's port):
```powershell
python -m esptool --chip esp32c5 -p COMx read_flash 0x10000 0x100 $env:TEMP\desc.bin
$b = [IO.File]::ReadAllBytes("$env:TEMP\desc.bin")
function S($o,$n){ [Text.Encoding]::ASCII.GetString($b,$o,$n).Trim([char]0) }
"time=" + (S 0x70 16) + " date=" + (S 0x80 16) + " idf=" + (S 0x90 32)
```
`idf=v6.1...` means the board runs the production OBU (`obu-firmware`). Don't flash this beacon
over it. `idf=v5.5.4` means this transmitter, or another bench image.
2. **Build:**
```powershell
idf.py build
```
A rebuild after small changes takes about 1-2 minutes. The output is
`build\obu_firmware.bin`.
3. **Flash** (the board must be on its UART bridge port or its native USB port):
```powershell
idf.py -p COMx flash
```
The flash is good when esptool prints `Hash of data verified.`, then resets the board.
4. **Check that it's transmitting:**
```powershell
idf.py -p COMx monitor
```
(Exit with `Ctrl+]`.) About 1.4 s after reset you should see:
```
W obu-tx: OCB @ 5900 MHz - CAM beacon armed, driving a 103-point street loop
I obu-tx: CAM sent (119 bytes) @ 5900 MHz genDeltaT=1087 pos=53.5531770,10.0220980 50.0 km/h heading 77.0 pt1
```
After that, a `CAM sent` line appears about 3 times a second, with the position, speed and
heading changing. These lines only mean each frame was
handed to the radio. To confirm the frames actually went out, capture them with a second
ESP32-C5 running the receiver firmware.
Don't open the console of the production OBU (COM3) while the phone is attached. Opening the port
resets that board and drops the phone's USB link. The beacon boards have no phone attached, so
this doesn't apply to them.
## Simulated drive
The beacon pretends to be a car driving a loop through St. Georg / Berliner Tor in Hamburg, on
the real streets. The route comes from six waypoints, which you set in `tools/make_route.py`.
**Changing the route:** edit `WAYPOINTS` in `tools/make_route.py`, then run
```powershell
py -3.11 tools/make_route.py
```
The script asks the OSRM demo server (router.project-osrm.org) for a legal driving route through the
waypoints in order and back to the first, then writes three files:
- `main/route_points.h`: the street geometry, thinned to points no more than 1.5 m off the line
(currently 103 points).
- `tools/route_osrm.json`: OSRM's raw answer. `--offline` rebuilds the header from it without the
network.
- `tools/route_map.html`: the route on an OpenStreetMap map. Open it in a browser and check it
before building.
Then build and flash as above. Route data (c) OpenStreetMap contributors, ODbL; routing by OSRM.
**Things to know about the routing:**
- OSRM follows one-way streets and turn bans, so the loop can be longer than the waypoints suggest.
The current one is 5.2 km, with two turn-round detours: a loop via Borgfelder Straße and
Anckelmannsplatz between wp2 and wp3, and one round Nagelsweg, Norderstraße and Repsoldstraße
between wp5 and wp6. To avoid a detour, move the waypoint on either side of it.
- Each waypoint is sent with the direction towards the next one. Without it, points on divided
roads (Beim Strohhause, for example) snap to the carriageway going the other way, and the loop
grows to 8.4 km of U-turns.
**How the car drives** (`main/route.c`):
- **Speed:** it cruises at 50 km/h (`CRUISE_MPS` in `main/main.c`). Each bend gets a speed limit
from its radius, keeping sideways acceleration at 2 m/s², so a 90° junction turn is taken at
about 15 km/h and a gentle curve barely slows the car. It never drops below 10 km/h
(`MIN_CORNER_MPS`). It brakes at 2 m/s² and accelerates at 1.5 m/s², planning braking across as
many points as a bend needs. A lap takes about 7.7 min, averaging 40 km/h.
- **Heading:** the compass bearing of the current straight piece. It changes gradually through
curves but jumps at sharp junction turns.
- **When CAMs are sent:** following ETSI EN 302 637-2, the state is checked every 100 ms. A CAM goes
out when the heading changed by more than 4°, the position by more than 4 m, or the speed by more
than 0.5 m/s since the last one, and at least once a second. That's about 3 CAMs a second at
50 km/h.
- **What's filled in:** position, speed and heading go into both the CAM and the GeoNetworking
source position vector. `genDeltaT` is milliseconds since boot.
- **Testing:** `route.c` only uses standard headers, so you can compile it on the PC with MSYS2 gcc
and simulate a lap.
## CAM encoding
`main/cam.c` IS compiled here (unlike `obu-firmware`'s copy, which is a
@@ -161,12 +44,56 @@ hazard-light GPIO is grounded. No location/alacarte containers.
- `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/route.c` / `.h` - simulated drive round the route loop
- `main/route_points.h` - the route, generated by `tools/make_route.py`
- `main/geonet.c` / `.h` - GeoNetworking Basic/Common/SHB headers + BTP-B
- `main/dot11p.c` / `.h` - 802.11 OCB (QoS Data, broadcast) frame + LLC/SNAP
Known gaps, tracked as TODOs in the source: no real GNSS (the CAM position comes
from the simulated drive above), no real time source (detectionTime/referenceTime hardcoded 0, decodes as
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).
## Running it as a bench beacon
This firmware needs no phone: it beacons a CAM every second by itself
(`TX_INTERVAL_MS`) from station `0x0BADC0DE` (195936478), stationType 5
(passengerCar), at the hardcoded bench position, under the fixed MAC
`02:00:00:00:00:01`, on 5900 MHz. That makes it the quickest way to put known,
repeatable traffic on air, and it is how the 4-bit `yawRateConfidence` encoding
was confirmed over the air on 2026-09-14.
A board with only one USB-C port is fine. This firmware's console is on UART0,
so such a board shows no log output, but nothing here needs the console.
Flash it from the toolchain terminal (ESP-IDF 5.5.4, see the table above):
```powershell
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-cam-transmistter
idf.py -p COM10 -b 921600 flash
```
Or flash the existing build without any toolchain terminal:
```powershell
cd obu-cam-transmistter\build
C:\Espressif\python_env\idf5.5_py3.11_env\Scripts\python.exe -m esptool --chip esp32c5 -p COM10 -b 921600 write_flash --flash_mode dio --flash_freq 80m --flash_size 2MB 0x2000 bootloader/bootloader.bin 0x8000 partition_table/partition-table.bin 0x10000 obu_firmware.bin
```
It starts beaconing as soon as it boots, so there is nothing to start by hand,
and unplugging it is how you stop it.
**It transmits under the same MAC as the phone's CAM pinger**, so on air the two
are told apart by station ID (195936478 here, 999999 for the pinger), never by
source address.
To see what it is sending, capture on the sniffer board and decode:
```powershell
cd capture
py -3.11 live_capture.py COM8
py -3.11 ..\obu-firmware\test\pcap_gn_tally.py recordings\capture_<timestamp>.pcap
```
The tally lists it as SHB / port 2001 / lifetime `0x05`. For the message itself,
decode the payload with `asn1tools` against `asn1/cam_1_4_1.asn` +
`asn1/cdd_1_3_1_1.asn`; re-encoding must return the identical bytes. On
2026-09-14, 72 of 72 frames did.
+2 -2
View File
@@ -1,8 +1,8 @@
# wifi_patches.c is intentionally NOT in this list anymore - superseded by
# tx_custom.c (see that file for why). Left on disk, unused, for history.
idf_component_register(
SRCS "main.c" "denm.c" "cam.c" "geonet.c" "dot11p.c" "tx_custom.c" "route.c"
SRCS "main.c" "denm.c" "cam.c" "geonet.c" "dot11p.c" "tx_custom.c"
INCLUDE_DIRS "."
REQUIRES esp_event esp_timer esp_netif nvs_flash driver esp_phy
REQUIRES esp_event esp_netif nvs_flash driver esp_phy
PRIV_REQUIRES esp_wifi
)
+6 -7
View File
@@ -4,7 +4,6 @@
int geonet_wrap_shb(const uint8_t *its_payload, int its_len,
const uint8_t mac[6], uint8_t station_type,
int32_t latitude_tenmicrodeg, int32_t longitude_tenmicrodeg,
uint16_t speed_cm_s, uint16_t heading_ddeg,
uint16_t btp_dest_port,
uint8_t *out, size_t out_len)
{
@@ -69,12 +68,12 @@ int geonet_wrap_shb(const uint8_t *its_payload, int its_len,
uint32_t lon_u = (uint32_t)longitude_tenmicrodeg;
*p++ = (uint8_t)(lon_u >> 24); *p++ = (uint8_t)(lon_u >> 16);
*p++ = (uint8_t)(lon_u >> 8); *p++ = (uint8_t)(lon_u);
// PAI(1 bit) + Speed(15 bits, signed, 0.01 m/s), packed into 2 bytes. PAI stays 0: the
// position has no accuracy estimate behind it.
uint16_t spd = speed_cm_s > 0x7FFF ? 0x7FFF : speed_cm_s;
*p++ = (uint8_t)(spd >> 8); *p++ = (uint8_t)(spd & 0xFF);
// Heading (16 bits, 0.1 degree units, clockwise from north)
*p++ = (uint8_t)(heading_ddeg >> 8); *p++ = (uint8_t)(heading_ddeg & 0xFF);
// PAI(1 bit) + Speed(15 bits), packed into 2 bytes: 0 = PAI false,
// speed 0 - which is actually correct semantics for a STATIONARY
// vehicle beacon, not just a placeholder.
*p++ = 0x00; *p++ = 0x00;
// Heading (16 bits, 0.1 degree units): 0 = due north / unavailable
*p++ = 0x00; *p++ = 0x00;
// Reserved (4 bytes) - clause 9.8.4: the SHB extended header is the 24-byte Source Position
// Vector FOLLOWED BY a 4-byte reserved field (media-dependent data), 28 bytes in total. These
// four bytes were missing, which is why a standards-compliant receiver read our CAM payload's
-5
View File
@@ -31,10 +31,6 @@
// working (same extended header shape as CAM). Fine for a single-vehicle
// beacon; revisit if you need real multi-hop forwarding later.
//
// `speed_cm_s` (0.01 m/s) and `heading_ddeg` (0.1 deg) also go into the Source Long Position
// Vector; pass the same values as the CAM's high-frequency container. Speed is a 15-bit field, so
// values above 32767 are clamped.
//
// `btp_dest_port` is the BTP-B destination port for the service being carried
// (ETSI TS 103 248): 2001 = CAM, 2002 = DENM, 2003 = MAPEM, 2004 = SPATEM, ...
//
@@ -42,7 +38,6 @@
int geonet_wrap_shb(const uint8_t *its_payload, int its_len,
const uint8_t mac[6], uint8_t station_type,
int32_t latitude_tenmicrodeg, int32_t longitude_tenmicrodeg,
uint16_t speed_cm_s, uint16_t heading_ddeg,
uint16_t btp_dest_port,
uint8_t *out, size_t out_len);
+30 -82
View File
@@ -1,11 +1,7 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_timer.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event.h"
@@ -18,17 +14,13 @@
#include "geonet.h"
#include "dot11p.h"
#include "tx_custom.h"
#include "route.h"
#include "route_points.h"
static const char *TAG = "obu-tx";
// CAM beacon for a simulated car driving round a block in Hamburg (see route.c). The CAM
// generation rules follow ETSI EN 302 637-2 clause 6.1.3: every CHECK_INTERVAL_MS the car's state
// is compared with the last CAM sent, and a new CAM goes out when the heading changed by more than
// 4 degrees, the position by more than 4 m, the speed by more than 0.5 m/s, or 1 s has passed.
// There is no hazard-light gating - CAM is a continuous beacon, unlike the event-triggered DENM.
// Transmits on 5900 MHz like the working Rust reference (esp32-c_its-companion, feat/tx-cam).
// CAM beacon: transmit a Cooperative Awareness Message every TX_INTERVAL_MS,
// unconditionally (no hazard-light gating - CAM is a continuous beacon, unlike
// the event-triggered DENM). Matches the working Rust reference
// (esp32-c_its-companion, feat/tx-cam), which beacons CAM on 5900 MHz.
// ISOLATION TEST for whether tx_custom.c is the blocker.
// 1 = transmit via the STANDARD, well-tested esp_wifi_80211_tx() using a
@@ -63,19 +55,15 @@ static const char *TAG = "obu-tx";
#define VEHICLE_LENGTH_DM 40 // VehicleLengthValue, 10cm steps (4.0 m)
#define VEHICLE_WIDTH_DM 18 // VehicleWidth, 10cm steps (1.8 m)
#define BTP_PORT_CAM 2001 // BTP-B destination port for CAM (ETSI TS 103 248)
#define CHECK_INTERVAL_MS 100 // T_CheckCamGen: how often the generation rules are evaluated
#define CAM_MAX_INTERVAL_MS 1000 // T_GenCamMax: a CAM goes out at least this often
#define CAM_HEADING_DDEG 40 // > 4 degrees heading change triggers a CAM
#define CAM_POSITION_M 4.0 // > 4 m position change triggers a CAM
#define CAM_SPEED_CM_S 50 // > 0.5 m/s speed change triggers a CAM
#define TX_INTERVAL_MS 1000 // CAM beacon period (1 Hz; ITS allows 1-10 Hz)
// ---- Simulated drive ----
// route_points (main/route_points.h) is the street geometry of a driving loop through six waypoints
// in St. Georg, generated by tools/make_route.py from OpenStreetMap via OSRM. To change the route,
// edit WAYPOINTS in that script and rerun it. No GNSS is wired in; replace with real fixes once
// there is one.
#define CRUISE_MPS (50.0 / 3.6) // 50 km/h, the urban limit
#define MIN_CORNER_MPS (10.0 / 3.6) // slowest the car goes, for hairpins and U-turns
// Bench location, hardcoded since there's no GNSS module wired in yet and
// the unit is genuinely stationary here: 53°33'16.8"N 10°01'20.6"E, in
// 1/10-microdegree units (decimal_degrees * 10,000,000). Replace with real
// GNSS output once you have a fix source; until then this beats 0/0
// ("Null Island"), which is an obvious placeholder-tell on any map.
#define BENCH_LATITUDE_TENMICRODEG 535546667
#define BENCH_LONGITUDE_TENMICRODEG 100223889
// Single source of truth for the pseudonym/link-layer address: used both as
// the 802.11 source MAC (Addr2) and as GN_ADDR's MID field, since the GN
@@ -90,28 +78,33 @@ static const uint8_t pseudonym_mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};
extern void phy_11p_set(int enable, int unused);
extern void phy_change_channel(int freq_mhz, int bw_mode, int sec_chan_offset, int unused);
static void send_cam(const route_state_t *car, uint16_t gen_delta)
static void send_cam(void)
{
// GenerationDeltaTime is TimestampIts mod 65536 (ms). No RTC/GNSS time here,
// so use a free-running ms counter that advances one beacon-interval per
// send. It wraps at 65536, which is exactly the field's defined behaviour.
static uint16_t gen_delta = 0;
uint8_t frame[300];
cam_fields_t fields = {
.station_id = STATION_ID,
.station_type = STATION_TYPE,
.generation_delta_time = gen_delta,
.latitude_tenmicrodeg = car->latitude_tenmicrodeg,
.longitude_tenmicrodeg = car->longitude_tenmicrodeg,
.speed_cm_s = car->speed_cm_s,
.heading_ddeg = car->heading_ddeg,
.latitude_tenmicrodeg = BENCH_LATITUDE_TENMICRODEG,
.longitude_tenmicrodeg = BENCH_LONGITUDE_TENMICRODEG,
.speed_cm_s = 0, // stationary
.heading_ddeg = 3601, // HeadingValue unavailable (no heading source)
.vehicle_length_dm = VEHICLE_LENGTH_DM,
.vehicle_width_dm = VEHICLE_WIDTH_DM,
};
gen_delta += TX_INTERVAL_MS;
uint8_t cam_payload[96];
int cam_len = cam_encode(&fields, cam_payload, sizeof(cam_payload));
uint8_t gn_payload[160];
int gn_len = geonet_wrap_shb(cam_payload, cam_len, pseudonym_mac, STATION_TYPE,
car->latitude_tenmicrodeg, car->longitude_tenmicrodeg,
car->speed_cm_s, car->heading_ddeg,
BENCH_LATITUDE_TENMICRODEG, BENCH_LONGITUDE_TENMICRODEG,
BTP_PORT_CAM, gn_payload, sizeof(gn_payload));
// qos=false for the standard-TX path (esp_wifi_80211_tx accepts only non-QoS
@@ -134,10 +127,7 @@ static void send_cam(const route_state_t *car, uint16_t gen_delta)
if (err != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_80211_tx (standard) failed: %d", err);
} else {
ESP_LOGI(TAG, "CAM sent (%d bytes) @ %d MHz genDeltaT=%u pos=%.7f,%.7f %.1f km/h heading %.1f pt%d",
frame_len, TX_FREQ_MHZ, gen_delta,
car->latitude_tenmicrodeg / 1e7, car->longitude_tenmicrodeg / 1e7,
car->speed_cm_s * 0.036, car->heading_ddeg / 10.0, car->segment + 1);
ESP_LOGI(TAG, "CAM sent via STANDARD tx (%d bytes) @ %d MHz genDeltaT=%u", frame_len, TX_FREQ_MHZ, gen_delta);
}
#else
// tx_custom path: submits to the driver's internal HMAC TX path,
@@ -161,49 +151,12 @@ static void send_cam(const route_state_t *car, uint16_t gen_delta)
}
}
static bool cam_due(const route_state_t *car, const route_state_t *last, int64_t since_last_ms)
{
if (since_last_ms >= CAM_MAX_INTERVAL_MS) {
return true;
}
int dh = abs((int)car->heading_ddeg - (int)last->heading_ddeg);
if (dh > 1800) {
dh = 3600 - dh;
}
if (dh > CAM_HEADING_DDEG) {
return true;
}
if (abs((int)car->speed_cm_s - (int)last->speed_cm_s) > CAM_SPEED_CM_S) {
return true;
}
// Flat-earth distance is plenty for a 4 m threshold.
double north_m = (car->latitude_tenmicrodeg - last->latitude_tenmicrodeg) * 0.0111194930;
double east_m = (car->longitude_tenmicrodeg - last->longitude_tenmicrodeg) * 0.0111194930
* cos(car->latitude_tenmicrodeg / 1e7 * M_PI / 180.0);
return north_m * north_m + east_m * east_m > CAM_POSITION_M * CAM_POSITION_M;
}
static void tx_task(void *arg)
{
route_state_t car;
route_state_t last_sent;
int64_t last_sent_ms = 0;
bool sent_any = false;
TickType_t wake = xTaskGetTickCount();
route_step(0.0, &car);
while (1) {
int64_t now_ms = esp_timer_get_time() / 1000;
if (!sent_any || cam_due(&car, &last_sent, now_ms - last_sent_ms)) {
// GenerationDeltaTime is TimestampIts mod 65536 (ms). No real clock here, so use
// milliseconds since boot, which advances at the right rate.
send_cam(&car, (uint16_t)now_ms);
last_sent = car;
last_sent_ms = now_ms;
sent_any = true;
}
vTaskDelayUntil(&wake, pdMS_TO_TICKS(CHECK_INTERVAL_MS));
route_step(CHECK_INTERVAL_MS / 1000.0, &car);
// CAM is a continuous beacon - send every interval, unconditionally.
send_cam();
vTaskDelay(pdMS_TO_TICKS(TX_INTERVAL_MS));
}
}
@@ -302,13 +255,8 @@ void app_main(void)
phy_change_channel(TX_FREQ_MHZ, 1, 0, 0);
ESP_LOGI(TAG, "phy_change_channel returned");
if (route_init(route_points, sizeof(route_points) / sizeof(route_points[0]),
CRUISE_MPS, MIN_CORNER_MPS) != 0) {
ESP_LOGE(TAG, "route_init failed - check route_points");
return;
}
ESP_LOGW(TAG, "OCB @ %d MHz - CAM beacon armed, driving a %d-point street loop",
TX_FREQ_MHZ, (int)(sizeof(route_points) / sizeof(route_points[0])));
ESP_LOGW(TAG, "OCB @ %d MHz - CAM beacon armed, transmitting every %d ms",
TX_FREQ_MHZ, TX_INTERVAL_MS);
xTaskCreate(tx_task, "tx_task", 4096, NULL, 5, NULL);
}
-125
View File
@@ -1,125 +0,0 @@
#include "route.h"
#include <math.h>
#define DEG_TO_RAD (M_PI / 180.0)
#define METRES_PER_DEG 111194.93 // mean Earth radius 6371 km; a block is small enough for a flat projection
#define ACCEL_MPS2 1.5 // pulling away from a corner
#define DECEL_MPS2 2.0 // braking ahead of a corner
#define LATERAL_MPS2 2.0 // sideways acceleration a normal driver takes a bend at
#define STRAIGHT_DEG 3.0 // kinks gentler than this are digitising noise, not bends
#define BEND_SPAN_M 15.0 // longest segment counted towards a bend's radius (see route_init)
static const route_point_t *s_pts;
static int s_n;
static double s_len[ROUTE_MAX_POINTS]; // segment i runs from point i to point (i+1) % n
static double s_bearing_deg[ROUTE_MAX_POINTS];
static double s_corner_mps[ROUTE_MAX_POINTS]; // speed limit at point i, where segment i starts
static double s_cruise_mps;
static int s_seg;
static double s_pos_m; // distance along the current segment
static double segment_speed(int seg, double pos_m)
{
double v = s_cruise_mps;
double pull_away = sqrt(s_corner_mps[seg] * s_corner_mps[seg] + 2.0 * ACCEL_MPS2 * pos_m);
int next = (seg + 1) % s_n;
double braking = sqrt(s_corner_mps[next] * s_corner_mps[next]
+ 2.0 * DECEL_MPS2 * (s_len[seg] - pos_m));
if (pull_away < v) v = pull_away;
if (braking < v) v = braking;
return v;
}
int route_init(const route_point_t *points, int n, double cruise_mps, double min_corner_mps)
{
if (n < 2 || n > ROUTE_MAX_POINTS) {
return -1;
}
s_pts = points;
s_n = n;
s_cruise_mps = cruise_mps;
for (int i = 0; i < n; i++) {
const route_point_t *a = &points[i];
const route_point_t *b = &points[(i + 1) % n];
double mid_lat = (a->latitude_tenmicrodeg + (double)b->latitude_tenmicrodeg) / 2e7;
double north_m = (b->latitude_tenmicrodeg - a->latitude_tenmicrodeg) / 1e7 * METRES_PER_DEG;
double east_m = (b->longitude_tenmicrodeg - a->longitude_tenmicrodeg) / 1e7 * METRES_PER_DEG
* cos(mid_lat * DEG_TO_RAD);
s_len[i] = sqrt(north_m * north_m + east_m * east_m);
if (s_len[i] < 0.01) {
return -1;
}
double bearing = atan2(east_m, north_m) / DEG_TO_RAD;
s_bearing_deg[i] = bearing < 0 ? bearing + 360.0 : bearing;
}
// Speed limit at each point from how tight the bend there is. A polyline bend of angle theta
// between segments of length L approximates an arc of radius L / theta, and a car takes a
// radius R at sqrt(a_lat * R). L is capped at BEND_SPAN_M: at a junction the two streets can be
// hundreds of metres long, but the car still turns within the width of the crossing.
for (int i = 0; i < n; i++) {
double turn = fabs(s_bearing_deg[i] - s_bearing_deg[(i + n - 1) % n]);
if (turn > 180.0) {
turn = 360.0 - turn;
}
double v = cruise_mps;
if (turn > STRAIGHT_DEG) {
double span = s_len[(i + n - 1) % n] < s_len[i] ? s_len[(i + n - 1) % n] : s_len[i];
if (span > BEND_SPAN_M) {
span = BEND_SPAN_M;
}
v = sqrt(LATERAL_MPS2 * span / (turn * DEG_TO_RAD));
}
if (v > cruise_mps) v = cruise_mps;
if (v < min_corner_mps) v = min_corner_mps;
s_corner_mps[i] = v;
}
// A point's limit also has to respect the bends after it (the car must be able to brake for
// them within the segments in between) and before it (it can only have sped up so much since).
// segment_speed only looks at the two ends of a segment, so settle this here. Limits only ever
// go down, so repeating the two passes until nothing changes terminates.
for (int changed = 1; changed;) {
changed = 0;
for (int k = 0; k < 2 * n; k++) {
int i = (2 * n - 1 - k) % n; // backwards: braking
int next = (i + 1) % n;
double v = sqrt(s_corner_mps[next] * s_corner_mps[next] + 2.0 * DECEL_MPS2 * s_len[i]);
if (v < s_corner_mps[i] - 1e-9) { s_corner_mps[i] = v; changed = 1; }
}
for (int k = 0; k < 2 * n; k++) {
int i = k % n; // forwards: accelerating
int next = (i + 1) % n;
double v = sqrt(s_corner_mps[i] * s_corner_mps[i] + 2.0 * ACCEL_MPS2 * s_len[i]);
if (v < s_corner_mps[next] - 1e-9) { s_corner_mps[next] = v; changed = 1; }
}
}
s_seg = 0;
s_pos_m = 0.0;
return 0;
}
void route_step(double dt_s, route_state_t *out)
{
// Advance with the speed at the start of the step; at 100 ms steps the error is well under a metre.
double d = segment_speed(s_seg, s_pos_m) * dt_s;
while (s_pos_m + d >= s_len[s_seg]) {
d -= s_len[s_seg] - s_pos_m;
s_seg = (s_seg + 1) % s_n;
s_pos_m = 0.0;
}
s_pos_m += d;
const route_point_t *a = &s_pts[s_seg];
const route_point_t *b = &s_pts[(s_seg + 1) % s_n];
double f = s_pos_m / s_len[s_seg];
out->latitude_tenmicrodeg = (int32_t)lround(a->latitude_tenmicrodeg
+ f * (b->latitude_tenmicrodeg - a->latitude_tenmicrodeg));
out->longitude_tenmicrodeg = (int32_t)lround(a->longitude_tenmicrodeg
+ f * (b->longitude_tenmicrodeg - a->longitude_tenmicrodeg));
out->speed_cm_s = (uint16_t)lround(segment_speed(s_seg, s_pos_m) * 100.0);
out->heading_ddeg = (uint16_t)(lround(s_bearing_deg[s_seg] * 10.0) % 3600);
out->segment = s_seg;
}
-40
View File
@@ -1,40 +0,0 @@
#ifndef ROUTE_H
#define ROUTE_H
#include <stdint.h>
// Simulated drive around a closed loop of waypoints, so the beacon looks like a
// car going round the block instead of a parked one.
//
// The car follows straight lines between the points and goes from the last one
// back to the first, forever. For street-following, the points are the street
// geometry from tools/make_route.py (main/route_points.h). Speed is a function
// of where the car is on a segment: it cruises, brakes ahead of each bend down to
// the speed that bend allows, and accelerates away after it. Heading is the
// bearing of the current segment.
//
// Uses only standard headers, so it also compiles on the host for testing.
typedef struct {
int32_t latitude_tenmicrodeg; // 1/10 microdegree, same units as the CAM
int32_t longitude_tenmicrodeg;
} route_point_t;
typedef struct {
int32_t latitude_tenmicrodeg;
int32_t longitude_tenmicrodeg;
uint16_t speed_cm_s; // SpeedValue units (0.01 m/s)
uint16_t heading_ddeg; // HeadingValue units (0.1 deg, 0..3599, 0 = north, clockwise)
int segment; // index of the route point the car last passed
} route_state_t;
#define ROUTE_MAX_POINTS 512 // keep in step with MAX_POINTS in tools/make_route.py
// `points` must stay valid for as long as the route is used. Returns 0, or -1
// if n is out of range (2..ROUTE_MAX_POINTS) or a segment has zero length.
// min_corner_mps is the slowest the car ever goes (hairpins, U-turns).
int route_init(const route_point_t *points, int n, double cruise_mps, double min_corner_mps);
// Moves the car on by dt_s seconds and writes its new position into `out`.
void route_step(double dt_s, route_state_t *out);
#endif
-116
View File
@@ -1,116 +0,0 @@
// GENERATED by tools/make_route.py - do not edit by hand; change WAYPOINTS there and rerun.
// Route data (c) OpenStreetMap contributors, ODbL. Routing by OSRM.
//
// Driving loop through 6 waypoints: 5179 m (legs 147 m, 1837 m, 381 m, 819 m, 1234 m, 761 m), 103 points after
// simplifying to 1.5 m. Streets: Beim Strohhause, Berlinertordamm, Berliner Tor, Bei der Hauptfeuerwache, Westphalensweg, Berliner Tor, Berlinertordamm, Borgfelder Straße, Anckelmannstraße, Anckelmannsplatz, Bürgerweide, Wallstraße, Lübeckertordamm, Steindamm, Kreuzweg, Adenauerallee, Nagelsweg, Norderstraße, Repsoldstraße, Kurt-Schumacher-Allee, Kreuzweg, Adenauerallee, Kurt-Schumacher-Allee, Beim Strohhause.
#ifndef ROUTE_POINTS_H
#define ROUTE_POINTS_H
#include "route.h"
static const route_point_t route_points[] = {
{ 535531770, 100220980 },
{ 535534470, 100240600 },
{ 535535790, 100244160 },
{ 535536400, 100244520 },
{ 535537130, 100244160 },
{ 535538480, 100242840 },
{ 535538720, 100242140 },
{ 535540390, 100240200 },
{ 535548880, 100233930 },
{ 535549470, 100235130 },
{ 535554140, 100253280 },
{ 535553570, 100254580 },
{ 535546070, 100251700 },
{ 535543130, 100250020 },
{ 535542570, 100249130 },
{ 535542760, 100247800 },
{ 535539980, 100244600 },
{ 535538720, 100242140 },
{ 535538140, 100241960 },
{ 535535720, 100243380 },
{ 535535300, 100244470 },
{ 535535090, 100246580 },
{ 535536830, 100264460 },
{ 535537600, 100270920 },
{ 535538520, 100275220 },
{ 535541110, 100290830 },
{ 535540170, 100291550 },
{ 535539890, 100294430 },
{ 535539580, 100295330 },
{ 535532290, 100299300 },
{ 535527980, 100302450 },
{ 535525130, 100291880 },
{ 535524220, 100289760 },
{ 535522900, 100287820 },
{ 535522890, 100285300 },
{ 535522610, 100282810 },
{ 535520620, 100276050 },
{ 535519820, 100271130 },
{ 535519670, 100269030 },
{ 535520220, 100267120 },
{ 535520930, 100262840 },
{ 535521850, 100260020 },
{ 535522840, 100258210 },
{ 535527790, 100257880 },
{ 535538650, 100261370 },
{ 535551660, 100266470 },
{ 535555790, 100268750 },
{ 535559620, 100271540 },
{ 535561120, 100272050 },
{ 535562430, 100271250 },
{ 535563830, 100269390 },
{ 535569610, 100260190 },
{ 535579530, 100242810 },
{ 535584090, 100237660 },
{ 535585850, 100234670 },
{ 535584970, 100230060 },
{ 535584000, 100227260 },
{ 535580730, 100222030 },
{ 535579100, 100218590 },
{ 535574500, 100208430 },
{ 535570560, 100199010 },
{ 535568130, 100194820 },
{ 535564910, 100187620 },
{ 535563990, 100184630 },
{ 535562540, 100181160 },
{ 535559780, 100176310 },
{ 535542180, 100136840 },
{ 535539720, 100133430 },
{ 535537350, 100132010 },
{ 535534760, 100131390 },
{ 535523840, 100132690 },
{ 535524980, 100155090 },
{ 535524890, 100156360 },
{ 535524440, 100157650 },
{ 535523030, 100158530 },
{ 535517610, 100158580 },
{ 535504440, 100168810 },
{ 535501360, 100156400 },
{ 535499250, 100144880 },
{ 535498470, 100133880 },
{ 535498630, 100126150 },
{ 535499110, 100121980 },
{ 535504260, 100117230 },
{ 535505720, 100115500 },
{ 535507630, 100112310 },
{ 535508400, 100111560 },
{ 535510000, 100110940 },
{ 535511390, 100119560 },
{ 535512440, 100122280 },
{ 535514510, 100132770 },
{ 535515020, 100134120 },
{ 535516630, 100135630 },
{ 535518260, 100136100 },
{ 535523950, 100134870 },
{ 535524980, 100155090 },
{ 535524890, 100156360 },
{ 535524440, 100157650 },
{ 535523470, 100158460 },
{ 535518560, 100158480 },
{ 535519070, 100162430 },
{ 535522260, 100178080 },
{ 535527880, 100197650 },
{ 535530060, 100209020 },
};
#endif
-170
View File
@@ -1,170 +0,0 @@
"""Turn the beacon's waypoints into a street-following route for main/route_points.h.
Asks the OSRM demo server (router.project-osrm.org, OpenStreetMap data) for a driving route that
visits WAYPOINTS in order and returns to the first, thins the street geometry out, and writes:
main/route_points.h the C array the firmware drives (commit this)
tools/route_osrm.json the raw OSRM answer, so the header can be regenerated offline (--offline)
tools/route_map.html the route over an OpenStreetMap map, to check it before flashing
Each waypoint also gets a bearing (the direction towards the next waypoint), so OSRM snaps it onto
the carriageway going that way. Without it, points on divided roads land on the wrong side and
every leg grows a U-turn detour.
Usage (Python 3.8+, standard library only):
py tools/make_route.py fetch from OSRM, then write all three files
py -3 tools/make_route.py --offline rebuild from the saved route_osrm.json
Route data (c) OpenStreetMap contributors, ODbL. Routing by OSRM.
"""
import argparse
import json
import math
import pathlib
import urllib.request
# (latitude, longitude) in decimal degrees, in driving order. The route closes back to the first.
WAYPOINTS = [
(53.553309, 10.022043),
(53.553611, 10.024146),
(53.556164, 10.027121),
(53.558310, 10.023362),
(53.554062, 10.013515),
(53.551540, 10.013398),
]
BEARING_TOLERANCE_DEG = 60 # how far the road's direction may differ from the waypoint bearing
SIMPLIFY_M = 1.5 # drop points that move the line by less than this
MAX_POINTS = 512 # must match ROUTE_MAX_POINTS in main/route.h
HERE = pathlib.Path(__file__).resolve().parent
PROJECT = HERE.parent
OSRM_JSON = HERE / "route_osrm.json"
HEADER = PROJECT / "main" / "route_points.h"
MAP_HTML = HERE / "route_map.html"
METRES_PER_DEG = 111194.93
def to_xy(lat, lon, lat0):
return (lon * METRES_PER_DEG * math.cos(math.radians(lat0)), lat * METRES_PER_DEG)
def bearing(a, b):
north = b[0] - a[0]
east = (b[1] - a[1]) * math.cos(math.radians(a[0]))
return math.degrees(math.atan2(east, north)) % 360
def fetch():
n = len(WAYPOINTS)
pts = WAYPOINTS + [WAYPOINTS[0]]
bearings = [round(bearing(WAYPOINTS[i], WAYPOINTS[(i + 1) % n])) for i in range(n)]
bearings.append(bearings[0])
url = ("https://router.project-osrm.org/route/v1/driving/"
+ ";".join(f"{lon},{lat}" for lat, lon in pts)
+ "?overview=full&geometries=geojson&steps=true&bearings="
+ ";".join(f"{b},{BEARING_TOLERANCE_DEG}" for b in bearings))
req = urllib.request.Request(url, headers={"User-Agent": "MicrOBU-route-tool"})
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.load(resp)
if data.get("code") != "Ok":
raise SystemExit(f"OSRM error: {data.get('code')} {data.get('message')}")
OSRM_JSON.write_text(json.dumps(data, indent=1), encoding="utf-8")
return data
def simplify(xy, tol):
"""Douglas-Peucker, iterative. Keeps the first and last point."""
keep = [False] * len(xy)
keep[0] = keep[-1] = True
stack = [(0, len(xy) - 1)]
while stack:
a, b = stack.pop()
(ax, ay), (bx, by) = xy[a], xy[b]
dx, dy = bx - ax, by - ay
seg2 = dx * dx + dy * dy
worst, worst_d = -1, tol
for i in range(a + 1, b):
px, py = xy[i]
if seg2 == 0:
d = math.hypot(px - ax, py - ay)
else:
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / seg2))
d = math.hypot(px - ax - t * dx, py - ay - t * dy)
if d > worst_d:
worst, worst_d = i, d
if worst >= 0:
keep[worst] = True
stack += [(a, worst), (worst, b)]
return [i for i, k in enumerate(keep) if k]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--offline", action="store_true", help="use the saved route_osrm.json")
args = ap.parse_args()
data = json.loads(OSRM_JSON.read_text(encoding="utf-8")) if args.offline else fetch()
route = data["routes"][0]
# GeoJSON is [lon, lat]; round to the CAM's 1/10-microdegree grid and drop repeats.
raw = []
for lon, lat in route["geometry"]["coordinates"]:
p = (round(lat * 1e7), round(lon * 1e7))
if not raw or p != raw[-1]:
raw.append(p)
if raw[0] == raw[-1]:
raw.pop()
closed = raw + [raw[0]]
lat0 = closed[0][0] / 1e7
xy = [to_xy(p[0] / 1e7, p[1] / 1e7, lat0) for p in closed]
pts = [closed[i] for i in simplify(xy, SIMPLIFY_M)][:-1]
if len(pts) > MAX_POINTS:
raise SystemExit(f"{len(pts)} points is more than MAX_POINTS={MAX_POINTS}; raise SIMPLIFY_M")
streets = []
for leg in route["legs"]:
for step in leg["steps"]:
if step["name"] and (not streets or streets[-1] != step["name"]):
streets.append(step["name"])
legs = ", ".join(f"{round(l['distance'])} m" for l in route["legs"])
lines = [
"// GENERATED by tools/make_route.py - do not edit by hand; change WAYPOINTS there and rerun.",
"// Route data (c) OpenStreetMap contributors, ODbL. Routing by OSRM.",
"//",
f"// Driving loop through {len(WAYPOINTS)} waypoints: {round(route['distance'])} m "
f"(legs {legs}), {len(pts)} points after",
f"// simplifying to {SIMPLIFY_M} m. Streets: {', '.join(streets)}.",
"#ifndef ROUTE_POINTS_H",
"#define ROUTE_POINTS_H",
'#include "route.h"',
"",
"static const route_point_t route_points[] = {",
]
lines += [f" {{ {lat}, {lon} }}," for lat, lon in pts]
lines += ["};", "", "#endif", ""]
HEADER.write_text("\n".join(lines), encoding="utf-8", newline="\n")
MAP_HTML.write_text(f"""<!doctype html><meta charset="utf-8"><title>Beacon route</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>html,body,#m{{height:100%;margin:0}}</style><div id="m"></div><script>
const pts={json.dumps([[p[0] / 1e7, p[1] / 1e7] for p in pts])};
const wps={json.dumps(WAYPOINTS)};
const m=L.map('m');
L.tileLayer('https://tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png',{{maxZoom:19,
attribution:'&copy; OpenStreetMap contributors'}}).addTo(m);
const line=L.polyline(pts.concat([pts[0]]),{{color:'#d33',weight:4}}).addTo(m);
wps.forEach((w,i)=>L.marker(w,{{title:'wp'+(i+1)}}).bindTooltip('wp'+(i+1),{{permanent:true}}).addTo(m));
L.circleMarker(pts[0],{{radius:7,color:'#060'}}).bindTooltip('start').addTo(m);
m.fitBounds(line.getBounds(),{{padding:[20,20]}});
</script>
""", encoding="utf-8")
print(f"{round(route['distance'])} m, legs {legs}")
print(f"{len(route['geometry']['coordinates'])} OSRM points -> {len(pts)} after simplifying")
print(f"wrote {HEADER.relative_to(PROJECT)}, {OSRM_JSON.relative_to(PROJECT)}, "
f"{MAP_HTML.relative_to(PROJECT)}")
if __name__ == "__main__":
main()
-14
View File
@@ -1,14 +0,0 @@
<!doctype html><meta charset="utf-8"><title>Beacon route</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>html,body,#m{height:100%;margin:0}</style><div id="m"></div><script>
const pts=[[53.553177, 10.022098], [53.553447, 10.02406], [53.553579, 10.024416], [53.55364, 10.024452], [53.553713, 10.024416], [53.553848, 10.024284], [53.553872, 10.024214], [53.554039, 10.02402], [53.554888, 10.023393], [53.554947, 10.023513], [53.555414, 10.025328], [53.555357, 10.025458], [53.554607, 10.02517], [53.554313, 10.025002], [53.554257, 10.024913], [53.554276, 10.02478], [53.553998, 10.02446], [53.553872, 10.024214], [53.553814, 10.024196], [53.553572, 10.024338], [53.55353, 10.024447], [53.553509, 10.024658], [53.553683, 10.026446], [53.55376, 10.027092], [53.553852, 10.027522], [53.554111, 10.029083], [53.554017, 10.029155], [53.553989, 10.029443], [53.553958, 10.029533], [53.553229, 10.02993], [53.552798, 10.030245], [53.552513, 10.029188], [53.552422, 10.028976], [53.55229, 10.028782], [53.552289, 10.02853], [53.552261, 10.028281], [53.552062, 10.027605], [53.551982, 10.027113], [53.551967, 10.026903], [53.552022, 10.026712], [53.552093, 10.026284], [53.552185, 10.026002], [53.552284, 10.025821], [53.552779, 10.025788], [53.553865, 10.026137], [53.555166, 10.026647], [53.555579, 10.026875], [53.555962, 10.027154], [53.556112, 10.027205], [53.556243, 10.027125], [53.556383, 10.026939], [53.556961, 10.026019], [53.557953, 10.024281], [53.558409, 10.023766], [53.558585, 10.023467], [53.558497, 10.023006], [53.5584, 10.022726], [53.558073, 10.022203], [53.55791, 10.021859], [53.55745, 10.020843], [53.557056, 10.019901], [53.556813, 10.019482], [53.556491, 10.018762], [53.556399, 10.018463], [53.556254, 10.018116], [53.555978, 10.017631], [53.554218, 10.013684], [53.553972, 10.013343], [53.553735, 10.013201], [53.553476, 10.013139], [53.552384, 10.013269], [53.552498, 10.015509], [53.552489, 10.015636], [53.552444, 10.015765], [53.552303, 10.015853], [53.551761, 10.015858], [53.550444, 10.016881], [53.550136, 10.01564], [53.549925, 10.014488], [53.549847, 10.013388], [53.549863, 10.012615], [53.549911, 10.012198], [53.550426, 10.011723], [53.550572, 10.01155], [53.550763, 10.011231], [53.55084, 10.011156], [53.551, 10.011094], [53.551139, 10.011956], [53.551244, 10.012228], [53.551451, 10.013277], [53.551502, 10.013412], [53.551663, 10.013563], [53.551826, 10.01361], [53.552395, 10.013487], [53.552498, 10.015509], [53.552489, 10.015636], [53.552444, 10.015765], [53.552347, 10.015846], [53.551856, 10.015848], [53.551907, 10.016243], [53.552226, 10.017808], [53.552788, 10.019765], [53.553006, 10.020902]];
const wps=[[53.553309, 10.022043], [53.553611, 10.024146], [53.556164, 10.027121], [53.55831, 10.023362], [53.554062, 10.013515], [53.55154, 10.013398]];
const m=L.map('m');
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19,
attribution:'&copy; OpenStreetMap contributors'}).addTo(m);
const line=L.polyline(pts.concat([pts[0]]),{color:'#d33',weight:4}).addTo(m);
wps.forEach((w,i)=>L.marker(w,{title:'wp'+(i+1)}).bindTooltip('wp'+(i+1),{permanent:true}).addTo(m));
L.circleMarker(pts[0],{radius:7,color:'#060'}).bindTooltip('start').addTo(m);
m.fitBounds(line.getBounds(),{padding:[20,20]});
</script>
File diff suppressed because it is too large Load Diff
+7 -39
View File
@@ -1,41 +1,9 @@
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")
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")
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")
endif()
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")
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(microbu_firmware)
include("${CMAKE_CURRENT_LIST_DIR}/cmake/no_efuse_writes.cmake")
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()
# 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.
idf_component_get_property(bt_lib bt COMPONENT_LIB)
if(bt_lib)
target_compile_options(${bt_lib} PRIVATE -Wno-error=array-bounds)
endif()
# No longer need -Wl,-zmuldefs here - that was only for main/wifi_patches.c's
# symbol-override attempt (which didn't work anyway; see docs/04-transmit-setup.md),
# and that file is no longer part of the build. Superseded by main/tx_custom.c,
# which bypasses the gate at a different layer instead of trying to override it.
project(obu_firmware)
+92 -136
View File
@@ -1,150 +1,106 @@
# 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
This project builds against the receiver-firmware's pinned ESP-IDF **6.1**.
The separate `obu-cam-transmistter` project builds against the global ESP-IDF
**5.5.4**. Exporting both 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.
## Every new PowerShell session
Activate the toolchain (obu-firmware has no esp-idf of its own — reuse the
receiver firmware's already-installed checkout):
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
$env:IDF_TOOLS_PATH = "C:\Espressif"
C:\Espressif\frameworks\esp-idf-v6.0.2\export.ps1
C:\Users\Ashin\Documents\micrOBU_workspace\its-g5-receiver-firmware\esp-idf\export.ps1
idf.py --version
```
## Build & flash
```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 COM5 -b 921600 flash monitor
```
## Flash
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).
```powershell
idf.py -p COM6 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/`:
```powershell
python -m esptool --chip esp32c5 -p COM6 --no-stub --before=no-reset --after=hard-reset write-flash "@flash_args"
```
A board left in download mode comes back after unplugging and replugging without BOOT.
**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).
### First flash onto a board with other firmware
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.
Swap `COM5` for whatever port the ESP32-C5 enumerates as (Device Manager →
Ports). `monitor` opens the serial console after flashing — `Ctrl+]` to exit.
## 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 CAM serial link
(`serial_link.c`) 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.** `SERIAL_LINK_MAX_PAYLOAD` is 512 on both sides.
A phone at 512 talking to firmware still at 160 (or vice versa) silently
rejects every large frame at the `length exceeds max, resync` branch. Never
update one side alone.
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 heartbeat 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.
5. **If it connects but no CAM_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 /
oversize-drop / CRC-error totals from the heartbeat. A rising `tx fail` means
CAMs reach the ESP32 but `esp_wifi_80211_tx` rejects them — a radio problem,
not a link problem.
## 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 — always export from
the receiver-firmware's pinned checkout, since this firmware's undocumented
PHY/driver internals were verified against that specific build.
+15 -130
View File
@@ -1,134 +1,19 @@
# obu-firmware
# OBU transmit firmware - Phase 2 (in progress: HLN-SV DENM beacon)
The production OBU firmware: the ESP32-C5 half of the MicrOBU station (Seeed XIAO ESP32-C5).
Started. See `docs/04-transmit-setup.md` in the project root for build/flash
steps and how to validate this against your own sniffer.
## Since 2026-11-10: Niklas Dathe's microbu-firmware architecture
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.
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.
- `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
Layout:
| 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 |
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.
Board: `CONFIG_MICROBU_BOARD_XIAO_C5` (sdkconfig.defaults). Their default is `mainboard-v5`, the
custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
### MicrOBU additions (search for `MicrOBU`)
- **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 over 494 bytes does not fit a
512-octet link message and is dropped and counted (not fragmented).
- **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 does not reassemble.
- **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.
### Link spec revision 2
`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.
### Dropped from the earlier MicrOBU version, and why
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, up to 494 octets) and `RAW_FRAME` (the spec's debug capture, on after `RAW_CAPTURE`, the whole radio frame, fragmented when large). The Android app has a switch for which one it consumes; the board always sends `V2X_RX`. See [NOTES.md](NOTES.md).
```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 -->|always, signed or not, up to 494 octets| 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. 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()

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