Compare commits
2
Commits
main
..
ca57e5702b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca57e5702b | ||
|
|
0e9525162d |
-39
@@ -54,42 +54,3 @@ sdkconfig.old
|
||||
# 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*
|
||||
|
||||
# Overnight bench test: LaTeX build output (the PDF is committed) and raw run folders (only the reports are committed)
|
||||
obu-firmware/docs/*.fdb_latexmk
|
||||
obu-firmware/docs/*.fls
|
||||
obu-firmware/test/results/*/
|
||||
|
||||
@@ -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
|
||||
@@ -2,90 +2,42 @@
|
||||
|
||||
Android companion app for the micrOBU; a compact V2X on-board unit developed by HAW Hamburg and consider it GmbH for vulnerable road users (cyclists, e-bike riders, pedestrians).
|
||||
|
||||
The app is the HMI for the OBU hardware and, on the ESP32-C5 path, also the ITS facilities layer: it builds and decodes the ITS messages, while the board does GeoNetworking, signing and the radio. It handles V2X message display, use case detection, traffic lights per lane, sensor collection, trip recording, and the link to the OBU over USB-C or Bluetooth LE.
|
||||
The app is the HMI for the OBU hardware and, on one of the two supported hardware paths, the entire V2X protocol stack. It handles V2X message display, use case detection, sensor collection, trip recording, and OBU communication over USB-C.
|
||||
|
||||
**Platform:** Android (Kotlin) / **Min SDK:** 29 (Android 10) / **Target SDK:** 36 / **Version:** 0.1.0 (`versionName`, Phase 03)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Phone[Android app]
|
||||
UI[Compose UI and use cases]
|
||||
Fac[ITS facilities: CAM, VAM, DENM, SPATEM and MAPEM codecs]
|
||||
Sens[GNSS, IMU, trip recording]
|
||||
Link[Esp32Link and StationLink]
|
||||
end
|
||||
Sens --> Fac
|
||||
Fac -->|BTP_DATA_REQUEST, POTI_UPDATE| Link
|
||||
Link -->|V2X_RX, CONFIRM with status| Fac
|
||||
Fac --> UI
|
||||
Link <-->|USB-C or encrypted BLE, station-link rev. 2| OBU[obu-firmware on the XIAO ESP32-C5]
|
||||
OBU <-->|BTP, GeoNetworking, signing| Air[ITS-G5 5.9 GHz]
|
||||
UI <-->|IP over USB tethering, MQTT| CiT[consider it CiT One]
|
||||
```
|
||||
|
||||
```yaml
|
||||
platform: Android
|
||||
language: Kotlin
|
||||
UI: Jetpack-Compose
|
||||
DI: Hilt
|
||||
min_sdk: 29
|
||||
target_sdk: 36
|
||||
hardware_paths:
|
||||
esp32_c5: # primary; the app is the ITS facilities layer
|
||||
firmware: obu-firmware/ # Niklas Dathe's microbu-firmware plus MicrOBU additions
|
||||
transport: [USB-C native Serial/JTAG, Bluetooth LE GATT]
|
||||
protocol: station-link revision 2 (obu-firmware/docs/station-link.pdf)
|
||||
app_builds: [CAM, VAM, decodes CAM, DENM, SPATEM, MAPEM, VAM]
|
||||
board_does: [BTP, GeoNetworking, signing, radio]
|
||||
cit_one: # consider it CiT One
|
||||
transport: IP over USB tethering, MQTT
|
||||
messages_received: V2X_RX (0x90), signed or not, up to 494 octets
|
||||
messages_sent: signed or unsigned per setting (Settings > Connection > ESP32-C5)
|
||||
credentials: throwaway demo chain in app/src/main/assets/demo-chain.vcr
|
||||
tests: 145 JVM unit tests, no emulator needed (domain/ has no Android imports)
|
||||
```
|
||||
**Platform:** Android (Kotlin) / **Min SDK:** 29 (Android 10) / **Target SDK:** 36 / **Version:** 0.5.0 (Phase 03)
|
||||
|
||||
## Project goal
|
||||
|
||||
Demonstrate V2X communication with at least one C2C-CC bicycle safety use case working on the ESP32-C5, specifically intersection movement assist: a car approaching an intersection on a path that conflicts with the rider's.
|
||||
|
||||
That use case is driven entirely from the periodic position and kinematics vehicles broadcast. It needs no traffic light state and no intersection lane geometry. The app now also shows traffic lights per lane from SPATEM and MAPEM, but no use case depends on them.
|
||||
That use case is driven entirely from the periodic position and kinematics vehicles broadcast. It needs no traffic light state and no intersection lane geometry, which is why several scope decisions in this repository look deliberately narrow.
|
||||
|
||||
## Two hardware paths
|
||||
|
||||
The project began against the consider it CiT One and later added the ESP32-C5 as a second option. Both paths are supported at runtime and selected by the rider in Settings > OBU Hardware.
|
||||
|
||||
| | consider it CiT One | ESP32-C5 (micrOBU, `obu-firmware/`) |
|
||||
| | consider it CiT One | ESP32-C5 |
|
||||
|---|---|---|
|
||||
| What it is | Complete V2X on-board unit | Seeed XIAO ESP32-C5 running Niklas Dathe's microbu-firmware ITS station |
|
||||
| Transport | IP over USB tethering, MQTT | Station-link protocol over native USB-C or Bluetooth LE |
|
||||
| Reaches the phone as | Processed JSON, plus raw protobuf-wrapped UPER | Raw ASN.1 UPER per message, with RSSI |
|
||||
| V2X stack lives | On the OBU | Facilities (CAM/VAM/DENM/SPATEM/MAPEM codecs) on the phone; BTP, GeoNetworking, security and radio on the board |
|
||||
| Own messages | CAM, generated by the OBU | CAM or VAM, generated by the phone and sent by the board |
|
||||
| Signing (ETSI TS 103 097) | By the OBU | By the board, with a demo PKI the app provisions; or unsigned |
|
||||
| What it is | Complete V2X on-board unit | Development board acting as a plain radio |
|
||||
| Transport | IP over USB tethering, MQTT | Framed binary protocol over USB CDC serial |
|
||||
| Reaches the phone as | Processed JSON | Raw ASN.1 UPER bytes |
|
||||
| V2X stack lives | On the OBU | On the phone, except the radio and GeoNetworking |
|
||||
| Own CAM generated by | The OBU, autonomously | The phone, transmitted on the phone's clock |
|
||||
| DENM trigger | Available (manual test tool) | Not available |
|
||||
| Needs a network | Yes, internally | No |
|
||||
|
||||
Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived into the domain types (`Cam`, `DenmEvent`, `SpatEvent`, `MapEvent`). Everything above that point, including the use case detection engine and all UI, is shared and transport-agnostic. That is what makes the ESP32-C5 a drop-in second OBU rather than a fork of the application.
|
||||
Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived into the domain `Cam` type. Everything above that point, including the entire use case detection engine and all UI, is shared and transport-agnostic. That is what makes the ESP32-C5 a drop-in second OBU rather than a fork of the application.
|
||||
|
||||
## What it does
|
||||
|
||||
**Real-time V2X monitoring**; live CAM, DENM, SPATEM and MAPEM with a station list, active hazards, live signal phase, and a map view. On the CiT One path the topic viewer additionally shows whatever the broker publishes, grouped by topic with pretty-printed JSON and TX/RX badges.
|
||||
|
||||
**Traffic lights per lane**; SPATEM says what each signal group shows, MAPEM where each lane runs and which signal group controls each way out of it. `TrafficLights.join` puts the two together and picks the rider's own ingress lane from position and heading. The dashboard card then names the intersection and shows the rider's lane, the distance to its stop line, and one light per signal group with its turn arrows (↑ ← →) and countdown. The V2X map puts the light on the intersection's reference point and draws the lanes in their signal colours. Without a MAPEM, signal groups are shown as bare numbers.
|
||||
**Real-time V2X monitoring**; live CAM, DENM and SPATEM with a station list, active hazards, live signal phase, and a map view. On the CiT One path the topic viewer additionally shows whatever the broker publishes, grouped by topic with pretty-printed JSON and TX/RX badges.
|
||||
|
||||
**CAM-based use case detection**; correlates the rider's own state with a short per-station history of received CAMs to evaluate five C2C-CC bicycle safety use cases (IMA-B, IMA-S, RTW-B, LTW-B, SMVA/BCW-B) and raises alerts under the three-tier Info / Awareness / Warning model. None of these use cases generates a DENM.
|
||||
|
||||
**Phone-generated CAM or VAM**; on the ESP32-C5 path the app builds a CAM (EN 302 637-2) or a VAM (TS 103 300-3, cyclist profile, its generation rules included) from live GNSS and IMU, UPER-encodes it, and hands it to the board with "signed" or "unsigned" (Settings > Connection > ESP32-C5). The board adds BTP and GeoNetworking, signs it with its authorization ticket, and transmits it over ITS-G5. The CAM and VAM station ID rotates as a pseudonym, and the link-layer address (802.11 source and GN address) rotates with it: the app sends the pseudonym's MAC in the 16-octet STATION_CONFIGURE and the board reconfigures on a change. The bench CAM pinger keeps one fixed identity and MAC. ITS time is TAI.
|
||||
**Phone-generated CAM**; on the ESP32-C5 path the app builds a CAM from live GNSS and IMU, UPER-encodes it, and pushes it down the serial link for the board to broadcast over ITS-G5.
|
||||
|
||||
**DENM transmission**; CiT One path only. Triggers the stationary vehicle profile (`hln-sv`, causeCode 94) via the consider it Use Case API. This is a manual antenna and range test tool. It is never triggered by a detected event or a use case alert, and the control is hidden entirely on the ESP32-C5 path.
|
||||
|
||||
**OBU status**; the ESP32-C5 card shows the link in use, signing (tickets, signed, refused, on air) and the board's battery voltage with a low/critical warning, which also appears in the top bar.
|
||||
|
||||
**V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside. With Settings > Ride > Record motion sensors on, a log also records accelerometer, gyroscope and gravity at 100 Hz, raw GPS fixes next to the fused location, and the phone's clocks, for sensor fusion; `tools/fusion_log_check.py` checks such a log. See `docs/07-sensor-fusion-logging.md`.
|
||||
|
||||
**Ride settings**; Settings > Ride. Where the phone rides (handlebar, bag or pocket), recorded in every V2X log for sensor fusion, and the motion sensor recording switch above.
|
||||
|
||||
**Trip recording**; foreground service records all sensor streams and detects cycling manoeuvres (braking, turning, stopping) using orientation-independent signal processing. Works fully offline with no OBU connected. The detected manoeuvres are neither shown nor stored - their only effect is to raise the CAM transmit rate through the manoeuvre on the ESP32-C5 path.
|
||||
|
||||
**Trip review**; past trips displayed as a route on an OpenStreetMap layer, with duration and distance.
|
||||
@@ -97,91 +49,37 @@ Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived
|
||||
MVVM with Repository pattern throughout. Jetpack Compose for all UI (no XML layouts). Hilt for dependency injection.
|
||||
|
||||
```
|
||||
app/src/main/java/com/hawhamburg/micr0bu/
|
||||
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor and map, Settings, V2X logger...)
|
||||
ui/navigation/ Navigation graph and bottom nav bar
|
||||
viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel, RideSettingsViewModel
|
||||
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope
|
||||
data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport
|
||||
data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager
|
||||
data/log/ V2xLogger, V2xLogWriter (the V2X data logger)
|
||||
data/db/ Room database (sessions, trips, V2X messages)
|
||||
data/ SensorRepository, GnssTimeSource, RidePreferences, TripRepository, CsvExporter, TripExporter
|
||||
domain/asn1/ BitReader/BitWriter, ItsTime, and the CAM, DENM, SPATEM, MAPEM and VAM UPER codecs
|
||||
domain/map/ MAPEM intersection geometry: lanes, nodes, connections, maneuvers
|
||||
domain/spat/ SPATEM signal state, and TrafficLights (SPATEM on MAPEM lanes, the rider's approach)
|
||||
domain/vam/ VAM generation rules (TS 103 300-3 clause 6.4)
|
||||
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
|
||||
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
|
||||
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig, Pseudonym
|
||||
domain/fusion/ Sensor fusion: YawRateEstimator (yaw rate about the vertical), PhoneMount
|
||||
service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService
|
||||
|
||||
obu-firmware/ ESP32-C5 OBU on Niklas Dathe's microbu-firmware (station, signing, BTP, GeoNetworking,
|
||||
station link over USB and BLE) plus our raw receive path (gn_unwrap.c, V2X_RX),
|
||||
unsigned TX and battery guard; host tests in test/
|
||||
obu-firmware/{components,external}/ microbu_v2x, Vanetza and its patched source (vendored, unchanged)
|
||||
obu-cam-transmistter/ Bench CAM beacon (the "simulated car"), fixed station ID, drives a loop in St. Georg
|
||||
asn1/ Vendored ETSI ASN.1 modules the codecs are verified against
|
||||
tools/ Bench scripts: STATUS watcher, bench-listener tally, MAPEM test-corpus generator
|
||||
docs/ Requirements traceability, signed ITS / VAM / BLE design, architecture diagrams
|
||||
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor, Settings...)
|
||||
ui/navigation/ Navigation graph and bottom nav bar
|
||||
viewmodel/ MqttViewModel, SensorViewModel, TripRecordingViewModel
|
||||
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection
|
||||
data/transport/ UsbSerialTransport, SerialFrame, UsbNetworkDetector, ObuHardware
|
||||
data/cam/ CamUseCaseRepository; where both hardware paths converge
|
||||
data/db/ Room database (sessions, trips, detected events, V2X messages)
|
||||
data/ SensorRepository, TripRepository, CsvExporter, TripExporter
|
||||
domain/asn1/ BitReader/BitWriter and the CAM, DENM and SPATEM UPER codecs
|
||||
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
|
||||
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
|
||||
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig
|
||||
service/ TripRecordingService, CamTransmitLoop, CamPinger
|
||||
obu-firmware/ ESP32-C5 firmware (serial link, GeoNetworking, 802.11 OCB, raw TX)
|
||||
asn1/ Vendored ETSI ASN.1 modules the codecs are verified against
|
||||
```
|
||||
|
||||
The `domain/` packages contain no Android imports. That is what makes the 145-test JVM suite possible without an emulator or instrumentation.
|
||||
The `domain/` packages contain no Android imports. That is what makes the 41-test JVM suite possible without an emulator or instrumentation.
|
||||
|
||||
## Connectivity
|
||||
|
||||
USB-C on both hardware paths. Bluetooth is **not implemented** and remains an open question in the requirements.
|
||||
|
||||
| Transport | Path | Status |
|
||||
|---|---|---|
|
||||
| USB-C tethering (IP + MQTT) | CiT One | Active |
|
||||
| USB-C, native USB Serial/JTAG (station link) | ESP32-C5 | Active |
|
||||
| Bluetooth LE GATT (station link) | ESP32-C5 | Active |
|
||||
| USB-C serial (framed binary) | ESP32-C5 | Active |
|
||||
| Wi-Fi | CiT One | Developer builds only |
|
||||
| Bluetooth | Either | Not implemented |
|
||||
|
||||
On the CiT One path the MQTT broker runs on the OBU (Mosquitto 2.0.11, port 1883); Android USB tethering exposes it as a virtual Ethernet interface at `192.168.42.x` and the app auto-detects the gateway IP on plug-in.
|
||||
|
||||
On the ESP32-C5 path there is no network layer. Both links carry the same **station-link protocol**, revision 2 ([obu-firmware/docs/station-link.tex](obu-firmware/docs/station-link.tex); revision 1 is Niklas Dathe's, revision 2 adds our extensions): `[opcode][flags][sequence LE][body]`, at most 512 octets per message (`LINK_MAX_MESSAGE` in the app, `link::maximum_message` in the firmware). The phone configures the station, provisions the demo credentials once, keeps the board's clock and position current (`POTI_UPDATE` per new GNSS fix) and submits messages (`BTP_DATA_REQUEST`); the board answers every request with `CONFIRM`, the phone asks for `STATUS_REQUEST` every second (the status snapshot is in the CONFIRM), and the board forwards every ITS message it hears as `V2X_RX` (0x90, a MicrOBU extension). Over USB each message is one `0xAA55` frame with CRC-16; over BLE it is one GATT value. Details: [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md).
|
||||
|
||||
### Bluetooth LE
|
||||
|
||||
Settings > Connection > ESP32-C5 > link: Bluetooth.
|
||||
|
||||
- **GATT layout**: service `0000C175-BA5E-4C17-8000-00805F9B34FB`, one characteristic per primitive. Each value is one whole link message, never fragmented, so the app raises the ATT MTU to 517 first (the firmware asks for 517 too); the firmware drops a notification rather than send it cut short.
|
||||
- **Pairing**: the board advertises as `micrOBU-XXXX`. LE Secure Connections with a fixed passkey, **123456**, entered once in Android's own pairing dialog. The bond is kept on both sides (the board stores it in its 80 KB NVS). The passkey is public, so this gives an encrypted link but no protection against an active attacker during that first pairing.
|
||||
- **Reconnect**: after a drop (4 s supervision timeout) the app reconnects by itself, 1 s later and then backing off to 30 s. With several bonded micrOBUs (a replaced board stays bonded), the one that connected last is tried first, then the others in turn.
|
||||
- **Several boards nearby**: with no bond the app connects to the first micrOBU it hears, which on a bench with several is not necessarily yours. Pair the right one in Android's Bluetooth settings first (name `micrOBU-` plus the last two octets of its BLE address); the app then prefers a bonded micrOBU. See [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md).
|
||||
- **BLE and ITS-G5 share the C5's single RF front end**: the firmware holds an ITS-G5 frame out of the BLE connection-event windows (`CONFIG_MICROBU_TX_BLE_GUARD`).
|
||||
- **Permissions**: `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT` (Android 12+), requested at start-up.
|
||||
|
||||
Whether an active BLE connection costs 5.9 GHz reception has not been measured yet.
|
||||
|
||||
### Received messages on the ESP32-C5 path
|
||||
|
||||
vanetza-idf verifies strictly and would drop anything unsigned or signed under another root, i.e. the bench car and every RSU. So every captured frame also goes through `gn_unwrap.c`, which strips 802.11, LLC/SNAP, GeoNetworking (single-hop and GeoBroadcast), an IEEE 1609.2 signed envelope if there is one, and BTP, and forwards the ITS payload for BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM. Signatures are not checked on this path; the message is flagged "signed, not verified". A payload over 494 bytes does not fit one link message and is dropped and counted.
|
||||
|
||||
**Two receive paths, switchable** (Settings > Connection > ESP32-C5 > Receive path). Both end in the same decoded messages, so nothing above the link changes:
|
||||
|
||||
| | V2X_RX (default) | Raw frames |
|
||||
|---|---|---|
|
||||
| Source | the MicrOBU extension, opcode 0x90 | the spec's `RAW_FRAME` (0x85), switched on with `RAW_CAPTURE` |
|
||||
| Who unpacks the frame | the board (`gn_unwrap.c`) | the app (`GnUnwrap.kt`, a port tested frame by frame against the C code) |
|
||||
| Size | up to 494 octets | not limited: fragments are reassembled (`LinkReassembly`, as the spec defines) |
|
||||
| Reliability | normal indication | debug copy: can be dropped when the link is busy, more bandwidth, especially over BLE |
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Air[ITS-G5 frame] --> Board[ESP32-C5: radio, gn_unwrap.c, raw capture tap]
|
||||
Board -->|V2X_RX 0x90, always| Link[USB or BLE]
|
||||
Board -->|RAW_FRAME 0x85, after RAW_CAPTURE| Link
|
||||
Link --> Re[LinkReassembly]
|
||||
Re --> Sel{Receive path setting}
|
||||
Sel -->|V2X_RX, default| Dec[V2xRxFrame]
|
||||
Sel -->|Raw frames| Raw[RawFrame + GnUnwrap]
|
||||
Raw --> Dec
|
||||
Dec --> Rest[Codecs, use cases, V2X screens, logger]
|
||||
```
|
||||
|
||||
The board always sends `V2X_RX`; the app consumes one path and ignores the other. Changing the setting takes effect at once on a configured station (`RAW_CAPTURE` mode 3 = on and broadcast frames only, mode 0 = off). `GnUnwrapTest` checks the Kotlin unwrapper against `obu-firmware/test/host/dump_corpus.c`'s output for 602 recorded, cut and corrupted frames.
|
||||
On the CiT One path the MQTT broker runs on the OBU (Mosquitto 2.0.11, port 1883); Android USB tethering exposes it as a virtual Ethernet interface at `192.168.42.x` and the app auto-detects the gateway IP on plug-in. On the ESP32-C5 path there is no network layer at all: a private framed protocol runs over the board's native USB-C port as a CDC-ACM device.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -189,14 +87,9 @@ The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path,
|
||||
|
||||
Verification therefore uses an independent oracle: `asn1tools` compiled from the ETSI modules vendored in `asn1/`.
|
||||
|
||||
- **Golden-byte fixtures** assert exact encoder output (CAM, VAM), with expected values produced by the oracle rather than by this encoder.
|
||||
- **Golden-byte fixtures** assert exact encoder output, with expected values produced by the oracle rather than by this encoder.
|
||||
- **Bulk replay** compares every field over real captures: 79,042 SPATEMs and 1,885 DENMs, zero mismatches.
|
||||
- **MAPEM**: every distinct MAPEM on record (17 from the 2026-03-18 drive, 288 to 1348 bytes, plus the bench RSU's) decodes field for field like asn1tools (`MapemUperCodecTest`; fixtures from `tools/mapem_corpus.py`). Joined with recorded SPATEMs of the same intersections, 340 of 341 signalled lane exits find their signal group (`TrafficLightsTest`).
|
||||
- **Station link**: the codec is pinned to bytes from Niklas Dathe's Python implementation (`StationLinkTest`).
|
||||
- **Signatures on air**: `obu-firmware/test/verify_signed_pcap.py` checks captured frames with asn1tools and OpenSSL, sharing no code with the firmware: 12 of 12 signed CAMs valid, demo chain valid (2026-09-23). The CiT One and the V2X2MAP bridge receive them too.
|
||||
- **Firmware receive path**: host tests (`obu-firmware/test/host`, `make`) run the TX-to-RX chain, every recorded frame cross-checked by asn1tools, and a guard-page fuzz of `gn_unwrap_its`.
|
||||
- **Off-air confirmation**: 26 of this project's own CAMs captured back by an independent receiver, all accepted.
|
||||
- **CI**: every push runs the merge gate in `microbu-tests` (`.gitlab-ci.yml`).
|
||||
|
||||
Never regenerate a golden fixture from this project's own encoder output. See `asn1/README.md`.
|
||||
|
||||
@@ -207,15 +100,9 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
|
||||
| [docs/MicrOBU-User-Guide.docx](docs/MicrOBU-User-Guide.docx) | Riders. Setup, screens, what the alerts mean, troubleshooting |
|
||||
| [docs/MicrOBU-Technical-Documentation.docx](docs/MicrOBU-Technical-Documentation.docx) | Supervisors and stakeholders. Architecture, message path, verification, results, decisions |
|
||||
| [docs/01-requirements-traceability.md](docs/01-requirements-traceability.md) | Requirements chapters 0 to 13 mapped to implementation and evidence |
|
||||
| [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md) | Signed ITS messages, VAM and the BLE link: who does what, link protocol, recovery, verification |
|
||||
| [docs/07-sensor-fusion-logging.md](docs/07-sensor-fusion-logging.md) | Sensor fusion phases 0 and 1: yaw rate and GNSS time inputs, Ride settings, the fusion log schema, `tools/fusion_log_check.py`, test rides |
|
||||
| [docs/Architecture-signed-its.drawio.png](docs/Architecture-signed-its.drawio.png) | Block diagram of the signed-ITS architecture |
|
||||
| [05-obu-bench-test-2026-08-25.md](05-obu-bench-test-2026-08-25.md) | Bench campaign T1 to T9, measured results |
|
||||
| [04-transmit-setup.md](04-transmit-setup.md) | Transmitter bring-up, radio configuration diagnosis, the TX bypass |
|
||||
| [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md) | Toolchain setup (ESP-IDF 6.0.2), flashing, battery and pins, phone-to-board bring-up |
|
||||
| [obu-firmware/NOTES.md](obu-firmware/NOTES.md) | What the firmware changes against Niklas Dathe's station, and why |
|
||||
| [obu-firmware/test/host/README.md](obu-firmware/test/host/README.md) | Host tests of the firmware's frame code |
|
||||
| [TODO.md](TODO.md) | Open engineering items, including the hardware checks still to run |
|
||||
| [obu-firmware/FLASHING.md](obu-firmware/FLASHING.md) | Toolchain setup, flashing, phone-to-board bring-up checklist |
|
||||
| [asn1/README.md](asn1/README.md) | ASN.1 module provenance and the fixture regeneration rule |
|
||||
| [docs/references.bib](docs/references.bib) | Standards references as BibTeX |
|
||||
|
||||
@@ -225,14 +112,12 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
|
||||
|---|---|
|
||||
| Jetpack Compose + Material3 | UI |
|
||||
| Eclipse Paho MQTT | CiT One path communication |
|
||||
| usb-serial-for-android | ESP32-C5 USB link (custom probe table for Espressif VID/PID) |
|
||||
| Android BLE (`BluetoothGatt`) | ESP32-C5 Bluetooth link |
|
||||
| usb-serial-for-android | ESP32-C5 path communication (custom probe table for Espressif VID/PID) |
|
||||
| Room | Local database |
|
||||
| Hilt | Dependency injection |
|
||||
| OSMDroid | Trip review and live V2X map |
|
||||
| DataStore | Settings persistence |
|
||||
| FusedLocationProviderClient | GNSS |
|
||||
| vanetza-idf (firmware) | BTP, GeoNetworking and TS 103 097 security on the ESP32-C5 |
|
||||
|
||||
## Getting started
|
||||
|
||||
@@ -242,42 +127,31 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
|
||||
|
||||
**CiT One path.** Plug the phone into the OBU via USB-C, enable USB tethering on the phone, and the app detects the interface and connects automatically. Broker IP can be overridden in Settings > Connection.
|
||||
|
||||
**ESP32-C5 path.**
|
||||
|
||||
1. Flash `obu-firmware/` with ESP-IDF 6.0.2 (`obu-firmware/FLASHING.md`; use the full flash the first time, the partition layout differs from older images). The XIAO ESP32-C5 has a single USB-C port, used for both flashing and the phone.
|
||||
2. In Settings > Connection > ESP32-C5 choose the link (USB-C or Bluetooth), what to transmit while recording (CAM or VAM) and whether to sign it.
|
||||
3. Tap Connect. USB: grant the USB permission. Bluetooth: pair with `micrOBU-XXXX`, passkey 123456, once. On the first connection the app provisions the demo credentials; the card then shows "Signing on · tickets 1".
|
||||
4. Use the CAM Pinger on the V2X screen to check the link and radio without starting a trip.
|
||||
**ESP32-C5 path.** Flash `obu-firmware/` (see `obu-firmware/FLASHING.md`), then plug the phone into the board's **native** USB-C port, not the UART bridge port used for flashing. Tap Connect and grant the USB permission. Use the CAM Pinger on the V2X screen to verify the link and radio without starting a trip.
|
||||
|
||||
**Standalone trip recording.** No OBU required. Go to the Record tab and tap REC.
|
||||
|
||||
The Wi-Fi transport (broker at `192.168.3.202`) remains available in developer builds via Settings > Developer.
|
||||
|
||||
Keep app and firmware in step (the app from 2026-11-10 needs the firmware from 2026-11-10: `CONFIRM` and `STATUS_REQUEST`, `V2X_RX` is 0x90, the configure message has 6 octets): both cap a link message at 512 octets, and the app speaks station-link revision 2 (it still falls back to the previous firmware's frames for CAM over USB).
|
||||
|
||||
## Credits
|
||||
|
||||
The ESP32-C5 station firmware (BTP, GeoNetworking, TS 103 097 security, the station-link protocol, BLE and the radio driver) and its interface specification are by **Niklas Dathe** (HAW Hamburg, microbu-firmware). `obu-firmware/` is his firmware with the MicrOBU additions listed in [obu-firmware/NOTES.md](obu-firmware/NOTES.md).
|
||||
Firmware and app must be flashed and installed together: `SERIAL_LINK_MAX_PAYLOAD` is 512 on both sides and a mismatch silently rejects every large frame.
|
||||
|
||||
## Status and known limitations
|
||||
|
||||
Bench verified against live ITS-G5 traffic on 2026-08-25: 2868 frames over 305 seconds, zero decode failures, zero USB errors, zero crashes. Signed CAM and VAM, the BLE link and reception over both links were checked on the bench on 2026-09-23; on 2026-10-28 the ESP32-C5 forwarded the bench RSU's MAPEM (295 bytes), SPATEM and CAM with nothing dropped. On 2026-11-11 the production XIAO and a Pixel 9 Pro were run together: the simulated car's CAMs reach the app, signed and unsigned CAMs from the phone are heard by a second board, the BLE bond survives a board reset, and BLE adds no measurable transmit loss over USB (95.7 % of signed CAMs heard in both; about 4 % is lost on the air or at the listener). On 2026-11-10 the firmware was rebuilt on Niklas Dathe's newer microbu-firmware layout and the app's link followed (link spec revision 2); that firmware boots, advertises and answers STATUS on the XIAO, while reception, transmission, signing and the battery guard on real hardware are still to be re-checked (`TODO.md`). Not yet road validated.
|
||||
Bench verified against live ITS-G5 traffic on 2026-08-25: 2868 frames over 305 seconds, zero decode failures, zero USB errors, zero crashes. Not yet road validated.
|
||||
|
||||
- **Requirement 11.6, Phase A success criteria, is not met.** The bench proves reception. It cannot prove the use case behaves correctly with two genuinely moving stations, because nothing on the bench moves. This is the main open evidence gap for the project's central claim.
|
||||
- **Demo PKI only.** Signed messages carry a throwaway chain shipped with the app, not an EU-registered one; receivers that verify against the EU trust list drop them. No TS 102 941 enrolment. The board's stack verifies signatures (counted in STATUS), but the `V2X_RX` path the app uses delivers everything without a verdict, only whether a signature is present.
|
||||
- **No message signing.** ETSI TS 103 097 is out of scope. Secured frames are rejected rather than mis-parsed.
|
||||
- **Detection thresholds are untuned engineering estimates**, not calibrated against real intersection data.
|
||||
- **494-byte receive limit on the ESP32-C5 path.** A larger message does not fit one link message and is dropped: about 70% of real road SPATEMs (median 555 bytes) and many road MAPEMs. The CiT One path is not limited.
|
||||
- **Traffic lights per lane not yet seen live.** Tested on recorded messages only. Riders on crosswalks or sidewalks are not matched to a lane, and computed lanes (`ComputedLane`) are not decoded.
|
||||
- **BLE and ITS-G5 share one RF front end**; the effect of an active BLE connection on reception is unmeasured.
|
||||
- **No automatic reconnect after USB re-enumeration**; requires a manual Connect. BLE reconnects by itself.
|
||||
- **The prototype cell has no protection board.** The firmware's low-voltage shutdown (below 3.30 V with no phone on USB) is the only guard.
|
||||
- **512-byte serial payload cap.** Roughly 70% of real road RSU SPATEMs would be dropped as oversize. Accepted deliberately: the intersection use case is CAM-driven and needs none of it.
|
||||
- **No automatic reconnect** after USB re-enumeration; requires a manual Connect.
|
||||
- **Station IDs rotate**, so they cannot identify a physical unit over time.
|
||||
- **No backend, no login.** Everything is on-device.
|
||||
- **No MAPEM decoder**, so signal groups cannot yet be associated with the rider's lane.
|
||||
|
||||
## Project context
|
||||
|
||||
The micrOBU project is funded under the ZIM program (BMWK) and targets micromobility users in Hamburg. The companion app offloads processing from the compact OBU hardware to the smartphone; GNSS fusion, event detection, and on the ESP32-C5 path the full ASN.1 encoding and decoding all run on the phone to keep the OBU lightweight and power-efficient. The ESP32-C5 keeps what must stay on the radio side: GeoNetworking, the signing key and the radio itself.
|
||||
The micrOBU project is funded under the ZIM program (BMWK) and targets micromobility users in Hamburg. The companion app offloads processing from the compact OBU hardware to the smartphone; GNSS fusion, event detection, and on the ESP32-C5 path the full ASN.1 encoding and decoding all run on the phone to keep the OBU lightweight and power-efficient.
|
||||
|
||||
V2X communication uses ITS-G5 (IEEE 802.11p) at 5.9 GHz. On the CiT One path the app communicates via the consider it MQTT API v6 (processed JSON and raw protobuf). On the ESP32-C5 path the app performs its own ASN.1 UPER encoding and decoding against the ETSI modules vendored in `asn1/`.
|
||||
V2X communication uses ITS-G5 (IEEE 802.11p) at 5.9 GHz. On the CiT One path the app communicates via the consider it MQTT API v6 (processed JSON). On the ESP32-C5 path the app performs its own ASN.1 UPER encoding and decoding against the ETSI modules vendored in `asn1/`.
|
||||
|
||||
**Owner:** HAW Hamburg
|
||||
|
||||
@@ -5,312 +5,9 @@ Engineering to-do list. The reviewer-facing open items live in
|
||||
|
||||
## Waiting on hardware
|
||||
|
||||
### Stored HafenCity MAPEMs (added 2026-11-30)
|
||||
|
||||
The app ships 15 intersections (16 revisions) from the 2026-03-18 drive plus the bench RSU
|
||||
(Berliner Tor / Kolbergstrasse, -1/23 rev 2) in `assets/mapem/hamburg.txt`, and matches a SPATEM to
|
||||
them on region, intersection id, revision and, when known, position within 2 km. Add to the list with
|
||||
`py -3.11 tools/mapem_bundle.py <V2X log .db or hex .txt>`, then run the tests and rebuild.
|
||||
|
||||
- [ ] Bench RSU sending its SPATEM **without** the MAPEM: the lanes appear on the V2X map; logcat says
|
||||
`storedMaps: 17 intersection revisions loaded`.
|
||||
- [ ] Ride through HafenCity: note intersections whose SPATEM shows no lanes (revision changed since
|
||||
March, or not in the bundle) and check on the ones that do that the shown light matches the real one.
|
||||
- [ ] Not built yet: saving newly heard or changed MAPEMs on the phone, so the list updates itself.
|
||||
|
||||
### Large SPATEM / MAPEM through V2X_RX in fragments (added 2026-11-23)
|
||||
|
||||
The 2026-11-23 bench run (CiT node sending a 377 B MAPEM and 58 B SPATEM, then 1198 B and 888 B ones; phone on
|
||||
BLE) lost every large message: 0 of 1537 MAPEMs and 0 of 3004 SPATEMs against 98.5 % / 96.5 % of the small ones,
|
||||
because `Station::forward_raw` dropped everything over 494 bytes. Firmware now sends those in link fragments
|
||||
(`link_fragment.hpp`, `v2x_rx_plan`; NOTES.md). Done on the PC, not flashed yet: `make check` in
|
||||
`obu-firmware/test/host` (46 unit tests, the pcap replay of 3384 + 1727 large messages through unwrap -> fragments ->
|
||||
two reassemblers, fuzz), the app's `LinkReassemblyTest` on the firmware's own fragments, asn1tools on the large
|
||||
payloads, ESP-IDF 6.0.2 image build.
|
||||
- [x] Flashed to COM10 and run against the Berliner Tor RSU (2026-11-23 17:08-17:20, phone on BLE): MAPEM 1198 B 92.9 %,
|
||||
SPATEM 888 B 81.7 % of what the node heard, `radio_dropped` 0. The V2X screens stayed empty because the app's
|
||||
`SpatemUperCodec` refused the RSU's SPATEMs (intersection and movement names, advisory speeds); fixed and checked
|
||||
against asn1tools on all 718 distinct messages, **needs the app reinstalled on the phone**.
|
||||
- [ ] (original plan) Flash COM6 (`--no-stub` recipe, read the app descriptor first) and repeat the bench run: the node alternating
|
||||
small and large MAPEM/SPATEM, the phone on BLE, a pcap recorded at the same time. Compare with
|
||||
`py -3.11 tools/rx_size_compare.py LOG.db capture.pcap replay.tsv` (the header says how to make replay.tsv).
|
||||
Accept: small messages stay at ~96-98 % of what the node saw, the large ones arrive at a comparable rate,
|
||||
CAMs unchanged (92-96 % on 2026-11-23).
|
||||
- [ ] `radio_dropped` (link_status) stays 0 with the large messages, as it did on 2026-11-23 without them, and no BLE
|
||||
disconnects. If it moves, the fragments hold the station task too long: look at the fragment cap and BLE notify
|
||||
failures (the board's LOG line "V2X_RX: ... fragmented (... not taken by any transport)", 1 per 10 s).
|
||||
- [ ] The same over USB, and once with the app set to Raw frames: RAW_FRAME must still deliver the large ones, V2X_RX must
|
||||
not send them a second time (`raw_covered_`), and switching back to V2X_RX must work without a reconnect.
|
||||
- [ ] TX unchanged: a phone-originated CAM (signed and unsigned) is still seen by the node in the same session.
|
||||
|
||||
### App refresh: map dashboard, V2X switch, routing (added 2026-11-19)
|
||||
|
||||
Map-first dashboard (MapLibre, glass panels, folding bottom bar), "V2X ON/OFF" switch in the MicrOBU
|
||||
box, V2X sending decoupled from trip recording, "Where to?" search and bicycle routing. Built, 185
|
||||
unit tests green, and driven on the emulator with a mocked GPS fix (map, search, route preview and
|
||||
guidance all work). Not checked without the ESP32-C5 or a phone on a bike:
|
||||
|
||||
- [ ] Connect the ESP32-C5 with no trip recording: V2X turns on by itself and the second ESP32 (or
|
||||
`tools/cit_one_rx_watch.py`) hears the phone's CAMs. Switch it off on the Connection screen (tap the
|
||||
MicrOBU box on the dashboard): they stop, and the dashboard box reads "V2X OFF".
|
||||
Unplug and reconnect: it is on again, even if it was switched off before.
|
||||
- [ ] Screen off for 5 minutes with V2X on: CAMs keep coming at 1 Hz (`V2xTransmitService` holds the
|
||||
process and GNSS; the "V2X on" notification is showing).
|
||||
- [ ] Connect while the app is in the background on Android 14+: the loop still sends if the foreground
|
||||
service is refused (the start is allowed to fail), but the notification will be missing.
|
||||
- [ ] CiT One selected: the V2X switch is disabled and mirrors the link, and nothing is sent by the phone.
|
||||
- [ ] MicrOBU box shows the real battery percentage over BLE and USB, amber and red at the warn and
|
||||
shutdown voltages.
|
||||
- [ ] On a ride: heading-up mode tilts and turns the map with the course; guidance announces the turn
|
||||
before the corner; going off route reroutes within about 15 s.
|
||||
- [ ] GLOSA hint (speed box) at a real signalised junction with MAPEM and SPATEM on the air: the
|
||||
advice matches the lights. The rules are unit-tested only; never tried against a live signal.
|
||||
- [ ] Motion gate (`MotionDetector`): standing still indoors with GPS wandering, the speed box reads 0;
|
||||
then ride: it never reads 0 while moving, in each mount (handlebar, bag, pocket). Thresholds
|
||||
(`ENTER_STD` 0.15, `EXIT_STD` 0.07 m/s², 8 s hold) are from synthetic data only; a smooth-road
|
||||
ride on a handlebar mount is the case most likely to need tuning. Not applied to the CAM speed
|
||||
the phone transmits yet, which is still the raw GNSS speed.
|
||||
- [ ] Settings > Developer > CAM pinger (moved from the V2X screen): starts and stops, shows the
|
||||
loopback count, only appears with the ESP32-C5 selected.
|
||||
- [ ] Decide the satellite and terrain tile provider (the layer buttons are in the map settings,
|
||||
disabled until `MapLayer.styleUrl` has a source), and where routing and search run for real:
|
||||
the app now sends the rider's position to photon.komoot.io and valhalla1.openstreetmap.de, which
|
||||
are shared demo instances.
|
||||
|
||||
### Why the simulated car drops out of the V2X screen while the phone transmits (added 2026-11-19)
|
||||
|
||||
The bench beacon (`obu-cam-transmistter`, station 0x0BADC0DE) vanishes from the V2X screen for a
|
||||
moment and comes back while the phone is sending. The V2X screen forgets a station after 3 s without
|
||||
a CAM (`staleRemoteMs`), so these are gaps of 3 s or more. Hypothesis: the ESP32-C5 shares its radio
|
||||
between BLE and ITS-G5 and a transmission and a reception collide with a BLE event.
|
||||
|
||||
Not confirmed. Read from the firmware source only, not measured: the TX hold for BLE
|
||||
(`Station::hold_for_ble_guard`) is a busy-wait of at most 3.5 ms, too short to overflow the 16-frame
|
||||
receive queue, so a queue overflow from transmitting is unlikely; the firmware's own notes say a frame
|
||||
handed to the radio during a BLE connection event is accepted and never transmitted, and nothing says
|
||||
reception is spared; frames the radio never delivers (or the PHY flags bad) are in no counter.
|
||||
|
||||
Tooling is in: the V2X data logger (schema 3) now records `link_status` once a second, and
|
||||
`tools/rx_gap_analysis.py` accounts for every gap in the beacon's frames (lost before the radio saw
|
||||
them, dropped in the firmware queue, or lost between board and phone) per condition, and checks
|
||||
whether the gaps recur at a steady interval (two clocks beating). Self-tested on synthetic data only.
|
||||
|
||||
- [ ] Install the current build on the Pixel. Beacon on, 1-2 m from the OBU, nothing else on 5.9 GHz.
|
||||
- [ ] Settings > Developer > V2X data logger > Start logging, then four stretches of at least 3
|
||||
minutes each in one log, switching between them without stopping the log:
|
||||
BLE with V2X off (Connection screen), BLE with V2X on, then the same two over USB
|
||||
(cable from the phone to the OBU, Settings > Connection > ESP32 link = USB).
|
||||
- [ ] Stop, pull the `.db` (`adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/<file>`)
|
||||
and run `python tools/rx_gap_analysis.py <file>.db`. The table says which condition loses frames,
|
||||
and where; if the beacon's frames vanish before the radio and only on BLE with V2X on, BLE
|
||||
coexistence with transmitting is the cause, and the recurrence line says whether it is a beat.
|
||||
- [ ] If it is coexistence: the lever is in the firmware (the colleague's BLE guard calibrates only
|
||||
TX), not the app; options are fewer or longer-interval BLE events while transmitting, or USB.
|
||||
|
||||
### Sensor fusion phase 1: logging and test rides (added 2026-11-18)
|
||||
|
||||
Settings > Ride (phone position, Record motion sensors) and the fusion data in the V2X data logger,
|
||||
described in `docs/07-sensor-fusion-logging.md`. Unit-tested and built; `tools/fusion_log_check.py`
|
||||
tested on synthetic logs only. On the Pixel 9 Pro:
|
||||
|
||||
- [ ] Settings > Ride: Units is gone, Ride is there; the position and the switch survive an app restart.
|
||||
- [ ] One-minute bench log with Record motion sensors on: the logger screen shows the mount, the motion
|
||||
sensor count climbing by about 300 a second, and a raw GPS fix age; the file is named
|
||||
`..._imu-<mount>.db`; `fusion_log_check.py` on it gives no FAIL (accel, gyro, gravity at about
|
||||
100 Hz, `phone` and `phone_gps` fixes with `elapsed_ns`, `clock` rows with GNSS time).
|
||||
- [ ] Screen off for 5 minutes during a log: no motion sensor gap over 1 s in the check (the log
|
||||
service holds the CPU awake; confirm the sensors keep coming too).
|
||||
- [ ] Record motion sensors off: the log has empty `imu` and `clock` tables, no `phone_gps` rows,
|
||||
and no `_imu-` in its name, but still `meta.phone_mount`.
|
||||
- [ ] Rides, 20-30 minutes each, mount set before Start, each with left and right turns, a
|
||||
roundabout, stops of 10 s or more and if possible a bridge or underpass. Run the check on each
|
||||
and keep the files for phase 2:
|
||||
- [ ] handlebar
|
||||
- [ ] bag (on the bike)
|
||||
- [ ] pocket or backpack
|
||||
|
||||
### Sensor fusion phase 0: yaw rate about the vertical, fix times on GNSS time (added 2026-11-18)
|
||||
|
||||
The phone's own CAM/VAM now take the yaw rate from the gyroscope projected onto gravity
|
||||
(`domain/fusion/YawRateEstimator`, 100 ms average, gyro and gravity at `SENSOR_DELAY_GAME`) instead of
|
||||
the raw z axis. They stamp the GNSS time of the fix itself, through its monotonic
|
||||
`elapsedRealtimeNanos` (`GnssTimeSource.atElapsedRealtime`). The loop's own intervals (elevated rate, VAM
|
||||
rules) run on `SystemClock.elapsedRealtime`. Unit-tested (`YawRateEstimatorTest`), not yet on the phone.
|
||||
With the CAM pinger on and a listener that decodes yawRate:
|
||||
|
||||
- [ ] Turn the Pixel 9 Pro on an office chair at about 90°/s: flat, tilted about 50° as on the
|
||||
handlebar, and upright. All three should read about the same yaw rate. The old z-axis value
|
||||
fell to about 64 % tilted and to about 0 upright.
|
||||
- [ ] Phone still on the desk: yaw rate stays inside the 1 °/s noise floor, so it goes out as 0.
|
||||
- [ ] Set the phone's clock 10 minutes wrong by hand (automatic time off) with a GNSS fix: the CAM
|
||||
generationDeltaTime and GN TST still match GNSS time. Then step the clock back mid-run: CAMs and
|
||||
VAMs keep going at their rate, with no gap and no time_regression on the micrOBU.
|
||||
- [ ] Ride with the phone on the handlebar, then in a bag: the yaw rate's sign and size match the
|
||||
turns (left and right, roundabout).
|
||||
- [ ] Yaw rate sign on air (fixed 2026-11-18: `CamUperCodec` and `CamParser` now flip the ETSI/CiT
|
||||
left-positive value into the app's clockwise-positive one). Turn the pinging phone left: a
|
||||
standard decoder (asn1tools, or the CiT One's `v2x-uca/output/json/cam`) shows a positive
|
||||
YawRateValue, and the app's own decode of the same CAM reads a negative yaw rate (left, in the
|
||||
app's clockwise-positive convention).
|
||||
The logs in `databases/` (not committed) already settled the CiT One side: its CAM topic is
|
||||
left-positive (316 of 316 turning samples), its `obu_gnss` `yawRate_degps` right-positive
|
||||
despite the API document (27 of 27, bacospat ride of 2026-03-18). Only 27 samples from one
|
||||
ride: re-check on the next CiT One ride with turns.
|
||||
- [ ] CiT One JSON parsers (fixed 2026-11-18): `ObuGnssParser` returned null for every real `obu_gnss`
|
||||
message (position is under `gnss`, it read `own_info`), and `CamParser` for every real CAM-topic
|
||||
message (`stationType` is a name). So on the CiT One the ego state never came from `obu_gnss`,
|
||||
the app's V2X logger wrote no OBU fixes, and the processed CAM fallback was dead. On the next
|
||||
CiT One session: the use-case engine runs on `obu_gnss` (the phone GNSS fallback only kicks in
|
||||
after 2.5 s without it), the own station ID is learned so own CAMs stop showing as remote, and
|
||||
the V2X log has `obu` rows in its `gnss` table.
|
||||
|
||||
### obu-firmware on Niklas Dathe's microbu-firmware (added 2026-11-10, bench run 2026-11-11)
|
||||
|
||||
Flashed on the production XIAO (COM10) and the phone (Pixel 9 Pro, BLE) on 2026-11-11. Done, by hand
|
||||
on the bench with the COM3 board as a listener:
|
||||
|
||||
- [x] Beacon on air: V2X_RX of the simulated car (port 2001, unsigned, -39 to -52 dBm) reaches the app,
|
||||
which shows station 195936478 with speed, heading and distance.
|
||||
- [x] Signed CAM from the phone (CAM pinger, signing on): "tickets 1, signed 113, refused 0, on air 113"
|
||||
on the Connection card; the COM3 listener hears them as signed port 2001 CAMs, 17 in 20 s of a 1 Hz
|
||||
pinger (the signature itself was not verified; `test/verify_signed_pcap.py` on a capture would).
|
||||
- [x] Unsigned CAM from the phone (signing off): the listener hears 82 unsigned in 20 s, simulated car
|
||||
(about 60) plus the phone (about 20), none signed.
|
||||
- [x] BLE: the phone connected and ran the whole test; the demo credentials were provisioned (tickets 1).
|
||||
- [x] Battery: the app shows 4.16 V, about 95 % on the charging cell (the reading was 0 mV until the
|
||||
divider settle-time fix, c78b663).
|
||||
|
||||
Still open:
|
||||
|
||||
- [x] Receive path switch (2026-11-11, over BLE): `Raw frames` gave `RAW_CAPTURE mode 3 -> accepted` and the simulated car kept
|
||||
arriving through the app's own unwrapper; back to `V2X_RX` gave mode 0 and it kept arriving.
|
||||
- [x] V2X data logger on both receive paths (2026-11-11, 33 s each, the simulated car): `V2X_RX` 103 CAMs, `Raw frames` 106 CAMs; the logger
|
||||
listens to the same decoded frames for both, so it needs no change. It stores the decoded message, not the radio frame.
|
||||
- [ ] Fragmentation on air: a RAW_FRAME above one link message (a large MAPEM or SPATEM from a road RSU) reassembled in the
|
||||
app over BLE and over USB; only unit-tested so far.
|
||||
- [ ] Count both paths on the same traffic to see how many frames the raw copy drops on a busy link.
|
||||
- [x] Bond persistence (2026-11-11): the board was reflashed (MTU 517) with its NVS kept; the phone reconnected to
|
||||
micrOBU-66AA without a pairing prompt.
|
||||
- [ ] Verify a captured signature with `test/verify_signed_pcap.py` (needs the sniffer firmware).
|
||||
- [ ] 17 of 20 signed CAMs heard against 20 sent: measure the loss over a few minutes, with and without
|
||||
the BLE link busy (TX BLE guard).
|
||||
- [ ] Battery: no multimeter reference (the board is glued in); compare the plateau at full charge with
|
||||
the charger's 4.20 V, and run the shutdown rule on a flat cell.
|
||||
- [ ] The Connection settings text still says "the board only advertises while nothing uses its USB-C port"
|
||||
(the firmware no longer pauses advertising) and the card header says "ESP32-C5 (USB Serial)" while
|
||||
connected over Bluetooth.
|
||||
- [x] Pseudonym rotation (2026-11-11): the app sends the pseudonym MAC in the 16-octet STATION_CONFIGURE
|
||||
again; checked with `tools/station_tx_test.py` over USB and the station's own raw capture: a named MAC
|
||||
is the 802.11 source of signed and of unsigned frames; without one a signed frame carries the
|
||||
ticket-derived address and an unsigned one a random MAC. Still to see on a ride: the MAC changes at the
|
||||
rotation interval.
|
||||
- [x] TX loss, measured 2026-11-11 with the COM3 listener: USB with BLE off 287 of 300 signed CAMs heard (95.7 %,
|
||||
the board reports 300 submitted and 300 completed); BLE from the phone's pinger with the screen on 180 of
|
||||
the 188 the board put on air (95.7 %). So the BLE link adds no measurable loss, and the ~4 % is on the air
|
||||
or in the listener. One earlier BLE run, during which the phone screen turned off, heard 261 of about
|
||||
305 (86 %): to check whether Android's changed connection interval (the board logged 48.75 ms once; the TX
|
||||
guard is calibrated for 20 ms only) is the cause, log the board's `BLE interval ... no calibrated TX guard`
|
||||
warning over a longer run with the screen off.
|
||||
- [ ] BLE with several boards: with no bond the app connects to the first micrOBU it hears. On the bench four
|
||||
advertise at -49 to -55 dBm (4AFA, 3FAA, A25E, 66AA) and it paired with the wrong one (4AFA). Pair the
|
||||
right board in Android's Bluetooth settings first, or add a choice to the app.
|
||||
- [ ] A phone whose bond is gone (it showed none after a Bluetooth toggle) gets a connect-then-drop loop from a
|
||||
board that still holds the bond: erase the board's NVS (`esptool erase-region 0x9000 0x15000`) and pair again.
|
||||
|
||||
### MAPEM decoder and traffic lights per lane (added 2026-10-28)
|
||||
|
||||
`MapemUperCodec` decodes every recorded MAPEM (17 from the 2026-03-18 drive + the bench RSU's)
|
||||
field-for-field like asn1tools (`MapemUperCodecTest`, fixture from `tools/mapem_corpus.py`).
|
||||
`TrafficLights.join` puts SPATEM signal groups on MAPEM lanes: on the recorded pairs, 340 of 341
|
||||
signalled exits find their SPATEM movement (3/165's group 65 is never in its SPATEMs), and the
|
||||
geometric turn fallback agrees with 198 of 201 stated maneuvers (`TrafficLightsTest`). 132 unit
|
||||
tests pass. Installed on the Pixel 2026-10-28 16:38 (from Android Studio); not yet seen live, the
|
||||
RSU was switched off.
|
||||
|
||||
Needs the Pixel (new APK), the XIAO on COM10 and the bench RSU sending CAM + SPATEM + MAPEM:
|
||||
|
||||
- [ ] Dashboard: the signal card says "MicrOBU test crossroads" instead of "Traffic light -1/23".
|
||||
- [ ] Walk or ride toward the bench crossroads along an ingress lane (the RSU's refPoint is
|
||||
53.554698, 10.022548; lanes run 12-72 m out N/E/S/W): the card shows "North in · N m to the
|
||||
stop line" (or the lane you are on) and chips with arrows (↑←→) in the group's colour.
|
||||
- [ ] V2X map: the light stands on the reference point (no RSU CAM needed), 4 ingress lanes in
|
||||
their signal colour, the rider's lane thicker, 4 egress lanes grey.
|
||||
- [ ] logcat `handleMapUper[serial]: decoded station=... -1/23 rev 1 (8 lanes)` about 1 Hz, and no
|
||||
"unexpected BTP port 2003" lines.
|
||||
- [ ] V2X data logger: `MAPEM` rows with `source='esp32'`, `lat/lon` = the reference point and a
|
||||
summary naming the intersection.
|
||||
|
||||
### XIAO ESP32-C5 battery: voltage, low-battery warning, shutdown (added 2026-10-05)
|
||||
|
||||
The production board is now a Seeed XIAO ESP32-C5 on COM10 (8 MB flash), on a LiPo with no protection
|
||||
board. Firmware reads the cell (GPIO6 behind the GPIO26 load switch) every 5 s, puts it in STATUS
|
||||
(octets 103-105), warns below 3.50 V and deep-sleeps below 3.30 V when no phone is on USB; the app shows
|
||||
voltage, percentage and the warning. Details: `obu-firmware/FLASHING.md`, "Battery and pins".
|
||||
Host tests (`make battery`, 6 groups) and the app's 116 unit tests pass; the production image was
|
||||
flashed to COM10 on 2026-10-05 and `tools/station_status_watch.py COM10` showed 106-octet STATUS with
|
||||
3998 mV, stable over 18 s. Backup of what COM10 held before: `firmware-backups/COM10-xiao-before-obu-firmware-2026-10-05.bin`.
|
||||
|
||||
Needs the XIAO, the cell and a multimeter (shutdown test: also the phone, or just the PC script):
|
||||
|
||||
- [ ] **Is the reading right?** (3998 mV before the cell was soldered, 4078 then 4104 mV after, rising as USB charges it.) Measure the cell at the BAT pads with the multimeter while the board runs and
|
||||
compare with `py -3.11 tools/station_status_watch.py COM10`. Off by more than ~2 %: set
|
||||
`CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` = 1000 x multimeter / reading (the divider is 2 x 100 k into
|
||||
the ADC, so a high source impedance can read low). Unplug USB first to see the cell alone: with USB
|
||||
the charger holds the pin above the cell voltage.
|
||||
- [x] **Low-voltage shutdown and wake (done 2026-10-05 on COM10, cell soldered):** with the bench image the flags were 0x03 at once, the board stayed up for 85 s while the script talked, then slept 87 s after the script stopped (its port close resets the board, so that is 60 s grace + 30 s) and woke every 30 s, measured 4078 mV < 4100 and went straight back to sleep. A RESET press recovers it. Production image reflashed afterwards (c13c389-dirty, IDF v6.0.2, 4104 mV, flags 0). Original steps. Build with
|
||||
`CONFIG_MICROBU_BATTERY_WARN_MV=4150`, `SHUTDOWN_MV=4100`, `RESUME_MV=4100`, `SLEEP_S=30` (edit a
|
||||
copy of `sdkconfig`, `idf.py -B <dir> -DSDKCONFIG=<copy> build`), flash it, then expect:
|
||||
`station_status_watch.py` shows flags 0x01 (low) at once and 0x03 (critical); the board does NOT
|
||||
shut down while the script keeps talking; stop the script, wait about 2 minutes (60 s uptime + 30 s
|
||||
+ sampling): COM10 disappears (deep sleep); it reappears about every 30 s for a moment and goes
|
||||
away again while the cell reads below RESUME_MV. Then flash the production image again.
|
||||
- [ ] **App** (BLE checked 2026-10-05 on the Pixel: the card shows "Battery 4.12 V · about 90 %"; USB and the low/critical look still to do): with the phone on the XIAO (USB, then BLE), Settings > Connection > ESP32-C5 shows
|
||||
"Battery 3.xx V · about N %"; with a bench image whose WARN_MV is above the cell the card turns amber
|
||||
with "Low battery" and the top bar shows the battery-alert icon.
|
||||
- [ ] **Does the ADC read disturb the radio, or the radio the reading?** Connect the phone, transmit CAMs
|
||||
(radio on), and check the STATUS voltage does not jump by more than ~50 mV during TX bursts and
|
||||
that `radio_failed` stays 0 (the C5's ADC power is shared with the Wi-Fi PHY's power detector).
|
||||
- [ ] **Charge current and charge time.** The XIAO wiki gives no figure for the SGM40567. Measure the
|
||||
current into the cell with USB plugged in (multimeter in series in the cell's + wire), and note how
|
||||
the cell voltage rises. A 5000 mAh cell charged at ~100 mA takes days.
|
||||
- [ ] **Idle current from the cell** with the radio off (before Connect) and on, to estimate runtime.
|
||||
- [ ] Decide whether the cell needs a protection board before it goes anywhere but the bench: nothing
|
||||
protects it from a short, an over-current or a charge outside 0-45 degC.
|
||||
|
||||
### On-air check of the V2X data logger (added 2026-10-02)
|
||||
|
||||
Needs the phone, a second station sending (the simulated car works) and, for the CiT One part, the OBU.
|
||||
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
|
||||
obu-firmware is now a port of the colleague's `microbu-esp32c5` station (vanetza-idf, TS 103 097
|
||||
signing, station-link protocol, BLE GATT), built with **ESP-IDF 6.0.2**. See `obu-firmware/NOTES.md`.
|
||||
The previous firmware is backed up in `firmware-backups/` (restore command in its README.txt).
|
||||
The app speaks the new protocol over USB or BLE and still falls back to the old frames against the
|
||||
@@ -318,14 +15,14 @@ old firmware.
|
||||
|
||||
Done without hardware: IDF 6.0.2 build clean (39 % app partition free); host suite (`make` in
|
||||
`obu-firmware/test/host`) passes unchanged; app unit tests 103/103, including the VAM encoder
|
||||
against asn1tools, the station-link codec against Niklas Dathe's Python `messages.py`, and the VAM
|
||||
against asn1tools, the station-link codec against the colleague's Python `messages.py`, and the VAM
|
||||
generation rules. Flashed to **COM3** 2026-09-23 (hash verified); boot log: IDF v6.0.2,
|
||||
`BLE advertising started as 'micrOBU-4AFA'`, station task ready. The radio stays off until the app
|
||||
configures the station. New app build installed on the Pixel 9 Pro (adb, `install -r`).
|
||||
|
||||
First phone session (user, 2026-09-23): BLE works and CAMs go out. Three faults, fixed and
|
||||
reflashed/reinstalled the same day:
|
||||
1. No RX until the CAM pinger ran, with ~177 RX-queue drops: Niklas Dathe's `Station::tick()`
|
||||
1. No RX until the CAM pinger ran, with ~177 RX-queue drops: the colleague's `Station::tick()`
|
||||
returned before draining the radio until the first PoTi had set the clock. Now drained always.
|
||||
2. "refused a request: time_regression": the loops re-send the latest fix every tick; a stale fix
|
||||
timestamp read as the clock going back > 1 s, and each time the board rebuilt its stack.
|
||||
@@ -336,7 +33,7 @@ reflashed/reinstalled the same day:
|
||||
|
||||
Second session (user, 2026-09-23): USB, RX and signing work; BLE still prompted every time and
|
||||
never connected; time_regression every ~8 s. Found and fixed, reflashed (full flash, NVS erased):
|
||||
4. The board never stored a bond: NVS (24 KB, Niklas Dathe's 4 MB-board layout) was full, mostly
|
||||
4. The board never stored a bond: NVS (24 KB, the colleague's 4 MB-board layout) was full, mostly
|
||||
Wi-Fi settings the previous firmware left behind, and NimBLE's bond write failed. NVS is now
|
||||
80 KB (app moved to 0x20000) and was erased; boot logs `N bonded phone(s) in NVS`.
|
||||
5. The station loop waited `pdMS_TO_TICKS(5)` = 0 ticks at 100 Hz, so it spun on the single core
|
||||
@@ -372,13 +69,13 @@ resets the board, the phone is on the other port.
|
||||
- [x] **Unsigned toggle.** Signing off: the same capture shows next header 1 (common header), as
|
||||
the previous firmware sent. The card's `signed` count stops rising.
|
||||
Confirmed 2026-09-23: unsigned pinger CAMs show on V2X2MAP as unsigned.
|
||||
- [x] **Signed VAM on V2X2MAP.** Since 2026-09-23 17:16 the COM10 bridge is Niklas Dathe's
|
||||
- [x] **Signed VAM on V2X2MAP.** Since 2026-09-23 17:16 the COM10 bridge is the colleague's
|
||||
v2x2map-0.3.0 from source with a new `verify.py` and `--trust demo-chain.vcr` (launcher:
|
||||
`micrOBU_workspace/v2x-obu-esp32c5/start-v2x2map-signed.bat`, replacing its-g5-bridge.exe).
|
||||
Signed CAMs from the pinger already show "signature verified" live. Switch to VAM with signing
|
||||
on: the VAM must be decoded (cyclist, position) and show "signature verified" too.
|
||||
Confirmed by the user 2026-09-23: signed VAMs decode and verify.
|
||||
- [x] **VAM.** Transmit VAM: BTP port 2018, psid 638; with `tools/wireshark/psid-vru.lua` from Niklas Dathe's microbu-esp32c5 repository
|
||||
- [x] **VAM.** Transmit VAM: BTP port 2018, psid 638; with `microbu-esp32c5/tools/wireshark/psid-vru.lua`
|
||||
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.
|
||||
|
||||
@@ -72,12 +72,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"
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# Stored MAPEMs. One UPER MAPEM per line, hex, each below a comment naming its intersections.
|
||||
# Written by tools/mapem_bundle.py; add to it with that script.
|
||||
# -1/23 rev 2 Berliner Tor / Kolbergstrasse
|
||||
02054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
|
||||
# 1/1 rev 2 MAP_ITS_03\310\5.2
|
||||
020500ff3b6208000308cd8342fc9a94efb067719b16171aae6500010001042ac7d5cd389e98d881450d240314200000057fb8d632200bce2061ad419ea25e00b0c8000101100c22200000059f074a9208f383d45501c3ae04804284000000b3028afdd1005e7102f56a8cf4b2f10585c00008108059110000002cf9d66620479c1ea2a80e1d70240e14021000000afe339584401544436946e3336cd18161f0000406201e4404200000166fb9320822a20f5136070eac12049210000002da0a08c79440179c983032e44c65da950583400018208030910000002cc6471bc0479c01555001829524082420000005b405716c08802f393038666c98e9b4ca0b0580003051005122000000598a2612208f3802aaa003052a480e484000000b3fb5a9011005e726084ccb931dd694c1609000060c2008244000000b30d2bda811e70055540060a54900450800000166133693a200bce205cad619e8e5e40b0a8000107100a22200000059f6e4ef808f383d45501c3ae0
|
||||
# 1/1 rev 3 MAP_ITS_03_312_6.3
|
||||
020500122a7408000308cd8342fc9a94efb0677d9b1657db2e6700010001062ac7e6c6389e8341014524240624200000059ea6242680020f415a1ec1588e2b0f800010c58190001008807a1100000024c39963a0047520009a34400c488800001275dcc1282adf5432370612029210000002cf37d0e1400107a6ac8f5e2c3f05874000086880721100000024c1d54ff004d518015aa09010908000001678e47d7a00083d55607af462682c36000043840350880000011fff07a800a6a209f39744818884000008b2e9d3f290004010d4a213ca82111ad0e8406d62116d4d68858e97467aa96a885aa924436b45c23d796a1058d3a083a6a50464733833c0cbd4669e94f0c8072c4103fcbb04b1c511588900018cac26000103c4044c8880000126576511013e0d00a711e201244400000093af12d881eb2b01e74b60902d1080000115fc181fa80020096a4109f540888ce878201eb208b6e6b442cb4b833d54b5442d549221b4a2e11eb4b5082d69cc41d3528232199c19dea5f03346ca8c63f7963881d25e025263702c2200010404020888000001276bc64a03d65603ce96c12052210000022bfb788c50004014d442140a801118d0f0401566116e4d60859e97067aa96a885aa924436545e23d596b105cd39083a2a50463f33a33b9cbe8667c9540c7d52ca10344bd048d4700583c000208880391100000024ef2cdc507aaac079d2d8241034220000459a259348800204f8341af5cf8611763104bd05d624aa065128a0f7894104006bc13240944056c49e62aa158c3a828600085500c622eb8730895ccd000030ba13ca530488e430eb0920005125841000289ac1c800145161a8000a34b0e400051b587a00028e2c0e00020256568000a3a4804284400003b386364310004156faa39c2e57035afc482b6f2813cf0819cdb785571ada1979ba9161e4000c04b0e200060358690003022c460001c156564000c164802284400008b399d62a10004156faa2a42e231d0a74fa39696cb07321e5992446dae872dbc7a8ebb98b61552610872ffbd15a5e5087ccf660f91e9e1c977e43c4680876ec760f448f61f5b1bcd60e8000c0cb084000607584a0003042ca9000182840ad08084000002ccd297ba0460c01c590010ab6102a22021000000b38ab28f0118307acb383d159810498102000000ced41692400104bef10084c04104d8102000000cdbf17ed400103430f008480810518102000000cd5a8a54400104baee008540c10558102000000cc7bcbaa4001034712008501010590084000000cedf14c3400104bef08085c14005c8084000000cd63565e400103410d020c2010800000198af19ba8002068a20010c83000c901080000019aee16ac80020979dd042c604080000033c1c4df11005e7043d2f828b4245410b58102000000ceb84f91440179c0f13420a2c0a16042e604080000033a813b591005e7043f2f828bc2c5c10bd8102000000ce568b4e440179c0f0b420a2e0c18043060408000003326059991005e704412f828c4347810c58102000000cc4c12e7440179c0f53720a300e1f04326040800000330d948d51005e704432f028cc3c8010cd8102000000cbe80ebb440179c0efb440a32102100346021000004b46d8a439011511e0c1d8a4cb65b8926d06c5e07ab22d1f7516880fe5da278bab400f658c450f407da2e614f600356021000000b6a9c1bb5811511071d308806ee200
|
||||
# 1900/2396 rev 3 MAP_ITS_23_2396_12.3
|
||||
02050000302908000309cd8342fc9a94efb2677d93372dafb164b99c1db0257018ab1d58e8e27e146a05147090109080000036724ae59a00082bf0c873a533b86ab9744e0f30280082b0f800011b581200010f0807a1100000024c7271ad0283e701d9938901490800000267454e862200b9c0afc325d81822680081a9433856210000238b0b2000226101042200000049982e3d20507ce03794c12099201080000059d293e968802ce02c00c4940c976e2b14800011d589100010f880a2101080000059a3d628608c18141f380fad9620042440000012f9c386f0479c083bf6815a10400402d50288091901080000059fb1c8a208ce0741b960462fa92049a10000002cf2f675e400107d6d59337672e4160e8000640200e444000000b36da793011e7057e1902305ec9028d08000001679c9464a200bce0fadab26710e4a82c0a00010849044d0084000002ceca6a5144017381f63564ce21c951581c0002112c508000cdc400c48084000002be5766e0118302dcd220224750010903510800000165f65842a0008141f3849d7eee0b0b4000523100b32200000059ed9cbb208dfa3eb6ac12280586f092072210000002cbab7026440179c0a0f9c24e7f3a1583c0003122c08800149490045088000055f69ed86880319003180044a105023267dc19ec9ec221fd7801103bc52ac2e0001c9d60e4001050b082000829589400039b2c3d00020e1620800107220104404200000166abcf410233809194d052051120aa201080000097df5f51a200b061627950072de224f7e6515844000495ac0c80028a810598102000002cc90aebd400142bedca002018f738142e1658082ec08100000066a9780a200083129e4142c185a0830c0810000005f9539de800203c182050c8697020cb020400000598af5cae8002890e1f4004059b2f8286038bc10698102000000ce416b404001031d8a8286c3cc0106d8102000000cf0c2383400104e475828683cc410718102000000bf0debb500040d06380a1d1032041d60408000002ffb15c3400104c0720287044cc10798102000000cd03e0c5400101aaf68287c48d0107d8102000000ce9f212e400106a7098287848d40
|
||||
# 3/120 rev 1 MAP_ITS_01_120_6.1
|
||||
0205000177d308000308cd8342fc9a94efb0637d8b2617db2e6300030078022ac82671b8a0b56681450d24082420000009b0b7aaf068002007d7d19e59bdc336c362416070000210200624400000096234d61701f050c0ca66424072420000009b0c26ac968002007d7d026ce490efc723816090000212200824400000096248d5c701f050c0d0e7424062420000009b0cc0aa228002007d7d080962c3107b510160b000020a200a24400000096261157941f050c0d82502401142000000db0fc4b77480020f76960f87a503d0ad0bc79c59d402c2a000081840288880000012c26a2d6700225b426f5aa12010a10000006d883e5a74400107c1430b95a9745ea760a3cf1cf101613000040e20124440000009614e56644008aba13a8d84102d8102000000d86415bfe4001032b83828300c0410318102000000d86ed5961400104ac708282c0c0810358102000000d871b5886400103599002838100c10398102000000d87f954df400105027c028341010
|
||||
# 3/121 rev 4 MAP_ITS_01_121_17.4
|
||||
0205001233b4080003094d8342fc9a94efb0637d8b2637d8b75cd2000600f211558fedf6713dabfa1000028a1648042804200000461f312fd8230614fdc0c4cf1896272fc441ba6f9ae4761b7ed0585c0000808805990108000001619f932823061bca52c900450c00000518076e341515ba04d9582c271ad0113b9eec89daf8b08ebaeeb00b0a8000102100a3230000000628f98c86f294b2408342000000d65639ec023ce0bc87315ca1680f3262e715db99b82c18800080c4018888800001596176a20970839bc6c386ab992049a010800001165c5ab2823060bb87a15a395f0afc0a005b9e08a2c4a27e1582c0001822c188000814401448084000002b0c0f68c11830315ea81a1ff8901cd0c0000045913a65c08f382f71ac57385883cbe0c641b58521d003d41609000060c20082460000008c0e9d5b0311ef05cfe08040c60408000000cb496b0061f3f828341030103581020000003014d07c078b020a0c040d
|
||||
# 3/165 rev 1 MAP_ITS_01_165_15.1
|
||||
020500ffef5d080003094d8342fc9a94efb0637d8b66b7d8b55cc60006014a04558f6b78713f201c028a364802284000001b33e3b8c100040ef7fab781e42500100fec303744f578961b0000202b1220002025889000103080699100000024d519dfa049209022245c40490888000011f11e60c01390a099d54a4820884400000afcd8fe8400100a0859557cd9ebc56150000618b0b800030e100a22200000049fe5d2fe0e7b1607ffb91207a210000002bee6440d0004027214555f367af0584c000186880491100000024f9f2a440e16ad00daef7100b22021000000b68056211811830e626d40e12172405242000000d9d5252d880023c10d5205c537262e3faab1707ce302c35000103c9018908000008673e753ea0008f05154c16fb5c40bb02bb05e073cc3f04474c781990a8f2b13721e25a9243d2ed82416230000a2020228440000008f9dd1e5009c8504ceaa5240724200000219d5058fa8002aed1c60400416f65cb0bc0abf45e6d3e43f0547505fed4183c9a4d90787da428f4b16060589400028892061a11000006cda81e3440010492091612197b20918f19604973cd51458510003092c24800184d6164000c28b0380007045824000382920e1210000004ce74320940010e2b41c1e8ad8538c2b2200202c0c801040c400c48800000126e8fad98211d6c2fe76488020901080000059cb06a5c08c182b8f2415ada64836480420000016667b4bda200ad407e67103ed3c02c3900020544038c8084000002cd075dd60460c124824088917240824021000004b3960b365100551176a63106d8f01160ed380b4c295c5d194622d7e9812681d23d0fa5153e0ff17b23d7ada3016250000a2c480428042000001665e96d0a200b06276ad495432f25a00202c3a000241c104d8102000000cca3ec05440179c0cf3d80a140a08041460408000003371db3e11005e704c50a0084c2410558102000000cdfd6c42440179c0f34c00a160b0a04166040800000339da94cd1005e70434d0028542c2c105d8102000000ccd1a110440179c0d3ba60a180c1704186040800000336ec8bb11005e704b3168285c306010658102000000bfd757351005e703a33782868346410698102000000cc6020f9440179c1123460a190d1a
|
||||
# 3/1745 rev 3 MAP_ITS_17_1745_10.3
|
||||
0205001232f808000309cd8342fc9a94efb16f7d8b768d6fb160b99c000c1b441aab20465ce27b0616200005142c9018500840000029cdab9811831be7757237397f3c160700002022006640420000014eca07808c18a1a4d701130f2480a28400000107be3e71bdfb7b02763f7313a5f2c02c0a00004084008c880000010fd80c408c00f14389e912009a100000022e1e3902466a17006191ec0583c000101880389100000022dc876e13eb63681e7ff09010d0084000002af164ba0460c9109184e38b68e58161100004082010240420000015767bcb8230627d6c7703d9f20205b020400000058a2ba0899615400405060185820630204000000388cc701917d014160818081ac08100000016992fc21847b50010141c061a081cc08100000017afb170258840141a081c
|
||||
# 3/2052 rev 3 MAP_ITS_20_2052_12.3
|
||||
020500ffb03a08000309cd8342fc9a94efb2617d9306acafb164b99c000c20101aab1e4648e2792cf4200005147090045088000012ae75c04981c3fc0af425700c8b0d200010758610000842c19000082560e8000414b08400020b100d4220000004ab43ef77211deee423f1e00806211000000255a2f7a5208797761300f50401888800000120b8a97e07cdbd20e6a7c4200e444000000905b146b83ac1f207a9bd5100822021000000b05b242b411830e6f7c81f28f50900c90800000220af6ee48700c2b164fc27a3da35900101604400060c200424400000095784205742e3bd205e9e6f2404242000000882c6b8f61c030a55ccf0ea80084ecde1f20586c0002021202921000000241669b230e1e8425a1908269058640002029204a21000000855a3271aa0901774433c9e8a19741bfa20c68e211d4cb282c1e000140890291080000042ad05397784753c821a86f430cb7ae071091c6a88f22548160d0000a024816880420000056ad90b85d822d41344f6086dcbd3e210366a115fba3080ea34047072f80b088000503040e604080000015718dfd3c06c3ac0a0f060e040f6040800000157df5fefc1944540a0e060f04104021000001b00937ad811510e408dc1d26fe87d4687c9364585f014220e20002240420000006ae33bf0a022a223e379604126040800000103c179400f8cf40a130813041360408000001041e69b010e1aa0a120812041460210000003023a78e8118303f92e02854245010558084000000c09b5a490460c1049a80a140915041660408000001045f4e6c1096560a170a16041760408000001042e41a40f71aa0a160a1704186021000000302ce4e841183042f95828642c6010658084000000c0a3d0730460c0f49aa0a180b19041a60408000001573d9dc4c0663de0a1b0c1a041b6040800000157b79dcbc195c2c0a1a0c1b041c602100000035734de22411830176f202874347010758084000000d5ec978a30460c195c1e0a1c0d1d
|
||||
# 3/2349 rev 5 MAP_ITS_23_2349_7.5
|
||||
0205001225f4080003094d8342fc9a94efb2677d93368e6fb75cd60006125a15558ef699713ed5421000028a32480628400000210dd38b307adb8d50fd212fb05ab16030deb8169c6c0b08400010410082220000004816f339a186c76031b42312051a1000000255ab37dd109db78654f907a8b15841000103ac160001018901c908000004210c0d4f8e26a6b0146282d061e1af13b19a906239b1158290001842c108000c24401448800000121c5b01c831e898595f156200824400000090dee85fc19d45c2ca58a824093420000004ab50afe2213b4f0ca9f2cf4d80b04800040524011402100000110d8195a09810c4e83c5748003d127582c3200014084030c8084000002559df82ee00f0ea08dc9e10900850800000221b5120e930ef8b0c5ea73302c0a9080585c0002818805991000000255a06819e01b8ee88c2ddec901890800000220e3cd351232117c07112216961cccdfcc16168000c14081ac081000000217ed2e681e2ca8141c0e1a081cc0810000002193cfa7820f60c141a0e1c081ec0810000002adab420381ed9f41420101e0820c0810000002add6c085a2165c10010141e12200822c08100000060cb4dc40230682d5d0400405090508820930204000001847937b208c182bb86c142216240826c08100000060280d8c023060529f5050a0589820a3020400000181c8366608c1a37f895001014261828082a804200000160148e0e022a2434b5e1b2adb7bdf182858342c00588084000000c0dddc35045451bec288008082e804200000060c78e3b022a282e1d34004050c0706000c101080000058494b9be08a8876547d07c51a820fb0204000000ab7a2ffd287ce9140040510078f821030204000000ab83efa6c083d85050f84100
|
||||
# 3/2394 rev 4 MAP_ITS_23_2394_9.4
|
||||
0205001230ec080003094d8342fc9a94efb2677d93372d2fb95cd2000612b411558ef699713ed5421000028a2a480248042000002276537e41352fa0187e4eae20b232790161b0000208201a840420000011f6e775412e4d4c2411a3120112100000044ee66e9026a8940b8f2153a91e74a8160b0e8000105100e42200000047dfcd300485b4f096d6b4480e680420000072711f1330e7745db154609e8e8505fb5cdc8f1480082a4e2f20d442b039f41fb073c33ae82c3500008309018d080000072739316c8e7765da151d0fd0e8bc55115a30148a96cadc3520920e8647a51ce54ec42b0420003075829000184080211100000024f4269620717400728cb5100522200000049e5055560e127a0e55974480648400000213bf6b5249c49d2e83edad69c14947809678005251e02c2500010184024c8800000126a950af02bc0d836a839920622100000043f9e5cf020dd9f8cc4ee1619511c880b058000503240b44200000087f6cb00845234f196fdc18329f38dc16090000a0448148840000020ff594ba084c6a632a037bc4536e52109921c0773ce0b092000601241734200000189bad43cc0ae830155b0460e67a77e1cf18dd60b5c581595995a2a11d90010161c800041c081e80420000026657d178823063261b84844d2dd4332fbbb814200e1400204042000001673b12d4823061c4b3983d6ea00208b020400000099d0c3b40635d2050904088209302040000009cf748780a3a32050884090209b02040000009d69d88c894d4e4004050a0489820a302040000009ce35ff00776720509850a020ab02040000009db5d5d286eaab4004050b058a820b302040000009e12d10408a578050a860b00
|
||||
# 3/2421 rev 3 MAP_ITS_24_2421_4.3
|
||||
020500ffa9ca080003094d8342fc9a94efb2697d93464c6fb45cce000612ea0d558ed997713d5c091000028a2648028824000050a83ba1c42fcf8a22e087009109a0126f6242756da84fc6101980f4cc2083ff41236e31890ef08087c4e20c2b0980001015859000284880491090000024c6167cf07d31607f246d24034420000028540df9e22a37b710e244384d34b50953af8002f8b09dcc26311ef95821d7ec091d316c482f86843e5f109158340000812c2c80014204018888000001262c947503ef8c83f623992029201080000089815d9100fd2321ef762924dc7229605824000101880221010800000470b7d8404e63d909567a4480e4840000011304dad2c1f7c643cdec4749c95458c0b0280002041002422000000470dace3000f7882439e992041211000008cc18aa2c0479c3d7a240b1de1d41834360edb79060d0f02c2d0000c14402cc888000011e4d25a0093c110c8907848146864000020f8173670c4b30018d83c010d28c03c8a60434a30ac24800101960c400080e48186844000010f59d338046c080a39070871382b80ac0900018296088000c16081ac0810000001ccd781a07ea53050703868207302040000007378cb1a2116410010141a101c081ec0810000001fa73a1e07d27c050804878208302040000007f22b6d020758c141e12200822c081000000178e62a013b7c0142414220824c0810000001f3ca9d00ba20a05088509020ab020400000073a1c3a21e79fd0010142c102a082cc08100000015dd6f682085ac142a0e2c0
|
||||
# 3/2422 rev 3 MAP_ITS_24_2422_4.3
|
||||
02050012453c080003094d8342fc9a94efb2697d93464cafb45cce000612ec0d558edbb6713db4271000028a1648022804200000124e7184f87144432d02ac1ce82c22000040440208808400000239b7ff2c25d5b508b8dd1490085080000011de03e583e53c5acb595d0a660b07800010210072220000004737bf2b84d6b881167b9c120312100000023a8ef010644b72a905e574d41607000040620062440000008f085cb40f9e8f21eeb18c90149048000011c9174ac213e70b207d4e6d02c12000081040104848000011e10b6ee1c5110c5a5113c0812c0810000001d8abc640881760505018482053020400000092cce1fa077ace050482050206b0204000000766ce9001dda20141c061a081cc0810000001dc574e0087969050682070
|
||||
# 3/2423 rev 3 MAP_ITS_24_2423_9.3
|
||||
020500ffaf52080003094d8342fc9a94efb2697d93464cefb95cce000612ee0d558ee835713e2ed41000025826481468400000088b6f52463d9757153c45e9d4160f0000208200e4440000008f4296df0e2a86e1ecf15c9024d0800000111547408c7b0eae2a78bbd3702c1a000041440188880000011e7df0461c550dc3d9e2b92041a100000082284fc10020e5088f1d20037b3c00ecf5020ce582c110000818401048c800001242f185c81e4ab42d4ffd920092100000043c2b6a5c38aa1b933e488c0b420307422b0b80003075821000209880599100000023519e4202759e188fd9e3c90149048000021e0d77d61c530dc99dd44445a12783c7158210002042c560000c0c90085088000011bc63d1247523222237efe748ac2c800142562a4008228480628400000211fb6ca700ece3a374ee35c0ea6360233e403ad8e0ac19000182960e8000c16202a6424000008d429a420020e508ef1e201035810200000035e96c980f8d040a0e070d040e604080000009203260103b5e0a0d070e040f60408000000e6ffd6f05a50802840203c1041810200000036ed72c00bd3ee0a0f0810041160408000000eb13c5803eb2e028482444104981020000002e34dc6040ac3828442448104d0084000000acddda4045a8104b2a0a140a0c001420210000002e85bc2d045a80fc4ba0
|
||||
# 3/2429 rev 1 MAP_ITS_24_2429_6.1
|
||||
020500ffbb17080003094d8342fc9a94efb2697d93464e6fb65cc6000612fa04558f3b5e713fb33b028a16480228400000136f2ba4725000401215623f755b21ddebb582c2e0000404402c8880000012dfd6ca280750f1915e966412010a10000004dbd7290ba4001003e4b042b99a21c94b9082c32000040840308880000012e038c9a88784f2c15e966412019210000010dbdbc972940010e7bbda2c97bff1682f008f119b1d1e4bf4583cc268205a4fd783cf46d201906bc0b09800030310091220000004b749f29e800e8ff11252858202b0204000001b7f012348800208e5ae05030202020330204000001b7c1b276e8002876a3e40242828141014101d8102000000dbca595644001468448a0121414100a0c0810c0810000006dd8f4bc2200081c6944140e0a0e081a80420000076e0c2cde820008b3db3a477dcd350b15b57c58d1a163cc668245cabe041ae1fe87b16e1b02838082000388084000000dbce298244001084d33a
|
||||
# 3/256 rev 1 HH02\256\9
|
||||
02050012346c08000304c890c195c64d5b5c7300030100022ac7c7a8389ef572014534240324200000199b50cc1808f38b1e5c807c676f18f952ee11f1a1fea4e0861aa276811138fd611600587400030088072110000002b900ea3011e700353b04e7c88240424200000199b6dce6408f38b1d9c807c586f30f920ee31f141fea4e0561a9276791138fd5d1600587c0003010807a110000002b9246ebc11e700353b04e7c88240524200000199b8ad0b208f38b1c9c847c486f40f8eeee61f0e5fea4e0261a9276711130fd5916015884000301ac46000181040410880000015ca3f9a608f3801a9d8273e440808a110000002b96af7dc11e700353b04e7c88240b442000000571d7c37823ce006a762ad88446502c1a0001c144018888000001670131d7023ce0fb1a50ec56f84818884000000aa643d2c11e700373b156c422328160f0000e0c200e444000000b37d28a1c11e707d8d28762b7c240d44200000055295c5008f3801d9d4ab62111942b088000707585100068408041110000002cde6e1600479c1f634a1d8adf04028c880000011f325e3c08ec100c403d24802284000000b2a9bc23811e75bcd3166800a473afb2445871000084ac3c80004296204000216b11200010c585400018b92010a10000008cb09f0250479c4f0bafa075fce43e54f8233801a29443e34fa00292c21000083560e800041cb06400020f240934200000087fd26b5061a9f32c43e2a2a926300681960c4001020b07200081158410004092c45000384d6208001c28b0f4000e15587200070b0209203040800009a074bf208199c0509848c00099030408000099eb539a07ea64041440608100001344da7180fbcc80a150a1900152060810000134a89790104b38082c80c1020000268d30788209670142e1634002e40c10200002681d27e81f7990106101820400004d2864f603fb3202864306c006481820400004d3121060406ce020d202040800007416c37821a98414362a38003640810200001597e8201e667c107101020400002a5dd2003d2cf828745874007481020400003997e22c10bcc2083c80810200001d5b7bf8086261050f8b8f000f90204080000744ecb581e867c1081010204000039a9661c0f433e0a21181f002120408100000e8e3e2604313082112010408000076bdee5821998414463240004640410200001d64324a079d9f042440208100000eadb837043530828946884009480820400002c7fcb703cccf8213302040800007dd2f3d02627b4144e0844084ec0810200001e603ea6067a13051302118214201040800007e57e7c82627ac14520a48005240410200001e24bc76067a15042a40408100000fd8f057033d0a028ac3c9400ac81020400004c661fc504c4f602162020408000098a5be020981e3051688130016902040800007edc7df01a087410b901020400003da3c5140cfc2e0a2f1127002f20408100000fafd0c004c2f48218202040800007dab80b82617a814622450006240810200001ee6a120067e16043240208100000fd1f170033f0b828cc4ca400cc80820400004c9ea08204c2f4821a201040800007a92935819f868146a2854006a40410200001f5223660985e6
|
||||
# 4/937 rev 4 MAP_ITS_09_937_23.4
|
||||
0205000161d3080003094d8342fc9a94efb0737dcb36f7d9335cd20008075210558f5971713d6892028a6e48042840000022c6c0b9c40010d27c262b5fd6d04692a02de8f01164b04b19200010158b40001012c52000080c4065088800001211eeb9c08d0254c4483312202c64440000090a2f2a1829ec3405110e71014322200000485d4143c159243427882192008a11000006b2582bd90004166f902ba8f452c7d7501092facf54856168000608b041000313100b22220000048d5f923a1e8ca5858a0c364834884400002306464ad90004015d544352e75e02e51c00ba5b00b94722b044000405585c0002830802091100000234af1c50537d8501afde48906110880000160b608c9a000909aaa420642eb9312c3a000141d62c4000810b14200040a100e22220000048d120fe61db6b2859b0bb64826684400001313ec197d000469d62738cf7293720e568530ac12000182560b0000c28481448440000231cb93bf500045a40a182d2b4fb0598c482df0b41673182b04200070b58cc00040612069211000004c758cba940011ff68eba3edcad4c98f33af20b14400090d24255422000005944a82e6800200e6cc0947a720b2a8000a0e102a7222000004b458cb5700fbdc216caba692132a11000002ca44829e4001000f6b84bcd2e0594c0005078814b9110000025a2ff5bea07dee10b655d34908d9088000036c157ae9620008c64ecc118d7540c43c89530219c6a7182caa0002c4090919088000036c1572f5020008c9c8d981894d3c643b214f12197ca6082ca60002c44900c50084000006b0d9ac051005512547788092989d1a09680f09c2b25fc2058bc000609080b990108000005848c15d208a8812d0442a086588028901080000056a9a355022a219c7894545fb0c481848440000131da833c900047bd54a98fceaa0b26b1ee3a02c5900024549054d088000046256038520008d6c074e12219ce00d127027048a809736016328001a2c080cc08100000059f94c10800203a66b0503870b8203b02040000016a67288a0008317654140c1c300810c081000000581d541a800203de8c0504878c8204b02040000016401421a000830b5e014101e34081ec081000000635166592000819c394142020360820c0810000005af6c0d2800209931b0507880e0208b02040000018ce5949a800209931b0509088e8209302040000018c788fca80020670e50508888f020db020400000184f62b94800205d0f7050e090f820e30204000001859fb09c80020a3309050d8910020eb02040000018403a50280020a130d050f0990820f30204000001836da038800205f0f3050e8991020fb02040000018461186c8002038a5905100a11821030204000001866015ec80020c79a7050f8a120210b0204000001892d9084800203ae7005110a928211302040000018a7e0e6280020c559005108a930213b0204000001b08a2b91e80020838d405140b13821430204000001b0860bebe800207cb2c05138b140215a0108000001895212308002039e6605160a948016101080000018aa8103e80020c659a042d60210000003615c97dc500040f26540a2e162a042e60210000003616d972b1000410e1ac0a2d162b042f4021000000317bf219900040ce9ca0a30112c00302021000000318a12bb10004131e36086280420000005a8846b080020c3d82051907168019101080000016740257200080f19f810cd0084000000b1909a7d00041862f60a340f2e0034202100000030f4e6219000407a50a086a8042000000633066aa200081b237c146c205e006c40420000005aa9c31e8002093b21043740210000003087f37a10004079d060a3814300038202100000030d202e990004186afa0
|
||||
@@ -54,15 +54,12 @@ import com.hawhamburg.micr0bu.ui.screens.LanguageSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.SettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.RideSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.UnitsSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.UseCaseAlertsSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.screens.V2xLogSettingsScreen
|
||||
import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme
|
||||
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
|
||||
import com.hawhamburg.micr0bu.viewmodel.RideSettingsViewModel
|
||||
import com.hawhamburg.micr0bu.viewmodel.SensorViewModel
|
||||
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
|
||||
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
|
||||
@AndroidEntryPoint
|
||||
@@ -71,8 +68,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()
|
||||
private val rideViewModel: RideSettingsViewModel by viewModels()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
installSplashScreen()
|
||||
@@ -95,21 +90,15 @@ class MainActivity : AppCompatActivity() {
|
||||
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
|
||||
val obuHardware by mqttViewModel.obuHardware.collectAsState()
|
||||
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
|
||||
val stationStatus by mqttViewModel.stationStatus.collectAsState()
|
||||
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
||||
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
||||
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
||||
val phoneMount by rideViewModel.phoneMount.collectAsState()
|
||||
val fusionLogging by rideViewModel.fusionLogging.collectAsState()
|
||||
val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
|
||||
// Received hazards and live signal state, for the Dashboard's V2X summary cards.
|
||||
// Both flows already expire their own entries on a clock, so nothing here has to
|
||||
// decide when a hazard or a traffic light has gone stale.
|
||||
val denmEvents by mqttViewModel.denmEvents.collectAsState()
|
||||
val trafficLights by mqttViewModel.trafficLights.collectAsState()
|
||||
val spatIntersections by mqttViewModel.spatIntersections.collectAsState()
|
||||
val ownCamPosition by mqttViewModel.ownCamPosition.collectAsState()
|
||||
val v2xLogState by logViewModel.state.collectAsState()
|
||||
val v2xLogFiles by logViewModel.files.collectAsState()
|
||||
|
||||
MicrOBUTheme(darkTheme = state.darkTheme) {
|
||||
val view = LocalView.current
|
||||
@@ -169,8 +158,6 @@ class MainActivity : AppCompatActivity() {
|
||||
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
|
||||
esp32LinkState = esp32LinkState,
|
||||
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
|
||||
obuBatteryLow = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryLow == true,
|
||||
obuBatteryCritical = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryCritical == true,
|
||||
)
|
||||
}
|
||||
},
|
||||
@@ -193,7 +180,7 @@ class MainActivity : AppCompatActivity() {
|
||||
obuStationTypeWarning = obuStationTypeWarning,
|
||||
obuStationType = obuStationType,
|
||||
hazards = denmEvents,
|
||||
signals = trafficLights,
|
||||
signals = spatIntersections,
|
||||
ownPosition = ownCamPosition,
|
||||
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
|
||||
onNavigateToSensors = {
|
||||
@@ -308,7 +295,7 @@ class MainActivity : AppCompatActivity() {
|
||||
onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) },
|
||||
onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.route) },
|
||||
onOpenSensors = { navController.navigate(Screen.SettingsSensors.route) },
|
||||
onOpenRide = { navController.navigate(Screen.SettingsRide.route) },
|
||||
onOpenUnits = { navController.navigate(Screen.SettingsUnits.route) },
|
||||
onOpenConnection = { navController.navigate(Screen.SettingsConnection.route) },
|
||||
onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) },
|
||||
onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) },
|
||||
@@ -333,8 +320,6 @@ class MainActivity : AppCompatActivity() {
|
||||
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
|
||||
outgoingMessage = outgoingMessage,
|
||||
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
|
||||
esp32RxPath = esp32RxPath,
|
||||
onEsp32RxPathChange = mqttViewModel::setEsp32RxPath,
|
||||
signOutgoing = signOutgoing,
|
||||
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
|
||||
onBack = { navController.popBackStack() },
|
||||
@@ -361,13 +346,11 @@ class MainActivity : AppCompatActivity() {
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Screen.SettingsRide.route) {
|
||||
RideSettingsScreen(
|
||||
phoneMount = phoneMount,
|
||||
onPhoneMount = rideViewModel::setPhoneMount,
|
||||
fusionLogging = fusionLogging,
|
||||
onFusionLogging = rideViewModel::setFusionLogging,
|
||||
onBack = { navController.popBackStack() },
|
||||
composable(Screen.SettingsUnits.route) {
|
||||
UnitsSettingsScreen(
|
||||
useMetric = state.useMetric,
|
||||
onUseMetric = viewModel::setUseMetric,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Screen.SettingsMqtt.route) {
|
||||
@@ -382,21 +365,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() })
|
||||
}
|
||||
|
||||
@@ -58,20 +58,6 @@ object GnssTimeSource {
|
||||
return ItsTime.onGnssTime(systemMs, lastErrorMs?.let { systemNow + it }, systemNow)
|
||||
}
|
||||
|
||||
/**
|
||||
* GNSS time of an instant given on the monotonic `elapsedRealtimeNanos` base, such as a fix's
|
||||
* [GnssReading.elapsedRealtimeNanos]: GNSS time now, minus the instant's age.
|
||||
*
|
||||
* Prefer this to [correct] on a stored wall-clock stamp. The age comes from the monotonic
|
||||
* clock, and the wall clock is only read now, inside [correct], where its error cancels out.
|
||||
* A phone clock that is stepped between the fix and its transmission (automatic time catching
|
||||
* up, or someone setting it) therefore cannot move the result.
|
||||
*/
|
||||
fun atElapsedRealtime(elapsedRealtimeNanos: Long): Long {
|
||||
val ageMs = (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
|
||||
return correct(System.currentTimeMillis() - ageMs)
|
||||
}
|
||||
|
||||
private fun noteSource(gnssNow: Long?, systemNow: Long) {
|
||||
val usingGnss = gnssNow != null
|
||||
if (lastUsedGnss == usingGnss) return
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private val Context.rideDataStore by preferencesDataStore(name = "ride_prefs")
|
||||
|
||||
/**
|
||||
* Settings > Ride: where the phone rides ([PhoneMount]) and whether the V2X data logger also
|
||||
* records the motion sensors and raw GPS for sensor fusion (see `docs/07-sensor-fusion-logging.md`).
|
||||
*/
|
||||
@Singleton
|
||||
class RidePreferences @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
) {
|
||||
private object Keys {
|
||||
val PHONE_MOUNT = stringPreferencesKey("phone_mount")
|
||||
val FUSION_LOGGING = booleanPreferencesKey("fusion_logging")
|
||||
}
|
||||
|
||||
val phoneMountFlow: Flow<PhoneMount> = context.rideDataStore.data.map { prefs ->
|
||||
PhoneMount.fromId(prefs[Keys.PHONE_MOUNT])
|
||||
}
|
||||
|
||||
suspend fun setPhoneMount(mount: PhoneMount) {
|
||||
context.rideDataStore.edit { it[Keys.PHONE_MOUNT] = mount.id }
|
||||
}
|
||||
|
||||
/**
|
||||
* Off by default: at 100 Hz the motion sensors add about 300 rows a second, tens of MB per
|
||||
* hour, which only a fusion test ride needs.
|
||||
*/
|
||||
val fusionLoggingFlow: Flow<Boolean> = context.rideDataStore.data.map { prefs ->
|
||||
prefs[Keys.FUSION_LOGGING] ?: false
|
||||
}
|
||||
|
||||
suspend fun setFusionLogging(enabled: Boolean) {
|
||||
context.rideDataStore.edit { it[Keys.FUSION_LOGGING] = enabled }
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,6 @@ import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Handler
|
||||
import android.os.SystemClock
|
||||
import com.google.android.gms.location.LocationCallback
|
||||
import com.google.android.gms.location.LocationRequest
|
||||
import com.google.android.gms.location.LocationResult
|
||||
@@ -19,35 +15,13 @@ import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
|
||||
/**
|
||||
* One sample of a three-axis sensor.
|
||||
*
|
||||
* @property timestamp wall-clock ms of the moment the sample was taken (not of its delivery), for
|
||||
* logs and the UI, which compare it with other wall-clock stamps.
|
||||
* @property elapsedRealtimeNanos the sample's own `SensorEvent.timestamp`, on the
|
||||
* `SystemClock.elapsedRealtimeNanos` base. Monotonic: use it for intervals and for lining samples
|
||||
* up with GNSS fixes, never [timestamp], which jumps whenever the phone's clock is set.
|
||||
*/
|
||||
data class ImuReading(
|
||||
val x: Float,
|
||||
val y: Float,
|
||||
val z: Float,
|
||||
val timestamp: Long = System.currentTimeMillis(),
|
||||
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
/**
|
||||
* One location fix.
|
||||
*
|
||||
* @property timestamp wall-clock ms of the moment of the fix (not of its delivery), for in-app
|
||||
* comparisons with other wall-clock stamps. What goes on air is GNSS time instead, from
|
||||
* [GnssTimeSource.atElapsedRealtime] on [elapsedRealtimeNanos].
|
||||
* @property elapsedRealtimeNanos `Location.getElapsedRealtimeNanos()`: the moment of the fix on the
|
||||
* monotonic clock that sensor samples are also stamped with. Use it for intervals between fixes.
|
||||
* @property speedAccuracyMps 1-sigma speed accuracy, null when the provider gives none.
|
||||
* @property bearingAccuracyDeg 1-sigma bearing accuracy, null when the provider gives none.
|
||||
* @property provider the location provider that produced the fix, e.g. "fused" or "gps".
|
||||
*/
|
||||
data class GnssReading(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
@@ -55,11 +29,7 @@ data class GnssReading(
|
||||
val speedMs: Float,
|
||||
val bearingDeg: Float,
|
||||
val accuracyM: Float,
|
||||
val timestamp: Long = System.currentTimeMillis(),
|
||||
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
|
||||
val speedAccuracyMps: Float? = null,
|
||||
val bearingAccuracyDeg: Float? = null,
|
||||
val provider: String? = null,
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
class SensorRepository(private val context: Context) {
|
||||
@@ -67,30 +37,12 @@ class SensorRepository(private val context: Context) {
|
||||
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||
private val fusedLocation = LocationServices.getFusedLocationProviderClient(context)
|
||||
|
||||
/**
|
||||
* @param samplingPeriodUs a `SensorManager.SENSOR_DELAY_*` constant or a period in µs. The
|
||||
* default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
|
||||
*/
|
||||
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
|
||||
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
|
||||
fun accelerometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_ACCELEROMETER)
|
||||
|
||||
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
|
||||
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs, handler)
|
||||
fun gyroscopeFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_GYROSCOPE)
|
||||
|
||||
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
|
||||
|
||||
/**
|
||||
* Gravity in the device frame, m/s². Points up (it reads +9.81 on z with the phone flat, screen
|
||||
* up), as the accelerometer does at rest.
|
||||
*
|
||||
* From the platform's `TYPE_GRAVITY` virtual sensor, which separates gravity from motion with
|
||||
* the gyroscope. On a phone without it the raw accelerometer stands in, which still carries
|
||||
* the bike's own accelerations and vibration.
|
||||
*/
|
||||
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
|
||||
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs, handler)
|
||||
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
|
||||
|
||||
fun barometerFlow(): Flow<Float> = callbackFlow {
|
||||
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
|
||||
if (sensor == null) {
|
||||
@@ -123,37 +75,9 @@ class SensorRepository(private val context: Context) {
|
||||
awaitClose { fusedLocation.removeLocationUpdates(callback) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes from the platform's `GPS_PROVIDER` alone, next to [gnssFlow]'s fused location: no Wi-Fi
|
||||
* or cell positions mixed in and no smoothing by Google Play services, so a fusion filter sees
|
||||
* the GNSS chip's own errors. As fast as the chip delivers (minimum time and distance 0); on
|
||||
* most phones that is 1 Hz.
|
||||
*/
|
||||
@Suppress("MissingPermission")
|
||||
fun gpsProviderFlow(): Flow<GnssReading> = callbackFlow {
|
||||
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
val listener = LocationListener { loc -> trySend(loc.toReading()) }
|
||||
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, listener, context.mainLooper)
|
||||
awaitClose { locationManager.removeUpdates(listener) }
|
||||
}
|
||||
|
||||
/** "name (vendor), max N Hz" for the sensor of [type], or null if the phone has none. For log metadata. */
|
||||
fun describeSensor(type: Int): String? = sensorManager.getDefaultSensor(type)?.let { s ->
|
||||
val maxHz = if (s.minDelay > 0) ", max ${1_000_000 / s.minDelay} Hz" else ""
|
||||
"${s.name} (${s.vendor})$maxHz"
|
||||
}
|
||||
|
||||
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
|
||||
|
||||
/**
|
||||
* @param handler where sensor callbacks run; null for the main thread. A high-rate consumer
|
||||
* passes a background handler so 100 Hz callbacks neither wait on nor slow down the UI.
|
||||
*/
|
||||
private fun sensorFlow(
|
||||
type: Int,
|
||||
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
|
||||
handler: Handler? = null,
|
||||
): Flow<ImuReading> = callbackFlow {
|
||||
private fun sensorFlow(type: Int): Flow<ImuReading> = callbackFlow {
|
||||
val sensor = sensorManager.getDefaultSensor(type)
|
||||
if (sensor == null) {
|
||||
close()
|
||||
@@ -161,42 +85,20 @@ class SensorRepository(private val context: Context) {
|
||||
}
|
||||
val listener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
trySend(ImuReading(
|
||||
x = event.values[0],
|
||||
y = event.values[1],
|
||||
z = event.values[2],
|
||||
timestamp = wallClockMsAt(event.timestamp),
|
||||
elapsedRealtimeNanos = event.timestamp,
|
||||
))
|
||||
trySend(ImuReading(event.values[0], event.values[1], event.values[2]))
|
||||
}
|
||||
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
|
||||
}
|
||||
sensorManager.registerListener(listener, sensor, samplingPeriodUs, handler)
|
||||
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
|
||||
awaitClose { sensorManager.unregisterListener(listener) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wall-clock ms of an instant given on the `elapsedRealtimeNanos` base: now minus its age.
|
||||
* Both clocks are read together, so a clock change only moves the result by the change itself.
|
||||
*/
|
||||
private fun wallClockMsAt(elapsedRealtimeNanos: Long): Long =
|
||||
System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
|
||||
|
||||
private fun Location.toReading(): GnssReading {
|
||||
// A fix without its own monotonic stamp (0, as some mock providers leave it) is taken as now.
|
||||
val fixNanos = elapsedRealtimeNanos.takeIf { it > 0L } ?: SystemClock.elapsedRealtimeNanos()
|
||||
return GnssReading(
|
||||
latitude = latitude,
|
||||
longitude = longitude,
|
||||
altitude = altitude,
|
||||
speedMs = speed,
|
||||
bearingDeg = bearing,
|
||||
accuracyM = accuracy,
|
||||
timestamp = wallClockMsAt(fixNanos),
|
||||
elapsedRealtimeNanos = fixNanos,
|
||||
speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond else null,
|
||||
bearingAccuracyDeg = if (hasBearingAccuracy()) bearingAccuracyDegrees else null,
|
||||
provider = provider,
|
||||
)
|
||||
}
|
||||
private fun Location.toReading() = GnssReading(
|
||||
latitude = latitude,
|
||||
longitude = longitude,
|
||||
altitude = altitude,
|
||||
speedMs = speed,
|
||||
bearingDeg = bearing,
|
||||
accuracyM = accuracy
|
||||
)
|
||||
|
||||
@@ -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
|
||||
@@ -21,7 +20,6 @@ import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
||||
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
||||
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.cam.Cam
|
||||
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
||||
@@ -30,9 +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.IntersectionGeometry
|
||||
import com.hawhamburg.micr0bu.domain.map.MapEvent
|
||||
import com.hawhamburg.micr0bu.domain.map.StoredMaps
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
|
||||
@@ -201,21 +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 _storedMaps = MutableStateFlow<List<IntersectionGeometry>>(emptyList())
|
||||
/** The intersections the app ships with ([StoredMaps]); empty until the asset has been read. */
|
||||
val storedMaps: StateFlow<List<IntersectionGeometry>> = _storedMaps.asStateFlow()
|
||||
|
||||
private val _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
|
||||
/**
|
||||
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
|
||||
@@ -226,17 +206,6 @@ class CamUseCaseRepository @Inject constructor(
|
||||
val decodedDenm: SharedFlow<DenmEvent> = _decodedDenm.asSharedFlow()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
runCatching {
|
||||
context.assets.open(StoredMaps.ASSET_PATH).bufferedReader().use { StoredMaps.parse(it.readText()) }
|
||||
}
|
||||
.onSuccess {
|
||||
_storedMaps.value = it
|
||||
Log.d(TAG, "storedMaps: ${it.size} intersection revisions loaded")
|
||||
}
|
||||
.onFailure { Log.e(TAG, "storedMaps: cannot read ${StoredMaps.ASSET_PATH}", it) }
|
||||
}
|
||||
|
||||
scope.launch {
|
||||
mqttRepository.messages.collect { msg ->
|
||||
when (msg.topic) {
|
||||
@@ -272,7 +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}")
|
||||
}
|
||||
}
|
||||
@@ -325,7 +293,6 @@ class CamUseCaseRepository @Inject constructor(
|
||||
BtpPort.CAM -> handleCamFromSerial(v2x)
|
||||
BtpPort.DENM -> handleDenmFromSerial(v2x)
|
||||
BtpPort.SPATEM -> handleSpatFromSerial(v2x)
|
||||
BtpPort.MAPEM -> handleMapUper(v2x.uper, v2x.rssiDbm, source = "serial")
|
||||
// The firmware only forwards ports it was told to accept, so anything else
|
||||
// means the two sides have drifted out of sync.
|
||||
else -> Log.w(TAG, "unexpected BTP port ${v2x.btpPort} from firmware")
|
||||
@@ -599,19 +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,329 +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,
|
||||
/** The fix's own monotonic time (`Location.getElapsedRealtimeNanos`); phone fixes only. */
|
||||
val elapsedNs: Long? = null,
|
||||
/** 1-sigma speed and bearing accuracy, where the provider gives them; phone fixes only. */
|
||||
val speedAccuracyMps: Double? = null,
|
||||
val bearingAccuracyDeg: Double? = null,
|
||||
/** The location provider, e.g. `fused` or `gps`; phone fixes only. */
|
||||
val provider: String? = null,
|
||||
)
|
||||
|
||||
/** One received V2X message, ready to be written. */
|
||||
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)
|
||||
|
||||
/**
|
||||
* One motion sensor sample for the `imu` table (sensor fusion logging only). [sensor] is `accel`,
|
||||
* `gyro` or `gravity`; [elapsedNs] the sample's own `SensorEvent.timestamp`.
|
||||
*/
|
||||
class LogImuSample(val sensor: String, val elapsedNs: Long, val tsMs: Long, val x: Float, val y: Float, val z: Float)
|
||||
|
||||
/**
|
||||
* The phone's three clocks read together, for the `clock` table: what lines the monotonic sensor
|
||||
* and fix times up with wall-clock and GNSS time afterwards. [gnssMs] is null without GNSS time.
|
||||
*/
|
||||
class LogClockSample(val elapsedNs: Long, val wallMs: Long, val gnssMs: Long?)
|
||||
|
||||
/**
|
||||
* A V2X log: one self-contained SQLite file. Not Room, on purpose: a log is a file the developer
|
||||
* pulls off the phone and opens in any SQLite tool or pandas, so it carries its own schema and
|
||||
* 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.
|
||||
*
|
||||
* Schema 2 (2026-11-18) adds what sensor fusion needs, described in
|
||||
* `docs/07-sensor-fusion-logging.md`: the monotonic time, accuracies and provider of each phone fix
|
||||
* in `gnss`, and the `imu` and `clock` tables. Those two stay empty unless Settings > Ride >
|
||||
* "Record motion sensors" was on when the log started.
|
||||
*/
|
||||
class V2xLogWriter(val file: File, meta: Map<String, String>) {
|
||||
|
||||
private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null)
|
||||
private val insertMessage: SQLiteStatement
|
||||
private val insertGnss: SQLiteStatement
|
||||
private val insertImu: SQLiteStatement
|
||||
private val insertClock: SQLiteStatement
|
||||
|
||||
init {
|
||||
db.execSQL(
|
||||
"""
|
||||
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,
|
||||
elapsed_ns INTEGER,
|
||||
speed_accuracy_mps REAL,
|
||||
bearing_accuracy_deg REAL,
|
||||
provider TEXT
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)")
|
||||
// No index: about 300 rows a second, read back in order by replay, never searched on the phone.
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE imu (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
sensor TEXT NOT NULL,
|
||||
elapsed_ns INTEGER NOT NULL,
|
||||
ts_ms INTEGER NOT NULL,
|
||||
x REAL NOT NULL,
|
||||
y REAL NOT NULL,
|
||||
z REAL NOT NULL
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE clock (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
elapsed_ns INTEGER NOT NULL,
|
||||
wall_ms INTEGER NOT NULL,
|
||||
gnss_ms INTEGER
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
// Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI.
|
||||
db.execSQL(
|
||||
"CREATE VIEW messages_v AS SELECT *, " +
|
||||
"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, " +
|
||||
"elapsed_ns, speed_accuracy_mps, bearing_accuracy_deg, provider) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
|
||||
)
|
||||
insertImu = db.compileStatement(
|
||||
"INSERT INTO imu (sensor, elapsed_ns, ts_ms, x, y, z) VALUES (?,?,?,?,?,?)"
|
||||
)
|
||||
insertClock = db.compileStatement(
|
||||
"INSERT INTO clock (elapsed_ns, wall_ms, gnss_ms) VALUES (?,?,?)"
|
||||
)
|
||||
}
|
||||
|
||||
fun setMeta(key: String, value: String) {
|
||||
db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value))
|
||||
}
|
||||
|
||||
/** Writes all rows in one transaction. */
|
||||
fun writeBatch(
|
||||
messages: List<LogMessage>,
|
||||
gnss: List<LogGnssSample>,
|
||||
imu: List<LogImuSample> = emptyList(),
|
||||
clock: List<LogClockSample> = emptyList(),
|
||||
) {
|
||||
if (messages.isEmpty() && gnss.isEmpty() && imu.isEmpty() && clock.isEmpty()) return
|
||||
db.beginTransaction()
|
||||
try {
|
||||
for (m in messages) bindAndRun(m)
|
||||
for (g in gnss) bindAndRun(g)
|
||||
for (i in imu) bindAndRun(i)
|
||||
for (c in clock) bindAndRun(c)
|
||||
db.setTransactionSuccessful()
|
||||
} finally {
|
||||
db.endTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
runCatching { insertMessage.close() }
|
||||
runCatching { insertGnss.close() }
|
||||
runCatching { insertImu.close() }
|
||||
runCatching { insertClock.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.bind(10, g.fix.elapsedNs)
|
||||
s.bind(11, g.fix.speedAccuracyMps)
|
||||
s.bind(12, g.fix.bearingAccuracyDeg)
|
||||
s.bind(13, g.fix.provider)
|
||||
s.executeInsert()
|
||||
}
|
||||
|
||||
private fun bindAndRun(i: LogImuSample) {
|
||||
val s = insertImu
|
||||
s.clearBindings()
|
||||
s.bind(1, i.sensor)
|
||||
s.bind(2, i.elapsedNs)
|
||||
s.bind(3, i.tsMs)
|
||||
s.bind(4, i.x.toDouble())
|
||||
s.bind(5, i.y.toDouble())
|
||||
s.bind(6, i.z.toDouble())
|
||||
s.executeInsert()
|
||||
}
|
||||
|
||||
private fun bindAndRun(c: LogClockSample) {
|
||||
val s = insertClock
|
||||
s.clearBindings()
|
||||
s.bind(1, c.elapsedNs)
|
||||
s.bind(2, c.wallMs)
|
||||
s.bind(3, c.gnssMs)
|
||||
s.executeInsert()
|
||||
}
|
||||
|
||||
// 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 = 2
|
||||
}
|
||||
}
|
||||
@@ -1,567 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.data.log
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import com.hawhamburg.micr0bu.data.GnssReading
|
||||
import com.hawhamburg.micr0bu.data.ImuReading
|
||||
import com.hawhamburg.micr0bu.data.RidePreferences
|
||||
import com.hawhamburg.micr0bu.data.SensorRepository
|
||||
import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository
|
||||
import com.hawhamburg.micr0bu.data.mqtt.MessageDirection
|
||||
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.fusion.PhoneMount
|
||||
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.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.io.File
|
||||
import java.time.DateTimeException
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
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"
|
||||
/** The phone's fused location (Google Play services). */
|
||||
private const val SOURCE_PHONE = "phone"
|
||||
/** The phone's raw `GPS_PROVIDER` fixes; sensor fusion logging only. */
|
||||
private const val SOURCE_PHONE_GPS = "phone_gps"
|
||||
private const val SOURCE_OBU = "obu"
|
||||
|
||||
/** Motion sensor rate while sensor fusion logging is on: 10 000 us, 100 Hz. */
|
||||
private const val IMU_PERIOD_US = 10_000
|
||||
|
||||
/** How often the three clocks are read together into the `clock` table. */
|
||||
private const val CLOCK_INTERVAL_MS = 1_000L
|
||||
|
||||
/** How long the writer collects rows before it commits them. */
|
||||
private const val FLUSH_INTERVAL_MS = 250L
|
||||
|
||||
/** 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,
|
||||
/** Whether this log records the motion sensors and raw GPS (Settings > Ride), and the mount it started with. */
|
||||
val fusionLogging: Boolean = false,
|
||||
val phoneMount: PhoneMount? = null,
|
||||
/** Motion sensor rows written so far. */
|
||||
val imuSamples: Long = 0L,
|
||||
/** Age of the newest raw GPS_PROVIDER fix; null if none yet or not logging it. */
|
||||
val phoneGpsFixAgeMs: Long? = null,
|
||||
/** Set when the file could not be created or written. */
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** 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.
|
||||
*
|
||||
* With Settings > Ride > "Record motion sensors" on when the log starts, it also records what sensor
|
||||
* fusion needs (`docs/07-sensor-fusion-logging.md`): accelerometer, gyroscope and gravity at 100 Hz
|
||||
* into `imu`, the raw `GPS_PROVIDER` fixes next to the fused ones in `gnss`, and the three phone
|
||||
* clocks once a second into `clock`. The phone mount is recorded in `meta` either way.
|
||||
*
|
||||
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
|
||||
* keeps the process alive and the CPU awake while a log runs; this class does the work.
|
||||
*/
|
||||
@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 ridePreferences: RidePreferences,
|
||||
) {
|
||||
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 phoneGpsFix: LogGnss? = null
|
||||
@Volatile private var obuFix: LogGnss? = null
|
||||
|
||||
fun start() {
|
||||
if (session?.isActive == true) return
|
||||
val startedMs = System.currentTimeMillis()
|
||||
val hardware = mqttRepository.obuHardware.value
|
||||
// Read once, at the start: a log is one mount and one mode, so changing either mid-log
|
||||
// must not quietly mix two kinds of data in one file. DataStore answers in milliseconds.
|
||||
val (mount, fusion) = runBlocking {
|
||||
ridePreferences.phoneMountFlow.first() to ridePreferences.fusionLoggingFlow.first()
|
||||
}
|
||||
val sensors = SensorRepository(context)
|
||||
val file = File(logDir, fileNameFor(startedMs, hardware, mount.takeIf { fusion }))
|
||||
val writer = try {
|
||||
V2xLogWriter(file, metaFor(startedMs, hardware, mount, fusion, sensors))
|
||||
} 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
|
||||
phoneGpsFix = null
|
||||
obuFix = null
|
||||
rows = Channel(Channel.UNLIMITED)
|
||||
_state.value = V2xLogState(
|
||||
active = true, fileName = file.name, startedMs = startedMs,
|
||||
fusionLogging = fusion, phoneMount = mount,
|
||||
)
|
||||
refreshFiles()
|
||||
|
||||
// Sensor callbacks at 100 Hz get a thread of their own, off the main thread.
|
||||
val sensorThread = if (fusion) HandlerThread("V2xLogger-imu").apply { start() } else null
|
||||
|
||||
session = scope.launch {
|
||||
val sources = mutableListOf(
|
||||
launch { collectEsp32() },
|
||||
launch { collectCitOneRaw() },
|
||||
launch { collectCitOneMessages() },
|
||||
launch { collectPhoneGnss(sensors) },
|
||||
)
|
||||
if (sensorThread != null) {
|
||||
val handler = Handler(sensorThread.looper)
|
||||
sources += launch { collectImu(sensors, handler) }
|
||||
sources += launch { collectPhoneGps(sensors) }
|
||||
sources += launch { collectClock() }
|
||||
}
|
||||
try {
|
||||
runWriter(writer, file)
|
||||
} finally {
|
||||
sources.forEach { it.cancel() }
|
||||
sensorThread?.quitSafely()
|
||||
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
|
||||
writer.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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(sensors: SensorRepository) {
|
||||
while (true) {
|
||||
runCatching {
|
||||
sensors.gnssFlow().collect { reading ->
|
||||
val fix = reading.toLogGnss()
|
||||
phoneFix = fix
|
||||
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE, fix))
|
||||
}
|
||||
}
|
||||
delay(5_000L)
|
||||
}
|
||||
}
|
||||
|
||||
/** Raw `GPS_PROVIDER` fixes, retried like [collectPhoneGnss] in case permission comes later. */
|
||||
private suspend fun collectPhoneGps(sensors: SensorRepository) {
|
||||
while (true) {
|
||||
runCatching {
|
||||
sensors.gpsProviderFlow().collect { reading ->
|
||||
val fix = reading.toLogGnss()
|
||||
phoneGpsFix = fix
|
||||
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE_GPS, fix))
|
||||
}
|
||||
}
|
||||
delay(5_000L)
|
||||
}
|
||||
}
|
||||
|
||||
/** Accelerometer, gyroscope and gravity at 100 Hz, each sample with its own monotonic time. */
|
||||
private suspend fun collectImu(sensors: SensorRepository, handler: Handler) = coroutineScope {
|
||||
launch { sensors.accelerometerFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("accel")) } }
|
||||
launch { sensors.gyroscopeFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gyro")) } }
|
||||
// Only from the real TYPE_GRAVITY sensor: gravityFlow's accelerometer stand-in would only
|
||||
// repeat the accel rows under another name.
|
||||
if (sensors.hasSensor(Sensor.TYPE_GRAVITY)) {
|
||||
launch { sensors.gravityFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gravity")) } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The monotonic, wall and GNSS clocks read back to back once a second. Sensor samples and fixes
|
||||
* carry monotonic time, messages and OBU fixes wall time, and the transmit path GNSS time; these
|
||||
* rows convert between them, and show the phone clock's error and any step in it.
|
||||
*/
|
||||
private suspend fun collectClock() {
|
||||
while (true) {
|
||||
val elapsedNs = SystemClock.elapsedRealtimeNanos()
|
||||
val wallMs = System.currentTimeMillis()
|
||||
val gnssMs = try {
|
||||
SystemClock.currentGnssTimeClock().millis()
|
||||
} catch (e: DateTimeException) {
|
||||
null
|
||||
}
|
||||
rows.trySend(LogClockSample(elapsedNs, wallMs, gnssMs))
|
||||
delay(CLOCK_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rows ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private fun enqueueRaw(
|
||||
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>()
|
||||
val imu = ArrayList<LogImuSample>()
|
||||
val clock = ArrayList<LogClockSample>()
|
||||
var imuTotal = 0L
|
||||
|
||||
while (true) {
|
||||
// Block for the first row of a batch, give more a moment to arrive, then take
|
||||
// whatever is queued. No timeout around receive: a cancelled receive can lose the
|
||||
// element it was handing over, which a logger must not do.
|
||||
val first = rows.receiveCatching().getOrNull() ?: break
|
||||
add(first, messages, gnss, imu, clock)
|
||||
delay(FLUSH_INTERVAL_MS)
|
||||
while (true) {
|
||||
val next = rows.tryReceive().getOrNull() ?: break
|
||||
add(next, messages, gnss, imu, clock)
|
||||
}
|
||||
try {
|
||||
writer.writeBatch(messages, gnss, imu, clock)
|
||||
} catch (e: Exception) {
|
||||
// Disk full or the file went away. Say so on screen rather than logging into a void.
|
||||
Log.e(TAG, "write failed", e)
|
||||
failure = e.message ?: e.javaClass.simpleName
|
||||
rows.close()
|
||||
break
|
||||
}
|
||||
for (m in messages) counts.merge(m.kind, 1, Int::plus)
|
||||
total += messages.size
|
||||
imuTotal += imu.size
|
||||
messages.clear(); gnss.clear(); imu.clear(); clock.clear()
|
||||
|
||||
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 },
|
||||
imuSamples = imuTotal,
|
||||
phoneGpsFixAgeMs = phoneGpsFix?.let { f -> now - f.fixMs },
|
||||
)
|
||||
}
|
||||
}
|
||||
_state.update { it.copy(fileBytes = file.length(), error = failure ?: it.error, active = it.active && failure == null) }
|
||||
}
|
||||
|
||||
private fun add(
|
||||
row: Any,
|
||||
messages: MutableList<LogMessage>,
|
||||
gnss: MutableList<LogGnssSample>,
|
||||
imu: MutableList<LogImuSample>,
|
||||
clock: MutableList<LogClockSample>,
|
||||
) {
|
||||
when (row) {
|
||||
is LogMessage -> messages += row
|
||||
is LogGnssSample -> gnss += row
|
||||
is LogImuSample -> imu += row
|
||||
is LogClockSample -> clock += 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,
|
||||
elapsedNs = elapsedRealtimeNanos,
|
||||
speedAccuracyMps = speedAccuracyMps?.toDouble(),
|
||||
bearingAccuracyDeg = bearingAccuracyDeg?.toDouble(),
|
||||
provider = provider,
|
||||
)
|
||||
|
||||
private fun ImuReading.toLogImu(sensor: String) =
|
||||
LogImuSample(sensor, elapsedRealtimeNanos, timestamp, x, y, z)
|
||||
|
||||
/** `v2x_log_<start>_<hardware>.db`, with `_imu-<mount>` when it records sensor fusion data. */
|
||||
private fun fileNameFor(startedMs: Long, hardware: ObuHardware, fusionMount: PhoneMount?): String {
|
||||
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(startedMs))
|
||||
val mode = if (hardware == ObuHardware.ESP32_C5) "esp32" else "citone"
|
||||
val fusion = fusionMount?.let { "_imu-${it.id}" }.orEmpty()
|
||||
return "v2x_log_${stamp}_$mode$fusion.db"
|
||||
}
|
||||
|
||||
private fun metaFor(
|
||||
startedMs: Long,
|
||||
hardware: ObuHardware,
|
||||
mount: PhoneMount,
|
||||
fusion: Boolean,
|
||||
sensors: SensorRepository,
|
||||
): Map<String, String> {
|
||||
val meta = linkedMapOf(
|
||||
"started_ms" to startedMs.toString(),
|
||||
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
|
||||
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
|
||||
"android_sdk" to Build.VERSION.SDK_INT.toString(),
|
||||
"app_version" to runCatching {
|
||||
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
|
||||
}.getOrDefault("?"),
|
||||
"phone_mount" to mount.id,
|
||||
"fusion_logging" to fusion.toString(),
|
||||
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
|
||||
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5. gnss.source: phone = " +
|
||||
"fused location, phone_gps = raw GPS_PROVIDER, obu = the CiT One's obu_gnss. " +
|
||||
"elapsed_ns is SystemClock.elapsedRealtimeNanos; the clock table converts it to wall " +
|
||||
"and GNSS time. See docs/07-sensor-fusion-logging.md.",
|
||||
)
|
||||
if (fusion) {
|
||||
meta["imu_period_us"] = IMU_PERIOD_US.toString()
|
||||
sensors.describeSensor(Sensor.TYPE_ACCELEROMETER)?.let { meta["sensor_accel"] = it }
|
||||
sensors.describeSensor(Sensor.TYPE_GYROSCOPE)?.let { meta["sensor_gyro"] = it }
|
||||
meta["sensor_gravity"] = sensors.describeSensor(Sensor.TYPE_GRAVITY) ?: "none (not logged)"
|
||||
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
meta["gnss_hardware"] = "${lm.gnssHardwareModelName ?: "?"} (year ${lm.gnssYearOfHardware})"
|
||||
}
|
||||
return meta
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -6,7 +6,6 @@ import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||
@@ -39,7 +38,6 @@ class ObuHardwarePreferences @Inject constructor(
|
||||
// ESP32-C5 only.
|
||||
val ESP32_TRANSPORT = stringPreferencesKey("esp32_transport")
|
||||
val OUTGOING_MESSAGE = stringPreferencesKey("outgoing_message")
|
||||
val ESP32_RX_PATH = stringPreferencesKey("esp32_rx_path")
|
||||
val SIGN_OUTGOING = booleanPreferencesKey("sign_outgoing")
|
||||
}
|
||||
|
||||
@@ -60,15 +58,6 @@ class ObuHardwarePreferences @Inject constructor(
|
||||
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_TRANSPORT] = transport.id }
|
||||
}
|
||||
|
||||
/** Where received ITS messages come from on the ESP32-C5 path: V2X_RX (default) or the RAW_FRAME debug capture. */
|
||||
val esp32RxPathFlow: Flow<Esp32RxPath> = context.obuHardwareDataStore.data.map { prefs ->
|
||||
Esp32RxPath.entries.firstOrNull { it.id == prefs[Keys.ESP32_RX_PATH] } ?: Esp32RxPath.V2X_RX
|
||||
}
|
||||
|
||||
suspend fun setEsp32RxPath(path: Esp32RxPath) {
|
||||
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_RX_PATH] = path.id }
|
||||
}
|
||||
|
||||
/** What the ESP32-C5 path transmits while recording: CAM (default) or VAM. */
|
||||
val outgoingMessageFlow: Flow<OutgoingMessage> = context.obuHardwareDataStore.data.map { prefs ->
|
||||
OutgoingMessage.entries.firstOrNull { it.id == prefs[Keys.OUTGOING_MESSAGE] } ?: OutgoingMessage.CAM
|
||||
|
||||
@@ -45,7 +45,7 @@ private const val TAG = "BleLinkTransport"
|
||||
|
||||
/**
|
||||
* BLE GATT central for the micrOBU's station link: the Android counterpart of the firmware's
|
||||
* `obu-firmware/main/simple_ble.cpp` (from Niklas Dathe's microbu-esp32c5) and of their Python
|
||||
* `obu-firmware/main/simple_ble.cpp` (from the colleague's microbu-esp32c5) and of their Python
|
||||
* `microbu_link/ble_transport.py`, which this follows step for step.
|
||||
*
|
||||
* ## The GATT layout (what the firmware actually implements)
|
||||
@@ -94,7 +94,6 @@ class BleLinkTransport @Inject constructor(
|
||||
private const val SCAN_TIMEOUT_MS = 15_000L
|
||||
/** Long enough for the user to find and type the passkey in the system dialog. */
|
||||
private const val BOND_TIMEOUT_MS = 60_000L
|
||||
private const val KEY_LAST_ADDRESS = "last_address"
|
||||
private const val GATT_OP_TIMEOUT_MS = 5_000L
|
||||
/** After a working link dropped: try again soon. */
|
||||
private const val RECONNECT_DELAY_MS = 1_000L
|
||||
@@ -115,20 +114,6 @@ class BleLinkTransport @Inject constructor(
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
|
||||
private val prefs = context.getSharedPreferences("ble_link", Context.MODE_PRIVATE)
|
||||
/** Failed connections since the last good one, with several bonded micrOBUs; picks which one is next. */
|
||||
private var connectAttempt = 0
|
||||
|
||||
/**
|
||||
* Of the bonded micrOBUs, the one to try now: the address that last reached CONNECTED first, then
|
||||
* the others in turn after each failed connection. Null when none is bonded.
|
||||
*/
|
||||
private fun pickBonded(bonded: List<BluetoothDevice>): BluetoothDevice? {
|
||||
if (bonded.isEmpty()) return null
|
||||
val last = prefs.getString(KEY_LAST_ADDRESS, null)
|
||||
val ordered = bonded.sortedBy { if (it.address == last) 0 else 1 }
|
||||
return ordered[connectAttempt % ordered.size]
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
|
||||
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
|
||||
@@ -238,10 +223,7 @@ class BleLinkTransport @Inject constructor(
|
||||
_state.value = Esp32LinkState.DEVICE_ATTACHED
|
||||
// A bonded micrOBU is reused without scanning: its address is stable (public address), and
|
||||
// this is what makes a reconnect after a dropout fast.
|
||||
// Android may hold several bonded micrOBUs (a replaced board stays bonded): the one that
|
||||
// worked last goes first, and each failed connection moves on to the next.
|
||||
val bonded = adapter.bondedDevices.filter { it.name?.startsWith(NAME_PREFIX) == true }
|
||||
val device = pickBonded(bonded)
|
||||
val device = adapter.bondedDevices.firstOrNull { it.name?.startsWith(NAME_PREFIX) == true }
|
||||
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
|
||||
deviceName = device.name
|
||||
_detail.value = null
|
||||
@@ -250,7 +232,6 @@ class BleLinkTransport @Inject constructor(
|
||||
connected = CompletableDeferred()
|
||||
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
|
||||
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
|
||||
if (bonded.size > 1) connectAttempt++
|
||||
return fail("Could not connect to ${device.name}")
|
||||
}
|
||||
|
||||
@@ -296,8 +277,6 @@ class BleLinkTransport @Inject constructor(
|
||||
if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
|
||||
}
|
||||
_state.value = Esp32LinkState.CONNECTED
|
||||
connectAttempt = 0
|
||||
prefs.edit().putString(KEY_LAST_ADDRESS, device.address).apply()
|
||||
Log.i(TAG, "BLE station link ready: ${device.name}")
|
||||
// Wait until the link drops (callback completes `connected` anew with false).
|
||||
val dropped = CompletableDeferred<Boolean>()
|
||||
@@ -335,7 +314,7 @@ class BleLinkTransport @Inject constructor(
|
||||
* does not finish within [BOND_TIMEOUT_MS].
|
||||
*
|
||||
* The probe is a read of the STATUS characteristic, which needs an encrypted and authenticated
|
||||
* link, as Niklas Dathe's Python transport does. Android answers a read the link is not
|
||||
* link, as the colleague's Python transport does. Android answers a read the link is not
|
||||
* secure enough for by encrypting, or by pairing and showing the passkey dialog, and then
|
||||
* retries the read itself. While it pairs, the card says which passkey to type.
|
||||
*/
|
||||
|
||||
@@ -39,21 +39,6 @@ enum class Esp32LinkState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED,
|
||||
/** Which physical link the phone uses to reach the ESP32-C5 (Settings). */
|
||||
enum class Esp32Transport(val id: String) { USB("usb"), BLE("ble") }
|
||||
|
||||
/**
|
||||
* Where the app takes received ITS messages from (Settings > Connection > ESP32-C5 > Receive path).
|
||||
*
|
||||
* - [V2X_RX]: the MicrOBU extension (opcode 0x90). The board unwraps every received frame itself and
|
||||
* sends the finished ITS message, signed or not. Small, always on, the default.
|
||||
* - [RAW_FRAME]: the station-link `RAW_FRAME` debug capture of docs/station-link.pdf (opcode 0x85,
|
||||
* switched on with `RAW_CAPTURE`). The board sends the whole 802.11 frame, possibly fragmented, and
|
||||
* the app unwraps it with [GnUnwrap]. Spec-defined and not limited to 494 octets, but best effort:
|
||||
* copies can be dropped when the link is busy, and it costs more bandwidth, especially over BLE.
|
||||
*
|
||||
* Both reach the rest of the app as the same [SerialFrameType.V2X_RX] frames, so nothing above this
|
||||
* class changes with the setting. The board keeps sending `V2X_RX` regardless; the app uses one path.
|
||||
*/
|
||||
enum class Esp32RxPath(val id: String) { V2X_RX("v2x_rx"), RAW_FRAME("raw_frame") }
|
||||
|
||||
/** What the phone transmits while a trip records (Settings). */
|
||||
enum class OutgoingMessage(val id: String) { CAM("cam"), VAM("vam") }
|
||||
|
||||
@@ -110,9 +95,6 @@ class Esp32Link @Inject constructor(
|
||||
companion object {
|
||||
private const val TAG = "Esp32Link"
|
||||
private const val REPLY_TIMEOUT_MS = 3_000L
|
||||
private const val STATUS_POLL_MS = 1_000L
|
||||
/** RAW_CAPTURE mode: on (bit 0) and broadcast frames only (bit 1): every ITS-G5 frame, no unicast noise. */
|
||||
private const val RAW_CAPTURE_ON_BROADCAST = 0x03
|
||||
/** Applying a bundle verifies the chain and rebuilds the stack on the C5: seconds, not ms. */
|
||||
private const val PROVISION_TIMEOUT_MS = 15_000L
|
||||
private const val SEGMENT_SIZE = 240
|
||||
@@ -132,7 +114,7 @@ class Esp32Link @Inject constructor(
|
||||
const val ITS_AID_VAM = 638L
|
||||
/** CAM SSP version 1, no special-vehicle permissions: what the demo ticket grants for ITS-AID 36. */
|
||||
val SSP_CAM = byteArrayOf(0x01, 0x00, 0x00)
|
||||
/** VRU SSP as the demo ticket grants for ITS-AID 638 (same as Niklas Dathe's VBS). */
|
||||
/** VRU SSP as the demo ticket grants for ITS-AID 638 (same as the colleague's VBS). */
|
||||
val SSP_VAM = byteArrayOf(0x01)
|
||||
}
|
||||
|
||||
@@ -141,17 +123,6 @@ class Esp32Link @Inject constructor(
|
||||
val transport: StateFlow<Esp32Transport> =
|
||||
prefs.esp32TransportFlow.stateIn(scope, SharingStarted.Eagerly, Esp32Transport.USB)
|
||||
|
||||
/** Which received-message path is in use. See [Esp32RxPath]. */
|
||||
val rxPath: StateFlow<Esp32RxPath> =
|
||||
prefs.esp32RxPathFlow.stateIn(scope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
|
||||
|
||||
/** Fragments of RAW_FRAME (and any other large indication) in flight; reset with every session. */
|
||||
private val reassembly = LinkReassembly()
|
||||
|
||||
/** RAW_FRAME bodies seen, unwrapped to an ITS message, and not an ITS message (the usual case on air). */
|
||||
@Volatile private var rawSeen = 0L
|
||||
@Volatile private var rawForwarded = 0L
|
||||
|
||||
val state: StateFlow<Esp32LinkState> = combine(transport, usb.state, ble.state) { t, u, b ->
|
||||
if (t == Esp32Transport.USB) u else b
|
||||
}.stateIn(scope, SharingStarted.Eagerly, Esp32LinkState.DISCONNECTED)
|
||||
@@ -199,7 +170,6 @@ class Esp32Link @Inject constructor(
|
||||
@Volatile private var lastPotiFixMs: Long? = null
|
||||
|
||||
init {
|
||||
scope.launch { pollStatus() }
|
||||
scope.launch { usb.incomingFrames.collect { onUsbFrame(it) } }
|
||||
scope.launch { ble.incoming.collect { onLinkMessage(it) } }
|
||||
scope.launch { usb.linkStatus.collect { if (it != null) _linkStatus.value = it } }
|
||||
@@ -213,15 +183,12 @@ class Esp32Link @Inject constructor(
|
||||
_linkStatus.value = null
|
||||
pending.values.forEach { it.cancel() }
|
||||
pending.clear()
|
||||
reassembly.reset()
|
||||
} else if (transport.value == Esp32Transport.BLE) {
|
||||
_protocol.value = Esp32Protocol.STATION_LINK // BLE exists only on the current firmware
|
||||
scope.launch { ensureConfigured(null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
// A change of receive path in Settings takes effect at once on a configured station.
|
||||
scope.launch { rxPath.collect { scope.launch { applyRxPath() } } }
|
||||
scope.launch { ble.detail.collect { if (transport.value == Esp32Transport.BLE) _detail.value = it } }
|
||||
// Switching transport in Settings closes the other one; connecting stays a user action.
|
||||
scope.launch {
|
||||
@@ -304,7 +271,7 @@ class Esp32Link @Inject constructor(
|
||||
private suspend fun ensureConfigured(wanted: StationConfigure?): Boolean = sessionMutex.withLock {
|
||||
val current = configured
|
||||
if (current != null && (wanted == null || current == wanted)) return@withLock true
|
||||
val config = wanted ?: StationConfigure(stationType = StationType.CYCLIST)
|
||||
val config = wanted ?: StationConfigure(stationType = StationType.CYCLIST, mid = pseudonymManager.current().mac)
|
||||
_detail.value = "Configuring the micrOBU"
|
||||
val result = request(LinkOpcode.STATION_CONFIGURE, config.encode(), REPLY_TIMEOUT_MS)
|
||||
if (result == null || !result.accepted) {
|
||||
@@ -318,36 +285,9 @@ class Esp32Link @Inject constructor(
|
||||
}
|
||||
configured = config
|
||||
_detail.value = null
|
||||
scope.launch { applyRxPath() } // a (re)configured station starts with raw capture off
|
||||
true
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the station's raw capture to match [rxPath]: on (receive only, broadcast frames) for
|
||||
* [Esp32RxPath.RAW_FRAME], off for [Esp32RxPath.V2X_RX]. RAW_CAPTURE needs a started radio, so it
|
||||
* is sent only once the station is configured; a station that restarted forgets it and is
|
||||
* configured again, which sends it again.
|
||||
*/
|
||||
private suspend fun applyRxPath() {
|
||||
if (_protocol.value != Esp32Protocol.STATION_LINK || state.value != Esp32LinkState.CONNECTED) return
|
||||
if (configured == null) return
|
||||
val mode = if (rxPath.value == Esp32RxPath.RAW_FRAME) RAW_CAPTURE_ON_BROADCAST else 0
|
||||
val result = request(LinkOpcode.RAW_CAPTURE, byteArrayOf(mode.toByte()), REPLY_TIMEOUT_MS)
|
||||
Log.i(TAG, "receive path ${rxPath.value}: RAW_CAPTURE mode $mode -> ${result?.let { LinkResultCode.name(it.code) } ?: "no reply"}")
|
||||
if (result != null && !result.accepted && mode != 0) _detail.value = "Raw capture refused: ${LinkResultCode.name(result.code)}"
|
||||
}
|
||||
|
||||
/** One RAW_FRAME: unwrap it to the ITS message inside and hand it on like a V2X_RX message. */
|
||||
private fun onRawFrame(body: ByteArray) {
|
||||
val raw = RawFrame.parse(body) ?: return
|
||||
if (raw.ownTransmission) return
|
||||
rawSeen++
|
||||
val unwrapped = GnUnwrap.unwrap(raw.frame) ?: return
|
||||
val v2xRx = GnUnwrap.toV2xRxBody(unwrapped, raw.rssiDbm) ?: return
|
||||
rawForwarded++
|
||||
_incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, v2xRx))
|
||||
}
|
||||
|
||||
private suspend fun provisionDemoCredentials(): Boolean {
|
||||
_detail.value = "Provisioning the demo credentials"
|
||||
val bundle = runCatching { context.assets.open(DEMO_BUNDLE_ASSET).use { it.readBytes() } }.getOrElse {
|
||||
@@ -428,14 +368,10 @@ class Esp32Link @Inject constructor(
|
||||
}
|
||||
|
||||
private fun onLinkMessage(octets: ByteArray) {
|
||||
// Fragments are put back together first (flags 1-3 of docs/station-link.pdf); a complete
|
||||
// message, the usual case, passes straight through.
|
||||
val message = reassembly.feed(LinkMessage.decode(octets) ?: return) ?: return
|
||||
val message = LinkMessage.decode(octets) ?: return
|
||||
when (message.opcode) {
|
||||
LinkOpcode.V2X_RX ->
|
||||
if (rxPath.value == Esp32RxPath.V2X_RX) _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
|
||||
LinkOpcode.RAW_FRAME -> if (rxPath.value == Esp32RxPath.RAW_FRAME) onRawFrame(message.body)
|
||||
LinkOpcode.CONFIRM -> {
|
||||
LinkOpcode.V2X_RX -> _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
|
||||
LinkOpcode.RESULT -> {
|
||||
val result = LinkResult.decode(message.body) ?: return
|
||||
val waiting = pending.remove(message.sequence)
|
||||
if (waiting != null) {
|
||||
@@ -451,37 +387,26 @@ class Esp32Link @Inject constructor(
|
||||
noteRefusal("micrOBU refused a request: ${LinkResultCode.name(result.code)}")
|
||||
}
|
||||
}
|
||||
LinkOpcode.STATUS -> {
|
||||
val status = StationStatus.decode(message.body) ?: return
|
||||
val first = _protocol.value != Esp32Protocol.STATION_LINK
|
||||
_protocol.value = Esp32Protocol.STATION_LINK
|
||||
_stationStatus.value = status
|
||||
_linkStatus.value = EspLinkStatus(
|
||||
status = 0,
|
||||
oversizeDrops = 0,
|
||||
txFailures = status.radioFailed.coerceAtMost(0xFFFF).toInt(),
|
||||
rxCrcErrors = status.linkCrcErrors.coerceAtMost(0xFFFF).toInt(),
|
||||
rxQueueDrops = status.radioDropped.coerceAtMost(0xFFFF).toInt(),
|
||||
)
|
||||
// Board reset (or first contact): configure now, so its receiver runs even before
|
||||
// the first message is sent.
|
||||
if (!status.configured) { configured = null; lastPotiMs = null; lastPotiFixMs = null }
|
||||
if (first || !status.configured) scope.launch { ensureConfigured(null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks for the status snapshot once a second while connected (the board does not push it). */
|
||||
private suspend fun pollStatus() {
|
||||
while (true) {
|
||||
delay(STATUS_POLL_MS)
|
||||
if (state.value != Esp32LinkState.CONNECTED || _protocol.value == Esp32Protocol.LEGACY_SERIAL) continue
|
||||
val result = request(LinkOpcode.STATUS_REQUEST, ByteArray(0), REPLY_TIMEOUT_MS) ?: continue
|
||||
if (!result.accepted) continue
|
||||
handleStatus(StationStatus.decode(result.detail) ?: continue)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleStatus(status: StationStatus) {
|
||||
val first = _protocol.value != Esp32Protocol.STATION_LINK
|
||||
_protocol.value = Esp32Protocol.STATION_LINK
|
||||
_stationStatus.value = status
|
||||
_linkStatus.value = EspLinkStatus(
|
||||
status = 0,
|
||||
oversizeDrops = 0,
|
||||
txFailures = status.radioFailed.coerceAtMost(0xFFFF).toInt(),
|
||||
rxCrcErrors = status.linkCrcErrors.coerceAtMost(0xFFFF).toInt(),
|
||||
rxQueueDrops = status.radioDropped.coerceAtMost(0xFFFF).toInt(),
|
||||
)
|
||||
// Board reset (or first contact): configure now, so its receiver runs even before the first
|
||||
// message is sent.
|
||||
if (!status.configured) { configured = null; lastPotiMs = null; lastPotiFixMs = null }
|
||||
if (first || !status.configured) scope.launch { ensureConfigured(null) }
|
||||
}
|
||||
|
||||
private fun noteRefusal(line: String) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastRefusalLogMs < 5_000) return
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.data.transport
|
||||
|
||||
/**
|
||||
* Kotlin counterpart of obu-firmware's `gn_unwrap.c`: takes one received 802.11 data frame down
|
||||
* through LLC/SNAP, GeoNetworking and BTP-B to the ITS message inside, signed or not.
|
||||
*
|
||||
* It exists so the app can consume the station's `RAW_FRAME` debug capture the way it consumes
|
||||
* `V2X_RX` (which the board builds with the C version). The two are tested against each other on the
|
||||
* same frames (`GnUnwrapTest`, corpus from the C code), so they accept and reject the same frames and
|
||||
* return the same fields.
|
||||
*
|
||||
* What it does and does not do, as in the C version:
|
||||
* - Plain Data frames only, QoS or not, no WDS; LLC/SNAP with the GeoNetworking ethertype 0x8947.
|
||||
* - Single-hop broadcast (TSB subtype 0) and GeoBroadcast; BTP-B on ports 2001-2004 and 2018.
|
||||
* - A secured packet (TS 103 097 / IEEE 1609.2 `signedData` or `unsecuredData`, protocolVersion 3) is
|
||||
* unwrapped WITHOUT verifying the signature or certificate; the result says it was signed.
|
||||
* Encrypted and legacy v1.2.1 envelopes are rejected.
|
||||
* - The payload is exactly as long as the Common Header declares, not what is left of the frame.
|
||||
*/
|
||||
object GnUnwrap {
|
||||
|
||||
/** An unwrapped ITS message. [payload] is its UPER encoding. */
|
||||
class Result(
|
||||
val btpPort: Int,
|
||||
val payload: ByteArray,
|
||||
val hasGeoArea: Boolean,
|
||||
val areaLatTenMicroDeg: Int,
|
||||
val areaLonTenMicroDeg: Int,
|
||||
val areaDistanceAMeters: Int,
|
||||
/** The packet carried a signature envelope; it was not checked. */
|
||||
val signedUnverified: Boolean,
|
||||
/** The frame ended before the payload its headers declare; [payload] is only what arrived. */
|
||||
val truncated: Boolean,
|
||||
)
|
||||
|
||||
private const val GN_ETHERTYPE = 0x8947
|
||||
private const val LLC_SNAP_HEADER_LEN = 8
|
||||
private const val IEEE80211_HEADER_LEN = 24
|
||||
private const val IEEE80211_QOS_CTRL_LEN = 2
|
||||
private const val FC_TYPE_DATA = 2
|
||||
private const val FC_QOS_SUBTYPE_BIT = 0x08
|
||||
private const val GN_BASIC_HEADER_LEN = 4
|
||||
private const val GN_COMMON_HEADER_LEN = 8
|
||||
private const val BTP_B_HEADER_LEN = 4
|
||||
private const val GN_SHB_EXT_HEADER_LEN = 28
|
||||
private const val GN_GBC_EXT_HEADER_LEN = 44
|
||||
private const val GBC_AREA_LAT_OFFSET = 28
|
||||
private const val GBC_AREA_LON_OFFSET = 32
|
||||
private const val GBC_AREA_DIST_A_OFFSET = 36
|
||||
private const val GN_HEADER_TYPE_GBC = 4
|
||||
private const val GN_HEADER_TYPE_TSB = 5
|
||||
private const val GN_HEADER_SUBTYPE_SINGLE_HOP = 0
|
||||
private const val GN_NEXT_HEADER_COMMON = 1
|
||||
private const val GN_NEXT_HEADER_SECURED = 2
|
||||
private const val GN_COMMON_NEXT_HEADER_BTP_B = 2
|
||||
private const val GN_COMMON_PAYLOAD_LEN_OFFSET = 4
|
||||
private const val IEEE1609DOT2_VERSION = 3
|
||||
private const val CONTENT_TAG_UNSECURED_DATA = 0x80
|
||||
private const val CONTENT_TAG_SIGNED_DATA = 0x81
|
||||
private const val SIGNED_PAYLOAD_HAS_DATA = 0x40
|
||||
|
||||
private val BTP_PORTS = setOf(2001, 2002, 2003, 2004, 2018)
|
||||
private val LLC_SNAP_PREFIX = intArrayOf(0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00)
|
||||
|
||||
private fun ByteArray.u8(i: Int) = this[i].toInt() and 0xFF
|
||||
private fun ByteArray.be16(i: Int) = (u8(i) shl 8) or u8(i + 1)
|
||||
private fun ByteArray.be32(i: Int) = (u8(i) shl 24) or (u8(i + 1) shl 16) or (u8(i + 2) shl 8) or u8(i + 3)
|
||||
|
||||
/** COER length determinant: returns (octets used, length), or null when it does not fit. */
|
||||
private fun coerLength(f: ByteArray, at: Int, avail: Int): Pair<Int, Int>? {
|
||||
if (avail < 1) return null
|
||||
val first = f.u8(at)
|
||||
if (first < 0x80) return 1 to first
|
||||
val n = first and 0x7F
|
||||
if (n < 1 || n > 2 || avail < 1 + n) return null
|
||||
var v = 0
|
||||
for (i in 1..n) v = (v shl 8) or f.u8(at + i)
|
||||
return (1 + n) to v
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Common Header offset inside the envelope, the end of the envelope's inner packet
|
||||
* and whether it was signed; null for anything this does not handle.
|
||||
*/
|
||||
private fun unwrapSecured(f: ByteArray, offset: Int, frameLen: Int): Triple<Int, Int, Boolean>? {
|
||||
val avail = frameLen - offset
|
||||
if (avail < 2 || f.u8(offset) != IEEE1609DOT2_VERSION) return null
|
||||
val i: Int
|
||||
val signed: Boolean
|
||||
if (f.u8(offset + 1) == CONTENT_TAG_SIGNED_DATA) {
|
||||
if (avail < 6 ||
|
||||
f.u8(offset + 2) >= 0x80 ||
|
||||
(f.u8(offset + 3) and SIGNED_PAYLOAD_HAS_DATA) == 0 ||
|
||||
f.u8(offset + 4) != IEEE1609DOT2_VERSION ||
|
||||
f.u8(offset + 5) != CONTENT_TAG_UNSECURED_DATA
|
||||
) return null
|
||||
i = 6
|
||||
signed = true
|
||||
} else if (f.u8(offset + 1) == CONTENT_TAG_UNSECURED_DATA) {
|
||||
i = 2
|
||||
signed = false
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
val (used, len) = coerLength(f, offset + i, avail - i) ?: return null
|
||||
val innerStart = offset + i + used
|
||||
return Triple(innerStart, offset + i + used + len, signed)
|
||||
}
|
||||
|
||||
/** Unwraps one 802.11 frame; null when it is not an ITS message this handles (the common case on air). */
|
||||
fun unwrap(frame: ByteArray): Result? {
|
||||
val frameLen = frame.size
|
||||
if (frameLen < IEEE80211_HEADER_LEN) return null
|
||||
val fc0 = frame.u8(0)
|
||||
val fc1 = frame.u8(1)
|
||||
val type = (fc0 shr 2) and 0x03
|
||||
val subtype = (fc0 shr 4) and 0x0F
|
||||
val toDs = (fc1 and 0x01) != 0
|
||||
val fromDs = (fc1 and 0x02) != 0
|
||||
if (type != FC_TYPE_DATA || (toDs && fromDs)) return null
|
||||
|
||||
var offset = IEEE80211_HEADER_LEN
|
||||
if ((subtype and FC_QOS_SUBTYPE_BIT) != 0) offset += IEEE80211_QOS_CTRL_LEN
|
||||
|
||||
if (frameLen < offset + LLC_SNAP_HEADER_LEN) return null
|
||||
for (k in LLC_SNAP_PREFIX.indices) if (frame.u8(offset + k) != LLC_SNAP_PREFIX[k]) return null
|
||||
if (frame.be16(offset + 6) != GN_ETHERTYPE) return null
|
||||
offset += LLC_SNAP_HEADER_LEN
|
||||
|
||||
if (frameLen < offset + GN_BASIC_HEADER_LEN) return null
|
||||
val basicNextHeader = frame.u8(offset) and 0x0F
|
||||
offset += GN_BASIC_HEADER_LEN
|
||||
|
||||
var limit = frameLen
|
||||
var envelopeEnd = -1
|
||||
var signed = false
|
||||
if (basicNextHeader == GN_NEXT_HEADER_SECURED) {
|
||||
val (inner, end, isSigned) = unwrapSecured(frame, offset, frameLen) ?: return null
|
||||
offset = inner
|
||||
envelopeEnd = end
|
||||
signed = isSigned
|
||||
if (envelopeEnd < limit) limit = envelopeEnd
|
||||
} else if (basicNextHeader != GN_NEXT_HEADER_COMMON) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (limit < offset + GN_COMMON_HEADER_LEN) return null
|
||||
val nextHeader = (frame.u8(offset) shr 4) and 0x0F
|
||||
val headerType = (frame.u8(offset + 1) shr 4) and 0x0F
|
||||
val headerSubtype = frame.u8(offset + 1) and 0x0F
|
||||
val gnPayloadLen = frame.be16(offset + GN_COMMON_PAYLOAD_LEN_OFFSET)
|
||||
if (nextHeader != GN_COMMON_NEXT_HEADER_BTP_B) return null
|
||||
offset += GN_COMMON_HEADER_LEN
|
||||
|
||||
val extLen: Int
|
||||
var isGbc = false
|
||||
if (headerType == GN_HEADER_TYPE_TSB && headerSubtype == GN_HEADER_SUBTYPE_SINGLE_HOP) {
|
||||
extLen = GN_SHB_EXT_HEADER_LEN
|
||||
} else if (headerType == GN_HEADER_TYPE_GBC) {
|
||||
extLen = GN_GBC_EXT_HEADER_LEN
|
||||
isGbc = true
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
if (limit < offset + extLen) return null
|
||||
var areaLat = 0
|
||||
var areaLon = 0
|
||||
var areaDist = 0
|
||||
if (isGbc) {
|
||||
areaLat = frame.be32(offset + GBC_AREA_LAT_OFFSET)
|
||||
areaLon = frame.be32(offset + GBC_AREA_LON_OFFSET)
|
||||
areaDist = frame.be16(offset + GBC_AREA_DIST_A_OFFSET)
|
||||
}
|
||||
offset += extLen
|
||||
|
||||
if (limit < offset + BTP_B_HEADER_LEN) return null
|
||||
val destPort = frame.be16(offset)
|
||||
if (destPort !in BTP_PORTS) return null
|
||||
|
||||
if (gnPayloadLen <= BTP_B_HEADER_LEN) return null
|
||||
val payloadStart = offset + BTP_B_HEADER_LEN
|
||||
val payloadEnd = offset + gnPayloadLen
|
||||
if (envelopeEnd >= 0 && payloadEnd > envelopeEnd) return null
|
||||
val truncated = payloadEnd > frameLen
|
||||
val payloadLen = (if (truncated) frameLen else payloadEnd) - payloadStart
|
||||
if (payloadLen <= 0) return null
|
||||
|
||||
return Result(
|
||||
btpPort = destPort,
|
||||
payload = frame.copyOfRange(payloadStart, payloadStart + payloadLen),
|
||||
hasGeoArea = isGbc,
|
||||
areaLatTenMicroDeg = areaLat,
|
||||
areaLonTenMicroDeg = areaLon,
|
||||
areaDistanceAMeters = areaDist,
|
||||
signedUnverified = signed,
|
||||
truncated = truncated,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The `V2X_RX` body for [result] (the layout [V2xRxFrame.parse] reads and the firmware's
|
||||
* `encode_v2x_rx` writes): `u16 port, i8 rssi, u8 flags (bit 0 GBC area, bit 1 signed), i32 lat,
|
||||
* i32 lon, u16 distance_a, payload`. Null for a truncated message, which must not be forwarded.
|
||||
*/
|
||||
fun toV2xRxBody(result: Result, rssiDbm: Int): ByteArray? {
|
||||
if (result.truncated || result.payload.isEmpty()) return null
|
||||
val out = java.io.ByteArrayOutputStream(V2xRxFrame.PREFIX_SIZE + result.payload.size)
|
||||
fun u8(v: Int) = out.write(v and 0xFF)
|
||||
fun u16(v: Int) { u8(v); u8(v shr 8) }
|
||||
fun i32(v: Int) { u16(v); u16(v shr 16) }
|
||||
u16(result.btpPort)
|
||||
u8(rssiDbm.coerceIn(-128, 127))
|
||||
u8((if (result.hasGeoArea) 0x01 else 0) or (if (result.signedUnverified) 0x02 else 0))
|
||||
i32(result.areaLatTenMicroDeg)
|
||||
i32(result.areaLonTenMicroDeg)
|
||||
u16(result.areaDistanceAMeters)
|
||||
out.write(result.payload)
|
||||
return out.toByteArray()
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.data.transport
|
||||
|
||||
/**
|
||||
* Reassembles fragmented station-link messages (docs/station-link.pdf, "Fragmented messages").
|
||||
*
|
||||
* A body too large for one transport message is split in order, every fragment carrying the same
|
||||
* opcode and sequence and `flags` 1 (first), 2 (middle) or 3 (last). Each fragment's body starts with
|
||||
* `total_length u16` and `body_offset u16`, then the data. The complete body is handed on once the
|
||||
* last fragment brings it to exactly `total_length`.
|
||||
*
|
||||
* Validation follows the spec: gaps, duplicates, wrong order and a changed total drop the stream;
|
||||
* an unfinished stream is discarded after [IDLE_TIMEOUT_MS] of silence; at most [MAX_PENDING] streams
|
||||
* are held; a complete body is at most [MAX_BODY] octets (the largest station-to-host indication).
|
||||
*
|
||||
* One instance per link session (USB and BLE keep separate streams in the spec; the app uses one
|
||||
* transport at a time and starts a new instance when the session restarts).
|
||||
*/
|
||||
class LinkReassembly(private val nowMs: () -> Long = { System.currentTimeMillis() }) {
|
||||
|
||||
private class Stream(val opcode: Int, val sequence: Int, val total: Int, var lastMs: Long) {
|
||||
val bytes = java.io.ByteArrayOutputStream()
|
||||
}
|
||||
|
||||
private val streams = ArrayList<Stream>()
|
||||
|
||||
/** Fragments dropped for any validation reason since this instance was created. */
|
||||
var dropped: Int = 0
|
||||
private set
|
||||
|
||||
/**
|
||||
* Feeds one received message. Returns it unchanged when it is complete (`flags` 0), the
|
||||
* reassembled message (`flags` 0) when [message] was the last fragment, and null otherwise.
|
||||
*/
|
||||
fun feed(message: LinkMessage): LinkMessage? {
|
||||
val now = nowMs()
|
||||
streams.removeAll { now - it.lastMs > IDLE_TIMEOUT_MS }
|
||||
if (message.flags == 0) {
|
||||
// A complete message supersedes any unfinished stream with the same key.
|
||||
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||
return message
|
||||
}
|
||||
val flags = message.flags
|
||||
val body = message.body
|
||||
if (flags > FLAG_LAST || body.size <= FRAGMENT_HEADER) return drop(message)
|
||||
fun u16(i: Int) = (body[i].toInt() and 0xFF) or ((body[i + 1].toInt() and 0xFF) shl 8)
|
||||
val total = u16(0)
|
||||
val offset = u16(2)
|
||||
val length = body.size - FRAGMENT_HEADER
|
||||
if (total == 0 || total > MAX_BODY || offset + length > total) return drop(message)
|
||||
// the last fragment ends exactly at the declared total, and only the last one does
|
||||
if ((flags == FLAG_LAST) != (offset + length == total)) return drop(message)
|
||||
|
||||
var stream = streams.firstOrNull { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||
if (flags == FLAG_FIRST) {
|
||||
if (offset != 0) return drop(message)
|
||||
stream?.let { streams.remove(it) } // a restarted stream replaces the old one
|
||||
if (streams.size >= MAX_PENDING) return drop(message)
|
||||
stream = Stream(message.opcode, message.sequence, total, now)
|
||||
streams.add(stream)
|
||||
} else if (stream == null) {
|
||||
return drop(message) // a middle or last fragment without a first
|
||||
}
|
||||
if (stream.total != total || stream.bytes.size() != offset) {
|
||||
streams.remove(stream) // changed total, a gap or a duplicate
|
||||
return drop(message)
|
||||
}
|
||||
stream.bytes.write(body, FRAGMENT_HEADER, length)
|
||||
stream.lastMs = now
|
||||
if (flags != FLAG_LAST) return null
|
||||
streams.remove(stream)
|
||||
return LinkMessage(message.opcode, message.sequence, stream.bytes.toByteArray(), 0)
|
||||
}
|
||||
|
||||
/** Forgets every unfinished stream (a new session, a reconnect). */
|
||||
fun reset() = streams.clear()
|
||||
|
||||
private fun drop(message: LinkMessage): LinkMessage? {
|
||||
dropped++
|
||||
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||
return null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val FLAG_FIRST = 1
|
||||
const val FLAG_MIDDLE = 2
|
||||
const val FLAG_LAST = 3
|
||||
const val FRAGMENT_HEADER = 4
|
||||
const val IDLE_TIMEOUT_MS = 2_000L
|
||||
const val MAX_PENDING = 8
|
||||
const val MAX_BODY = 65_535
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.data.transport
|
||||
|
||||
/**
|
||||
* Body of the station-link `RAW_FRAME` (0x85, docs/station-link.pdf, "Raw capture"): a debug copy of
|
||||
* a radio frame the station received (or, with the own-transmission option, sent).
|
||||
*
|
||||
* u32 counter, u8 flags (bit 0 own transmission, bit 1 UTC time stamp), i8 rssi,
|
||||
* ITS5 record: "ITS5", u32 seconds, u32 microseconds, u16 frame_length, frame[frame_length]
|
||||
*
|
||||
* The frame is the 802.11 MPDU without its FCS. [GnUnwrap] turns it into the ITS message.
|
||||
*/
|
||||
data class RawFrame(
|
||||
val counter: Long,
|
||||
val ownTransmission: Boolean,
|
||||
/** The record time is UTC (the station's clock was synchronised) rather than time since boot. */
|
||||
val utcTime: Boolean,
|
||||
val rssiDbm: Int,
|
||||
val seconds: Long,
|
||||
val microseconds: Long,
|
||||
val frame: ByteArray,
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean = other is RawFrame && counter == other.counter &&
|
||||
ownTransmission == other.ownTransmission && utcTime == other.utcTime && rssiDbm == other.rssiDbm &&
|
||||
seconds == other.seconds && microseconds == other.microseconds && frame.contentEquals(other.frame)
|
||||
|
||||
override fun hashCode(): Int = 31 * counter.hashCode() + frame.contentHashCode()
|
||||
|
||||
companion object {
|
||||
/** `[counter 4][flags 1][rssi 1]` before the record, `["ITS5" 4][sec 4][usec 4][len 2]` in it. */
|
||||
const val HEADER_SIZE = 6 + 14
|
||||
|
||||
private val MAGIC = byteArrayOf('I'.code.toByte(), 'T'.code.toByte(), 'S'.code.toByte(), '5'.code.toByte())
|
||||
|
||||
/** Returns null for a body that is not a well-formed RAW_FRAME (short, wrong magic, bad length). */
|
||||
fun parse(body: ByteArray): RawFrame? {
|
||||
if (body.size < HEADER_SIZE) return null
|
||||
for (i in 0 until 4) if (body[6 + i] != MAGIC[i]) return null
|
||||
fun u8(i: Int) = body[i].toInt() and 0xFF
|
||||
fun u16(i: Int) = u8(i) or (u8(i + 1) shl 8)
|
||||
fun u32(i: Int) = (u16(i).toLong()) or (u16(i + 2).toLong() shl 16)
|
||||
val length = u16(18)
|
||||
if (body.size != HEADER_SIZE + length) return null
|
||||
val flags = u8(4)
|
||||
return RawFrame(
|
||||
counter = u32(0),
|
||||
ownTransmission = (flags and 0x01) != 0,
|
||||
utcTime = (flags and 0x02) != 0,
|
||||
rssiDbm = body[5].toInt(),
|
||||
seconds = u32(10),
|
||||
microseconds = u32(14),
|
||||
frame = body.copyOfRange(HEADER_SIZE, body.size),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,6 @@ object Crc16CcittFalse {
|
||||
object BtpPort {
|
||||
const val CAM = 2001
|
||||
const val DENM = 2002
|
||||
const val MAPEM = 2003
|
||||
|
||||
/**
|
||||
* Watch the crossover: SPATEM is BTP port **2004** but ItsPduHeader messageID **4**, while
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.hawhamburg.micr0bu.data.transport
|
||||
|
||||
/**
|
||||
* Phone side of the station-link message layer, version 1: the protocol of Niklas Dathe's
|
||||
* Phone side of the station-link message layer, version 1: the protocol of the colleague's
|
||||
* vanetza-idf ESP32-C5 firmware (microbu-esp32c5/station-link/README.md), which obu-firmware runs
|
||||
* since 2026-09-23. Kotlin counterpart of `obu-firmware/main/link_protocol.hpp` and of the
|
||||
* Niklas Dathe's Python `microbu_link/messages.py`; the unit test pins these encoders to bytes that
|
||||
* colleague's Python `microbu_link/messages.py`; the unit test pins these encoders to bytes that
|
||||
* Python module produced.
|
||||
*
|
||||
* Transport independent: over USB each message is the payload of one serial frame of type
|
||||
@@ -12,12 +12,11 @@ package com.hawhamburg.micr0bu.data.transport
|
||||
* message is one GATT value (see [BleLinkTransport]).
|
||||
*
|
||||
* Message: `[opcode:1][flags:1][sequence:2 LE][body]`, at most [LINK_MAX_MESSAGE] octets, all
|
||||
* integers little-endian. The phone numbers its requests; the firmware answers with a CONFIRM
|
||||
* carrying the same sequence (docs/station-link.pdf, obu-firmware/docs). The status snapshot is not
|
||||
* pushed: the phone asks for it with STATUS_REQUEST once a second and finds it in CONFIRM.detail.
|
||||
* integers little-endian. The phone numbers its requests; the firmware answers with a RESULT
|
||||
* carrying the same sequence.
|
||||
*
|
||||
* Only what this app uses is implemented: configure, PoTi, BTP-DATA.request, credential
|
||||
* provisioning, STATUS_REQUEST, CONFIRM, and the MicrOBU extension [LinkOpcode.V2X_RX]. The SF-SAP
|
||||
* provisioning, RESULT, STATUS, and the MicrOBU extension [LinkOpcode.V2X_RX]. The SF-SAP
|
||||
* identifier-change primitives are not used: the app owns its pseudonym (see
|
||||
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager]) and reconfigures the station on a change.
|
||||
*/
|
||||
@@ -32,17 +31,14 @@ object LinkOpcode {
|
||||
const val CREDENTIALS_PROVISION = 0x04
|
||||
const val CREDENTIALS_ERASE = 0x05
|
||||
const val STATUS_REQUEST = 0x0C
|
||||
/** Debug path: body is one mode octet (bit 0 on, bit 1 broadcast only, bit 2 own transmissions); 0 switches it off. */
|
||||
const val RAW_CAPTURE = 0x0D
|
||||
const val CONFIRM = 0x80
|
||||
const val RESULT = 0x80
|
||||
const val BTP_DATA_INDICATION = 0x81
|
||||
/** Raw 802.11 frame copy of the RAW_CAPTURE debug path, fragmented when large: see [RawFrame]. */
|
||||
const val RAW_FRAME = 0x85
|
||||
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
|
||||
const val V2X_RX = 0x90
|
||||
const val STATUS = 0x84
|
||||
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). */
|
||||
const val V2X_RX = 0x85
|
||||
}
|
||||
|
||||
/** CONFIRM result codes: the stack's own first, then the link's. */
|
||||
/** RESULT codes: vanetza_idf::Result first, then the link's own. */
|
||||
object LinkResultCode {
|
||||
const val ACCEPTED = 0
|
||||
const val TIME_REGRESSION = 7
|
||||
@@ -95,40 +91,36 @@ internal class LinkWriter {
|
||||
|
||||
/**
|
||||
* STATION_CONFIGURE body. (Re)creates the GeoNetworking stack and security entity on the micrOBU.
|
||||
*
|
||||
* Without [mid] it is the 6-octet form of docs/station-link.pdf: the GN address derives from the
|
||||
* authorization ticket (signed) or is drawn at random per configuration (unsigned). With [mid], the
|
||||
* pseudonym MAC, it is the 16-octet form (address_configuration 0, AUTO), which the station still
|
||||
* accepts: [mid] becomes both the GN_ADDR MID and the 802.11 source address, signed or not. A ride
|
||||
* sends the rotating pseudonym's MAC, so the link-layer address rotates with the station ID; the bench
|
||||
* CAM pinger sends its fixed MAC. A different [mid] is a different configuration, so the next message
|
||||
* reconfigures the station. Radio mode, traffic class and lifetime are the station's (transmit and
|
||||
* receive, DP2, 1 s).
|
||||
* [mid] is the pseudonym MAC: with [addressConfiguration] 0 (AUTO) it becomes both the GN_ADDR MID
|
||||
* and the 802.11 source address, as with the old CAM_TX_PV prefix.
|
||||
*/
|
||||
data class StationConfigure(
|
||||
val stationType: Int,
|
||||
val mid: ByteArray,
|
||||
val security: Int = 1,
|
||||
val addressConfiguration: Int = 0,
|
||||
val beaconing: Int = 0,
|
||||
val channelNumber: Int = 180,
|
||||
val transmitPowerDbm: Int = 20,
|
||||
val mid: ByteArray? = null,
|
||||
/** 0 off, 1 receive only, 2 transmit and receive. */
|
||||
val radio: Int = 2,
|
||||
/** Raw GN traffic class octet: TC-ID 2, as the previous firmware's geonet.c. */
|
||||
val defaultTrafficClass: Int = 2,
|
||||
/** Raw GN lifetime octet: 1 s. */
|
||||
val defaultLifetime: Int = 0x05,
|
||||
) {
|
||||
init { require(mid == null || mid.size == 6) }
|
||||
init { require(mid.size == 6) }
|
||||
|
||||
fun encode(): ByteArray = if (mid == null) {
|
||||
LinkWriter().u8(stationType).u16(channelNumber).u8(transmitPowerDbm).u8(security).u8(beaconing)
|
||||
.toByteArray()
|
||||
} else {
|
||||
LinkWriter().u8(stationType).u8(security).u8(0).bytes(mid).u8(beaconing)
|
||||
.u16(channelNumber).u8(transmitPowerDbm).u8(2).u8(2).u8(0x05)
|
||||
.toByteArray()
|
||||
}
|
||||
fun encode(): ByteArray = LinkWriter()
|
||||
.u8(stationType).u8(security).u8(addressConfiguration).bytes(mid).u8(beaconing)
|
||||
.u16(channelNumber).u8(transmitPowerDbm).u8(radio).u8(defaultTrafficClass).u8(defaultLifetime)
|
||||
.toByteArray()
|
||||
|
||||
override fun equals(other: Any?): Boolean = other is StationConfigure && encode().contentEquals(other.encode())
|
||||
override fun hashCode(): Int = encode().contentHashCode()
|
||||
}
|
||||
|
||||
/** CONFIRM detail of STATION_CONFIGURE. */
|
||||
/** RESULT detail of STATION_CONFIGURE. */
|
||||
data class StationInfo(val credentialsLoaded: Boolean, val tickets: Int) {
|
||||
companion object {
|
||||
fun decode(detail: ByteArray): StationInfo? =
|
||||
@@ -220,11 +212,7 @@ data class LinkResult(val code: Int, val detail: ByteArray) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Status snapshot, the CONFIRM.detail of STATUS_REQUEST (131 octets, docs/station-link.pdf). Counters
|
||||
* are since the last configure. The board reports only the cell voltage ([batteryMv]); the warning
|
||||
* and shutdown thresholds below mirror obu-firmware's Kconfig defaults (3.50 V and 3.30 V).
|
||||
*/
|
||||
/** STATUS body (103 octets), sent by the micrOBU every second. Counters are since the last configure. */
|
||||
data class StationStatus(
|
||||
val uptimeMs: Long,
|
||||
val configured: Boolean,
|
||||
@@ -247,16 +235,7 @@ data class StationStatus(
|
||||
val linkMalformed: Long,
|
||||
val potiUpdates: Long,
|
||||
val itsTimeMs: Long,
|
||||
/** Cell voltage in millivolts; 0 when the board does not report one (older firmware, no cell, no sensor). */
|
||||
val batteryMv: Int = 0,
|
||||
) {
|
||||
/** The cell is below the warning threshold. */
|
||||
val batteryLow: Boolean get() = batteryMv > 0 && batteryMv < BATTERY_WARN_MV
|
||||
/** The cell is below the shutdown threshold: the board powers down unless this phone keeps it on USB. */
|
||||
val batteryCritical: Boolean get() = batteryMv > 0 && batteryMv < BATTERY_SHUTDOWN_MV
|
||||
/** Rough charge of a LiPo cell from its voltage, or null when not measured. An indicator, not a fuel gauge. */
|
||||
val batteryPercent: Int? get() = if (batteryMv > 0) lipoPercent(batteryMv) else null
|
||||
|
||||
/** Signing refusals of every kind: no usable ticket, a pending id change, or a missing permission. */
|
||||
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
|
||||
|
||||
@@ -265,33 +244,10 @@ data class StationStatus(
|
||||
override fun hashCode(): Int = toString().hashCode()
|
||||
|
||||
companion object {
|
||||
/** Octets of the status snapshot. */
|
||||
const val SIZE = 131
|
||||
const val BATTERY_WARN_MV = 3500
|
||||
const val BATTERY_SHUTDOWN_MV = 3300
|
||||
const val SIZE = 103
|
||||
|
||||
/** Open-circuit voltage (mV) to charge (%) of a single LiPo cell, interpolated linearly. */
|
||||
private val LIPO_CURVE = arrayOf(
|
||||
3300 to 0, 3500 to 5, 3690 to 10, 3730 to 20, 3770 to 30, 3800 to 40,
|
||||
3840 to 50, 3870 to 60, 3950 to 70, 4020 to 80, 4110 to 90, 4200 to 100,
|
||||
)
|
||||
|
||||
fun lipoPercent(millivolts: Int): Int {
|
||||
if (millivolts <= LIPO_CURVE.first().first) return 0
|
||||
if (millivolts >= LIPO_CURVE.last().first) return 100
|
||||
for (i in 1 until LIPO_CURVE.size) {
|
||||
val (v1, p1) = LIPO_CURVE[i]
|
||||
if (millivolts <= v1) {
|
||||
val (v0, p0) = LIPO_CURVE[i - 1]
|
||||
return p0 + (p1 - p0) * (millivolts - v0) / (v1 - v0)
|
||||
}
|
||||
}
|
||||
return 100
|
||||
}
|
||||
|
||||
/** Accepts the 131-octet snapshot and any longer one (later fields are appended); shorter is malformed. */
|
||||
fun decode(body: ByteArray): StationStatus? {
|
||||
if (body.size < SIZE) return null
|
||||
if (body.size != SIZE) return null
|
||||
fun u8(i: Int) = body[i].toInt() and 0xFF
|
||||
fun u32(i: Int) = (0 until 4).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
|
||||
fun u64(i: Int) = (0 until 8).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
|
||||
@@ -312,8 +268,6 @@ data class StationStatus(
|
||||
// c + 56: link_rx_frames
|
||||
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
|
||||
itsTimeMs = u64(95),
|
||||
// [103] cbr, dcc, heap and temperature fields the app does not use; [129] battery_mv u16
|
||||
batteryMv = u8(129) or (u8(130) shl 8),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,11 +144,8 @@ object CamUperCodec {
|
||||
bw.putBits(0, 1) // extension bit: value is in the root list
|
||||
bw.putBits(2, 2) // curvatureCalculationMode: unavailable(2)
|
||||
|
||||
// YawRateValue is positive to the LEFT (degSec-000-01ToLeft(1), TS 102 894-2), the opposite
|
||||
// of Cam.yawRateDps (positive clockwise, i.e. to the right). Until 2026-11-18 neither side
|
||||
// negated, so every CAM this phone sent turned the wrong way for a standard receiver.
|
||||
val yawRateCentiDegS = cam.yawRateDps
|
||||
?.let { (-it * 100.0).roundToInt().coerceIn(-32766, 32766) }
|
||||
?.let { (it * 100.0).roundToInt().coerceIn(-32766, 32766) }
|
||||
?: YAW_RATE_UNAVAILABLE
|
||||
bw.putBits(yawRateCentiDegS - (-32766), 16)
|
||||
// YawRateConfidence has NINE enumerands (degSec-000-01(0) .. unavailable(8), see
|
||||
@@ -309,8 +306,7 @@ object CamUperCodec {
|
||||
|
||||
val yawRateRaw = br.getBitsInt(16) + (-32766)
|
||||
br.getBits(4) // yawRateConfidence: 9 enumerands -> 4 bits, see the note in encode()
|
||||
// Left-positive on air, clockwise-positive in Cam: negate, as encode() does.
|
||||
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else -yawRateRaw / 100.0
|
||||
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else yawRateRaw / 100.0
|
||||
|
||||
// Everything after yawRate is deliberately left unread: the 7 optional high-frequency
|
||||
// fields, then lowFrequencyContainer (vehicleRole / exteriorLights / pathHistory), then
|
||||
|
||||
@@ -42,6 +42,9 @@ object DenmUperCodec {
|
||||
private const val MESSAGE_ID_DENM = 1
|
||||
private const val PROTOCOL_VERSION = 2
|
||||
|
||||
/** TimestampIts epoch: 2004-01-01T00:00:00Z in Unix epoch milliseconds. */
|
||||
private const val TS_ITS_EPOCH_MS = 1_072_915_200_000L
|
||||
|
||||
/**
|
||||
* Decodes a UPER DENM into a [DenmEvent].
|
||||
*
|
||||
@@ -144,8 +147,7 @@ object DenmUperCodec {
|
||||
// on it; if any of it is ever needed, the unparsed optionals must be consumed in order
|
||||
// first or every later read lands at the wrong bit offset.
|
||||
|
||||
// TimestampIts is TAI-based: back to UTC through the one conversion the transmit side uses.
|
||||
val detectionTimeMs = ItsTime.epochMs(detectionTimeIts)
|
||||
val detectionTimeMs = detectionTimeIts + TS_ITS_EPOCH_MS
|
||||
|
||||
return DenmEvent(
|
||||
stationId = originatingStationId,
|
||||
|
||||
@@ -1,65 +1,30 @@
|
||||
package com.hawhamburg.micr0bu.domain.asn1
|
||||
|
||||
/**
|
||||
* ITS time, as used by every timestamp this app puts on the air or reads from it.
|
||||
* ITS time, as used by every timestamp this app puts on the air.
|
||||
*
|
||||
* TimestampIts (ETSI TS 102 894-2 V2.5.1) is "the number of elapsed (TAI) milliseconds since the ITS
|
||||
* Epoch", 2004-01-01T00:00:00.000 UTC, counted without interruption, so it is not altered by the leap
|
||||
* seconds UTC inserts. It therefore runs ahead of UTC by the leap seconds inserted since 2004: 5 s since
|
||||
* 2017-01-01 (the standard's own example: 2007-01-01T00:00:00.000 UTC is 94 694 401 000 ms, one leap
|
||||
* second included). Three fields in a single transmitted frame come from it: the CAM's and VAM's
|
||||
* generationDeltaTime (modulo 65536), the GeoNetworking Source Position Vector's TST (modulo 2^32) and,
|
||||
* on the station-link path, the PoTi timestamp that sets the micrOBU's ITS clock, which the security
|
||||
* entity stamps into every signature's generationTime and checks received messages against. A receiver
|
||||
* compares them with its own TAI clock, so they all go through here and cannot drift apart.
|
||||
*
|
||||
* Until 2026-10 this was Unix time minus the epoch, without the leap seconds: the micrOBU's clock ran
|
||||
* 5 s behind, so it rejected correctly timed VAMs from other stations as Invalid_Timestamp and restarted
|
||||
* its stack whenever another source (the PC tools, which add the leap seconds) had set it correctly.
|
||||
* TimestampIts (ETSI TS 102 894-2) counts milliseconds from 2004-01-01T00:00:00Z. Two fields in a
|
||||
* single transmitted frame come from it: the CAM's generationDeltaTime (modulo 65536) and the
|
||||
* GeoNetworking Source Position Vector's TST (modulo 2^32). A receiver can compare the two, so
|
||||
* they must follow one rule. Both go through here so they cannot drift apart.
|
||||
*
|
||||
* **Which clock.** The input should be GNSS time, not the phone's wall clock. A phone with no SIM
|
||||
* and no internet time has no automatic time source at all, and the bench phone was found 24
|
||||
* minutes fast that way. `GnssTimeSource` moves a timestamp onto GNSS time, using [onGnssTime],
|
||||
* before it gets here. Android reports GNSS time as UTC (Unix epoch ms), so the leap seconds are
|
||||
* added here, not there.
|
||||
* before it gets here.
|
||||
*
|
||||
* **Open question: leap seconds.** This is Unix time minus the 2004 epoch, with no leap-second
|
||||
* term. If TimestampIts is read as TAI-based, the correct value is currently 5 s higher, for the
|
||||
* five leap seconds inserted since 2004. Whichever reading turns out right, it is changed here and
|
||||
* nowhere else. Settling it needs a frame from a third-party stack with a trusted clock, such as
|
||||
* the RSU's CAM compared against GNSS time, and no such traffic was on air when this was written.
|
||||
*/
|
||||
object ItsTime {
|
||||
/** 2004-01-01T00:00:00Z in Unix epoch milliseconds. */
|
||||
const val EPOCH_MS = 1_072_915_200_000L
|
||||
|
||||
/**
|
||||
* Unix epoch ms (UTC) from which each leap second inserted after the ITS epoch counts, from IERS via
|
||||
* the IANA leap-seconds.list (TAI-UTC 32 s at the epoch, 37 s since 2017-01-01; the file of
|
||||
* 2026-07 announces none before its expiry on 2027-06-28). A new leap second is added here when
|
||||
* IERS Bulletin C announces one.
|
||||
*/
|
||||
private val LEAP_SECONDS_FROM_MS = longArrayOf(
|
||||
1_136_073_600_000L, // 2006-01-01
|
||||
1_230_768_000_000L, // 2009-01-01
|
||||
1_341_100_800_000L, // 2012-07-01
|
||||
1_435_708_800_000L, // 2015-07-01
|
||||
1_483_228_800_000L, // 2017-01-01
|
||||
)
|
||||
|
||||
/** Leap seconds inserted between the ITS epoch and the UTC instant [epochMs]. */
|
||||
fun leapSecondsAt(epochMs: Long): Int = LEAP_SECONDS_FROM_MS.count { epochMs >= it }
|
||||
|
||||
/** TimestampIts for the UTC instant [epochMs] (Unix epoch ms), before any modulo is applied. */
|
||||
fun timestampIts(epochMs: Long): Long = epochMs - EPOCH_MS + 1_000L * leapSecondsAt(epochMs)
|
||||
|
||||
/**
|
||||
* The UTC instant (Unix epoch ms) of [timestampIts], the inverse of [timestampIts]. During an
|
||||
* inserted leap second, which UTC cannot name, the first millisecond after it is returned.
|
||||
*/
|
||||
fun epochMs(timestampIts: Long): Long {
|
||||
var leaps = 0
|
||||
for ((index, from) in LEAP_SECONDS_FROM_MS.withIndex()) {
|
||||
val itsAtFrom = timestampIts(from) // first TimestampIts after leap second index + 1
|
||||
if (timestampIts >= itsAtFrom) leaps = index + 1
|
||||
else if (timestampIts >= itsAtFrom - 1_000L) return from // inside the inserted second
|
||||
}
|
||||
return timestampIts + EPOCH_MS - 1_000L * leaps
|
||||
}
|
||||
/** TimestampIts for wall-clock [epochMs], before any modulo is applied. */
|
||||
fun timestampIts(epochMs: Long): Long = epochMs - EPOCH_MS
|
||||
|
||||
/**
|
||||
* Moves [systemMs], a reading of this phone's wall clock, onto GNSS time, using one pair of
|
||||
|
||||
@@ -1,298 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.domain.asn1
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneConnection
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneNode
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneType
|
||||
import com.hawhamburg.micr0bu.domain.map.MapEvent
|
||||
import com.hawhamburg.micr0bu.domain.map.MapLane
|
||||
import com.hawhamburg.micr0bu.domain.map.Maneuvers
|
||||
import com.hawhamburg.micr0bu.domain.map.NodeOffset
|
||||
import com.hawhamburg.micr0bu.domain.map.SpeedLimit
|
||||
|
||||
/**
|
||||
* ASN.1 UPER **decoder** for MAPEM (ETSI TS 103 301 / SAE J2735 DSRC `MapData`), for messages
|
||||
* received over the air on the ESP32-C5 path and from the CiT One's `v2x/rx/mapem` topic.
|
||||
*
|
||||
* Decode-only, like [SpatemUperCodec]: MAPEM is an RSU's message.
|
||||
*
|
||||
* ## Field widths
|
||||
* From the ETSI modules in `asn1/` (`mapem_2_2_1.asn`, `dsrc_2_2_1.asn`, `cdd_2_2_1.asn`):
|
||||
*
|
||||
* - `Latitude` (-900000000..900000001) = 31 bits, `Longitude` (-1800000000..1800000001) = 32
|
||||
* - `Elevation` (-4096..61439) = 16, `LaneWidth` (0..32767) = 15, `Velocity` (0..8191) = 13
|
||||
* - `MsgCount` = 7, `LaneID` / `SignalGroupID` / `LaneConnectionID` / `RestrictionClassID` = 8,
|
||||
* `ApproachID` = 4, `IntersectionID` / `RoadRegulatorID` = 16, `LayerID` (0..100) = 7
|
||||
* - `Offset-B10..B16` = 10, 11, 12, 13, 14, 16 bits (offset by -2^(n-1)), the six XY node sizes
|
||||
* - `DescriptiveName` IA5String (SIZE(1..63)): 6-bit length, then 7 bits per character
|
||||
* - BIT STRINGs of fixed size are just their bits: `LaneDirection` 2, `LaneSharing` 10,
|
||||
* `AllowedManeuvers` 12, the lane-type attributes 16, except `LaneAttributes-Vehicle`, which is
|
||||
* `SIZE (8,...)` and so has an extension bit before its 8 bits
|
||||
* - Extensible ENUMERATEDs are an extension bit plus the root index: `LayerType` 3,
|
||||
* `SpeedLimitType` 4, `NodeAttributeXY` 4, `SegmentAttributeXY` (38 values) 6
|
||||
* - `SEQUENCE (SIZE(lo..hi)) OF` counts are `n-lo` in ceil(log2(hi-lo+1)) bits: intersections 5,
|
||||
* lanes 8, nodes (2..63) 6, connections 4, speed limits 4, node/segment attributes 3, overlays 3
|
||||
*
|
||||
* Traps, each of which silently shifts everything after it:
|
||||
* - `LaneAttributes`, `Connection`, `ConnectingLane`, `IntersectionReferenceID` and
|
||||
* `RegulatorySpeedLimit` are NOT extensible: no extension bit, unlike the SEQUENCEs around them.
|
||||
* - `NodeOffsetPointXY` is a non-extensible CHOICE of 8 (3 bits), but `NodeListXY` and
|
||||
* `LaneTypeAttributes` are extensible CHOICEs (extension bit first).
|
||||
* - A lane's nodes start at the stop line and run outward, so an ingress lane is driven from its
|
||||
* last node toward its first.
|
||||
*
|
||||
* ## Verification
|
||||
* `MapemUperCodecTest` decodes every distinct MAPEM on record (17 from the 2026-03-18 drive, out of
|
||||
* 7 916 received, 288 to 1348 bytes, plus the bench RSU's) and compares every decoded field with
|
||||
* `asn1tools` decoding the same bytes against those modules.
|
||||
*
|
||||
* Returns null rather than guessing on an extension, a regional extension, a computed lane, or
|
||||
* preempt priority data. A dropped MAPEM costs nothing - the next comes within a second - while a
|
||||
* misread one would put a signal on the wrong lane.
|
||||
*/
|
||||
object MapemUperCodec {
|
||||
|
||||
private const val MESSAGE_ID_MAPEM = 5
|
||||
private const val PROTOCOL_VERSION = 2
|
||||
|
||||
fun decode(bytes: ByteArray, receivedAtEpochMs: Long, rssiDbm: Int? = null): MapEvent? = try {
|
||||
decodeOrNull(BitReader(bytes), receivedAtEpochMs, rssiDbm)
|
||||
} catch (e: IndexOutOfBoundsException) {
|
||||
null // truncated
|
||||
}
|
||||
|
||||
private fun decodeOrNull(br: BitReader, receivedAtEpochMs: Long, rssiDbm: Int?): MapEvent? {
|
||||
// ---- ItsPduHeader ----
|
||||
if (br.getBitsInt(8) != PROTOCOL_VERSION) return null
|
||||
if (br.getBitsInt(8) != MESSAGE_ID_MAPEM) return null
|
||||
val stationId = br.getBits(32)
|
||||
|
||||
// ---- MapData: extension bit + 8 optionals ----
|
||||
if (br.bit()) return null
|
||||
val hasTimeStamp = br.bit()
|
||||
val hasLayerType = br.bit()
|
||||
val hasLayerId = br.bit()
|
||||
val hasIntersections = br.bit()
|
||||
br.getBits(4) // roadSegments, dataParameters, restrictionList, regional: after intersections
|
||||
if (hasTimeStamp) br.getBits(20)
|
||||
val revision = br.getBitsInt(7)
|
||||
if (hasLayerType && !br.enumerated(3)) return null
|
||||
if (hasLayerId) br.getBits(7)
|
||||
if (!hasIntersections) return null // road segments only: nothing to join a SPATEM to
|
||||
|
||||
val count = br.getBitsInt(5) + 1
|
||||
val intersections = ArrayList<IntersectionGeometry>(count)
|
||||
repeat(count) { intersections.add(readIntersection(br) ?: return null) }
|
||||
// What follows the intersections is not needed and nothing after it is read, so it is not
|
||||
// walked either.
|
||||
return MapEvent(stationId, revision, intersections, rssiDbm, receivedAtEpochMs)
|
||||
}
|
||||
|
||||
private fun readIntersection(br: BitReader): IntersectionGeometry? {
|
||||
if (br.bit()) return null
|
||||
val hasName = br.bit()
|
||||
val hasLaneWidth = br.bit()
|
||||
val hasSpeedLimits = br.bit()
|
||||
val hasPreempt = br.bit()
|
||||
val hasRegional = br.bit()
|
||||
|
||||
val name = if (hasName) br.name() else null
|
||||
val hasRegion = br.bit() // IntersectionReferenceID: not extensible
|
||||
val region = if (hasRegion) br.getBitsInt(16) else null
|
||||
val id = br.getBitsInt(16)
|
||||
val revision = br.getBitsInt(7)
|
||||
|
||||
// Position3D: extensible, elevation + regional optional
|
||||
if (br.bit()) return null
|
||||
val hasElevation = br.bit()
|
||||
if (br.bit()) return null // Position3D.regional
|
||||
val lat = br.getBits(31) - 900_000_000L
|
||||
val lon = br.getBits(32) - 1_800_000_000L
|
||||
val elevation = if (hasElevation) br.getBitsInt(16) - 4096 else null
|
||||
|
||||
val laneWidth = if (hasLaneWidth) br.getBitsInt(15) else null
|
||||
val speedLimits = if (hasSpeedLimits) br.speedLimits() ?: return null else emptyList()
|
||||
|
||||
val laneCount = br.getBitsInt(8) + 1
|
||||
val lanes = ArrayList<MapLane>(laneCount)
|
||||
repeat(laneCount) { lanes.add(readLane(br) ?: return null) }
|
||||
if (hasPreempt || hasRegional) return null
|
||||
|
||||
return IntersectionGeometry(
|
||||
region = region, id = id, revision = revision, name = name,
|
||||
refLatitude = lat / 1e7, refLongitude = lon / 1e7, elevationDm = elevation,
|
||||
laneWidthCm = laneWidth, speedLimits = speedLimits, lanes = lanes,
|
||||
)
|
||||
}
|
||||
|
||||
private fun readLane(br: BitReader): MapLane? {
|
||||
if (br.bit()) return null
|
||||
val hasName = br.bit()
|
||||
val hasIngress = br.bit()
|
||||
val hasEgress = br.bit()
|
||||
val hasManeuvers = br.bit()
|
||||
val hasConnects = br.bit()
|
||||
val hasOverlays = br.bit()
|
||||
val hasRegional = br.bit()
|
||||
|
||||
val laneId = br.getBitsInt(8)
|
||||
val name = if (hasName) br.name() else null
|
||||
val ingress = if (hasIngress) br.getBitsInt(4) else null
|
||||
val egress = if (hasEgress) br.getBitsInt(4) else null
|
||||
|
||||
// LaneAttributes: NOT extensible, regional optional
|
||||
val hasAttrRegional = br.bit()
|
||||
val direction = br.getBitsInt(2)
|
||||
val sharedWith = br.getBitsInt(10)
|
||||
if (br.bit()) return null // LaneTypeAttributes extension
|
||||
val type = LaneType.entries[br.getBitsInt(3)]
|
||||
val typeAttributes = if (type == LaneType.VEHICLE) {
|
||||
if (br.bit()) return null // LaneAttributes-Vehicle SIZE(8,...) extension
|
||||
br.getBitsInt(8)
|
||||
} else {
|
||||
br.getBitsInt(16)
|
||||
}
|
||||
if (hasAttrRegional) return null
|
||||
|
||||
val maneuvers = if (hasManeuvers) Maneuvers(br.getBitsInt(12)) else null
|
||||
|
||||
// NodeListXY: extensible CHOICE { nodes, computed }
|
||||
if (br.bit()) return null
|
||||
if (br.getBitsInt(1) != 0) return null // ComputedLane
|
||||
val nodeCount = br.getBitsInt(6) + 2
|
||||
val nodes = ArrayList<LaneNode>(nodeCount)
|
||||
repeat(nodeCount) { nodes.add(readNode(br) ?: return null) }
|
||||
|
||||
val connections = if (hasConnects) {
|
||||
List(br.getBitsInt(4) + 1) { readConnection(br) }
|
||||
} else emptyList()
|
||||
val overlays = if (hasOverlays) List(br.getBitsInt(3) + 1) { br.getBitsInt(8) } else emptyList()
|
||||
if (hasRegional) return null
|
||||
|
||||
return MapLane(
|
||||
laneId = laneId, name = name, ingressApproach = ingress, egressApproach = egress,
|
||||
isIngress = direction and 0b10 != 0, isEgress = direction and 0b01 != 0,
|
||||
sharedWith = sharedWith, type = type, typeAttributes = typeAttributes,
|
||||
maneuvers = maneuvers, nodes = nodes, connections = connections, overlays = overlays,
|
||||
)
|
||||
}
|
||||
|
||||
private fun readNode(br: BitReader): LaneNode? {
|
||||
if (br.bit()) return null // NodeXY extension
|
||||
val hasAttributes = br.bit()
|
||||
val offset = when (br.getBitsInt(3)) {
|
||||
0 -> br.xy(10)
|
||||
1 -> br.xy(11)
|
||||
2 -> br.xy(12)
|
||||
3 -> br.xy(13)
|
||||
4 -> br.xy(14)
|
||||
5 -> br.xy(16)
|
||||
6 -> {
|
||||
val lon = br.getBits(32) - 1_800_000_000L
|
||||
val lat = br.getBits(31) - 900_000_000L
|
||||
NodeOffset.LatLon(latitude = lat.toInt(), longitude = lon.toInt())
|
||||
}
|
||||
else -> return null // regional
|
||||
}
|
||||
if (!hasAttributes) return LaneNode(offset)
|
||||
|
||||
// NodeAttributeSetXY: extensible, 7 optionals
|
||||
if (br.bit()) return null
|
||||
val hasLocal = br.bit()
|
||||
val hasDisabled = br.bit()
|
||||
val hasEnabled = br.bit()
|
||||
val hasData = br.bit()
|
||||
val hasDWidth = br.bit()
|
||||
val hasDElevation = br.bit()
|
||||
val hasRegional = br.bit()
|
||||
val local = if (hasLocal) br.enumList(4) ?: return null else emptyList()
|
||||
val disabled = if (hasDisabled) br.enumList(6) ?: return null else emptyList()
|
||||
val enabled = if (hasEnabled) br.enumList(6) ?: return null else emptyList()
|
||||
if (hasData && !br.skipLaneDataAttributes()) return null
|
||||
val dWidth = if (hasDWidth) br.getBitsInt(10) - 512 else null
|
||||
val dElevation = if (hasDElevation) br.getBitsInt(10) - 512 else null
|
||||
if (hasRegional) return null
|
||||
return LaneNode(offset, local, disabled, enabled, dWidth, dElevation)
|
||||
}
|
||||
|
||||
private fun readConnection(br: BitReader): LaneConnection {
|
||||
// Connection and ConnectingLane: neither is extensible
|
||||
val hasRemote = br.bit()
|
||||
val hasSignalGroup = br.bit()
|
||||
val hasUserClass = br.bit()
|
||||
val hasConnectionId = br.bit()
|
||||
val hasManeuver = br.bit()
|
||||
val toLane = br.getBitsInt(8)
|
||||
val maneuver = if (hasManeuver) Maneuvers(br.getBitsInt(12)) else null
|
||||
var remoteRegion: Int? = null
|
||||
var remoteId: Int? = null
|
||||
if (hasRemote) {
|
||||
if (br.bit()) remoteRegion = br.getBitsInt(16)
|
||||
remoteId = br.getBitsInt(16)
|
||||
}
|
||||
return LaneConnection(
|
||||
toLane = toLane, maneuver = maneuver, remoteRegion = remoteRegion, remoteIntersection = remoteId,
|
||||
signalGroup = if (hasSignalGroup) br.getBitsInt(8) else null,
|
||||
userClass = if (hasUserClass) br.getBitsInt(8) else null,
|
||||
connectionId = if (hasConnectionId) br.getBitsInt(8) else null,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- primitives ----
|
||||
|
||||
private fun BitReader.bit(): Boolean = getBitsInt(1) == 1
|
||||
|
||||
private fun BitReader.xy(bits: Int): NodeOffset.Xy {
|
||||
val half = 1 shl (bits - 1)
|
||||
val x = getBitsInt(bits) - half
|
||||
val y = getBitsInt(bits) - half
|
||||
return NodeOffset.Xy(x, y)
|
||||
}
|
||||
|
||||
/** DescriptiveName: IA5String (SIZE(1..63)). */
|
||||
private fun BitReader.name(): String {
|
||||
val length = getBitsInt(6) + 1
|
||||
return String(CharArray(length) { getBitsInt(7).toChar() })
|
||||
}
|
||||
|
||||
/** Reads an extensible ENUMERATED; false (value unusable) if it is an extension value. */
|
||||
private fun BitReader.enumerated(rootBits: Int): Boolean {
|
||||
if (bit()) return false
|
||||
getBits(rootBits)
|
||||
return true
|
||||
}
|
||||
|
||||
/** SEQUENCE (SIZE(1..8)) OF an extensible ENUMERATED with [rootBits]-bit root indices. */
|
||||
private fun BitReader.enumList(rootBits: Int): List<Int>? =
|
||||
List(getBitsInt(3) + 1) {
|
||||
if (bit()) return null
|
||||
getBitsInt(rootBits)
|
||||
}
|
||||
|
||||
/** SpeedLimitList ::= SEQUENCE (SIZE(1..9)) OF RegulatorySpeedLimit (not extensible). */
|
||||
private fun BitReader.speedLimits(): List<SpeedLimit>? =
|
||||
List(getBitsInt(4) + 1) {
|
||||
if (bit()) return null // SpeedLimitType extension value
|
||||
val type = getBitsInt(4)
|
||||
SpeedLimit(type, getBitsInt(13))
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks a LaneDataAttributeList: SEQUENCE (SIZE(1..8)) OF an extensible CHOICE of 7. Nothing
|
||||
* here uses its content (none of the recorded MAPEMs carry one), but it sits between fields
|
||||
* that are used.
|
||||
*/
|
||||
private fun BitReader.skipLaneDataAttributes(): Boolean {
|
||||
repeat(getBitsInt(3) + 1) {
|
||||
if (bit()) return false
|
||||
when (getBitsInt(3)) {
|
||||
0 -> getBits(9) // pathEndPointAngle DeltaAngle (-150..150)
|
||||
1, 2, 3 -> getBits(8) // laneCrownPoint* RoadwayCrownAngle (-128..127)
|
||||
4 -> getBits(9) // laneAngle MergeDivergeNodeAngle (-180..180)
|
||||
5 -> if (speedLimits() == null) return false
|
||||
else -> return false // regional
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -28,10 +28,6 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
|
||||
* A `SEQUENCE (SIZE(lo..hi)) OF` writes its count in `ceil(log2(hi-lo+1))` bits holding `n-lo`:
|
||||
* intersections 1..32 gives 5 bits, movements 1..255 gives 8, events 1..16 gives 4.
|
||||
*
|
||||
* Names and advisory speeds are walked, not kept: a road RSU (Hamburg, 2026-11-23: 888-byte SPATEMs naming
|
||||
* "Berliner Tor / Kolbergstrasse" and each movement, with a greenwave and an ecoDrive advice per event) sends
|
||||
* both, and until then every one of its SPATEMs was refused.
|
||||
*
|
||||
* Two traps worth naming, both of which silently shift every later field:
|
||||
* - `TimeChangeDetails` is **not** extensible, so it has 5 optional bits and no extension bit,
|
||||
* unlike almost every other SEQUENCE here, which all carry one.
|
||||
@@ -45,7 +41,7 @@ import com.hawhamburg.micr0bu.domain.spat.SpatEvent
|
||||
* exactly, with no message hitting an unsupported branch.
|
||||
*
|
||||
* Returns null rather than guessing whenever an extension bit is set or an unsupported optional
|
||||
* (regional extensions) appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
|
||||
* appears: a dropped SPATEM is recoverable (they repeat at ~2 Hz), a misread one shows a driver
|
||||
* the wrong light.
|
||||
*/
|
||||
object SpatemUperCodec {
|
||||
@@ -77,7 +73,9 @@ object SpatemUperCodec {
|
||||
val hasName = br.getBitsInt(1) == 1
|
||||
val hasRegional = br.getBitsInt(1) == 1
|
||||
val minuteOfYear = if (hasTimeStamp) br.getBitsInt(20) else null
|
||||
if (hasName) skipName(br)
|
||||
// DescriptiveName is a variable-length IA5String. Nothing in 79k real messages uses it,
|
||||
// and guessing its length would desynchronise everything after it.
|
||||
if (hasName) return null
|
||||
|
||||
val intersectionCount = br.getBitsInt(5) + 1
|
||||
if (intersectionCount > MAX_INTERSECTIONS) return null
|
||||
@@ -104,7 +102,7 @@ object SpatemUperCodec {
|
||||
val hasEnabledLanes = br.getBitsInt(1) == 1
|
||||
val hasManeuvers = br.getBitsInt(1) == 1
|
||||
val hasRegional = br.getBitsInt(1) == 1
|
||||
if (hasName) skipName(br)
|
||||
if (hasName) return null
|
||||
|
||||
// IntersectionReferenceID - not extensible, one optional bit for region.
|
||||
val region = if (br.getBitsInt(1) == 1) br.getBitsInt(16) else null
|
||||
@@ -135,7 +133,7 @@ object SpatemUperCodec {
|
||||
val hasName = br.getBitsInt(1) == 1
|
||||
val hasManeuvers = br.getBitsInt(1) == 1
|
||||
val hasRegional = br.getBitsInt(1) == 1
|
||||
if (hasName) skipName(br)
|
||||
if (hasName) return null
|
||||
|
||||
val signalGroup = br.getBitsInt(8)
|
||||
val eventCount = br.getBitsInt(4) + 1
|
||||
@@ -164,8 +162,7 @@ object SpatemUperCodec {
|
||||
if (hasConfidence) br.getBits(4)
|
||||
if (hasNext) br.getBits(16)
|
||||
}
|
||||
if (hasSpeeds && !skipAdvisorySpeedList(br)) return null
|
||||
if (hasRegionalEvent) return null
|
||||
if (hasSpeeds || hasRegionalEvent) return null
|
||||
events.add(SignalPhaseEvent(phase, minEnd, maxEnd, likely))
|
||||
}
|
||||
|
||||
@@ -174,41 +171,6 @@ object SpatemUperCodec {
|
||||
return SignalMovement(signalGroup, events)
|
||||
}
|
||||
|
||||
/**
|
||||
* `DescriptiveName` IA5String (SIZE(1..63)): 6-bit length holding n-1, then 7 bits per character.
|
||||
* Not surfaced (a real RSU names its intersections and movements, the app does not show them here), but
|
||||
* it has to be walked: it sits in front of fields that are.
|
||||
*/
|
||||
private fun skipName(br: BitReader) {
|
||||
val length = br.getBitsInt(6) + 1
|
||||
repeat(length) { br.getBits(7) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks an `AdvisorySpeedList` (SIZE(1..16) OF AdvisorySpeed: the RSU's green wave and eco-drive advice)
|
||||
* without keeping it; nothing consumes it yet. AdvisorySpeed is extensible with five optional fields
|
||||
* (speed, confidence, distance, class, regional); `type` is an extensible ENUMERATED of four values.
|
||||
* Returns false for an extension value or a regional extension, which this decoder cannot size.
|
||||
*/
|
||||
private fun skipAdvisorySpeedList(br: BitReader): Boolean {
|
||||
repeat(br.getBitsInt(4) + 1) {
|
||||
if (br.getBitsInt(1) != 0) return false // AdvisorySpeed extension
|
||||
val hasSpeed = br.getBitsInt(1) == 1
|
||||
val hasConfidence = br.getBitsInt(1) == 1
|
||||
val hasDistance = br.getBitsInt(1) == 1
|
||||
val hasClass = br.getBitsInt(1) == 1
|
||||
val hasRegional = br.getBitsInt(1) == 1
|
||||
if (br.getBitsInt(1) != 0) return false // AdvisorySpeedType extension value
|
||||
br.getBits(2) // type: none, greenwave, ecoDrive, transit
|
||||
if (hasSpeed) br.getBits(9) // SpeedAdvice (0..500)
|
||||
if (hasConfidence) br.getBits(3) // SpeedConfidenceDSRC, 8 values, not extensible
|
||||
if (hasDistance) br.getBits(14) // ZoneLength (0..10000)
|
||||
if (hasClass) br.getBits(8) // RestrictionClassID (0..255)
|
||||
if (hasRegional) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks a `ManeuverAssistList` without keeping it. Nothing consumes queue lengths yet, but the
|
||||
* list is variable-length, so it has to be parsed to find where the next field starts.
|
||||
|
||||
@@ -28,7 +28,7 @@ data class VamContent(
|
||||
* UPER encoder for the VAM of ETSI TS 103 300-3 V2.3.1 (VAM-PDU-Descriptions major version 3,
|
||||
* over the CDD of TS 102 894-2 V2.4.1), for a bicyclist in VRU profile 2.
|
||||
*
|
||||
* Covers the same field set as Niklas Dathe's reference VBS (microbu-esp32c5,
|
||||
* Covers the same field set as the colleague's reference VBS (microbu-esp32c5,
|
||||
* station-link/python/microbu_link/vbs.py, `VbsLite.assemble`), which encodes with asn1tools from
|
||||
* the ETSI modules: header, basic container, the three mandatory fields of the high-frequency
|
||||
* container, and optionally the low-frequency container with profile and size class. No cluster
|
||||
|
||||
@@ -14,20 +14,6 @@ object StationType {
|
||||
* is 15 and not 12 - mapping by list position mislabels every RSU.
|
||||
*/
|
||||
const val ROAD_SIDE_UNIT = 15
|
||||
|
||||
/**
|
||||
* The Use Case API's `stationType` string enum ("passengerCar") mapped to its ITS-G5 integer,
|
||||
* per StationType in the ETSI CDD (CiT MQTT API v6, sections 2.1.1 and 2.2.3). Mapped by name,
|
||||
* never by list position, because of the gap before [ROAD_SIDE_UNIT].
|
||||
*/
|
||||
private val BY_API_NAME = mapOf(
|
||||
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
|
||||
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
|
||||
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
|
||||
)
|
||||
|
||||
/** The ITS-G5 integer for an API station type name, or null for a blank or unknown name. */
|
||||
fun fromApiName(name: String?): Int? = name?.takeIf { it.isNotBlank() }?.let { BY_API_NAME[it] }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,13 +45,8 @@ data class Cam(
|
||||
val headingDeg: Double,
|
||||
|
||||
/**
|
||||
* Yaw rate, degrees per second, where available (positive = turning clockwise, to the right,
|
||||
* like [headingDeg] increasing). Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and
|
||||
* `v2x-uca/output/json/cam` (remote).
|
||||
*
|
||||
* The CAM's YawRateValue and the CiT One's CAM topic count the other way, positive to the
|
||||
* left, so `CamUperCodec` and `CamParser` flip the sign. The CiT One's `obu_gnss` topic is
|
||||
* already positive to the right in practice, despite its document, so `ObuGnssParser` does not.
|
||||
* Yaw rate, degrees per second, where available (positive = turning clockwise).
|
||||
* Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and `v2x-uca/output/json/cam` (remote).
|
||||
* A much more direct "is this road user turning" signal than heading-delta heuristics —
|
||||
* see [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
||||
*/
|
||||
|
||||
@@ -27,24 +27,17 @@ object CamParser {
|
||||
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||
|
||||
val stationId = JsonFieldReader.firstLong(obj, "stationId", "stationID", "station_id") ?: return null
|
||||
// The API sends the name ("passengerCar", CiT MQTT API v6 section 2.2.3); a number is still
|
||||
// accepted. Until 2026-11-18 only a number was, so every real payload was dropped here.
|
||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||
?: StationType.fromApiName(obj.optString("stationType"))
|
||||
?: return null
|
||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: return null
|
||||
|
||||
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
|
||||
|
||||
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
|
||||
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
|
||||
// Positive to the left on this topic (CiT MQTT API v6, v2x-uca/output/json/cam), as in the CAM
|
||||
// itself; negated into Cam.yawRateDps, which is positive clockwise.
|
||||
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
||||
?.let { -it }
|
||||
|
||||
val driveDirection = JsonFieldReader.firstInt(obj, "driveDirection", "drive_direction")
|
||||
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength_m", "vehicleLength", "vehicle_length")
|
||||
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth_m", "vehicleWidth", "vehicle_width")
|
||||
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength", "vehicle_length")
|
||||
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth", "vehicle_width")
|
||||
val accel = JsonFieldReader.firstDouble(obj, "accelerationControl", "longitudinalAcceleration", "acceleration_mps2")
|
||||
|
||||
// Own/remote: prefer an explicit flag if the API provides one; otherwise compare
|
||||
|
||||
@@ -24,34 +24,16 @@ object ObuGnssParser {
|
||||
*/
|
||||
fun parseEgo(json: String, fallbackStationId: Long = 0L, timestamp: Long = System.currentTimeMillis()): Cam? {
|
||||
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||
// Identity and yaw rate are in `own_info`, kinematics in `gnss` (CiT MQTT API v6 Listing 2.1,
|
||||
// and every logged payload). Until 2026-11-18 everything was read from `own_info`, which
|
||||
// has no position, so every real message was dropped and the ego state never came from
|
||||
// here. A flat payload with everything on the root is still accepted.
|
||||
val obj = root.optJSONObject("own_info") ?: root
|
||||
val gnss = root.optJSONObject("gnss") ?: obj
|
||||
|
||||
val stationId = JsonFieldReader.firstLong(obj, "stationID", "stationId", "station_id") ?: fallbackStationId
|
||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||
?: StationType.fromApiName(obj.optString("stationType"))
|
||||
?: StationType.CYCLIST
|
||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: StationType.CYCLIST
|
||||
|
||||
val (lat, lon) = JsonFieldReader.firstLatLon(gnss) ?: JsonFieldReader.firstLatLon(obj) ?: return null
|
||||
// 91 / 181 is the API's "no 2D fix" marker, not a place.
|
||||
if (lat > 90.0 || lon > 180.0) return null
|
||||
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
|
||||
|
||||
// 163.82 m/s is the API's "invalid speed" marker; treated like a missing speed.
|
||||
val speed = JsonFieldReader.firstDouble(gnss, "speed_mps", "speed", "speedMps")
|
||||
?.takeIf { it < INVALID_SPEED_MPS } ?: 0.0
|
||||
val heading = JsonFieldReader.firstDouble(gnss, "heading_deg", "heading", "headingDeg") ?: 0.0
|
||||
val acceleration = JsonFieldReader.firstDouble(gnss, "acceleration_mpss")
|
||||
// `yawRate_degps` is this topic's name (CiT MQTT API v6, Listing 2.1, own_info, and every
|
||||
// logged payload). The document says positive to the left, but the CiT One sends it positive
|
||||
// to the RIGHT: in the 2026-03-18 bacospat log, all 27 one-second windows of turning at over
|
||||
// 4 m/s had it with the same sign as the clockwise heading change. That is already
|
||||
// Cam.yawRateDps's convention, so it is taken as it is - unlike the CAM topic (CamParser),
|
||||
// which the logs show is left-positive, as documented.
|
||||
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_degps", "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
||||
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
|
||||
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
|
||||
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
||||
|
||||
return Cam(
|
||||
stationId = stationId,
|
||||
@@ -61,17 +43,11 @@ object ObuGnssParser {
|
||||
speedMps = speed,
|
||||
headingDeg = JsonFieldReader.normaliseHeadingDeg(heading),
|
||||
yawRateDps = yawRate,
|
||||
vehicleLengthM = JsonFieldReader.firstDouble(obj, "vehicleLength_m"),
|
||||
vehicleWidthM = JsonFieldReader.firstDouble(obj, "vehicleWidth_m"),
|
||||
accelerationMps2 = acceleration,
|
||||
timestamp = timestamp,
|
||||
isOwn = true,
|
||||
)
|
||||
}
|
||||
|
||||
/** The API's "invalid speed calculation" value (CiT MQTT API v6 section 2.1.1). */
|
||||
private const val INVALID_SPEED_MPS = 163.82
|
||||
|
||||
/** Just the stationID/stationType, for when only identity (not a full fix) is needed. */
|
||||
fun parseOwnIdentity(json: String): Pair<Long, Int>? {
|
||||
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||
|
||||
@@ -12,19 +12,18 @@ import kotlin.math.abs
|
||||
*
|
||||
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
|
||||
*
|
||||
* Position/speed/heading come straight from GNSS. Yaw rate comes from the gyroscope projected
|
||||
* onto gravity ([com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]), so it is the rotation
|
||||
* about the true vertical however the phone is mounted, rather than from GNSS heading deltas,
|
||||
* which are noisy at low speed — same rationale already used for remote-vehicle turn detection
|
||||
* in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
||||
* Position/speed/heading come straight from GNSS. Yaw rate is derived from the gyroscope's
|
||||
* z-axis reading (rotation about the vertical axis while the phone is roughly flat/mounted
|
||||
* upright) rather than from GNSS heading deltas, which are noisy at low speed — same rationale
|
||||
* already used for remote-vehicle turn detection in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
||||
*/
|
||||
object PhoneCamBuilder {
|
||||
|
||||
/**
|
||||
* @param gnss latest phone GNSS fix, its timestamp already on the time base to transmit.
|
||||
* @param yawRateDps yaw rate about the vertical, deg/s, in the convention of [Cam.yawRateDps]
|
||||
* (positive = clockwise), from [com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator].
|
||||
* Null encodes as the ASN.1 `unavailable` sentinel.
|
||||
* @param gnss latest phone GNSS fix.
|
||||
* @param gyroZRadPerSec latest gyroscope z-axis reading, rad/s (device frame). Positive per
|
||||
* Android's convention is counter-clockwise around +Z; converted to the clockwise-positive
|
||||
* yaw rate convention already used by [Cam.yawRateDps] to match OBU/remote CAM data.
|
||||
* @param stationId the station ID to transmit under: the current pseudonym from
|
||||
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager], or the bench pinger's fixed ID.
|
||||
* Receivers track a station across successive CAMs by this ID, which is why it only ever
|
||||
@@ -38,10 +37,12 @@ object PhoneCamBuilder {
|
||||
*/
|
||||
fun build(
|
||||
gnss: GnssReading,
|
||||
yawRateDps: Double?,
|
||||
gyroZRadPerSec: Float?,
|
||||
stationId: Long,
|
||||
longitudinalAccelMps2: Double? = null,
|
||||
): Cam {
|
||||
val yawRateDps = gyroZRadPerSec?.let { -it * RAD_TO_DEG } // negate: CCW+ -> CW+ convention
|
||||
|
||||
return Cam(
|
||||
stationId = stationId,
|
||||
stationType = StationType.CYCLIST,
|
||||
@@ -62,6 +63,8 @@ object PhoneCamBuilder {
|
||||
return h
|
||||
}
|
||||
|
||||
private const val RAD_TO_DEG = 180.0 / Math.PI
|
||||
|
||||
/**
|
||||
* Gyro noise floor below which yaw rate is clamped to zero. Placeholder — initial
|
||||
* engineering estimate pending real-world tuning, same disclaimer as
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.hawhamburg.micr0bu.domain.denm
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.cam.JsonFieldReader
|
||||
import com.hawhamburg.micr0bu.domain.cam.StationType
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
@@ -124,6 +123,17 @@ object DenmParser {
|
||||
*/
|
||||
fun causeCodeName(causeCode: Int?): String? = causeCode?.let { NAME_BY_CAUSE_CODE[it] }
|
||||
|
||||
/**
|
||||
* The Use Case API's `stationType` string enum mapped to its ITS-G5 integer, per StationType in
|
||||
* the ETSI CDD. Note roadSideUnit is **15**, not 12 - the enumeration has a gap after tram(11),
|
||||
* so mapping by list position would silently mislabel every RSU.
|
||||
*/
|
||||
private val STATION_TYPE_BY_NAME = mapOf(
|
||||
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
|
||||
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
|
||||
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
|
||||
)
|
||||
|
||||
/**
|
||||
* Parses the API's RFC3339 timestamps ("2021-05-11T12:01:02+00:00") to epoch millis. The air
|
||||
* path carries a binary TimestampIts instead, so the two transports arrive here in completely
|
||||
@@ -177,7 +187,7 @@ object DenmParser {
|
||||
val isTermination = obj.has("termination") && obj.optBoolean("termination", true)
|
||||
|
||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||
?: StationType.fromApiName(obj.optString("stationType"))
|
||||
?: STATION_TYPE_BY_NAME[obj.optString("stationType").takeIf { it.isNotBlank() }]
|
||||
|
||||
return DenmEvent(
|
||||
stationId = stationId,
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.domain.fusion
|
||||
|
||||
/**
|
||||
* Where the phone rides, as set in Settings > Ride.
|
||||
*
|
||||
* The sensor fusion filter treats the motion sensors differently per mount: on the handlebar the
|
||||
* phone is fixed to the bike (but turns with the steering), in a bag on the bike it is mostly fixed
|
||||
* but can shift, and in a pocket or backpack it moves with the rider's body, so shoulder checks look
|
||||
* like turns. Every V2X log records the setting (`meta.phone_mount`), so a recorded ride says which
|
||||
* mount it was.
|
||||
*
|
||||
* [id] is what is stored and logged; it must not change once logs exist.
|
||||
*/
|
||||
enum class PhoneMount(val id: String) {
|
||||
HANDLEBAR("handlebar"),
|
||||
BAG("bag"),
|
||||
POCKET("pocket");
|
||||
|
||||
companion object {
|
||||
val DEFAULT = HANDLEBAR
|
||||
|
||||
/** The mount stored under [id], or [DEFAULT] for a missing or unknown value. */
|
||||
fun fromId(id: String?): PhoneMount = entries.firstOrNull { it.id == id } ?: DEFAULT
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.domain.fusion
|
||||
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Yaw rate about the true vertical, whatever way up the phone is held.
|
||||
*
|
||||
* ## Why
|
||||
* Yaw rate used to be the gyroscope's z axis alone. That is rotation about the screen's normal, so
|
||||
* it is the yaw rate only with the phone lying flat, screen up. On a handlebar mount tilted towards
|
||||
* the rider it is scaled down by the tilt and mixed with pitch and roll; with the phone upright,
|
||||
* or loose in a bag, it is unrelated to the bike's turning at all.
|
||||
*
|
||||
* ## How
|
||||
* Gravity (from `TYPE_GRAVITY`, in the device frame) gives the up direction. The rate about it is
|
||||
* the gyroscope vector projected onto that unit vector: `ω · up`. That is the same number for any
|
||||
* orientation of the phone, as long as the phone is held still relative to the bike.
|
||||
*
|
||||
* Samples are averaged over [windowNanos] ending at the newest gyroscope sample, rather than taking
|
||||
* one raw sample: a single gyroscope sample on a bike is mostly vibration.
|
||||
*
|
||||
* A bike leans into a turn, and over a sustained turn `TYPE_GRAVITY` drifts toward the bike's own
|
||||
* vertical. The result is then the turn rate scaled by the cosine of the lean, about 6 % low at
|
||||
* 20° of lean. Small next to what the z-axis reading got wrong.
|
||||
*
|
||||
* All times are on the monotonic `SystemClock.elapsedRealtimeNanos` base (`SensorEvent.timestamp`),
|
||||
* never the wall clock. Pure Kotlin, so it is tested apart from Android. Thread-safe: samples and
|
||||
* reads may come from different threads.
|
||||
*/
|
||||
class YawRateEstimator(
|
||||
private val windowNanos: Long = DEFAULT_WINDOW_NANOS,
|
||||
private val staleNanos: Long = DEFAULT_STALE_NANOS,
|
||||
) {
|
||||
private val lock = Any()
|
||||
|
||||
private var upX = 0.0
|
||||
private var upY = 0.0
|
||||
private var upZ = 0.0
|
||||
/** When the up direction was last measured; null until the first gravity sample. */
|
||||
private var upAtNanos: Long? = null
|
||||
|
||||
private val times = LongArray(CAPACITY)
|
||||
/** Rotation about up, rad/s, counter-clockwise seen from above (Android's sign convention). */
|
||||
private val rates = DoubleArray(CAPACITY)
|
||||
private var next = 0
|
||||
private var count = 0
|
||||
|
||||
/** A gravity sample, m/s², device frame, pointing up. Ignored if too weak to give a direction. */
|
||||
fun onGravity(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
|
||||
val norm = sqrt(x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
|
||||
if (norm < MIN_GRAVITY_MPS2) return // free fall or a broken sample: no direction to trust
|
||||
synchronized(lock) {
|
||||
upX = x / norm
|
||||
upY = y / norm
|
||||
upZ = z / norm
|
||||
upAtNanos = elapsedRealtimeNanos
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A gyroscope sample, rad/s, device frame. Dropped while the up direction is unknown or stale,
|
||||
* since projecting onto an old up vector would report the phone's rotation since then as yaw.
|
||||
*/
|
||||
fun onGyro(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
|
||||
synchronized(lock) {
|
||||
val upAt = upAtNanos ?: return
|
||||
if (elapsedRealtimeNanos - upAt > staleNanos) return
|
||||
times[next] = elapsedRealtimeNanos
|
||||
rates[next] = x * upX + y * upY + z * upZ
|
||||
next = (next + 1) % CAPACITY
|
||||
if (count < CAPACITY) count++
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mean yaw rate over the last [windowNanos] of samples, deg/s, positive = turning clockwise
|
||||
* seen from above: the convention of [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps].
|
||||
* Null when there is no sample newer than [staleNanos] before [nowElapsedRealtimeNanos].
|
||||
*/
|
||||
fun yawRateDps(nowElapsedRealtimeNanos: Long): Double? {
|
||||
synchronized(lock) {
|
||||
if (count == 0) return null
|
||||
val newestIndex = (next - 1 + CAPACITY) % CAPACITY
|
||||
val newest = times[newestIndex]
|
||||
if (nowElapsedRealtimeNanos - newest > staleNanos) return null
|
||||
|
||||
var sum = 0.0
|
||||
var n = 0
|
||||
for (k in 0 until count) {
|
||||
val i = (newestIndex - k + CAPACITY) % CAPACITY
|
||||
if (newest - times[i] > windowNanos) break
|
||||
sum += rates[i]
|
||||
n++
|
||||
}
|
||||
// Negate: counter-clockwise positive (Android) -> clockwise positive (Cam.yawRateDps).
|
||||
return -(sum / n) * RAD_TO_DEG
|
||||
}
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
synchronized(lock) {
|
||||
upAtNanos = null
|
||||
next = 0
|
||||
count = 0
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 100 ms: five samples at `SENSOR_DELAY_GAME` (about 50 Hz). */
|
||||
const val DEFAULT_WINDOW_NANOS = 100_000_000L
|
||||
|
||||
/** Older than this, a gyroscope or gravity sample no longer describes the present. */
|
||||
const val DEFAULT_STALE_NANOS = 500_000_000L
|
||||
|
||||
/** Room for the window at up to a few hundred Hz. */
|
||||
private const val CAPACITY = 128
|
||||
|
||||
/** Well below 9.81: gravity this weak means free fall or a bad sample, not a direction. */
|
||||
private const val MIN_GRAVITY_MPS2 = 3.0
|
||||
|
||||
private const val RAD_TO_DEG = 180.0 / Math.PI
|
||||
}
|
||||
}
|
||||
@@ -1,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,38 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.domain.map
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
|
||||
|
||||
/**
|
||||
* Intersection geometry the app ships with (`assets/mapem/hamburg.txt`, built by
|
||||
* `tools/mapem_bundle.py` from recorded MAPEMs), so a SPATEM can be placed on its lanes without
|
||||
* waiting for, or ever receiving, the intersection's MAPEM.
|
||||
*
|
||||
* Which stored intersection a SPATEM belongs to is decided in
|
||||
* [com.hawhamburg.micr0bu.domain.spat.TrafficLights.geometryFor].
|
||||
*/
|
||||
object StoredMaps {
|
||||
|
||||
const val ASSET_PATH = "mapem/hamburg.txt"
|
||||
|
||||
/**
|
||||
* One UPER MAPEM per line as hex; blank lines and `#` comments are skipped, as is a line that
|
||||
* does not decode, so one bad entry does not cost the rest.
|
||||
*/
|
||||
fun parse(text: String): List<IntersectionGeometry> =
|
||||
text.lineSequence()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith("#") }
|
||||
.mapNotNull { hexToBytes(it) }
|
||||
.flatMap { MapemUperCodec.decode(it, 0L)?.intersections.orEmpty() }
|
||||
.toList()
|
||||
|
||||
private fun hexToBytes(hex: String): ByteArray? {
|
||||
if (hex.length % 2 != 0) return null
|
||||
return ByteArray(hex.length / 2) { i ->
|
||||
val high = Character.digit(hex[2 * i], 16)
|
||||
val low = Character.digit(hex[2 * i + 1], 16)
|
||||
if (high < 0 || low < 0) return null
|
||||
(high * 16 + low).toByte()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.domain.spat
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneConnection
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneType
|
||||
import com.hawhamburg.micr0bu.domain.map.MapLane
|
||||
import com.hawhamburg.micr0bu.domain.map.MapPoint
|
||||
import com.hawhamburg.micr0bu.domain.map.Maneuvers
|
||||
import com.hawhamburg.micr0bu.domain.map.lanePoints
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.hypot
|
||||
|
||||
/**
|
||||
* A signalised intersection as a road user sees it: SPATEM's signal groups placed on MAPEM's lanes.
|
||||
*
|
||||
* MAPEM says "ingress lane 1 may be left straight ahead for lane 6, under signal group 1"; SPATEM
|
||||
* says "signal group 1 is green for another 12 s". Joined, that is "North in, straight: green,
|
||||
* 12 s" - and, with the rider's position and heading, which of those is the rider's own light.
|
||||
*/
|
||||
data class TrafficLight(
|
||||
/** `region/id`, as [IntersectionSignalState.key] and [IntersectionGeometry.key]. */
|
||||
val key: String,
|
||||
/** The latest SPATEM for this intersection, if one has been heard. */
|
||||
val signal: SpatIntersection?,
|
||||
/** The latest MAPEM for it, if one has been heard. Without it, signal groups are bare numbers. */
|
||||
val geometry: IntersectionGeometry?,
|
||||
/** Every ingress lane that has a signalled connection, in MAPEM order. */
|
||||
val approaches: List<ApproachSignals>,
|
||||
/** The ingress lane the rider is on, when [geometry], a position and a heading say so. */
|
||||
val ownApproach: OwnApproach?,
|
||||
) {
|
||||
/**
|
||||
* The SPATEM's revision differs from the MAPEM's: the geometry the signal groups refer to has
|
||||
* changed since this MAPEM, so the lane labels may be wrong until the new MAPEM arrives.
|
||||
*/
|
||||
val revisionMismatch: Boolean
|
||||
get() = signal != null && geometry != null && signal.state.revision != geometry.revision
|
||||
|
||||
val name: String? get() = geometry?.name
|
||||
}
|
||||
|
||||
/** One ingress lane and the light for each way out of it. */
|
||||
data class ApproachSignals(
|
||||
val lane: MapLane,
|
||||
/** Where the lane's stop line is (its first node). */
|
||||
val stopLine: MapPoint,
|
||||
/** Travel direction into the intersection, degrees clockwise from north. */
|
||||
val bearingDeg: Double,
|
||||
val exits: List<LaneExit>,
|
||||
) {
|
||||
/**
|
||||
* Exits grouped by signal group, each with every turn that group controls: the usual case is
|
||||
* one group for straight-and-right and another for left, and a rider wants one light per group.
|
||||
*/
|
||||
val byGroup: List<Pair<Int?, List<LaneExit>>>
|
||||
get() = exits.groupBy { it.connection.signalGroup }.toList()
|
||||
}
|
||||
|
||||
/** One `Connection` with the turn it makes and the SPATEM movement that controls it. */
|
||||
data class LaneExit(
|
||||
val connection: LaneConnection,
|
||||
val turn: Turn,
|
||||
/** The movement for [LaneConnection.signalGroup] in the latest SPATEM, if it has one. */
|
||||
val movement: SignalMovement?,
|
||||
)
|
||||
|
||||
enum class Turn { STRAIGHT, LEFT, RIGHT, U_TURN, UNKNOWN }
|
||||
|
||||
data class OwnApproach(
|
||||
val approach: ApproachSignals,
|
||||
/** Along the lane from the rider to the stop line. */
|
||||
val distanceToStopLineM: Double,
|
||||
)
|
||||
|
||||
object TrafficLights {
|
||||
|
||||
/** Farther than this from the reference point, no lane is matched to the rider. */
|
||||
const val MATCH_RADIUS_M = 200.0
|
||||
/** A lane matches only if the rider is within this of its centre line. */
|
||||
private const val MATCH_LATERAL_M = 6.0
|
||||
/** ...and travelling within this of its direction, when moving fast enough for a heading. */
|
||||
private const val MATCH_HEADING_DEG = 50.0
|
||||
private const val MIN_SPEED_FOR_HEADING_MPS = 1.0
|
||||
|
||||
/**
|
||||
* Joins [signal] and [geometry] (either may be null, not both) for a rider at [own], if known.
|
||||
* [ownSpeedMps] below [MIN_SPEED_FOR_HEADING_MPS] means the heading is not trusted and the
|
||||
* nearest lane wins on distance alone.
|
||||
*/
|
||||
fun join(
|
||||
signal: SpatIntersection?,
|
||||
geometry: IntersectionGeometry?,
|
||||
own: MapPoint? = null,
|
||||
ownHeadingDeg: Double? = null,
|
||||
ownSpeedMps: Double? = null,
|
||||
): TrafficLight {
|
||||
val key = signal?.key ?: geometry?.key ?: error("join needs a SPATEM or a MAPEM")
|
||||
if (geometry == null) return TrafficLight(key, signal, null, emptyList(), null)
|
||||
val movements = signal?.state?.movements?.associateBy { it.signalGroup } ?: emptyMap()
|
||||
val approaches = geometry.lanes
|
||||
.filter { it.isIngress && it.connections.any { c -> c.signalGroup != null } }
|
||||
.mapNotNull { lane ->
|
||||
val points = geometry.lanePoints(lane)
|
||||
if (points.size < 2) return@mapNotNull null
|
||||
val bearing = bearing(geometry, points[1], points[0])
|
||||
ApproachSignals(
|
||||
lane = lane,
|
||||
stopLine = points[0],
|
||||
bearingDeg = bearing,
|
||||
exits = lane.connections.filter { it.signalGroup != null }.map { c ->
|
||||
LaneExit(c, turnOf(geometry, lane, c, bearing), movements[c.signalGroup])
|
||||
},
|
||||
)
|
||||
}
|
||||
val ownApproach = own?.let { match(geometry, approaches, it, ownHeadingDeg, ownSpeedMps) }
|
||||
return TrafficLight(key, signal, geometry, approaches, ownApproach)
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn a connection makes: its own `maneuver` when it names exactly one turn, else the
|
||||
* lane's, else the angle between the ingress lane and the lane it leads to. Only about half the
|
||||
* recorded connections carry a maneuver.
|
||||
*/
|
||||
internal fun turnOf(geometry: IntersectionGeometry, lane: MapLane, c: LaneConnection, inBearing: Double): Turn {
|
||||
c.maneuver?.single()?.let { return it }
|
||||
lane.maneuvers?.single()?.let { return it }
|
||||
return geometricTurn(geometry, c, inBearing)
|
||||
}
|
||||
|
||||
/** The turn from the angle between the ingress lane ([inBearing]) and where [c] leads. */
|
||||
internal fun geometricTurn(geometry: IntersectionGeometry, c: LaneConnection, inBearing: Double): Turn {
|
||||
if (c.remoteIntersection != null) return Turn.UNKNOWN
|
||||
val target = geometry.lane(c.toLane) ?: return Turn.UNKNOWN
|
||||
val points = geometry.lanePoints(target)
|
||||
if (points.size < 2) return Turn.UNKNOWN
|
||||
val delta = normalise(bearing(geometry, points[0], points[1]) - inBearing)
|
||||
return when {
|
||||
abs(delta) <= 35.0 -> Turn.STRAIGHT
|
||||
delta in 35.0..150.0 -> Turn.RIGHT
|
||||
delta in -150.0..-35.0 -> Turn.LEFT
|
||||
else -> Turn.U_TURN
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of the MAPEMs heard for one intersection a SPATEM refers to: the one with its revision,
|
||||
* else the newest. Two revisions of one intersection can be on air at once (the 2026-03-18 drive
|
||||
* heard 1/1 at revisions 2 and 3, with SPATEMs for both), and their signal groups differ.
|
||||
*/
|
||||
fun pickGeometry(candidates: List<IntersectionGeometry>, spatRevision: Int?): IntersectionGeometry? =
|
||||
candidates.lastOrNull { it.revision == spatRevision } ?: candidates.lastOrNull()
|
||||
|
||||
/** A stored MAPEM is only used for a rider this close to its reference point. */
|
||||
const val STORED_MAP_RADIUS_M = 2_000.0
|
||||
|
||||
/**
|
||||
* The geometry for the intersection a SPATEM names, out of what was heard on air ([live],
|
||||
* oldest first) and what the app ships with ([stored]).
|
||||
*
|
||||
* Both are matched on region and intersection id ([IntersectionGeometry.key]), never on the
|
||||
* sending station: one intersection is heard under several station ids. In order:
|
||||
*
|
||||
* 1. a live MAPEM of the SPATEM's revision;
|
||||
* 2. a stored one of that revision, within [STORED_MAP_RADIUS_M] of [own] when the position
|
||||
* is known;
|
||||
* 3. the newest live one of another revision (flagged by [TrafficLight.revisionMismatch]).
|
||||
*
|
||||
* A stored MAPEM of another revision is never used: it may be months old, and its signal groups
|
||||
* could put the wrong light on a lane.
|
||||
*/
|
||||
fun geometryFor(
|
||||
key: String,
|
||||
spatRevision: Int,
|
||||
live: List<IntersectionGeometry>,
|
||||
stored: List<IntersectionGeometry>,
|
||||
own: MapPoint? = null,
|
||||
): IntersectionGeometry? {
|
||||
val heard = pickGeometry(live.filter { it.key == key }, spatRevision)
|
||||
if (heard?.revision == spatRevision) return heard
|
||||
val shipped = stored.lastOrNull {
|
||||
it.key == key && it.revision == spatRevision && (own == null || isNear(it, own))
|
||||
}
|
||||
return shipped ?: heard
|
||||
}
|
||||
|
||||
private fun isNear(geometry: IntersectionGeometry, own: MapPoint): Boolean {
|
||||
val (east, north) = geometry.toLocal(own)
|
||||
return hypot(east, north) <= STORED_MAP_RADIUS_M
|
||||
}
|
||||
|
||||
internal fun Maneuvers.single(): Turn? {
|
||||
val turns = listOfNotNull(
|
||||
Turn.STRAIGHT.takeIf { straight }, Turn.LEFT.takeIf { left },
|
||||
Turn.RIGHT.takeIf { right }, Turn.U_TURN.takeIf { uTurn },
|
||||
)
|
||||
return turns.singleOrNull()
|
||||
}
|
||||
|
||||
private fun match(
|
||||
geometry: IntersectionGeometry,
|
||||
approaches: List<ApproachSignals>,
|
||||
own: MapPoint,
|
||||
headingDeg: Double?,
|
||||
speedMps: Double?,
|
||||
): OwnApproach? {
|
||||
val p = geometry.toLocal(own)
|
||||
if (hypot(p.first, p.second) > MATCH_RADIUS_M) return null
|
||||
val useHeading = headingDeg != null && (speedMps ?: 0.0) >= MIN_SPEED_FOR_HEADING_MPS
|
||||
var best: Pair<OwnApproach, Double>? = null
|
||||
for (approach in approaches) {
|
||||
// A rider can only be on a lane they may use: crosswalks and sidewalks are not theirs.
|
||||
if (approach.lane.type != LaneType.VEHICLE && approach.lane.type != LaneType.BIKE_LANE) continue
|
||||
val points = geometry.lanePoints(approach.lane).map { geometry.toLocal(it) }
|
||||
var along = 0.0
|
||||
for (s in 0 until points.size - 1) {
|
||||
val (ax, ay) = points[s]
|
||||
val (bx, by) = points[s + 1]
|
||||
val dx = bx - ax
|
||||
val dy = by - ay
|
||||
val length = hypot(dx, dy)
|
||||
if (length < 0.01) continue
|
||||
// Projection onto segment a->b (outward from the stop line)
|
||||
val t = (((p.first - ax) * dx + (p.second - ay) * dy) / (length * length)).coerceIn(0.0, 1.0)
|
||||
val lateral = hypot(p.first - (ax + t * dx), p.second - (ay + t * dy))
|
||||
val beyondStopLine = s == 0 && t == 0.0 && ((p.first - ax) * dx + (p.second - ay) * dy) < 0
|
||||
if (lateral <= MATCH_LATERAL_M && !beyondStopLine) {
|
||||
// Travel on an ingress lane runs b->a, toward the stop line.
|
||||
val travel = compassBearing(-dx, -dy)
|
||||
val headingOk = !useHeading || abs(normalise(headingDeg!! - travel)) <= MATCH_HEADING_DEG
|
||||
if (headingOk && (best == null || lateral < best.second)) {
|
||||
best = OwnApproach(approach, along + t * length) to lateral
|
||||
}
|
||||
}
|
||||
along += length
|
||||
}
|
||||
}
|
||||
return best?.first
|
||||
}
|
||||
|
||||
/** East/north metres from the reference point, on the same tangent plane as the XY offsets. */
|
||||
private fun IntersectionGeometry.toLocal(p: MapPoint): Pair<Double, Double> =
|
||||
Pair(
|
||||
(p.longitude - refLongitude) * METRES_PER_DEGREE * cos(refLatitude * PI / 180.0),
|
||||
(p.latitude - refLatitude) * METRES_PER_DEGREE,
|
||||
)
|
||||
|
||||
private fun bearing(geometry: IntersectionGeometry, from: MapPoint, to: MapPoint): Double {
|
||||
val a = geometry.toLocal(from)
|
||||
val b = geometry.toLocal(to)
|
||||
return compassBearing(b.first - a.first, b.second - a.second)
|
||||
}
|
||||
|
||||
/** Degrees clockwise from north of the vector (east, north), in [0, 360). */
|
||||
private fun compassBearing(east: Double, north: Double): Double =
|
||||
(atan2(east, north) * 180.0 / PI + 360.0) % 360.0
|
||||
|
||||
/** Into (-180, 180]. */
|
||||
private fun normalise(deg: Double): Double {
|
||||
var d = deg % 360.0
|
||||
if (d > 180.0) d -= 360.0
|
||||
if (d <= -180.0) d += 360.0
|
||||
return d
|
||||
}
|
||||
|
||||
private const val METRES_PER_DEGREE = 6_378_137.0 * PI / 180.0
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* When to send an individual VAM: ETSI TS 103 300-3 V2.3.1 clause 6.4, items 1 to 4, with the
|
||||
* recommended values of Tables 16 and 17 — the same rules Niklas Dathe's reference VBS applies
|
||||
* recommended values of Tables 16 and 17 — the same rules the colleague's reference VBS applies
|
||||
* (microbu-esp32c5/station-link/python/microbu_link/vbs.py, `VbsLite.due`). No clustering, no
|
||||
* redundancy mitigation, T_GenVam fixed at its minimum (no DCC input).
|
||||
*
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.hawhamburg.micr0bu.service
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.SensorManager
|
||||
import android.os.SystemClock
|
||||
import com.hawhamburg.micr0bu.data.GnssReading
|
||||
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
||||
@@ -14,7 +13,6 @@ import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
||||
import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
|
||||
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
||||
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -64,7 +62,7 @@ class CamPinger @Inject constructor(
|
||||
private var job: Job? = null
|
||||
|
||||
@Volatile private var latestGnss: GnssReading? = null
|
||||
private val yawRate = YawRateEstimator()
|
||||
@Volatile private var latestGyroZ: Float? = null
|
||||
@Volatile private var previousGnss: GnssReading? = null
|
||||
|
||||
private val _isActive = MutableStateFlow(false)
|
||||
@@ -104,24 +102,16 @@ class CamPinger @Inject constructor(
|
||||
|
||||
private suspend fun runPingLoop() = coroutineScope {
|
||||
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
||||
yawRate.reset()
|
||||
launch {
|
||||
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||
}
|
||||
launch {
|
||||
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||
}
|
||||
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
|
||||
|
||||
while (true) {
|
||||
val gnss = latestGnss
|
||||
_hasFix.value = gnss != null
|
||||
if (gnss != null) {
|
||||
val cam = PhoneCamBuilder.build(
|
||||
// Stamped with the GNSS time of the fix itself; see GnssTimeSource.atElapsedRealtime.
|
||||
gnss = gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos)),
|
||||
yawRateDps = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos()),
|
||||
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource.
|
||||
gnss = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)),
|
||||
gyroZRadPerSec = latestGyroZ,
|
||||
stationId = OwnStationIds.BENCH_PING,
|
||||
longitudinalAccelMps2 = longitudinalAccel(gnss),
|
||||
)
|
||||
@@ -150,7 +140,7 @@ class CamPinger @Inject constructor(
|
||||
previousGnss = gnss
|
||||
if (prev == null) return null
|
||||
|
||||
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
|
||||
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
|
||||
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
||||
|
||||
return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.hawhamburg.micr0bu.service
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.SensorManager
|
||||
import android.os.SystemClock
|
||||
import com.hawhamburg.micr0bu.data.GnssReading
|
||||
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
||||
import com.hawhamburg.micr0bu.data.SensorRepository
|
||||
@@ -18,7 +16,6 @@ import com.hawhamburg.micr0bu.domain.asn1.VamContent
|
||||
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.cam.CamTransmitConfig
|
||||
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
||||
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
|
||||
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
@@ -76,9 +73,7 @@ class CamTransmitLoop @Inject constructor(
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
@Volatile private var latestGnss: GnssReading? = null
|
||||
private val yawRate = YawRateEstimator()
|
||||
|
||||
/** [SystemClock.elapsedRealtime] until which the elevated rate holds; monotonic, see [nowMs]. */
|
||||
@Volatile private var latestGyroZ: Float? = null
|
||||
@Volatile private var elevatedUntilMs: Long = 0L
|
||||
|
||||
/** Previous GNSS fix, kept only to derive along-track acceleration — see [longitudinalAccel]. */
|
||||
@@ -94,7 +89,7 @@ class CamTransmitLoop @Inject constructor(
|
||||
* denser updates through the maneuver, not just at the instant it was detected.
|
||||
*/
|
||||
fun onDetectedEvent() {
|
||||
elevatedUntilMs = nowMs() + ELEVATED_HOLD_MS
|
||||
elevatedUntilMs = System.currentTimeMillis() + ELEVATED_HOLD_MS
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,15 +118,7 @@ class CamTransmitLoop @Inject constructor(
|
||||
|
||||
private suspend fun runTransmitLoop() = coroutineScope {
|
||||
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
||||
yawRate.reset()
|
||||
launch {
|
||||
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||
}
|
||||
launch {
|
||||
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||
}
|
||||
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
|
||||
launch { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
|
||||
launch {
|
||||
obuHardwarePrefs.outgoingMessageFlow.collect {
|
||||
@@ -156,23 +143,25 @@ class CamTransmitLoop @Inject constructor(
|
||||
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
|
||||
// rotation fall cleanly between two frames instead of inside one.
|
||||
val pseudonym = pseudonymManager.current()
|
||||
val fix = onAirFix(gnss)
|
||||
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
|
||||
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the
|
||||
// outgoing CAM is: acceleration below still differences wall-clock samples.
|
||||
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
|
||||
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
|
||||
val bytes = codec.encodeCam(cam)
|
||||
esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes,
|
||||
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
|
||||
}
|
||||
|
||||
private suspend fun sendVamIfDue(gnss: GnssReading) {
|
||||
val now = nowMs()
|
||||
val now = System.currentTimeMillis()
|
||||
val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude,
|
||||
gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble())
|
||||
if (!vamRules.due(now, kinematics)) return
|
||||
val pseudonym = pseudonymManager.current()
|
||||
val fix = onAirFix(gnss)
|
||||
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
|
||||
// The CAM view of this fix is built only for its position vector, so the GN header of a VAM
|
||||
// follows exactly the rules a CAM's does. It is not transmitted.
|
||||
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
|
||||
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
|
||||
val withLowFrequency = vamRules.includeLowFrequency(now)
|
||||
val bytes = VamUperCodec.encode(VamContent(
|
||||
stationId = pseudonym.stationId,
|
||||
@@ -209,31 +198,15 @@ class CamTransmitLoop @Inject constructor(
|
||||
previousGnss = gnss
|
||||
if (prev == null) return null
|
||||
|
||||
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
|
||||
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
|
||||
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
||||
|
||||
val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble()
|
||||
return dv / dtSec
|
||||
}
|
||||
|
||||
/**
|
||||
* [gnss] stamped with the GNSS time of the fix itself, for what goes on air: the fix's
|
||||
* monotonic stamp moved onto GNSS time ([GnssTimeSource.atElapsedRealtime]). Neither the
|
||||
* phone's clock setting nor a step of it between the fix and now can reach the result.
|
||||
*/
|
||||
private fun onAirFix(gnss: GnssReading): GnssReading =
|
||||
gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos))
|
||||
|
||||
private fun currentYawRateDps(): Double? = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos())
|
||||
|
||||
/**
|
||||
* The clock for this loop's own intervals (elevated-rate hold, VAM generation rules). Monotonic,
|
||||
* so a phone clock that is set back cannot hold transmission off until it catches up again.
|
||||
*/
|
||||
private fun nowMs(): Long = SystemClock.elapsedRealtime()
|
||||
|
||||
private fun currentRateHz(gnss: GnssReading?): Double {
|
||||
val now = nowMs()
|
||||
val now = System.currentTimeMillis()
|
||||
val inGeofence = gnss != null && config.geofences.any { fence ->
|
||||
GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM
|
||||
}
|
||||
|
||||
@@ -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,7 +15,6 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.GpsFixed
|
||||
import androidx.compose.material.icons.filled.GpsOff
|
||||
import androidx.compose.material.icons.filled.Sensors
|
||||
@@ -39,10 +38,8 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hawhamburg.micr0bu.R
|
||||
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||
@@ -61,9 +58,6 @@ fun StatusTopBar(
|
||||
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
|
||||
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
|
||||
esp32Bluetooth: Boolean = false,
|
||||
/** The connected ESP32-C5 reports a low cell (amber) or a critical one (red). */
|
||||
obuBatteryLow: Boolean = false,
|
||||
obuBatteryCritical: Boolean = false,
|
||||
) {
|
||||
TopAppBar(
|
||||
title = {
|
||||
@@ -103,17 +97,6 @@ fun StatusTopBar(
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (isEsp32 && (obuBatteryLow || obuBatteryCritical)) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.BatteryAlert,
|
||||
contentDescription = stringResource(
|
||||
if (obuBatteryCritical) R.string.status_battery_critical else R.string.status_battery_low,
|
||||
),
|
||||
tint = if (obuBatteryCritical) ErrorRed else AmberAcquiring,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -46,12 +46,11 @@ sealed class Screen(val route: String, val labelRes: Int) {
|
||||
data object SettingsLanguage : Screen("settings/language", R.string.settings_language)
|
||||
data object SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance)
|
||||
data object SettingsSensors : Screen("settings/sensors", R.string.settings_sensors)
|
||||
data object SettingsRide : Screen("settings/ride", R.string.settings_ride)
|
||||
data object SettingsUnits : Screen("settings/units", R.string.settings_units)
|
||||
data object SettingsConnection : Screen("settings/connection", R.string.settings_connection)
|
||||
data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
|
||||
data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts)
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.BatteryFull
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.LinkOff
|
||||
import androidx.compose.material.icons.filled.Usb
|
||||
@@ -315,39 +313,6 @@ fun ConnectionSetupScreen(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// The OBU's own cell (XIAO ESP32-C5 on its battery); absent from older firmware.
|
||||
s.batteryPercent?.let { percent ->
|
||||
val batteryColor = when {
|
||||
s.batteryCritical -> Color(0xFFFF5252)
|
||||
s.batteryLow -> UsbAmber
|
||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (s.batteryLow || s.batteryCritical) Icons.Default.BatteryAlert else Icons.Default.BatteryFull,
|
||||
null,
|
||||
tint = batteryColor,
|
||||
modifier = Modifier.size(14.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.conn_esp32_battery, s.batteryMv / 1000.0, percent),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = batteryColor,
|
||||
)
|
||||
}
|
||||
if (s.batteryLow || s.batteryCritical) {
|
||||
Text(
|
||||
stringResource(
|
||||
if (s.batteryCritical) R.string.conn_esp32_battery_critical else R.string.conn_esp32_battery_low,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = batteryColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,10 +65,7 @@ import com.hawhamburg.micr0bu.domain.cam.Cam
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmParser
|
||||
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
|
||||
import com.hawhamburg.micr0bu.domain.spat.SignalMovement
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
|
||||
import com.hawhamburg.micr0bu.domain.spat.Turn
|
||||
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
|
||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -88,7 +85,7 @@ fun DashboardScreen(
|
||||
obuStationTypeWarning: Boolean = false,
|
||||
obuStationType: Int? = null,
|
||||
hazards: List<DenmEvent> = emptyList(),
|
||||
signals: List<TrafficLight> = emptyList(),
|
||||
signals: List<SpatIntersection> = emptyList(),
|
||||
ownPosition: Cam? = null,
|
||||
onNavigateToConnection: () -> Unit,
|
||||
onNavigateToSensors: () -> Unit,
|
||||
@@ -412,18 +409,17 @@ fun DashboardScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// The intersection whose ingress lane the rider is on (MAPEM geometry plus position and
|
||||
// heading) comes first, nearest stop line first. Otherwise - no MAPEM heard, or not on one
|
||||
// of its lanes - the one changing soonest, which is the one a rider approaching a junction
|
||||
// most likely needs.
|
||||
// Signals cannot be ranked by distance: SPATEM carries no position at all. The geometry
|
||||
// that would place an intersection lives in MAPEM, which nothing on the air is currently
|
||||
// sending. So the one shown is the one changing soonest, which is in any case the one a
|
||||
// rider approaching a junction needs to see.
|
||||
val nextSignal = remember(signals) {
|
||||
val now = System.currentTimeMillis()
|
||||
signals.filter { it.ownApproach != null }.minByOrNull { it.ownApproach!!.distanceToStopLineM }
|
||||
?: signals.minByOrNull { it.signal?.secondsToNextChange(now) ?: Double.MAX_VALUE }
|
||||
signals.minByOrNull { it.secondsToNextChange(now) ?: Double.MAX_VALUE }
|
||||
}
|
||||
nextSignal?.let { light ->
|
||||
nextSignal?.let { signal ->
|
||||
SignalCard(
|
||||
light = light,
|
||||
signal = signal,
|
||||
additionalCount = signals.size - 1,
|
||||
onClick = onNavigateToV2x,
|
||||
)
|
||||
@@ -642,16 +638,16 @@ private fun HazardCard(
|
||||
}
|
||||
|
||||
/**
|
||||
* The intersection that matters most: the one whose lane the rider is on, else the one changing
|
||||
* soonest. With MAPEM geometry the card names the intersection and, once the rider is on one of
|
||||
* its ingress lanes, shows that lane's lights - one chip per signal group, with the turns it
|
||||
* controls - and the distance to the stop line. Without it, signal groups are bare numbers,
|
||||
* since anything friendlier would claim knowledge that is not there.
|
||||
* The signalised intersection changing soonest: its leading phase with a countdown, then every
|
||||
* signal group as a coloured chip.
|
||||
*
|
||||
* Signal groups are bare numbers because that is all the app knows. Calling one "your lane" needs
|
||||
* MAPEM geometry, and a friendlier label would claim knowledge that is not there.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun SignalCard(
|
||||
light: TrafficLight,
|
||||
signal: SpatIntersection,
|
||||
additionalCount: Int,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
@@ -666,28 +662,16 @@ private fun SignalCard(
|
||||
}
|
||||
}
|
||||
val now = nowMs.longValue
|
||||
val signal = light.signal ?: return
|
||||
val own = light.ownApproach
|
||||
|
||||
// The rider's own light: the straight-ahead exit of their lane, else its first. Without a
|
||||
// matched lane, the group changing soonest speaks for the intersection, as before.
|
||||
val leading = own?.approach?.let { approach ->
|
||||
(approach.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: approach.exits.firstOrNull())?.movement
|
||||
} ?: signal.state.movements.minByOrNull { movement ->
|
||||
val leading = signal.state.movements.minByOrNull { movement ->
|
||||
movement.current?.secondsUntil(now)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
||||
}
|
||||
val phase = leading?.current?.phase
|
||||
val tint = phaseTint(phase)
|
||||
val countdown = leading?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
|
||||
|
||||
// One chip per signal group: the rider's lane's groups with their turn arrows, or every group.
|
||||
val chips: List<Pair<String, SignalMovement?>> = own?.approach?.byGroup?.map { (_, exits) ->
|
||||
exits.joinToString("") { it.turn.arrow() } to exits.first().movement
|
||||
} ?: signal.state.movements.map { stringResource(R.string.v2x_spat_group, it.signalGroup) to it }
|
||||
|
||||
val hiddenGroups = chips.size - DASH_MAX_SIGNAL_GROUPS
|
||||
val hiddenGroups = signal.state.movements.size - DASH_MAX_SIGNAL_GROUPS
|
||||
val footer = listOfNotNull(
|
||||
if (light.revisionMismatch) stringResource(R.string.dash_signal_map_outdated) else null,
|
||||
if (hiddenGroups > 0) stringResource(R.string.dash_more_count, hiddenGroups) else null,
|
||||
if (additionalCount > 0) stringResource(R.string.dash_signal_more, additionalCount) else null,
|
||||
).joinToString(" · ")
|
||||
@@ -706,23 +690,11 @@ private fun SignalCard(
|
||||
Icon(Icons.Default.Traffic, null, tint = tint, modifier = Modifier.size(28.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
light.name ?: stringResource(R.string.dash_signal_title, light.key),
|
||||
stringResource(R.string.dash_signal_title, signal.state.key),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = tint,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
if (own != null) {
|
||||
Text(
|
||||
stringResource(
|
||||
R.string.dash_signal_own_approach,
|
||||
own.approach.lane.name
|
||||
?: stringResource(R.string.v2x_lane_fallback, own.approach.lane.laneId),
|
||||
own.distanceToStopLineM,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = countdown
|
||||
?.let { stringResource(R.string.dash_signal_countdown, phaseLabel(phase), it) }
|
||||
@@ -735,12 +707,12 @@ private fun SignalCard(
|
||||
// Wraps rather than scrolls: a horizontal scroller inside a scrolling dashboard
|
||||
// is awkward to drive one-handed, and the chip row is short by construction.
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
chips.take(DASH_MAX_SIGNAL_GROUPS).forEach { (label, movement) ->
|
||||
val groupTint = phaseTint(movement?.current?.phase)
|
||||
signal.state.movements.take(DASH_MAX_SIGNAL_GROUPS).forEach { movement ->
|
||||
val groupTint = phaseTint(movement.current?.phase)
|
||||
val groupCountdown =
|
||||
movement?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
|
||||
movement.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
|
||||
Text(
|
||||
text = label +
|
||||
text = stringResource(R.string.v2x_spat_group, movement.signalGroup) +
|
||||
(groupCountdown?.let { " " + stringResource(R.string.v2x_spat_countdown, it) } ?: ""),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
@@ -767,15 +739,6 @@ private fun SignalCard(
|
||||
}
|
||||
}
|
||||
|
||||
/** An arrow for a turn, as signs show it. */
|
||||
private fun Turn.arrow(): String = when (this) {
|
||||
Turn.STRAIGHT -> "↑"
|
||||
Turn.LEFT -> "←"
|
||||
Turn.RIGHT -> "→"
|
||||
Turn.U_TURN -> "↶"
|
||||
Turn.UNKNOWN -> "?"
|
||||
}
|
||||
|
||||
/** Traffic-light colour for a phase: go is green, stop is red, anything in between is amber. */
|
||||
@Composable
|
||||
private fun phaseTint(phase: SignalPhase?): Color = when {
|
||||
|
||||
@@ -33,7 +33,6 @@ 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 +46,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
|
||||
@@ -167,32 +165,6 @@ fun MqttTopicViewerScreen(
|
||||
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 ──────────────
|
||||
@@ -242,9 +214,13 @@ fun MqttTopicViewerScreen(
|
||||
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.disconnectEsp32()
|
||||
else viewModel.connectEsp32()
|
||||
} else {
|
||||
if (isConnected || isConnecting) viewModel.disconnect() else viewModel.connect()
|
||||
}
|
||||
},
|
||||
colors = IconButtonDefaults.iconButtonColors(
|
||||
contentColor = if (isConnected) ErrorRed else ConnectedGreen,
|
||||
|
||||
@@ -4,7 +4,6 @@ import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -48,11 +47,9 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.core.os.LocaleListCompat
|
||||
import com.hawhamburg.micr0bu.R
|
||||
import com.hawhamburg.micr0bu.data.mqtt.MqttPrefs
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionConfig
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
|
||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||
@@ -71,7 +68,7 @@ fun SettingsScreen(
|
||||
onOpenLanguage: () -> Unit,
|
||||
onOpenAppearance: () -> Unit,
|
||||
onOpenSensors: () -> Unit,
|
||||
onOpenRide: () -> Unit,
|
||||
onOpenUnits: () -> Unit,
|
||||
onOpenConnection: () -> Unit,
|
||||
onOpenMqtt: () -> Unit,
|
||||
onOpenUseCaseAlerts: () -> Unit,
|
||||
@@ -102,7 +99,7 @@ fun SettingsScreen(
|
||||
RowDivider()
|
||||
MenuRow(stringResource(R.string.settings_sensors), onOpenSensors)
|
||||
RowDivider()
|
||||
MenuRow(stringResource(R.string.settings_ride), onOpenRide)
|
||||
MenuRow(stringResource(R.string.settings_units), onOpenUnits)
|
||||
RowDivider()
|
||||
MenuRow(stringResource(R.string.settings_connection), onOpenConnection)
|
||||
RowDivider()
|
||||
@@ -140,7 +137,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()
|
||||
@@ -174,8 +171,6 @@ fun ConnectionSettingsScreen(
|
||||
onEsp32TransportChange: (Esp32Transport) -> Unit = {},
|
||||
outgoingMessage: OutgoingMessage = OutgoingMessage.CAM,
|
||||
onOutgoingMessageChange: (OutgoingMessage) -> Unit = {},
|
||||
esp32RxPath: Esp32RxPath = Esp32RxPath.V2X_RX,
|
||||
onEsp32RxPathChange: (Esp32RxPath) -> Unit = {},
|
||||
signOutgoing: Boolean = true,
|
||||
onSignOutgoingChange: (Boolean) -> Unit = {},
|
||||
onBack: () -> Unit,
|
||||
@@ -253,21 +248,6 @@ fun ConnectionSettingsScreen(
|
||||
onSecond = { onOutgoingMessageChange(OutgoingMessage.VAM) },
|
||||
)
|
||||
Divider()
|
||||
TwoWayChoice(
|
||||
label = stringResource(R.string.settings_esp32_rx_path),
|
||||
first = stringResource(R.string.settings_esp32_rx_v2x),
|
||||
second = stringResource(R.string.settings_esp32_rx_raw),
|
||||
firstSelected = esp32RxPath == Esp32RxPath.V2X_RX,
|
||||
onFirst = { onEsp32RxPathChange(Esp32RxPath.V2X_RX) },
|
||||
onSecond = { onEsp32RxPathChange(Esp32RxPath.RAW_FRAME) },
|
||||
)
|
||||
Text(
|
||||
stringResource(if (esp32RxPath == Esp32RxPath.V2X_RX) R.string.settings_esp32_rx_v2x_note else R.string.settings_esp32_rx_raw_note),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
Divider()
|
||||
SettingToggleRow(
|
||||
label = stringResource(R.string.settings_esp32_sign),
|
||||
checked = signOutgoing,
|
||||
@@ -387,51 +367,19 @@ fun SensorsSettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings > Ride. Replaced the old Units screen: the app is metric throughout, so that switch had
|
||||
* nothing to switch. Where the phone rides, and whether the V2X data logger also records the motion
|
||||
* sensors and raw GPS for sensor fusion (`docs/07-sensor-fusion-logging.md`).
|
||||
*/
|
||||
@Composable
|
||||
fun RideSettingsScreen(
|
||||
phoneMount: PhoneMount,
|
||||
onPhoneMount: (PhoneMount) -> Unit,
|
||||
fusionLogging: Boolean,
|
||||
onFusionLogging: (Boolean) -> Unit,
|
||||
fun UnitsSettingsScreen(
|
||||
useMetric: Boolean,
|
||||
onUseMetric: (Boolean) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
SubScreen(stringResource(R.string.settings_ride), onBack) {
|
||||
Text(
|
||||
stringResource(R.string.settings_ride_mount_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SubScreen(stringResource(R.string.settings_units), onBack) {
|
||||
SectionCard {
|
||||
Choice(
|
||||
label = stringResource(R.string.settings_ride_mount),
|
||||
options = PhoneMount.entries.map { it to stringResource(phoneMountLabel(it)) },
|
||||
selected = phoneMount,
|
||||
onSelect = onPhoneMount,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.settings_ride_fusion_log_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SectionCard {
|
||||
SettingToggleRow(stringResource(R.string.settings_ride_fusion_log), fusionLogging, onFusionLogging)
|
||||
SettingToggleRow(stringResource(R.string.settings_metric), useMetric, onUseMetric)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The display name of a [PhoneMount]; also used by the V2X logger screen. */
|
||||
internal fun phoneMountLabel(mount: PhoneMount): Int = when (mount) {
|
||||
PhoneMount.HANDLEBAR -> R.string.settings_ride_mount_handlebar
|
||||
PhoneMount.BAG -> R.string.settings_ride_mount_bag
|
||||
PhoneMount.POCKET -> R.string.settings_ride_mount_pocket
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun MqttSettingsScreen(
|
||||
mqttPrefs: MqttPrefs,
|
||||
@@ -500,7 +448,6 @@ fun DeveloperSettingsScreen(
|
||||
state: SensorUiState,
|
||||
onDeveloperMode: (Boolean) -> Unit,
|
||||
onOpenSensorMonitor: () -> Unit,
|
||||
onOpenV2xLogger: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
SubScreen(stringResource(R.string.settings_developer), onBack) {
|
||||
@@ -510,9 +457,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))
|
||||
@@ -537,7 +481,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),
|
||||
@@ -751,45 +695,11 @@ private fun TwoWayChoice(
|
||||
}
|
||||
}
|
||||
|
||||
/** [TwoWayChoice] for any number of options: a labelled row of outlined buttons, the selected one filled. */
|
||||
@Composable
|
||||
private fun <T> Choice(
|
||||
label: String,
|
||||
options: List<Pair<T, String>>,
|
||||
selected: T,
|
||||
onSelect: (T) -> Unit,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
for ((value, text) in options) {
|
||||
val isSelected = value == selected
|
||||
OutlinedButton(
|
||||
onClick = { onSelect(value) },
|
||||
modifier = Modifier.weight(1f),
|
||||
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 8.dp),
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
|
||||
contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
) { Text(text, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, maxLines = 1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
|
||||
|
||||
@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(
|
||||
@@ -813,7 +723,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,
|
||||
|
||||
@@ -31,11 +31,7 @@ import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.hawhamburg.micr0bu.R
|
||||
import com.hawhamburg.micr0bu.domain.cam.Cam
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||
import com.hawhamburg.micr0bu.domain.map.lanePoints
|
||||
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
|
||||
import com.hawhamburg.micr0bu.domain.spat.Turn
|
||||
import com.hawhamburg.micr0bu.domain.usecase.AlertLevel
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||
import org.osmdroid.config.Configuration
|
||||
@@ -44,7 +40,6 @@ import org.osmdroid.util.GeoPoint
|
||||
import org.osmdroid.views.CustomZoomButtonsController
|
||||
import org.osmdroid.views.MapView
|
||||
import org.osmdroid.views.overlay.Marker
|
||||
import org.osmdroid.views.overlay.Polyline
|
||||
|
||||
/**
|
||||
* V2X Monitor live map (Phase 03, Section 13) — the map body behind [V2xMapScreen], plotting the
|
||||
@@ -54,9 +49,7 @@ import org.osmdroid.views.overlay.Polyline
|
||||
* Marker vocabulary, one shape per message type so the map reads without a legend:
|
||||
* - CAM — teardrop pin, tinted by that station's most severe active alert level
|
||||
* - DENM — hazard warning triangle
|
||||
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit. With the
|
||||
* intersection's MAPEM it stands on the MAPEM's reference point and its lanes are drawn: each
|
||||
* ingress lane in the colour of its straight-ahead light (else its first), egress lanes grey
|
||||
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit
|
||||
*
|
||||
* Unlike [MapScreen] this has no phone-GNSS-only fallback: [own] always reflects whichever ego
|
||||
* source [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository] currently trusts (obu_gnss /
|
||||
@@ -76,7 +69,7 @@ fun V2xLiveMapView(
|
||||
remotes: Map<Long, Cam>,
|
||||
alerts: List<UseCaseAlert>,
|
||||
denms: List<DenmEvent> = emptyList(),
|
||||
lights: List<TrafficLight> = emptyList(),
|
||||
spats: List<SpatIntersection> = emptyList(),
|
||||
followOwn: Boolean = true,
|
||||
onUserPanned: () -> Unit = {},
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -99,7 +92,6 @@ fun V2xLiveMapView(
|
||||
// tint applied would recolour every pin on the map.
|
||||
val icons = remember(context) { MapIcons(context) }
|
||||
val markers = remember { mutableMapOf<String, Marker>() }
|
||||
val lanes = remember { mutableMapOf<String, Polyline>() }
|
||||
|
||||
val mapViewRef = remember { mutableStateOf<MapView?>(null) }
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
@@ -151,17 +143,14 @@ fun V2xLiveMapView(
|
||||
update = { mv ->
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
// Intersections we can actually place: at the MAPEM's reference point when its MAPEM
|
||||
// has been heard, else at the sending RSU's own CAM position (SPATEM has no geometry).
|
||||
val locatedSpats = lights.mapNotNull { light ->
|
||||
val spat = light.signal ?: return@mapNotNull null
|
||||
val at = light.geometry?.let { GeoPoint(it.refLatitude, it.refLongitude) }
|
||||
?: remotes[spat.stationId]?.let { rsu -> GeoPoint(rsu.latitude, rsu.longitude) }
|
||||
at?.let { Triple(light, spat, it) }
|
||||
// Intersections we can actually place: SPATEM carries signal state but no geometry
|
||||
// (that is MAPEM's job), so the only position available is the sending RSU's own CAM.
|
||||
val locatedSpats = spats.mapNotNull { spat ->
|
||||
remotes[spat.stationId]?.let { rsu -> spat to rsu }
|
||||
}
|
||||
// An RSU drawn as a traffic light must not also be drawn as a CAM pin underneath it:
|
||||
// two markers on one point, the lower one unreachable.
|
||||
val spatStationIds = locatedSpats.map { (_, spat, _) -> spat.stationId }.toSet()
|
||||
val spatStationIds = locatedSpats.map { (spat, _) -> spat.stationId }.toSet()
|
||||
|
||||
val live = mutableSetOf<String>()
|
||||
|
||||
@@ -212,38 +201,13 @@ fun V2xLiveMapView(
|
||||
}
|
||||
}
|
||||
|
||||
val liveLanes = mutableSetOf<String>()
|
||||
lights.forEach { light ->
|
||||
val geometry = light.geometry ?: return@forEach
|
||||
val signalled = light.approaches.associateBy { it.lane.laneId }
|
||||
geometry.lanes.forEach lane@{ lane ->
|
||||
val points = geometry.lanePoints(lane)
|
||||
if (points.size < 2) return@lane
|
||||
val key = "${light.key}#${lane.laneId}"
|
||||
liveLanes += key
|
||||
val approach = signalled[lane.laneId]
|
||||
val exit = approach?.let { a -> a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull() }
|
||||
val own = light.ownApproach?.approach?.lane?.laneId == lane.laneId
|
||||
lanes.getOrPut(key) { Polyline(mv) }.apply {
|
||||
setPoints(points.map { GeoPoint(it.latitude, it.longitude) })
|
||||
outlinePaint.color = if (approach == null) LANE_GREY else exit?.movement?.current?.phase.toLaneColor()
|
||||
outlinePaint.strokeWidth = if (approach == null) 4f else if (own) 14f else 9f
|
||||
title = lane.name ?: context.getString(R.string.v2x_lane_fallback, lane.laneId)
|
||||
}
|
||||
}
|
||||
}
|
||||
lanes.keys.retainAll { it in liveLanes }
|
||||
|
||||
locatedSpats.forEach { (light, spat, at) ->
|
||||
// On the rider's lane, that lane's light speaks for the intersection.
|
||||
val phase = light.ownApproach?.approach?.let { a ->
|
||||
(a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull())?.movement?.current?.phase
|
||||
}?.toLamp() ?: spat.leadingPhase(now)
|
||||
locatedSpats.forEach { (spat, rsu) ->
|
||||
val phase = spat.leadingPhase(now)
|
||||
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
|
||||
position = at
|
||||
position = GeoPoint(rsu.latitude, rsu.longitude)
|
||||
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
|
||||
icon = icons.signal(phase)
|
||||
title = light.name ?: context.getString(
|
||||
title = context.getString(
|
||||
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
|
||||
)
|
||||
snippet = spat.state.movements.joinToString(" · ") { movement ->
|
||||
@@ -261,8 +225,6 @@ fun V2xLiveMapView(
|
||||
(key in live).also { kept -> if (!kept) markers[key]?.closeInfoWindow() }
|
||||
}
|
||||
mv.overlays.clear()
|
||||
// Lanes first, so every marker draws over them.
|
||||
lanes.values.forEach { mv.overlays.add(it) }
|
||||
markers.entries
|
||||
.sortedBy { (key, _) -> key.drawOrder() }
|
||||
.forEach { (_, marker) -> mv.overlays.add(marker) }
|
||||
@@ -293,7 +255,6 @@ fun V2xLiveMapView(
|
||||
// guarantees no further update after it.
|
||||
onRelease = {
|
||||
markers.clear()
|
||||
lanes.clear()
|
||||
it.onDetach()
|
||||
},
|
||||
modifier = modifier.fillMaxSize(),
|
||||
@@ -367,35 +328,25 @@ private enum class SignalLamp(val drawableRes: Int) {
|
||||
/**
|
||||
* The lamp to light for this intersection.
|
||||
*
|
||||
* Used when the rider is not on one of the intersection's ingress lanes (or no MAPEM is known):
|
||||
* then no signal group is theirs, and this follows the rule the Dashboard's SignalCard uses — the
|
||||
* group changing soonest speaks for the intersection — so it reads the same in both places.
|
||||
* Without MAPEM there is no lane geometry, so there is no way to know which of an intersection's
|
||||
* signal groups applies to the rider's own approach. This follows the rule the Dashboard's
|
||||
* SignalCard already uses — the group changing soonest speaks for the intersection — so the same
|
||||
* intersection reads the same way in both places rather than inventing a second convention.
|
||||
*/
|
||||
private fun SpatIntersection.leadingPhase(nowMs: Long): SignalLamp {
|
||||
val leading = state.movements.minByOrNull { movement ->
|
||||
movement.current?.secondsUntil(nowMs)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
||||
}
|
||||
return leading?.current?.phase.toLamp()
|
||||
val phase = leading?.current?.phase
|
||||
return when {
|
||||
phase == null -> SignalLamp.DARK
|
||||
phase.isGo -> SignalLamp.GREEN
|
||||
phase.isStop -> SignalLamp.RED
|
||||
phase.isTransition -> SignalLamp.AMBER
|
||||
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
|
||||
}
|
||||
}
|
||||
|
||||
private fun SignalPhase?.toLamp(): SignalLamp = when {
|
||||
this == null -> SignalLamp.DARK
|
||||
isGo -> SignalLamp.GREEN
|
||||
isStop -> SignalLamp.RED
|
||||
isTransition -> SignalLamp.AMBER
|
||||
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
|
||||
}
|
||||
|
||||
/** Lane colour on the map: the traffic-light colours, with a lane whose group is silent dark grey. */
|
||||
private fun SignalPhase?.toLaneColor(): Int = when (toLamp()) {
|
||||
SignalLamp.GREEN -> 0xFF4CAF50.toInt()
|
||||
SignalLamp.RED -> 0xFFE53935.toInt()
|
||||
SignalLamp.AMBER -> 0xFFFFC107.toInt()
|
||||
SignalLamp.DARK -> 0xFF546E7A.toInt()
|
||||
}
|
||||
|
||||
private const val LANE_GREY = 0x9978909C.toInt()
|
||||
|
||||
/**
|
||||
* Marker tint per severity, matching [UseCaseAlertPanel]'s colours so the same station reads the
|
||||
* same way in both places. Stations with no active alert stay neutral grey-blue rather than green:
|
||||
|
||||
@@ -1,262 +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),
|
||||
)
|
||||
Divider()
|
||||
DisabledRow(
|
||||
stringResource(R.string.v2xlog_fusion),
|
||||
if (state.fusionLogging && state.phoneMount != null) {
|
||||
stringResource(R.string.v2xlog_fusion_on, stringResource(phoneMountLabel(state.phoneMount)))
|
||||
} else {
|
||||
stringResource(R.string.v2xlog_fusion_off)
|
||||
},
|
||||
)
|
||||
if (state.fusionLogging) {
|
||||
Divider()
|
||||
DisabledRow(stringResource(R.string.v2xlog_imu), state.imuSamples.toString())
|
||||
Divider()
|
||||
DisabledRow(stringResource(R.string.v2xlog_phone_gps), fixAge(state.phoneGpsFixAgeMs))
|
||||
}
|
||||
}
|
||||
if (state.total == 0) {
|
||||
Text(
|
||||
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)))
|
||||
}
|
||||
@@ -61,17 +61,17 @@ fun V2xMapScreen(
|
||||
val stations by viewModel.stationsInRange.collectAsState()
|
||||
val alerts by viewModel.useCaseAlerts.collectAsState()
|
||||
val denms by viewModel.denmEvents.collectAsState()
|
||||
val lights by viewModel.trafficLights.collectAsState()
|
||||
val spats by viewModel.spatIntersections.collectAsState()
|
||||
|
||||
// Follow is on until the rider touches the map, and comes back when they ask for it. Without
|
||||
// the hand-over, every incoming CAM would drag the viewport back to the ego position and the
|
||||
// map could not be panned at all while traffic is flowing.
|
||||
var followOwn by remember { mutableStateOf(true) }
|
||||
|
||||
// SPATEM carries no geometry of its own, so an intersection can only be placed if its MAPEM or
|
||||
// its RSU's CAM has been heard too. Saying so is better than silently dropping it: "the map shows two
|
||||
// SPATEM carries no geometry of its own, so an intersection can only be placed if its RSU has
|
||||
// also been heard over CAM. Saying so is better than silently dropping it: "the map shows two
|
||||
// of the three lights I can see in the list" is otherwise an unexplained discrepancy.
|
||||
val unlocatedSpats = lights.count { it.geometry == null && it.signal?.stationId !in stations.keys }
|
||||
val unlocatedSpats = spats.count { it.stationId !in stations.keys }
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
V2xLiveMapView(
|
||||
@@ -79,7 +79,7 @@ fun V2xMapScreen(
|
||||
remotes = stations,
|
||||
alerts = alerts,
|
||||
denms = denms,
|
||||
lights = lights,
|
||||
spats = spats,
|
||||
followOwn = followOwn,
|
||||
onUserPanned = { followOwn = false },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -125,7 +125,7 @@ fun V2xMapScreen(
|
||||
MapCount(
|
||||
icon = Icons.Default.Traffic,
|
||||
tint = SignalGreenDot,
|
||||
count = lights.size,
|
||||
count = spats.size,
|
||||
label = stringResource(R.string.v2x_map_legend_spat),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -15,17 +15,12 @@ import com.hawhamburg.micr0bu.data.transport.TransportType
|
||||
import com.hawhamburg.micr0bu.data.transport.UsbNetworkDetector
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||
import com.hawhamburg.micr0bu.data.transport.StationStatus
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmParser
|
||||
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
|
||||
import com.hawhamburg.micr0bu.domain.map.MapPoint
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
|
||||
import com.hawhamburg.micr0bu.domain.denm.DenmUseCase
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
|
||||
@@ -118,13 +113,6 @@ class MqttViewModel @Inject constructor(
|
||||
viewModelScope.launch { obuHardwarePrefs.setOutgoingMessage(message) }
|
||||
}
|
||||
|
||||
val esp32RxPath: StateFlow<Esp32RxPath> = obuHardwarePrefs.esp32RxPathFlow
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
|
||||
|
||||
fun setEsp32RxPath(path: Esp32RxPath) {
|
||||
viewModelScope.launch { obuHardwarePrefs.setEsp32RxPath(path) }
|
||||
}
|
||||
|
||||
val signOutgoing: StateFlow<Boolean> = obuHardwarePrefs.signOutgoingFlow
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
||||
|
||||
@@ -281,49 +269,6 @@ class MqttViewModel @Inject constructor(
|
||||
.sortedByDescending { it.timestamp }
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
|
||||
/**
|
||||
* Intersection geometry heard over MAPEM, oldest first. Kept per intersection AND revision:
|
||||
* two revisions of one intersection can be on air at once, and a SPATEM's signal groups mean
|
||||
* whatever its own revision's MAPEM says ([TrafficLights.pickGeometry]).
|
||||
*/
|
||||
private val mapGeometries: StateFlow<List<IntersectionGeometry>> = combine(
|
||||
camUseCaseRepository.decodedMap
|
||||
.runningFold(emptyMap<String, Pair<IntersectionGeometry, Long>>()) { acc, map ->
|
||||
acc + map.intersections.associate { "${it.key}#${it.revision}" to (it to map.timestamp) }
|
||||
},
|
||||
tickerFlow(MAP_EXPIRY_TICK_MS),
|
||||
) { byKey, _ ->
|
||||
val now = System.currentTimeMillis()
|
||||
byKey.values
|
||||
.filter { (_, heardAt) -> now - heardAt <= MAP_TTL_MS }
|
||||
.sortedBy { (_, heardAt) -> heardAt }
|
||||
.map { (geometry, _) -> geometry }
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
|
||||
/**
|
||||
* [spatIntersections] with each SPATEM's signal groups placed on its MAPEM's lanes, and the
|
||||
* rider's own approach picked from their position and heading. The MAPEM is one heard on air or
|
||||
* one the app ships with ([TrafficLights.geometryFor]). An intersection with neither is still
|
||||
* listed, with no lanes: its signal groups stay bare numbers.
|
||||
*/
|
||||
val trafficLights: StateFlow<List<TrafficLight>> = combine(
|
||||
spatIntersections,
|
||||
mapGeometries,
|
||||
camUseCaseRepository.storedMaps,
|
||||
camUseCaseRepository.ownPosition,
|
||||
) { spats, live, stored, own ->
|
||||
val position = own?.let { MapPoint(it.latitude, it.longitude) }
|
||||
spats.map { spat ->
|
||||
TrafficLights.join(
|
||||
signal = spat,
|
||||
geometry = TrafficLights.geometryFor(spat.key, spat.state.revision, live, stored, position),
|
||||
own = position,
|
||||
ownHeadingDeg = own?.headingDeg,
|
||||
ownSpeedMps = own?.speedMps,
|
||||
)
|
||||
}
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
|
||||
/** Emits immediately, then every [periodMs], purely to re-trigger a time-dependent combine. */
|
||||
private fun tickerFlow(periodMs: Long): Flow<Long> = flow {
|
||||
while (true) {
|
||||
@@ -354,13 +299,6 @@ class MqttViewModel @Inject constructor(
|
||||
const val SPAT_TTL_MS = 15_000L
|
||||
const val SPAT_EXPIRY_TICK_MS = 2_000L
|
||||
|
||||
/**
|
||||
* MAPEM repeats at about 1 Hz and its geometry is static, so a minute of silence is generous;
|
||||
* a light is only ever shown while its SPATEM is live anyway.
|
||||
*/
|
||||
const val MAP_TTL_MS = 60_000L
|
||||
const val MAP_EXPIRY_TICK_MS = 5_000L
|
||||
|
||||
/** RSU CAMs arrive at ~2 Hz, same as any other station, so the same window applies. */
|
||||
const val RSU_TTL_MS = 15_000L
|
||||
const val RSU_EXPIRY_TICK_MS = 2_000L
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package com.hawhamburg.micr0bu.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.hawhamburg.micr0bu.data.RidePreferences
|
||||
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
/** Backs Settings > Ride. */
|
||||
@HiltViewModel
|
||||
class RideSettingsViewModel @Inject constructor(
|
||||
private val prefs: RidePreferences,
|
||||
) : ViewModel() {
|
||||
|
||||
val phoneMount: StateFlow<PhoneMount> =
|
||||
prefs.phoneMountFlow.stateIn(viewModelScope, SharingStarted.Eagerly, PhoneMount.DEFAULT)
|
||||
|
||||
val fusionLogging: StateFlow<Boolean> =
|
||||
prefs.fusionLoggingFlow.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
|
||||
fun setPhoneMount(mount: PhoneMount) {
|
||||
viewModelScope.launch { prefs.setPhoneMount(mount) }
|
||||
}
|
||||
|
||||
fun setFusionLogging(enabled: Boolean) {
|
||||
viewModelScope.launch { prefs.setFusionLogging(enabled) }
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ data class SensorUiState(
|
||||
val barometerEnabled: Boolean = true,
|
||||
val gnssEnabled: Boolean = true,
|
||||
val developerMode: Boolean = true,
|
||||
val useMetric: Boolean = true,
|
||||
val darkTheme: Boolean = true,
|
||||
)
|
||||
|
||||
@@ -294,5 +295,6 @@ class SensorViewModel(application: Application) : AndroidViewModel(application)
|
||||
if (!v) _state.value = _state.value.copy(gnss = null)
|
||||
}
|
||||
fun setDeveloperMode(v: Boolean) { _state.value = _state.value.copy(developerMode = v) }
|
||||
fun setUseMetric(v: Boolean) { _state.value = _state.value.copy(useMetric = v) }
|
||||
fun setDarkTheme(v: Boolean) { _state.value = _state.value.copy(darkTheme = v) }
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,6 @@
|
||||
<string name="dash_signal_phase_dark">Dunkel</string>
|
||||
<string name="dash_signal_phase_unknown">Unbekannt</string>
|
||||
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
|
||||
<string name="dash_signal_own_approach">%1$s · %2$.0f m bis zur Haltelinie</string>
|
||||
<string name="dash_signal_map_outdated">Fahrstreifenkarte veraltet</string>
|
||||
<string name="v2x_lane_fallback">Fahrstreifen %1$d</string>
|
||||
<string name="stat_pressure">Luftdruck</string>
|
||||
<string name="stat_altitude">Höhe</string>
|
||||
<string name="stat_heading">Richtung</string>
|
||||
@@ -78,9 +75,9 @@
|
||||
<string name="conn_bluetooth">Bluetooth</string>
|
||||
<string name="conn_bluetooth_phase3">Bluetooth</string>
|
||||
<string name="conn_bluetooth_phase3_desc">Bluetooth-Verbindung ist für Phase 03 geplant und noch nicht implementiert.</string>
|
||||
<string name="conn_esp32_title">ESP32-C5</string>
|
||||
<string name="conn_esp32_title">ESP32-C5 (USB Seriell)</string>
|
||||
<string name="conn_esp32_phase3_desc">Die USB-Seriell-Verbindung zum ESP32-C5 ist für Phase 03 vorgesehen, aber noch nicht funktionsfähig - dafür muss zuerst das ESP32-Firmware-Protokoll nach Kotlin übersetzt werden.</string>
|
||||
<string name="conn_esp32_state_disconnected">Nicht verbunden - Verbinden antippen (USB-C-Verbindung: ESP32-C5 zuerst an den nativen USB-C-Port anschließen).</string>
|
||||
<string name="conn_esp32_state_disconnected">Nicht verbunden - ESP32-C5 an den nativen USB-C-Port anschließen und Verbinden antippen.</string>
|
||||
<string name="conn_esp32_state_device_attached">Gerät erkannt, wird geöffnet…</string>
|
||||
<string name="conn_esp32_state_permission_requested">Warte auf USB-Berechtigung…</string>
|
||||
<string name="conn_esp32_state_connected">Verbunden</string>
|
||||
@@ -169,14 +166,8 @@
|
||||
<string name="settings_gyro">Gyroskop</string>
|
||||
<string name="settings_magnet">Magnetometer</string>
|
||||
<string name="settings_baro">Barometer</string>
|
||||
<string name="settings_ride">Fahrt</string>
|
||||
<string name="settings_ride_mount">Position des Telefons</string>
|
||||
<string name="settings_ride_mount_handlebar">Lenker</string>
|
||||
<string name="settings_ride_mount_bag">Tasche</string>
|
||||
<string name="settings_ride_mount_pocket">Hosentasche</string>
|
||||
<string name="settings_ride_mount_desc">Wo das Telefon mitfährt: in einer Lenkerhalterung, in einer Tasche am Fahrrad oder in einer Hosentasche bzw. einem Rucksack. Die Sensorfusion wertet die Bewegungssensoren je nach Position anders aus, und jedes V2X-Log hält sie fest.</string>
|
||||
<string name="settings_ride_fusion_log">Bewegungssensoren aufzeichnen</string>
|
||||
<string name="settings_ride_fusion_log_desc">Für Testfahrten zur Sensorfusion: Der V2X-Datenlogger zeichnet zusätzlich Beschleunigungssensor, Gyroskop und Schwerkraft mit 100 Hz auf, sowie rohe GPS-Positionen neben der fusionierten Position. Das sind einige zehn MB pro Stunde.</string>
|
||||
<string name="settings_units">Einheiten</string>
|
||||
<string name="settings_metric">Metrisch (m, km/h, hPa)</string>
|
||||
<string name="settings_mqtt_section">MQTT-Broker</string>
|
||||
<string name="settings_broker_ip">Broker-IP</string>
|
||||
<string name="settings_port">Port</string>
|
||||
@@ -329,12 +320,7 @@
|
||||
<string name="v2x_spat_countdown">%1$.0f s</string>
|
||||
<string name="settings_esp32_link">ESP32-C5-Verbindung</string>
|
||||
<string name="settings_esp32_link_ble">Bluetooth</string>
|
||||
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, zuerst das richtige in den Android-Bluetooth-Einstellungen koppeln. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
|
||||
<string name="settings_esp32_rx_path">Empfangspfad</string>
|
||||
<string name="settings_esp32_rx_v2x">V2X_RX</string>
|
||||
<string name="settings_esp32_rx_raw">Rohframes</string>
|
||||
<string name="settings_esp32_rx_v2x_note">Die Platine entpackt jedes empfangene Frame und sendet die fertige Nachricht, signiert oder nicht (MicrOBU-Erweiterung, bis 494 Byte). Klein und immer aktiv.</string>
|
||||
<string name="settings_esp32_rx_raw_note">Debug: Die Platine sendet das ganze Funkframe (RAW_FRAME aus der Spezifikation, bei Bedarf fragmentiert) und die App entpackt es. Keine 494-Byte-Grenze, aber Frames können bei ausgelastetem Link verloren gehen und es braucht mehr Bandbreite, besonders über Bluetooth.</string>
|
||||
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Die Platine wirbt nur, solange ihr USB-C-Port nicht benutzt wird. BLE teilt sich das Funk-Frontend mit ITS-G5; der Einfluss auf den 5,9-GHz-Empfang ist noch nicht gemessen.</string>
|
||||
<string name="settings_esp32_message">Senden während der Aufzeichnung</string>
|
||||
<string name="settings_esp32_message_cam">CAM</string>
|
||||
<string name="settings_esp32_message_vam">VAM</string>
|
||||
@@ -344,42 +330,6 @@
|
||||
<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_fusion">Daten für Sensorfusion</string>
|
||||
<string name="v2xlog_fusion_off">aus (Einstellungen > Fahrt)</string>
|
||||
<string name="v2xlog_fusion_on">an · Telefon: %1$s</string>
|
||||
<string name="v2xlog_imu">Bewegungssensor-Messwerte</string>
|
||||
<string name="v2xlog_phone_gps">Telefon-GPS (roh)</string>
|
||||
<string name="v2xlog_fix_age">Fix vor %1$d s</string>
|
||||
<string name="v2xlog_no_fix">kein Fix</string>
|
||||
<string name="v2xlog_not_available">nicht verfügbar</string>
|
||||
<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>
|
||||
|
||||
@@ -45,9 +45,6 @@
|
||||
<string name="dash_signal_phase_dark">Dark</string>
|
||||
<string name="dash_signal_phase_unknown">Unknown</string>
|
||||
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
|
||||
<string name="dash_signal_own_approach">%1$s · %2$.0f m to the stop line</string>
|
||||
<string name="dash_signal_map_outdated">Lane map out of date</string>
|
||||
<string name="v2x_lane_fallback">Lane %1$d</string>
|
||||
<string name="stat_pressure">Pressure</string>
|
||||
<string name="stat_altitude">Altitude</string>
|
||||
<string name="stat_heading">Heading</string>
|
||||
@@ -79,9 +76,9 @@
|
||||
<string name="conn_bluetooth">Bluetooth</string>
|
||||
<string name="conn_bluetooth_phase3">Bluetooth</string>
|
||||
<string name="conn_bluetooth_phase3_desc">Bluetooth connection is planned for Phase 03 and is not yet implemented.</string>
|
||||
<string name="conn_esp32_title">ESP32-C5</string>
|
||||
<string name="conn_esp32_title">ESP32-C5 (USB Serial)</string>
|
||||
<string name="conn_esp32_phase3_desc">USB-serial connection to the ESP32-C5 is scaffolded for Phase 03 but not yet functional - it needs the ESP32 firmware protocol translated to Kotlin first.</string>
|
||||
<string name="conn_esp32_state_disconnected">Not connected - tap Connect (USB-C link: plug the ESP32-C5 into the native USB-C port first).</string>
|
||||
<string name="conn_esp32_state_disconnected">Not connected - plug the ESP32-C5 into the native USB-C port and tap Connect.</string>
|
||||
<string name="conn_esp32_state_device_attached">Device detected, opening…</string>
|
||||
<string name="conn_esp32_state_permission_requested">Waiting for USB permission…</string>
|
||||
<string name="conn_esp32_state_connected">Connected</string>
|
||||
@@ -170,14 +167,8 @@
|
||||
<string name="settings_gyro">Gyroscope</string>
|
||||
<string name="settings_magnet">Magnetometer</string>
|
||||
<string name="settings_baro">Barometer</string>
|
||||
<string name="settings_ride">Ride</string>
|
||||
<string name="settings_ride_mount">Phone position</string>
|
||||
<string name="settings_ride_mount_handlebar">Handlebar</string>
|
||||
<string name="settings_ride_mount_bag">Bag</string>
|
||||
<string name="settings_ride_mount_pocket">Pocket</string>
|
||||
<string name="settings_ride_mount_desc">Where the phone rides: on a handlebar mount, in a bag on the bike, or in a pocket or backpack. Sensor fusion reads the motion sensors differently for each, and every V2X log records it.</string>
|
||||
<string name="settings_ride_fusion_log">Record motion sensors</string>
|
||||
<string name="settings_ride_fusion_log_desc">For sensor fusion test rides: the V2X data logger also records accelerometer, gyroscope and gravity at 100 Hz, and raw GPS fixes next to the fused location. Adds tens of MB per hour.</string>
|
||||
<string name="settings_units">Units</string>
|
||||
<string name="settings_metric">Metric (m, km/h, hPa)</string>
|
||||
<string name="settings_mqtt_section">MQTT Broker</string>
|
||||
<string name="settings_broker_ip">Broker IP</string>
|
||||
<string name="settings_port">Port</string>
|
||||
@@ -336,12 +327,7 @@
|
||||
<string name="trip_review_title">Trip Review</string>
|
||||
<string name="settings_esp32_link">ESP32-C5 link</string>
|
||||
<string name="settings_esp32_link_ble">Bluetooth</string>
|
||||
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. With several micrOBUs nearby, pair the right one in Android\'s Bluetooth settings first. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
|
||||
<string name="settings_esp32_rx_path">Receive path</string>
|
||||
<string name="settings_esp32_rx_v2x">V2X_RX</string>
|
||||
<string name="settings_esp32_rx_raw">Raw frames</string>
|
||||
<string name="settings_esp32_rx_v2x_note">The board unpacks every received frame and sends the finished message, signed or not (MicrOBU extension, up to 494 bytes). Small and always on.</string>
|
||||
<string name="settings_esp32_rx_raw_note">Debug: the board sends the whole radio frame (the spec\'s RAW_FRAME, fragmented if large) and the app unpacks it. No 494-byte limit, but frames can be lost when the link is busy and it needs more bandwidth, especially over Bluetooth.</string>
|
||||
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. The board only advertises while nothing uses its USB-C port. BLE shares the radio front end with ITS-G5; its effect on 5.9 GHz reception has not been measured yet.</string>
|
||||
<string name="settings_esp32_message">Transmit while recording</string>
|
||||
<string name="settings_esp32_message_cam">CAM</string>
|
||||
<string name="settings_esp32_message_vam">VAM</string>
|
||||
@@ -351,42 +337,6 @@
|
||||
<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_fusion">Sensor fusion data</string>
|
||||
<string name="v2xlog_fusion_off">off (Settings > Ride)</string>
|
||||
<string name="v2xlog_fusion_on">on · phone on %1$s</string>
|
||||
<string name="v2xlog_imu">Motion sensor samples</string>
|
||||
<string name="v2xlog_phone_gps">Phone GPS (raw)</string>
|
||||
<string name="v2xlog_fix_age">fix %1$d s ago</string>
|
||||
<string name="v2xlog_no_fix">no fix</string>
|
||||
<string name="v2xlog_not_available">not available</string>
|
||||
<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,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
|
||||
|
||||
@@ -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,200 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.data.transport.LinkMessage
|
||||
import com.hawhamburg.micr0bu.data.transport.LinkReassembly
|
||||
import com.hawhamburg.micr0bu.data.transport.RawFrame
|
||||
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** Fragment reassembly as docs/station-link.pdf specifies it, and the RAW_FRAME record parser. */
|
||||
class LinkReassemblyTest {
|
||||
|
||||
private var clock = 0L
|
||||
private val reassembly = LinkReassembly { clock }
|
||||
|
||||
private fun fragment(flags: Int, seq: Int, total: Int, offset: Int, data: ByteArray, opcode: Int = LinkOpcode_RAW_FRAME) =
|
||||
LinkMessage(
|
||||
opcode, seq,
|
||||
byteArrayOf(total.toByte(), (total shr 8).toByte(), offset.toByte(), (offset shr 8).toByte()) + data,
|
||||
flags,
|
||||
)
|
||||
|
||||
private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
|
||||
|
||||
@Test
|
||||
fun `a complete message passes through unchanged`() {
|
||||
val m = LinkMessage(0x81, 5, bytes(1, 2, 3))
|
||||
assertArrayEquals(bytes(1, 2, 3), reassembly.feed(m)!!.body)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `three fragments in order become one message with flags 0`() {
|
||||
assertNull(reassembly.feed(fragment(1, 9, 6, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(2, 9, 6, 2, bytes(3, 4))))
|
||||
val whole = reassembly.feed(fragment(3, 9, 6, 4, bytes(5, 6)))!!
|
||||
assertArrayEquals(bytes(1, 2, 3, 4, 5, 6), whole.body)
|
||||
assertEquals(0, whole.flags)
|
||||
assertEquals(9, whole.sequence)
|
||||
assertEquals(LinkOpcode_RAW_FRAME, whole.opcode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a gap, a duplicate and a changed total drop the stream`() {
|
||||
assertNull(reassembly.feed(fragment(1, 1, 6, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(3, 1, 6, 4, bytes(5, 6)))) // skipped the middle
|
||||
assertNull(reassembly.feed(fragment(3, 1, 6, 2, bytes(3, 4)))) // the stream is gone: nothing completes
|
||||
assertNull(reassembly.feed(fragment(1, 2, 6, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(2, 2, 6, 0, bytes(1, 2)))) // the same offset twice
|
||||
assertNull(reassembly.feed(fragment(1, 3, 6, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(2, 3, 8, 2, bytes(3, 4)))) // total changed
|
||||
assertNull(reassembly.feed(fragment(2, 4, 6, 2, bytes(3, 4)))) // a middle without a first
|
||||
assertTrue(reassembly.dropped >= 4)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unfinished stream is discarded after two seconds of silence`() {
|
||||
assertNull(reassembly.feed(fragment(1, 7, 4, 0, bytes(1, 2))))
|
||||
clock += 2_500
|
||||
assertNull(reassembly.feed(fragment(3, 7, 4, 2, bytes(3, 4)))) // the first fragment is gone
|
||||
assertNull(reassembly.feed(fragment(1, 8, 4, 0, bytes(1, 2))))
|
||||
clock += 1_500 // still inside the window
|
||||
assertNotNull(reassembly.feed(fragment(3, 8, 4, 2, bytes(3, 4))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `at most eight streams are held and the ninth is refused`() {
|
||||
for (s in 1..8) assertNull(reassembly.feed(fragment(1, s, 4, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(1, 9, 4, 0, bytes(1, 2))))
|
||||
assertNull(reassembly.feed(fragment(3, 9, 4, 2, bytes(3, 4)))) // refused, so nothing to complete
|
||||
assertNotNull(reassembly.feed(fragment(3, 1, 4, 2, bytes(3, 4)))) // the held ones still finish
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an indication of 65535 octets is the largest, more is refused, a message of 2000 octets works`() {
|
||||
val big = ByteArray(2000) { it.toByte() }
|
||||
val chunk = 500
|
||||
var out: LinkMessage? = null
|
||||
var offset = 0
|
||||
while (offset < big.size) {
|
||||
val n = minOf(chunk, big.size - offset)
|
||||
val flags = if (offset == 0) 1 else if (offset + n == big.size) 3 else 2
|
||||
out = reassembly.feed(fragment(flags, 11, big.size, offset, big.copyOfRange(offset, offset + n)))
|
||||
offset += n
|
||||
}
|
||||
assertArrayEquals(big, out!!.body)
|
||||
assertNull(reassembly.feed(fragment(1, 12, 65_536 + 4, 0, bytes(1, 2))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `different opcodes with the same sequence are separate streams`() {
|
||||
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(1, 2), opcode = 0x85)))
|
||||
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(9, 9), opcode = 0x81)))
|
||||
val a = reassembly.feed(fragment(3, 5, 4, 2, bytes(3, 4), opcode = 0x85))!!
|
||||
val b = reassembly.feed(fragment(3, 5, 4, 2, bytes(8, 8), opcode = 0x81))!!
|
||||
assertArrayEquals(bytes(1, 2, 3, 4), a.body)
|
||||
assertArrayEquals(bytes(9, 9, 8, 8), b.body)
|
||||
}
|
||||
|
||||
// ---- large V2X_RX, fragmented by the firmware ---------------------------------------------
|
||||
|
||||
private fun hexBytes(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
|
||||
|
||||
/**
|
||||
* `v2x_rx_fragments.tsv` is written by `test_v2x_fragments --dump` in obu-firmware/test/host: the first 888-byte
|
||||
* SPATEM and 1198-byte MAPEM of the CiT node's 2026-11-23 recording, as the firmware's own code splits them for
|
||||
* serial / BLE MTU 517 (512-octet messages) and BLE MTU 247 (244). Each line: port, UPER size, limit, V2X_RX body,
|
||||
* then the link messages in order. The app must put back exactly that body and read the message out of it.
|
||||
*/
|
||||
@Test
|
||||
fun `the firmware's fragments of a large V2X_RX reassemble to the body and parse`() {
|
||||
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
|
||||
assertEquals(4, lines.size)
|
||||
for (line in lines) {
|
||||
val f = line.split('\t')
|
||||
val port = f[0].toInt()
|
||||
val size = f[1].toInt()
|
||||
val limit = f[2].toInt()
|
||||
val body = hexBytes(f[3])
|
||||
val wires = f.drop(4).map { hexBytes(it) }
|
||||
assertTrue("$port/$size at $limit: needs fragments", wires.size >= 2)
|
||||
var whole: LinkMessage? = null
|
||||
wires.forEachIndexed { i, wire ->
|
||||
assertTrue("$port/$size at $limit: a message of ${wire.size} octets exceeds $limit", wire.size <= limit)
|
||||
val message = LinkMessage.decode(wire)!!
|
||||
assertEquals(0x90, message.opcode)
|
||||
assertEquals(if (i == 0) 1 else if (i == wires.size - 1) 3 else 2, message.flags)
|
||||
whole = reassembly.feed(message)
|
||||
if (i < wires.size - 1) assertNull(whole)
|
||||
}
|
||||
assertEquals(0x90, whole!!.opcode)
|
||||
assertEquals(0, whole!!.flags)
|
||||
assertArrayEquals(body, whole!!.body)
|
||||
val v2x = V2xRxFrame.parse(whole!!.body)!!
|
||||
assertEquals(port, v2x.btpPort)
|
||||
assertEquals(size, v2x.uper.size)
|
||||
assertEquals(if (port == 2003) 5 else 4, v2x.uper[1].toInt() and 0xFF) // ItsPduHeader.messageId: MAPEM 5, SPATEM 4
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `losing one fragment of a large V2X_RX costs that message only`() {
|
||||
val lines = javaClass.classLoader!!.getResource("v2x_rx_fragments.tsv")!!.readText().lines().filter { it.isNotBlank() }
|
||||
val f = lines.first { it.split('\t')[2] == "512" && it.split('\t')[0] == "2003" }.split('\t')
|
||||
val wires = f.drop(4).map { hexBytes(it) }
|
||||
// the first message loses its middle fragment; the same message again, in full, still completes afterwards
|
||||
val lost = wires.mapIndexedNotNull { i, w -> if (i == 1) null else LinkMessage.decode(w)!! }
|
||||
for (m in lost) assertNull(reassembly.feed(m))
|
||||
val next = wires.map { w -> LinkMessage.decode(w)!!.let { LinkMessage(it.opcode, it.sequence + 1, it.body, it.flags) } }
|
||||
var whole: LinkMessage? = null
|
||||
for (m in next) whole = reassembly.feed(m)
|
||||
assertArrayEquals(hexBytes(f[3]), whole!!.body)
|
||||
}
|
||||
|
||||
// ---- RAW_FRAME record ------------------------------------------------------------------
|
||||
|
||||
private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray {
|
||||
val h = java.io.ByteArrayOutputStream()
|
||||
fun u8(v: Int) = h.write(v and 0xFF)
|
||||
fun u16(v: Int) { u8(v); u8(v shr 8) }
|
||||
fun u32(v: Long) { u16(v.toInt()); u16((v shr 16).toInt()) }
|
||||
u32(42); u8(flags); u8(rssi)
|
||||
h.write("ITS5".toByteArray())
|
||||
u32(1_900_000_000L); u32(123_456); u16(frame.size)
|
||||
h.write(frame)
|
||||
return h.toByteArray()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a RAW_FRAME body parses into its fields and frame`() {
|
||||
val frame = ByteArray(30) { (it * 3).toByte() }
|
||||
val r = RawFrame.parse(rawBody(frame))!!
|
||||
assertEquals(42L, r.counter)
|
||||
assertTrue(r.utcTime)
|
||||
assertFalse(r.ownTransmission)
|
||||
assertEquals(-61, r.rssiDbm)
|
||||
assertEquals(1_900_000_000L, r.seconds)
|
||||
assertEquals(123_456L, r.microseconds)
|
||||
assertArrayEquals(frame, r.frame)
|
||||
assertTrue(RawFrame.parse(rawBody(frame, flags = 0x01))!!.ownTransmission)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a malformed RAW_FRAME is refused`() {
|
||||
val good = rawBody(ByteArray(10))
|
||||
assertNull(RawFrame.parse(good.copyOf(19))) // shorter than the header
|
||||
assertNull(RawFrame.parse(good.copyOf(good.size - 1))) // length field says more
|
||||
assertNull(RawFrame.parse(good + byteArrayOf(0))) // or less
|
||||
val bad = good.copyOf(); bad[6] = 'X'.code.toByte()
|
||||
assertNull(RawFrame.parse(bad)) // wrong magic
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LinkOpcode_RAW_FRAME = 0x85
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.map.LaneType
|
||||
import com.hawhamburg.micr0bu.domain.map.MapEvent
|
||||
import com.hawhamburg.micr0bu.domain.map.NodeOffset
|
||||
import com.hawhamburg.micr0bu.domain.map.lanePoints
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* [MapemUperCodec] against every distinct MAPEM on record, field by field.
|
||||
*
|
||||
* `src/test/resources/mapem/corpus.txt` holds each MAPEM's bytes followed by every field as
|
||||
* `asn1tools` decodes it with the ETSI modules in `asn1/` (written by `tools/mapem_corpus.py`):
|
||||
* 17 distinct MAPEMs from the 2026-03-18 drive (7 916 received, 288 to 1348 bytes) and the bench
|
||||
* RSU's, captured by the ESP32-C5 on 2026-10-28. [dump] renders the decoder's output in the same
|
||||
* text, so any field this decoder reads at the wrong width or in the wrong place shows up as a
|
||||
* differing line - and since UPER has no padding, as a cascade of them.
|
||||
*/
|
||||
class MapemUperCodecTest {
|
||||
|
||||
private class Sample(val hex: String, val expected: List<String>)
|
||||
|
||||
private val corpus: List<Sample> by lazy {
|
||||
val text = javaClass.classLoader!!.getResource("mapem/corpus.txt")!!.readText()
|
||||
val samples = ArrayList<Sample>()
|
||||
var hex: String? = null
|
||||
val lines = ArrayList<String>()
|
||||
fun flush() { hex?.let { samples.add(Sample(it, lines.toList())) }; lines.clear() }
|
||||
for (line in text.lines()) {
|
||||
when {
|
||||
line.startsWith("#hex ") -> { flush(); hex = line.removePrefix("#hex ") }
|
||||
line.startsWith("#") || line.isBlank() -> {}
|
||||
else -> lines.add(line)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
samples
|
||||
}
|
||||
|
||||
private fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
|
||||
private fun Int?.orNone(): String = this?.toString() ?: "None"
|
||||
|
||||
/** Same text as `tools/mapem_corpus.py`'s dump(). */
|
||||
private fun dump(m: MapEvent): List<String> {
|
||||
val out = mutableListOf("station=${m.stationId} rev=${m.msgIssueRevision}")
|
||||
for (i in m.intersections) {
|
||||
val lat = Math.round(i.refLatitude * 1e7)
|
||||
val lon = Math.round(i.refLongitude * 1e7)
|
||||
out += "I key=${i.key} rev=${i.revision} name=${i.name ?: "None"} ref=$lat,$lon " +
|
||||
"elev=${i.elevationDm.orNone()} width=${i.laneWidthCm.orNone()} " +
|
||||
"speeds=${i.speedLimits.joinToString(",") { "${it.type}:${it.speed}" }}"
|
||||
for (lane in i.lanes) {
|
||||
val dir = (if (lane.isIngress) 2 else 0) or (if (lane.isEgress) 1 else 0)
|
||||
out += "L id=${lane.laneId} name=${lane.name ?: "None"} in=${lane.ingressApproach.orNone()} " +
|
||||
"eg=${lane.egressApproach.orNone()} dir=$dir share=${lane.sharedWith} " +
|
||||
"type=${lane.type.ordinal} attr=${lane.typeAttributes} man=${lane.maneuvers?.bits.orNone()}"
|
||||
for (node in lane.nodes) {
|
||||
val pos = when (val o = node.offset) {
|
||||
is NodeOffset.Xy -> "xy=${o.xCm},${o.yCm}"
|
||||
is NodeOffset.LatLon -> "ll=${o.latitude},${o.longitude}"
|
||||
}
|
||||
out += "N $pos local=${node.localAttributes.joinToString(",")} " +
|
||||
"dis=${node.disabled.joinToString(",")} en=${node.enabled.joinToString(",")} " +
|
||||
"dw=${node.dWidthCm.orNone()} de=${node.dElevationCm.orNone()}"
|
||||
}
|
||||
for (c in lane.connections) {
|
||||
val remote = c.remoteIntersection?.let { "${c.remoteRegion ?: -1}/$it" } ?: "None"
|
||||
out += "C to=${c.toLane} man=${c.maneuver?.bits.orNone()} remote=$remote " +
|
||||
"sg=${c.signalGroup.orNone()} uc=${c.userClass.orNone()} cid=${c.connectionId.orNone()}"
|
||||
}
|
||||
if (lane.overlays.isNotEmpty()) out += "O " + lane.overlays.joinToString(",")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every recorded MAPEM decodes to exactly what asn1tools reads`() {
|
||||
assertEquals("corpus size", 18, corpus.size)
|
||||
corpus.forEachIndexed { n, sample ->
|
||||
val decoded = MapemUperCodec.decode(sample.hex.hexToBytes(), receivedAtEpochMs = 0L)
|
||||
assertNotNull("MAPEM #$n (${sample.hex.length / 2} bytes) did not decode", decoded)
|
||||
val actual = dump(decoded!!)
|
||||
val first = sample.expected.indices.firstOrNull { it >= actual.size || actual[it] != sample.expected[it] }
|
||||
if (first != null || actual.size != sample.expected.size) {
|
||||
val at = first ?: sample.expected.size
|
||||
throw AssertionError(
|
||||
"MAPEM #$n differs at line ${at + 1}:\n asn1tools: ${sample.expected.getOrNull(at)}\n" +
|
||||
" decoder: ${actual.getOrNull(at)}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bench RSU MAPEM - test crossroads geometry`() {
|
||||
val bench = corpus.single { it.expected.any { line -> "MicrOBU test crossroads" in line } }
|
||||
val map = MapemUperCodec.decode(bench.hex.hexToBytes(), 0L, rssiDbm = -58)!!
|
||||
assertEquals(-58, map.rssiDbm)
|
||||
val i = map.intersections.single()
|
||||
assertEquals("-1/23", i.key)
|
||||
assertEquals(53.554698, i.refLatitude, 1e-9)
|
||||
assertEquals(10.022548, i.refLongitude, 1e-9)
|
||||
assertEquals(8, i.lanes.size)
|
||||
|
||||
val northIn = i.lane(1)!!
|
||||
assertEquals("North in", northIn.name)
|
||||
assertTrue(northIn.isIngress && !northIn.isEgress)
|
||||
assertEquals(LaneType.VEHICLE, northIn.type)
|
||||
// Straight to lane 6 (South out), left to 4 (East out), right to 8 (West out), all group 1
|
||||
val byTarget = northIn.connections.associateBy { it.toLane }
|
||||
assertTrue(byTarget.getValue(6).maneuver!!.straight)
|
||||
assertTrue(byTarget.getValue(4).maneuver!!.left)
|
||||
assertTrue(byTarget.getValue(8).maneuver!!.right)
|
||||
assertEquals(setOf(1), northIn.connections.map { it.signalGroup }.toSet())
|
||||
|
||||
// First node 12 m north (and 1.75 m west) of the reference point: the stop line.
|
||||
val points = i.lanePoints(northIn)
|
||||
assertEquals(12.0, (points[0].latitude - i.refLatitude) * 111_319.49, 0.01)
|
||||
assertEquals(72.0, (points[1].latitude - i.refLatitude) * 111_319.49, 0.01)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wrong message, wrong version and truncation give null`() {
|
||||
val bytes = corpus.first().hex.hexToBytes()
|
||||
assertNull(MapemUperCodec.decode(bytes.copyOf().also { it[1] = 4 }, 0L)) // a SPATEM id
|
||||
assertNull(MapemUperCodec.decode(bytes.copyOf().also { it[0] = 1 }, 0L)) // protocol version 1
|
||||
for (n in 0 until bytes.size - 1) {
|
||||
// UPER has no end marker: a cut inside the last few bits may still decode, but must not throw
|
||||
MapemUperCodec.decode(bytes.copyOf(n), 0L)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/** The stored and logged ids of [PhoneMount] are a file format: logs on disk carry them. */
|
||||
class PhoneMountTest {
|
||||
|
||||
@Test
|
||||
fun `ids are the ones written to settings and logs`() {
|
||||
assertEquals(listOf("handlebar", "bag", "pocket"), PhoneMount.entries.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every id reads back as its mount`() {
|
||||
PhoneMount.entries.forEach { assertEquals(it, PhoneMount.fromId(it.id)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a missing or unknown id falls back to the handlebar`() {
|
||||
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId(null))
|
||||
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId("roof"))
|
||||
}
|
||||
}
|
||||
@@ -153,34 +153,6 @@ class SpatemUperCodecTest {
|
||||
assertNull(SignalPhaseEvent(SignalPhase.DARK, null, null, null).secondsUntil(topOfHour))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decodes a road RSU SPATEM with names and advisory speeds`() {
|
||||
// 888 bytes from the Berliner Tor RSU (2026-11-23): intersection and movement names, and a greenwave
|
||||
// plus an ecoDrive AdvisorySpeed on every event. Before names and speeds were walked, every one of
|
||||
// its SPATEMs was refused and the V2X screens stayed empty. Expected values: asn1tools, ETSI modules.
|
||||
val bytes = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim().hexToBytes()
|
||||
assertEquals(888, bytes.size)
|
||||
val spat = SpatemUperCodec.decode(bytes, receivedAt)
|
||||
assertNotNull(spat)
|
||||
spat!!
|
||||
assertEquals(1_095_348_116L, spat.stationId)
|
||||
assertEquals(470_408, spat.minuteOfYear)
|
||||
val i = spat.intersections.single()
|
||||
assertEquals("-1/23", i.key)
|
||||
assertEquals(2, i.revision)
|
||||
assertEquals(470_408, i.moy)
|
||||
assertEquals(59_719, i.timeStampMs)
|
||||
assertEquals(listOf(1, 2, 3, 4, 5), i.movements.map { it.signalGroup })
|
||||
i.movements.forEach { assertEquals(8, it.events.size) }
|
||||
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5562, 5562, 5562), i.movements[0].events.first())
|
||||
assertEquals(SignalPhase.PERMISSIVE_CLEARANCE, i.movements[0].events.last().phase)
|
||||
assertEquals(6522, i.movements[0].events.last().minEndTimeDs)
|
||||
assertEquals(SignalPhase.PROTECTED_MOVEMENT_ALLOWED, i.movements[2].events.first().phase)
|
||||
assertEquals(SignalPhase.PERMISSIVE_MOVEMENT_ALLOWED, i.movements[3].events.first().phase)
|
||||
assertEquals(SignalPhaseEvent(SignalPhase.STOP_AND_REMAIN, 5802, 5802, 5802), i.movements[4].events.first())
|
||||
assertEquals(6762, i.movements[4].events.last().minEndTimeDs)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `does not decode another message type as SPATEM`() {
|
||||
// protocolVersion 2, messageId 2 (CAM) - the header guard must reject it outright.
|
||||
|
||||
@@ -12,7 +12,6 @@ import com.hawhamburg.micr0bu.data.transport.StationStatus
|
||||
import com.hawhamburg.micr0bu.data.transport.credentialsSegment
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -22,7 +21,7 @@ import org.junit.Test
|
||||
* Pins the phone side of the station-link message layer.
|
||||
*
|
||||
* ## Where the expected bytes come from
|
||||
* Niklas Dathe's Python implementation of the same protocol, microbu-esp32c5
|
||||
* The colleague's Python implementation of the same protocol, microbu-esp32c5
|
||||
* station-link/python/microbu_link/messages.py (`encode_message` over each body's `encode`),
|
||||
* run with the same field values. That module is what their phone emulator drives the firmware
|
||||
* with, so an agreement here is agreement with a second, independent implementation.
|
||||
@@ -34,26 +33,11 @@ class StationLinkTest {
|
||||
|
||||
@Test
|
||||
fun `STATION_CONFIGURE matches the Python encoder`() {
|
||||
// station_type 2, channel 180 (0x00b4), 20 dBm, security on, beaconing off: the 6-octet body of docs/station-link.pdf
|
||||
val body = StationConfigure(stationType = 2).encode()
|
||||
assertEquals(
|
||||
"0100070002b400140100",
|
||||
LinkMessage(LinkOpcode.STATION_CONFIGURE, 7, body).encode().hex(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `STATION_CONFIGURE with a MAC is the 16-octet form that names the address`() {
|
||||
// type 2, security on, address_configuration 0 (AUTO), the MAC, no beaconing, channel 180, 20 dBm, TX+RX, DP2, 1 s
|
||||
val body = StationConfigure(stationType = 2, mid = "021122334455".hexToBytes()).encode()
|
||||
assertEquals(
|
||||
"0100070002010002112233445500b40014020205",
|
||||
LinkMessage(LinkOpcode.STATION_CONFIGURE, 7, body).encode().hex(),
|
||||
)
|
||||
// another MAC is another configuration (the station is reconfigured), the same MAC is the same one
|
||||
assertEquals(StationConfigure(2, mid = "021122334455".hexToBytes()), StationConfigure(2, mid = "021122334455".hexToBytes()))
|
||||
assertFalse(StationConfigure(2, mid = "021122334455".hexToBytes()) == StationConfigure(2, mid = "021122334466".hexToBytes()))
|
||||
assertFalse(StationConfigure(2, mid = "021122334455".hexToBytes()) == StationConfigure(2))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,22 +70,17 @@ class StationLinkTest {
|
||||
assertEquals("04000a00b702f00003ababab", LinkMessage(LinkOpcode.CREDENTIALS_PROVISION, 10, body).encode().hex())
|
||||
}
|
||||
|
||||
/** The first 103 octets of the Python-encoder STATUS snapshot: counters up to its_time_ms. */
|
||||
private val statusHead = (
|
||||
"40e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
|
||||
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
|
||||
"190000001a0000001b0000001c000000fbb2b7ffa6000000"
|
||||
).hexToBytes()
|
||||
|
||||
/** A 131-octet snapshot: [statusHead], 26 octets of CBR, DCC, heap and temperature, then the cell voltage. */
|
||||
private fun status131(batteryMv: Int): ByteArray =
|
||||
statusHead + ByteArray(26) + byteArrayOf(batteryMv.toByte(), (batteryMv shr 8).toByte())
|
||||
|
||||
@Test
|
||||
fun `STATUS snapshot decodes field by field`() {
|
||||
val body = status131(3871)
|
||||
assertEquals(StationStatus.SIZE, body.size)
|
||||
val status = StationStatus.decode(body)!!
|
||||
fun `STATUS from the Python encoder decodes field by field`() {
|
||||
val message = LinkMessage.decode(
|
||||
("8400341240e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
|
||||
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
|
||||
"190000001a0000001b0000001c000000fbb2b7ffa6000000").hexToBytes(),
|
||||
)
|
||||
assertNotNull(message)
|
||||
assertEquals(LinkOpcode.STATUS, message!!.opcode)
|
||||
assertEquals(0x1234, message.sequence)
|
||||
val status = StationStatus.decode(message.body)!!
|
||||
assertEquals(123_456L, status.uptimeMs)
|
||||
assertTrue(status.configured)
|
||||
assertArrayEquals("b80b49387a4c12eb".hexToBytes(), status.identifier)
|
||||
@@ -126,57 +105,12 @@ class StationLinkTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a STATUS shorter than 131 octets is refused, a longer one is accepted`() {
|
||||
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE - 1)))
|
||||
assertNull(StationStatus.decode(statusHead))
|
||||
assertNotNull(StationStatus.decode(status131(3871) + ByteArray(4)))
|
||||
fun `a STATUS of the wrong length is refused, as the Python decoder does`() {
|
||||
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the battery voltage at octet 129 is decoded`() {
|
||||
val status = StationStatus.decode(status131(3871))!!
|
||||
assertEquals(3871, status.batteryMv)
|
||||
assertFalse(status.batteryLow)
|
||||
assertFalse(status.batteryCritical)
|
||||
assertEquals(60, status.batteryPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `low and critical follow the voltage thresholds`() {
|
||||
val low = StationStatus.decode(status131(3400))!!
|
||||
assertTrue(low.batteryLow)
|
||||
assertFalse(low.batteryCritical)
|
||||
val critical = StationStatus.decode(status131(3290))!!
|
||||
assertTrue(critical.batteryLow)
|
||||
assertTrue(critical.batteryCritical)
|
||||
assertEquals(0, critical.batteryPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no voltage means no battery`() {
|
||||
val status = StationStatus.decode(status131(0))!!
|
||||
assertFalse(status.batteryLow)
|
||||
assertFalse(status.batteryCritical)
|
||||
assertNull(status.batteryPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `LiPo percent is monotonic, clamped and anchored`() {
|
||||
assertEquals(0, StationStatus.lipoPercent(3000))
|
||||
assertEquals(0, StationStatus.lipoPercent(3300))
|
||||
assertEquals(5, StationStatus.lipoPercent(3500))
|
||||
assertEquals(100, StationStatus.lipoPercent(4200))
|
||||
assertEquals(100, StationStatus.lipoPercent(4300))
|
||||
var last = -1
|
||||
for (mv in 3000..4300 step 10) {
|
||||
val p = StationStatus.lipoPercent(mv)
|
||||
assertTrue("$mv mV -> $p% went down", p >= last)
|
||||
last = p
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `CONFIRM of STATION_CONFIGURE carries the credential state`() {
|
||||
fun `RESULT of STATION_CONFIGURE carries the credential state`() {
|
||||
val message = LinkMessage.decode("8000070000120800021122334455b80b49387a4c12eb0101".hexToBytes())!!
|
||||
val result = LinkResult.decode(message.body)!!
|
||||
assertTrue(result.accepted)
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.map.MapPoint
|
||||
import com.hawhamburg.micr0bu.domain.map.StoredMaps
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/** The bundled intersections, and which of them a SPATEM is matched to. */
|
||||
class StoredMapsTest {
|
||||
|
||||
private val stored by lazy { StoredMaps.parse(File("src/main/assets/${StoredMaps.ASSET_PATH}").readText()) }
|
||||
|
||||
private val one by lazy { stored.last { it.key == "3/2349" } }
|
||||
private val here by lazy { MapPoint(one.refLatitude, one.refLongitude) }
|
||||
|
||||
private fun pick(
|
||||
key: String = one.key,
|
||||
revision: Int = one.revision,
|
||||
live: List<com.hawhamburg.micr0bu.domain.map.IntersectionGeometry> = emptyList(),
|
||||
own: MapPoint? = here,
|
||||
) = TrafficLights.geometryFor(key, revision, live, stored, own)
|
||||
|
||||
@Test
|
||||
fun `bundle holds the recorded Hamburg intersections and the bench RSU, one per revision`() {
|
||||
// Lower bounds: tools/mapem_bundle.py adds to the list.
|
||||
assertTrue(stored.size >= 17)
|
||||
assertTrue(stored.count { it.region != null } >= 16)
|
||||
assertEquals(stored.size, stored.map { it.key to it.revision }.toSet().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the bench RSU's SPATEM joins its stored intersection`() {
|
||||
val hex = javaClass.classLoader!!.getResource("spatem_road_rsu_888.hex")!!.readText().trim()
|
||||
val spat = SpatemUperCodec.decode(hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray(), 0L)!!
|
||||
val state = spat.intersections.single()
|
||||
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)!!
|
||||
assertEquals("-1/23", matched.key)
|
||||
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
|
||||
assertTrue(light.approaches.isNotEmpty())
|
||||
assertFalse(light.revisionMismatch)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `every recorded intersection joins the SPATEM recorded for it`() {
|
||||
val samples = javaClass.classLoader!!.getResource("mapem/spat_samples.txt")!!.readText()
|
||||
.lines().filter { it.isNotBlank() }.associate { line ->
|
||||
val (key, revision, hex) = line.split(" ")
|
||||
(key to revision.toInt()) to hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
}
|
||||
// Entries added later may have no recorded SPATEM; the original 16 all do.
|
||||
val sampled = stored.filter { it.region != null && (it.key to it.revision) in samples }
|
||||
assertTrue(sampled.size >= 16)
|
||||
for (geometry in sampled) {
|
||||
val spat = SpatemUperCodec.decode(samples.getValue(geometry.key to geometry.revision), 0L)!!
|
||||
val state = spat.intersections.single { it.key == geometry.key && it.revision == geometry.revision }
|
||||
val matched = TrafficLights.geometryFor(state.key, state.revision, emptyList(), stored)
|
||||
assertSame(geometry, matched)
|
||||
val light = TrafficLights.join(SpatIntersection(state, spat.stationId, null, 0L), matched)
|
||||
assertTrue("no approaches for ${geometry.key}", light.approaches.isNotEmpty())
|
||||
assertFalse(light.revisionMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `matched on region and id together`() {
|
||||
assertSame(one, pick())
|
||||
assertNull(pick(key = "4/2349"))
|
||||
assertNull(pick(key = "-1/2349"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a stored map of another revision is not used`() {
|
||||
assertNull(pick(revision = one.revision + 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a stored map far from the rider is not used, an unknown position does not block it`() {
|
||||
// 0.03 deg of latitude is 3.3 km, beyond the radius; 0.01 deg is 1.1 km, inside it.
|
||||
assertNull(pick(own = MapPoint(one.refLatitude + 0.03, one.refLongitude)))
|
||||
assertSame(one, pick(own = MapPoint(one.refLatitude + 0.01, one.refLongitude)))
|
||||
assertSame(one, pick(own = null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a live map of the same revision wins over the stored one`() {
|
||||
val live = one.copy(name = "live")
|
||||
assertSame(live, pick(live = listOf(live)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the stored map wins over a live one of another revision`() {
|
||||
val live = one.copy(revision = one.revision + 1)
|
||||
assertSame(one, pick(live = listOf(live)))
|
||||
// And with nothing stored for the SPATEM's revision, the live one is still the fallback.
|
||||
assertSame(live, pick(revision = one.revision + 2, live = listOf(live)))
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
|
||||
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
|
||||
import com.hawhamburg.micr0bu.domain.map.MapPoint
|
||||
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
|
||||
import com.hawhamburg.micr0bu.domain.spat.TrafficLights.single
|
||||
import com.hawhamburg.micr0bu.domain.spat.Turn
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
|
||||
/**
|
||||
* [TrafficLights.join] on recorded messages only: every MAPEM in `mapem/corpus.txt` with a SPATEM
|
||||
* of the same intersection and revision from `mapem/spat_samples.txt` (both written by
|
||||
* `tools/mapem_corpus.py`): 16 road intersections from the 2026-03-18 drive and the bench RSU's
|
||||
* test crossroads from the 2026-10-28 ESP32-C5 capture.
|
||||
*/
|
||||
class TrafficLightsTest {
|
||||
|
||||
private fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
|
||||
private fun resource(name: String) = javaClass.classLoader!!.getResource(name)!!.readText()
|
||||
|
||||
/** Every intersection geometry in the corpus, in order. */
|
||||
private val maps: List<IntersectionGeometry> by lazy {
|
||||
resource("mapem/corpus.txt").lines().filter { it.startsWith("#hex ") }.flatMap {
|
||||
MapemUperCodec.decode(it.removePrefix("#hex ").hexToBytes(), 0L)!!.intersections
|
||||
}
|
||||
}
|
||||
|
||||
/** (key, revision) -> the recorded SPATEM's state for that intersection. */
|
||||
private val spats: Map<Pair<String, Int>, SpatIntersection> by lazy {
|
||||
resource("mapem/spat_samples.txt").lines().filter { it.isNotBlank() }.associate { line ->
|
||||
val (key, revision, hex) = line.split(" ")
|
||||
val spat = SpatemUperCodec.decode(hex.hexToBytes(), 0L)
|
||||
assertNotNull("recorded SPATEM for $key rev $revision does not decode", spat)
|
||||
val state = spat!!.intersections.single { it.key == key && it.revision == revision.toInt() }
|
||||
(key to revision.toInt()) to SpatIntersection(state, spat.stationId, null, 0L)
|
||||
}
|
||||
}
|
||||
|
||||
private val bench by lazy { maps.single { it.key == "-1/23" } }
|
||||
private val benchSpat by lazy { spats.getValue("-1/23" to 1) }
|
||||
|
||||
/** [north] / [east] metres from the bench intersection's reference point. */
|
||||
private fun benchPoint(north: Double, east: Double) = MapPoint(
|
||||
bench.refLatitude + north / 111_319.49,
|
||||
bench.refLongitude + east / (111_319.49 * cos(bench.refLatitude * PI / 180)),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `bench crossroads - four approaches, three exits each, all on SPATEM groups`() {
|
||||
val light = TrafficLights.join(benchSpat, bench)
|
||||
assertEquals("MicrOBU test crossroads", light.name)
|
||||
assertFalse(light.revisionMismatch)
|
||||
assertEquals(listOf("North in", "East in", "South in", "West in"), light.approaches.map { it.lane.name })
|
||||
for (approach in light.approaches) {
|
||||
assertEquals(setOf(Turn.STRAIGHT, Turn.LEFT, Turn.RIGHT), approach.exits.map { it.turn }.toSet())
|
||||
approach.exits.forEach { assertNotNull("group ${it.connection.signalGroup} not in SPATEM", it.movement) }
|
||||
}
|
||||
// North in drives south (180 deg) toward a stop line 12 m north of the reference point.
|
||||
val north = light.approaches.first()
|
||||
assertEquals(180.0, north.bearingDeg, 2.0)
|
||||
assertEquals(listOf(1), north.byGroup.map { it.first })
|
||||
assertEquals(benchSpat.state.movements.first { it.signalGroup == 1 }, north.exits.first().movement)
|
||||
assertEquals(270.0, light.approaches[1].bearingDeg, 2.0) // East in drives west
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `bench crossroads - the rider's approach from position and heading`() {
|
||||
// 40 m north, on the North-in lane (1.75 m west of the centre line), riding south
|
||||
val riding = TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.75), ownHeadingDeg = 180.0, ownSpeedMps = 5.0)
|
||||
assertEquals("North in", riding.ownApproach?.approach?.lane?.name)
|
||||
assertEquals(28.0, riding.ownApproach!!.distanceToStopLineM, 0.1)
|
||||
|
||||
// Same place, riding north: that is the North-out lane's direction, an egress lane, no light
|
||||
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.75), 0.0, 5.0).ownApproach)
|
||||
// Standing still: heading is not trusted, the nearest ingress lane wins
|
||||
assertEquals("North in",
|
||||
TrafficLights.join(benchSpat, bench, benchPoint(40.0, -1.0), 0.0, 0.0).ownApproach?.approach?.lane?.name)
|
||||
// West of the intersection, riding east: West in
|
||||
assertEquals("West in",
|
||||
TrafficLights.join(benchSpat, bench, benchPoint(-1.75, -30.0), 90.0, 4.0).ownApproach?.approach?.lane?.name)
|
||||
// Inside the intersection, past the stop line: no approach
|
||||
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(5.0, -1.75), 180.0, 5.0).ownApproach)
|
||||
// Far away
|
||||
assertNull(TrafficLights.join(benchSpat, bench, benchPoint(400.0, -1.75), 180.0, 5.0).ownApproach)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recorded road intersections - every signalled exit finds its SPATEM movement`() {
|
||||
var exits = 0
|
||||
val missing = mutableListOf<String>()
|
||||
for (map in maps.distinctBy { it.key to it.revision }) {
|
||||
val spat = spats[map.key to map.revision]
|
||||
assertNotNull("no recorded SPATEM for ${map.key} rev ${map.revision}", spat)
|
||||
val light = TrafficLights.join(spat, map)
|
||||
assertFalse(light.revisionMismatch)
|
||||
assertTrue("${map.key}: no signalled approach", light.approaches.isNotEmpty())
|
||||
for (approach in light.approaches) for (exit in approach.exits) {
|
||||
exits++
|
||||
if (exit.movement == null) missing += "${map.key} lane ${approach.lane.laneId} group ${exit.connection.signalGroup}"
|
||||
}
|
||||
}
|
||||
println("TrafficLightsTest: $exits signalled exits, unmatched: $missing")
|
||||
// The one gap on record: 3/165's MAPEM names a group 65 that its SPATEMs never carry.
|
||||
assertTrue("only 3/165 group 65 may be missing, got $missing", missing.all { it.startsWith("3/165 ") && it.endsWith(" group 65") })
|
||||
assertTrue("exits checked: $exits", exits > 300)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `geometric turn agrees with the maneuver wherever a recorded connection carries one`() {
|
||||
var compared = 0
|
||||
val disagreements = mutableListOf<String>()
|
||||
for (map in maps.distinctBy { it.key to it.revision }) {
|
||||
for (approach in TrafficLights.join(null, map).approaches) for (exit in approach.exits) {
|
||||
val stated = exit.connection.maneuver?.single() ?: continue
|
||||
if (stated == Turn.U_TURN) continue
|
||||
compared++
|
||||
val geometric = TrafficLights.geometricTurn(map, exit.connection, approach.bearingDeg)
|
||||
if (geometric != stated) disagreements += "${map.key} ${approach.lane.laneId}->${exit.connection.toLane}: $stated vs $geometric"
|
||||
}
|
||||
}
|
||||
println("TrafficLightsTest: geometric turn vs stated maneuver: ${compared - disagreements.size}/$compared agree; $disagreements")
|
||||
// The fallback only decides connections without a maneuver; it has to be right nearly always.
|
||||
assertTrue("compared $compared", compared > 100)
|
||||
assertTrue("${disagreements.size}/$compared disagree: ${disagreements.take(10)}", disagreements.size * 20 <= compared)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two revisions on air - the SPATEM's revision picks the MAPEM`() {
|
||||
val both = maps.filter { it.key == "1/1" }.distinctBy { it.revision }
|
||||
assertEquals(listOf(2, 3), both.map { it.revision }.sorted())
|
||||
assertEquals(2, TrafficLights.pickGeometry(both, 2)?.revision)
|
||||
assertEquals(3, TrafficLights.pickGeometry(both, 3)?.revision)
|
||||
assertEquals(both.last(), TrafficLights.pickGeometry(both, 9))
|
||||
// The wrong pairing is flagged
|
||||
assertTrue(TrafficLights.join(spats.getValue("1/1" to 2), both.single { it.revision == 3 }).revisionMismatch)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `SPATEM without MAPEM still gives a light, just without lanes`() {
|
||||
val light = TrafficLights.join(benchSpat, null)
|
||||
assertEquals("-1/23", light.key)
|
||||
assertTrue(light.approaches.isEmpty())
|
||||
assertNull(light.ownApproach)
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,9 @@ import org.junit.Test
|
||||
* ## Where the expected bytes come from
|
||||
* asn1tools 0.167, compiling the ETSI modules vanetza-idf ships (asn1/release2:
|
||||
* TS102894-2v241-CDD.asn, TS103300-3v231/VAM-PDU-Descriptions.asn and its motorcyclist container),
|
||||
* encoding the same values as a Python dict: the same toolchain Niklas Dathe's reference VBS
|
||||
* encoding the same values as a Python dict: the same toolchain the colleague's reference VBS
|
||||
* (microbu-esp32c5/station-link/python/microbu_link/vbs.py) builds its VAMs with. Station
|
||||
* 0x12345678, fix at Unix ms 1790170000123 (generationDeltaTime 50819: TimestampIts mod 65536 with the
|
||||
* 5 leap seconds since 2004, TAI per TS 102 894-2 V2.5.1; regenerated 2026-10 through asn1tools from the
|
||||
* earlier UTC-based vectors with 45819, every other bit unchanged), 53.5546667 N
|
||||
* 0x12345678, fix at Unix ms 1790170000123 (generationDeltaTime 45819), 53.5546667 N
|
||||
* 10.0223889 E, 5.43 m/s, heading 123.4 deg, -1.26 m/s^2; every confidence and the altitude
|
||||
* unavailable, as the encoder sends them.
|
||||
*/
|
||||
@@ -38,7 +36,7 @@ class VamUperCodecTest {
|
||||
@Test
|
||||
fun `VAM with the low-frequency container matches asn1tools`() {
|
||||
assertEquals(
|
||||
"031012345678c683400aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f322220",
|
||||
"031012345678b2fb400aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f322220",
|
||||
VamUperCodec.encode(content(includeLowFrequency = true)).hex(),
|
||||
)
|
||||
}
|
||||
@@ -46,7 +44,7 @@ class VamUperCodecTest {
|
||||
@Test
|
||||
fun `VAM without the low-frequency container matches asn1tools`() {
|
||||
assertEquals(
|
||||
"031012345678c683000aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f30",
|
||||
"031012345678b2fb000aac85a15b8a18ec88f30f3708eddd0f8002697e087ff24f30",
|
||||
VamUperCodec.encode(content(includeLowFrequency = false)).hex(),
|
||||
)
|
||||
}
|
||||
@@ -54,7 +52,7 @@ class VamUperCodecTest {
|
||||
@Test
|
||||
fun `unknown accuracy encodes the confidence ellipse as unavailable`() {
|
||||
assertEquals(
|
||||
"031012345678c683000aac85a15b8a18ec8fffffff08eddd0f8002697e087ff24f30",
|
||||
"031012345678b2fb000aac85a15b8a18ec8fffffff08eddd0f8002697e087ff24f30",
|
||||
VamUperCodec.encode(content(includeLowFrequency = false, accuracyM = null)).hex(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* The yaw rate must be the rotation about the true vertical whatever way up the phone is, which is
|
||||
* what the old z-axis reading got wrong for anything but a phone lying flat, screen up.
|
||||
*/
|
||||
class YawRateEstimatorTest {
|
||||
|
||||
private val g = 9.81f
|
||||
private val ms = 1_000_000L
|
||||
private val radToDeg = 180.0 / Math.PI
|
||||
|
||||
/** Feeds [up] (a unit vector, device frame) as gravity and a pure yaw of [ccwRadPerSec] about it. */
|
||||
private fun YawRateEstimator.yawAbout(up: DoubleArray, ccwRadPerSec: Double, startNanos: Long, samples: Int = 5) {
|
||||
onGravity((up[0] * g).toFloat(), (up[1] * g).toFloat(), (up[2] * g).toFloat(), startNanos)
|
||||
for (i in 0 until samples) {
|
||||
onGyro(
|
||||
(up[0] * ccwRadPerSec).toFloat(),
|
||||
(up[1] * ccwRadPerSec).toFloat(),
|
||||
(up[2] * ccwRadPerSec).toFloat(),
|
||||
startNanos + i * 20 * ms,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flat phone, left turn, is negative in the clockwise-positive convention`() {
|
||||
val est = YawRateEstimator()
|
||||
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||
// 0.5 rad/s counter-clockwise = turning left = -28.6 deg/s clockwise-positive, as the old z-axis path gave.
|
||||
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `handlebar tilt does not shrink the yaw rate`() {
|
||||
// Phone tilted 50 deg toward the rider about its x axis: up is (0, sin 50, cos 50) in the device frame.
|
||||
val tilt = Math.toRadians(50.0)
|
||||
val up = doubleArrayOf(0.0, sin(tilt), cos(tilt))
|
||||
val est = YawRateEstimator()
|
||||
est.yawAbout(up, 0.5, 0L)
|
||||
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||
// The z axis alone would have read only cos 50 = 64 % of it.
|
||||
assertEquals(0.643, up[2], 1e-3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `upright phone, where the z axis reads nothing, still gives the yaw rate`() {
|
||||
val est = YawRateEstimator()
|
||||
est.yawAbout(doubleArrayOf(0.0, 1.0, 0.0), -0.3, 0L)
|
||||
assertEquals(0.3 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `rotation about a horizontal axis is not yaw`() {
|
||||
// Flat phone pitching about its x axis, as on a bump: no yaw at all.
|
||||
val est = YawRateEstimator()
|
||||
est.onGravity(0f, 0f, g, 0L)
|
||||
for (i in 0 until 5) est.onGyro(1.0f, 0f, 0f, i * 20 * ms)
|
||||
assertEquals(0.0, est.yawRateDps(80 * ms)!!, 1e-9)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `averages over the window ending at the newest sample`() {
|
||||
val est = YawRateEstimator(windowNanos = 100 * ms)
|
||||
est.onGravity(0f, 0f, g, 0L)
|
||||
est.onGyro(0f, 0f, 10f, 0L) // 300 ms before the newest: outside the window
|
||||
est.onGyro(0f, 0f, 0.2f, 220 * ms)
|
||||
est.onGyro(0f, 0f, 0.4f, 260 * ms)
|
||||
est.onGyro(0f, 0f, 0.6f, 300 * ms)
|
||||
assertEquals(-0.4 * radToDeg, est.yawRateDps(300 * ms)!!, 1e-3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no yaw rate before gravity is known`() {
|
||||
val est = YawRateEstimator()
|
||||
est.onGyro(0f, 0f, 0.5f, 0L)
|
||||
assertNull(est.yawRateDps(0L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no yaw rate once the gyroscope has gone quiet`() {
|
||||
val est = YawRateEstimator(staleNanos = 500 * ms)
|
||||
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||
assertNotNull(est.yawRateDps(500 * ms))
|
||||
assertNull(est.yawRateDps(600 * ms))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `gyroscope samples are dropped against a stale up direction`() {
|
||||
val est = YawRateEstimator(staleNanos = 500 * ms)
|
||||
est.onGravity(0f, 0f, g, 0L)
|
||||
est.onGyro(0f, 0f, 0.5f, 900 * ms)
|
||||
assertNull(est.yawRateDps(900 * ms))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a gravity sample too weak to give a direction is ignored`() {
|
||||
val est = YawRateEstimator()
|
||||
est.onGravity(0f, 0f, 0.5f, 0L)
|
||||
est.onGyro(0f, 0f, 0.5f, 0L)
|
||||
assertNull(est.yawRateDps(0L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reset forgets the up direction and the samples`() {
|
||||
val est = YawRateEstimator()
|
||||
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||
est.reset()
|
||||
assertNull(est.yawRateDps(80 * ms))
|
||||
est.onGyro(0f, 0f, 0.5f, 100 * ms)
|
||||
assertNull(est.yawRateDps(100 * ms))
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.hawhamburg.micr0bu
|
||||
|
||||
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
||||
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps] is positive clockwise. The CiT One's CAM topic
|
||||
* is positive to the left (documented, and 316 of 316 turning samples in the logged runs), so
|
||||
* [CamParser] flips it. Its `obu_gnss` topic is documented as left-positive too, but the logs show
|
||||
* it positive to the right (27 of 27), so [ObuGnssParser] keeps it.
|
||||
*/
|
||||
class YawRateJsonSignTest {
|
||||
|
||||
@Test
|
||||
fun `CAM topic - positive is a left turn, so it becomes negative`() {
|
||||
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02,
|
||||
"yawRate_dps": 15.0}"""
|
||||
assertEquals(-15.0, CamParser.parse(json, ownStationId = null)!!.yawRateDps!!, 1e-9)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `CAM topic - a missing yaw rate stays unavailable`() {
|
||||
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02}"""
|
||||
assertNull(CamParser.parse(json, ownStationId = null)!!.yawRateDps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `obu_gnss - yawRate_degps is read as it is, since the CiT One sends it right-positive`() {
|
||||
// own_info as in Listing 2.1, with the position placed where this parser reads it.
|
||||
val json = """{"own_info": {"stationID": 1345678, "stationType": 2,
|
||||
"latitude": 53.55, "longitude": 10.02, "yawRate_degps": -7.5}}"""
|
||||
assertEquals(-7.5, ObuGnssParser.parseEgo(json)!!.yawRateDps!!, 1e-9)
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -1,17 +0,0 @@
|
||||
-1/23 1 020418ff6ed745a2a1018000b8104005a2a1d3d501001143710e390e390e3fa238876c876c876fc00850dc413641364137e88e20af20af20aff0
|
||||
1/1 2 020400ff3b6241ae52018800080008202001ae527c060220100020004002001c8080000003203000200100050018
|
||||
1/1 3 020400122a7441ae53018800080008302001ae53104e0f201646703e803f203ed724381fb820081fe390dc12481270125de88e092e09420938f467058205cd05af6a4382c882ee02df350dc18c419f01979c4006001a007101322b81f401f901f6b91dc0fdc10040ff1c86e09240938092ef447049704a1049c7a2b82c102e682d7b51dc1644177016f9a86e0c620cf80cbce0000480d915c0e880e9c0e9d68ee0762076c076cb4370492049c04977a23824b8250824e3d15c152c173415a588ee0ab40bb80af0c437064006c2065e680032408c8ce0744074e074eb48703b103b603b65a1b8249024e024bbd11c125c12841271e8ce0a960b9a0ad2c487055a05dc0578621b83200361032f34800f00400112056437040b0415041072238208020d020ab915c119411bc11a9c8ee08e808fc08f2e437058c059605917a2382c882cd82cb3d15c179817c017adec009002600a003400d803800e903321b8203020a82083511c102c10681055a8ae08c008de08d4e477046f047e0479721b82c382cb02c8bd11c1630166c1659e8ae0bc20be00bd6f700080030010006001c008002800b20764370406041504106a238205820d020ab519c118011bc11a9c90e08de08fc08f2e4370587059605917a2382c602cd82cb3d19c178417c017ade0002904321b8205820a82083911c104010681055c8ce08ca08de08d4e4870474047e0479721b82c602cb02c8bd11c1644166c1659e8ce0bcc0be00bd6f00024824d0dc100410181019c8ce087a08840884e4370569056e056e7a3382d282d502d53c001520a34370401040b04067233823282378235390dc1644166c1659e8ce0bea0bfe0bf4f0005882cd0dc1004102c1019c8ce08f2090608fce43705a505af05aa7a33830e831383113c001720c343703fc041004066a3382170221021c390dc156815b81591e8ce0b180b400b2cf00060834d0dc101810541041a8ce0870088e0884e43705640573056e7a3382cb02d282d03c001e20e3437040b041004107233823c823f023f3d0dc169416a816a9e8ce0c260c3a0c30f0007c83cd0dc102c10681041c8ce08de08fc08e8e437059b05aa05a07a3382ff830703023c00202103437040b041a041072338223822b0226390dc15cc160815e1e8ce0b5e0b7c0b68f00084
|
||||
1900/2396 3 02040000302941ae6701883b604ae0302001ae67949c1120164371bda1bda1bda7a238def8def8defbd19c728872887289e90e396239623962f4371d9c1d9c1d9c7a238ed08ed08ed0bd19c799079907991e400d803800e901321b8ded0ded0ded3d11c6f7c6f7c6f7de8ae394439443944f4771cb11cb11cb17a1b8ece0ece0ece3d11c768476847685e8ae3cc83cc83cc8f2007801f009880dd1dc6f046f046f05c86e398039b239a8e4471cc51cde1cd9722b8ead8eba0eb7b91dc75a8760c75f9c86e3d043d363d2cf4471e871ea01e9b7a2b8f8e8f9b0f98bc402000dc811d21c6f046f046f05c86e398039b239a8e4471cc51cde1cd972338ead8eba0eb7b921c75a8760c75f9c86e3d043d363d2cf4471e871ea01e9b7a338f8e8f9b0f98bc4021008881590dc6f686f686f69c88e37be37be37bee4571cac1cac1cac7a3b8e5d8e5d8e5dbd0dc767076847671e88e3b423b4c3b42f4571e6e1e731e6e788046012903321b8ded0ded0ded3911c6f7c6f7c6f7dc8ce395839583958f4871cbb1cbb1cbb7a1b8ece0ed08ece3d11c768476987685e8ce3cdc3ce63cdcf0009081dd21c6f046f046f05c86e397639b239a8e4471cc01cde1cd972338eab0eba0eb7b921c7594760c75f9c86e3cfa3d363d2cf4471e821ea01e9b7a338f8c0f9b0f98bc402700d8821d1dc6f046f046f05c86e397639b239a8e4471cc01cde1cd9722b8eab0eba0eb7b91dc7594760c75f9c86e3cfa3d363d2cf4471e821ea01e9b7a2b8f8c0f9b0f98bcc02800a403800e4824018002b20a005000a882cd0dc73007378733dc8ce3a703aac3a8ee4371e641e821e7372338f6e0f7d0f75bc002c20c34671bb71bb71bb77a1b8e678e678e67bd19c75e475e475e5e86e3d223d223d22f000b4834d0dc73147350733dc8ce3a7a3a983a8ef4371e691e781e737a338f708f780f75bc002e20e34671bb71bb71bb77a1b8e678e678e67bd19c75e475e475e5e86e3d223d223d22f000bc83cd0dc6f686f686f69c8ce38fe38fe38fef4371d971d9c1d9c7a338f1e0f208f20bc403000c4840024003221134371bda1bda1bda72338e3f8e3f8e3fbd0dc767076707671e8ce3c823c823c82f000cc848d0dc731473787365c8ce3a8e3ac03ab6e4371e731e8c1e877a338f7a8f870f84bc403400d40
|
||||
3/120 1 0204000177d341ae480188001803c0102001ae48e320032010062002000900148080184006001c80c00c4001000881000c40030010
|
||||
3/121 4 0204001233b441ae520188001803c8402001ae527d6b032016467032f0424039d2a43819f021981d6150dc0ed812ac1091088e077609600852846703f705dc04fb3a43820302f582851d0dc120c19a0161d020008004404c8ae065e0848073a5477033e043303ac2a1b81db025582122111c0eec12c010a508ae07ee0bb809f67477040605eb050a3a1b8241833402c3a04003001480d919c0cbc10900e74a90e067c08660758543703b604ab0424422381dd82580214a119c0fdc177013ece90e080c0bd60a1474370483066805874080080031021a1b81a6821201d89919c0dfc11580f8ce86e08200b0409f69467044205b9052d48801800680
|
||||
3/165 1 020400ffef5d41ae68018800180528102001ae6841f20c20134671c8e1cca1cb63a1b8e790ee70ea61d19c75bc7be87800e86e3bf6404c3e58800004808d15c7238732872d8e86e39e43b9c3a9874571d6f1efa1e003a1b8efd90130f96204002001880cd0dc72b0738c733d28ce39943b1a3a4864371d9c1eb91e2d4a338eee8fd70f7fa4800c003400e20434371cac1cf21cd94a2b8e6a0ed08e97190dc76847b3478dd28ae3bce3f983e2690003c814d0dc72b073c8736528ce39a83b423a5c64371da11ecd1e374a338ef38fe60f89a48010004401620634571c8e1cca1cb63a1b8e768ee48ea39d15c75bc7bd47800e86e3bec40423e44820048013005081cd19c7238732872d8e86e39da3b923a8e74671d6f1ef51e003a1b8efb10108f912040040014820d15c7238732872d8e86e39e43b9c3a9874571d6f1efa1e003a1b8efd90130f9620001520934671c7a1cbb1ca22a1b8e768ee70ea61d19c756c7bc077b0c86e3bec40383e3080001c828d0dc72c473b4736528ce399e3b2e3a4864371da61ec31e374a338eee8fd98f84a4000820b34371d1a1d921d4752338ebf0f2a8ee7250dc7a087e047be968ce3dc2407e3ebca1002800b20c34371ca71ce81ccf4a338e650ec90e92190dc76707af878b528ce3bb03f663dfe91005c01820d34371d241d8d1d5152338ebf0f258ee7250dc7a307ddc7be968ce3dc240563ea8a1006401a
|
||||
3/1745 3 0204001232f841ae52018800183688302001ae5284e303201646703a20429041f524381d8821c0217290dc106812ac1285688e083e0960094cb46704ec05dc05d25a43827d82f582f0ad0dc15a4198c1965820008004404c8ce074e0852083ea48703b60438042e521b820f82558250ad11c109012c0129968ce09e20bb80ba4b487050005eb05e15a1b82b70331832cb04003001080cd0dc0f1410a410a568ce082008fc08fcc437050505aa05aa623382a802ff82ffb0400b0034810d0dc0f1410a410a568ce07da08b608b6b437050a058705876a33829902dc82dcb4400c0038
|
||||
3/2052 3 020400ffb03a41ae58018800184020302001ae583e860c201643709ff8a228a09da2385024513c5076d15c288a291628b388ee146314a91477c4370acc8b6c8aead2238568c5b8c577e915c2bbe2e3e2c37420038010404c86e13ff14451413b4470a048a278a0eda2b85114522c516711dc28c6295228ef886e159916d915d5a4470ad18b718aefd22b8577c5c7c586e88009002800b203645709e689f589ebe23b84fac50244fd710dc2952298e2967c88e14b314d114bde4570ab38b948ac2c23b856145d1c568e10dc2c9a301e2cd720003102323384f344fac4f5f121c27d6281227eb886e14a914c714b3e4470a598a688a5ef2338559c5ca45616121c2b0a2e8e2b47086e164d180f166b910010005205646709eb89fa89f5e24384fd4504c502710dc293e29a2298fa88e14a914db14d1d4670aae8b998ac7c243855ec5d4456b610dc2c4a30322ceb2400100020019031a3384f344fac4f5f10dc2902293e2917c8ce156716f7158f84370b0d8bd58b21d0801c0079039a3384f344fac4f5f10dc2902293e2917c8ce156716f7158f84370b0d8bd58b21d00020410686e13f5143b1409b4670a278a4a8a31e21b8563c5bb4572e519c2bd22ea22c4b420098024412686e13f5143b1409b4670a278a4a8a31e21b8563c5bb4572e519c2bd22ea22c4b4200a002a414686e141314591431c4670a318a5e8a4ae21b856645c5457ce519c2bbe2ef22caf4200b002e416686e141314591431c4670a318a5e8a4ae21b856645c5457ce519c2bbe2ef22caf4200c003241868ce13eb141d1409c4370a458a5e8a54ea33856145c5456de50dc2c4a2f6a2caf4200d003641a68ce13eb141d1409c4370a458a5e8a54ea33856145c5456de50dc2c4a2f6a2caf4200e003a0
|
||||
3/2349 5 0204001225f441ae65018800184968502001ae657ef30e201645719b41a6819eb3a3b8ce18d3b8cfd1d0dc698c6d386a69288e34d036a6353e94571aea1c7f1bad4a3b8d7c8e470dde250dc6e7875a8718520002101322b8cd50d340cf3191dc66e469dc67d4c86e34b2369c353494471a5e1b531a9f4a2b8d700e3f8dd4251dc6bbc72386edd286e37283ad438c290001c80d90dc6798698c68b1488e33d634d03462a4571a451afe1a90523b8d2a0d868d4fa90dc6c7070946edd688e364238543778b4571b801cc01c1b50801000490232338cd50d340cf31921c66e469dc67d4c86e34b2369c353494471a5e1b531a9f4a338d700e3f8dd42521c6bbc72386edd286e37283ad438c2910018005205646719b41a6819eb3a438ce18d3b8cfd1d0dc698c6d386a69288e34d036a6353e94671aea1c7f1bad4a438d7c8e470dde250dc6e7875a8718522001000640cc86e33cc34c63458a44719eb1a681a31522b8d228d7f0d48291dc69506c346a7d486e3638384a376eb4471b211c2a1bbc5a2b8dc00e600e0da8000a207343719dc1a681a2c4a338d098d4f8d31a90dc6c5c6f2c6e3d88ce369c3804378cc1003400e208343719e11a681a2c4a338d098d4d0d2f290dc6c5c6f186e2988ce369237f03778c1003c020209343719e11a681a314a338d1d8d638d45ad0dc6c5c6fcc6edd68ce36ec38a4382cc00040828d19c66f869a067d4e86e34bc3728352a74671af41cc01bb2421b8dca0ef60e2920001120b346719821a6819b41a1b8d2f0dca0d481d19c6ae073006dc4e86e37283bd8389a81004801320c346719be1a6819f53a1b8d2f0dca0d4a9d19c6bbc73006ec9086e371e3bd838a4800050834d19c660869a066d0686e34bc3728352074671ab81cc01b713a1b8dca0ef60e26a0000b20e346719be1a6819f53a1b8d2f0dca0d4a9d19c6bd073006ec9086e37283bd838a480003083cd0dc678469a068c548ce3480358e3520b4371b171bf31bbc5a338dbb0e290e0db0001f
|
||||
3/2394 4 0204001230ec41ae65018800184ad0402001ae65ce4f0b20164671a181acc1a7c42438d138d6d8d45a10dc6b1c6dec6cad488e359837003660a4671b671cac1c4352438dbb0e5d8e29290dc706c758073dd62002000a404c86e346c358e355ca4471a3b1acc1ab3522b8d4f8d980d8bad1dc6ab86cfc6c99686e370038ae387cc4471b851c5c1c43622b8df48e600e53b0400c003880d90dc68ec6b1c6ab9488e348035983566a4571aa41b301b175a3b8d598d9f8d932d0dc6e14715c70f9888e371438b83886c4571bee1cc51ca760800e004102321b8d250d638d63ad11c693c6b306b3168ae3502366a35fca4771a901b441b0d521b8da98e2e0e12ad11c6d60718470a968ae3714399438b8a00018815919c689c6b30693ce90e346c35b634bc74371aa41bf31afe3a238d548dfc0d819d19c6c5c7490701d090e364c3a66382c84371b9e1e501d06408006001103322b8d138d660d279d1dc68d86b6c6978e86e354837e635fc74471aa91bf81b033a2b8d8b8e920e03a11dc6c9874cc7059086e373c3ca03a0c80000481cd19c67d46b30689c886e352a37f035fc74671ae51d241be43a1b8dc28f280e7e20000a208346719f51acc1a27221b8d4a8dfc0d7f1d19c6b9474906f90e86e370a3ca039f881004401220934371a401acc1ab352338d4f8d980d8bad0dc6e147170710d88ce37d2398a394ec0004c828d0dc68c46b306ab928ce34c635fc35c0a4371b801c2a1c0c62338dd90e308e1f30001420b34371a401acc1ab352338d520d980d8bad0dc6e287170710d88ce37dc398a394ec00054830d0dc69006b306ae148ce34ee360635deb4371b8a1c2f1c1b62338de08e330e29300016
|
||||
3/2421 3 020400ffa9ca41ae58018800184ba8302001ae58ac220920164670aa50afa0ad75243855a05848573290dc2d282f442ddd688e169e17ac16f8b4670c170d020c995a438613068886542d0dc3304378c350d620008004404c8ce154a15f415a494870ab40b090ae14a1b85a785e885be2d11c2d502f582e0568ce182e1a041928b4870c260d110ca35a1b866306f186a1ac4003001080d915c2a942be82b4928ee1568161215c294370b4f0bd10b7c5a2385aa05eb05c0ad15c305c3408325168ee184c1a221946b4370cc60de30d4358000a408c86e159a164e15f4a4470ad20b2c0aff522b859b05dc05b1ad1dc2d142f1c2dc9686e187e19be1914c4470c440ce40c8f622b865406ba8679b04006001c815915c2a942be82b5d48ee1568161215cca4370b4a0bd10b775a2385a785eb05be2d15c305c3408326568ee184c1a221950b4370cc10de30d43588010004903321b85668593857d2911c2b482cb02bfd48ae166c177016c6b4770b450bc70b725a1b861f866f86453111c31103390323d88ae19501aea19e6c1002800b20734370ac80b270aff5233857f85af059b2d0dc30ac32283189a8ce18c419821932d1003401620834370ad20b270aff5a33859b05c585b1b10dc312432dc323da8ce195a1a3619e6d1003801520934370ad20b270aff5a33858985b405a02d0dc30fc325031b1a8ce190019aa195ad1003c01020a34670a7d0ad70aa0421b85a505fa05b92919c2f9434803175286e19641c8e1a5ea100440120
|
||||
3/2422 3 02040012453c41ae5b018800184bb0302001ae5b0fa80320164370d390d4d0d486223869f06a906a6b119c377839f839e5690e1bda1d1a1d10b4370e650f0a0f006223873507878782b119c3c1440ec40c5620008004404c86e1a7c1aa41a86c4470d430d570d48623386f18741873a2d21c37c83a483a0d686e1cd41e141df6c4470e6f0f0f0f0062338787881d88162c4003001080cd19c349434e434bd686e1bf81cca1cb6c4670e4c0ef10eb05a1b8791880e87ee2c40090034810d19c33e0343033f4686e1bd01c701c52c4670e100eba0e51521b878787f307beac400a0038
|
||||
3/2423 3 020400ffaf5241ae5c018800184bb8302001ae5cb68a0a20164670fc810220ff55a4387eb881888022d0dc41b443e442a5888e20e421fc215cc46710f4122a11b75a438881891c88e32d0dc46784c0449c162002000a404c8ae1f9020441feab4770fd7103110045a1b8836887c8854b111c41c843f842b988ae21e82454236eb4771103123911c65a1b88cf098089382c000620364670fb910220ff55a4387e4081888022d0dc416443d04291688e20bc21f22152b46710e5122511b25243887a091a08e0a90dc46284bdc4999620038006408c8ae1f7220441feab4770fc8103110045a1b882c887a08522d11c417843e442a568ae21ca244a2364a47710f4123411c1521b88c5097b89332c4008004c81590dc3fd440744075a88e1ff420442044d457105910b31090623b88340861084fb10dc44ac476846dd888e226023be2378c457118a1270122a60001240cc86e1fea203a203ad4470ffa102210226a2b882c88598848311dc41a04308427d886e225623b4236ec447113011df11bc622b88c50938091530400a002c904000001420734370fff102210226a33882008390839350dc44c046784679a8ce22e223dc23dcd1003400e20834670f8710220fdc4a1b8820088688522919c42cc48e44665286e22d8263e24c2a1003c01020934370ffa102210226a33881608318831b50dc44c0463c463da8ce22ba23a023a0d1004401220a34370ffa102210226a33881608318831b50dc44c0463c463da8ce22ba23a023a0d000300
|
||||
3/2429 1 020400ffbb1741ae68018800184be8102001ae6842870420134671d471da11d97621b8ef38f208f1bb119c7b0c7db47d65886e3ec6401a3ff2d1000400220334671d471da11d97621b8ef38f208f1bb119c7b0c7db47d51886e3ec6401a3fe8d0000c810d0dc75807684768588ae3b923c143c14d4371ee11f361f366a2b8fa50fcf8fcfb840040014814d0dc75a876847671a8ae3b383ba63b9cd4371ec81eff1efa722b8f7d0f988f96384006001c808d15c751c7684765d886e3bce3c823c6ec4571ec31f6d1f54621b8fb190068ffa340008
|
||||
3/256 1 02040012346c41ae52018800180800102001ae527bf719206646703ca03ed03e36a4381ec81fe01f9350dc122012ac1285c88e091a0960094ce467058705dc05a5724382cb02f582da390dc19281a7c19a1c60008004001800840ec8ce077607c607b2d48703ca03f203e86a1b823f0253024e3911c120c12ac1285c8ce0af00bae0b36d487058705e605aa6a1b8320034f8331b88005001800720d645703bb03e303d96a3b81e501f901f4350dc11f812981271c88e090609560942e457057805d7059b6a3b82c382f302d5350dc19001a7c198dc0004100b21b81fe02058205b911c100410401041c8ae085c08e808acc477043d04830465621b82aa82cd82beb911c156816801609c8ae0b0e0c080b86d3002400a002c00c202643703fc040b040b72238200820802083915c10b811d0115988ee087a090608cac4370555059b057d722382ad02d002c13915c161c1810170da4006801c007904321b81fb82058205b911c0ff010401041c8ae085208e808acc477043804830465621b82a802cd82beb911c155416801609c8ae0b040c080b86d20040011004883990dc0fdc102c102dc88e07f808200820e457042904740456623b821c02418232b10dc1540166c15f5c88e0aaa0b400b04e4570582060405c369802600a002a00b101b21b81fe02058205b911c100410401041c8ce085c08e808acc487043d04830465621b82aa82cd82beb911c156816801609c8ce0b0e0c080b86d0005c824d0dc0fdc10401019c8ae08ca08fc08e8e437059105aa05a0722b82ff830e83073c001820a343703f204060401722b8223822d822b390dc15cc161c1609e8ae0b900bb80baef0006482cd0dc0fa010681019a8ae083e08a2087ad437054b057d0569722b82c102da02d038001a20c343703ed041504066a2b8237824b8244390dc166c170c16d1c8ae0c3a0c8a0c6ce0006c854d0dc0fc8107c102da8ae08c0091a08f2e437058c05b905a5722b82fd03138309b8001c216343703ed041504016a2b82148228821eb50dc155415f415a5c8ae0b220b720b4ae0007485cd0dc0fb4107c102da8ae083e08a2087ad437054b057d0569722b82bc02d782cdb8001e218343703f70410040b722b822d823a0237b90dc161c1680166dc8ae0bd60c080bfef0007c864d0dc0fb4107c102da8ae083e08a2087ad437054b057d0569722b82bc02d782cdb8002021a343703f2041f040b6a2b82300246823cb90dc163016e41695c8ae0bf40c4e0c26e00084810d15c0f140fdc0f79886e087a094c08dec457055005d2059b6a1b82e403408313b04022008c814d15c0f140fdc0f79886e087a094c08dec457055005d2059b6a1b82e403408313b0002420f0060009484001800262110060009c8480180028213345703d403f703ed6a1b82260253023f3115c157c174816a9a86e0bae0d020c6cc000a4850d15c0eb00f780f15886e0898096a08fcc457053705e1058c621b82eb835c031db0002a0
|
||||
4/937 4 0204000161d341ae53018800201d48402001ae53853215201005000048080184002000c80c0144004004c81000c8005002000a20500310018007206003100240142070030002c82000c000c2090031003401520a0061003800f20b0031004001120c0060004883400c001620e0062005c01800b483c00c8019006802e2100062006c01c00bc84400c801d007802c2120061007c020213006100840222140032008c02400c0854018802500980292160063009c02800a802b
|
||||
@@ -1 +0,0 @@
|
||||
02044149af94472d8803872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c10200396c474a3823310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966670b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966670ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e000018028191859796cd3bb2f241537f241cb4e7d1d009d8dc2b742b742b75e2e145c0259c453804b323857385738573bc5c28b804b388a700966570b410b410b4178b851700967114e012ccee16aa16aa16aaf170a2e012ce229c02598dc311431143115e2e145c0259c453804b323862786278627bc5c28b804b388a700966570ca90ca90ca978b851700967114e012ccee197a197a197af170a2e012ce229c02581e01001c02819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb33856485648564bc5c28b804b388a700966770add0add0add78b851700967114e012cc6e179a179a179af170a2e012ce229c025991c2f5c2f5c2f5de2e145c0259c453804b333861886188618bc5c28b804b388a700966770c450c450c4578b851700967114e012cc6e1a6a1a6a1a6af170a2e012ce229c025991c34fc34fc34fde2e145c0259c453804b03c06002805031f2f7ecc597967e7d3920e5a73e8e808ecae159215921592f170a2e012ce229c02599dc2b742b742b75e2e145c0259c453804b31b85e685e685e6bc5c28b804b388a700966470bd70bd70bd778b851700967114e012ccae186218621862f170a2e012ce229c02599dc311431143115e2e145c0259c453804b31b869a869a869abc5c28b804b388a700966470d3f0d3f0d3f78b851700967114e012c0f0100140140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b85aa85aa85aabc5c28b804b388a700966470b5f0b5f0b5f78b851700967114e012ccce177217721772f170a2e012ce229c02599dc2f342f342f35e2e145c0259c453804b31b865e865e865ebc5c28b804b388a700966470cc70cc70cc778b851700967114e012ccce1a421a421a42f170a2e012ce229c02599dc34d434d434d5e2e145c0259c453804b0bc0800400503c0a00480500
|
||||
@@ -1,4 +0,0 @@
|
||||
2004 888 512 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a70096 90034d008603f80164732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
|
||||
2004 888 244 d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd3bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500 90014d0086030000d407c40164cceb1fc851f905900102044149af94472d3103872165e5b34eecbc9054dfc902f412f7ecc597967e7d3961e7cf28005c1020039698b4b0023310b2f2d9a7765e482a6fe483a68e5bfae7d0af665cdd005d99cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025999cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e00001c028191859796cd 90024d008603ec003bb2f241537f241cb4e7d1d009d95cc3b2c3b2c3b3e2e145c0259c453804b33b9880588058807c5c28b804b388a7009663731f0b1f0b1f0f8b851700967114e012cc8e63f563f563f5f170a2e012ce229c025995cc952c952c953e2e145c0259c453804b33b9934593459347c5c28b804b388a700966373358b358b358f8b851700967114e012cc8e66c566c566c5f170a2e012ce229c02581e01001802819697bf662cbcb3f3e9c9074d1cb7f5cfa15eccb9ba01bb1b98bc58bc58bc7c5c28b804b388a700966473182b182b182f8b851700967114e012ccce63b963b963b9f170a2e012ce229c02599dcc7 90024d008603d801c2c7c2c7c3e2e145c0259c453804b31b9970597059707c5c28b804b388a7009664732eab2eab2eaf8b851700967114e012ccce668966896689f170a2e012ce229c02599dccd62cd62cd63e2e145c0259c453804b03c06002005031f2f7ecc597967e7d3920e5a73e8e808ec6e62f162f162f1f170a2e012ce229c025991cc60ac60ac60be2e145c0259c453804b32b98ee58ee58ee7c5c28b804b388a7009667731f0b1f0b1f0f8b851700967114e012cc6e65c165c165c1f170a2e012ce229c025991ccbaacbaacbabe2e145c0259c453804b32b99a259a259a27c5c28b804b388a700966773358b358b358 90034d008603c402f8b851700967114e012c0f0100160140cdc8c3d7874cd97ae5e5df0e3d195074d1cb7f5cfa15eccb9ba02bb1b9880588058807c5c28b804b388a70096647310ab10ab10af8b851700967114e012ccce62c962c962c9f170a2e012ce229c02599dcc5e2c5e2c5e3e2e145c0259c453804b31b9934593459347c5c28b804b388a700966473272b272b272f8b851700967114e012ccce659965996599f170a2e012ce229c02599dccb82cb82cb83e2e145c0259c453804b0bc0800480503c0a00400500
|
||||
2003 1198 512 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a7712100001400781 90024d00bc04f80119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900 90034d00bc04f003a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
|
||||
2003 1198 244 d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b0494af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f54c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46 90014d00bc040000d307c40164cceb1fc851f905900102054149af940801038e42cbcb669dd97920a9bf9205e825efd98b2f2cfcfa72c3cf9e5000b8255642f5d9c50d15ac419009601456c0ad802742cbcb669dd97920a9bf920d3b85080000600370c942ae092d5b0496ad024a56c125ab4092d5b0496ad824a568125ab6092d5a0496ad824a568125ab6092d5b0496ad024b56c1252b4092d5b0496ad824b5681252b6092d5a0496ad824b5681252b6092d5b0496ad024b56c125ab409295b0496ad824b568125ab609295a0496ad824b568125ab609295b0496ad024b56c125ab4092d5b0494ad824b568125ab609295b049 90024d00bc04ec004af824a57c124abc09295f0494af824a57c124abe09295f0488b5023c6a4121b3e2b0440001005831000100a8011f0b2f2d9a7765e482a6fe4837f5e824400001b85c18db0494ad824b56c125ab4092d5b0494ad024b56c125ab6092d5a0496ad824a568125ab6092d5a0496ad824a56c125ab4092d5b0496ad024a56c125ab6092d5a0496ad824b5681252b6092d5a0496ad824b56c1252b4092d5b0496ad024b56c1252b6092d5a0496ad824b568125ab609295a0496ad824b56c125ab409295b0496ad024b56c125ab609295a0496ad024a57c1252be09295f0492af024a57c1252be09255f0494af824f 90024d00bc04d80154c125328090d9e6c03425efd98b2f2cfcfa72c3cf9e541a771210000140078119d1800ee41c05f21b02db0e818a85c0b83ca054de002d4f2819e72c0c4b820665c90378e181af6e00c1b1a06118d02ecc1016c6b00be36a05edb502f6da01756c40ac36e057db902c0dd01a87640fab8c07a17803cebb81d84a808c32e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb81606e00afb6e2b0220004025834000181 90024d00bc04c402a802232f7ecc597967e7d3961e7cf2a0dfd7a1110000078127d5dc0e143005822002dd0e815188809bbb6054de00278ee01756d80c538005e5b90342d581ad6d80c1318060d8d0320cc818a6f40be36a05edb402f6da81826e40b3b78057dba02bedd01176640ec252079d7803cebb81f67140d3bae057db802bedb815f6e00afb6e0581b802bedb815f6e00afb6e057db802c0db815f6e00afb6e057db802c0db815f6e00afb6e057db802bedb81606e00afb6e057db802bedb815f6e00b036e057db802bedb815f6e00b036e057db802bedb815f6e00afb6ed80acc2cba5064cbc9048c3d7874cd97ae5e5 90024d00bc04b003df0e3d195069dc684000060010072364504510b82a992815148e0a864705452382a192015148e0a8a4705432382a291c150c8e0a8a4705452382a191c1514900a864705452382a4920151c900a924805492402a4920151c900a924805492402a4920151c900a9248054523829691814bc8e0a5e46052f238ac0900014116090000a0aa00cd42cba5064cbc9048c3d7874cd97ae5e5df0e3d19506febd0c880000200edba82086a0f05372202a191c15148e0a8a4705432382a291c150c8e0a8a4705452382a192015148e0a864705452382a291c150c8e0a8a4705492402a39201524900a924805472402a49 90034d00bc049c04201524900a924805472402a49201524900a9649053323829791c14bc8e0a5e46
|
||||
|
@@ -1,24 +1,21 @@
|
||||
# 06 – Signed ITS messages, VAM and the BLE link (2026-09-23, firmware part updated 2026-11-10)
|
||||
# 06 – Signed ITS messages, VAM and the BLE link (2026-09-23)
|
||||
|
||||
What changed when the ESP32-C5 OBU moved onto Niklas Dathe's station, how the pieces
|
||||
fit together, how it was verified, and what is still open. Since 2026-11-10 the firmware is built on
|
||||
Niklas Dathe's newer `microbu-firmware` layout (link spec revision 2, `obu-firmware/docs/station-link.tex`);
|
||||
the parts below that describe the earlier vanetza-idf port say so. Hardware checks still to do are in
|
||||
What changed when the ESP32-C5 OBU moved onto the colleague's vanetza-idf station, how the pieces
|
||||
fit together, how it was verified, and what is still open. Hardware checks still to do are in
|
||||
`TODO.md` ("Signed-TX firmware ...").
|
||||
|
||||
## Summary
|
||||
|
||||
- **Signing lives on the ESP32-C5.** The authorization ticket's private key is in the board's NVS;
|
||||
the station's security entity signs every secured message there (IEEE 1609.2 / ETSI TS 103 097,
|
||||
vanetza-idf's security entity signs every secured message there (IEEE 1609.2 / ETSI TS 103 097,
|
||||
ECDSA NIST P-256). The phone never holds a key and never signs.
|
||||
- **The phone decides what to send and when.** It builds CAM or VAM (UPER) from its own GNSS/IMU,
|
||||
hands each message to the board with the flag "signed" or "unsigned", and keeps the board's clock
|
||||
and position current.
|
||||
- **Two links, one protocol.** USB-C (native USB Serial/JTAG) or Bluetooth LE, chosen in Settings.
|
||||
Both carry Niklas Dathe's station-link protocol (revision 2 of the spec adds the MicrOBU extensions: `V2X_RX`, unsigned sending, battery guard).
|
||||
Both carry the colleague's station-link protocol v1 plus one MicrOBU extension for reception.
|
||||
- **Reception is unchanged for the app.** Every ITS message heard on air reaches the phone, signed
|
||||
or not, verifiable or not, exactly as with the previous firmware. Since 2026-11-11 the app can instead take the spec's
|
||||
`RAW_FRAME` debug capture and unwrap it itself (Settings > Receive path); both paths stay in the firmware.
|
||||
or not, verifiable or not, exactly as with the previous firmware.
|
||||
- **Demo PKI, not the EU trust list.** Signed messages carry a throwaway chain. Receivers that
|
||||
verify against the EU trust list drop them; unsigned sending remains available.
|
||||
|
||||
@@ -38,104 +35,67 @@ the parts below that describe the earlier vanetza-idf port say so. Hardware chec
|
||||
|
||||
## Firmware (obu-firmware)
|
||||
|
||||
obu-firmware is Niklas Dathe's `microbu-firmware` (commit e4e4bd8, HAW GitLab, not part of this
|
||||
repository; nothing is pushed there) with the MicrOBU additions: `main/`, `components/microbu_v2x`,
|
||||
`components/vanetza` and the patched `external/vanetza` are copied in unchanged, so obu-firmware builds
|
||||
from a plain clone. It builds with **ESP-IDF 6.0.2 only**: the raw-TX path uses private Wi-Fi driver
|
||||
structures that `microbu_v2x` pins to that version. Setup and flashing: `obu-firmware/FLASHING.md`.
|
||||
Design notes and every deviation from Niklas Dathe's code (`MicrOBU:` in the sources):
|
||||
`obu-firmware/NOTES.md`. The earlier port (vanetza-idf, 2026-09-23) and the previous C firmware are in
|
||||
git history (`1c3a66e`, `7285fa1`).
|
||||
obu-firmware is now a port of `microbu-esp32c5/firmware`: the colleague's repository, of which
|
||||
this repository keeps a copy in `microbu-esp32c5/` (their commit cf4b99f plus our V2X2MAP signature
|
||||
verification; nothing is pushed to their repository). vanetza-idf is taken from
|
||||
`microbu-esp32c5/external/vanetza-idf`. It builds
|
||||
with **ESP-IDF 6.0.2 only**: the raw-TX path uses private Wi-Fi driver structures that vanetza-idf
|
||||
pins to that version. The previous C firmware (IDF 6.1) is backed up as a full flash image in
|
||||
`firmware-backups/` (gitignored, restore command in its README.txt); its sources stay on disk,
|
||||
unbuilt. Setup and flashing: `obu-firmware/FLASHING.md`. Design notes and every deviation from the
|
||||
colleague's code (`MicrOBU:` in the sources): `obu-firmware/NOTES.md`.
|
||||
|
||||
Main changes against Niklas Dathe's firmware:
|
||||
Main changes against the colleague's firmware:
|
||||
|
||||
- **Raw receive path kept.** The stack decapsulates strictly and would drop unsigned frames (the
|
||||
bench car) and anything not signed under the demo root (every RSU). Every received frame also
|
||||
goes through `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (**0x90**; 0x85 is the
|
||||
spec's RAW_FRAME), whose body is the old `SERIAL_MSG_V2X_RX` payload.
|
||||
- **Unsigned sending kept.** Niklas Dathe's station refuses unsecured requests; here they go out
|
||||
with `geonet.c`'s header and a random MAC per configuration.
|
||||
- **Production board: Seeed XIAO ESP32-C5** (8 MB flash, a single native USB-C port) running from a LiPo
|
||||
on its BAT pads. The log travels as LOG frames on the USB link (no UART adapter needed).
|
||||
- **Battery:** the XIAO's divider (GPIO6, enabled by GPIO26) is read every 5 s and reported in STATUS
|
||||
(`battery_mv`, octets 129-130); the app shows the voltage, a rough percentage and a low (3.50 V) /
|
||||
critical (3.30 V) warning on the ESP32-C5 card and in the top bar. Below 3.30 V with no phone on USB
|
||||
the board deep-sleeps, because the prototype cell has no protection board. See `obu-firmware/FLASHING.md`.
|
||||
- **ATT MTU 517** so that a 494-octet V2X_RX (a 512-octet link message) is not split.
|
||||
- **BLE and ITS-G5** share one RF front end. Niklas Dathe's TX guard (`CONFIG_MICROBU_TX_BLE_GUARD`)
|
||||
holds a frame out of the BLE connection-event windows; the earlier "pause advertising while USB is
|
||||
in use" is gone.
|
||||
- **Raw receive path kept.** vanetza-idf decapsulates strictly and would drop unsigned frames (the
|
||||
bench car) and anything not signed under the demo root (every RSU). Every captured frame also
|
||||
goes through the previous firmware's `gn_unwrap.c` and reaches the phone as link opcode
|
||||
`V2X_RX` (0x85), whose body is the old `SERIAL_MSG_V2X_RX` payload.
|
||||
- **Unsigned sending kept.** The colleague's station refuses unsecured requests; here they go out
|
||||
with the previous firmware's `geonet.c` header.
|
||||
- **Console on UART0** (CH343, COM3 on the bench); the native USB port carries only link frames.
|
||||
- **BLE pauses advertising while USB is in use** (BLE and ITS-G5 share one RF front end).
|
||||
- **NVS 80 KB instead of 24 KB**, app at 0x20000. At 24 KB the BLE bond could not be stored and the
|
||||
phone had to pair on every connection.
|
||||
- Fixes carried over from the bench: radio queue drained before the first PoTi; 2.4 KB RX buffer off
|
||||
the Wi-Fi task stack; serial writes skipped when no USB host is present; manual country policy.
|
||||
- Fixes found on the bench: radio queue drained before the first PoTi (no RX, ~177 queue drops
|
||||
before); station loop waited 0 ticks at 100 Hz and starved the idle task; 2.4 KB RX buffer moved
|
||||
off the Wi-Fi task stack; no silent truncation of BLE notifications; ATT MTU 517; serial writes
|
||||
skipped when no USB host is present.
|
||||
|
||||
## Link protocol
|
||||
|
||||
Station-link, revision 2 (`obu-firmware/docs/station-link.tex`; revision 1 is Niklas Dathe's): `[opcode][flags][sequence LE][body]`,
|
||||
little-endian, at most 512 octets (bodies above that are fragmented by the spec; this app never needs it). Over USB each message is one `0xAA55` frame of type `0x10`
|
||||
Station-link v1 (`microbu-esp32c5/station-link/README.md`): `[opcode][flags][sequence LE][body]`,
|
||||
little-endian, at most 512 octets. Over USB each message is one `0xAA55` frame of type `0x10`
|
||||
(the old framing and CRC). Over BLE each message is one GATT value on service
|
||||
`0000C175-BA5E-4C17-8000-00805F9B34FB` (the README describes a different, Nordic-UART layout; the
|
||||
firmware is what counts; the current spec table lists the same UUIDs).
|
||||
firmware is what counts).
|
||||
|
||||
| Direction | Message | Used for |
|
||||
|---|---|---|
|
||||
| phone → board | `STATION_CONFIGURE` | station type, channel 180, 20 dBm; the 16-octet form also names the MAC (pseudonym); starts the radio |
|
||||
| phone → board | `STATION_CONFIGURE` | pseudonym MAC, station type, channel 180, 20 dBm; starts the radio |
|
||||
| phone → board | `CREDENTIALS_PROVISION` | the demo bundle, once, when the board reports no ticket |
|
||||
| phone → board | `POTI_UPDATE` | position and ITS time, once per new GNSS fix |
|
||||
| phone → board | `BTP_DATA_REQUEST` | one CAM (port 2001, psid 36) or VAM (port 2018, psid 638), signed or not |
|
||||
| phone → board | `STATUS_REQUEST` | once a second; the answer is the heartbeat |
|
||||
| board → phone | `CONFIRM` | answer to a request; for `STATUS_REQUEST` its detail is the 131-octet snapshot: counters, tickets, signed/refused counts, battery |
|
||||
| board → phone | `V2X_RX` (0x90, MicrOBU) | every ITS message heard on air |
|
||||
| board → phone | `RAW_FRAME` (0x85, spec) | debug copy of each radio frame, only while `RAW_CAPTURE` is on; the app can use it instead of `V2X_RX` (Settings > Receive path) |
|
||||
| board → phone | `RESULT` | answer to a request |
|
||||
| board → phone | `STATUS` | every second: counters, tickets, signed/refused counts |
|
||||
| board → phone | `V2X_RX` (0x85, MicrOBU) | every ITS message heard on air |
|
||||
|
||||
The app side is `Esp32Link.kt` (session), `StationLink.kt` (codec, pinned by unit tests to bytes
|
||||
from Niklas Dathe's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
|
||||
A board still on the previous C firmware is recognised by its old heartbeat and keeps working for
|
||||
CAM over USB. The pseudonym's MAC goes to the board in the 16-octet STATION_CONFIGURE (which Niklas Dathe's
|
||||
spec retires but the station still decodes, and revision 2 documents): a ride rotates it with the station ID, the bench CAM
|
||||
pinger keeps one fixed MAC, and a new MAC reconfigures the station. Without one a signed station takes its address from the
|
||||
ticket and an unsigned one draws a random MAC per configuration. With one, signed and unsigned frames both leave from it.
|
||||
|
||||
Data flow of a received frame, with both paths:
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Board[ESP32-C5 board]
|
||||
Air[ITS-G5 frame] --> Radio[Radio, promiscuous RX]
|
||||
Radio --> Stack[Vanetza: decap, verify]
|
||||
Radio --> Unwrap[gn_unwrap.c]
|
||||
Radio -->|RAW_CAPTURE on| Tap[Raw capture tap]
|
||||
Stack -->|verified| Ind[BTP_DATA_INDICATION]
|
||||
Unwrap --> Rx[V2X_RX 0x90]
|
||||
Tap --> RawF[RAW_FRAME 0x85, fragmented]
|
||||
end
|
||||
Ind & Rx & RawF --> Link[USB or BLE link]
|
||||
subgraph Phone[Android app]
|
||||
Link --> Re[LinkReassembly]
|
||||
Re --> Sel{Receive path}
|
||||
Sel -->|V2X_RX| Dec[V2xRxFrame]
|
||||
Sel -->|Raw frames| Pr[RawFrame, then GnUnwrap]
|
||||
Pr --> Dec
|
||||
Dec --> Cod[CAM, DENM, SPATEM, MAPEM, VAM codecs]
|
||||
Cod --> UI[Use cases, V2X screens, logger]
|
||||
end
|
||||
```
|
||||
|
||||
The app also **reassembles fragmented link messages** (flags 1-3 of the spec) and has two receive paths: `V2X_RX`
|
||||
(default) and `RAW_FRAME`, which it unwraps itself with `GnUnwrap.kt`; see the README for the comparison.
|
||||
from the colleague's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
|
||||
A board still on the previous firmware is recognised by its old heartbeat and keeps working for
|
||||
CAM over USB.
|
||||
|
||||
## Redundancy and recovery
|
||||
|
||||
| Situation | What notices | What happens |
|
||||
|---|---|---|
|
||||
| USB link dead (board hung, cable) | app watchdog: no frame for 3.5 s (the app polls `STATUS` every second) | link marked ERROR on the card |
|
||||
| USB link dead (board hung, cable) | app watchdog: no frame for 3.5 s (the board's `STATUS` comes every second) | link marked ERROR on the card |
|
||||
| USB unplugged | Android detach broadcast | port closed; Connect again after re-plugging |
|
||||
| BLE link lost | BLE supervision timeout (4 s) | app reconnects by itself: 1 s after a drop, then backing off to 30 s if attempts fail |
|
||||
| Board reset / power cycle | first `STATUS` reply says "not configured" | app reconfigures (and re-provisions if needed) without user action |
|
||||
| Board reset / power cycle | first `STATUS` says "not configured" | app reconfigures (and re-provisions if needed) without user action |
|
||||
| App closed and reopened | new session | app configures the board again; BLE reconnects with the stored bond, no passkey (confirmed) |
|
||||
| Phone clock or GNSS time jumping | app tracks the board's clock | PoTi never moves it backwards (except a real correction of ≥ 60 s), so the board does not restart its stack |
|
||||
| Board firmware wedged | ESP task watchdog (30 s) | the phone sees it as a dead link (above) |
|
||||
| Board firmware wedged | ESP task watchdog (30 s, logs on COM3) | the phone sees it as a dead link (above) |
|
||||
|
||||
## App changes
|
||||
|
||||
@@ -151,14 +111,14 @@ The app also **reassembles fragmented link messages** (flags 1-3 of the spec) an
|
||||
|
||||
## Credentials (demo PKI)
|
||||
|
||||
`app/src/main/assets/demo-chain.vcr`, generated 2026-09-23 with Niklas Dathe's `vidf_issue`: root
|
||||
`app/src/main/assets/demo-chain.vcr`, generated 2026-09-23 with the colleague's `vidf_issue`: root
|
||||
`6E7D0374FB021901` → AA `B3312F29844299E0` → AT `B80B49387A4C12EB` (two years; psid 36 SSP `010000`,
|
||||
psid 638 SSP `01`). It is throwaway and not EU-registered; its private key ships with the app on
|
||||
purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs.
|
||||
purpose. The colleague's own demo chain only grants psid 638 and cannot sign CAMs.
|
||||
|
||||
## Verification
|
||||
|
||||
- **Unit tests** (103): VAM bytes against asn1tools, station-link messages against Niklas Dathe's
|
||||
- **Unit tests** (103): VAM bytes against asn1tools, station-link messages against the colleague's
|
||||
Python encoder, VAM generation rules.
|
||||
- **Signatures on air**: `obu-firmware/test/verify_signed_pcap.py` checks a pcap with asn1tools
|
||||
and OpenSSL, sharing no code with the firmware. Pinger capture of 2026-09-23: 12/12 signed CAMs,
|
||||
@@ -166,7 +126,7 @@ purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs
|
||||
- **Third-party stack**: the CiT One receives the signed CAMs (~1 Hz on `v2x/rx/cam`), so its
|
||||
stack unwraps our envelope. Its MQTT interface exposes no security information, and it forwards
|
||||
unsigned and unknown-root messages alike, so it cannot tell whether it verified the signature.
|
||||
- **V2X2MAP (COM10)**: now Niklas Dathe's v2x2map 0.3.0 bridge from source with a new
|
||||
- **V2X2MAP (COM10)**: now the colleague's v2x2map 0.3.0 bridge from source with a new
|
||||
`verify.py` and `--trust demo-chain.vcr`; it shows "signature verified", "SIGNATURE INVALID" or
|
||||
"not verified" per packet. Signed CAMs and signed VAMs verified live; a one-bit change in a
|
||||
signed CAM comes out invalid. Launcher: `micrOBU_workspace/v2x-obu-esp32c5/start-v2x2map-signed.bat`.
|
||||
@@ -176,4 +136,6 @@ purpose. Niklas Dathe's own demo chain only grants psid 638 and cannot sign CAMs
|
||||
- BLE/ITS-G5 coexistence is not measured: does an active BLE connection cost 5.9 GHz reception?
|
||||
- `time_regression` standing still indoors for several minutes, and board reset recovery over BLE,
|
||||
after the last fixes.
|
||||
- The signature's generationTime follows the app's UTC-based `ItsTime`; the colleague's VBS adds
|
||||
the 5 leap seconds (TAI). Which is right is the open question in `ItsTime.kt`.
|
||||
- Real EU PKI enrolment/authorisation (TS 102 941) instead of the demo chain.
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# 07 – Sensor fusion, phase 0 and 1: inputs and logging (2026-11-18)
|
||||
|
||||
The goal is a GNSS/IMU fusion filter on the phone that gives the CAM and VAM a fresh position at
|
||||
every send, plus a better heading, yaw rate and acceleration, on any phone mount. Phase 0 fixed the
|
||||
inputs the transmit path already had. Phase 1 records everything the filter needs, so the filter can
|
||||
be built and tuned offline against real rides before it touches what goes on air. Hardware checks
|
||||
still to do are in `TODO.md` ("Sensor fusion ...").
|
||||
|
||||
## Phases
|
||||
|
||||
| Phase | What | State |
|
||||
|---|---|---|
|
||||
| 0 | Correct inputs: yaw rate about the vertical, fix times on GNSS time, monotonic clock for intervals | done (727c911, sign fix 6fa91d1) |
|
||||
| 1 | Logging: motion sensors, both phone GNSS sources, clocks, phone mount | done, rides pending |
|
||||
| 2 | Filter core: 5-state EKF (position, heading, speed, gyro bias), pure Kotlin, replayed on phase 1 logs | next |
|
||||
| 3 | Any mount: forward-axis estimate, rigidity check, mount-dependent noise | after 2 |
|
||||
| 4 | Offline tuning: GNSS outage drift, heading vs. course over ground, innovation statistics | with 2 and 3 |
|
||||
| 5 | Into CAM/VAM, the confidence ellipse and the use-case engine, behind a switch | last |
|
||||
|
||||
## Phase 0 in short
|
||||
|
||||
- **Yaw rate** is the gyroscope projected onto gravity (`domain/fusion/YawRateEstimator`), the
|
||||
rotation about the true vertical however the phone is held, averaged over 100 ms, at
|
||||
`SENSOR_DELAY_GAME`. The gyroscope's z axis alone was only right with the phone flat, screen up.
|
||||
- **Time on air** is the GNSS time of the fix itself: its monotonic age
|
||||
(`Location.getElapsedRealtimeNanos`) taken off GNSS time now (`GnssTimeSource.atElapsedRealtime`).
|
||||
The phone's clock setting, or a step of it, cannot reach the CAM or GN timestamps.
|
||||
- **Intervals** (elevated CAM rate, VAM generation rules, acceleration from GNSS speed) use the
|
||||
monotonic clock, so setting the phone clock back cannot hold VAMs off.
|
||||
- **Yaw rate sign**: the CAM's YawRateValue is positive to the left; the app's `Cam.yawRateDps` is
|
||||
positive to the right. `CamUperCodec` and `CamParser` flip it; the CiT One's `obu_gnss` sends it
|
||||
right-positive already (checked against logged rides), so `ObuGnssParser` does not.
|
||||
|
||||
## Settings > Ride
|
||||
|
||||
Replaces the old Units screen (the app is metric throughout; that switch did nothing).
|
||||
|
||||
- **Phone position**: Handlebar, Bag (on the bike) or Pocket (also a backpack). Stored in
|
||||
`RidePreferences` as `handlebar` / `bag` / `pocket` and written into every V2X log as
|
||||
`meta.phone_mount`. The filter will use it to choose how much to trust the gyroscope: fixed to the
|
||||
bike on the handlebar (but turning with the steering), mostly fixed in a bag, moving with the
|
||||
rider's body in a pocket. It is a manual setting; detecting the mount from the sensors is phase 3
|
||||
work, and these labelled logs are what it would be built and checked on.
|
||||
- **Record motion sensors**: off by default. When on at the moment a V2X log starts, that log also
|
||||
records the data below. It adds about 300 rows a second, tens of MB per hour.
|
||||
|
||||
Both are read once when a log starts, so one file is always one mount and one mode. Changing them
|
||||
mid-log takes effect from the next log.
|
||||
|
||||
## What a fusion log contains
|
||||
|
||||
Settings > Developer > V2X data logger, with Record motion sensors on. File name
|
||||
`v2x_log_<start>_<hardware>_imu-<mount>.db` (without the suffix when it is off). Schema version 2
|
||||
(`meta.schema_version`, `PRAGMA user_version`); version 1 logs have no `imu` or `clock` table and
|
||||
none of the new `gnss` columns.
|
||||
|
||||
### `imu` (new)
|
||||
|
||||
| Column | |
|
||||
|---|---|
|
||||
| `sensor` | `accel` (m/s², gravity included), `gyro` (rad/s), `gravity` (m/s², `TYPE_GRAVITY`, points up) |
|
||||
| `elapsed_ns` | the sample's own `SensorEvent.timestamp`, on `SystemClock.elapsedRealtimeNanos` |
|
||||
| `ts_ms` | the same instant as wall-clock epoch ms, for browsing only |
|
||||
| `x`, `y`, `z` | device frame: x right, y up the screen, z out of the screen |
|
||||
|
||||
Requested at 100 Hz (`meta.imu_period_us` = 10000), on a background thread of its own. `gravity` is
|
||||
only logged when the phone has a real `TYPE_GRAVITY` sensor (the Pixel 9 Pro does); the sensors'
|
||||
names, vendors and maximum rates are in `meta.sensor_*`.
|
||||
|
||||
### `gnss` (new columns)
|
||||
|
||||
| Column | |
|
||||
|---|---|
|
||||
| `source` | `phone` = fused location (Google Play services, as before), `phone_gps` = raw `GPS_PROVIDER` (new, fusion logging only), `obu` = the CiT One's `obu_gnss` |
|
||||
| `elapsed_ns` | the fix's own monotonic time; phone sources only. What fusion lines fixes up with sensor samples on |
|
||||
| `speed_accuracy_mps`, `bearing_accuracy_deg` | 1-sigma, where the provider gives them |
|
||||
| `provider` | `fused` or `gps` |
|
||||
|
||||
`fix_ms` is the fix's instant as wall-clock ms and `ts_ms` when the app received it, so
|
||||
`ts_ms - fix_ms` is the delivery delay. The fused and the raw source are logged side by side because
|
||||
the Pixel's fused location includes Google's city-street corrections while the raw one is the chip
|
||||
alone and not pre-filtered; the rides decide which one the filter uses. `meta.gnss_hardware` names
|
||||
the GNSS chip.
|
||||
|
||||
### `clock` (new)
|
||||
|
||||
Once a second, the three phone clocks read back to back: `elapsed_ns` (monotonic), `wall_ms` (the
|
||||
phone clock), `gnss_ms` (`SystemClock.currentGnssTimeClock`, NULL without GNSS time). Sensor samples
|
||||
and phone fixes carry monotonic time, received messages and OBU fixes wall time, and the transmit
|
||||
path GNSS time; these rows convert between them, and show the phone clock's error and any step in it.
|
||||
|
||||
## Checking a log
|
||||
|
||||
```
|
||||
py -3.11 tools/fusion_log_check.py v2x_log_..._imu-handlebar.db
|
||||
```
|
||||
|
||||
Read-only, standard library only. Per file it prints the metadata, each sensor's sample count, rate,
|
||||
interval distribution, gaps and magnitude, each GNSS source's rate, accuracy, delivery delay and
|
||||
whether its fixes fall inside the sensor recording, the distance between the fused and raw fixes
|
||||
(and the OBU's, on the CiT One), and the phone clock's error and steps. It ends with PASS, WARN or
|
||||
FAIL lines, and exits with 1 if anything failed:
|
||||
|
||||
- FAIL: logging was off, no `imu`/`clock` table, a sensor missing, a sensor gap over 1 s, a phone
|
||||
source missing, phone fixes without `elapsed_ns`.
|
||||
- WARN: a sensor rate outside 80–130 Hz, gaps over 100 ms, an accelerometer or gravity magnitude far
|
||||
from g, a GNSS gap over 5 s, fixes with no gyroscope sample within 20 ms, no GNSS time, a phone
|
||||
clock step, a log that was not stopped cleanly.
|
||||
|
||||
Tested against synthetic logs built from `V2xLogWriter`'s own table definitions (a clean ride, an
|
||||
injected 300 ms gyroscope gap, a 14-minute clock step, logging off, fixes without monotonic time);
|
||||
not yet against a real ride.
|
||||
|
||||
## Test rides
|
||||
|
||||
Recorded per mount (handlebar, bag, pocket), 20–30 minutes each, with Record motion sensors on and the
|
||||
phone mount set before pressing Start. Each ride should include left and right turns, a roundabout,
|
||||
stops of at least 10 s (the filter estimates the gyroscope offset while standing), and if possible a
|
||||
bridge or underpass for a real GNSS outage. The list to tick off is in `TODO.md`.
|
||||
|
||||
## Code
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `domain/fusion/PhoneMount.kt` | the mount setting and its stored ids |
|
||||
| `data/RidePreferences.kt`, `viewmodel/RideSettingsViewModel.kt` | Settings > Ride storage and screen state |
|
||||
| `ui/screens/SettingsScreen.kt` (`RideSettingsScreen`) | the screen |
|
||||
| `data/SensorRepository.kt` | `gpsProviderFlow`, sensor flows on a chosen thread, `describeSensor` |
|
||||
| `data/log/V2xLogger.kt`, `data/log/V2xLogWriter.kt` | the logging and the schema |
|
||||
| `ui/screens/V2xLogSettingsScreen.kt` | shows mount, motion sensor row count and raw GPS fix age while logging |
|
||||
| `tools/fusion_log_check.py` | the check above |
|
||||
@@ -1,113 +0,0 @@
|
||||
# Large SPATEM / MAPEM reception (2026-11-23)
|
||||
|
||||
Why a road RSU's SPATEMs and MAPEMs did not reach the phone's V2X screens, in two independent places, and what was
|
||||
changed. Interface changes are in `obu-firmware/docs/station-link.tex` (revision 3).
|
||||
|
||||
## Symptom
|
||||
|
||||
A MAPEM and a SPATEM compiled to sit below 494 bytes arrived on the phone; larger ones did not. Later, with the
|
||||
firmware fixed, the phone *logger* showed the RSU's large messages but the app's V2X screens stayed empty.
|
||||
|
||||
The "larger" test messages were far above the limit: **888 bytes (SPATEM) and 1198 bytes (MAPEM)**, from the
|
||||
Berliner Tor RSU (station 1095348116, intersection 23, 6 lanes, 5 signal groups). The small pair were 377 B (MAPEM)
|
||||
and 58 B (SPATEM). The test therefore showed that nothing is fragmented on that path, not where a cutoff sits.
|
||||
|
||||
## Problem 1: the firmware dropped everything over 494 bytes
|
||||
|
||||
**It did receive them.** The radio captures frames up to 2346 bytes, and the firmware's own `gn_unwrap.c`, replayed
|
||||
on the PC over the CiT node's pcap (`its5_20261123_150746.pcap`, 27 367 frames), accepts all of them: 1727 MAPEMs
|
||||
of 1198 B and 3384 SPATEMs of 888 B. They are valid: asn1tools decodes every distinct one and re-encodes it
|
||||
byte-identically.
|
||||
|
||||
**The firmware then threw them away.** `V2X_RX` (opcode 0x90, MicrOBU's own) was designed as one link message. A link
|
||||
message is at most 512 octets (the largest GATT value), minus 4 header and 14 prefix octets leaves **494 bytes** of
|
||||
ITS payload. `Station::forward_raw` called `v2x_rx_fits()`, and for a longer message only incremented
|
||||
`raw_oversize_` and returned. The fragmenting code (`LinkService::send_fragmented`, used for `RAW_FRAME`, PKI and
|
||||
indications) existed and the app already reassembled any fragmented opcode, but the gate in front of it meant a
|
||||
`V2X_RX` was never offered to it.
|
||||
|
||||
**Why nobody noticed:**
|
||||
- It was a known, documented limit (`gn_unwrap.h`, `NOTES.md`, TODO.md: "road MAPEMs over 494 bytes are still dropped as
|
||||
oversize (no fragmentation)"), but every earlier bench run used the bench RSU, whose messages are 58 and 295 bytes.
|
||||
- The drop was silent where the phone could see it. The counter lived only in the firmware, STATUS has a fixed
|
||||
131-octet layout with no field for it, and the only trace was one LOG line per 10 s on the USB log, which a phone on
|
||||
BLE never gets.
|
||||
- Comparing the phone log with a second receiver (the node's pcap) is what exposed it: 0 of 1537 large MAPEMs and
|
||||
0 of 3004 large SPATEMs reached the phone, against 98.5 % and 96.5 % of the small ones.
|
||||
|
||||
**What the 2026-11-23 COM10 read did and did not show.** An early check of COM10's log concluded the board "never saw
|
||||
a large message". That was wrong. `tools/station_status_watch.py` prints only the first few V2X_RX lines unless asked,
|
||||
and opening the port reset the board. It showed nothing about large messages either way.
|
||||
|
||||
### Fix (obu-firmware)
|
||||
- `v2x_rx.hpp`: `v2x_rx_plan()` decides `single` (up to 494 B, byte-identical to before), `fragmented` (up to
|
||||
`v2x_rx_max_forward` = 2300 B), `covered_by_raw` (large and `RAW_CAPTURE` on) or `drop`.
|
||||
- `link_fragment.hpp` (new, host-testable): `split_fragments()` is the one fragmenter. `LinkService::send_fragmented`
|
||||
uses it, with the same bytes on the wire as before.
|
||||
- Best effort, never blocking: fragments of a large `V2X_RX` go out on serial through the non-blocking
|
||||
`try_write`, no retry, no wait. The first failed fragment ends that message; the app drops the incomplete stream
|
||||
(2 s idle, or the next first fragment). A transport that would need more than 8 fragments (ATT MTU 23) skips the
|
||||
message.
|
||||
- `serial::try_write` now writes nothing when no USB host is connected.
|
||||
- Counters `raw_fragmented_`, `raw_fragment_failed_`, `raw_covered_`, `raw_oversize_`, in the throttled LOG line.
|
||||
STATUS is unchanged.
|
||||
- The app's V2X_RX / Raw frames switch is untouched. While `RAW_CAPTURE` is on a large message is not sent a second
|
||||
time as V2X_RX.
|
||||
- TX path untouched.
|
||||
|
||||
### Result on air (COM10, BLE, 17:08-17:20)
|
||||
`tools/rx_size_compare.py` on the new phone log and node pcap: MAPEM 1198 B 92.9 % of what the node heard, SPATEM
|
||||
888 B 81.7 %, CAMs 92.5-99.3 %, `radio_dropped` 0, no BLE disconnects.
|
||||
|
||||
## Problem 2: the app's SPATEM decoder refused the RSU's messages
|
||||
|
||||
**Why the logger had them and the screens did not.** Both read the same `V2X_RX` frames from `Esp32Link`. They differ
|
||||
in what they do with the bytes:
|
||||
- `V2xLogger` stores the raw UPER payload and classifies it from the ITS PDU header. Decoding only fills convenience
|
||||
columns (position, speed, a summary), inside `runCatching`, so a decoder that fails leaves them NULL and the row is
|
||||
stored anyway.
|
||||
- `CamUseCaseRepository.handleSpatUper` hands the bytes to `SpatemUperCodec.decode`; on `null` it logs
|
||||
"decode FAILED" and emits nothing, so no SPAT reached the traffic-light screens.
|
||||
|
||||
**Why the decoder returned null.** `SpatemUperCodec` returned null whenever it met an optional it could not size.
|
||||
The RSU's SPATEM uses two such fields on every intersection:
|
||||
- `name` / `movementName` (`DescriptiveName`, IA5String SIZE(1..63)): "Berliner Tor / Kolbergstrasse" and one per
|
||||
movement.
|
||||
- `speeds` (`AdvisorySpeedList`) on every event: a greenwave and an ecoDrive advice per phase. This, with the names
|
||||
and the 8 events per movement, is why the message is 888 bytes and not ~58.
|
||||
|
||||
The decoder's header comment said it had been validated against 79 042 SPATEMs from the 2026-03-18 drive; those
|
||||
messages simply carried neither field. The gap was latent: until the firmware forwarded large messages, an 888-byte
|
||||
SPATEM never reached the app, so the decoder never met one.
|
||||
|
||||
The MAPEM decoded correctly all along (it already reads names); the traffic-light screens need the SPATEM as well.
|
||||
|
||||
### Fix (app)
|
||||
`SpatemUperCodec` now walks, without keeping, `DescriptiveName` (6-bit length n-1, then 7 bits per character) and
|
||||
`AdvisorySpeedList` (4-bit count n-1; per entry: extension bit, five optional bits, type = extension bit plus 2 bits,
|
||||
speed 9 bits, confidence 3 bits, distance 14 bits, class 8 bits). Regional extensions and extension values still
|
||||
return null. Widths come from `dsrc_2_2_1.asn`.
|
||||
|
||||
## Verification
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| Firmware host suite (`make check` in `obu-firmware/test/host`): chain, replay with asn1tools, 2 M-iteration fuzz, battery, firmware | pass; the firmware unit tests grew from 40 to 46 |
|
||||
| `test_v2x_fragments`: the node pcap through unwrap, plan, fragments, two independent reassemblers, at link limits 512 and 244, with a lost fragment | 5111 large messages, 0 failures |
|
||||
| App `LinkReassemblyTest` on the firmware's own fragments (`v2x_rx_fragments.tsv`) | pass |
|
||||
| `SpatemUperCodec` against asn1tools on every distinct SPATEM of the new phone log | 718 of 718 equal field for field, 3590 movements |
|
||||
| App unit suite | 197 tests, 0 failures |
|
||||
| ESP-IDF 6.0.2 image build | 0x1f7aa0 bytes, 34 % of the app partition free |
|
||||
|
||||
## Files changed
|
||||
Firmware: `v2x_rx.hpp`, `link_fragment.hpp` (new), `link_service.cpp/.hpp`, `station.cpp/.hpp`, `serial_link.cpp`,
|
||||
`gn_unwrap.h` (comment), `NOTES.md`, `README.md`, `docs/station-link.tex`. Tests: `test_firmware.cpp`,
|
||||
`test_v2x_fragments.cpp` (new), `Makefile`. App: `SpatemUperCodec.kt`, `SpatemUperCodecTest.kt`,
|
||||
`LinkReassemblyTest.kt`, resources `v2x_rx_fragments.tsv`, `spatem_road_rsu_888.hex`. Tool: `tools/rx_size_compare.py`.
|
||||
|
||||
## Still open
|
||||
- The V2X screens on the phone with the rebuilt app (this document was written before that check).
|
||||
- MAPEM / SPATEM loss on BLE rises with size (58-byte SPATEM 96.5 % on 2026-11-23 earlier, 888-byte SPATEM 81.7 % now): a lost fragment loses
|
||||
the message. If the screens need better, options are a smaller fragment cadence or a loss counter in the app
|
||||
(`LinkReassembly.dropped`).
|
||||
- Advisory speeds are walked, not used; a GLOSA display could read them.
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 660 KiB |
@@ -0,0 +1,43 @@
|
||||
# --- ESP-IDF build output ---
|
||||
firmware/build/
|
||||
firmware/build-*/
|
||||
firmware/managed_components/
|
||||
firmware/.cache/
|
||||
firmware/.vscode/
|
||||
firmware/sdkconfig
|
||||
firmware/sdkconfig.old
|
||||
firmware/*.log
|
||||
firmware/rf_characterization_output/
|
||||
|
||||
# --- Secrets: never commit real private key material ---
|
||||
# (this repo only ever ships the disposable, non-registered demo chain)
|
||||
*.vkey
|
||||
*.ekey
|
||||
private/
|
||||
*_private_encrypted.pem
|
||||
*_RCA_NEW_*/
|
||||
|
||||
# --- PKI reference-generator: regenerate locally, do not commit ---
|
||||
# (vendored Rust crates for the offline/deterministic c-its build path; see
|
||||
# pki/uml-l0-rca/reference-generator/README.md to rebuild with `cargo vendor`)
|
||||
pki/uml-l0-rca/reference-generator/vendor/
|
||||
pki/uml-l0-rca/reference-generator/_build_cits/
|
||||
pki/uml-l0-rca/reference-generator/_cargo_vendor/
|
||||
|
||||
# --- Python ---
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# --- v2x2map bridge local artifacts ---
|
||||
tools/v2x2map-0.3.0/bridge/recordings/
|
||||
tools/v2x2map-0.3.0/bridge/dist/
|
||||
tools/v2x2map-0.3.0/bridge/build/
|
||||
*.pcap
|
||||
|
||||
# --- OS / editor ---
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.swp
|
||||
@@ -0,0 +1,155 @@
|
||||
# micrOBU ESP32-C5
|
||||
|
||||
A standalone ITS-G5 (802.11p) VRU (Vulnerable Road User) ITS-S station on the
|
||||
ESP32-C5: firmware, the embedded [Vanetza](https://github.com/riebl/vanetza)
|
||||
C-ITS protocol stack (`external/vanetza-idf/`, see
|
||||
[PROVENANCE.md](external/vanetza-idf/PROVENANCE.md)), a phone-emulator
|
||||
example for the station-internal link, a localhost PKI reference chain, a
|
||||
Wireshark VAM dissector and the [V2X2MAP](https://github.com/711it/v2x2map)
|
||||
receiver bridge.
|
||||
|
||||
A fresh clone can send a real, signed VAM (VRU Awareness Message) over the
|
||||
air in a handful of commands — see [Send a signed VAM](#4-send-a-signed-vam-in-a-few-commands)
|
||||
below. `station-link/python/demo-chain.vcr` is a disposable, **non-EU-registered**
|
||||
test credential chain generated specifically for this purpose (see
|
||||
[Security note on credentials](#security-note-on-credentials)); it carries no
|
||||
real-world trust and is safe to ship.
|
||||
|
||||
## Quickstart
|
||||
|
||||
### 1. Build & flash the ESP32-C5 firmware
|
||||
|
||||
Requires [ESP-IDF](https://docs.espressif.com/projects/esp-idf/en/latest/esp32c5/get-started/) 6.0.2 with the `esp32c5` target.
|
||||
|
||||
```powershell
|
||||
cd firmware
|
||||
idf.py set-target esp32c5
|
||||
idf.py build
|
||||
idf.py -p COM<PORT> flash monitor
|
||||
```
|
||||
|
||||
### 2. Install the Wireshark VAM dissector
|
||||
|
||||
Wireshark decodes IEEE 1609.2 / ETSI TS 103 097 secured packets only down to
|
||||
`unsecuredData` unless the PSID is registered in its dissector table. **PSID
|
||||
638** (VRU Awareness Service, ETSI TS 102 965) is not registered by default
|
||||
in Wireshark 4.x, so signed VAM traffic stops decoding at the security
|
||||
envelope without this plugin.
|
||||
|
||||
```powershell
|
||||
# Windows
|
||||
Copy-Item tools\wireshark\psid-vru.lua "$env:APPDATA\Wireshark\plugins\"
|
||||
```
|
||||
```bash
|
||||
# Linux
|
||||
mkdir -p ~/.local/lib/wireshark/plugins && cp tools/wireshark/psid-vru.lua ~/.local/lib/wireshark/plugins/
|
||||
# macOS
|
||||
mkdir -p ~/.config/wireshark/plugins && cp tools/wireshark/psid-vru.lua ~/.config/wireshark/plugins/
|
||||
```
|
||||
|
||||
Verify under **Help → About Wireshark → Plugins**, or use it directly with `tshark`:
|
||||
|
||||
```bash
|
||||
tshark -X lua_script:tools/wireshark/psid-vru.lua -r capture.pcap
|
||||
```
|
||||
|
||||
See [tools/wireshark/README.md](tools/wireshark/README.md) for details.
|
||||
|
||||
### 3. Install Python dependencies
|
||||
|
||||
```bash
|
||||
pip install -r station-link/python/requirements.txt
|
||||
pip install -r tools/v2x2map-0.3.0/bridge/requirements.txt
|
||||
```
|
||||
|
||||
### 4. Send a signed VAM in a few commands
|
||||
|
||||
With the firmware flashed (step 1) and the ESP32-C5 connected over USB
|
||||
Serial/JTAG, the phone emulator provisions the disposable demo credential
|
||||
chain and starts a small VRU basic service that assembles and transmits
|
||||
VAMs:
|
||||
|
||||
```bash
|
||||
python station-link/python/phone_emulator.py \
|
||||
--port COM<PORT> --bundle station-link/python/demo-chain.vcr \
|
||||
--radio txrx --duration 30
|
||||
```
|
||||
|
||||
That's it — the micrOBU signs every VAM with the demo AT ticket (VRU ITS-AID
|
||||
638, `psid 638 ssp 01`) and transmits it over ITS-G5. Capture it with a
|
||||
second ITS-G5-capable radio (or the [V2X2MAP bridge](#5-run-the-v2x2map-receiver-bridge-optional)
|
||||
below) and decode it with the [Wireshark dissector](#2-install-the-wireshark-vam-dissector)
|
||||
from step 2.
|
||||
|
||||
To provision over BLE instead of USB, or to mirror packets to a `.pcap`
|
||||
without radiating, see the header of
|
||||
[`phone_emulator.py`](station-link/python/phone_emulator.py) for the
|
||||
`--ble`, `--radio off --divert --pcap` and full `--pki-*` (real online TS
|
||||
102 941 enrolment/authorization) variants, and
|
||||
[station-link/README.md](station-link/README.md) for the link protocol
|
||||
itself.
|
||||
|
||||
### 5. Run the V2X2MAP receiver bridge (optional)
|
||||
|
||||
A second ESP32-C5 flashed with the receiver firmware in
|
||||
[`tools/v2x2map-0.3.0/bridge/firmware/`](tools/v2x2map-0.3.0/bridge/firmware/)
|
||||
can feed a live web dashboard:
|
||||
|
||||
```bash
|
||||
python tools/v2x2map-0.3.0/bridge/its_g5_bridge.py --port COM<PORT> --dashboard-port 8080 --open-browser
|
||||
```
|
||||
|
||||
Open `http://localhost:8080` if it doesn't open automatically. This tool
|
||||
decodes VAMs for display but does **not** verify signatures (see
|
||||
[tools/v2x2map-0.3.0/README.md](tools/v2x2map-0.3.0/README.md)).
|
||||
|
||||
## Repository layout
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `firmware/` | ESP-IDF firmware project for the ESP32-C5 VRU ITS-S |
|
||||
| `external/vanetza-idf/` | Vanetza C-ITS stack + ESP-IDF port (upstream provenance in [PROVENANCE.md](external/vanetza-idf/PROVENANCE.md)) |
|
||||
| `station-link/` | Station-internal link protocol, Python client library, phone emulator |
|
||||
| `pki/` | Localhost PKI reference chain (root/AA/AT tooling); see [security note](#security-note-on-credentials) |
|
||||
| `tools/wireshark/` | PSID 638 (VRU) Wireshark Lua dissector |
|
||||
| `tools/v2x2map-0.3.0/` | Vendored [V2X2MAP](https://github.com/711it/v2x2map) receiver bridge and live dashboard |
|
||||
|
||||
## Security note on credentials
|
||||
|
||||
`pki/uml-l0-rca/` documents the tooling for a **real, EU CCMS L0 ECTL-registered**
|
||||
root CA used elsewhere in the wider micrOBU project. Its private key material
|
||||
is intentionally **not** in this repository — `.gitignore` also backstops
|
||||
this (`*.vkey`, `*.ekey`, `private/`).
|
||||
|
||||
`station-link/python/demo-chain.vcr` is unrelated: a separate, throwaway,
|
||||
**non-registered** root/AA/AT chain generated specifically for this repo's
|
||||
quickstart with `pki/uml-l0-rca/bin/windows/vidf_issue.exe`. Its
|
||||
`HashedId8` values do not match the registered root, it grants no real-world
|
||||
trust, and regenerating it is safe:
|
||||
|
||||
```powershell
|
||||
$pool = "<some scratch directory>"
|
||||
$exe = "pki\uml-l0-rca\bin\windows\vidf_issue.exe"
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "$pool\demo_root_key.pem"
|
||||
& $exe root --key "$pool\demo_root_key.pem" --name "Demo Root (NOT REGISTERED)" --id DEMO_RCA --out $pool --years 10
|
||||
& $exe authority --issuer "$pool\DEMO_RCA.oer" --issuer-key "$pool\demo_root_key.pem" --name "Demo AA" --id DEMO_AA --out $pool --years 5
|
||||
& $exe ticket --issuer "$pool\DEMO_AA.oer" --issuer-key "$pool\DEMO_AA.vkey" --id DEMO_AT --out $pool --hours 8760 --root "$pool\DEMO_RCA.oer"
|
||||
python external\vanetza-idf\ports\esp_idf\tools\credential_bundle.py build `
|
||||
--pool $pool --root DEMO_RCA --aa DEMO_AA --at DEMO_AT --out station-link\python\demo-chain.vcr
|
||||
```
|
||||
|
||||
`pki/uml-l0-rca/reference-generator/` cross-validates certificate generation
|
||||
against an independent Rust implementation ([`TheEnbyperor/c-its`](https://github.com/TheEnbyperor/c-its),
|
||||
pinned commit in [`reference-generator/README.md`](pki/uml-l0-rca/reference-generator/README.md)).
|
||||
Its vendored crates (`vendor/`) are excluded from this repository by
|
||||
`.gitignore` for size; regenerate with `cargo vendor` from that directory's
|
||||
`Cargo.lock`, or use `vidf_issue` directly as shown above — the vendor tree
|
||||
is only needed for that independent cross-check, not for ordinary use.
|
||||
|
||||
## License / provenance
|
||||
|
||||
- Vanetza and its ESP-IDF port: BSD-3-Clause, see
|
||||
[external/vanetza-idf/LICENSE.md](external/vanetza-idf/LICENSE.md) and
|
||||
[external/vanetza-idf/PROVENANCE.md](external/vanetza-idf/PROVENANCE.md).
|
||||
- V2X2MAP bridge: MIT, see
|
||||
[tools/v2x2map-0.3.0/LICENSE](tools/v2x2map-0.3.0/LICENSE).
|
||||
@@ -0,0 +1,14 @@
|
||||
build
|
||||
.cache/
|
||||
build-*/
|
||||
build-*.log
|
||||
sdkconfig
|
||||
sdkconfig.old
|
||||
sdkconfig.*.old
|
||||
managed_components/
|
||||
dependencies.lock
|
||||
__pycache__/
|
||||
conanfile.pyc
|
||||
doxygen/html/
|
||||
www/
|
||||
build.asn1/
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
if(ESP_PLATFORM)
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/ports/esp_idf/CMakeLists.txt")
|
||||
return()
|
||||
endif()
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
cmake_policy(VERSION 3.14...3.31)
|
||||
project(Vanetza VERSION 26.02)
|
||||
set(VANETZA_SOVERSION 0)
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
|
||||
|
||||
# Look up threading library (usually pthread)
|
||||
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
|
||||
find_package(Threads MODULE)
|
||||
|
||||
# Build configuration options
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries" OFF)
|
||||
|
||||
option(BUILD_TESTS "Build unit tests" OFF)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(gtest)
|
||||
endif()
|
||||
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib/static)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(UseVanetza)
|
||||
|
||||
# Enable usage of targets' folder property (good for Visual Studio)
|
||||
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
|
||||
# Find project dependencies
|
||||
find_package(Boost 1.70 REQUIRED COMPONENTS date_time OPTIONAL_COMPONENTS program_options CONFIG)
|
||||
vanetza_optional_dependency(GeographicLib 1.37 VANETZA_WITH_GEOGRAPHICLIB "Use GeographicLib for precise geodesy")
|
||||
vanetza_optional_dependency(CapnProto 0.8 VANETZA_WITH_RPC "Enable RPC support")
|
||||
vanetza_optional_dependency(CryptoPP 5.6.1 VANETZA_WITH_CRYPTOPP "Enable Crypto++ support")
|
||||
vanetza_optional_dependency(OpenSSL 1.1.1 VANETZA_WITH_OPENSSL "Enable OpenSSL extensions")
|
||||
|
||||
option(VANETZA_WITH_PQC "Enable the experimental hybrid-PQC certificate profile" OFF)
|
||||
if(VANETZA_WITH_PQC)
|
||||
find_package(liboqs 0.14 CONFIG REQUIRED)
|
||||
endif()
|
||||
|
||||
option(VANETZA_EMBED_COUNTRY_DATA "Embed country boundary data into geodesy library" OFF)
|
||||
|
||||
add_subdirectory(vanetza/access)
|
||||
add_subdirectory(vanetza/asn1)
|
||||
add_subdirectory(vanetza/btp)
|
||||
add_subdirectory(vanetza/common)
|
||||
add_subdirectory(vanetza/dcc)
|
||||
add_subdirectory(vanetza/facilities)
|
||||
add_subdirectory(vanetza/geodesy)
|
||||
add_subdirectory(vanetza/geonet)
|
||||
add_subdirectory(vanetza/gnss)
|
||||
add_subdirectory(vanetza/net)
|
||||
add_subdirectory(vanetza/rpc)
|
||||
add_subdirectory(vanetza/security)
|
||||
add_subdirectory(vanetza/units)
|
||||
|
||||
option(BUILD_SOCKTAP "Build socktap application" OFF)
|
||||
if(BUILD_SOCKTAP)
|
||||
add_subdirectory(tools/socktap)
|
||||
endif()
|
||||
|
||||
option(BUILD_CERTIFY "Build certify application" OFF)
|
||||
if(BUILD_CERTIFY)
|
||||
add_subdirectory(tools/certify)
|
||||
if(VANETZA_WITH_PQC)
|
||||
add_subdirectory(tools/certify-pqc)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
option(BUILD_BENCHMARK "Build benchmark application" OFF)
|
||||
if(BUILD_BENCHMARK)
|
||||
add_subdirectory(tools/benchmark)
|
||||
endif()
|
||||
|
||||
option(BUILD_FUZZ "Build fuzz harness" OFF)
|
||||
if(BUILD_FUZZ)
|
||||
add_subdirectory(tools/fuzz-harness)
|
||||
endif()
|
||||
|
||||
option(BUILD_PKI "Build PKI tools" OFF)
|
||||
if(BUILD_PKI AND VANETZA_WITH_PQC)
|
||||
message(FATAL_ERROR
|
||||
"BUILD_PKI cannot be combined with VANETZA_WITH_PQC: the unchanged PKI "
|
||||
"client uses Vanetza's standard Security ASN.1 profile. Build the PKI "
|
||||
"client separately with VANETZA_WITH_PQC=OFF.")
|
||||
endif()
|
||||
if(BUILD_PKI)
|
||||
add_subdirectory(tools/pki)
|
||||
endif()
|
||||
|
||||
# interface library for convenience
|
||||
get_property(_components GLOBAL PROPERTY VANETZA_COMPONENTS)
|
||||
add_library(vanetza INTERFACE)
|
||||
add_library(Vanetza::vanetza ALIAS vanetza)
|
||||
foreach(_component IN LISTS _components)
|
||||
target_link_libraries(vanetza INTERFACE ${_component})
|
||||
endforeach()
|
||||
|
||||
# installation rules
|
||||
include(CMakePackageConfigHelpers)
|
||||
set(CMAKECONFIG_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/Vanetza")
|
||||
set(CMAKECONFIG_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/cmake-config")
|
||||
write_basic_package_version_file(${CMAKECONFIG_BUILD_DIR}/VanetzaConfigVersion.cmake
|
||||
COMPATIBILITY ExactVersion)
|
||||
configure_package_config_file(cmake/VanetzaConfig.cmake.in
|
||||
${CMAKECONFIG_BUILD_DIR}/VanetzaConfig.cmake
|
||||
INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR}
|
||||
PATH_VARS CMAKE_INSTALL_INCLUDEDIR)
|
||||
|
||||
install(TARGETS vanetza EXPORT ${PROJECT_NAME})
|
||||
|
||||
install(FILES
|
||||
${CMAKECONFIG_BUILD_DIR}/VanetzaConfig.cmake
|
||||
${CMAKECONFIG_BUILD_DIR}/VanetzaConfigVersion.cmake
|
||||
DESTINATION ${CMAKECONFIG_INSTALL_DIR})
|
||||
|
||||
install(DIRECTORY ${PROJECT_SOURCE_DIR}/cmake/
|
||||
DESTINATION ${CMAKECONFIG_INSTALL_DIR}
|
||||
FILES_MATCHING
|
||||
PATTERN "Find*.cmake")
|
||||
|
||||
install(EXPORT ${PROJECT_NAME} NAMESPACE Vanetza:: FILE VanetzaTargets.cmake DESTINATION ${CMAKECONFIG_INSTALL_DIR})
|
||||
|
||||
# install all C++ headers except those found for tests
|
||||
file(GLOB_RECURSE _vanetza_headers
|
||||
RELATIVE ${PROJECT_SOURCE_DIR}
|
||||
CONFIGURE_DEPENDS
|
||||
vanetza/*.hpp)
|
||||
list(FILTER _vanetza_headers EXCLUDE REGEX "/tests/")
|
||||
if(NOT VANETZA_WITH_PQC)
|
||||
list(FILTER _vanetza_headers EXCLUDE REGEX "vanetza/security/pqc/")
|
||||
endif()
|
||||
foreach(_header IN LISTS _vanetza_headers)
|
||||
get_filename_component(_dir ${_header} DIRECTORY)
|
||||
install(FILES ${_header}
|
||||
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${_dir})
|
||||
endforeach()
|
||||
|
||||
# export build tree (allows import by outside projects)
|
||||
option(VANETZA_EXPORT_PACKAGE "Export Vanetza build directory to CMake package registry" OFF)
|
||||
if(VANETZA_EXPORT_PACKAGE)
|
||||
export(EXPORT ${PROJECT_NAME} NAMESPACE Vanetza:: FILE VanetzaExports.cmake)
|
||||
file(COPY ${CMAKECONFIG_BUILD_DIR}/VanetzaConfigVersion.cmake
|
||||
DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
|
||||
configure_file(cmake/VanetzaExportsConfig.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/VanetzaConfig.cmake @ONLY)
|
||||
export(PACKAGE ${PROJECT_NAME})
|
||||
endif()
|
||||
|
||||
# mark build directory as cache dir, see https://bford.info/cachedir
|
||||
file(WRITE ${PROJECT_BINARY_DIR}/CACHEDIR.TAG
|
||||
"Signature: 8a477f597d28d172789f06886806bc55")
|
||||
+2983
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
rsource "ports/esp_idf/Kconfig"
|
||||
Vendored
@@ -0,0 +1,26 @@
|
||||
# Vanetza Upstream Provenance
|
||||
|
||||
This directory (`external/vanetza-idf`) contains the Vanetza protocol stack and its ESP-IDF integration for the micrOBU ESP32-C5 ITS-S station.
|
||||
|
||||
## Upstream Software Basis
|
||||
|
||||
- **Project**: Vanetza (ETSI C-ITS protocol stack implementation in C++17)
|
||||
- **Upstream Repository**: `https://github.com/riebl/vanetza.git`
|
||||
- **Pinned Upstream Revision**: `a7cacc1879f3e2124dfb8ef2d83886b1e82d3b36`
|
||||
- **Author / Upstream Maintainer**: Raphael Riebl et al.
|
||||
- **Citekey**: `rieblRieblVanetza2026`
|
||||
- **License**: BSD-3-Clause (retained in `LICENSE.md`)
|
||||
|
||||
## Integrated Components & Third-Party Dependencies
|
||||
|
||||
1. **Boost C++ Libraries (v1.87.0)**:
|
||||
- Located in `ports/esp_idf/third_party/` (`circular_buffer`, `geometry`, `heap`, `iostreams`, `multiprecision`, `rational`).
|
||||
- License: Boost Software License 1.0 (`BSL-1.0`).
|
||||
|
||||
2. **OpenTrafficMap (OTM) Transmitter**:
|
||||
- Upstream: `https://codeberg.org/opentrafficmap/its-g5-receiver-firmware_txenabled.git`
|
||||
- Reviewed Revision: `674e34128279235ba34c9f8d778f43cf1d075397`
|
||||
- Core file: `ports/esp_idf/third_party/otm/main/tx_custom.c` (guarded by SHA-256 in `firmware/CMakeLists.txt`).
|
||||
|
||||
3. **ESP-IDF Port (`ports/esp_idf`)**:
|
||||
- Implements hardware-accelerated crypto (mbedTLS ECC/ECDSA/SHA), NVS credential persistence, ESP32-C5 802.11p PHY bindings (`radio_c5.cmake`), and localhost PKI verification tooling (`ports/esp_idf/tools/local_pki.py`, `pki_client.py`).
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# vanetza-idf
|
||||
|
||||
Modular C++17 Vanetza library for ESP-IDF. Choose an access, network/transport,
|
||||
or facilities-codec profile; supply your own platform and radio adapters.
|
||||
The portable core targets the ESP32 family. The integrated C5 radio backend
|
||||
is experimental and requires separate hardware validation.
|
||||
|
||||
**Start with the [ESP-IDF integration guide](docs/idf/README.md).** It covers
|
||||
installation, Kconfig, ownership/event-loop rules, examples, and standalone
|
||||
host/device tests. [Standards traceability](docs/idf/standards.md) links the public
|
||||
interfaces to precise ETSI editions and clauses.
|
||||
The [interface assessment](docs/idf/interface-assessment.md) identifies remaining
|
||||
contract and capability gaps. [Test campaigns](docs/idf/test-campaigns.md) explains
|
||||
how the separately installed ETSI framework and two-C5 radio tests connect.
|
||||
|
||||
**This is an experimental port, not a completed ETSI-conformant stack.**
|
||||
See [implementation and conformance gaps](docs/idf/conformance.md) and
|
||||
[validation results](docs/idf/validation.md). CAM/DENM/VAM codecs and endpoints
|
||||
are distinct from complete Basic Services.
|
||||
|
||||
## Components and configurable boundaries
|
||||
|
||||
The arrangement follows the facilities, networking/transport and access layers
|
||||
of the ETSI ITS station architecture, with management and security as shared
|
||||
cross-layer services. It is an implementation map, inspired by
|
||||
[TS 102 723-11, clauses 4–5](https://www.etsi.org/deliver/etsi_ts/102700_102799/10272311/01.01.01_60/ts_10272311v010101p.pdf)
|
||||
and [EN 303 797, Annex B](https://www.etsi.org/deliver/etsi_en/303700_303799/303797/02.01.01_60/en_303797v020101p.pdf).
|
||||
It does not imply that every service in those figures is implemented.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph station["vanetza-idf"]
|
||||
direction TB
|
||||
|
||||
subgraph entry["Application / test entry points"]
|
||||
direction LR
|
||||
application["Application or upper tester"]
|
||||
f_entry["Facilities PDU entry"]
|
||||
b_entry["BTP-DATA entry"]
|
||||
a_entry["AL_DATA entry"]
|
||||
application --> f_entry
|
||||
application --> b_entry
|
||||
application --> a_entry
|
||||
end
|
||||
|
||||
subgraph dataplane["Protocol data plane"]
|
||||
direction LR
|
||||
|
||||
subgraph facilities["Facilities"]
|
||||
direction TB
|
||||
codecs["CAM R2 / DENM R2 / VAM R2\nASN.1 codecs"]
|
||||
basic_services["CA / DEN / VRU Basic Services\npending"]
|
||||
end
|
||||
|
||||
subgraph nt["Networking & Transport"]
|
||||
direction TB
|
||||
btp["BTP-A / BTP-B"]
|
||||
gn["GeoNetworking\nSHB / GBC"]
|
||||
btp --> gn
|
||||
end
|
||||
|
||||
subgraph access_layer["Access boundary"]
|
||||
direction TB
|
||||
access["AL_DATA\nparameter validation"]
|
||||
end
|
||||
|
||||
codecs --> btp
|
||||
gn --> access
|
||||
end
|
||||
|
||||
subgraph shared["Shared / cross-layer services"]
|
||||
direction LR
|
||||
position["Position + clock"]
|
||||
management["Management\nMIB + configuration"]
|
||||
security["Security entity\nTS 103 097 signing + ticket pool\nverification pending"]
|
||||
saps["SAP bindings\nSN / SF / MN / MF / MI"]
|
||||
end
|
||||
|
||||
f_entry --> codecs
|
||||
b_entry --> btp
|
||||
a_entry --> access
|
||||
|
||||
position -.-> gn
|
||||
management -.-> gn
|
||||
security -.-> gn
|
||||
saps -.-> security
|
||||
saps -.-> gn
|
||||
end
|
||||
|
||||
subgraph integration["Platform / external integration"]
|
||||
direction LR
|
||||
etsi["External ETSI TTCN-3\nframework + SUT adapter"]
|
||||
hil["Optional HIL framing\nbounded VID1 envelope"]
|
||||
adapter["External access adapter\nsoftware lower tester / radio"]
|
||||
radio["ESP32-C5 radio backend\nexperimental; DCC + HW validation pending"]
|
||||
|
||||
hil -.-> etsi
|
||||
adapter -.-> radio
|
||||
end
|
||||
|
||||
etsi -.-> application
|
||||
etsi -.-> adapter
|
||||
access <-->|"owned GNPDU + metadata"| adapter
|
||||
```
|
||||
|
||||
The main transmit path is deliberately kept horizontal: Facilities → BTP →
|
||||
GeoNetworking → Access. Management, position/time and security are shown as
|
||||
shared services because they support protocol processing rather than form another
|
||||
encapsulation stage. Reception travels back up the selected layers. The access
|
||||
profile omits the network and facilities layers; the network profile adds
|
||||
BTP/GeoNetworking; the facilities profile also enables the individually
|
||||
selectable codecs. Complete CA, DEN and VRU Basic Services are still pending.
|
||||
The optional HIL envelope carries adapter payloads; it is not an ETSI protocol.
|
||||
|
||||
## External TTCN-3 and HIL
|
||||
|
||||
Install the TTCN-3 runtime and the [official ETSI ITS framework](https://forge.etsi.org/rep/ITS/TS.ITS)
|
||||
separately. The library does not install or bundle them. The test application
|
||||
connects that framework's suite-specific SUT adapter to these points:
|
||||
|
||||
| Point | API/boundary | Intended use |
|
||||
|---|---|---|
|
||||
| Upper tester | Named NF-SAP binding, `Stack::request`, position/time/security injection | Stimulate implemented behavior and collect actual results; full service operations remain pending |
|
||||
| Software lower tester | `Access::request` and `Stack::indicate` | Inject/observe GN traffic while the protocol implementation runs on the ESP32 |
|
||||
| Physical lower tester | Independent ITS-G5 capture/injection radio | Validate transmitted frames, access behavior and RF properties |
|
||||
|
||||
Enable `CONFIG_VANETZA_IDF_HIL` for optional bounded framing. USB/UART/BLE/IP
|
||||
transports and suite-specific command decoding remain in the test application
|
||||
and host SUT adapter. Preserve the ETSI codec payload and map it to the actual
|
||||
service under test; never synthesize a successful acknowledgement.
|
||||
|
||||
The [hook-up guide](docs/idf/README.md#connect-a-separately-installed-etsi-ttcn-3-framework)
|
||||
explains payload boundaries, metadata, real-time versus injected-time tests,
|
||||
PICS/PIXIT, Release 2 ATS adaptation, and evidence retention. A mirrored SUT
|
||||
packet is software evidence; radio conformance requires independent observation.
|
||||
|
||||
## Foundation and acknowledgements
|
||||
|
||||
vanetza-idf is an independent ESP-IDF adaptation built on
|
||||
[Vanetza](https://github.com/riebl/vanetza). It is not maintained by, affiliated
|
||||
with, or endorsed by the Vanetza team. Upstream authorship and license notices
|
||||
remain with the original source files. See the
|
||||
[upstream documentation](https://www.vanetza.org/) for the original library.
|
||||
|
||||
Thank you to [OpenTrafficMap](https://codeberg.org/opentrafficmap) for the
|
||||
foundational work that established how to transmit ITS-G5 using the ESP32-C5
|
||||
radio, shared in their
|
||||
[receiver firmware with TX enabled](https://codeberg.org/opentrafficmap/its-g5-receiver-firmware_txenabled).
|
||||
The C5 backend builds on that work. Its private SDK dependencies and validation
|
||||
status are documented separately from the portable protocol core.
|
||||
|
||||
Vanetza is licensed under LGPLv3; see [LICENSE.md](LICENSE.md).
|
||||
Third-party components retain their respective notices and licensing terms.
|
||||
@@ -0,0 +1,47 @@
|
||||
These ASN.1 files are taken from their respective standardisation documents and are **not** licensed the same way as Vanetza itself.
|
||||
Please refer to the referenced standardisation documents for details about the applicable Intellectual Property Rights (IPR).
|
||||
To the best of my knowledge, ETSI does not object to bundling ASN.1 files of their published documents along with software.
|
||||
Some editorial changes may have been applied, e.g. removal of trailing whitespace etc.
|
||||
Code generated from the files located here can be found in the *vanetza/asn1/its* directory.
|
||||
|
||||
# Standardisation documents
|
||||
|
||||
- *EN302637-2v141-CAM.asn* from ETSI EN 302 637-2 v1.4.1 (2019-04)
|
||||
- *EN302637-3v131-DENM.asn* from ETSI EN 302 637-3 v1.3.1 (2019-04)
|
||||
- *TS102894-2v131-CDD.asn* from ETSI TS 102 894-2 v1.3.1 (2018-08)
|
||||
- *TS102941v131-\*.asn* from ETSI TS 102 941 v1.3.1 (2019-02)
|
||||
- *TS103097v131.asn* from ETSI TS 103 097 v1.3.1 (2017-10)
|
||||
- *TS103097v211-\*.asn* from ETSI TS 103 097 v2.1.1 (2021-10)
|
||||
- *TR103562v211.asn* from ETSI TR 103 562 v2.1.1 (2019-12)
|
||||
|
||||
- *IEEE1609dot2.asn* and *IEEE1609dot2BaseTypes.asn* from IEEE 1609.2 as printed in ETSI TS 103 097 v1.3.1
|
||||
|
||||
# ETSI WebSVN
|
||||
|
||||
You may find these ITS ASN.1 modules also in ETSI's public SVN repository: http://oldforge.etsi.org/websvn/listing.php?repname=ITS.ITS_ASN1
|
||||
While above source is still online (in March 2020), ETSI seems to have moved to https://forge.etsi.org/rep/ITS/ITS_ASN1 by now.
|
||||
This newer source also contains a license file explicitly. A copy is included below for reference.
|
||||
|
||||
> Copyright 2019 ETSI
|
||||
>
|
||||
> Redistribution and use in source and binary forms, with or without
|
||||
> modification, are permitted provided that the following conditions are met:
|
||||
> 1. Redistributions of source code must retain the above copyright notice,
|
||||
> this list of conditions and the following disclaimer.
|
||||
> 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
> this list of conditions and the following disclaimer in the documentation
|
||||
> and/or other materials provided with the distribution.
|
||||
> 3. Neither the name of the copyright holder nor the names of its contributors
|
||||
> may be used to endorse or promote products derived from this software without
|
||||
> specific prior written permission.
|
||||
>
|
||||
> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
> ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
> WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
> IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
> INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
> BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
> DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
> LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
> OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
|
||||
> OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,132 @@
|
||||
CAM-PDU-Descriptions {
|
||||
itu-t (0) identified-organization (4) etsi (0) itsDomain (5) wg1 (1) en (302637) cam (2) version (2)
|
||||
}
|
||||
|
||||
DEFINITIONS AUTOMATIC TAGS ::=
|
||||
|
||||
BEGIN
|
||||
|
||||
IMPORTS
|
||||
ItsPduHeader, CauseCode, ReferencePosition, AccelerationControl, Curvature, CurvatureCalculationMode, Heading, LanePosition, EmergencyPriority, EmbarkationStatus, Speed, DriveDirection, LongitudinalAcceleration, LateralAcceleration, VerticalAcceleration, StationType, ExteriorLights, DangerousGoodsBasic, SpecialTransportType, LightBarSirenInUse, VehicleRole, VehicleLength, VehicleWidth, PathHistory, RoadworksSubCauseCode, ClosedLanes, TrafficRule, SpeedLimit, SteeringWheelAngle, PerformanceClass, YawRate, ProtectedCommunicationZone, PtActivation, Latitude, Longitude, ProtectedCommunicationZonesRSU, CenDsrcTollingZone FROM ITS-Container {
|
||||
itu-t (0) identified-organization (4) etsi (0) itsDomain (5) wg1 (1) ts (102894) cdd (2) version (2)
|
||||
};
|
||||
|
||||
|
||||
-- The root data frame for cooperative awareness messages
|
||||
|
||||
CAM ::= SEQUENCE {
|
||||
header ItsPduHeader,
|
||||
cam CoopAwareness
|
||||
}
|
||||
|
||||
CoopAwareness ::= SEQUENCE {
|
||||
generationDeltaTime GenerationDeltaTime,
|
||||
camParameters CamParameters
|
||||
}
|
||||
|
||||
CamParameters ::= SEQUENCE {
|
||||
basicContainer BasicContainer,
|
||||
highFrequencyContainer HighFrequencyContainer,
|
||||
lowFrequencyContainer LowFrequencyContainer OPTIONAL,
|
||||
specialVehicleContainer SpecialVehicleContainer OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
HighFrequencyContainer ::= CHOICE {
|
||||
basicVehicleContainerHighFrequency BasicVehicleContainerHighFrequency,
|
||||
rsuContainerHighFrequency RSUContainerHighFrequency,
|
||||
...
|
||||
}
|
||||
|
||||
LowFrequencyContainer ::= CHOICE {
|
||||
basicVehicleContainerLowFrequency BasicVehicleContainerLowFrequency,
|
||||
...
|
||||
}
|
||||
|
||||
SpecialVehicleContainer ::= CHOICE {
|
||||
publicTransportContainer PublicTransportContainer,
|
||||
specialTransportContainer SpecialTransportContainer,
|
||||
dangerousGoodsContainer DangerousGoodsContainer,
|
||||
roadWorksContainerBasic RoadWorksContainerBasic,
|
||||
rescueContainer RescueContainer,
|
||||
emergencyContainer EmergencyContainer,
|
||||
safetyCarContainer SafetyCarContainer,
|
||||
...
|
||||
}
|
||||
|
||||
BasicContainer ::= SEQUENCE {
|
||||
stationType StationType,
|
||||
referencePosition ReferencePosition,
|
||||
...
|
||||
}
|
||||
|
||||
BasicVehicleContainerHighFrequency ::= SEQUENCE {
|
||||
heading Heading,
|
||||
speed Speed,
|
||||
driveDirection DriveDirection,
|
||||
vehicleLength VehicleLength,
|
||||
vehicleWidth VehicleWidth,
|
||||
longitudinalAcceleration LongitudinalAcceleration,
|
||||
curvature Curvature,
|
||||
curvatureCalculationMode CurvatureCalculationMode,
|
||||
yawRate YawRate,
|
||||
accelerationControl AccelerationControl OPTIONAL,
|
||||
lanePosition LanePosition OPTIONAL,
|
||||
steeringWheelAngle SteeringWheelAngle OPTIONAL,
|
||||
lateralAcceleration LateralAcceleration OPTIONAL,
|
||||
verticalAcceleration VerticalAcceleration OPTIONAL,
|
||||
performanceClass PerformanceClass OPTIONAL,
|
||||
cenDsrcTollingZone CenDsrcTollingZone OPTIONAL
|
||||
}
|
||||
|
||||
BasicVehicleContainerLowFrequency ::= SEQUENCE {
|
||||
vehicleRole VehicleRole,
|
||||
exteriorLights ExteriorLights,
|
||||
pathHistory PathHistory
|
||||
}
|
||||
|
||||
PublicTransportContainer ::= SEQUENCE {
|
||||
embarkationStatus EmbarkationStatus,
|
||||
ptActivation PtActivation OPTIONAL
|
||||
}
|
||||
|
||||
SpecialTransportContainer ::= SEQUENCE {
|
||||
specialTransportType SpecialTransportType,
|
||||
lightBarSirenInUse LightBarSirenInUse
|
||||
}
|
||||
|
||||
DangerousGoodsContainer ::= SEQUENCE {
|
||||
dangerousGoodsBasic DangerousGoodsBasic
|
||||
}
|
||||
|
||||
RoadWorksContainerBasic ::= SEQUENCE {
|
||||
roadworksSubCauseCode RoadworksSubCauseCode OPTIONAL,
|
||||
lightBarSirenInUse LightBarSirenInUse,
|
||||
closedLanes ClosedLanes OPTIONAL
|
||||
}
|
||||
|
||||
RescueContainer ::= SEQUENCE {
|
||||
lightBarSirenInUse LightBarSirenInUse
|
||||
}
|
||||
|
||||
EmergencyContainer ::= SEQUENCE {
|
||||
lightBarSirenInUse LightBarSirenInUse,
|
||||
incidentIndication CauseCode OPTIONAL,
|
||||
emergencyPriority EmergencyPriority OPTIONAL
|
||||
}
|
||||
|
||||
SafetyCarContainer ::= SEQUENCE {
|
||||
lightBarSirenInUse LightBarSirenInUse,
|
||||
incidentIndication CauseCode OPTIONAL,
|
||||
trafficRule TrafficRule OPTIONAL,
|
||||
speedLimit SpeedLimit OPTIONAL
|
||||
}
|
||||
|
||||
RSUContainerHighFrequency ::= SEQUENCE {
|
||||
protectedCommunicationZonesRSU ProtectedCommunicationZonesRSU OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
GenerationDeltaTime ::= INTEGER { oneMilliSec(1) } (0..65535)
|
||||
|
||||
END
|
||||
@@ -0,0 +1,109 @@
|
||||
DENM-PDU-Descriptions {
|
||||
itu-t (0) identified-organization (4) etsi (0) itsDomain (5) wg1 (1) en (302637) denm (1) version (2)
|
||||
}
|
||||
|
||||
DEFINITIONS AUTOMATIC TAGS ::=
|
||||
|
||||
BEGIN
|
||||
|
||||
IMPORTS
|
||||
ItsPduHeader, CauseCode, Speed, InformationQuality, ReferencePosition, ClosedLanes, DangerousGoodsExtended, Heading, LanePosition, LightBarSirenInUse, RoadType, HeightLonCarr, PosLonCarr, PosCentMass, PositioningSolutionType, RequestResponseIndication, StationType, SpeedLimit, StationarySince, TimestampIts, WheelBaseVehicle, TurningRadius, PosFrontAx, PositionOfOccupants, Temperature, VehicleMass, VehicleIdentification, EnergyStorageType, ActionID, ItineraryPath, NumberOfOccupants, PositionOfPillars, RelevanceTrafficDirection, RestrictedTypes, Traces, TransmissionInterval, ValidityDuration, RelevanceDistance, EventHistory, TrafficRule, DeltaReferencePosition FROM ITS-Container {
|
||||
itu-t (0) identified-organization (4) etsi (0) itsDomain (5) wg1 (1) ts (102894) cdd (2) version (2)
|
||||
};
|
||||
|
||||
|
||||
DENM ::= SEQUENCE {
|
||||
header ItsPduHeader,
|
||||
denm DecentralizedEnvironmentalNotificationMessage
|
||||
}
|
||||
|
||||
DecentralizedEnvironmentalNotificationMessage ::= SEQUENCE {
|
||||
management ManagementContainer,
|
||||
situation SituationContainer OPTIONAL,
|
||||
location LocationContainer OPTIONAL,
|
||||
alacarte AlacarteContainer OPTIONAL
|
||||
}
|
||||
|
||||
ManagementContainer ::= SEQUENCE {
|
||||
actionID ActionID,
|
||||
detectionTime TimestampIts,
|
||||
referenceTime TimestampIts,
|
||||
termination Termination OPTIONAL,
|
||||
eventPosition ReferencePosition,
|
||||
relevanceDistance RelevanceDistance OPTIONAL,
|
||||
relevanceTrafficDirection RelevanceTrafficDirection OPTIONAL,
|
||||
validityDuration ValidityDuration DEFAULT defaultValidity,
|
||||
transmissionInterval TransmissionInterval OPTIONAL,
|
||||
stationType StationType,
|
||||
...
|
||||
}
|
||||
|
||||
SituationContainer ::= SEQUENCE {
|
||||
informationQuality InformationQuality,
|
||||
eventType CauseCode,
|
||||
linkedCause CauseCode OPTIONAL,
|
||||
eventHistory EventHistory OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
LocationContainer ::= SEQUENCE {
|
||||
eventSpeed Speed OPTIONAL,
|
||||
eventPositionHeading Heading OPTIONAL,
|
||||
traces Traces,
|
||||
roadType RoadType OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
ImpactReductionContainer ::= SEQUENCE {
|
||||
heightLonCarrLeft HeightLonCarr,
|
||||
heightLonCarrRight HeightLonCarr,
|
||||
posLonCarrLeft PosLonCarr,
|
||||
posLonCarrRight PosLonCarr,
|
||||
positionOfPillars PositionOfPillars,
|
||||
posCentMass PosCentMass,
|
||||
wheelBaseVehicle WheelBaseVehicle,
|
||||
turningRadius TurningRadius,
|
||||
posFrontAx PosFrontAx,
|
||||
positionOfOccupants PositionOfOccupants,
|
||||
vehicleMass VehicleMass,
|
||||
requestResponseIndication RequestResponseIndication
|
||||
}
|
||||
|
||||
RoadWorksContainerExtended ::= SEQUENCE {
|
||||
lightBarSirenInUse LightBarSirenInUse OPTIONAL,
|
||||
closedLanes ClosedLanes OPTIONAL,
|
||||
restriction RestrictedTypes OPTIONAL,
|
||||
speedLimit SpeedLimit OPTIONAL,
|
||||
incidentIndication CauseCode OPTIONAL,
|
||||
recommendedPath ItineraryPath OPTIONAL,
|
||||
startingPointSpeedLimit DeltaReferencePosition OPTIONAL,
|
||||
trafficFlowRule TrafficRule OPTIONAL,
|
||||
referenceDenms ReferenceDenms OPTIONAL
|
||||
}
|
||||
|
||||
StationaryVehicleContainer ::= SEQUENCE {
|
||||
stationarySince StationarySince OPTIONAL,
|
||||
stationaryCause CauseCode OPTIONAL,
|
||||
carryingDangerousGoods DangerousGoodsExtended OPTIONAL,
|
||||
numberOfOccupants NumberOfOccupants OPTIONAL,
|
||||
vehicleIdentification VehicleIdentification OPTIONAL,
|
||||
energyStorageType EnergyStorageType OPTIONAL
|
||||
}
|
||||
|
||||
AlacarteContainer ::= SEQUENCE {
|
||||
lanePosition LanePosition OPTIONAL,
|
||||
impactReduction ImpactReductionContainer OPTIONAL,
|
||||
externalTemperature Temperature OPTIONAL,
|
||||
roadWorks RoadWorksContainerExtended OPTIONAL,
|
||||
positioningSolution PositioningSolutionType OPTIONAL,
|
||||
stationaryVehicle StationaryVehicleContainer OPTIONAL,
|
||||
...
|
||||
}
|
||||
|
||||
defaultValidity INTEGER ::= 600
|
||||
|
||||
Termination ::= ENUMERATED {isCancellation(0), isNegation (1)}
|
||||
|
||||
ReferenceDenms ::= SEQUENCE (SIZE(1..8, ...)) OF ActionID
|
||||
|
||||
END
|
||||
@@ -0,0 +1,306 @@
|
||||
IEEE1609dot2 {
|
||||
iso(1) identified-organization(3) ieee(111) standards-association-numbered-series-standards(2) wave-stds(1609) dot2(2) base (1) schema (1) major-version-2(2)
|
||||
}
|
||||
|
||||
--******************************************************************************
|
||||
--
|
||||
-- IEEE P1609.2 Data Types
|
||||
--
|
||||
--******************************************************************************
|
||||
|
||||
DEFINITIONS AUTOMATIC TAGS ::= BEGIN
|
||||
|
||||
EXPORTS ALL;
|
||||
|
||||
IMPORTS
|
||||
CrlSeries,
|
||||
EccP256CurvePoint,
|
||||
EciesP256EncryptedKey,
|
||||
EncryptionKey,
|
||||
GeographicRegion,
|
||||
GroupLinkageValue,
|
||||
HashAlgorithm,
|
||||
HashedId3,
|
||||
HashedId8,
|
||||
Hostname,
|
||||
IValue,
|
||||
LinkageValue,
|
||||
Opaque,
|
||||
Psid,
|
||||
PsidSsp,
|
||||
PsidSspRange,
|
||||
PublicEncryptionKey,
|
||||
PublicVerificationKey,
|
||||
SequenceOfHashedId3,
|
||||
SequenceOfPsidSsp,
|
||||
SequenceOfPsidSspRange,
|
||||
ServiceSpecificPermissions,
|
||||
Signature,
|
||||
SubjectAssurance,
|
||||
SymmetricEncryptionKey,
|
||||
ThreeDLocation,
|
||||
Time64,
|
||||
Uint3,
|
||||
Uint8,
|
||||
Uint16,
|
||||
Uint32,
|
||||
ValidityPeriod
|
||||
FROM IEEE1609dot2BaseTypes {
|
||||
iso(1) identified-organization(3) ieee(111) standards-association-numbered-series-standards(2) wave-stds(1609) dot2(2) base(1) base-types(2) major-version-2 (2)
|
||||
};
|
||||
|
||||
--
|
||||
--*********************************************************************
|
||||
--
|
||||
-- Structures for describing secured data
|
||||
--
|
||||
--*********************************************************************
|
||||
|
||||
-- Necessary to get certain tools to generate sample PDUs
|
||||
-- TestIeee1609Dot2Data ::= Ieee1609Dot2Data
|
||||
-- TestCertificate ::= Certificate
|
||||
|
||||
-- this structure belongs later in the file but putting it here avoids
|
||||
-- compiler errors with certain tools
|
||||
SignedDataPayload ::= SEQUENCE {
|
||||
data Ieee1609Dot2Data OPTIONAL,
|
||||
extDataHash HashedData OPTIONAL,
|
||||
...
|
||||
}
|
||||
(WITH COMPONENTS {..., data PRESENT} |
|
||||
WITH COMPONENTS {..., extDataHash PRESENT})
|
||||
|
||||
Ieee1609Dot2Data ::= SEQUENCE {
|
||||
protocolVersion Uint8(3),
|
||||
content Ieee1609Dot2Content
|
||||
}
|
||||
|
||||
Ieee1609Dot2Content ::= CHOICE {
|
||||
unsecuredData Opaque,
|
||||
signedData SignedData,
|
||||
encryptedData EncryptedData,
|
||||
signedCertificateRequest Opaque,
|
||||
...
|
||||
}
|
||||
|
||||
SignedData ::= SEQUENCE {
|
||||
hashId HashAlgorithm,
|
||||
tbsData ToBeSignedData,
|
||||
signer SignerIdentifier,
|
||||
signature Signature
|
||||
}
|
||||
|
||||
SignerIdentifier ::= CHOICE {
|
||||
digest HashedId8,
|
||||
certificate SequenceOfCertificate,
|
||||
self NULL,
|
||||
...
|
||||
}
|
||||
|
||||
ToBeSignedData ::= SEQUENCE {
|
||||
payload SignedDataPayload,
|
||||
headerInfo HeaderInfo
|
||||
}
|
||||
|
||||
HashedData::= CHOICE {
|
||||
sha256HashedData OCTET STRING (SIZE(32)),
|
||||
...
|
||||
}
|
||||
|
||||
HeaderInfo ::= SEQUENCE {
|
||||
psid Psid,
|
||||
generationTime Time64 OPTIONAL,
|
||||
expiryTime Time64 OPTIONAL,
|
||||
generationLocation ThreeDLocation OPTIONAL,
|
||||
p2pcdLearningRequest HashedId3 OPTIONAL,
|
||||
missingCrlIdentifier MissingCrlIdentifier OPTIONAL,
|
||||
encryptionKey EncryptionKey OPTIONAL,
|
||||
...,
|
||||
inlineP2pcdRequest SequenceOfHashedId3 OPTIONAL,
|
||||
requestedCertificate Certificate OPTIONAL
|
||||
}
|
||||
|
||||
MissingCrlIdentifier ::= SEQUENCE {
|
||||
cracaId HashedId3,
|
||||
crlSeries CrlSeries,
|
||||
...
|
||||
}
|
||||
|
||||
Countersignature ::= Ieee1609Dot2Data (WITH COMPONENTS {...,
|
||||
content (WITH COMPONENTS {...,
|
||||
signedData (WITH COMPONENTS {...,
|
||||
tbsData (WITH COMPONENTS {...,
|
||||
payload (WITH COMPONENTS {...,
|
||||
data ABSENT,
|
||||
extDataHash PRESENT
|
||||
}),
|
||||
headerInfo(WITH COMPONENTS {...,
|
||||
generationTime PRESENT,
|
||||
expiryTime ABSENT,
|
||||
generationLocation ABSENT,
|
||||
p2pcdLearningRequest ABSENT,
|
||||
missingCrlIdentifier ABSENT,
|
||||
encryptionKey ABSENT
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
--**********************************************************************
|
||||
--
|
||||
-- Structures for describing encrypted data
|
||||
--
|
||||
--**********************************************************************
|
||||
|
||||
EncryptedData ::= SEQUENCE {
|
||||
recipients SequenceOfRecipientInfo,
|
||||
ciphertext SymmetricCiphertext
|
||||
}
|
||||
RecipientInfo ::= CHOICE {
|
||||
pskRecipInfo PreSharedKeyRecipientInfo,
|
||||
symmRecipInfo SymmRecipientInfo,
|
||||
certRecipInfo PKRecipientInfo,
|
||||
signedDataRecipInfo PKRecipientInfo,
|
||||
rekRecipInfo PKRecipientInfo
|
||||
}
|
||||
|
||||
SequenceOfRecipientInfo ::= SEQUENCE OF RecipientInfo
|
||||
|
||||
PreSharedKeyRecipientInfo ::= HashedId8
|
||||
SymmRecipientInfo ::= SEQUENCE {
|
||||
recipientId HashedId8,
|
||||
encKey SymmetricCiphertext
|
||||
}
|
||||
|
||||
PKRecipientInfo ::= SEQUENCE {
|
||||
recipientId HashedId8,
|
||||
encKey EncryptedDataEncryptionKey
|
||||
}
|
||||
|
||||
EncryptedDataEncryptionKey ::= CHOICE {
|
||||
eciesNistP256 EciesP256EncryptedKey,
|
||||
eciesBrainpoolP256r1 EciesP256EncryptedKey,
|
||||
...
|
||||
}
|
||||
|
||||
SymmetricCiphertext ::= CHOICE {
|
||||
aes128ccm AesCcmCiphertext,
|
||||
...
|
||||
}
|
||||
|
||||
AesCcmCiphertext ::= SEQUENCE {
|
||||
nonce OCTET STRING (SIZE (12)),
|
||||
ccmCiphertext Opaque -- 16 bytes longer than plaintext
|
||||
}
|
||||
|
||||
|
||||
--**********************************************************************
|
||||
--
|
||||
-- Certificates and other security management data structures
|
||||
--
|
||||
--**********************************************************************
|
||||
|
||||
-- Certificates are implicit (type = implicit, toBeSigned includes
|
||||
-- reconstruction value, signature absent) or explicit (type = explicit,
|
||||
-- toBeSigned includes verification key, signature present).
|
||||
|
||||
Certificate ::= CertificateBase (ImplicitCertificate | ExplicitCertificate)
|
||||
|
||||
SequenceOfCertificate ::= SEQUENCE OF Certificate
|
||||
|
||||
CertificateBase ::= SEQUENCE {
|
||||
version Uint8(3),
|
||||
type CertificateType,
|
||||
issuer IssuerIdentifier,
|
||||
toBeSigned ToBeSignedCertificate,
|
||||
signature Signature OPTIONAL
|
||||
}
|
||||
|
||||
CertificateType ::= ENUMERATED {
|
||||
explicit,
|
||||
implicit,
|
||||
...
|
||||
}
|
||||
|
||||
ImplicitCertificate ::= CertificateBase (WITH COMPONENTS {...,
|
||||
type(implicit),
|
||||
toBeSigned (WITH COMPONENTS {...,
|
||||
verifyKeyIndicator(WITH COMPONENTS {reconstructionValue})
|
||||
}),
|
||||
signature ABSENT
|
||||
})
|
||||
|
||||
ExplicitCertificate ::= CertificateBase (WITH COMPONENTS {...,
|
||||
type(explicit),
|
||||
toBeSigned(WITH COMPONENTS {...,
|
||||
verifyKeyIndicator(WITH COMPONENTS {verificationKey})
|
||||
}),
|
||||
signature PRESENT
|
||||
})
|
||||
|
||||
IssuerIdentifier ::= CHOICE {
|
||||
sha256AndDigest HashedId8,
|
||||
self HashAlgorithm,
|
||||
...,
|
||||
sha384AndDigest HashedId8
|
||||
}
|
||||
|
||||
ToBeSignedCertificate ::= SEQUENCE {
|
||||
id CertificateId,
|
||||
cracaId HashedId3,
|
||||
crlSeries CrlSeries,
|
||||
validityPeriod ValidityPeriod,
|
||||
region GeographicRegion OPTIONAL,
|
||||
assuranceLevel SubjectAssurance OPTIONAL,
|
||||
appPermissions SequenceOfPsidSsp OPTIONAL,
|
||||
certIssuePermissions SequenceOfPsidGroupPermissions OPTIONAL,
|
||||
certRequestPermissions SequenceOfPsidGroupPermissions OPTIONAL,
|
||||
canRequestRollover NULL OPTIONAL,
|
||||
encryptionKey PublicEncryptionKey OPTIONAL,
|
||||
verifyKeyIndicator VerificationKeyIndicator,
|
||||
...
|
||||
}
|
||||
(WITH COMPONENTS { ..., appPermissions PRESENT} |
|
||||
WITH COMPONENTS { ..., certIssuePermissions PRESENT} |
|
||||
WITH COMPONENTS { ..., certRequestPermissions PRESENT})
|
||||
|
||||
CertificateId ::= CHOICE {
|
||||
linkageData LinkageData,
|
||||
name Hostname,
|
||||
binaryId OCTET STRING(SIZE(1..64)),
|
||||
none NULL,
|
||||
...
|
||||
}
|
||||
|
||||
LinkageData ::= SEQUENCE {
|
||||
iCert IValue,
|
||||
linkage-value LinkageValue,
|
||||
group-linkage-value GroupLinkageValue OPTIONAL
|
||||
}
|
||||
|
||||
EndEntityType ::= BIT STRING { app (0), enrol (1) } (SIZE (8)) (ALL EXCEPT {})
|
||||
|
||||
PsidGroupPermissions ::= SEQUENCE {
|
||||
subjectPermissions SubjectPermissions,
|
||||
minChainLength INTEGER DEFAULT 1,
|
||||
chainLengthRange INTEGER DEFAULT 0,
|
||||
eeType EndEntityType DEFAULT {app} -- vanetza-idf: IEEE Std 1609.2-2022 6.4.28 (was '00'H)
|
||||
}
|
||||
|
||||
SequenceOfPsidGroupPermissions ::= SEQUENCE OF PsidGroupPermissions
|
||||
|
||||
SubjectPermissions ::= CHOICE {
|
||||
explicit SequenceOfPsidSspRange,
|
||||
all NULL,
|
||||
...
|
||||
}
|
||||
|
||||
VerificationKeyIndicator ::= CHOICE {
|
||||
verificationKey PublicVerificationKey,
|
||||
reconstructionValue EccP256CurvePoint,
|
||||
...
|
||||
}
|
||||
|
||||
END
|
||||
@@ -0,0 +1,330 @@
|
||||
IEEE1609dot2BaseTypes {
|
||||
iso(1) identified-organization(3) ieee(111) standards-association-numbered-series-standards(2) wave-stds(1609) dot2(2) base(1) base-types(2) major-version-2(2)
|
||||
}
|
||||
|
||||
--
|
||||
--********************************************************************
|
||||
-- IEEE P1609.2 Base Data Types
|
||||
--
|
||||
--********************************************************************
|
||||
|
||||
DEFINITIONS AUTOMATIC TAGS ::= BEGIN
|
||||
|
||||
EXPORTS ALL;
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Integers
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
Uint3 ::= INTEGER (0..7) -- (hex) 07
|
||||
Uint8 ::= INTEGER (0..255) -- (hex) ff
|
||||
Uint16 ::= INTEGER (0..65535) -- (hex) ff ff
|
||||
Uint32 ::= INTEGER (0..4294967295) -- (hex) ff ff ff ff
|
||||
Uint64 ::= INTEGER (0..18446744073709551615) -- (hex) ff ff ff ff ff ff ff ff
|
||||
|
||||
SequenceOfUint8 ::= SEQUENCE OF Uint8
|
||||
SequenceOfUint16 ::= SEQUENCE OF Uint16
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- OCTET STRING types
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
Opaque ::= OCTET STRING
|
||||
|
||||
HashedId10 ::= OCTET STRING (SIZE(10))
|
||||
HashedId8 ::= OCTET STRING (SIZE(8))
|
||||
HashedId3 ::= OCTET STRING (SIZE(3))
|
||||
SequenceOfHashedId3 ::= SEQUENCE OF HashedId3
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Time
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
Time32 ::= Uint32
|
||||
Time64 ::= Uint64
|
||||
|
||||
ValidityPeriod ::= SEQUENCE {
|
||||
start Time32,
|
||||
duration Duration
|
||||
}
|
||||
|
||||
Duration ::= CHOICE {
|
||||
microseconds Uint16,
|
||||
milliseconds Uint16,
|
||||
seconds Uint16,
|
||||
minutes Uint16,
|
||||
hours Uint16,
|
||||
sixtyHours Uint16,
|
||||
years Uint16
|
||||
}
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Location
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
GeographicRegion ::= CHOICE {
|
||||
circularRegion CircularRegion,
|
||||
rectangularRegion SequenceOfRectangularRegion,
|
||||
polygonalRegion PolygonalRegion,
|
||||
identifiedRegion SequenceOfIdentifiedRegion,
|
||||
...
|
||||
}
|
||||
|
||||
CircularRegion ::= SEQUENCE {
|
||||
center TwoDLocation,
|
||||
radius Uint16
|
||||
}
|
||||
|
||||
RectangularRegion ::= SEQUENCE {
|
||||
northWest TwoDLocation,
|
||||
southEast TwoDLocation
|
||||
}
|
||||
|
||||
SequenceOfRectangularRegion ::= SEQUENCE OF RectangularRegion
|
||||
|
||||
PolygonalRegion ::= SEQUENCE SIZE(3..MAX) OF TwoDLocation
|
||||
|
||||
TwoDLocation ::= SEQUENCE {
|
||||
latitude Latitude,
|
||||
longitude Longitude
|
||||
}
|
||||
|
||||
IdentifiedRegion ::= CHOICE {
|
||||
countryOnly CountryOnly,
|
||||
countryAndRegions CountryAndRegions,
|
||||
countryAndSubregions CountryAndSubregions,
|
||||
...
|
||||
}
|
||||
|
||||
SequenceOfIdentifiedRegion ::= SEQUENCE OF IdentifiedRegion
|
||||
|
||||
CountryOnly ::= Uint16
|
||||
|
||||
CountryAndRegions ::= SEQUENCE {
|
||||
countryOnly CountryOnly,
|
||||
regions SequenceOfUint8
|
||||
}
|
||||
|
||||
CountryAndSubregions ::= SEQUENCE {
|
||||
country CountryOnly,
|
||||
regionAndSubregions SequenceOfRegionAndSubregions
|
||||
}
|
||||
|
||||
RegionAndSubregions ::= SEQUENCE {
|
||||
region Uint8,
|
||||
subregions SequenceOfUint16
|
||||
}
|
||||
|
||||
SequenceOfRegionAndSubregions ::= SEQUENCE OF RegionAndSubregions
|
||||
|
||||
ThreeDLocation ::= SEQUENCE {
|
||||
latitude Latitude,
|
||||
longitude Longitude,
|
||||
elevation Elevation
|
||||
}
|
||||
|
||||
Latitude ::= NinetyDegreeInt
|
||||
Longitude ::= OneEightyDegreeInt
|
||||
Elevation ::= ElevInt
|
||||
|
||||
NinetyDegreeInt ::= INTEGER {
|
||||
min (-900000000),
|
||||
max (900000000),
|
||||
unknown (900000001)
|
||||
} (-900000000..900000001)
|
||||
|
||||
KnownLatitude ::= NinetyDegreeInt (min..max) -- Minus 90deg to +90deg in microdegree intervals
|
||||
UnknownLatitude ::= NinetyDegreeInt (unknown)
|
||||
|
||||
OneEightyDegreeInt ::= INTEGER {
|
||||
min (-1799999999),
|
||||
max (1800000000),
|
||||
unknown (1800000001)
|
||||
} (-1799999999..1800000001)
|
||||
|
||||
KnownLongitude ::= OneEightyDegreeInt (min..max)
|
||||
UnknownLongitude ::= OneEightyDegreeInt (unknown)
|
||||
|
||||
ElevInt ::= Uint16 -- Range is from -4096 to 61439 in units of one-tenth of a meter
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Crypto
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
Signature ::= CHOICE {
|
||||
ecdsaNistP256Signature EcdsaP256Signature,
|
||||
ecdsaBrainpoolP256r1Signature EcdsaP256Signature,
|
||||
...,
|
||||
ecdsaBrainpoolP384r1Signature EcdsaP384Signature
|
||||
}
|
||||
|
||||
EcdsaP256Signature ::= SEQUENCE {
|
||||
rSig EccP256CurvePoint,
|
||||
sSig OCTET STRING (SIZE (32))
|
||||
}
|
||||
|
||||
EcdsaP384Signature ::= SEQUENCE {
|
||||
rSig EccP384CurvePoint,
|
||||
sSig OCTET STRING (SIZE (48))
|
||||
}
|
||||
|
||||
EccP256CurvePoint ::= CHOICE {
|
||||
x-only OCTET STRING (SIZE (32)),
|
||||
fill NULL, -- consistency with 1363 / X9.62
|
||||
compressed-y-0 OCTET STRING (SIZE (32)),
|
||||
compressed-y-1 OCTET STRING (SIZE (32)),
|
||||
uncompressedP256 SEQUENCE {
|
||||
x OCTET STRING (SIZE (32)),
|
||||
y OCTET STRING (SIZE (32))
|
||||
}
|
||||
}
|
||||
|
||||
EccP384CurvePoint ::= CHOICE {
|
||||
x-only OCTET STRING (SIZE (48)),
|
||||
fill NULL, -- consistency w 1363 / X9.62
|
||||
compressed-y-0 OCTET STRING (SIZE (48)),
|
||||
compressed-y-1 OCTET STRING (SIZE (48)),
|
||||
uncompressedP384 SEQUENCE {
|
||||
x OCTET STRING (SIZE (48)),
|
||||
y OCTET STRING (SIZE (48))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
SymmAlgorithm ::= ENUMERATED {
|
||||
aes128Ccm,
|
||||
...
|
||||
}
|
||||
|
||||
HashAlgorithm ::= ENUMERATED {
|
||||
sha256,
|
||||
...,
|
||||
sha384
|
||||
}
|
||||
|
||||
EciesP256EncryptedKey ::= SEQUENCE {
|
||||
v EccP256CurvePoint,
|
||||
c OCTET STRING (SIZE (16)),
|
||||
t OCTET STRING (SIZE (16))
|
||||
}
|
||||
|
||||
EncryptionKey ::= CHOICE {
|
||||
public PublicEncryptionKey,
|
||||
symmetric SymmetricEncryptionKey
|
||||
}
|
||||
|
||||
PublicEncryptionKey ::= SEQUENCE {
|
||||
supportedSymmAlg SymmAlgorithm,
|
||||
publicKey BasePublicEncryptionKey
|
||||
}
|
||||
|
||||
BasePublicEncryptionKey ::= CHOICE {
|
||||
eciesNistP256 EccP256CurvePoint,
|
||||
eciesBrainpoolP256r1 EccP256CurvePoint,
|
||||
...
|
||||
}
|
||||
|
||||
PublicVerificationKey ::= CHOICE {
|
||||
ecdsaNistP256 EccP256CurvePoint,
|
||||
ecdsaBrainpoolP256r1 EccP256CurvePoint,
|
||||
...,
|
||||
ecdsaBrainpoolP384r1 EccP384CurvePoint
|
||||
}
|
||||
|
||||
SymmetricEncryptionKey ::= CHOICE {
|
||||
aes128Ccm OCTET STRING(SIZE(16)),
|
||||
...
|
||||
}
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- PSID / ITS-AID
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
PsidSsp ::= SEQUENCE {
|
||||
psid Psid,
|
||||
ssp ServiceSpecificPermissions OPTIONAL
|
||||
}
|
||||
|
||||
SequenceOfPsidSsp ::= SEQUENCE OF PsidSsp
|
||||
|
||||
Psid ::= INTEGER (0..MAX)
|
||||
|
||||
SequenceOfPsid ::= SEQUENCE OF Psid
|
||||
|
||||
ServiceSpecificPermissions ::= CHOICE {
|
||||
opaque OCTET STRING (SIZE(0..MAX)),
|
||||
...,
|
||||
bitmapSsp BitmapSsp
|
||||
}
|
||||
|
||||
BitmapSsp ::= OCTET STRING (SIZE(0..31))
|
||||
|
||||
PsidSspRange ::= SEQUENCE {
|
||||
psid Psid,
|
||||
sspRange SspRange OPTIONAL
|
||||
}
|
||||
|
||||
SequenceOfPsidSspRange ::= SEQUENCE OF PsidSspRange
|
||||
|
||||
SspRange ::= CHOICE {
|
||||
opaque SequenceOfOctetString,
|
||||
all NULL,
|
||||
... ,
|
||||
bitmapSspRange BitmapSspRange
|
||||
}
|
||||
|
||||
BitmapSspRange ::= SEQUENCE {
|
||||
sspValue OCTET STRING (SIZE(1..32)),
|
||||
sspBitmask OCTET STRING (SIZE(1..32))
|
||||
}
|
||||
|
||||
SequenceOfOctetString ::= SEQUENCE (SIZE (0..MAX)) OF OCTET STRING (SIZE(0..MAX))
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Goes in certs
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
SubjectAssurance ::= OCTET STRING (SIZE(1))
|
||||
|
||||
CrlSeries ::= Uint16
|
||||
|
||||
|
||||
-- ------------------------------------------------------------------
|
||||
--
|
||||
-- Pseudonym Linkage
|
||||
--
|
||||
-- ------------------------------------------------------------------
|
||||
|
||||
IValue ::= Uint16
|
||||
Hostname ::= UTF8String (SIZE(0..255))
|
||||
LinkageValue ::= OCTET STRING (SIZE(9))
|
||||
GroupLinkageValue ::= SEQUENCE {
|
||||
jValue OCTET STRING (SIZE(4)),
|
||||
value OCTET STRING (SIZE(9))
|
||||
}
|
||||
|
||||
LaId ::= OCTET STRING (SIZE(2))
|
||||
LinkageSeed ::= OCTET STRING (SIZE(16))
|
||||
|
||||
END
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user