Compare commits
4
Commits
d0fcb45a55
...
6dce3977d7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6dce3977d7 | ||
|
|
8cbe3c337c | ||
|
|
fc3354a4ba | ||
|
|
9f77f9f0e4 |
@@ -5,6 +5,66 @@ Engineering to-do list. The reviewer-facing open items live in
|
|||||||
|
|
||||||
## Waiting on hardware
|
## Waiting on hardware
|
||||||
|
|
||||||
|
### 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)
|
### 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.
|
Needs the phone, a second station sending (the simulated car works) and, for the CiT One part, the OBU.
|
||||||
@@ -18,11 +78,23 @@ Settings > Developer > V2X data logger. 110 unit tests pass. ESP32-C5 path check
|
|||||||
- [ ] **CiT One:** same, `source='cit_one'`, `rssi_dbm` NULL, `obu_*` filled from `v2x/rx/obu_gnss`.
|
- [ ] **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.
|
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).
|
- [ ] **Screen off for a few minutes** with the log running: rows keep arriving (foreground service).
|
||||||
- [ ] **MAPEM and VAM on the ESP32-C5 need a firmware change.** `gn_unwrap.c` accepts only BTP ports
|
- [ ] **MAPEM and VAM on the ESP32-C5.** Firmware side done 2026-10-28: `gn_unwrap.c` accepts 2003
|
||||||
2001, 2002, 2004; add 2003 (MAPEM) and 2018 (VAM) and reflash. Real MAPEMs are mostly over the
|
(MAPEM) and 2018 (VAM), signed or not. The bench RSU's MAPEM is 295 bytes and fits; real
|
||||||
512-byte link limit, so most will still be counted as oversize drops. The app side already logs
|
road MAPEMs over 494 bytes are still dropped as oversize (no fragmentation). On air with the
|
||||||
any port. On the CiT One, MAPEM arrives via `v2x/rx/mapem` (subscribed now) or the processed
|
bench listener on COM3 (`tools/bench_listen_watch.py COM3 90`): 104 MAPEM (295 B, GBC), 185
|
||||||
`v2x-uca/output/json/map` topic; the API lists no VAM topic, so no VAM rows are expected there.
|
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)
|
### Signed-TX firmware (vanetza-idf port), VAM and BLE: first on-air checks (added 2026-09-23)
|
||||||
|
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
|
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
|
||||||
val obuHardware by mqttViewModel.obuHardware.collectAsState()
|
val obuHardware by mqttViewModel.obuHardware.collectAsState()
|
||||||
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
|
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
|
||||||
|
val stationStatus by mqttViewModel.stationStatus.collectAsState()
|
||||||
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
||||||
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
||||||
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
||||||
@@ -100,7 +101,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// Both flows already expire their own entries on a clock, so nothing here has to
|
// 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.
|
// decide when a hazard or a traffic light has gone stale.
|
||||||
val denmEvents by mqttViewModel.denmEvents.collectAsState()
|
val denmEvents by mqttViewModel.denmEvents.collectAsState()
|
||||||
val spatIntersections by mqttViewModel.spatIntersections.collectAsState()
|
val trafficLights by mqttViewModel.trafficLights.collectAsState()
|
||||||
val ownCamPosition by mqttViewModel.ownCamPosition.collectAsState()
|
val ownCamPosition by mqttViewModel.ownCamPosition.collectAsState()
|
||||||
val v2xLogState by logViewModel.state.collectAsState()
|
val v2xLogState by logViewModel.state.collectAsState()
|
||||||
val v2xLogFiles by logViewModel.files.collectAsState()
|
val v2xLogFiles by logViewModel.files.collectAsState()
|
||||||
@@ -163,6 +164,8 @@ class MainActivity : AppCompatActivity() {
|
|||||||
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
|
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
|
||||||
esp32LinkState = esp32LinkState,
|
esp32LinkState = esp32LinkState,
|
||||||
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
|
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
|
||||||
|
obuBatteryLow = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryLow == true,
|
||||||
|
obuBatteryCritical = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryCritical == true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -185,7 +188,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
obuStationTypeWarning = obuStationTypeWarning,
|
obuStationTypeWarning = obuStationTypeWarning,
|
||||||
obuStationType = obuStationType,
|
obuStationType = obuStationType,
|
||||||
hazards = denmEvents,
|
hazards = denmEvents,
|
||||||
signals = spatIntersections,
|
signals = trafficLights,
|
||||||
ownPosition = ownCamPosition,
|
ownPosition = ownCamPosition,
|
||||||
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
|
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
|
||||||
onNavigateToSensors = {
|
onNavigateToSensors = {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
|||||||
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
||||||
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
|
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
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.asn1.SpatemUperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.cam.Cam
|
import com.hawhamburg.micr0bu.domain.cam.Cam
|
||||||
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
||||||
@@ -29,6 +30,7 @@ import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
|
|||||||
import com.hawhamburg.micr0bu.domain.cam.OwnTxLoopback
|
import com.hawhamburg.micr0bu.domain.cam.OwnTxLoopback
|
||||||
import com.hawhamburg.micr0bu.domain.cam.StationType
|
import com.hawhamburg.micr0bu.domain.cam.StationType
|
||||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.MapEvent
|
||||||
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
|
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
|
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
|
||||||
@@ -197,6 +199,17 @@ class CamUseCaseRepository @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
val decodedSpat: SharedFlow<SpatEvent> = _decodedSpat.asSharedFlow()
|
val decodedSpat: SharedFlow<SpatEvent> = _decodedSpat.asSharedFlow()
|
||||||
|
|
||||||
|
private val _decodedMap = MutableSharedFlow<MapEvent>(replay = 16, extraBufferCapacity = 16)
|
||||||
|
/**
|
||||||
|
* MAPEMs decoded from UPER, from the ESP32-C5 (BTP port 2003, since firmware d0fcb45) or the
|
||||||
|
* CiT One's `v2x/rx/mapem` topic: the lane geometry SPATEM's signal groups refer to. Replayed
|
||||||
|
* like [decodedSpat], since a MAPEM repeats only about once a second.
|
||||||
|
*
|
||||||
|
* The ESP32-C5 forwards only MAPEMs of up to 494 bytes (one link message); road MAPEMs are often
|
||||||
|
* bigger and then arrive only over the CiT One.
|
||||||
|
*/
|
||||||
|
val decodedMap: SharedFlow<MapEvent> = _decodedMap.asSharedFlow()
|
||||||
|
|
||||||
private val _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
|
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
|
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
|
||||||
@@ -242,8 +255,7 @@ class CamUseCaseRepository @Inject constructor(
|
|||||||
source = "mqtt",
|
source = "mqtt",
|
||||||
)
|
)
|
||||||
RAW_SPATEM_TOPIC -> handleSpatUper(envelope.payload, rssiDbm = null, source = "mqtt")
|
RAW_SPATEM_TOPIC -> handleSpatUper(envelope.payload, rssiDbm = null, source = "mqtt")
|
||||||
// No MAPEM decoder yet; it is received for the V2X data logger only.
|
RAW_MAPEM_TOPIC -> handleMapUper(envelope.payload, rssiDbm = null, source = "mqtt")
|
||||||
RAW_MAPEM_TOPIC -> Unit
|
|
||||||
else -> Log.w(TAG, "rawV2x: unexpected topic ${raw.topic}")
|
else -> Log.w(TAG, "rawV2x: unexpected topic ${raw.topic}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,6 +308,7 @@ class CamUseCaseRepository @Inject constructor(
|
|||||||
BtpPort.CAM -> handleCamFromSerial(v2x)
|
BtpPort.CAM -> handleCamFromSerial(v2x)
|
||||||
BtpPort.DENM -> handleDenmFromSerial(v2x)
|
BtpPort.DENM -> handleDenmFromSerial(v2x)
|
||||||
BtpPort.SPATEM -> handleSpatFromSerial(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
|
// The firmware only forwards ports it was told to accept, so anything else
|
||||||
// means the two sides have drifted out of sync.
|
// means the two sides have drifted out of sync.
|
||||||
else -> Log.w(TAG, "unexpected BTP port ${v2x.btpPort} from firmware")
|
else -> Log.w(TAG, "unexpected BTP port ${v2x.btpPort} from firmware")
|
||||||
@@ -569,6 +582,19 @@ class CamUseCaseRepository @Inject constructor(
|
|||||||
_decodedSpat.tryEmit(spat)
|
_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
|
* 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
|
* it came off the serial link or an MQTT topic. [rssiDbm] is null on the MQTT path: the
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import com.hawhamburg.micr0bu.data.transport.SerialFrameType
|
|||||||
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
|
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
|
||||||
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
|
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
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.asn1.SpatemUperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
|
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
|
||||||
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
|
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
|
||||||
@@ -91,13 +92,14 @@ data class V2xLogFile(val file: File, val sizeBytes: Long, val modifiedMs: Long,
|
|||||||
* not publish `v2x/rx/mapem`). The OBU's position comes from `v2x/rx/obu_gnss`. The API carries
|
* 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.
|
* no RSSI, so that column stays NULL.
|
||||||
*
|
*
|
||||||
* Every message is stored, including kinds the app cannot decode (MAPEM, VAM): the UPER bytes go
|
* 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
|
* in the file untouched, and where a decoder exists a few fields are decoded alongside for
|
||||||
* convenience. A message is never skipped because decoding failed.
|
* 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 current ESP32-C5 firmware
|
* What it can hear is bounded by the hardware, not by this class: the ESP32-C5 firmware forwards
|
||||||
* forwards only BTP ports 2001, 2002 and 2004 (see `gn_unwrap.c`), so MAPEM and VAM appear in an
|
* BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only
|
||||||
* ESP32 log only once the firmware accepts ports 2003 and 2018.
|
* messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One.
|
||||||
*
|
*
|
||||||
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
|
* 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.
|
* keeps the process alive and the CPU awake while a log runs; this class does the work.
|
||||||
@@ -320,6 +322,15 @@ class V2xLogger @Inject constructor(
|
|||||||
Decoded(summary = "intersections=" + s.intersections.joinToString(",") { it.key } +
|
Decoded(summary = "intersections=" + s.intersections.joinToString(",") { it.key } +
|
||||||
" movements=" + s.intersections.sumOf { it.movements.size })
|
" 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
|
else -> null
|
||||||
}
|
}
|
||||||
}.getOrNull() ?: Decoded()
|
}.getOrNull() ?: Decoded()
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ class BleLinkTransport @Inject constructor(
|
|||||||
private const val SCAN_TIMEOUT_MS = 15_000L
|
private const val SCAN_TIMEOUT_MS = 15_000L
|
||||||
/** Long enough for the user to find and type the passkey in the system dialog. */
|
/** 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 BOND_TIMEOUT_MS = 60_000L
|
||||||
|
private const val KEY_LAST_ADDRESS = "last_address"
|
||||||
private const val GATT_OP_TIMEOUT_MS = 5_000L
|
private const val GATT_OP_TIMEOUT_MS = 5_000L
|
||||||
/** After a working link dropped: try again soon. */
|
/** After a working link dropped: try again soon. */
|
||||||
private const val RECONNECT_DELAY_MS = 1_000L
|
private const val RECONNECT_DELAY_MS = 1_000L
|
||||||
@@ -114,6 +115,20 @@ class BleLinkTransport @Inject constructor(
|
|||||||
|
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
|
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)
|
private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
|
||||||
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
|
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
|
||||||
@@ -223,7 +238,10 @@ class BleLinkTransport @Inject constructor(
|
|||||||
_state.value = Esp32LinkState.DEVICE_ATTACHED
|
_state.value = Esp32LinkState.DEVICE_ATTACHED
|
||||||
// A bonded micrOBU is reused without scanning: its address is stable (public address), and
|
// A bonded micrOBU is reused without scanning: its address is stable (public address), and
|
||||||
// this is what makes a reconnect after a dropout fast.
|
// this is what makes a reconnect after a dropout fast.
|
||||||
val device = adapter.bondedDevices.firstOrNull { it.name?.startsWith(NAME_PREFIX) == true }
|
// Android may hold several bonded micrOBUs (a replaced board stays bonded): the one that
|
||||||
|
// worked last goes first, and each failed connection moves on to the next.
|
||||||
|
val bonded = adapter.bondedDevices.filter { it.name?.startsWith(NAME_PREFIX) == true }
|
||||||
|
val device = pickBonded(bonded)
|
||||||
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
|
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
|
||||||
deviceName = device.name
|
deviceName = device.name
|
||||||
_detail.value = null
|
_detail.value = null
|
||||||
@@ -232,6 +250,7 @@ class BleLinkTransport @Inject constructor(
|
|||||||
connected = CompletableDeferred()
|
connected = CompletableDeferred()
|
||||||
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
|
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
|
||||||
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
|
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
|
||||||
|
if (bonded.size > 1) connectAttempt++
|
||||||
return fail("Could not connect to ${device.name}")
|
return fail("Could not connect to ${device.name}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,6 +296,8 @@ class BleLinkTransport @Inject constructor(
|
|||||||
if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
|
if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
|
||||||
}
|
}
|
||||||
_state.value = Esp32LinkState.CONNECTED
|
_state.value = Esp32LinkState.CONNECTED
|
||||||
|
connectAttempt = 0
|
||||||
|
prefs.edit().putString(KEY_LAST_ADDRESS, device.address).apply()
|
||||||
Log.i(TAG, "BLE station link ready: ${device.name}")
|
Log.i(TAG, "BLE station link ready: ${device.name}")
|
||||||
// Wait until the link drops (callback completes `connected` anew with false).
|
// Wait until the link drops (callback completes `connected` anew with false).
|
||||||
val dropped = CompletableDeferred<Boolean>()
|
val dropped = CompletableDeferred<Boolean>()
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ object Crc16CcittFalse {
|
|||||||
object BtpPort {
|
object BtpPort {
|
||||||
const val CAM = 2001
|
const val CAM = 2001
|
||||||
const val DENM = 2002
|
const val DENM = 2002
|
||||||
|
const val MAPEM = 2003
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Watch the crossover: SPATEM is BTP port **2004** but ItsPduHeader messageID **4**, while
|
* Watch the crossover: SPATEM is BTP port **2004** but ItsPduHeader messageID **4**, while
|
||||||
|
|||||||
@@ -212,7 +212,11 @@ data class LinkResult(val code: Int, val detail: ByteArray) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** STATUS body (103 octets), sent by the micrOBU every second. Counters are since the last configure. */
|
/**
|
||||||
|
* STATUS body, sent by the micrOBU every second. Counters are since the last configure. 103 octets in
|
||||||
|
* the colleague's layout; this firmware appends [batteryMv] and [batteryFlags] (106 octets), and a
|
||||||
|
* 103-octet body from an older board still decodes, with the battery left at "not measured".
|
||||||
|
*/
|
||||||
data class StationStatus(
|
data class StationStatus(
|
||||||
val uptimeMs: Long,
|
val uptimeMs: Long,
|
||||||
val configured: Boolean,
|
val configured: Boolean,
|
||||||
@@ -235,7 +239,18 @@ data class StationStatus(
|
|||||||
val linkMalformed: Long,
|
val linkMalformed: Long,
|
||||||
val potiUpdates: Long,
|
val potiUpdates: Long,
|
||||||
val itsTimeMs: 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,
|
||||||
|
/** BATTERY_FLAG_* bits. */
|
||||||
|
val batteryFlags: Int = 0,
|
||||||
) {
|
) {
|
||||||
|
/** The cell is below the firmware's warning threshold. */
|
||||||
|
val batteryLow: Boolean get() = batteryMv > 0 && (batteryFlags and BATTERY_FLAG_LOW) != 0
|
||||||
|
/** The cell is below the shutdown threshold: the board powers down unless this phone keeps it on USB. */
|
||||||
|
val batteryCritical: Boolean get() = batteryMv > 0 && (batteryFlags and BATTERY_FLAG_CRITICAL) != 0
|
||||||
|
/** 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. */
|
/** Signing refusals of every kind: no usable ticket, a pending id change, or a missing permission. */
|
||||||
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
|
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
|
||||||
|
|
||||||
@@ -244,10 +259,35 @@ data class StationStatus(
|
|||||||
override fun hashCode(): Int = toString().hashCode()
|
override fun hashCode(): Int = toString().hashCode()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/** Octets of the colleague's STATUS body. */
|
||||||
const val SIZE = 103
|
const val SIZE = 103
|
||||||
|
/** Octets with the MicrOBU battery fields appended. */
|
||||||
|
const val SIZE_WITH_BATTERY = 106
|
||||||
|
const val BATTERY_FLAG_LOW = 0x01
|
||||||
|
const val BATTERY_FLAG_CRITICAL = 0x02
|
||||||
|
|
||||||
|
/** 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 103-octet body and any body of at least 106 octets; 104 or 105 are malformed. */
|
||||||
fun decode(body: ByteArray): StationStatus? {
|
fun decode(body: ByteArray): StationStatus? {
|
||||||
if (body.size != SIZE) return null
|
if (body.size != SIZE && body.size < SIZE_WITH_BATTERY) return null
|
||||||
fun u8(i: Int) = body[i].toInt() and 0xFF
|
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 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)) }
|
fun u64(i: Int) = (0 until 8).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
|
||||||
@@ -268,6 +308,8 @@ data class StationStatus(
|
|||||||
// c + 56: link_rx_frames
|
// c + 56: link_rx_frames
|
||||||
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
|
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
|
||||||
itsTimeMs = u64(95),
|
itsTimeMs = u64(95),
|
||||||
|
batteryMv = if (body.size >= SIZE_WITH_BATTERY) u8(103) or (u8(104) shl 8) else 0,
|
||||||
|
batteryFlags = if (body.size >= SIZE_WITH_BATTERY) u8(105) else 0,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
package com.hawhamburg.micr0bu.domain.spat
|
||||||
|
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.LaneConnection
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.LaneType
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.MapLane
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.MapPoint
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.Maneuvers
|
||||||
|
import com.hawhamburg.micr0bu.domain.map.lanePoints
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.atan2
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.hypot
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A signalised intersection as a road user sees it: SPATEM's signal groups placed on MAPEM's lanes.
|
||||||
|
*
|
||||||
|
* MAPEM says "ingress lane 1 may be left straight ahead for lane 6, under signal group 1"; SPATEM
|
||||||
|
* says "signal group 1 is green for another 12 s". Joined, that is "North in, straight: green,
|
||||||
|
* 12 s" - and, with the rider's position and heading, which of those is the rider's own light.
|
||||||
|
*/
|
||||||
|
data class TrafficLight(
|
||||||
|
/** `region/id`, as [IntersectionSignalState.key] and [IntersectionGeometry.key]. */
|
||||||
|
val key: String,
|
||||||
|
/** The latest SPATEM for this intersection, if one has been heard. */
|
||||||
|
val signal: SpatIntersection?,
|
||||||
|
/** The latest MAPEM for it, if one has been heard. Without it, signal groups are bare numbers. */
|
||||||
|
val geometry: IntersectionGeometry?,
|
||||||
|
/** Every ingress lane that has a signalled connection, in MAPEM order. */
|
||||||
|
val approaches: List<ApproachSignals>,
|
||||||
|
/** The ingress lane the rider is on, when [geometry], a position and a heading say so. */
|
||||||
|
val ownApproach: OwnApproach?,
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* The SPATEM's revision differs from the MAPEM's: the geometry the signal groups refer to has
|
||||||
|
* changed since this MAPEM, so the lane labels may be wrong until the new MAPEM arrives.
|
||||||
|
*/
|
||||||
|
val revisionMismatch: Boolean
|
||||||
|
get() = signal != null && geometry != null && signal.state.revision != geometry.revision
|
||||||
|
|
||||||
|
val name: String? get() = geometry?.name
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One ingress lane and the light for each way out of it. */
|
||||||
|
data class ApproachSignals(
|
||||||
|
val lane: MapLane,
|
||||||
|
/** Where the lane's stop line is (its first node). */
|
||||||
|
val stopLine: MapPoint,
|
||||||
|
/** Travel direction into the intersection, degrees clockwise from north. */
|
||||||
|
val bearingDeg: Double,
|
||||||
|
val exits: List<LaneExit>,
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* Exits grouped by signal group, each with every turn that group controls: the usual case is
|
||||||
|
* one group for straight-and-right and another for left, and a rider wants one light per group.
|
||||||
|
*/
|
||||||
|
val byGroup: List<Pair<Int?, List<LaneExit>>>
|
||||||
|
get() = exits.groupBy { it.connection.signalGroup }.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One `Connection` with the turn it makes and the SPATEM movement that controls it. */
|
||||||
|
data class LaneExit(
|
||||||
|
val connection: LaneConnection,
|
||||||
|
val turn: Turn,
|
||||||
|
/** The movement for [LaneConnection.signalGroup] in the latest SPATEM, if it has one. */
|
||||||
|
val movement: SignalMovement?,
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class Turn { STRAIGHT, LEFT, RIGHT, U_TURN, UNKNOWN }
|
||||||
|
|
||||||
|
data class OwnApproach(
|
||||||
|
val approach: ApproachSignals,
|
||||||
|
/** Along the lane from the rider to the stop line. */
|
||||||
|
val distanceToStopLineM: Double,
|
||||||
|
)
|
||||||
|
|
||||||
|
object TrafficLights {
|
||||||
|
|
||||||
|
/** Farther than this from the reference point, no lane is matched to the rider. */
|
||||||
|
const val MATCH_RADIUS_M = 200.0
|
||||||
|
/** A lane matches only if the rider is within this of its centre line. */
|
||||||
|
private const val MATCH_LATERAL_M = 6.0
|
||||||
|
/** ...and travelling within this of its direction, when moving fast enough for a heading. */
|
||||||
|
private const val MATCH_HEADING_DEG = 50.0
|
||||||
|
private const val MIN_SPEED_FOR_HEADING_MPS = 1.0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Joins [signal] and [geometry] (either may be null, not both) for a rider at [own], if known.
|
||||||
|
* [ownSpeedMps] below [MIN_SPEED_FOR_HEADING_MPS] means the heading is not trusted and the
|
||||||
|
* nearest lane wins on distance alone.
|
||||||
|
*/
|
||||||
|
fun join(
|
||||||
|
signal: SpatIntersection?,
|
||||||
|
geometry: IntersectionGeometry?,
|
||||||
|
own: MapPoint? = null,
|
||||||
|
ownHeadingDeg: Double? = null,
|
||||||
|
ownSpeedMps: Double? = null,
|
||||||
|
): TrafficLight {
|
||||||
|
val key = signal?.key ?: geometry?.key ?: error("join needs a SPATEM or a MAPEM")
|
||||||
|
if (geometry == null) return TrafficLight(key, signal, null, emptyList(), null)
|
||||||
|
val movements = signal?.state?.movements?.associateBy { it.signalGroup } ?: emptyMap()
|
||||||
|
val approaches = geometry.lanes
|
||||||
|
.filter { it.isIngress && it.connections.any { c -> c.signalGroup != null } }
|
||||||
|
.mapNotNull { lane ->
|
||||||
|
val points = geometry.lanePoints(lane)
|
||||||
|
if (points.size < 2) return@mapNotNull null
|
||||||
|
val bearing = bearing(geometry, points[1], points[0])
|
||||||
|
ApproachSignals(
|
||||||
|
lane = lane,
|
||||||
|
stopLine = points[0],
|
||||||
|
bearingDeg = bearing,
|
||||||
|
exits = lane.connections.filter { it.signalGroup != null }.map { c ->
|
||||||
|
LaneExit(c, turnOf(geometry, lane, c, bearing), movements[c.signalGroup])
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val ownApproach = own?.let { match(geometry, approaches, it, ownHeadingDeg, ownSpeedMps) }
|
||||||
|
return TrafficLight(key, signal, geometry, approaches, ownApproach)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The turn a connection makes: its own `maneuver` when it names exactly one turn, else the
|
||||||
|
* lane's, else the angle between the ingress lane and the lane it leads to. Only about half the
|
||||||
|
* recorded connections carry a maneuver.
|
||||||
|
*/
|
||||||
|
internal fun turnOf(geometry: IntersectionGeometry, lane: MapLane, c: LaneConnection, inBearing: Double): Turn {
|
||||||
|
c.maneuver?.single()?.let { return it }
|
||||||
|
lane.maneuvers?.single()?.let { return it }
|
||||||
|
return geometricTurn(geometry, c, inBearing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The turn from the angle between the ingress lane ([inBearing]) and where [c] leads. */
|
||||||
|
internal fun geometricTurn(geometry: IntersectionGeometry, c: LaneConnection, inBearing: Double): Turn {
|
||||||
|
if (c.remoteIntersection != null) return Turn.UNKNOWN
|
||||||
|
val target = geometry.lane(c.toLane) ?: return Turn.UNKNOWN
|
||||||
|
val points = geometry.lanePoints(target)
|
||||||
|
if (points.size < 2) return Turn.UNKNOWN
|
||||||
|
val delta = normalise(bearing(geometry, points[0], points[1]) - inBearing)
|
||||||
|
return when {
|
||||||
|
abs(delta) <= 35.0 -> Turn.STRAIGHT
|
||||||
|
delta in 35.0..150.0 -> Turn.RIGHT
|
||||||
|
delta in -150.0..-35.0 -> Turn.LEFT
|
||||||
|
else -> Turn.U_TURN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which of the MAPEMs heard for one intersection a SPATEM refers to: the one with its revision,
|
||||||
|
* else the newest. Two revisions of one intersection can be on air at once (the 2026-03-18 drive
|
||||||
|
* heard 1/1 at revisions 2 and 3, with SPATEMs for both), and their signal groups differ.
|
||||||
|
*/
|
||||||
|
fun pickGeometry(candidates: List<IntersectionGeometry>, spatRevision: Int?): IntersectionGeometry? =
|
||||||
|
candidates.lastOrNull { it.revision == spatRevision } ?: candidates.lastOrNull()
|
||||||
|
|
||||||
|
internal fun Maneuvers.single(): Turn? {
|
||||||
|
val turns = listOfNotNull(
|
||||||
|
Turn.STRAIGHT.takeIf { straight }, Turn.LEFT.takeIf { left },
|
||||||
|
Turn.RIGHT.takeIf { right }, Turn.U_TURN.takeIf { uTurn },
|
||||||
|
)
|
||||||
|
return turns.singleOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun match(
|
||||||
|
geometry: IntersectionGeometry,
|
||||||
|
approaches: List<ApproachSignals>,
|
||||||
|
own: MapPoint,
|
||||||
|
headingDeg: Double?,
|
||||||
|
speedMps: Double?,
|
||||||
|
): OwnApproach? {
|
||||||
|
val p = geometry.toLocal(own)
|
||||||
|
if (hypot(p.first, p.second) > MATCH_RADIUS_M) return null
|
||||||
|
val useHeading = headingDeg != null && (speedMps ?: 0.0) >= MIN_SPEED_FOR_HEADING_MPS
|
||||||
|
var best: Pair<OwnApproach, Double>? = null
|
||||||
|
for (approach in approaches) {
|
||||||
|
// A rider can only be on a lane they may use: crosswalks and sidewalks are not theirs.
|
||||||
|
if (approach.lane.type != LaneType.VEHICLE && approach.lane.type != LaneType.BIKE_LANE) continue
|
||||||
|
val points = geometry.lanePoints(approach.lane).map { geometry.toLocal(it) }
|
||||||
|
var along = 0.0
|
||||||
|
for (s in 0 until points.size - 1) {
|
||||||
|
val (ax, ay) = points[s]
|
||||||
|
val (bx, by) = points[s + 1]
|
||||||
|
val dx = bx - ax
|
||||||
|
val dy = by - ay
|
||||||
|
val length = hypot(dx, dy)
|
||||||
|
if (length < 0.01) continue
|
||||||
|
// Projection onto segment a->b (outward from the stop line)
|
||||||
|
val t = (((p.first - ax) * dx + (p.second - ay) * dy) / (length * length)).coerceIn(0.0, 1.0)
|
||||||
|
val lateral = hypot(p.first - (ax + t * dx), p.second - (ay + t * dy))
|
||||||
|
val beyondStopLine = s == 0 && t == 0.0 && ((p.first - ax) * dx + (p.second - ay) * dy) < 0
|
||||||
|
if (lateral <= MATCH_LATERAL_M && !beyondStopLine) {
|
||||||
|
// Travel on an ingress lane runs b->a, toward the stop line.
|
||||||
|
val travel = compassBearing(-dx, -dy)
|
||||||
|
val headingOk = !useHeading || abs(normalise(headingDeg!! - travel)) <= MATCH_HEADING_DEG
|
||||||
|
if (headingOk && (best == null || lateral < best.second)) {
|
||||||
|
best = OwnApproach(approach, along + t * length) to lateral
|
||||||
|
}
|
||||||
|
}
|
||||||
|
along += length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best?.first
|
||||||
|
}
|
||||||
|
|
||||||
|
/** East/north metres from the reference point, on the same tangent plane as the XY offsets. */
|
||||||
|
private fun IntersectionGeometry.toLocal(p: MapPoint): Pair<Double, Double> =
|
||||||
|
Pair(
|
||||||
|
(p.longitude - refLongitude) * METRES_PER_DEGREE * cos(refLatitude * PI / 180.0),
|
||||||
|
(p.latitude - refLatitude) * METRES_PER_DEGREE,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun bearing(geometry: IntersectionGeometry, from: MapPoint, to: MapPoint): Double {
|
||||||
|
val a = geometry.toLocal(from)
|
||||||
|
val b = geometry.toLocal(to)
|
||||||
|
return compassBearing(b.first - a.first, b.second - a.second)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Degrees clockwise from north of the vector (east, north), in [0, 360). */
|
||||||
|
private fun compassBearing(east: Double, north: Double): Double =
|
||||||
|
(atan2(east, north) * 180.0 / PI + 360.0) % 360.0
|
||||||
|
|
||||||
|
/** Into (-180, 180]. */
|
||||||
|
private fun normalise(deg: Double): Double {
|
||||||
|
var d = deg % 360.0
|
||||||
|
if (d > 180.0) d -= 360.0
|
||||||
|
if (d <= -180.0) d += 360.0
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val METRES_PER_DEGREE = 6_378_137.0 * PI / 180.0
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.size
|
|||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material.icons.Icons
|
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.GpsFixed
|
||||||
import androidx.compose.material.icons.filled.GpsOff
|
import androidx.compose.material.icons.filled.GpsOff
|
||||||
import androidx.compose.material.icons.filled.Sensors
|
import androidx.compose.material.icons.filled.Sensors
|
||||||
@@ -38,8 +39,10 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hawhamburg.micr0bu.R
|
||||||
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
|
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||||
@@ -58,6 +61,9 @@ fun StatusTopBar(
|
|||||||
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
|
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
|
||||||
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
|
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
|
||||||
esp32Bluetooth: Boolean = false,
|
esp32Bluetooth: Boolean = false,
|
||||||
|
/** The connected ESP32-C5 reports a low cell (amber) or a critical one (red). */
|
||||||
|
obuBatteryLow: Boolean = false,
|
||||||
|
obuBatteryCritical: Boolean = false,
|
||||||
) {
|
) {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = {
|
title = {
|
||||||
@@ -97,6 +103,17 @@ fun StatusTopBar(
|
|||||||
)
|
)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
|
|
||||||
|
if (isEsp32 && (obuBatteryLow || obuBatteryCritical)) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.BatteryAlert,
|
||||||
|
contentDescription = stringResource(
|
||||||
|
if (obuBatteryCritical) R.string.status_battery_critical else R.string.status_battery_low,
|
||||||
|
),
|
||||||
|
tint = if (obuBatteryCritical) ErrorRed else AmberAcquiring,
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
}
|
||||||
ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
|
ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
|||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.CheckCircle
|
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.Link
|
||||||
import androidx.compose.material.icons.filled.LinkOff
|
import androidx.compose.material.icons.filled.LinkOff
|
||||||
import androidx.compose.material.icons.filled.Usb
|
import androidx.compose.material.icons.filled.Usb
|
||||||
@@ -313,6 +315,39 @@ fun ConnectionSetupScreen(
|
|||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
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,7 +65,10 @@ import com.hawhamburg.micr0bu.domain.cam.Cam
|
|||||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||||
import com.hawhamburg.micr0bu.domain.denm.DenmParser
|
import com.hawhamburg.micr0bu.domain.denm.DenmParser
|
||||||
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
|
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.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.domain.usecase.GeoMath
|
||||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
@@ -85,7 +88,7 @@ fun DashboardScreen(
|
|||||||
obuStationTypeWarning: Boolean = false,
|
obuStationTypeWarning: Boolean = false,
|
||||||
obuStationType: Int? = null,
|
obuStationType: Int? = null,
|
||||||
hazards: List<DenmEvent> = emptyList(),
|
hazards: List<DenmEvent> = emptyList(),
|
||||||
signals: List<SpatIntersection> = emptyList(),
|
signals: List<TrafficLight> = emptyList(),
|
||||||
ownPosition: Cam? = null,
|
ownPosition: Cam? = null,
|
||||||
onNavigateToConnection: () -> Unit,
|
onNavigateToConnection: () -> Unit,
|
||||||
onNavigateToSensors: () -> Unit,
|
onNavigateToSensors: () -> Unit,
|
||||||
@@ -409,17 +412,18 @@ fun DashboardScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Signals cannot be ranked by distance: SPATEM carries no position at all. The geometry
|
// The intersection whose ingress lane the rider is on (MAPEM geometry plus position and
|
||||||
// that would place an intersection lives in MAPEM, which nothing on the air is currently
|
// heading) comes first, nearest stop line first. Otherwise - no MAPEM heard, or not on one
|
||||||
// sending. So the one shown is the one changing soonest, which is in any case the one a
|
// of its lanes - the one changing soonest, which is the one a rider approaching a junction
|
||||||
// rider approaching a junction needs to see.
|
// most likely needs.
|
||||||
val nextSignal = remember(signals) {
|
val nextSignal = remember(signals) {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
signals.minByOrNull { it.secondsToNextChange(now) ?: Double.MAX_VALUE }
|
signals.filter { it.ownApproach != null }.minByOrNull { it.ownApproach!!.distanceToStopLineM }
|
||||||
|
?: signals.minByOrNull { it.signal?.secondsToNextChange(now) ?: Double.MAX_VALUE }
|
||||||
}
|
}
|
||||||
nextSignal?.let { signal ->
|
nextSignal?.let { light ->
|
||||||
SignalCard(
|
SignalCard(
|
||||||
signal = signal,
|
light = light,
|
||||||
additionalCount = signals.size - 1,
|
additionalCount = signals.size - 1,
|
||||||
onClick = onNavigateToV2x,
|
onClick = onNavigateToV2x,
|
||||||
)
|
)
|
||||||
@@ -638,16 +642,16 @@ private fun HazardCard(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The signalised intersection changing soonest: its leading phase with a countdown, then every
|
* The intersection that matters most: the one whose lane the rider is on, else the one changing
|
||||||
* signal group as a coloured chip.
|
* 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
|
||||||
* Signal groups are bare numbers because that is all the app knows. Calling one "your lane" needs
|
* controls - and the distance to the stop line. Without it, signal groups are bare numbers,
|
||||||
* MAPEM geometry, and a friendlier label would claim knowledge that is not there.
|
* since anything friendlier would claim knowledge that is not there.
|
||||||
*/
|
*/
|
||||||
@OptIn(ExperimentalLayoutApi::class)
|
@OptIn(ExperimentalLayoutApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
private fun SignalCard(
|
private fun SignalCard(
|
||||||
signal: SpatIntersection,
|
light: TrafficLight,
|
||||||
additionalCount: Int,
|
additionalCount: Int,
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
@@ -662,16 +666,28 @@ private fun SignalCard(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
val now = nowMs.longValue
|
val now = nowMs.longValue
|
||||||
|
val signal = light.signal ?: return
|
||||||
|
val own = light.ownApproach
|
||||||
|
|
||||||
val leading = signal.state.movements.minByOrNull { movement ->
|
// 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 ->
|
||||||
movement.current?.secondsUntil(now)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
movement.current?.secondsUntil(now)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
||||||
}
|
}
|
||||||
val phase = leading?.current?.phase
|
val phase = leading?.current?.phase
|
||||||
val tint = phaseTint(phase)
|
val tint = phaseTint(phase)
|
||||||
val countdown = leading?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
|
val countdown = leading?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
|
||||||
|
|
||||||
val hiddenGroups = signal.state.movements.size - DASH_MAX_SIGNAL_GROUPS
|
// 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 footer = listOfNotNull(
|
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 (hiddenGroups > 0) stringResource(R.string.dash_more_count, hiddenGroups) else null,
|
||||||
if (additionalCount > 0) stringResource(R.string.dash_signal_more, additionalCount) else null,
|
if (additionalCount > 0) stringResource(R.string.dash_signal_more, additionalCount) else null,
|
||||||
).joinToString(" · ")
|
).joinToString(" · ")
|
||||||
@@ -690,11 +706,23 @@ private fun SignalCard(
|
|||||||
Icon(Icons.Default.Traffic, null, tint = tint, modifier = Modifier.size(28.dp))
|
Icon(Icons.Default.Traffic, null, tint = tint, modifier = Modifier.size(28.dp))
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.dash_signal_title, signal.state.key),
|
light.name ?: stringResource(R.string.dash_signal_title, light.key),
|
||||||
style = MaterialTheme.typography.labelLarge,
|
style = MaterialTheme.typography.labelLarge,
|
||||||
color = tint,
|
color = tint,
|
||||||
fontWeight = FontWeight.SemiBold,
|
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(
|
||||||
text = countdown
|
text = countdown
|
||||||
?.let { stringResource(R.string.dash_signal_countdown, phaseLabel(phase), it) }
|
?.let { stringResource(R.string.dash_signal_countdown, phaseLabel(phase), it) }
|
||||||
@@ -707,12 +735,12 @@ private fun SignalCard(
|
|||||||
// Wraps rather than scrolls: a horizontal scroller inside a scrolling dashboard
|
// 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.
|
// is awkward to drive one-handed, and the chip row is short by construction.
|
||||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
signal.state.movements.take(DASH_MAX_SIGNAL_GROUPS).forEach { movement ->
|
chips.take(DASH_MAX_SIGNAL_GROUPS).forEach { (label, movement) ->
|
||||||
val groupTint = phaseTint(movement.current?.phase)
|
val groupTint = phaseTint(movement?.current?.phase)
|
||||||
val groupCountdown =
|
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(
|
||||||
text = stringResource(R.string.v2x_spat_group, movement.signalGroup) +
|
text = label +
|
||||||
(groupCountdown?.let { " " + stringResource(R.string.v2x_spat_countdown, it) } ?: ""),
|
(groupCountdown?.let { " " + stringResource(R.string.v2x_spat_countdown, it) } ?: ""),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
fontFamily = FontFamily.Monospace,
|
fontFamily = FontFamily.Monospace,
|
||||||
@@ -739,6 +767,15 @@ 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. */
|
/** Traffic-light colour for a phase: go is green, stop is red, anything in between is amber. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun phaseTint(phase: SignalPhase?): Color = when {
|
private fun phaseTint(phase: SignalPhase?): Color = when {
|
||||||
|
|||||||
@@ -31,7 +31,11 @@ import androidx.lifecycle.compose.LocalLifecycleOwner
|
|||||||
import com.hawhamburg.micr0bu.R
|
import com.hawhamburg.micr0bu.R
|
||||||
import com.hawhamburg.micr0bu.domain.cam.Cam
|
import com.hawhamburg.micr0bu.domain.cam.Cam
|
||||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
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.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.AlertLevel
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||||
import org.osmdroid.config.Configuration
|
import org.osmdroid.config.Configuration
|
||||||
@@ -40,6 +44,7 @@ import org.osmdroid.util.GeoPoint
|
|||||||
import org.osmdroid.views.CustomZoomButtonsController
|
import org.osmdroid.views.CustomZoomButtonsController
|
||||||
import org.osmdroid.views.MapView
|
import org.osmdroid.views.MapView
|
||||||
import org.osmdroid.views.overlay.Marker
|
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
|
* V2X Monitor live map (Phase 03, Section 13) — the map body behind [V2xMapScreen], plotting the
|
||||||
@@ -49,7 +54,9 @@ import org.osmdroid.views.overlay.Marker
|
|||||||
* Marker vocabulary, one shape per message type so the map reads without a legend:
|
* 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
|
* - CAM — teardrop pin, tinted by that station's most severe active alert level
|
||||||
* - DENM — hazard warning triangle
|
* - DENM — hazard warning triangle
|
||||||
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit
|
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit. With the
|
||||||
|
* intersection's MAPEM it stands on the MAPEM's reference point and its lanes are drawn: each
|
||||||
|
* ingress lane in the colour of its straight-ahead light (else its first), egress lanes grey
|
||||||
*
|
*
|
||||||
* Unlike [MapScreen] this has no phone-GNSS-only fallback: [own] always reflects whichever ego
|
* 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 /
|
* source [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository] currently trusts (obu_gnss /
|
||||||
@@ -69,7 +76,7 @@ fun V2xLiveMapView(
|
|||||||
remotes: Map<Long, Cam>,
|
remotes: Map<Long, Cam>,
|
||||||
alerts: List<UseCaseAlert>,
|
alerts: List<UseCaseAlert>,
|
||||||
denms: List<DenmEvent> = emptyList(),
|
denms: List<DenmEvent> = emptyList(),
|
||||||
spats: List<SpatIntersection> = emptyList(),
|
lights: List<TrafficLight> = emptyList(),
|
||||||
followOwn: Boolean = true,
|
followOwn: Boolean = true,
|
||||||
onUserPanned: () -> Unit = {},
|
onUserPanned: () -> Unit = {},
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
@@ -92,6 +99,7 @@ fun V2xLiveMapView(
|
|||||||
// tint applied would recolour every pin on the map.
|
// tint applied would recolour every pin on the map.
|
||||||
val icons = remember(context) { MapIcons(context) }
|
val icons = remember(context) { MapIcons(context) }
|
||||||
val markers = remember { mutableMapOf<String, Marker>() }
|
val markers = remember { mutableMapOf<String, Marker>() }
|
||||||
|
val lanes = remember { mutableMapOf<String, Polyline>() }
|
||||||
|
|
||||||
val mapViewRef = remember { mutableStateOf<MapView?>(null) }
|
val mapViewRef = remember { mutableStateOf<MapView?>(null) }
|
||||||
val lifecycleOwner = LocalLifecycleOwner.current
|
val lifecycleOwner = LocalLifecycleOwner.current
|
||||||
@@ -143,14 +151,17 @@ fun V2xLiveMapView(
|
|||||||
update = { mv ->
|
update = { mv ->
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
|
|
||||||
// Intersections we can actually place: SPATEM carries signal state but no geometry
|
// Intersections we can actually place: at the MAPEM's reference point when its MAPEM
|
||||||
// (that is MAPEM's job), so the only position available is the sending RSU's own CAM.
|
// has been heard, else at the sending RSU's own CAM position (SPATEM has no geometry).
|
||||||
val locatedSpats = spats.mapNotNull { spat ->
|
val locatedSpats = lights.mapNotNull { light ->
|
||||||
remotes[spat.stationId]?.let { rsu -> spat to rsu }
|
val spat = light.signal ?: return@mapNotNull null
|
||||||
|
val at = light.geometry?.let { GeoPoint(it.refLatitude, it.refLongitude) }
|
||||||
|
?: remotes[spat.stationId]?.let { rsu -> GeoPoint(rsu.latitude, rsu.longitude) }
|
||||||
|
at?.let { Triple(light, spat, it) }
|
||||||
}
|
}
|
||||||
// An RSU drawn as a traffic light must not also be drawn as a CAM pin underneath it:
|
// 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.
|
// 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>()
|
val live = mutableSetOf<String>()
|
||||||
|
|
||||||
@@ -201,13 +212,38 @@ fun V2xLiveMapView(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
locatedSpats.forEach { (spat, rsu) ->
|
val liveLanes = mutableSetOf<String>()
|
||||||
val phase = spat.leadingPhase(now)
|
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)
|
||||||
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
|
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
|
||||||
position = GeoPoint(rsu.latitude, rsu.longitude)
|
position = at
|
||||||
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
|
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
|
||||||
icon = icons.signal(phase)
|
icon = icons.signal(phase)
|
||||||
title = context.getString(
|
title = light.name ?: context.getString(
|
||||||
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
|
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
|
||||||
)
|
)
|
||||||
snippet = spat.state.movements.joinToString(" · ") { movement ->
|
snippet = spat.state.movements.joinToString(" · ") { movement ->
|
||||||
@@ -225,6 +261,8 @@ fun V2xLiveMapView(
|
|||||||
(key in live).also { kept -> if (!kept) markers[key]?.closeInfoWindow() }
|
(key in live).also { kept -> if (!kept) markers[key]?.closeInfoWindow() }
|
||||||
}
|
}
|
||||||
mv.overlays.clear()
|
mv.overlays.clear()
|
||||||
|
// Lanes first, so every marker draws over them.
|
||||||
|
lanes.values.forEach { mv.overlays.add(it) }
|
||||||
markers.entries
|
markers.entries
|
||||||
.sortedBy { (key, _) -> key.drawOrder() }
|
.sortedBy { (key, _) -> key.drawOrder() }
|
||||||
.forEach { (_, marker) -> mv.overlays.add(marker) }
|
.forEach { (_, marker) -> mv.overlays.add(marker) }
|
||||||
@@ -255,6 +293,7 @@ fun V2xLiveMapView(
|
|||||||
// guarantees no further update after it.
|
// guarantees no further update after it.
|
||||||
onRelease = {
|
onRelease = {
|
||||||
markers.clear()
|
markers.clear()
|
||||||
|
lanes.clear()
|
||||||
it.onDetach()
|
it.onDetach()
|
||||||
},
|
},
|
||||||
modifier = modifier.fillMaxSize(),
|
modifier = modifier.fillMaxSize(),
|
||||||
@@ -328,25 +367,35 @@ private enum class SignalLamp(val drawableRes: Int) {
|
|||||||
/**
|
/**
|
||||||
* The lamp to light for this intersection.
|
* The lamp to light for this intersection.
|
||||||
*
|
*
|
||||||
* Without MAPEM there is no lane geometry, so there is no way to know which of an intersection's
|
* Used when the rider is not on one of the intersection's ingress lanes (or no MAPEM is known):
|
||||||
* signal groups applies to the rider's own approach. This follows the rule the Dashboard's
|
* then no signal group is theirs, and this follows the rule the Dashboard's SignalCard uses — the
|
||||||
* SignalCard already uses — the group changing soonest speaks for the intersection — so the same
|
* group changing soonest speaks for the intersection — so it reads the same in both places.
|
||||||
* intersection reads the same way in both places rather than inventing a second convention.
|
|
||||||
*/
|
*/
|
||||||
private fun SpatIntersection.leadingPhase(nowMs: Long): SignalLamp {
|
private fun SpatIntersection.leadingPhase(nowMs: Long): SignalLamp {
|
||||||
val leading = state.movements.minByOrNull { movement ->
|
val leading = state.movements.minByOrNull { movement ->
|
||||||
movement.current?.secondsUntil(nowMs)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
movement.current?.secondsUntil(nowMs)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
|
||||||
}
|
}
|
||||||
val phase = leading?.current?.phase
|
return leading?.current?.phase.toLamp()
|
||||||
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
|
* 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:
|
* same way in both places. Stations with no active alert stay neutral grey-blue rather than green:
|
||||||
|
|||||||
@@ -61,17 +61,17 @@ fun V2xMapScreen(
|
|||||||
val stations by viewModel.stationsInRange.collectAsState()
|
val stations by viewModel.stationsInRange.collectAsState()
|
||||||
val alerts by viewModel.useCaseAlerts.collectAsState()
|
val alerts by viewModel.useCaseAlerts.collectAsState()
|
||||||
val denms by viewModel.denmEvents.collectAsState()
|
val denms by viewModel.denmEvents.collectAsState()
|
||||||
val spats by viewModel.spatIntersections.collectAsState()
|
val lights by viewModel.trafficLights.collectAsState()
|
||||||
|
|
||||||
// Follow is on until the rider touches the map, and comes back when they ask for it. Without
|
// 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
|
// 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.
|
// map could not be panned at all while traffic is flowing.
|
||||||
var followOwn by remember { mutableStateOf(true) }
|
var followOwn by remember { mutableStateOf(true) }
|
||||||
|
|
||||||
// SPATEM carries no geometry of its own, so an intersection can only be placed if its RSU has
|
// SPATEM carries no geometry of its own, so an intersection can only be placed if its MAPEM or
|
||||||
// also been heard over CAM. Saying so is better than silently dropping it: "the map shows two
|
// its RSU's CAM has been heard too. Saying so is better than silently dropping it: "the map shows two
|
||||||
// of the three lights I can see in the list" is otherwise an unexplained discrepancy.
|
// of the three lights I can see in the list" is otherwise an unexplained discrepancy.
|
||||||
val unlocatedSpats = spats.count { it.stationId !in stations.keys }
|
val unlocatedSpats = lights.count { it.geometry == null && it.signal?.stationId !in stations.keys }
|
||||||
|
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
V2xLiveMapView(
|
V2xLiveMapView(
|
||||||
@@ -79,7 +79,7 @@ fun V2xMapScreen(
|
|||||||
remotes = stations,
|
remotes = stations,
|
||||||
alerts = alerts,
|
alerts = alerts,
|
||||||
denms = denms,
|
denms = denms,
|
||||||
spats = spats,
|
lights = lights,
|
||||||
followOwn = followOwn,
|
followOwn = followOwn,
|
||||||
onUserPanned = { followOwn = false },
|
onUserPanned = { followOwn = false },
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
@@ -125,7 +125,7 @@ fun V2xMapScreen(
|
|||||||
MapCount(
|
MapCount(
|
||||||
icon = Icons.Default.Traffic,
|
icon = Icons.Default.Traffic,
|
||||||
tint = SignalGreenDot,
|
tint = SignalGreenDot,
|
||||||
count = spats.size,
|
count = lights.size,
|
||||||
label = stringResource(R.string.v2x_map_legend_spat),
|
label = stringResource(R.string.v2x_map_legend_spat),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
|||||||
import com.hawhamburg.micr0bu.data.transport.StationStatus
|
import com.hawhamburg.micr0bu.data.transport.StationStatus
|
||||||
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
|
||||||
import com.hawhamburg.micr0bu.domain.denm.DenmParser
|
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.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.denm.DenmUseCase
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
|
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
|
||||||
@@ -269,6 +273,47 @@ class MqttViewModel @Inject constructor(
|
|||||||
.sortedByDescending { it.timestamp }
|
.sortedByDescending { it.timestamp }
|
||||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intersection geometry heard over MAPEM, oldest first. Kept per intersection AND revision:
|
||||||
|
* two revisions of one intersection can be on air at once, and a SPATEM's signal groups mean
|
||||||
|
* whatever its own revision's MAPEM says ([TrafficLights.pickGeometry]).
|
||||||
|
*/
|
||||||
|
private val mapGeometries: StateFlow<List<IntersectionGeometry>> = combine(
|
||||||
|
camUseCaseRepository.decodedMap
|
||||||
|
.runningFold(emptyMap<String, Pair<IntersectionGeometry, Long>>()) { acc, map ->
|
||||||
|
acc + map.intersections.associate { "${it.key}#${it.revision}" to (it to map.timestamp) }
|
||||||
|
},
|
||||||
|
tickerFlow(MAP_EXPIRY_TICK_MS),
|
||||||
|
) { byKey, _ ->
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
byKey.values
|
||||||
|
.filter { (_, heardAt) -> now - heardAt <= MAP_TTL_MS }
|
||||||
|
.sortedBy { (_, heardAt) -> heardAt }
|
||||||
|
.map { (geometry, _) -> geometry }
|
||||||
|
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [spatIntersections] with each SPATEM's signal groups placed on its MAPEM's lanes, and the
|
||||||
|
* rider's own approach picked from their position and heading. An intersection whose MAPEM has
|
||||||
|
* not been heard (yet) is still listed, with no lanes: its signal groups stay bare numbers.
|
||||||
|
*/
|
||||||
|
val trafficLights: StateFlow<List<TrafficLight>> = combine(
|
||||||
|
spatIntersections,
|
||||||
|
mapGeometries,
|
||||||
|
camUseCaseRepository.ownPosition,
|
||||||
|
) { spats, geometries, own ->
|
||||||
|
val byKey = geometries.groupBy { it.key }
|
||||||
|
spats.map { spat ->
|
||||||
|
TrafficLights.join(
|
||||||
|
signal = spat,
|
||||||
|
geometry = TrafficLights.pickGeometry(byKey[spat.key].orEmpty(), spat.state.revision),
|
||||||
|
own = own?.let { MapPoint(it.latitude, it.longitude) },
|
||||||
|
ownHeadingDeg = own?.headingDeg,
|
||||||
|
ownSpeedMps = own?.speedMps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||||
|
|
||||||
/** Emits immediately, then every [periodMs], purely to re-trigger a time-dependent combine. */
|
/** Emits immediately, then every [periodMs], purely to re-trigger a time-dependent combine. */
|
||||||
private fun tickerFlow(periodMs: Long): Flow<Long> = flow {
|
private fun tickerFlow(periodMs: Long): Flow<Long> = flow {
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -299,6 +344,13 @@ class MqttViewModel @Inject constructor(
|
|||||||
const val SPAT_TTL_MS = 15_000L
|
const val SPAT_TTL_MS = 15_000L
|
||||||
const val SPAT_EXPIRY_TICK_MS = 2_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. */
|
/** 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_TTL_MS = 15_000L
|
||||||
const val RSU_EXPIRY_TICK_MS = 2_000L
|
const val RSU_EXPIRY_TICK_MS = 2_000L
|
||||||
|
|||||||
@@ -44,6 +44,9 @@
|
|||||||
<string name="dash_signal_phase_dark">Dunkel</string>
|
<string name="dash_signal_phase_dark">Dunkel</string>
|
||||||
<string name="dash_signal_phase_unknown">Unbekannt</string>
|
<string name="dash_signal_phase_unknown">Unbekannt</string>
|
||||||
<string name="dash_signal_countdown">%1$s · %2$.0f s</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_pressure">Luftdruck</string>
|
||||||
<string name="stat_altitude">Höhe</string>
|
<string name="stat_altitude">Höhe</string>
|
||||||
<string name="stat_heading">Richtung</string>
|
<string name="stat_heading">Richtung</string>
|
||||||
@@ -330,6 +333,11 @@
|
|||||||
<string name="conn_esp32_via_ble">über Bluetooth (Passkey 123456 beim ersten Koppeln)</string>
|
<string name="conn_esp32_via_ble">über Bluetooth (Passkey 123456 beim ersten Koppeln)</string>
|
||||||
<string name="conn_esp32_cancel">Abbrechen</string>
|
<string name="conn_esp32_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_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_on">an</string>
|
||||||
<string name="conn_esp32_signing_off">aus</string>
|
<string name="conn_esp32_signing_off">aus</string>
|
||||||
<string name="v2xlog_title">V2X-Datenlogger</string>
|
<string name="v2xlog_title">V2X-Datenlogger</string>
|
||||||
|
|||||||
@@ -45,6 +45,9 @@
|
|||||||
<string name="dash_signal_phase_dark">Dark</string>
|
<string name="dash_signal_phase_dark">Dark</string>
|
||||||
<string name="dash_signal_phase_unknown">Unknown</string>
|
<string name="dash_signal_phase_unknown">Unknown</string>
|
||||||
<string name="dash_signal_countdown">%1$s · %2$.0f s</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_pressure">Pressure</string>
|
||||||
<string name="stat_altitude">Altitude</string>
|
<string name="stat_altitude">Altitude</string>
|
||||||
<string name="stat_heading">Heading</string>
|
<string name="stat_heading">Heading</string>
|
||||||
@@ -337,6 +340,11 @@
|
|||||||
<string name="conn_esp32_via_ble">via Bluetooth (passkey 123456 on first pairing)</string>
|
<string name="conn_esp32_via_ble">via Bluetooth (passkey 123456 on first pairing)</string>
|
||||||
<string name="conn_esp32_cancel">Cancel</string>
|
<string name="conn_esp32_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_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_on">on</string>
|
||||||
<string name="conn_esp32_signing_off">off</string>
|
<string name="conn_esp32_signing_off">off</string>
|
||||||
<string name="v2xlog_title">V2X data logger</string>
|
<string name="v2xlog_title">V2X data logger</string>
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import com.hawhamburg.micr0bu.data.transport.StationStatus
|
|||||||
import com.hawhamburg.micr0bu.data.transport.credentialsSegment
|
import com.hawhamburg.micr0bu.data.transport.credentialsSegment
|
||||||
import org.junit.Assert.assertArrayEquals
|
import org.junit.Assert.assertArrayEquals
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
import org.junit.Assert.assertNotNull
|
import org.junit.Assert.assertNotNull
|
||||||
import org.junit.Assert.assertNull
|
import org.junit.Assert.assertNull
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
@@ -107,6 +108,83 @@ class StationLinkTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `a STATUS of the wrong length is refused, as the Python decoder does`() {
|
fun `a STATUS of the wrong length is refused, as the Python decoder does`() {
|
||||||
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1)))
|
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1)))
|
||||||
|
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 2)))
|
||||||
|
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE - 1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The STATUS body of the Python-encoder test above, without its 4-octet message header. */
|
||||||
|
private val legacyStatusBody = (
|
||||||
|
"40e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
|
||||||
|
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
|
||||||
|
"190000001a0000001b0000001c000000fbb2b7ffa6000000"
|
||||||
|
).hexToBytes()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a 103 octet STATUS from an older board has no battery`() {
|
||||||
|
val legacy = legacyStatusBody
|
||||||
|
assertEquals(StationStatus.SIZE, legacy.size)
|
||||||
|
val status = StationStatus.decode(legacy)!!
|
||||||
|
assertEquals(0, status.batteryMv)
|
||||||
|
assertNull(status.batteryPercent)
|
||||||
|
assertFalse(status.batteryLow)
|
||||||
|
assertFalse(status.batteryCritical)
|
||||||
|
assertEquals(28L, status.potiUpdates)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `the battery fields after the 103 octets are decoded`() {
|
||||||
|
// 3871 mV = 0x0F1F, flags: low
|
||||||
|
val body = legacyStatusBody + "1f0f01".hexToBytes()
|
||||||
|
assertEquals(StationStatus.SIZE_WITH_BATTERY, body.size)
|
||||||
|
val status = StationStatus.decode(body)!!
|
||||||
|
assertEquals(3871, status.batteryMv)
|
||||||
|
assertEquals(StationStatus.BATTERY_FLAG_LOW, status.batteryFlags)
|
||||||
|
assertTrue(status.batteryLow)
|
||||||
|
assertFalse(status.batteryCritical)
|
||||||
|
assertEquals(60, status.batteryPercent)
|
||||||
|
assertEquals(28L, status.potiUpdates)
|
||||||
|
assertEquals(717_254_800_123L, status.itsTimeMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `critical flag, and octets of a later extension are tolerated`() {
|
||||||
|
// 3290 mV = 0x0CDA, flags: low + critical, then two octets of a later extension
|
||||||
|
val body = legacyStatusBody + "da0c03aabb".hexToBytes()
|
||||||
|
val status = StationStatus.decode(body)!!
|
||||||
|
assertEquals(3290, status.batteryMv)
|
||||||
|
assertTrue(status.batteryLow)
|
||||||
|
assertTrue(status.batteryCritical)
|
||||||
|
assertEquals(0, status.batteryPercent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `half a battery field is malformed`() {
|
||||||
|
assertNull(StationStatus.decode(legacyStatusBody + "1f".hexToBytes()))
|
||||||
|
assertNull(StationStatus.decode(legacyStatusBody + "1f0f".hexToBytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `battery flags are ignored while no voltage is reported`() {
|
||||||
|
val body = legacyStatusBody + "000003".hexToBytes()
|
||||||
|
val status = StationStatus.decode(body)!!
|
||||||
|
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
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
|||||||
|
-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
|
||||||
@@ -53,7 +53,13 @@ Main changes against the colleague's firmware:
|
|||||||
`V2X_RX` (0x85), whose body is the old `SERIAL_MSG_V2X_RX` payload.
|
`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
|
- **Unsigned sending kept.** The colleague's station refuses unsecured requests; here they go out
|
||||||
with the previous firmware's `geonet.c` header.
|
with the previous firmware's `geonet.c` header.
|
||||||
- **Console on UART0** (CH343, COM3 on the bench); the native USB port carries only link frames.
|
- **Console on UART0** (GPIO11/12; the earlier two-port bench board had a CH343 bridge there, COM3);
|
||||||
|
the native USB port carries only link frames. The production board is now a **Seeed XIAO ESP32-C5**
|
||||||
|
(8 MB flash, a single native USB-C port, COM10 on the bench) running from a LiPo on its BAT pads.
|
||||||
|
- **Battery:** the XIAO's own divider (GPIO6, enabled by GPIO26) is read every 5 s and sent in STATUS
|
||||||
|
(`battery_mv`, `battery_flags`, octets 103-105); the app shows the voltage, a rough percentage and a
|
||||||
|
low/critical 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`.
|
||||||
- **BLE pauses advertising while USB is in use** (BLE and ITS-G5 share one RF front end).
|
- **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
|
- **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.
|
phone had to pair on every connection.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# OBU transmit firmware - Phase 2 (in progress: HLN-SV DENM beacon)
|
# OBU transmit firmware
|
||||||
|
|
||||||
Build and flash steps are under "Build and flash" below. (`docs/04-transmit-setup.md`,
|
Build and flash steps are under "Build and flash" below. (`docs/04-transmit-setup.md`,
|
||||||
referenced here and in the sources, is not in the repo.)
|
referenced here and in the sources, is not in the repo.)
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
# obu-firmware — setup & flashing notes
|
# obu-firmware — setup & flashing notes
|
||||||
|
|
||||||
|
**Board (since 2026-10-05): Seeed XIAO ESP32-C5.** One USB-C port, which is the chip's native USB
|
||||||
|
Serial/JTAG (VID/PID 0x303A/0x1001); no UART bridge, no second port. 8 MB flash (`esptool flash-id`),
|
||||||
|
so `sdkconfig.defaults` sets `FLASHSIZE_8MB` (the earlier CH343 bench board had 16 MB). The same
|
||||||
|
port flashes the board *and* carries the phone's station link, so the PC and the phone take turns on
|
||||||
|
it. Pin map and what is wired: "Battery and pins" below. The sections that still say "UART-bridge
|
||||||
|
port" or "COM3" describe the earlier two-port bench board.
|
||||||
|
|
||||||
## Two toolchains - use a dedicated terminal for each
|
## Two toolchains - use a dedicated terminal for each
|
||||||
|
|
||||||
Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly
|
Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly
|
||||||
@@ -36,18 +43,25 @@ idf.py --version # v6.0.2
|
|||||||
|
|
||||||
## Build & flash
|
## Build & flash
|
||||||
|
|
||||||
Flash over the board's **UART-bridge port** (CH343; COM3 for the production OBU
|
The XIAO flashes over its one USB-C port (COM10 on the bench; Device Manager → Ports shows it as
|
||||||
on the bench), not the native port the phone uses.
|
"USB Serial Device"). esptool resets it into the bootloader by itself; no BOOT button is needed
|
||||||
|
unless the running firmware has crashed the USB peripheral, then hold BOOT while plugging in.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
|
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
|
||||||
idf.py set-target esp32c5 # only needed once per clean build folder
|
idf.py set-target esp32c5 # only needed once per clean build folder
|
||||||
idf.py build
|
idf.py build
|
||||||
idf.py -p COM3 -b 921600 flash monitor
|
idf.py -p COM10 -b 921600 flash
|
||||||
```
|
```
|
||||||
|
|
||||||
Swap `COM3` for whatever port the ESP32-C5's bridge enumerates as (Device Manager →
|
There is **no console on this port**: ESP_LOG stays on UART0 (GPIO11/GPIO12 = pads D6/D7), which a
|
||||||
Ports). `monitor` opens the serial console after flashing — `Ctrl+]` to exit.
|
bare XIAO does not route to USB, and `idf.py monitor` would only see the link frames. To read the
|
||||||
|
log, put a 3.3 V USB-UART adapter on D6 (TX) / D7 (RX), or set `CONFIG_MICROBU_LOG_OVER_LINK=y`
|
||||||
|
(LOG frames of type 0x7F on the link; the Android app has not been checked against them). To read
|
||||||
|
what the board says over the link, use `tools/station_status_watch.py COM10`.
|
||||||
|
|
||||||
|
The earlier two-port board flashed through its CH343 bridge port (COM3) with
|
||||||
|
`idf.py -p COM3 -b 921600 flash monitor`; its console was on that port.
|
||||||
Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the
|
Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the
|
||||||
partition table may differ from what the board has.
|
partition table may differ from what the board has.
|
||||||
|
|
||||||
@@ -58,8 +72,8 @@ The partition table changed with the port (NVS 24 KB → 80 KB, app 0x10000 →
|
|||||||
behind. Erase the whole new NVS range once, then do a full flash:
|
behind. Erase the whole new NVS range once, then do a full flash:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python -m esptool --chip esp32c5 -p COM3 -b 921600 erase-region 0x9000 0x15000
|
python -m esptool --chip esp32c5 -p COM10 -b 921600 erase-region 0x9000 0x15000
|
||||||
idf.py -p COM3 -b 921600 flash
|
idf.py -p COM10 -b 921600 flash
|
||||||
```
|
```
|
||||||
|
|
||||||
Without the erase, the board cannot store the BLE bond and the phone has to pair
|
Without the erase, the board cannot store the BLE bond and the phone has to pair
|
||||||
@@ -103,9 +117,14 @@ can come back two ways. The app detects it and falls back to its protocol.
|
|||||||
idf.py build
|
idf.py build
|
||||||
```
|
```
|
||||||
|
|
||||||
## Connecting the phone (ESP32-C5-WIFI6-KIT)
|
## Connecting the phone (XIAO ESP32-C5)
|
||||||
|
|
||||||
The board has two USB-C ports — use the right one:
|
The XIAO has a single USB-C port, the native USB Serial/JTAG one: the phone plugs into it via
|
||||||
|
USB-OTG, the station link runs over it (below), and unplugging the phone and plugging the PC in
|
||||||
|
is how it is flashed. Over BLE the phone does not need the cable at all (the board runs on its cell).
|
||||||
|
|
||||||
|
The rest of this section describes the earlier **ESP32-C5-WIFI6-KIT** bench board with two USB-C
|
||||||
|
ports — use the right one:
|
||||||
|
|
||||||
- **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this
|
- **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this
|
||||||
is where the phone plugs in via USB-OTG. The station link
|
is where the phone plugs in via USB-OTG. The station link
|
||||||
@@ -168,6 +187,54 @@ the first time: passkey **123456** (fixed in `simple_ble.cpp`). The bond is kept
|
|||||||
on both sides; the board keeps one bond, so pairing a second phone or a PC
|
on both sides; the board keeps one bond, so pairing a second phone or a PC
|
||||||
replaces the first. Log lines on the console start with `cits_ble:`.
|
replaces the first. Log lines on the console start with `cits_ble:`.
|
||||||
|
|
||||||
|
## Battery and pins (XIAO ESP32-C5)
|
||||||
|
|
||||||
|
The prototype runs on the 3.7 V LiPo of an Intenso XS5000 power bank (5000 mAh), on the XIAO's BAT
|
||||||
|
pads: cell `+` through a slide switch to **BAT+**, cell `−` to **BAT−**. The board's SGM40567 charger
|
||||||
|
charges it from USB (the phone, or the PC). Check the polarity with a multimeter before connecting:
|
||||||
|
reversed, the cell destroys the board. **The cell has no protection board** (the power bank's own
|
||||||
|
circuit board did that job), so nothing but the firmware stops an over-discharge, and nothing at all
|
||||||
|
stops a short.
|
||||||
|
|
||||||
|
| Pin | GPIO | Used for |
|
||||||
|
|---|---|---|
|
||||||
|
| (back pad) | GPIO6 | `BAT_VOLT_PIN`: the cell through two 100 kΩ resistors (ADC1) |
|
||||||
|
| (back pad) | GPIO26 | `BAT_VOLT_PIN_EN`: load switch that powers that divider, high only while measuring |
|
||||||
|
| D6 / D7 | GPIO11 / GPIO12 | UART0 (console) |
|
||||||
|
| native USB | GPIO13 / GPIO14 | USB D− / D+ (the phone link) |
|
||||||
|
| — | GPIO27 | the yellow user LED, active low; `CONFIG_MICROBU_TX_LED_GPIO=27` turns the activity LED on |
|
||||||
|
|
||||||
|
(Pin names from Seeed's XIAO ESP32-C5 wiki; GPIO13/14 and the LED are the chip's defaults, not
|
||||||
|
re-checked against the schematic.) The cell's two extra wires (temperature / ID) are not used.
|
||||||
|
|
||||||
|
What the firmware does with it (`battery.cpp`, `battery_monitor.hpp`):
|
||||||
|
|
||||||
|
- Every 5 s it enables the divider, takes the median of 16 samples, disables it, and smooths the
|
||||||
|
result. The cell voltage (twice the pin voltage) goes into the STATUS message the board sends
|
||||||
|
every second over USB and BLE: `battery_mv` u16 at octet 103 (0: no cell or no sensor) and
|
||||||
|
`battery_flags` u8 at 105 (bit 0 low, bit 1 critical). STATUS grew from 103 to 106 octets; the
|
||||||
|
app and the firmware both accept 103 (older board) or 106 and more. The colleague's Python
|
||||||
|
`Status.decode` requires exactly 103, so their `phone_emulator` rejects this board's STATUS.
|
||||||
|
- **Low** below 3.50 V (cleared at 3.60 V): the app shows an amber battery icon in the top bar and a
|
||||||
|
warning on the ESP32-C5 card. **Critical** below 3.30 V: red.
|
||||||
|
- **Shutdown:** when the smoothed voltage has stayed below 3.30 V for 30 s (6 samples), more than
|
||||||
|
60 s after boot, and **no phone has sent a frame over USB in the last 10 s**, the board sends a
|
||||||
|
last STATUS with the critical flag and goes into deep sleep. A phone on USB powers the board, so
|
||||||
|
the cell is not the reason it would stop and no shutdown happens. In deep sleep the board wakes
|
||||||
|
every 300 s, measures, and sleeps again until the cell reads 3.60 V (charged over USB); a reset
|
||||||
|
or power-cycle starts it normally and the rule applies again.
|
||||||
|
- The battery percentage in the app is a LiPo open-circuit-voltage table (`StationStatus.lipoPercent`):
|
||||||
|
an indicator, not a fuel gauge. It sags under TX and rises while charging.
|
||||||
|
|
||||||
|
All thresholds are `CONFIG_MICROBU_BATTERY_*` in `main/Kconfig.projbuild`. If the app's voltage
|
||||||
|
differs from a multimeter on the cell, set `CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` to
|
||||||
|
1000 × multimeter ÷ reading. Check it with `py -3.11 tools/station_status_watch.py COM10`: it
|
||||||
|
requests STATUS once a second and prints the battery fields.
|
||||||
|
|
||||||
|
Not measured yet: the charge current of the XIAO's charger (the wiki does not give it; a 5000 mAh
|
||||||
|
cell on a trickle charge takes days), whether the ADC reading is disturbed while the radio is
|
||||||
|
transmitting, and the board's own idle current from the cell. See TODO.md.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- No `git submodule update` needed here — obu-firmware has no pinned
|
- No `git submodule update` needed here — obu-firmware has no pinned
|
||||||
|
|||||||
+18
-5
@@ -22,14 +22,22 @@ Changed or added for this project (search for `MicrOBU:` in the sources):
|
|||||||
than the provisioned demo root (every RSU). Every captured frame therefore also goes through the
|
than the provisioned demo root (every RSU). Every captured frame therefore also goes through the
|
||||||
previous firmware's `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (0x85), whose body
|
previous firmware's `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (0x85), whose body
|
||||||
is exactly the old `SERIAL_MSG_V2X_RX` payload (`Station::forward_raw`). The app's receive side is
|
is exactly the old `SERIAL_MSG_V2X_RX` payload (`Station::forward_raw`). The app's receive side is
|
||||||
unchanged.
|
unchanged. Signed or not, BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM
|
||||||
|
pass (MAPEM and VAM since 2026-10-28); a message over 494 bytes does not fit a 512-octet link
|
||||||
|
message and is dropped and counted, not fragmented.
|
||||||
|
- **Bench listener** (`CONFIG_MICROBU_BENCH_LISTEN`, off in `sdkconfig`): for a board whose only PC
|
||||||
|
connection is the UART0 console. It configures itself receive-only at boot and logs every V2X_RX;
|
||||||
|
`tools/bench_listen_watch.py COMx` tallies the log. Build it from a copy of `sdkconfig` with the
|
||||||
|
option on and `CONFIG_MICROBU_BATTERY_ADC_GPIO=-1` (on a board without the XIAO's cell divider,
|
||||||
|
GPIO6 floats and can read like a flat cell, which deep-sleeps the board), e.g. `idf.py -B build-bench -DSDKCONFIG=<copy> build`.
|
||||||
- **Unsigned transmission is still possible.** The colleague's station refuses unsecured requests.
|
- **Unsigned transmission is still possible.** The colleague's station refuses unsecured requests.
|
||||||
Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header
|
Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header
|
||||||
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
|
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
|
||||||
messages" setting decides per message.
|
messages" setting decides per message.
|
||||||
- **Console on UART0.** ESP_LOG stays on the CH343 bridge port (COM3 on the bench); the native port
|
- **Console on UART0.** ESP_LOG stays on UART0 (GPIO11/12, pads D6/D7 on the XIAO); the native port
|
||||||
carries only link frames. The colleague's single-port board routes the log into LOG frames there
|
carries only link frames. The earlier bench board had a CH343 bridge on UART0 (COM3); the XIAO has
|
||||||
(`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
|
none, so its log is invisible unless a UART adapter is attached. The colleague's single-port board
|
||||||
|
routes the log into LOG frames on the native port (`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
|
||||||
- **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share
|
- **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share
|
||||||
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
|
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
|
||||||
(TODO.md).
|
(TODO.md).
|
||||||
@@ -38,7 +46,12 @@ Changed or added for this project (search for `MicrOBU:` in the sources):
|
|||||||
- The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack
|
- The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack
|
||||||
(the previous firmware's commit 04b0076 fixed the same risk).
|
(the previous firmware's commit 04b0076 fixed the same risk).
|
||||||
- Manual country policy and the TX-power read-back from the previous firmware's radio bring-up.
|
- Manual country policy and the TX-power read-back from the previous firmware's radio bring-up.
|
||||||
- The activity LED (GPIO27 on the colleague's XIAO board) is off unless configured.
|
- The activity LED (GPIO27 on the XIAO) is off unless configured (`CONFIG_MICROBU_TX_LED_GPIO`).
|
||||||
|
- **Production board is the XIAO ESP32-C5 (2026-10-05):** 8 MB flash, one native USB-C port, flashed
|
||||||
|
on COM10 on the bench. Battery: STATUS carries `battery_mv`/`battery_flags` (octets 103-105, a
|
||||||
|
MicrOBU extension; decoders accept 103 or >= 106 octets) and the board deep-sleeps below 3.30 V
|
||||||
|
when no phone is on USB, to protect a cell with no protection board. Details and thresholds:
|
||||||
|
FLASHING.md, "Battery and pins".
|
||||||
|
|
||||||
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the
|
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the
|
||||||
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
|
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
|
||||||
|
|||||||
@@ -12,11 +12,11 @@
|
|||||||
# Still compiled by the host tests in test/host.
|
# Still compiled by the host tests in test/host.
|
||||||
# tx_custom.c/.h - previous copy of the OpenTrafficMap raw TX; otm_tx_custom.c replaces it.
|
# tx_custom.c/.h - previous copy of the OpenTrafficMap raw TX; otm_tx_custom.c replaces it.
|
||||||
# denm.c/.h, cam.c/.h, wifi_patches.c - reference only, as before.
|
# denm.c/.h, cam.c/.h, wifi_patches.c - reference only, as before.
|
||||||
idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c"
|
idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "battery.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c"
|
||||||
"link_protocol.cpp" "serial_link.cpp" "station.cpp" "station_test.cpp"
|
"link_protocol.cpp" "serial_link.cpp" "station.cpp" "station_test.cpp"
|
||||||
"link_service.cpp" "test_channel.cpp"
|
"link_service.cpp" "test_channel.cpp"
|
||||||
"gn_unwrap.c" "geonet.c"
|
"gn_unwrap.c" "geonet.c"
|
||||||
INCLUDE_DIRS "."
|
INCLUDE_DIRS "."
|
||||||
LDFRAGMENTS "linker.lf"
|
LDFRAGMENTS "linker.lf"
|
||||||
REQUIRES vanetza-idf esp_wifi esp_phy esp_event bt esp_driver_gpio esp_driver_usb_serial_jtag nvs_flash esp_timer)
|
REQUIRES vanetza-idf esp_wifi esp_phy esp_event bt esp_driver_gpio esp_adc esp_driver_usb_serial_jtag nvs_flash esp_timer)
|
||||||
target_compile_features(${COMPONENT_LIB} PRIVATE cxx_std_17)
|
target_compile_features(${COMPONENT_LIB} PRIVATE cxx_std_17)
|
||||||
|
|||||||
@@ -36,4 +36,54 @@ config MICROBU_TX_LED_BLINK_MS
|
|||||||
config MICROBU_LED_INVERTED_RX
|
config MICROBU_LED_INVERTED_RX
|
||||||
bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)"
|
bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)"
|
||||||
default n
|
default n
|
||||||
|
config MICROBU_BENCH_LISTEN
|
||||||
|
bool "Bench listener: receive from boot and log every V2X_RX on the console"
|
||||||
|
default n
|
||||||
|
help
|
||||||
|
For a test board whose PC connection is only the UART0 console (no phone, no USB
|
||||||
|
Serial/JTAG link): the station configures itself at boot with the radio receive only and
|
||||||
|
security off, and logs one line per ITS message the raw path (gn_unwrap.c) unwraps: BTP
|
||||||
|
port, messageID, length, RSSI, signed, GeoBroadcast, and whether it fits a link message.
|
||||||
|
A phone that configures the station later replaces this configuration. Never enable it in
|
||||||
|
the production image.
|
||||||
|
config MICROBU_BATTERY_ADC_GPIO
|
||||||
|
int "Battery voltage ADC GPIO (-1: no battery monitoring)"
|
||||||
|
range -1 6
|
||||||
|
default 6
|
||||||
|
help
|
||||||
|
The XIAO ESP32-C5 reads its battery on GPIO6 (BAT_VOLT_PIN) through two 100 k resistors.
|
||||||
|
config MICROBU_BATTERY_EN_GPIO
|
||||||
|
int "Battery divider enable GPIO"
|
||||||
|
range 0 28
|
||||||
|
default 26
|
||||||
|
help
|
||||||
|
XIAO ESP32-C5: GPIO26 (BAT_VOLT_PIN_EN) switches the divider on for the reading.
|
||||||
|
config MICROBU_BATTERY_SCALE_PERMILLE
|
||||||
|
int "Battery reading trim (1000 = none)"
|
||||||
|
range 800 1200
|
||||||
|
default 1000
|
||||||
|
help
|
||||||
|
Multiplies the reading. Compare the STATUS battery voltage with a multimeter on the cell
|
||||||
|
and set this to 1000 * multimeter / reading if the divider or ADC is off.
|
||||||
|
config MICROBU_BATTERY_WARN_MV
|
||||||
|
int "Low-battery warning below this cell voltage (mV)"
|
||||||
|
range 3000 4200
|
||||||
|
default 3500
|
||||||
|
config MICROBU_BATTERY_SHUTDOWN_MV
|
||||||
|
int "Shutdown below this cell voltage (mV), see battery_monitor.hpp"
|
||||||
|
range 3000 4200
|
||||||
|
default 3300
|
||||||
|
help
|
||||||
|
There is no protection board on the prototype cell, so this is the only guard against
|
||||||
|
over-discharge. The board shuts down (deep sleep) once the smoothed voltage has stayed below
|
||||||
|
this for 30 s and no phone is talking over USB; it checks the cell again every
|
||||||
|
MICROBU_BATTERY_SLEEP_S and runs again from 3600 mV.
|
||||||
|
config MICROBU_BATTERY_RESUME_MV
|
||||||
|
int "After a shutdown, run again at or above this cell voltage (mV)"
|
||||||
|
range 3300 4200
|
||||||
|
default 3600
|
||||||
|
config MICROBU_BATTERY_SLEEP_S
|
||||||
|
int "Seconds between cell checks while shut down"
|
||||||
|
range 30 3600
|
||||||
|
default 300
|
||||||
endmenu
|
endmenu
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
// enqueues frames. Link messages: implementation/station-link/README.md.
|
// enqueues frames. Link messages: implementation/station-link/README.md.
|
||||||
#include "link_protocol.hpp"
|
#include "link_protocol.hpp"
|
||||||
#include "link_service.hpp"
|
#include "link_service.hpp"
|
||||||
|
#include "battery.hpp"
|
||||||
|
#include "battery_monitor.hpp"
|
||||||
#include "board_controls.hpp"
|
#include "board_controls.hpp"
|
||||||
#include "simple_ble.hpp"
|
#include "simple_ble.hpp"
|
||||||
#include "serial_link.hpp"
|
#include "serial_link.hpp"
|
||||||
@@ -30,6 +32,9 @@ struct Incoming {
|
|||||||
microbu::serial::Frame frame;
|
microbu::serial::Frame frame;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
constexpr std::int64_t battery_interval_us = 5000000; // one cell sample every 5 s
|
||||||
|
constexpr std::uint32_t battery_usb_window_ms = 10000; // a USB frame this recently means a phone powers the board
|
||||||
|
|
||||||
QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes never enter the queue itself
|
QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes never enter the queue itself
|
||||||
|
|
||||||
/// @brief Attempts to heap-allocate an Incoming so it can be pushed onto the frames queue.
|
/// @brief Attempts to heap-allocate an Incoming so it can be pushed onto the frames queue.
|
||||||
@@ -74,6 +79,36 @@ void pause_ble_while_usb_in_use() {
|
|||||||
microbu::ble::set_advertising_allowed(!usb_in_use);
|
microbu::ble::set_advertising_allowed(!usb_in_use);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// @brief MicrOBU: the battery policy with this build's Kconfig thresholds.
|
||||||
|
microbu::BatteryConfig battery_config() {
|
||||||
|
microbu::BatteryConfig config;
|
||||||
|
config.warn_mv = CONFIG_MICROBU_BATTERY_WARN_MV;
|
||||||
|
config.warn_clear_mv = CONFIG_MICROBU_BATTERY_WARN_MV + 100; // 100 mV of hysteresis
|
||||||
|
config.shutdown_mv = CONFIG_MICROBU_BATTERY_SHUTDOWN_MV;
|
||||||
|
config.resume_mv = CONFIG_MICROBU_BATTERY_RESUME_MV;
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @brief MicrOBU: samples the cell, publishes it in STATUS and powers the board down before the
|
||||||
|
/// unprotected cell is over-discharged. A phone on USB powers the board itself, so the cell does not
|
||||||
|
/// force a shutdown while one is talking (see BatteryMonitor::update).
|
||||||
|
void check_battery(microbu::Battery& battery, microbu::BatteryMonitor& monitor, microbu::LinkService& link) {
|
||||||
|
const auto now_ms = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
|
||||||
|
const auto last_usb = microbu::serial::last_frame_ms();
|
||||||
|
const bool usb_active = last_usb != 0 && now_ms - last_usb < battery_usb_window_ms;
|
||||||
|
monitor.update(battery.measure(), usb_active, now_ms);
|
||||||
|
std::uint8_t flags = 0;
|
||||||
|
if (monitor.low()) flags |= microbu::link::battery_flag_low;
|
||||||
|
if (monitor.critical()) flags |= microbu::link::battery_flag_critical;
|
||||||
|
link.set_battery(monitor.millivolts(), flags);
|
||||||
|
if (monitor.shutdown_due()) {
|
||||||
|
ESP_LOGW(TAG, "cell at %u mV and no phone on USB: shutting down", unsigned(monitor.millivolts()));
|
||||||
|
link.send_status_now(); // the phone sees the critical flag before the link goes away
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500));
|
||||||
|
microbu::Battery::deep_sleep();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// @brief FreeRTOS task body: owns the station, link service and board controls. Drains the incoming queue.
|
/// @brief FreeRTOS task body: owns the station, link service and board controls. Drains the incoming queue.
|
||||||
void station_task(void*) {
|
void station_task(void*) {
|
||||||
microbu::Station station;
|
microbu::Station station;
|
||||||
@@ -81,6 +116,22 @@ void station_task(void*) {
|
|||||||
microbu::BoardControls controls;
|
microbu::BoardControls controls;
|
||||||
station.on_disseminated([&controls] { controls.blink(); });
|
station.on_disseminated([&controls] { controls.blink(); });
|
||||||
station.on_received([&controls] { controls.blink(); });
|
station.on_received([&controls] { controls.blink(); });
|
||||||
|
microbu::Battery battery;
|
||||||
|
microbu::BatteryMonitor monitor(battery_config());
|
||||||
|
std::int64_t next_battery_us = 0;
|
||||||
|
#if CONFIG_MICROBU_BENCH_LISTEN
|
||||||
|
{ // MicrOBU: a console-only test board has nothing that would configure it (Kconfig help)
|
||||||
|
microbu::link::StationConfigure bench;
|
||||||
|
bench.security = 0;
|
||||||
|
bench.address_configuration = 0;
|
||||||
|
bench.beaconing = 0;
|
||||||
|
bench.radio = 1; // receive only
|
||||||
|
microbu::link::Bytes detail;
|
||||||
|
const auto code = station.configure(bench, detail);
|
||||||
|
ESP_LOGW(TAG, "BENCH LISTEN build: radio receive only, security off, logging every V2X_RX (result %u)",
|
||||||
|
unsigned(code));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
ESP_LOGI(TAG, "station task ready; the phone/PC configures the station over BLE or USB Serial-JTAG");
|
ESP_LOGI(TAG, "station task ready; the phone/PC configures the station over BLE or USB Serial-JTAG");
|
||||||
for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls
|
for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls
|
||||||
Incoming* incoming = nullptr;
|
Incoming* incoming = nullptr;
|
||||||
@@ -95,12 +146,27 @@ void station_task(void*) {
|
|||||||
link.tick();
|
link.tick();
|
||||||
controls.tick();
|
controls.tick();
|
||||||
pause_ble_while_usb_in_use();
|
pause_ble_while_usb_in_use();
|
||||||
|
if (esp_timer_get_time() >= next_battery_us) {
|
||||||
|
next_battery_us = esp_timer_get_time() + battery_interval_us;
|
||||||
|
check_battery(battery, monitor, link);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// @brief Firmware entry point: initializes NVS, watchdog, serial/BLE transports, and starts the station task.
|
/// @brief Firmware entry point: initializes NVS, watchdog, serial/BLE transports, and starts the station task.
|
||||||
extern "C" void app_main() {
|
extern "C" void app_main() {
|
||||||
|
// MicrOBU: woken from a low-battery shutdown. Judge the cell before anything else starts, and
|
||||||
|
// go back to sleep unless it has recovered (charged over USB).
|
||||||
|
if (microbu::Battery::woke_from_battery_sleep()) {
|
||||||
|
microbu::Battery battery;
|
||||||
|
const auto millivolts = battery.measure();
|
||||||
|
if (!microbu::BatteryMonitor(battery_config()).resume_ok(millivolts)) {
|
||||||
|
ESP_LOGW(TAG, "cell still at %u mV, back to sleep", unsigned(millivolts));
|
||||||
|
microbu::Battery::deep_sleep();
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "cell at %u mV, starting", unsigned(millivolts));
|
||||||
|
}
|
||||||
// NVS: the credential store (and the Wi-Fi driver's calibration data)
|
// NVS: the credential store (and the Wi-Fi driver's calibration data)
|
||||||
esp_err_t nvs = nvs_flash_init();
|
esp_err_t nvs = nvs_flash_init();
|
||||||
if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#include "battery.hpp"
|
||||||
|
#include "sdkconfig.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <driver/gpio.h>
|
||||||
|
#include <esp_adc/adc_cali.h>
|
||||||
|
#include <esp_adc/adc_cali_scheme.h>
|
||||||
|
#include <esp_adc/adc_oneshot.h>
|
||||||
|
#include <esp_log.h>
|
||||||
|
#include <esp_rom_sys.h>
|
||||||
|
#include <esp_sleep.h>
|
||||||
|
|
||||||
|
namespace microbu {
|
||||||
|
namespace {
|
||||||
|
const char* TAG = "battery";
|
||||||
|
constexpr int samples = 16;
|
||||||
|
constexpr std::uint32_t settle_us = 2000; // the load switch and the divider's RC settle in well under this
|
||||||
|
constexpr int divider = 2; // two equal 100 k resistors on the XIAO ESP32-C5
|
||||||
|
}
|
||||||
|
|
||||||
|
Battery::Battery() {
|
||||||
|
#if CONFIG_MICROBU_BATTERY_ADC_GPIO < 0
|
||||||
|
ESP_LOGI(TAG, "battery monitoring disabled");
|
||||||
|
return;
|
||||||
|
#endif
|
||||||
|
gpio_config_t enable = {};
|
||||||
|
enable.pin_bit_mask = 1ULL << CONFIG_MICROBU_BATTERY_EN_GPIO;
|
||||||
|
enable.mode = GPIO_MODE_OUTPUT;
|
||||||
|
if (gpio_config(&enable) != ESP_OK) { ESP_LOGE(TAG, "enable GPIO %d unusable", CONFIG_MICROBU_BATTERY_EN_GPIO); return; }
|
||||||
|
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
|
||||||
|
|
||||||
|
adc_unit_t unit;
|
||||||
|
adc_channel_t channel;
|
||||||
|
if (adc_oneshot_io_to_channel(CONFIG_MICROBU_BATTERY_ADC_GPIO, &unit, &channel) != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "GPIO %d is not an ADC pin", CONFIG_MICROBU_BATTERY_ADC_GPIO);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
adc_oneshot_unit_init_cfg_t unit_config = {};
|
||||||
|
unit_config.unit_id = unit;
|
||||||
|
adc_oneshot_unit_handle_t adc = nullptr;
|
||||||
|
if (adc_oneshot_new_unit(&unit_config, &adc) != ESP_OK) { ESP_LOGE(TAG, "ADC unit init failed"); return; }
|
||||||
|
adc_oneshot_chan_cfg_t channel_config = {};
|
||||||
|
channel_config.atten = ADC_ATTEN_DB_12; // the divided cell is at most about 2.1 V
|
||||||
|
channel_config.bitwidth = ADC_BITWIDTH_DEFAULT;
|
||||||
|
if (adc_oneshot_config_channel(adc, channel, &channel_config) != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "ADC channel config failed");
|
||||||
|
adc_oneshot_del_unit(adc);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
|
||||||
|
adc_cali_curve_fitting_config_t cali_config = {};
|
||||||
|
cali_config.unit_id = unit;
|
||||||
|
cali_config.chan = channel;
|
||||||
|
cali_config.atten = ADC_ATTEN_DB_12;
|
||||||
|
cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
|
||||||
|
adc_cali_handle_t cali = nullptr;
|
||||||
|
if (adc_cali_create_scheme_curve_fitting(&cali_config, &cali) == ESP_OK) cali_ = cali;
|
||||||
|
#endif
|
||||||
|
if (!cali_) ESP_LOGW(TAG, "no ADC calibration: readings are approximate");
|
||||||
|
adc_ = adc;
|
||||||
|
channel_ = static_cast<int>(channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint16_t Battery::measure() {
|
||||||
|
if (!adc_) return 0;
|
||||||
|
auto* adc = static_cast<adc_oneshot_unit_handle_t>(adc_);
|
||||||
|
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 1);
|
||||||
|
esp_rom_delay_us(settle_us);
|
||||||
|
int values[samples];
|
||||||
|
int count = 0;
|
||||||
|
for (int i = 0; i < samples; ++i) {
|
||||||
|
int raw = 0;
|
||||||
|
if (adc_oneshot_read(adc, static_cast<adc_channel_t>(channel_), &raw) != ESP_OK) continue;
|
||||||
|
int millivolts = 0;
|
||||||
|
if (cali_) {
|
||||||
|
if (adc_cali_raw_to_voltage(static_cast<adc_cali_handle_t>(cali_), raw, &millivolts) != ESP_OK) continue;
|
||||||
|
} else {
|
||||||
|
millivolts = raw * 3100 / 4095; // uncalibrated 12 dB full scale, roughly
|
||||||
|
}
|
||||||
|
values[count++] = millivolts;
|
||||||
|
}
|
||||||
|
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
|
||||||
|
if (count < samples / 2) return 0;
|
||||||
|
std::sort(values, values + count);
|
||||||
|
const int median = values[count / 2];
|
||||||
|
const long cell_mv = static_cast<long>(median) * divider * CONFIG_MICROBU_BATTERY_SCALE_PERMILLE / 1000;
|
||||||
|
return static_cast<std::uint16_t>(std::clamp(cell_mv, 0L, 65535L));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Battery::deep_sleep() {
|
||||||
|
ESP_LOGW(TAG, "deep sleep for %d s", CONFIG_MICROBU_BATTERY_SLEEP_S);
|
||||||
|
esp_sleep_enable_timer_wakeup(static_cast<std::uint64_t>(CONFIG_MICROBU_BATTERY_SLEEP_S) * 1000000ULL);
|
||||||
|
esp_deep_sleep_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Battery::woke_from_battery_sleep() {
|
||||||
|
return esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace microbu
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#pragma once
|
||||||
|
// Cell voltage of the XIAO ESP32-C5's battery, read through the board's own divider: GPIO6 (ADC1)
|
||||||
|
// behind two 100 k resistors, switched on by GPIO26 (a load switch that keeps the divider from
|
||||||
|
// draining the cell between readings). The policy (warning, shutdown) is in battery_monitor.hpp.
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace microbu {
|
||||||
|
|
||||||
|
class Battery {
|
||||||
|
public:
|
||||||
|
/// @brief Configures the enable GPIO and the ADC channel. On failure measure() returns 0.
|
||||||
|
Battery();
|
||||||
|
/// @brief Takes one measurement: enables the divider, samples, disables it again. Blocks for a few ms.
|
||||||
|
/// @return Cell voltage in millivolts, or 0 if the ADC could not be set up or read.
|
||||||
|
std::uint16_t measure();
|
||||||
|
/// @brief Puts the board into deep sleep and wakes it after CONFIG_MICROBU_BATTERY_SLEEP_S seconds.
|
||||||
|
/// Does not return.
|
||||||
|
[[noreturn]] static void deep_sleep();
|
||||||
|
/// @return true if this boot is the end of such a sleep (the only timer wake-up the firmware arms).
|
||||||
|
static bool woke_from_battery_sleep();
|
||||||
|
|
||||||
|
private:
|
||||||
|
void* adc_ = nullptr; // adc_oneshot_unit_handle_t
|
||||||
|
void* cali_ = nullptr; // adc_cali_handle_t, null when the chip has no calibration
|
||||||
|
int channel_ = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
#pragma once
|
||||||
|
// Cell-voltage policy for the XIAO ESP32-C5's LiPo: smoothing, the low-battery warning with
|
||||||
|
// hysteresis, and the decision to shut down. Pure logic with no ESP-IDF dependency, so the host
|
||||||
|
// tests (test/host/test_battery.cpp) compile this header unmodified.
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace microbu {
|
||||||
|
|
||||||
|
/// @brief Thresholds and timing of the battery policy. Millivolts at the cell, not at the ADC pin.
|
||||||
|
struct BatteryConfig {
|
||||||
|
std::uint16_t warn_mv = 3500; ///< low-battery warning below this
|
||||||
|
std::uint16_t warn_clear_mv = 3600;///< ... and cleared again at or above this (hysteresis)
|
||||||
|
std::uint16_t shutdown_mv = 3300; ///< shut down below this ...
|
||||||
|
unsigned shutdown_samples = 6; ///< ... for this many consecutive samples (6 x 5 s = 30 s: rides out TX sag)
|
||||||
|
std::uint32_t grace_ms = 60000; ///< no shutdown in the first minute after boot
|
||||||
|
std::uint16_t resume_mv = 3600; ///< after a shutdown the board only runs again at or above this
|
||||||
|
std::uint16_t valid_min_mv = 2500; ///< a reading outside valid_min..valid_max is "no cell / no sensor"
|
||||||
|
std::uint16_t valid_max_mv = 4500;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// @brief Turns raw cell-voltage samples into a smoothed value, a warning flag and a shutdown decision.
|
||||||
|
class BatteryMonitor {
|
||||||
|
public:
|
||||||
|
/// @param config Thresholds; the defaults suit a single LiPo cell.
|
||||||
|
explicit BatteryMonitor(BatteryConfig config = {}) : config_(config) {}
|
||||||
|
|
||||||
|
/// @brief Feeds one sample, taken every few seconds.
|
||||||
|
/// @param mv Cell voltage in millivolts, or 0 when the measurement failed.
|
||||||
|
/// @param usb_active A phone is talking over USB, so the board is powered from the phone and
|
||||||
|
/// the cell cannot be the reason it would stop.
|
||||||
|
/// @param uptime_ms Milliseconds since boot.
|
||||||
|
void update(std::uint16_t mv, bool usb_active, std::uint32_t uptime_ms) {
|
||||||
|
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) {
|
||||||
|
// No cell (or no sensor): report "not measured" and never shut down on it.
|
||||||
|
valid_ = false; ema_ = 0; low_ = false; below_ = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!valid_) { valid_ = true; ema_ = mv; } // first sample after a gap: no ramp from zero
|
||||||
|
else ema_ = static_cast<std::uint16_t>(ema_ + (static_cast<int>(mv) - static_cast<int>(ema_)) / 4);
|
||||||
|
if (ema_ < config_.warn_mv) low_ = true;
|
||||||
|
else if (ema_ >= config_.warn_clear_mv) low_ = false;
|
||||||
|
if (ema_ < config_.shutdown_mv && !usb_active && uptime_ms >= config_.grace_ms) ++below_;
|
||||||
|
else below_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @return Smoothed cell voltage in millivolts, 0 while there is no valid reading.
|
||||||
|
std::uint16_t millivolts() const { return valid_ ? ema_ : 0; }
|
||||||
|
/// @return true once the cell fell below the warning threshold, until it is back above the clear threshold.
|
||||||
|
bool low() const { return low_; }
|
||||||
|
/// @return true while the smoothed voltage is below the shutdown threshold (not yet sustained).
|
||||||
|
bool critical() const { return valid_ && ema_ < config_.shutdown_mv; }
|
||||||
|
/// @return true once the cell has stayed below the shutdown threshold with no USB link for long enough.
|
||||||
|
bool shutdown_due() const { return below_ >= config_.shutdown_samples; }
|
||||||
|
|
||||||
|
/// @param mv A single reading taken right after a wake-up.
|
||||||
|
/// @return true if the board may run: the cell recovered, or there is no valid reading to judge by.
|
||||||
|
bool resume_ok(std::uint16_t mv) const {
|
||||||
|
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) return true;
|
||||||
|
return mv >= config_.resume_mv;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
BatteryConfig config_;
|
||||||
|
std::uint16_t ema_ = 0;
|
||||||
|
bool valid_ = false;
|
||||||
|
bool low_ = false;
|
||||||
|
unsigned below_ = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu
|
||||||
@@ -47,7 +47,9 @@
|
|||||||
// NOTE the crossover: SPATEM is BTP port 2004 but ItsPduHeader messageID 4, while MAPEM is port
|
// NOTE the crossover: SPATEM is BTP port 2004 but ItsPduHeader messageID 4, while MAPEM is port
|
||||||
// 2003 and messageID 5. Port and messageID are NOT the same number - mixing them up routes every
|
// 2003 and messageID 5. Port and messageID are NOT the same number - mixing them up routes every
|
||||||
// message to the wrong decoder on the phone.
|
// message to the wrong decoder on the phone.
|
||||||
|
#define BTP_DEST_PORT_MAPEM (2003)
|
||||||
#define BTP_DEST_PORT_SPATEM (2004)
|
#define BTP_DEST_PORT_SPATEM (2004)
|
||||||
|
#define BTP_DEST_PORT_VAM (2018)
|
||||||
|
|
||||||
static const uint8_t s_llc_snap_prefix[6] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
|
static const uint8_t s_llc_snap_prefix[6] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
|
||||||
|
|
||||||
@@ -249,7 +251,8 @@ bool gn_unwrap_its(const uint8_t *frame, int frame_len, gn_rx_t *out)
|
|||||||
}
|
}
|
||||||
uint16_t dest_port = be16(frame + offset);
|
uint16_t dest_port = be16(frame + offset);
|
||||||
if (dest_port != BTP_DEST_PORT_CAM && dest_port != BTP_DEST_PORT_DENM &&
|
if (dest_port != BTP_DEST_PORT_CAM && dest_port != BTP_DEST_PORT_DENM &&
|
||||||
dest_port != BTP_DEST_PORT_SPATEM) {
|
dest_port != BTP_DEST_PORT_MAPEM && dest_port != BTP_DEST_PORT_SPATEM &&
|
||||||
|
dest_port != BTP_DEST_PORT_VAM) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,20 +47,23 @@
|
|||||||
// decoders stop where the message ends, which is why nothing visibly broke.
|
// decoders stop where the message ends, which is why nothing visibly broke.
|
||||||
//
|
//
|
||||||
// ---- Accepted BTP-B ports (ETSI TS 103 248) ------------------------------------------------
|
// ---- Accepted BTP-B ports (ETSI TS 103 248) ------------------------------------------------
|
||||||
// 2001 (CAM), 2002 (DENM) and 2004 (SPATEM). MAPEM (2003) and the rest are deliberately not
|
// 2001 (CAM), 2002 (DENM), 2003 (MAPEM, since 2026-10-28), 2004 (SPATEM) and 2018 (VAM, since
|
||||||
// accepted yet: the phone has no decoder for them, so forwarding would just burn serial
|
// 2026-10-28; another micrOBU's VAM is demo-signed, so the stack verifies it too, but the app reads
|
||||||
// bandwidth. Adding one is a one-line change here plus a decoder on the phone - the serial
|
// only this path). Other ports are dropped. The link message itself is generic: the port says what
|
||||||
// protocol itself is already generic (see SERIAL_MSG_V2X_RX in serial_link.h).
|
// the payload is.
|
||||||
//
|
//
|
||||||
// SPATEM size caveat: SERIAL_LINK_MAX_PAYLOAD is 512, so a SPATEM whose UPER exceeds 498 bytes is
|
// Size caveat: a link message is at most 512 octets (link::maximum_message, which is also the
|
||||||
// counted as an oversize drop rather than forwarded. The bench RSU trigger emits ~58-byte SPATEMs
|
// largest GATT attribute value), so Station::forward_raw() drops a message whose UPER exceeds
|
||||||
// and is unaffected, but real road RSUs measured 555 bytes median and 1243 max (2026-03-18 drive,
|
// 494 bytes and counts it as oversize instead of forwarding it. Nothing is fragmented. The bench
|
||||||
// 79k messages), i.e. roughly 70% would be dropped. Raising the cap is deliberately deferred: it
|
// RSU's messages all fit (2026-10-28 capture: SPATEM 58, MAPEM 295 bytes); real road SPATEMs and
|
||||||
// also requires enlarging main.c's RX_FRAME_MAX_LEN.
|
// MAPEMs often do not (SPATEM 555 bytes median, 1243 max on the 2026-03-18 drive). The radio
|
||||||
|
// itself captures frames of up to 2346 bytes (c5_radio.cpp), so `truncated` does not happen on
|
||||||
|
// this firmware.
|
||||||
//
|
//
|
||||||
// No FCS/CRC check here: the WiFi driver has already validated the frame.
|
// No FCS/CRC check here: the WiFi driver has already validated the frame.
|
||||||
typedef struct {
|
typedef struct {
|
||||||
// BTP-B destination port, identifying the service: 2001 = CAM, 2002 = DENM, 2004 = SPATEM.
|
// BTP-B destination port, identifying the service: 2001 = CAM, 2002 = DENM, 2003 = MAPEM,
|
||||||
|
// 2004 = SPATEM, 2018 = VAM.
|
||||||
uint16_t btp_dest_port;
|
uint16_t btp_dest_port;
|
||||||
|
|
||||||
// ITS payload (UPER message bytes). Points INTO the caller's `frame` buffer - NOT a copy, so
|
// ITS payload (UPER message bytes). Points INTO the caller's `frame` buffer - NOT a copy, so
|
||||||
@@ -80,8 +83,9 @@ typedef struct {
|
|||||||
// The packet arrived inside a TS 103 097 signed envelope. The signature was NOT checked.
|
// The packet arrived inside a TS 103 097 signed envelope. The signature was NOT checked.
|
||||||
bool signed_unverified;
|
bool signed_unverified;
|
||||||
|
|
||||||
// The frame ended before the payload its headers declare. On the board only main.c's
|
// The frame ended before the payload its headers declare. On the board only a capture limit
|
||||||
// RX_FRAME_MAX_LEN capture limit causes this (the driver drops frames that fail their FCS).
|
// causes this (the driver drops frames that fail their FCS): the old C firmware's 800-byte
|
||||||
|
// RX_FRAME_MAX_LEN did; c5_radio.cpp keeps whole frames.
|
||||||
// payload/payload_len then cover just the part that arrived, so it must not be forwarded.
|
// payload/payload_len then cover just the part that arrived, so it must not be forwarded.
|
||||||
bool truncated;
|
bool truncated;
|
||||||
} gn_rx_t;
|
} gn_rx_t;
|
||||||
|
|||||||
@@ -157,9 +157,11 @@ Bytes encode(const Status& s) {
|
|||||||
w.u32(s.radio_submitted); w.u32(s.radio_failed); w.u32(s.radio_received); w.u32(s.radio_dropped);
|
w.u32(s.radio_submitted); w.u32(s.radio_failed); w.u32(s.radio_received); w.u32(s.radio_dropped);
|
||||||
w.u32(s.link_rx_frames); w.u32(s.link_crc_errors); w.u32(s.link_malformed); w.u32(s.poti_updates);
|
w.u32(s.link_rx_frames); w.u32(s.link_crc_errors); w.u32(s.link_malformed); w.u32(s.poti_updates);
|
||||||
w.u64(s.its_time_ms);
|
w.u64(s.its_time_ms);
|
||||||
|
w.u16(s.battery_mv); w.u8(s.battery_flags);
|
||||||
return w.out;
|
return w.out;
|
||||||
}
|
}
|
||||||
bool decode(const Bytes& body, Status& s) {
|
bool decode(const Bytes& body, Status& s) {
|
||||||
|
if (body.size() != status_size_base && body.size() < status_size_battery) return false;
|
||||||
Reader r(body);
|
Reader r(body);
|
||||||
s.uptime_ms = r.u32(); s.configured = r.u8(); r.bytes(s.gn_address, 8); r.bytes(s.identifier, 8); s.change_pending = r.u8(); s.tickets = r.u8();
|
s.uptime_ms = r.u32(); s.configured = r.u8(); r.bytes(s.gn_address, 8); r.bytes(s.identifier, 8); s.change_pending = r.u8(); s.tickets = r.u8();
|
||||||
s.signed_messages = r.u32(); s.refused_no_ticket = r.u32(); s.refused_change_pending = r.u32(); s.refused_permission = r.u32();
|
s.signed_messages = r.u32(); s.refused_no_ticket = r.u32(); s.refused_change_pending = r.u32(); s.refused_permission = r.u32();
|
||||||
@@ -168,7 +170,10 @@ bool decode(const Bytes& body, Status& s) {
|
|||||||
s.radio_submitted = r.u32(); s.radio_failed = r.u32(); s.radio_received = r.u32(); s.radio_dropped = r.u32();
|
s.radio_submitted = r.u32(); s.radio_failed = r.u32(); s.radio_received = r.u32(); s.radio_dropped = r.u32();
|
||||||
s.link_rx_frames = r.u32(); s.link_crc_errors = r.u32(); s.link_malformed = r.u32(); s.poti_updates = r.u32();
|
s.link_rx_frames = r.u32(); s.link_crc_errors = r.u32(); s.link_malformed = r.u32(); s.poti_updates = r.u32();
|
||||||
s.its_time_ms = r.u64();
|
s.its_time_ms = r.u64();
|
||||||
return r.done();
|
if (!r.ok()) return false;
|
||||||
|
s.battery_mv = 0; s.battery_flags = 0;
|
||||||
|
if (r.remaining() >= 3) { s.battery_mv = r.u16(); s.battery_flags = r.u8(); }
|
||||||
|
return r.ok(); // octets beyond the known fields belong to a later extension
|
||||||
}
|
}
|
||||||
|
|
||||||
// RESULT
|
// RESULT
|
||||||
|
|||||||
@@ -292,9 +292,22 @@ struct Status {
|
|||||||
std::uint32_t radio_submitted = 0, radio_failed = 0, radio_received = 0, radio_dropped = 0;
|
std::uint32_t radio_submitted = 0, radio_failed = 0, radio_received = 0, radio_dropped = 0;
|
||||||
std::uint32_t link_rx_frames = 0, link_crc_errors = 0, link_malformed = 0, poti_updates = 0;
|
std::uint32_t link_rx_frames = 0, link_crc_errors = 0, link_malformed = 0, poti_updates = 0;
|
||||||
std::uint64_t its_time_ms = 0;
|
std::uint64_t its_time_ms = 0;
|
||||||
|
// MicrOBU extension, appended after the colleague's 103 octets: [103] battery_mv u16 (0: not
|
||||||
|
// measured, no cell or no sensor), [105] battery_flags u8. A 103-octet body (the colleague's
|
||||||
|
// layout, and this firmware before the battery) still decodes, with these two left at 0.
|
||||||
|
std::uint16_t battery_mv = 0;
|
||||||
|
std::uint8_t battery_flags = 0;
|
||||||
};
|
};
|
||||||
|
/// battery_flags bits of Status.
|
||||||
|
constexpr std::uint8_t battery_flag_low = 0x01; ///< cell below the warning threshold
|
||||||
|
constexpr std::uint8_t battery_flag_critical = 0x02; ///< cell below the shutdown threshold: the board powers down unless a phone is on USB
|
||||||
|
/// Octets of the STATUS body without / with the MicrOBU battery extension.
|
||||||
|
constexpr std::size_t status_size_base = 103;
|
||||||
|
constexpr std::size_t status_size_battery = 106;
|
||||||
/// @param body Raw message body bytes.
|
/// @param body Raw message body bytes.
|
||||||
/// @param out Receives the decoded status.
|
/// @param out Receives the decoded status. Accepts the 103-octet base body and any body of at
|
||||||
|
/// least 106 octets (trailing octets after the known fields are ignored, so a later
|
||||||
|
/// extension does not break this decoder); 104 or 105 octets are malformed.
|
||||||
/// @return false if malformed.
|
/// @return false if malformed.
|
||||||
bool decode(const Bytes& body, Status& out);
|
bool decode(const Bytes& body, Status& out);
|
||||||
/// @param value Status to encode.
|
/// @param value Status to encode.
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ link::Status LinkService::status() {
|
|||||||
value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages;
|
value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages;
|
||||||
value.link_crc_errors = serial_counters.crc_errors;
|
value.link_crc_errors = serial_counters.crc_errors;
|
||||||
value.link_malformed += ble_counters.malformed;
|
value.link_malformed += ble_counters.malformed;
|
||||||
|
value.battery_mv = battery_mv_;
|
||||||
|
value.battery_flags = battery_flags_;
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,6 +151,16 @@ void LinkService::handle(const link::Bytes& octets, LinkTransport origin) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void LinkService::set_battery(std::uint16_t millivolts, std::uint8_t flags) {
|
||||||
|
battery_mv_ = millivolts;
|
||||||
|
battery_flags_ = flags;
|
||||||
|
}
|
||||||
|
|
||||||
|
void LinkService::send_status_now() {
|
||||||
|
last_status_us_ = esp_timer_get_time();
|
||||||
|
broadcast(link::Opcode::STATUS, ++own_sequence_, link::encode(status()));
|
||||||
|
}
|
||||||
|
|
||||||
void LinkService::tick() {
|
void LinkService::tick() {
|
||||||
const auto now = esp_timer_get_time();
|
const auto now = esp_timer_get_time();
|
||||||
if (now - last_status_us_ < 1000000) return;
|
if (now - last_status_us_ < 1000000) return;
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ public:
|
|||||||
void handle(const link::Bytes& message, LinkTransport origin);
|
void handle(const link::Bytes& message, LinkTransport origin);
|
||||||
/// @brief Periodic work: broadcasts STATUS once a second.
|
/// @brief Periodic work: broadcasts STATUS once a second.
|
||||||
void tick();
|
void tick();
|
||||||
|
/// @brief Sets the battery fields of every following STATUS.
|
||||||
|
/// @param millivolts Cell voltage, 0 if not measured.
|
||||||
|
/// @param flags link::battery_flag_* bits.
|
||||||
|
void set_battery(std::uint16_t millivolts, std::uint8_t flags);
|
||||||
|
/// @brief Broadcasts a STATUS now instead of waiting for the next second.
|
||||||
|
void send_status_now();
|
||||||
private:
|
private:
|
||||||
/// @brief Encodes and writes one message on the given transport.
|
/// @brief Encodes and writes one message on the given transport.
|
||||||
/// @param transport Transport to write to.
|
/// @param transport Transport to write to.
|
||||||
@@ -46,6 +52,8 @@ private:
|
|||||||
link::Bytes bundle_; // credentials being provisioned
|
link::Bytes bundle_; // credentials being provisioned
|
||||||
std::uint16_t bundle_total_ = 0;
|
std::uint16_t bundle_total_ = 0;
|
||||||
std::int64_t last_status_us_ = 0;
|
std::int64_t last_status_us_ = 0;
|
||||||
|
std::uint16_t battery_mv_ = 0;
|
||||||
|
std::uint8_t battery_flags_ = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace microbu
|
} // namespace microbu
|
||||||
|
|||||||
@@ -360,8 +360,22 @@ void app_main(void)
|
|||||||
ESP_LOGW(TAG, "esp_wifi_set_country(MANUAL) failed: %d (continuing)", ctry_err);
|
ESP_LOGW(TAG, "esp_wifi_set_country(MANUAL) failed: %d (continuing)", ctry_err);
|
||||||
}
|
}
|
||||||
// Ensure the PA runs at full configured power (not a reduced regulatory
|
// Ensure the PA runs at full configured power (not a reduced regulatory
|
||||||
// default). Units are 0.25 dBm; 80 = 20 dBm.
|
// default). Units are 0.25 dBm; 80 = 20 dBm, which is also the build's own
|
||||||
esp_wifi_set_max_tx_power(80);
|
// ceiling (CONFIG_ESP_PHY_MAX_TX_POWER=20).
|
||||||
|
//
|
||||||
|
// Read back and logged, because the request is a ceiling and not a promise: the driver clamps
|
||||||
|
// it to its own calibrated power table, and our 5900 MHz is above the frequency range this
|
||||||
|
// chip is rated for (see docs/04-transmit-setup.md), so the table in use there is the one for
|
||||||
|
// channel 177. What the request alone tells you about radiated power is therefore nothing;
|
||||||
|
// this at least records what the driver admits to.
|
||||||
|
esp_err_t pw_err = esp_wifi_set_max_tx_power(80);
|
||||||
|
int8_t tx_power_q = 0;
|
||||||
|
if (pw_err != ESP_OK || esp_wifi_get_max_tx_power(&tx_power_q) != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "tx power: set/read back failed (set returned %d), level unknown", pw_err);
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "tx power: %d quarter-dBm = %d.%02d dBm (20.00 requested)",
|
||||||
|
tx_power_q, tx_power_q / 4, (tx_power_q % 4) * 25);
|
||||||
|
}
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
// Force the dual-band C5 onto its 5 GHz PHY. This MUST be called after
|
// Force the dual-band C5 onto its 5 GHz PHY. This MUST be called after
|
||||||
|
|||||||
@@ -366,8 +366,15 @@ void Station::forward_raw(const ByteBuffer& frame, int rssi) {
|
|||||||
gn_rx_t rx;
|
gn_rx_t rx;
|
||||||
if (!gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx)) return;
|
if (!gn_unwrap_its(frame.data(), static_cast<int>(frame.size()), &rx)) return;
|
||||||
constexpr std::size_t prefix = 14;
|
constexpr std::size_t prefix = 14;
|
||||||
if (rx.truncated || rx.payload_len <= 0 ||
|
const bool fits = !rx.truncated && rx.payload_len > 0 &&
|
||||||
static_cast<std::size_t>(rx.payload_len) + prefix + link::header_size > link::maximum_message) {
|
static_cast<std::size_t>(rx.payload_len) + prefix + link::header_size <= link::maximum_message;
|
||||||
|
#if CONFIG_MICROBU_BENCH_LISTEN
|
||||||
|
ESP_LOGI(TAG, "V2X_RX port %u msgid %u, %d bytes, %d dBm%s%s%s", unsigned(rx.btp_dest_port),
|
||||||
|
rx.payload_len > 1 ? unsigned(rx.payload[1]) : 0u, rx.payload_len, rssi,
|
||||||
|
rx.signed_unverified ? ", signed" : "", rx.has_geo_area ? ", GBC" : "",
|
||||||
|
fits ? "" : ", OVERSIZE (dropped)");
|
||||||
|
#endif
|
||||||
|
if (!fits) {
|
||||||
++raw_oversize_;
|
++raw_oversize_;
|
||||||
static std::int64_t last_report = 0; // one line per 10 s at most, the counter has the rest
|
static std::int64_t last_report = 0; // one line per 10 s at most, the counter has the rest
|
||||||
const auto now = esp_timer_get_time();
|
const auto now = esp_timer_get_time();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# Name, Type, SubType, Offset, Size, Flags
|
# Name, Type, SubType, Offset, Size, Flags
|
||||||
# MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, this one 16 MB).
|
# MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, ours 8 MB: the XIAO ESP32-C5; the earlier bench board had 16 MB).
|
||||||
# NVS holds the BLE bond, the credential bundle and PHY calibration; at 24 KB, with Wi-Fi settings the
|
# NVS holds the BLE bond, the credential bundle and PHY calibration; at 24 KB, with Wi-Fi settings the
|
||||||
# previous firmware had left in it, there was no room for the bond, so the board forgot the phone
|
# previous firmware had left in it, there was no room for the bond, so the board forgot the phone
|
||||||
# after every connection. The app therefore moves from 0x10000 to 0x20000 (64 KB aligned).
|
# after every connection. The app therefore moves from 0x10000 to 0x20000 (64 KB aligned).
|
||||||
|
|||||||
|
+30
-3
@@ -1142,13 +1142,13 @@ CONFIG_ESPTOOLPY_FLASHFREQ="80m"
|
|||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
|
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
|
||||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
|
||||||
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
|
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
|
||||||
# default:
|
# default:
|
||||||
CONFIG_ESPTOOLPY_FLASHSIZE="16MB"
|
CONFIG_ESPTOOLPY_FLASHSIZE="8MB"
|
||||||
# default:
|
# default:
|
||||||
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
|
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
|
||||||
# default:
|
# default:
|
||||||
@@ -1199,6 +1199,22 @@ CONFIG_MICROBU_TX_LED_GPIO=-1
|
|||||||
CONFIG_MICROBU_TX_LED_BLINK_MS=100
|
CONFIG_MICROBU_TX_LED_BLINK_MS=100
|
||||||
# default:
|
# default:
|
||||||
# CONFIG_MICROBU_LED_INVERTED_RX is not set
|
# CONFIG_MICROBU_LED_INVERTED_RX is not set
|
||||||
|
# default:
|
||||||
|
# CONFIG_MICROBU_BENCH_LISTEN is not set
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_ADC_GPIO=6
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_EN_GPIO=26
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_SCALE_PERMILLE=1000
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_WARN_MV=3500
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_SHUTDOWN_MV=3300
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_RESUME_MV=3600
|
||||||
|
# default:
|
||||||
|
CONFIG_MICROBU_BATTERY_SLEEP_S=300
|
||||||
# end of micrOBU firmware
|
# end of micrOBU firmware
|
||||||
|
|
||||||
#
|
#
|
||||||
@@ -1927,6 +1943,17 @@ CONFIG_BT_LE_DFT_CH39_TX_POWER_LEVEL_DBM_EFF=0
|
|||||||
CONFIG_EFUSE_MAX_BLK_LEN=256
|
CONFIG_EFUSE_MAX_BLK_LEN=256
|
||||||
# end of eFuse Bit Manager
|
# end of eFuse Bit Manager
|
||||||
|
|
||||||
|
#
|
||||||
|
# ADC and ADC Calibration
|
||||||
|
#
|
||||||
|
# default:
|
||||||
|
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
|
||||||
|
# default:
|
||||||
|
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
|
||||||
|
# default:
|
||||||
|
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
|
||||||
|
# end of ADC and ADC Calibration
|
||||||
|
|
||||||
#
|
#
|
||||||
# Wireless Coexistence
|
# Wireless Coexistence
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ CONFIG_COMPILER_CXX_EXCEPTIONS=y
|
|||||||
CONFIG_COMPILER_CXX_RTTI=y
|
CONFIG_COMPILER_CXX_RTTI=y
|
||||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
||||||
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
|
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
|
||||||
# MicrOBU: the production board has 16 MB of flash (esptool reports it); the partition table
|
# MicrOBU: the production board is a Seeed XIAO ESP32-C5 with 8 MB of flash (esptool flash-id reports
|
||||||
# only uses the first 4 MB.
|
# it); the partition table only uses the first 4 MB. The earlier CH343 bench board had 16 MB.
|
||||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
|
||||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||||
# Network profile: BTP + GeoNetworking, no facilities codecs (the phone builds CAM/VAM)
|
# Network profile: BTP + GeoNetworking, no facilities codecs (the phone builds CAM/VAM)
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
# asn1tools under `py -3.11` for the replay check.
|
# asn1tools under `py -3.11` for the replay check.
|
||||||
#
|
#
|
||||||
# make build and run everything: chain, replay, fuzz
|
# make build and run everything: chain, replay, fuzz
|
||||||
# make chain | replay | fuzz one of them
|
# make chain | replay | fuzz | battery one of them
|
||||||
# make fuzz FUZZ_ITER=50000000 FUZZ_SEED=7 a longer or different fuzz run
|
# make fuzz FUZZ_ITER=50000000 FUZZ_SEED=7 a longer or different fuzz run
|
||||||
# make clean remove build/
|
# make clean remove build/
|
||||||
#
|
#
|
||||||
# The firmware sources are compiled straight from ../../main, never copied.
|
# The firmware sources are compiled straight from ../../main, never copied.
|
||||||
|
|
||||||
CC = gcc
|
CC = gcc
|
||||||
|
CXX = g++
|
||||||
PYTHON = python
|
PYTHON = python
|
||||||
PYTHON_ASN1 = py -3.11
|
PYTHON_ASN1 = py -3.11
|
||||||
FW = ../../main
|
FW = ../../main
|
||||||
@@ -26,11 +27,11 @@ CFLAGS = -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW) \
|
|||||||
FW_SRCS = $(FW)/geonet.c $(FW)/dot11p.c $(FW)/gn_unwrap.c
|
FW_SRCS = $(FW)/geonet.c $(FW)/dot11p.c $(FW)/gn_unwrap.c
|
||||||
DEPS = test_util.c test_util.h $(FW_SRCS) $(wildcard $(FW)/*.h)
|
DEPS = test_util.c test_util.h $(FW_SRCS) $(wildcard $(FW)/*.h)
|
||||||
|
|
||||||
.PHONY: all check chain replay fuzz clean
|
.PHONY: all check chain replay fuzz battery clean
|
||||||
|
|
||||||
all: check
|
all: check
|
||||||
|
|
||||||
check: chain replay fuzz
|
check: chain replay fuzz battery
|
||||||
|
|
||||||
$(BUILD):
|
$(BUILD):
|
||||||
mkdir -p $@
|
mkdir -p $@
|
||||||
@@ -54,5 +55,14 @@ endif
|
|||||||
fuzz: $(BUILD)/fuzz_gn_unwrap$(EXE)
|
fuzz: $(BUILD)/fuzz_gn_unwrap$(EXE)
|
||||||
$(BUILD)/fuzz_gn_unwrap$(EXE) $(FUZZ_ITER) $(FUZZ_SEED) $(RECORDINGS)
|
$(BUILD)/fuzz_gn_unwrap$(EXE) $(FUZZ_ITER) $(FUZZ_SEED) $(RECORDINGS)
|
||||||
|
|
||||||
|
# Battery policy and the STATUS battery fields: C++17, so its own flags.
|
||||||
|
CXXFLAGS = -std=c++17 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW)
|
||||||
|
|
||||||
|
$(BUILD)/test_battery$(EXE): test_battery.cpp $(FW)/battery_monitor.hpp $(FW)/link_protocol.cpp $(FW)/link_protocol.hpp | $(BUILD)
|
||||||
|
$(CXX) $(CXXFLAGS) -o $@ test_battery.cpp $(FW)/link_protocol.cpp
|
||||||
|
|
||||||
|
battery: $(BUILD)/test_battery$(EXE)
|
||||||
|
$(BUILD)/test_battery$(EXE)
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BUILD)
|
rm -rf $(BUILD)
|
||||||
|
|||||||
@@ -22,20 +22,22 @@ import sys
|
|||||||
import asn1tools
|
import asn1tools
|
||||||
|
|
||||||
ROOT = pathlib.Path(__file__).resolve().parents[3]
|
ROOT = pathlib.Path(__file__).resolve().parents[3]
|
||||||
PORT_NAMES = {2001: "CAM", 2002: "DENM", 2004: "SPATEM"}
|
PORT_NAMES = {2001: "CAM", 2002: "DENM", 2003: "MAPEM", 2004: "SPATEM", 2018: "VAM"}
|
||||||
# main.c's RX_FRAME_MAX_LEN: the most of any frame the board hands to gn_unwrap_its. test_replay
|
# c5_radio.cpp's Raw::bytes: the most of any frame the board hands to gn_unwrap_its. test_replay
|
||||||
# cuts frames to it, so this does too.
|
# cuts frames to it, so this does too.
|
||||||
RX_FRAME_MAX_LEN = 800
|
RX_FRAME_MAX_LEN = 2346
|
||||||
|
|
||||||
|
|
||||||
def compile_specs():
|
def compile_specs():
|
||||||
a = ROOT / "asn1"
|
a = ROOT / "asn1"
|
||||||
|
spat_map = asn1tools.compile_files(
|
||||||
|
[str(a / n) for n in ("spatem_2_2_1.asn", "mapem_2_2_1.asn", "dsrc_2_2_1.asn", "cdd_2_2_1.asn")], "uper")
|
||||||
uper = {
|
uper = {
|
||||||
2001: asn1tools.compile_files([str(a / "cam_1_4_1.asn"), str(a / "cdd_1_3_1_1.asn")], "uper"),
|
2001: asn1tools.compile_files([str(a / "cam_1_4_1.asn"), str(a / "cdd_1_3_1_1.asn")], "uper"),
|
||||||
2002: asn1tools.compile_files([str(a / "denm_1_3_1.asn"), str(a / "cdd_1_3_1_1.asn")], "uper"),
|
2002: asn1tools.compile_files([str(a / "denm_1_3_1.asn"), str(a / "cdd_1_3_1_1.asn")], "uper"),
|
||||||
2004: asn1tools.compile_files(
|
2003: spat_map,
|
||||||
[str(a / n) for n in ("spatem_2_2_1.asn", "mapem_2_2_1.asn", "dsrc_2_2_1.asn", "cdd_2_2_1.asn")],
|
2004: spat_map,
|
||||||
"uper"),
|
# no VAM module in asn1/: VAMs are checked against the C parse only, not decoded
|
||||||
}
|
}
|
||||||
names = ("IEEE1609dot2BaseTypes.asn", "IEEE1609dot2.asn")
|
names = ("IEEE1609dot2BaseTypes.asn", "IEEE1609dot2.asn")
|
||||||
for d in (a, ROOT / "vanetza" / "asn1"):
|
for d in (a, ROOT / "vanetza" / "asn1"):
|
||||||
@@ -205,10 +207,10 @@ def main(argv):
|
|||||||
for key in got:
|
for key in got:
|
||||||
disagreements.append((key, "row from test_replay for a record this did not see"))
|
disagreements.append((key, "row from test_replay for a record this did not see"))
|
||||||
|
|
||||||
print("check_replay: %d records (%d cut to %d bytes), %d accepted (CAM %d, DENM %d, SPATEM %d; "
|
print("check_replay: %d records (%d cut to %d bytes), %d accepted (CAM %d, DENM %d, MAPEM %d, "
|
||||||
"%d signed, %d truncated)"
|
"SPATEM %d, VAM %d; %d signed, %d truncated)"
|
||||||
% (stats["records"], stats["capped"], RX_FRAME_MAX_LEN, stats["accepted"], stats["CAM"],
|
% (stats["records"], stats["capped"], RX_FRAME_MAX_LEN, stats["accepted"], stats["CAM"],
|
||||||
stats["DENM"], stats["SPATEM"], stats["signed"], stats["truncated"]))
|
stats["DENM"], stats["MAPEM"], stats["SPATEM"], stats["VAM"], stats["signed"], stats["truncated"]))
|
||||||
if sec_dir:
|
if sec_dir:
|
||||||
print(" envelopes decoded with asn1tools using %s" % sec_dir.relative_to(ROOT))
|
print(" envelopes decoded with asn1tools using %s" % sec_dir.relative_to(ROOT))
|
||||||
print(" C vs independent parse: %s" % ("agree on every record" if not disagreements
|
print(" C vs independent parse: %s" % ("agree on every record" if not disagreements
|
||||||
@@ -218,7 +220,10 @@ def main(argv):
|
|||||||
|
|
||||||
outcome, failures = collections.Counter(), []
|
outcome, failures = collections.Counter(), []
|
||||||
for (port, payload), key in messages.items():
|
for (port, payload), key in messages.items():
|
||||||
name, spec = PORT_NAMES[port], uper[port]
|
name, spec = PORT_NAMES[port], uper.get(port)
|
||||||
|
if spec is None:
|
||||||
|
outcome[(name, "not decoded (no module)")] += 1
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
decoded = spec.decode(name, payload)
|
decoded = spec.decode(name, payload)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
// Host tests for the battery policy (battery_monitor.hpp) and the STATUS battery extension
|
||||||
|
// (link_protocol.cpp). No ESP-IDF involved: both sources compile unmodified on the PC.
|
||||||
|
#include "battery_monitor.hpp"
|
||||||
|
#include "link_protocol.hpp"
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
|
using namespace microbu;
|
||||||
|
|
||||||
|
static int failures = 0;
|
||||||
|
#define CHECK(cond) do { if (!(cond)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); ++failures; } } while (0)
|
||||||
|
|
||||||
|
// Feeds the same sample n times, 5 s apart, starting at t_ms.
|
||||||
|
static void feed(BatteryMonitor& m, std::uint16_t mv, int n, bool usb, std::uint32_t& t_ms) {
|
||||||
|
for (int i = 0; i < n; ++i) { m.update(mv, usb, t_ms); t_ms += 5000; }
|
||||||
|
}
|
||||||
|
|
||||||
|
static void test_smoothing_and_validity() {
|
||||||
|
BatteryMonitor m;
|
||||||
|
CHECK(m.millivolts() == 0); // nothing measured yet
|
||||||
|
m.update(4100, false, 0);
|
||||||
|
CHECK(m.millivolts() == 4100); // first sample taken as is, no ramp from zero
|
||||||
|
m.update(4000, false, 5000);
|
||||||
|
CHECK(m.millivolts() == 4075); // 1/4 of the step
|
||||||
|
m.update(0, false, 10000); // failed measurement
|
||||||
|
CHECK(m.millivolts() == 0 && !m.low() && !m.critical() && !m.shutdown_due());
|
||||||
|
m.update(4100, false, 15000);
|
||||||
|
CHECK(m.millivolts() == 4100); // restarts from the new reading
|
||||||
|
m.update(5200, false, 20000); // implausible: no cell connected
|
||||||
|
CHECK(m.millivolts() == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void test_warning_hysteresis() {
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 0;
|
||||||
|
feed(m, 3700, 3, false, t);
|
||||||
|
CHECK(!m.low());
|
||||||
|
feed(m, 3450, 20, false, t);
|
||||||
|
CHECK(m.low());
|
||||||
|
feed(m, 3550, 20, false, t); // above the warning threshold but below the clear threshold
|
||||||
|
CHECK(m.low());
|
||||||
|
feed(m, 3650, 20, false, t);
|
||||||
|
CHECK(!m.low());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void test_shutdown_rules() {
|
||||||
|
{ // sustained low, no USB, after the grace period
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 120000;
|
||||||
|
feed(m, 3250, 5, false, t);
|
||||||
|
CHECK(m.critical() && !m.shutdown_due()); // five samples are not enough
|
||||||
|
feed(m, 3250, 1, false, t);
|
||||||
|
CHECK(m.shutdown_due());
|
||||||
|
}
|
||||||
|
{ // a phone on USB powers the board: never shut down, and the count restarts
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 120000;
|
||||||
|
feed(m, 3250, 5, false, t);
|
||||||
|
feed(m, 3250, 1, true, t);
|
||||||
|
CHECK(!m.shutdown_due());
|
||||||
|
feed(m, 3250, 5, false, t);
|
||||||
|
CHECK(!m.shutdown_due());
|
||||||
|
feed(m, 3250, 1, false, t);
|
||||||
|
CHECK(m.shutdown_due());
|
||||||
|
}
|
||||||
|
{ // not within the first minute after boot
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 0;
|
||||||
|
feed(m, 3250, 11, false, t); // 0..50 s
|
||||||
|
CHECK(!m.shutdown_due());
|
||||||
|
feed(m, 3250, 7, false, t); // 55..85 s: six of them at or past the 60 s grace period
|
||||||
|
CHECK(m.shutdown_due());
|
||||||
|
}
|
||||||
|
{ // a dip that recovers (TX sag) does not count
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 120000;
|
||||||
|
feed(m, 3250, 4, false, t);
|
||||||
|
feed(m, 3900, 10, false, t);
|
||||||
|
feed(m, 3250, 4, false, t);
|
||||||
|
CHECK(!m.shutdown_due());
|
||||||
|
}
|
||||||
|
{ // a normal cell never trips it
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 120000;
|
||||||
|
feed(m, 3800, 100, false, t);
|
||||||
|
CHECK(!m.shutdown_due() && !m.low() && !m.critical());
|
||||||
|
}
|
||||||
|
{ // no cell / no sensor: no shutdown
|
||||||
|
BatteryMonitor m;
|
||||||
|
std::uint32_t t = 120000;
|
||||||
|
feed(m, 0, 100, false, t);
|
||||||
|
CHECK(!m.shutdown_due());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void test_resume() {
|
||||||
|
BatteryMonitor m;
|
||||||
|
CHECK(!m.resume_ok(3300));
|
||||||
|
CHECK(!m.resume_ok(3599));
|
||||||
|
CHECK(m.resume_ok(3600));
|
||||||
|
CHECK(m.resume_ok(4100));
|
||||||
|
CHECK(m.resume_ok(0)); // cannot judge: run
|
||||||
|
}
|
||||||
|
|
||||||
|
static link::Status sample_status() {
|
||||||
|
link::Status s;
|
||||||
|
s.uptime_ms = 123456; s.configured = 1; s.tickets = 7; s.signed_messages = 42; s.poti_updates = 9;
|
||||||
|
s.its_time_ms = 0x0102030405060708ULL;
|
||||||
|
s.battery_mv = 3871; s.battery_flags = link::battery_flag_low;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void test_status_protocol() {
|
||||||
|
const auto body = link::encode(sample_status());
|
||||||
|
CHECK(body.size() == link::status_size_battery);
|
||||||
|
CHECK(body.size() == 106);
|
||||||
|
link::Status d;
|
||||||
|
CHECK(link::decode(body, d));
|
||||||
|
CHECK(d.battery_mv == 3871 && d.battery_flags == link::battery_flag_low);
|
||||||
|
CHECK(d.uptime_ms == 123456 && d.tickets == 7 && d.its_time_ms == 0x0102030405060708ULL);
|
||||||
|
|
||||||
|
// the 103-octet layout of the colleague's station (and of this firmware before the battery)
|
||||||
|
link::Bytes legacy(body.begin(), body.begin() + link::status_size_base);
|
||||||
|
link::Status l;
|
||||||
|
l.battery_mv = 999; l.battery_flags = 0xFF;
|
||||||
|
CHECK(link::decode(legacy, l));
|
||||||
|
CHECK(l.battery_mv == 0 && l.battery_flags == 0);
|
||||||
|
CHECK(l.uptime_ms == 123456 && l.its_time_ms == 0x0102030405060708ULL);
|
||||||
|
|
||||||
|
// trailing octets of a later extension are ignored; half a field is malformed
|
||||||
|
link::Bytes longer = body;
|
||||||
|
longer.push_back(0xEE); longer.push_back(0xEE);
|
||||||
|
link::Status x;
|
||||||
|
CHECK(link::decode(longer, x) && x.battery_mv == 3871);
|
||||||
|
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 104), x));
|
||||||
|
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 105), x));
|
||||||
|
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 102), x));
|
||||||
|
CHECK(!link::decode(link::Bytes(), x));
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
test_smoothing_and_validity();
|
||||||
|
test_warning_hysteresis();
|
||||||
|
test_shutdown_rules();
|
||||||
|
test_resume();
|
||||||
|
test_status_protocol();
|
||||||
|
if (failures) { std::printf("%d check(s) failed\n", failures); return EXIT_FAILURE; }
|
||||||
|
std::printf("battery: all checks passed\n");
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
||||||
@@ -374,7 +374,9 @@ static uint8_t *put32(uint8_t *p, uint32_t v)
|
|||||||
return put16(p, (uint16_t)v);
|
return put16(p, (uint16_t)v);
|
||||||
}
|
}
|
||||||
|
|
||||||
static int build_gbc(uint8_t subtype, int32_t area_lat, int32_t area_lon, uint16_t dist_a, uint8_t *f)
|
// Any BTP-B message by GeoBroadcast, the way the bench RSU sends SPATEM and MAPEM too.
|
||||||
|
static int build_gbc_msg(uint8_t subtype, int32_t area_lat, int32_t area_lon, uint16_t dist_a,
|
||||||
|
uint16_t port, const uint8_t *payload, int payload_len, uint8_t *f)
|
||||||
{
|
{
|
||||||
uint8_t *p = f;
|
uint8_t *p = f;
|
||||||
// 802.11 QoS Data: FC, duration, addr1..3, sequence control, QoS control
|
// 802.11 QoS Data: FC, duration, addr1..3, sequence control, QoS control
|
||||||
@@ -392,7 +394,7 @@ static int build_gbc(uint8_t subtype, int32_t area_lat, int32_t area_lon, uint16
|
|||||||
// Common: NH BTP-B, HT 4 (GBC) / subtype = area shape, TC 1, flags 0 (stationary), PL, MHL, reserved
|
// Common: NH BTP-B, HT 4 (GBC) / subtype = area shape, TC 1, flags 0 (stationary), PL, MHL, reserved
|
||||||
const uint8_t common[4] = {0x20, (uint8_t)(0x40 | subtype), 0x01, 0x00};
|
const uint8_t common[4] = {0x20, (uint8_t)(0x40 | subtype), 0x01, 0x00};
|
||||||
p = put(p, common, 4);
|
p = put(p, common, 4);
|
||||||
p = put16(p, (uint16_t)(BTP_B + DENM_STUB_LEN));
|
p = put16(p, (uint16_t)(BTP_B + payload_len));
|
||||||
*p++ = 10;
|
*p++ = 10;
|
||||||
*p++ = 0;
|
*p++ = 0;
|
||||||
// GBC extended header: SN, reserved, SO PV (GN_ADDR with station type 15 = RSU, MID, TST, lat,
|
// GBC extended header: SN, reserved, SO PV (GN_ADDR with station type 15 = RSU, MID, TST, lat,
|
||||||
@@ -412,13 +414,18 @@ static int build_gbc(uint8_t subtype, int32_t area_lat, int32_t area_lon, uint16
|
|||||||
p = put16(p, subtype ? 40 : 0);
|
p = put16(p, subtype ? 40 : 0);
|
||||||
p = put16(p, subtype ? 900 : 0);
|
p = put16(p, subtype ? 900 : 0);
|
||||||
p = put16(p, 0);
|
p = put16(p, 0);
|
||||||
// BTP-B: DENM
|
// BTP-B
|
||||||
p = put16(p, 2002);
|
p = put16(p, port);
|
||||||
p = put16(p, 0);
|
p = put16(p, 0);
|
||||||
p = put(p, k_denm_stub, DENM_STUB_LEN);
|
p = put(p, payload, payload_len);
|
||||||
return (int)(p - f);
|
return (int)(p - f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int build_gbc(uint8_t subtype, int32_t area_lat, int32_t area_lon, uint16_t dist_a, uint8_t *f)
|
||||||
|
{
|
||||||
|
return build_gbc_msg(subtype, area_lat, area_lon, dist_a, 2002, k_denm_stub, DENM_STUB_LEN, f);
|
||||||
|
}
|
||||||
|
|
||||||
static void test_gbc_rx(void)
|
static void test_gbc_rx(void)
|
||||||
{
|
{
|
||||||
static const struct { uint8_t subtype; int32_t lat, lon; uint16_t dist_a; } areas[] = {
|
static const struct { uint8_t subtype; int32_t lat, lon; uint16_t dist_a; } areas[] = {
|
||||||
@@ -481,10 +488,12 @@ static void test_rejections(void)
|
|||||||
{"Beacon (HeaderType 1)", 37, 0x10, false, 0},
|
{"Beacon (HeaderType 1)", 37, 0x10, false, 0},
|
||||||
{"GeoUnicast (HeaderType 2)", 37, 0x20, false, 0},
|
{"GeoUnicast (HeaderType 2)", 37, 0x20, false, 0},
|
||||||
{"multi-hop TSB (HeaderType 5, subtype 1)", 37, 0x51, false, 0},
|
{"multi-hop TSB (HeaderType 5, subtype 1)", 37, 0x51, false, 0},
|
||||||
{"BTP port 2003 (MAPEM, not accepted yet)", 73, 0xD3, false, 0},
|
|
||||||
{"BTP port 2018 (VAM, not accepted yet)", 73, 0xE2, false, 0},
|
|
||||||
{"BTP port 2002 (DENM)", 73, 0xD2, true, 2002},
|
{"BTP port 2002 (DENM)", 73, 0xD2, true, 2002},
|
||||||
|
{"BTP port 2003 (MAPEM)", 73, 0xD3, true, 2003},
|
||||||
{"BTP port 2004 (SPATEM)", 73, 0xD4, true, 2004},
|
{"BTP port 2004 (SPATEM)", 73, 0xD4, true, 2004},
|
||||||
|
{"BTP port 2018 (VAM)", 73, 0xE2, true, 2018},
|
||||||
|
{"BTP port 2005 (IVIM, not accepted)", 73, 0xD5, false, 0},
|
||||||
|
{"BTP port 2006 (SREM, not accepted)", 73, 0xD6, false, 0},
|
||||||
};
|
};
|
||||||
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
|
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
|
||||||
tu_set_context("mutation: %s", cases[i].what);
|
tu_set_context("mutation: %s", cases[i].what);
|
||||||
@@ -583,16 +592,14 @@ static int put_coer_length(int len, uint8_t *out)
|
|||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A secured CAM frame shaped like the recorded ones: our own SHB packet with the Basic Header's
|
// Secures an unsecured frame `plain` shaped like the recorded signed ones: the Basic Header (at
|
||||||
// NextHeader set to 2 and everything after the Basic Header wrapped as `prefix` + COER length +
|
// `basic`) gets NextHeader 2 and everything after it is wrapped as `prefix` + COER length + inner
|
||||||
// inner packet, then the signature stand-in. Sets where the ITS payload starts and ends.
|
// packet, then the signature stand-in. `ext_len` is the inner packet's extended-header length.
|
||||||
static int build_secured(const uint8_t *prefix, int prefix_len, const uint8_t *payload,
|
// Sets where the ITS payload starts and ends.
|
||||||
int payload_len, uint8_t *f, int *payload_start, int *payload_end)
|
static int secure_frame(const uint8_t *plain, int plain_len, int basic, int ext_len,
|
||||||
|
const uint8_t *prefix, int prefix_len, uint8_t *f,
|
||||||
|
int *payload_start, int *payload_end)
|
||||||
{
|
{
|
||||||
const gn_lpv_t lpv = test_lpv();
|
|
||||||
uint8_t plain[FRAME_BUF_LEN];
|
|
||||||
const int plain_len = build(payload, payload_len, &lpv, 2001, false, plain, sizeof plain);
|
|
||||||
const int basic = MAC_HDR + LLC_SNAP;
|
|
||||||
const int inner = basic + GN_BASIC; // the Common Header onward
|
const int inner = basic + GN_BASIC; // the Common Header onward
|
||||||
const int inner_len = plain_len - inner;
|
const int inner_len = plain_len - inner;
|
||||||
|
|
||||||
@@ -603,7 +610,7 @@ static int build_secured(const uint8_t *prefix, int prefix_len, const uint8_t *p
|
|||||||
n += prefix_len;
|
n += prefix_len;
|
||||||
n += put_coer_length(inner_len, f + n);
|
n += put_coer_length(inner_len, f + n);
|
||||||
memcpy(f + n, plain + inner, (size_t)inner_len);
|
memcpy(f + n, plain + inner, (size_t)inner_len);
|
||||||
*payload_start = n + GN_COMMON + SHB_EXT + BTP_B;
|
*payload_start = n + GN_COMMON + ext_len + BTP_B;
|
||||||
n += inner_len;
|
n += inner_len;
|
||||||
*payload_end = n;
|
*payload_end = n;
|
||||||
for (int i = 0; i < SIG_STUB_LEN; i++) {
|
for (int i = 0; i < SIG_STUB_LEN; i++) {
|
||||||
@@ -612,6 +619,17 @@ static int build_secured(const uint8_t *prefix, int prefix_len, const uint8_t *p
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A secured CAM: our own SHB packet, secured.
|
||||||
|
static int build_secured(const uint8_t *prefix, int prefix_len, const uint8_t *payload,
|
||||||
|
int payload_len, uint8_t *f, int *payload_start, int *payload_end)
|
||||||
|
{
|
||||||
|
const gn_lpv_t lpv = test_lpv();
|
||||||
|
uint8_t plain[FRAME_BUF_LEN];
|
||||||
|
const int plain_len = build(payload, payload_len, &lpv, 2001, false, plain, sizeof plain);
|
||||||
|
return secure_frame(plain, plain_len, MAC_HDR + LLC_SNAP, SHB_EXT, prefix, prefix_len, f,
|
||||||
|
payload_start, payload_end);
|
||||||
|
}
|
||||||
|
|
||||||
static const uint8_t k_signed_prefix[] = {0x03, 0x81, 0x00, 0x40, 0x03, 0x80};
|
static const uint8_t k_signed_prefix[] = {0x03, 0x81, 0x00, 0x40, 0x03, 0x80};
|
||||||
static const uint8_t k_unsecured_prefix[] = {0x03, 0x80};
|
static const uint8_t k_unsecured_prefix[] = {0x03, 0x80};
|
||||||
|
|
||||||
@@ -690,6 +708,51 @@ static void test_secured(void)
|
|||||||
CHECK(!gn_unwrap_its(tu_guarded(f, len), len, &rx), "payload overrunning its envelope: accepted");
|
CHECK(!gn_unwrap_its(tu_guarded(f, len), len, &rx), "payload overrunning its envelope: accepted");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Signed SPATEM and MAPEM by GeoBroadcast. No recording holds one yet (the bench RSU sent all three
|
||||||
|
// of its messages unsigned on 2026-10-28), so these are the RSU's recorded GBC frames with the
|
||||||
|
// signed envelope of the recorded CAMs and DENMs around them. 494 bytes is the largest message a
|
||||||
|
// link message carries (Station::forward_raw); 1243 is the largest SPATEM of the 2026-03-18 drive,
|
||||||
|
// which gn_unwrap_its must still unwrap whole even though the station then drops it as oversize.
|
||||||
|
static void test_secured_gbc(void)
|
||||||
|
{
|
||||||
|
static const struct { const char *what; uint16_t port; uint8_t message_id; int payload_len; } cases[] = {
|
||||||
|
{"signed GBC SPATEM, bench size", 2004, 4, 58},
|
||||||
|
{"signed GBC MAPEM, bench size", 2003, 5, 295},
|
||||||
|
{"signed GBC MAPEM, largest that fits a link message", 2003, 5, 494},
|
||||||
|
{"signed GBC SPATEM, largest seen on the road", 2004, 4, 1243},
|
||||||
|
};
|
||||||
|
static uint8_t payload[1243], plain[1400], f[1400];
|
||||||
|
for (size_t c = 0; c < sizeof cases / sizeof cases[0]; c++) {
|
||||||
|
tu_set_context("%s", cases[c].what);
|
||||||
|
const int n = cases[c].payload_len;
|
||||||
|
payload[0] = 0x02; // ItsPduHeader: protocolVersion 2, messageID, stationID
|
||||||
|
payload[1] = cases[c].message_id;
|
||||||
|
for (int i = 2; i < n; i++) {
|
||||||
|
payload[i] = (uint8_t)(i * 7 + cases[c].port);
|
||||||
|
}
|
||||||
|
const int plain_len = build_gbc_msg(0, 535540000, 100220000, 400, cases[c].port, payload, n, plain);
|
||||||
|
int start, end;
|
||||||
|
const int len = secure_frame(plain, plain_len, MAC_HDR + QOS_CTRL + LLC_SNAP, GBC_EXT,
|
||||||
|
k_signed_prefix, (int)sizeof k_signed_prefix, f, &start, &end);
|
||||||
|
gn_rx_t rx;
|
||||||
|
const uint8_t *g = tu_guarded(f, len);
|
||||||
|
const bool ok = gn_unwrap_its(g, len, &rx);
|
||||||
|
CHECK(ok, "%s: rejected", cases[c].what);
|
||||||
|
if (ok) {
|
||||||
|
CHECK(rx.btp_dest_port == cases[c].port && rx.signed_unverified && !rx.truncated &&
|
||||||
|
rx.has_geo_area && rx.geo_area_distance_a_m == 400,
|
||||||
|
"%s: port %d signed %d truncated %d area %d/%d", cases[c].what, rx.btp_dest_port,
|
||||||
|
rx.signed_unverified, rx.truncated, rx.has_geo_area, rx.geo_area_distance_a_m);
|
||||||
|
CHECK(rx.payload == g + start && rx.payload_len == n &&
|
||||||
|
memcmp(rx.payload, payload, (size_t)n) == 0,
|
||||||
|
"%s: payload offset %d length %d, expected %d / %d", cases[c].what,
|
||||||
|
(int)(rx.payload - g), rx.payload_len, start, n);
|
||||||
|
}
|
||||||
|
tu_pcap_add(f, len);
|
||||||
|
sweep(cases[c].what, f, len, start, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static void test_truncation(void)
|
static void test_truncation(void)
|
||||||
{
|
{
|
||||||
const gn_lpv_t lpv = test_lpv();
|
const gn_lpv_t lpv = test_lpv();
|
||||||
@@ -722,6 +785,7 @@ int main(int argc, char **argv)
|
|||||||
test_payload_length();
|
test_payload_length();
|
||||||
test_trailer();
|
test_trailer();
|
||||||
test_secured();
|
test_secured();
|
||||||
|
test_secured_gbc();
|
||||||
test_truncation();
|
test_truncation();
|
||||||
|
|
||||||
tu_pcap_close();
|
tu_pcap_close();
|
||||||
|
|||||||
@@ -17,14 +17,15 @@
|
|||||||
#include "gn_unwrap.h"
|
#include "gn_unwrap.h"
|
||||||
#include "test_util.h"
|
#include "test_util.h"
|
||||||
|
|
||||||
// main.c's RX_FRAME_MAX_LEN: the promiscuous callback copies at most this many bytes of a frame,
|
// c5_radio.cpp's Raw::bytes: the promiscuous callback copies at most this many bytes of a frame,
|
||||||
// so it is the most gn_unwrap_its ever sees on the board. Keep in step with main.c.
|
// so it is the most gn_unwrap_its ever sees on the board. Keep in step with c5_radio.cpp. (The old
|
||||||
#define RX_FRAME_MAX_LEN 800
|
// C firmware's main.c cut frames at 800 bytes.)
|
||||||
|
#define RX_FRAME_MAX_LEN 2346
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
FILE *out;
|
FILE *out;
|
||||||
const char *path;
|
const char *path;
|
||||||
long records, capped, accepted, cam, denm, spatem, signed_frames, truncated, bad;
|
long records, capped, accepted, cam, denm, mapem, spatem, vam, signed_frames, truncated, bad;
|
||||||
} replay_t;
|
} replay_t;
|
||||||
|
|
||||||
static void on_frame(const uint8_t *frame, int len, int index, void *ctx)
|
static void on_frame(const uint8_t *frame, int len, int index, void *ctx)
|
||||||
@@ -57,7 +58,9 @@ static void on_frame(const uint8_t *frame, int len, int index, void *ctx)
|
|||||||
r->accepted++;
|
r->accepted++;
|
||||||
r->cam += rx.btp_dest_port == 2001;
|
r->cam += rx.btp_dest_port == 2001;
|
||||||
r->denm += rx.btp_dest_port == 2002;
|
r->denm += rx.btp_dest_port == 2002;
|
||||||
|
r->mapem += rx.btp_dest_port == 2003;
|
||||||
r->spatem += rx.btp_dest_port == 2004;
|
r->spatem += rx.btp_dest_port == 2004;
|
||||||
|
r->vam += rx.btp_dest_port == 2018;
|
||||||
r->signed_frames += rx.signed_unverified;
|
r->signed_frames += rx.signed_unverified;
|
||||||
r->truncated += rx.truncated;
|
r->truncated += rx.truncated;
|
||||||
}
|
}
|
||||||
@@ -91,9 +94,9 @@ int main(int argc, char **argv)
|
|||||||
}
|
}
|
||||||
fclose(r.out);
|
fclose(r.out);
|
||||||
|
|
||||||
printf("test_replay: %ld records (%ld cut to %d bytes as main.c does), %ld accepted (CAM %ld, "
|
printf("test_replay: %ld records (%ld cut to %d bytes as c5_radio.cpp does), %ld accepted (CAM %ld, "
|
||||||
"DENM %ld, SPATEM %ld; %ld signed, %ld truncated), %ld bad\n",
|
"DENM %ld, MAPEM %ld, SPATEM %ld, VAM %ld; %ld signed, %ld truncated), %ld bad\n",
|
||||||
r.records, r.capped, RX_FRAME_MAX_LEN, r.accepted, r.cam, r.denm, r.spatem,
|
r.records, r.capped, RX_FRAME_MAX_LEN, r.accepted, r.cam, r.denm, r.mapem, r.spatem, r.vam,
|
||||||
r.signed_frames, r.truncated, r.bad);
|
r.signed_frames, r.truncated, r.bad);
|
||||||
return (r.bad || unreadable) ? 1 : 0;
|
return (r.bad || unreadable) ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Tally what an obu-firmware BENCH LISTEN build (CONFIG_MICROBU_BENCH_LISTEN) hears, from its UART0 console.
|
||||||
|
|
||||||
|
py -3.11 tools/bench_listen_watch.py COM3 [seconds]
|
||||||
|
|
||||||
|
The bench build logs one line per message its raw RX path (gn_unwrap.c) unwraps, e.g.
|
||||||
|
I (12345) station: V2X_RX port 2003 msgid 5, 295 bytes, -61 dBm, GBC
|
||||||
|
This counts them per BTP port: how many, sizes, RSSI range, how many signed, how many too big for a
|
||||||
|
link message (dropped). Opening the port resets the board (DTR/RTS), so the first lines are the boot.
|
||||||
|
Needs pyserial (the ESP-IDF python env has it).
|
||||||
|
"""
|
||||||
|
import collections
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import serial
|
||||||
|
|
||||||
|
LINE = re.compile(r"V2X_RX port (\d+) msgid (\d+), (\d+) bytes, (-?\d+) dBm(.*)")
|
||||||
|
NAMES = {2001: 'CAM', 2002: 'DENM', 2003: 'MAPEM', 2004: 'SPATEM', 2018: 'VAM'}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
port = sys.argv[1]
|
||||||
|
seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 60
|
||||||
|
stats = collections.defaultdict(lambda: {'n': 0, 'sizes': set(), 'msgids': set(), 'rssi': [],
|
||||||
|
'signed': 0, 'gbc': 0, 'oversize': 0})
|
||||||
|
with serial.Serial(port, 115200, timeout=0.5) as s:
|
||||||
|
end = time.monotonic() + seconds
|
||||||
|
buffer = b''
|
||||||
|
while time.monotonic() < end:
|
||||||
|
buffer += s.read(4096)
|
||||||
|
*lines, buffer = buffer.split(b'\n')
|
||||||
|
for raw in lines:
|
||||||
|
text = raw.decode(errors='replace').rstrip()
|
||||||
|
m = LINE.search(text)
|
||||||
|
if not m:
|
||||||
|
if 'BENCH' in text or 'radio' in text or ' E (' in text or text.startswith('E ('):
|
||||||
|
print(text)
|
||||||
|
continue
|
||||||
|
p, msgid, length, rssi, rest = int(m[1]), int(m[2]), int(m[3]), int(m[4]), m[5]
|
||||||
|
st = stats[p]
|
||||||
|
st['n'] += 1
|
||||||
|
st['sizes'].add(length)
|
||||||
|
st['msgids'].add(msgid)
|
||||||
|
st['rssi'].append(rssi)
|
||||||
|
st['signed'] += 'signed' in rest
|
||||||
|
st['gbc'] += 'GBC' in rest
|
||||||
|
st['oversize'] += 'OVERSIZE' in rest
|
||||||
|
print(f"\n{seconds:.0f} s on {port}:")
|
||||||
|
print(f"{'port':>5} {'type':7} {'count':>6} {'msgid':>6} {'bytes':>12} {'dBm':>10} {'signed':>7} {'GBC':>5} {'oversize':>9}")
|
||||||
|
for p in sorted(stats):
|
||||||
|
st = stats[p]
|
||||||
|
sizes = f"{min(st['sizes'])}-{max(st['sizes'])}" if len(st['sizes']) > 1 else str(min(st['sizes']))
|
||||||
|
msgids = ','.join(map(str, sorted(st['msgids'])))
|
||||||
|
rssi = f"{min(st['rssi'])}..{max(st['rssi'])}"
|
||||||
|
print(f"{p:>5} {NAMES.get(p, '?'):7} {st['n']:>6} {msgids:>6} {sizes:>12} {rssi:>10} {st['signed']:>7} {st['gbc']:>5} {st['oversize']:>9}")
|
||||||
|
if not stats:
|
||||||
|
print(" nothing: is it the bench build (BENCH LISTEN line at boot), and is anything on air?")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Builds the MAPEM test corpus for MapemUperCodecTest: every distinct MAPEM on record, with every
|
||||||
|
field decoded by asn1tools (the ETSI modules in asn1/), as canonical text the Kotlin test re-creates
|
||||||
|
from MapemUperCodec's output and compares line by line.
|
||||||
|
|
||||||
|
py -3.11 tools/mapem_corpus.py
|
||||||
|
|
||||||
|
Sources: the 2026-03-18 drive (its-g5-receiver-firmware/recordings/its_messages_*.db, msg_type 5, the
|
||||||
|
UPER is field 3 of the CiT One protobuf blob) and any MAPEM in obu-firmware's replay TSV (the bench
|
||||||
|
RSU, captured by the ESP32-C5; run `make replay` in obu-firmware/test/host first).
|
||||||
|
Writes app/src/test/resources/mapem/corpus.txt, and spat_samples.txt beside it: for every intersection
|
||||||
|
in the corpus, one recorded SPATEM of the same intersection (`<key> <revision> <hex>`), for
|
||||||
|
TrafficLightsTest.
|
||||||
|
"""
|
||||||
|
import collections
|
||||||
|
import glob
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import asn1tools
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ASN = ROOT / 'asn1'
|
||||||
|
OUT = ROOT / 'app/src/test/resources/mapem/corpus.txt'
|
||||||
|
SPAT_OUT = OUT.parent / 'spat_samples.txt'
|
||||||
|
LANE_TYPES = ['vehicle', 'crosswalk', 'bikeLane', 'sidewalk', 'median', 'striping', 'trackedVehicle', 'parking']
|
||||||
|
|
||||||
|
|
||||||
|
def enum_roots():
|
||||||
|
src = ''.join((ASN / n).read_text(encoding='utf-8', errors='replace') for n in ('dsrc_2_2_1.asn', 'cdd_2_2_1.asn'))
|
||||||
|
src = re.sub(r'/\*.*?\*/', '', src, flags=re.S)
|
||||||
|
src = re.sub(r'--.*', '', src)
|
||||||
|
roots = {}
|
||||||
|
for name in ('NodeAttributeXY', 'SegmentAttributeXY', 'SpeedLimitType'):
|
||||||
|
body = re.search(r'\b' + name + r'\s*::=\s*ENUMERATED\s*\{(.*?)\}', src, re.S).group(1).split('...')[0]
|
||||||
|
roots[name] = [x.strip() for x in body.split(',') if x.strip()]
|
||||||
|
return roots
|
||||||
|
|
||||||
|
|
||||||
|
def varint(b, i):
|
||||||
|
v = s = 0
|
||||||
|
while True:
|
||||||
|
x = b[i]
|
||||||
|
i += 1
|
||||||
|
v |= (x & 0x7F) << s
|
||||||
|
s += 7
|
||||||
|
if x < 0x80:
|
||||||
|
return v, i
|
||||||
|
|
||||||
|
|
||||||
|
def protobuf_field3(b):
|
||||||
|
i = 0
|
||||||
|
while i < len(b):
|
||||||
|
tag, i = varint(b, i)
|
||||||
|
field, wire = tag >> 3, tag & 7
|
||||||
|
if wire == 0:
|
||||||
|
_, i = varint(b, i)
|
||||||
|
elif wire == 2:
|
||||||
|
n, i = varint(b, i)
|
||||||
|
if field == 3:
|
||||||
|
return b[i:i + n]
|
||||||
|
i += n
|
||||||
|
elif wire == 5:
|
||||||
|
i += 4
|
||||||
|
elif wire == 1:
|
||||||
|
i += 8
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def bits(value):
|
||||||
|
data, n = value
|
||||||
|
return int.from_bytes(data, 'big') >> (len(data) * 8 - n) if n else 0
|
||||||
|
|
||||||
|
|
||||||
|
def dump(d, roots):
|
||||||
|
"""Canonical text; MapemUperCodecTest.dump() must produce the same."""
|
||||||
|
out = [f"station={d['header']['stationId']} rev={d['map']['msgIssueRevision']}"]
|
||||||
|
for i in d['map']['intersections']:
|
||||||
|
speeds = ','.join(f"{roots['SpeedLimitType'].index(s['type'])}:{s['speed']}" for s in i.get('speedLimits', []))
|
||||||
|
ref = i['refPoint']
|
||||||
|
out.append(f"I key={i['id'].get('region', -1)}/{i['id']['id']} rev={i['revision']} name={i.get('name')} "
|
||||||
|
f"ref={ref['lat']},{ref['long']} elev={ref.get('elevation')} width={i.get('laneWidth')} speeds={speeds}")
|
||||||
|
for lane in i['laneSet']:
|
||||||
|
a = lane['laneAttributes']
|
||||||
|
kind, attr = a['laneType']
|
||||||
|
man = bits(lane['maneuvers']) if 'maneuvers' in lane else None
|
||||||
|
out.append(f"L id={lane['laneID']} name={lane.get('name')} in={lane.get('ingressApproach')} "
|
||||||
|
f"eg={lane.get('egressApproach')} dir={bits(a['directionalUse'])} share={bits(a['sharedWith'])} "
|
||||||
|
f"type={LANE_TYPES.index(kind)} attr={bits(attr)} man={man}")
|
||||||
|
choice, nodes = lane['nodeList']
|
||||||
|
assert choice == 'nodes'
|
||||||
|
for node in nodes:
|
||||||
|
kind, v = node['delta']
|
||||||
|
pos = f"ll={v['lat']},{v['lon']}" if kind == 'node-LatLon' else f"xy={v['x']},{v['y']}"
|
||||||
|
at = node.get('attributes', {})
|
||||||
|
local = ','.join(str(roots['NodeAttributeXY'].index(x)) for x in at.get('localNode', []))
|
||||||
|
dis = ','.join(str(roots['SegmentAttributeXY'].index(x)) for x in at.get('disabled', []))
|
||||||
|
en = ','.join(str(roots['SegmentAttributeXY'].index(x)) for x in at.get('enabled', []))
|
||||||
|
out.append(f"N {pos} local={local} dis={dis} en={en} dw={at.get('dWidth')} de={at.get('dElevation')}")
|
||||||
|
for c in lane.get('connectsTo', []):
|
||||||
|
cl = c['connectingLane']
|
||||||
|
man = bits(cl['maneuver']) if 'maneuver' in cl else None
|
||||||
|
r = c.get('remoteIntersection')
|
||||||
|
remote = f"{r.get('region', -1)}/{r['id']}" if r else None
|
||||||
|
out.append(f"C to={cl['lane']} man={man} remote={remote} sg={c.get('signalGroup')} "
|
||||||
|
f"uc={c.get('userClass')} cid={c.get('connectionID')}")
|
||||||
|
if 'overlays' in lane:
|
||||||
|
out.append('O ' + ','.join(map(str, lane['overlays'])))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
spec = asn1tools.compile_files([str(ASN / n) for n in
|
||||||
|
('spatem_2_2_1.asn', 'mapem_2_2_1.asn', 'dsrc_2_2_1.asn', 'cdd_2_2_1.asn')], 'uper')
|
||||||
|
roots = enum_roots()
|
||||||
|
seen = collections.OrderedDict()
|
||||||
|
for path in sorted(glob.glob(str(ROOT / 'its-g5-receiver-firmware/recordings/its_messages_*.db'))):
|
||||||
|
db = sqlite3.connect(f'file:{path}?mode=ro', uri=True)
|
||||||
|
for (blob,) in db.execute('select asn1_message from messages where msg_type = 5'):
|
||||||
|
uper = protobuf_field3(bytes(blob))
|
||||||
|
if uper:
|
||||||
|
seen[uper] = seen.get(uper, 0) + 1
|
||||||
|
tsv = ROOT / 'obu-firmware/test/host/build/replay.tsv'
|
||||||
|
if tsv.exists():
|
||||||
|
for line in tsv.read_text().splitlines():
|
||||||
|
col = line.split('\t')
|
||||||
|
if len(col) > 10 and col[3] == '2003':
|
||||||
|
uper = bytes.fromhex(col[10])
|
||||||
|
seen[uper] = seen.get(uper, 0) + 1
|
||||||
|
lines = [f'# {len(seen)} distinct MAPEMs ({sum(seen.values())} received), fields by asn1tools. '
|
||||||
|
'Generated by tools/mapem_corpus.py; do not edit.']
|
||||||
|
for uper in seen:
|
||||||
|
lines.append('#hex ' + uper.hex())
|
||||||
|
lines.extend(dump(spec.decode('MAPEM', uper), roots))
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
OUT.write_text('\n'.join(lines) + '\n', encoding='ascii')
|
||||||
|
print(f'{OUT.relative_to(ROOT)}: {len(seen)} MAPEMs, {len(lines)} lines')
|
||||||
|
|
||||||
|
# One SPATEM per (intersection, MAP revision) in the corpus, with at least 2 movements.
|
||||||
|
wanted = set()
|
||||||
|
for uper in seen:
|
||||||
|
for i in spec.decode('MAPEM', uper)['map']['intersections']:
|
||||||
|
wanted.add((f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision']))
|
||||||
|
samples = {}
|
||||||
|
|
||||||
|
def offer(uper):
|
||||||
|
try:
|
||||||
|
d = spec.decode('SPATEM', uper)
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
for i in d['spat']['intersections']:
|
||||||
|
k = (f"{i['id'].get('region', -1)}/{i['id']['id']}", i['revision'])
|
||||||
|
if k in wanted and k not in samples and len(i['states']) >= 2:
|
||||||
|
samples[k] = uper
|
||||||
|
|
||||||
|
for path in sorted(glob.glob(str(ROOT / 'its-g5-receiver-firmware/recordings/its_messages_*.db'))):
|
||||||
|
db = sqlite3.connect(f'file:{path}?mode=ro', uri=True)
|
||||||
|
for (blob,) in db.execute('select asn1_message from messages where msg_type = 4'):
|
||||||
|
if len(samples) == len(wanted):
|
||||||
|
break
|
||||||
|
uper = protobuf_field3(bytes(blob))
|
||||||
|
if uper:
|
||||||
|
offer(uper)
|
||||||
|
if tsv.exists():
|
||||||
|
for line in tsv.read_text().splitlines():
|
||||||
|
col = line.split('\t')
|
||||||
|
if len(col) > 10 and col[3] == '2004':
|
||||||
|
offer(bytes.fromhex(col[10]))
|
||||||
|
SPAT_OUT.write_text(''.join(f'{k} {r} {u.hex()}\n' for (k, r), u in sorted(samples.items())), encoding='ascii')
|
||||||
|
print(f'{SPAT_OUT.relative_to(ROOT)}: {len(samples)} of {len(wanted)} intersection revisions have a SPATEM')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Print the micrOBU's STATUS (incl. the battery fields) from its native USB Serial/JTAG port.
|
||||||
|
|
||||||
|
py -3.11 tools/station_status_watch.py COM10 [seconds]
|
||||||
|
|
||||||
|
Speaks the station-link framing of obu-firmware (0xAA55, type, u16 length, payload, CRC-16/CCITT-FALSE
|
||||||
|
over type..payload, little endian; frame type 0x10 = LINK) and asks for STATUS once a second. The
|
||||||
|
board also broadcasts STATUS itself every second. Opening the port resets the board (DTR/RTS), so
|
||||||
|
the first frames come after the boot. Needs pyserial (the ESP-IDF python env has it).
|
||||||
|
"""
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import serial
|
||||||
|
|
||||||
|
LINK = 0x10
|
||||||
|
STATUS_REQUEST = 0x0C
|
||||||
|
STATUS = 0x84
|
||||||
|
|
||||||
|
|
||||||
|
def crc16(data: bytes) -> int:
|
||||||
|
crc = 0xFFFF
|
||||||
|
for b in data:
|
||||||
|
crc ^= b << 8
|
||||||
|
for _ in range(8):
|
||||||
|
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
|
||||||
|
return crc
|
||||||
|
|
||||||
|
|
||||||
|
def frame(type_: int, payload: bytes) -> bytes:
|
||||||
|
head = bytes([type_]) + struct.pack('<H', len(payload)) + payload
|
||||||
|
return b'\xaa\x55' + head + struct.pack('<H', crc16(head))
|
||||||
|
|
||||||
|
|
||||||
|
def parse(buffer: bytearray):
|
||||||
|
"""Yield (type, payload) for each complete, CRC-valid frame; consumes the buffer."""
|
||||||
|
while True:
|
||||||
|
i = buffer.find(b'\xaa\x55')
|
||||||
|
if i < 0 or len(buffer) < i + 5:
|
||||||
|
if i > 0:
|
||||||
|
del buffer[:i]
|
||||||
|
return
|
||||||
|
length = buffer[i + 3] | (buffer[i + 4] << 8)
|
||||||
|
end = i + 5 + length + 2
|
||||||
|
if len(buffer) < end:
|
||||||
|
if i > 0:
|
||||||
|
del buffer[:i]
|
||||||
|
return
|
||||||
|
head, crc = bytes(buffer[i + 2:end - 2]), buffer[end - 2] | (buffer[end - 1] << 8)
|
||||||
|
del buffer[:end if crc16(head) == crc else i + 2]
|
||||||
|
if crc16(head) == crc:
|
||||||
|
yield head[0], head[3:]
|
||||||
|
|
||||||
|
|
||||||
|
def describe(body: bytes) -> str:
|
||||||
|
uptime, configured = struct.unpack_from('<IB', body, 0)
|
||||||
|
text = f"len {len(body)} uptime {uptime / 1000:.1f}s configured {configured}"
|
||||||
|
if len(body) >= 106:
|
||||||
|
mv, flags = struct.unpack_from('<HB', body, 103)
|
||||||
|
text += f" battery {mv} mV flags 0x{flags:02x}" + (" LOW" if flags & 1 else "") + (" CRITICAL" if flags & 2 else "")
|
||||||
|
else:
|
||||||
|
text += " (no battery fields)"
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
port = sys.argv[1] if len(sys.argv) > 1 else 'COM10'
|
||||||
|
seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 15
|
||||||
|
buffer = bytearray()
|
||||||
|
sequence = 0
|
||||||
|
with serial.Serial(port, 115200, timeout=0.2) as s:
|
||||||
|
s.dtr = True # a CDC host asserts DTR; the firmware may gate TX on it
|
||||||
|
end = time.time() + seconds
|
||||||
|
next_request = 0.0
|
||||||
|
while time.time() < end:
|
||||||
|
if time.time() >= next_request:
|
||||||
|
sequence += 1
|
||||||
|
s.write(frame(LINK, bytes([STATUS_REQUEST, 0]) + struct.pack('<H', sequence)))
|
||||||
|
next_request = time.time() + 1.0
|
||||||
|
buffer += s.read(512)
|
||||||
|
for type_, payload in parse(buffer):
|
||||||
|
if type_ == LINK and len(payload) >= 4 and payload[0] == STATUS:
|
||||||
|
print(time.strftime('%H:%M:%S'), describe(payload[4:]), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user