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 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, 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() 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() 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) } }