Decode MAPEM and show traffic lights per lane

MapemUperCodec decodes MAPEM (MapData) from the ESP32-C5 (BTP port 2003)
and the CiT One's v2x/rx/mapem topic: intersection and lane names, the
reference point, lane types and directions, all node offset sizes and node
attributes, and each lane's connections with their signal groups. It
returns null on what it cannot size (extensions, regional data, computed
lanes) rather than guess.

TrafficLights.join places SPATEM signal groups on the MAPEM's ingress
lanes, gives each connection its turn (its maneuver, else the lane's, else
the angle between the lanes), picks the MAPEM whose revision the SPATEM
names when two are on air, and matches the rider to an ingress lane from
position and heading. The dashboard card then names the intersection and
shows the rider's lane, the distance to its stop line and one chip per
signal group with its turn arrows; the V2X map puts the light on the
reference point and draws the lanes in their signal colours.

Tested on recorded messages only: every distinct MAPEM on record (17 from
the 2026-03-18 drive, 288-1348 bytes, plus the bench RSU's) decodes field
for field like asn1tools; with a recorded SPATEM of the same intersection
and revision, 340 of 341 signalled exits find their movement (3/165's
group 65 never appears in its SPATEMs), and the geometric turn agrees with
198 of 201 stated maneuvers. tools/mapem_corpus.py rebuilds the fixtures.
This commit is contained in:
Ashin Walpola
2026-10-28 16:48:52 +01:00
parent fc3354a4ba
commit 8cbe3c337c
19 changed files with 3857 additions and 61 deletions
+26 -2
View File
@@ -5,6 +5,29 @@ Engineering to-do list. The reviewer-facing open items live in
## 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
@@ -62,8 +85,9 @@ Settings > Developer > V2X data logger. 110 unit tests pass. ESP32-C5 path check
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: `CamUseCaseRepository` logs "unexpected BTP
port" for 2003/2018 (no decoder there yet). On the CiT One, MAPEM arrives via `v2x/rx/mapem` (subscribed now) or
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
@@ -101,7 +101,7 @@ class MainActivity : AppCompatActivity() {
// Both flows already expire their own entries on a clock, so nothing here has to
// decide when a hazard or a traffic light has gone stale.
val denmEvents by mqttViewModel.denmEvents.collectAsState()
val spatIntersections by mqttViewModel.spatIntersections.collectAsState()
val trafficLights by mqttViewModel.trafficLights.collectAsState()
val ownCamPosition by mqttViewModel.ownCamPosition.collectAsState()
val v2xLogState by logViewModel.state.collectAsState()
val v2xLogFiles by logViewModel.files.collectAsState()
@@ -188,7 +188,7 @@ class MainActivity : AppCompatActivity() {
obuStationTypeWarning = obuStationTypeWarning,
obuStationType = obuStationType,
hazards = denmEvents,
signals = spatIntersections,
signals = trafficLights,
ownPosition = ownCamPosition,
onNavigateToConnection = { navController.navigate(Screen.Connection.route) },
onNavigateToSensors = {
@@ -21,6 +21,7 @@ import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.data.transport.Esp32Link
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.cam.CamParser
@@ -29,6 +30,7 @@ import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
import com.hawhamburg.micr0bu.domain.cam.OwnTxLoopback
import com.hawhamburg.micr0bu.domain.cam.StationType
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.map.MapEvent
import com.hawhamburg.micr0bu.domain.spat.SpatEvent
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine
@@ -197,6 +199,17 @@ class CamUseCaseRepository @Inject constructor(
*/
val decodedSpat: SharedFlow<SpatEvent> = _decodedSpat.asSharedFlow()
private val _decodedMap = MutableSharedFlow<MapEvent>(replay = 16, extraBufferCapacity = 16)
/**
* MAPEMs decoded from UPER, from the ESP32-C5 (BTP port 2003, since firmware d0fcb45) or the
* CiT One's `v2x/rx/mapem` topic: the lane geometry SPATEM's signal groups refer to. Replayed
* like [decodedSpat], since a MAPEM repeats only about once a second.
*
* The ESP32-C5 forwards only MAPEMs of up to 494 bytes (one link message); road MAPEMs are often
* bigger and then arrive only over the CiT One.
*/
val decodedMap: SharedFlow<MapEvent> = _decodedMap.asSharedFlow()
private val _decodedDenm = MutableSharedFlow<DenmEvent>(replay = 32, extraBufferCapacity = 32)
/**
* DENMs decoded from UPER, from either hardware path: the ESP32-C5 serial link or the CiT
@@ -242,8 +255,7 @@ class CamUseCaseRepository @Inject constructor(
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 -> Unit
RAW_MAPEM_TOPIC -> handleMapUper(envelope.payload, rssiDbm = null, source = "mqtt")
else -> Log.w(TAG, "rawV2x: unexpected topic ${raw.topic}")
}
}
@@ -296,6 +308,7 @@ class CamUseCaseRepository @Inject constructor(
BtpPort.CAM -> handleCamFromSerial(v2x)
BtpPort.DENM -> handleDenmFromSerial(v2x)
BtpPort.SPATEM -> handleSpatFromSerial(v2x)
BtpPort.MAPEM -> handleMapUper(v2x.uper, v2x.rssiDbm, source = "serial")
// The firmware only forwards ports it was told to accept, so anything else
// means the two sides have drifted out of sync.
else -> Log.w(TAG, "unexpected BTP port ${v2x.btpPort} from firmware")
@@ -569,6 +582,19 @@ class CamUseCaseRepository @Inject constructor(
_decodedSpat.tryEmit(spat)
}
/** A MAPEM heard over the air: lane geometry for one or more intersections. */
private fun handleMapUper(uper: ByteArray, rssiDbm: Int?, source: String) {
val map = MapemUperCodec.decode(uper, System.currentTimeMillis(), rssiDbm)
if (map == null) {
Log.w(TAG, "handleMapUper[$source]: decode FAILED for ${uper.size}-byte MAPEM " +
"(rssi=$rssiDbm dBm) - first bytes: ${uper.toHexPreview()}")
return
}
Log.d(TAG, "handleMapUper[$source]: decoded station=${map.stationId} " +
"intersections=${map.intersections.joinToString { "${it.key} rev ${it.revision} (${it.lanes.size} lanes)" }}")
_decodedMap.tryEmit(map)
}
/**
* The bits of a received frame the decoders and their log lines need, independent of whether
* it came off the serial link or an MQTT topic. [rssiDbm] is null on the MQTT path: the
@@ -20,6 +20,7 @@ import com.hawhamburg.micr0bu.data.transport.SerialFrameType
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import com.hawhamburg.micr0bu.domain.asn1.DenmUperCodec
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
@@ -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
* 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
* 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
* forwards only BTP ports 2001, 2002 and 2004 (see `gn_unwrap.c`), so MAPEM and VAM appear in an
* ESP32 log only once the firmware accepts ports 2003 and 2018.
* What it can hear is bounded by the hardware, not by this class: the ESP32-C5 firmware forwards
* BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only
* messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One.
*
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
* keeps the process alive and the CPU awake while a log runs; this class does the work.
@@ -320,6 +322,15 @@ class V2xLogger @Inject constructor(
Decoded(summary = "intersections=" + s.intersections.joinToString(",") { it.key } +
" movements=" + s.intersections.sumOf { it.movements.size })
}
ItsMessageKind.MAPEM -> MapemUperCodec.decode(uper, tsMs, rssiDbm)?.let { m ->
val first = m.intersections.first()
Decoded(
lat = first.refLatitude, lon = first.refLongitude,
summary = "intersections=" + m.intersections.joinToString(",") {
"${it.key}@${it.revision}" + (it.name?.let { n -> " '$n'" } ?: "")
} + " lanes=" + m.intersections.sumOf { it.lanes.size },
)
}
else -> null
}
}.getOrNull() ?: Decoded()
@@ -137,6 +137,7 @@ object Crc16CcittFalse {
object BtpPort {
const val CAM = 2001
const val DENM = 2002
const val MAPEM = 2003
/**
* Watch the crossover: SPATEM is BTP port **2004** but ItsPduHeader messageID **4**, while
@@ -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
}
@@ -65,7 +65,10 @@ import com.hawhamburg.micr0bu.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.denm.DenmParser
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
import com.hawhamburg.micr0bu.domain.spat.SignalMovement
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.Turn
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
import kotlinx.coroutines.delay
@@ -85,7 +88,7 @@ fun DashboardScreen(
obuStationTypeWarning: Boolean = false,
obuStationType: Int? = null,
hazards: List<DenmEvent> = emptyList(),
signals: List<SpatIntersection> = emptyList(),
signals: List<TrafficLight> = emptyList(),
ownPosition: Cam? = null,
onNavigateToConnection: () -> Unit,
onNavigateToSensors: () -> Unit,
@@ -409,17 +412,18 @@ fun DashboardScreen(
)
}
// Signals cannot be ranked by distance: SPATEM carries no position at all. The geometry
// that would place an intersection lives in MAPEM, which nothing on the air is currently
// sending. So the one shown is the one changing soonest, which is in any case the one a
// rider approaching a junction needs to see.
// The intersection whose ingress lane the rider is on (MAPEM geometry plus position and
// heading) comes first, nearest stop line first. Otherwise - no MAPEM heard, or not on one
// of its lanes - the one changing soonest, which is the one a rider approaching a junction
// most likely needs.
val nextSignal = remember(signals) {
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(
signal = signal,
light = light,
additionalCount = signals.size - 1,
onClick = onNavigateToV2x,
)
@@ -638,16 +642,16 @@ private fun HazardCard(
}
/**
* The signalised intersection changing soonest: its leading phase with a countdown, then every
* signal group as a coloured chip.
*
* Signal groups are bare numbers because that is all the app knows. Calling one "your lane" needs
* MAPEM geometry, and a friendlier label would claim knowledge that is not there.
* The intersection that matters most: the one whose lane the rider is on, else the one changing
* soonest. With MAPEM geometry the card names the intersection and, once the rider is on one of
* its ingress lanes, shows that lane's lights - one chip per signal group, with the turns it
* controls - and the distance to the stop line. Without it, signal groups are bare numbers,
* since anything friendlier would claim knowledge that is not there.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SignalCard(
signal: SpatIntersection,
light: TrafficLight,
additionalCount: Int,
onClick: () -> Unit,
) {
@@ -662,16 +666,28 @@ private fun SignalCard(
}
}
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
}
val phase = leading?.current?.phase
val tint = phaseTint(phase)
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(
if (light.revisionMismatch) stringResource(R.string.dash_signal_map_outdated) else null,
if (hiddenGroups > 0) stringResource(R.string.dash_more_count, hiddenGroups) else null,
if (additionalCount > 0) stringResource(R.string.dash_signal_more, additionalCount) else null,
).joinToString(" · ")
@@ -690,11 +706,23 @@ private fun SignalCard(
Icon(Icons.Default.Traffic, null, tint = tint, modifier = Modifier.size(28.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
stringResource(R.string.dash_signal_title, signal.state.key),
light.name ?: stringResource(R.string.dash_signal_title, light.key),
style = MaterialTheme.typography.labelLarge,
color = tint,
fontWeight = FontWeight.SemiBold,
)
if (own != null) {
Text(
stringResource(
R.string.dash_signal_own_approach,
own.approach.lane.name
?: stringResource(R.string.v2x_lane_fallback, own.approach.lane.laneId),
own.distanceToStopLineM,
),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
text = countdown
?.let { stringResource(R.string.dash_signal_countdown, phaseLabel(phase), it) }
@@ -707,12 +735,12 @@ private fun SignalCard(
// Wraps rather than scrolls: a horizontal scroller inside a scrolling dashboard
// is awkward to drive one-handed, and the chip row is short by construction.
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
signal.state.movements.take(DASH_MAX_SIGNAL_GROUPS).forEach { movement ->
val groupTint = phaseTint(movement.current?.phase)
chips.take(DASH_MAX_SIGNAL_GROUPS).forEach { (label, movement) ->
val groupTint = phaseTint(movement?.current?.phase)
val groupCountdown =
movement.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
movement?.current?.secondsUntil(now)?.takeIf { it in 0.0..99.0 }
Text(
text = stringResource(R.string.v2x_spat_group, movement.signalGroup) +
text = label +
(groupCountdown?.let { " " + stringResource(R.string.v2x_spat_countdown, it) } ?: ""),
style = MaterialTheme.typography.bodySmall,
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. */
@Composable
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.domain.cam.Cam
import com.hawhamburg.micr0bu.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.map.lanePoints
import com.hawhamburg.micr0bu.domain.spat.SignalPhase
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.Turn
import com.hawhamburg.micr0bu.domain.usecase.AlertLevel
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import org.osmdroid.config.Configuration
@@ -40,6 +44,7 @@ import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Polyline
/**
* V2X Monitor live map (Phase 03, Section 13) — the map body behind [V2xMapScreen], plotting the
@@ -49,7 +54,9 @@ import org.osmdroid.views.overlay.Marker
* Marker vocabulary, one shape per message type so the map reads without a legend:
* - CAM — teardrop pin, tinted by that station's most severe active alert level
* - DENM — hazard warning triangle
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit
* - SPATEM — traffic light, with the lamp for the intersection's leading phase lit. With the
* intersection's MAPEM it stands on the MAPEM's reference point and its lanes are drawn: each
* ingress lane in the colour of its straight-ahead light (else its first), egress lanes grey
*
* Unlike [MapScreen] this has no phone-GNSS-only fallback: [own] always reflects whichever ego
* source [com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository] currently trusts (obu_gnss /
@@ -69,7 +76,7 @@ fun V2xLiveMapView(
remotes: Map<Long, Cam>,
alerts: List<UseCaseAlert>,
denms: List<DenmEvent> = emptyList(),
spats: List<SpatIntersection> = emptyList(),
lights: List<TrafficLight> = emptyList(),
followOwn: Boolean = true,
onUserPanned: () -> Unit = {},
modifier: Modifier = Modifier,
@@ -92,6 +99,7 @@ fun V2xLiveMapView(
// tint applied would recolour every pin on the map.
val icons = remember(context) { MapIcons(context) }
val markers = remember { mutableMapOf<String, Marker>() }
val lanes = remember { mutableMapOf<String, Polyline>() }
val mapViewRef = remember { mutableStateOf<MapView?>(null) }
val lifecycleOwner = LocalLifecycleOwner.current
@@ -143,14 +151,17 @@ fun V2xLiveMapView(
update = { mv ->
val now = System.currentTimeMillis()
// Intersections we can actually place: SPATEM carries signal state but no geometry
// (that is MAPEM's job), so the only position available is the sending RSU's own CAM.
val locatedSpats = spats.mapNotNull { spat ->
remotes[spat.stationId]?.let { rsu -> spat to rsu }
// Intersections we can actually place: at the MAPEM's reference point when its MAPEM
// has been heard, else at the sending RSU's own CAM position (SPATEM has no geometry).
val locatedSpats = lights.mapNotNull { light ->
val spat = light.signal ?: return@mapNotNull null
val at = light.geometry?.let { GeoPoint(it.refLatitude, it.refLongitude) }
?: remotes[spat.stationId]?.let { rsu -> GeoPoint(rsu.latitude, rsu.longitude) }
at?.let { Triple(light, spat, it) }
}
// An RSU drawn as a traffic light must not also be drawn as a CAM pin underneath it:
// two markers on one point, the lower one unreachable.
val spatStationIds = locatedSpats.map { (spat, _) -> spat.stationId }.toSet()
val spatStationIds = locatedSpats.map { (_, spat, _) -> spat.stationId }.toSet()
val live = mutableSetOf<String>()
@@ -201,13 +212,38 @@ fun V2xLiveMapView(
}
}
locatedSpats.forEach { (spat, rsu) ->
val phase = spat.leadingPhase(now)
val liveLanes = mutableSetOf<String>()
lights.forEach { light ->
val geometry = light.geometry ?: return@forEach
val signalled = light.approaches.associateBy { it.lane.laneId }
geometry.lanes.forEach lane@{ lane ->
val points = geometry.lanePoints(lane)
if (points.size < 2) return@lane
val key = "${light.key}#${lane.laneId}"
liveLanes += key
val approach = signalled[lane.laneId]
val exit = approach?.let { a -> a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull() }
val own = light.ownApproach?.approach?.lane?.laneId == lane.laneId
lanes.getOrPut(key) { Polyline(mv) }.apply {
setPoints(points.map { GeoPoint(it.latitude, it.longitude) })
outlinePaint.color = if (approach == null) LANE_GREY else exit?.movement?.current?.phase.toLaneColor()
outlinePaint.strokeWidth = if (approach == null) 4f else if (own) 14f else 9f
title = lane.name ?: context.getString(R.string.v2x_lane_fallback, lane.laneId)
}
}
}
lanes.keys.retainAll { it in liveLanes }
locatedSpats.forEach { (light, spat, at) ->
// On the rider's lane, that lane's light speaks for the intersection.
val phase = light.ownApproach?.approach?.let { a ->
(a.exits.firstOrNull { it.turn == Turn.STRAIGHT } ?: a.exits.firstOrNull())?.movement?.current?.phase
}?.toLamp() ?: spat.leadingPhase(now)
markers.marker(mv, "$KEY_SPAT${spat.key}", live).apply {
position = GeoPoint(rsu.latitude, rsu.longitude)
position = at
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
icon = icons.signal(phase)
title = context.getString(
title = light.name ?: context.getString(
R.string.v2x_spat_rx_title, spat.state.key, spat.stationId,
)
snippet = spat.state.movements.joinToString(" · ") { movement ->
@@ -225,6 +261,8 @@ fun V2xLiveMapView(
(key in live).also { kept -> if (!kept) markers[key]?.closeInfoWindow() }
}
mv.overlays.clear()
// Lanes first, so every marker draws over them.
lanes.values.forEach { mv.overlays.add(it) }
markers.entries
.sortedBy { (key, _) -> key.drawOrder() }
.forEach { (_, marker) -> mv.overlays.add(marker) }
@@ -255,6 +293,7 @@ fun V2xLiveMapView(
// guarantees no further update after it.
onRelease = {
markers.clear()
lanes.clear()
it.onDetach()
},
modifier = modifier.fillMaxSize(),
@@ -328,25 +367,35 @@ private enum class SignalLamp(val drawableRes: Int) {
/**
* 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
* signal groups applies to the rider's own approach. This follows the rule the Dashboard's
* SignalCard already uses — the group changing soonest speaks for the intersection — so the same
* intersection reads the same way in both places rather than inventing a second convention.
* Used when the rider is not on one of the intersection's ingress lanes (or no MAPEM is known):
* then no signal group is theirs, and this follows the rule the Dashboard's SignalCard uses — the
* group changing soonest speaks for the intersection — so it reads the same in both places.
*/
private fun SpatIntersection.leadingPhase(nowMs: Long): SignalLamp {
val leading = state.movements.minByOrNull { movement ->
movement.current?.secondsUntil(nowMs)?.takeIf { it >= 0.0 } ?: Double.MAX_VALUE
}
val phase = leading?.current?.phase
return when {
phase == null -> SignalLamp.DARK
phase.isGo -> SignalLamp.GREEN
phase.isStop -> SignalLamp.RED
phase.isTransition -> SignalLamp.AMBER
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
}
return leading?.current?.phase.toLamp()
}
private fun SignalPhase?.toLamp(): SignalLamp = when {
this == null -> SignalLamp.DARK
isGo -> SignalLamp.GREEN
isStop -> SignalLamp.RED
isTransition -> SignalLamp.AMBER
else -> SignalLamp.DARK // UNAVAILABLE / DARK / caution
}
/** Lane colour on the map: the traffic-light colours, with a lane whose group is silent dark grey. */
private fun SignalPhase?.toLaneColor(): Int = when (toLamp()) {
SignalLamp.GREEN -> 0xFF4CAF50.toInt()
SignalLamp.RED -> 0xFFE53935.toInt()
SignalLamp.AMBER -> 0xFFFFC107.toInt()
SignalLamp.DARK -> 0xFF546E7A.toInt()
}
private const val LANE_GREY = 0x9978909C.toInt()
/**
* Marker tint per severity, matching [UseCaseAlertPanel]'s colours so the same station reads the
* same way in both places. Stations with no active alert stay neutral grey-blue rather than green:
@@ -61,17 +61,17 @@ fun V2xMapScreen(
val stations by viewModel.stationsInRange.collectAsState()
val alerts by viewModel.useCaseAlerts.collectAsState()
val denms by viewModel.denmEvents.collectAsState()
val 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
// the hand-over, every incoming CAM would drag the viewport back to the ego position and the
// map could not be panned at all while traffic is flowing.
var followOwn by remember { mutableStateOf(true) }
// SPATEM carries no geometry of its own, so an intersection can only be placed if its RSU has
// also been heard over CAM. Saying so is better than silently dropping it: "the map shows two
// SPATEM carries no geometry of its own, so an intersection can only be placed if its MAPEM or
// its RSU's CAM has been heard too. Saying so is better than silently dropping it: "the map shows two
// of the three lights I can see in the list" is otherwise an unexplained discrepancy.
val unlocatedSpats = spats.count { it.stationId !in stations.keys }
val unlocatedSpats = lights.count { it.geometry == null && it.signal?.stationId !in stations.keys }
Box(modifier = Modifier.fillMaxSize()) {
V2xLiveMapView(
@@ -79,7 +79,7 @@ fun V2xMapScreen(
remotes = stations,
alerts = alerts,
denms = denms,
spats = spats,
lights = lights,
followOwn = followOwn,
onUserPanned = { followOwn = false },
modifier = Modifier.fillMaxSize(),
@@ -125,7 +125,7 @@ fun V2xMapScreen(
MapCount(
icon = Icons.Default.Traffic,
tint = SignalGreenDot,
count = spats.size,
count = lights.size,
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.domain.denm.DenmEvent
import com.hawhamburg.micr0bu.domain.denm.DenmParser
import com.hawhamburg.micr0bu.domain.map.IntersectionGeometry
import com.hawhamburg.micr0bu.domain.map.MapPoint
import com.hawhamburg.micr0bu.domain.spat.SpatIntersection
import com.hawhamburg.micr0bu.domain.spat.TrafficLight
import com.hawhamburg.micr0bu.domain.spat.TrafficLights
import com.hawhamburg.micr0bu.domain.denm.DenmUseCase
import com.hawhamburg.micr0bu.domain.usecase.UseCaseAlert
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
@@ -269,6 +273,47 @@ class MqttViewModel @Inject constructor(
.sortedByDescending { it.timestamp }
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/**
* Intersection geometry heard over MAPEM, oldest first. Kept per intersection AND revision:
* two revisions of one intersection can be on air at once, and a SPATEM's signal groups mean
* whatever its own revision's MAPEM says ([TrafficLights.pickGeometry]).
*/
private val mapGeometries: StateFlow<List<IntersectionGeometry>> = combine(
camUseCaseRepository.decodedMap
.runningFold(emptyMap<String, Pair<IntersectionGeometry, Long>>()) { acc, map ->
acc + map.intersections.associate { "${it.key}#${it.revision}" to (it to map.timestamp) }
},
tickerFlow(MAP_EXPIRY_TICK_MS),
) { byKey, _ ->
val now = System.currentTimeMillis()
byKey.values
.filter { (_, heardAt) -> now - heardAt <= MAP_TTL_MS }
.sortedBy { (_, heardAt) -> heardAt }
.map { (geometry, _) -> geometry }
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/**
* [spatIntersections] with each SPATEM's signal groups placed on its MAPEM's lanes, and the
* rider's own approach picked from their position and heading. An intersection whose MAPEM has
* not been heard (yet) is still listed, with no lanes: its signal groups stay bare numbers.
*/
val trafficLights: StateFlow<List<TrafficLight>> = combine(
spatIntersections,
mapGeometries,
camUseCaseRepository.ownPosition,
) { spats, geometries, own ->
val byKey = geometries.groupBy { it.key }
spats.map { spat ->
TrafficLights.join(
signal = spat,
geometry = TrafficLights.pickGeometry(byKey[spat.key].orEmpty(), spat.state.revision),
own = own?.let { MapPoint(it.latitude, it.longitude) },
ownHeadingDeg = own?.headingDeg,
ownSpeedMps = own?.speedMps,
)
}
}.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
/** Emits immediately, then every [periodMs], purely to re-trigger a time-dependent combine. */
private fun tickerFlow(periodMs: Long): Flow<Long> = flow {
while (true) {
@@ -299,6 +344,13 @@ class MqttViewModel @Inject constructor(
const val SPAT_TTL_MS = 15_000L
const val SPAT_EXPIRY_TICK_MS = 2_000L
/**
* MAPEM repeats at about 1 Hz and its geometry is static, so a minute of silence is generous;
* a light is only ever shown while its SPATEM is live anyway.
*/
const val MAP_TTL_MS = 60_000L
const val MAP_EXPIRY_TICK_MS = 5_000L
/** RSU CAMs arrive at ~2 Hz, same as any other station, so the same window applies. */
const val RSU_TTL_MS = 15_000L
const val RSU_EXPIRY_TICK_MS = 2_000L
+3
View File
@@ -44,6 +44,9 @@
<string name="dash_signal_phase_dark">Dunkel</string>
<string name="dash_signal_phase_unknown">Unbekannt</string>
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
<string name="dash_signal_own_approach">%1$s · %2$.0f m bis zur Haltelinie</string>
<string name="dash_signal_map_outdated">Fahrstreifenkarte veraltet</string>
<string name="v2x_lane_fallback">Fahrstreifen %1$d</string>
<string name="stat_pressure">Luftdruck</string>
<string name="stat_altitude">Höhe</string>
<string name="stat_heading">Richtung</string>
+3
View File
@@ -45,6 +45,9 @@
<string name="dash_signal_phase_dark">Dark</string>
<string name="dash_signal_phase_unknown">Unknown</string>
<string name="dash_signal_countdown">%1$s · %2$.0f s</string>
<string name="dash_signal_own_approach">%1$s · %2$.0f m to the stop line</string>
<string name="dash_signal_map_outdated">Lane map out of date</string>
<string name="v2x_lane_fallback">Lane %1$d</string>
<string name="stat_pressure">Pressure</string>
<string name="stat_altitude">Altitude</string>
<string name="stat_heading">Heading</string>
@@ -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)
}
}
}
@@ -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
+176
View File
@@ -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()