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
@@ -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)
}
}