Add a receive path switch: V2X_RX or the spec's RAW_FRAME, with fragment reassembly

Settings > Connection > ESP32-C5 > Receive path chooses where received ITS messages come from.
V2X_RX (default) is the MicrOBU extension the board builds with gn_unwrap.c. Raw frames is the
station-link RAW_FRAME debug capture: the app switches RAW_CAPTURE on (mode 3), reassembles
fragmented link messages as the spec defines (LinkReassembly), parses the ITS5 record
(RawFrame) and unwraps the 802.11 frame with GnUnwrap, a Kotlin port of gn_unwrap.c. Both end
as the same V2X_RX frames, so nothing above the link changes, and the firmware keeps both.

GnUnwrapTest checks the port against the C code on 602 recorded, cut and corrupted frames
(corpus from obu-firmware/test/host: make corpus). 145 app tests. Fix the Connection text that
claimed the app picks the strongest micrOBU.
This commit is contained in:
Ashin Walpola
2026-11-11 16:19:32 +01:00
parent c96fd0086f
commit 1697091d3a
20 changed files with 1503 additions and 7 deletions
@@ -0,0 +1,131 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.GnUnwrap
import com.hawhamburg.micr0bu.data.transport.V2xRxFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The Kotlin port of `gn_unwrap.c` against the firmware's own code.
*
* `gn_unwrap_corpus.tsv` is written by `make corpus` in obu-firmware/test/host: frames from the recorded
* captures (unsigned and signed, single-hop and GeoBroadcast, CAM, DENM, MAPEM, SPATEM), copies cut at
* several lengths, copies with flipped bytes, and a few rejected frames, each with the verdict and the
* fields that `gn_unwrap_its` returns. Every line must come out the same here: same accept or reject,
* same port, flags, destination area, truncation and payload bytes.
*/
class GnUnwrapTest {
private class Line(
val frame: ByteArray, val accepted: Boolean, val port: Int, val flags: Int,
val lat: Int, val lon: Int, val dist: Int, val truncated: Boolean, val payload: ByteArray,
)
private fun String.hex(): ByteArray = ByteArray(length / 2) { substring(2 * it, 2 * it + 2).toInt(16).toByte() }
private fun corpus(): List<Line> {
val text = javaClass.classLoader!!.getResourceAsStream("gn_unwrap_corpus.tsv")!!.bufferedReader().readText()
return text.lines().filter { it.isNotBlank() }.map { l ->
val f = l.split("\t")
assertEquals("fields in: ${l.take(60)}", 9, f.size)
Line(f[0].hex(), f[1] == "A", f[2].toInt(), f[3].toInt(), f[4].toInt(), f[5].toInt(), f[6].toInt(),
f[7] == "1", f[8].hex())
}
}
@Test
fun `every corpus frame gets the verdict and fields of the C code`() {
val lines = corpus()
assertTrue("corpus too small: ${lines.size}", lines.size > 400)
var accepted = 0
var rejected = 0
for ((n, line) in lines.withIndex()) {
val r = GnUnwrap.unwrap(line.frame)
if (!line.accepted) {
assertNull("line $n: C rejects, Kotlin accepted", r)
rejected++
continue
}
assertNotNull("line $n: C accepts, Kotlin rejected", r)
r!!
assertEquals("line $n port", line.port, r.btpPort)
assertEquals("line $n area flag", line.flags and 1 != 0, r.hasGeoArea)
assertEquals("line $n signed flag", line.flags and 2 != 0, r.signedUnverified)
assertEquals("line $n area lat", line.lat, r.areaLatTenMicroDeg)
assertEquals("line $n area lon", line.lon, r.areaLonTenMicroDeg)
assertEquals("line $n area dist", line.dist, r.areaDistanceAMeters)
assertEquals("line $n truncated", line.truncated, r.truncated)
assertArrayEquals("line $n payload", line.payload, r.payload)
accepted++
}
// the corpus has both kinds in quantity: the test means something only if it does
assertTrue("accepted $accepted", accepted > 100)
assertTrue("rejected $rejected", rejected > 100)
}
@Test
fun `the corpus covers every message kind and both security shapes`() {
val seen = corpus().filter { it.accepted && !it.truncated }.map { Triple(it.port, it.flags and 2 != 0, it.flags and 1 != 0) }.toSet()
assertTrue(seen.contains(Triple(2001, false, false))) // unsigned single-hop CAM
assertTrue(seen.contains(Triple(2001, true, false))) // signed CAM
assertTrue(seen.any { it.first == 2002 && it.third }) // GeoBroadcast DENM
assertTrue(seen.any { it.first == 2003 }) // MAPEM
assertTrue(seen.any { it.first == 2004 }) // SPATEM
}
@Test
fun `a frame for a port that is not an ITS message port is rejected, VAM 2018 is accepted`() {
val cam = corpus().first { it.accepted && !it.truncated && it.port == 2001 && it.flags == 0 }
val vam = patchBtpPort(cam.frame, 2018)
assertEquals(2018, GnUnwrap.unwrap(vam)!!.btpPort)
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 1234)))
assertNull(GnUnwrap.unwrap(patchBtpPort(cam.frame, 2005)))
}
/** The BTP-B destination port sits right after the GN headers: find it by the known payload start. */
private fun patchBtpPort(frame: ByteArray, port: Int): ByteArray {
val r = GnUnwrap.unwrap(frame)!!
val start = frame.indices.first { i -> i + r.payload.size <= frame.size && (r.payload.indices).all { frame[i + it] == r.payload[it] } }
val copy = frame.copyOf()
copy[start - 4] = (port shr 8).toByte() // BTP-B header: port u16 BE, port info u16 BE
copy[start - 3] = port.toByte()
return copy
}
@Test
fun `short and garbage input is rejected without an exception`() {
assertNull(GnUnwrap.unwrap(ByteArray(0)))
assertNull(GnUnwrap.unwrap(ByteArray(23)))
assertNull(GnUnwrap.unwrap(ByteArray(200)))
assertNull(GnUnwrap.unwrap(ByteArray(200) { 0xFF.toByte() }))
// every prefix of a real frame: never throws
val frame = corpus().first { it.accepted && !it.truncated && it.flags and 2 != 0 }.frame
for (n in 0..frame.size) GnUnwrap.unwrap(frame.copyOf(n))
}
@Test
fun `the V2X_RX body is the one V2xRxFrame reads and the firmware writes`() {
val line = corpus().first { it.accepted && !it.truncated && it.port == 2002 && it.flags and 1 != 0 }
val r = GnUnwrap.unwrap(line.frame)!!
val body = GnUnwrap.toV2xRxBody(r, -61)!!
assertEquals(V2xRxFrame.PREFIX_SIZE + r.payload.size, body.size)
val parsed = V2xRxFrame.parse(body)!!
assertEquals(2002, parsed.btpPort)
assertEquals(-61, parsed.rssiDbm)
assertNotNull(parsed.geoArea)
assertEquals(line.lat / 1e7, parsed.geoArea!!.latitude, 1e-9)
assertEquals(line.dist, parsed.geoArea!!.radiusMeters)
assertArrayEquals(r.payload, parsed.uper)
// flags: bit 0 area, bit 1 signed
assertEquals(0x01 or (if (r.signedUnverified) 0x02 else 0), body[3].toInt())
// a truncated message is not forwarded
val cut = corpus().firstOrNull { it.accepted && it.truncated }
if (cut != null) assertNull(GnUnwrap.toV2xRxBody(GnUnwrap.unwrap(cut.frame)!!, -50))
assertEquals(127, GnUnwrap.toV2xRxBody(r, 500)!![2].toInt()) // clamped like the firmware
assertEquals(-128, GnUnwrap.toV2xRxBody(r, -500)!![2].toInt())
}
}
@@ -0,0 +1,144 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.data.transport.LinkMessage
import com.hawhamburg.micr0bu.data.transport.LinkReassembly
import com.hawhamburg.micr0bu.data.transport.RawFrame
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** Fragment reassembly as docs/station-link.pdf specifies it, and the RAW_FRAME record parser. */
class LinkReassemblyTest {
private var clock = 0L
private val reassembly = LinkReassembly { clock }
private fun fragment(flags: Int, seq: Int, total: Int, offset: Int, data: ByteArray, opcode: Int = LinkOpcode_RAW_FRAME) =
LinkMessage(
opcode, seq,
byteArrayOf(total.toByte(), (total shr 8).toByte(), offset.toByte(), (offset shr 8).toByte()) + data,
flags,
)
private fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
@Test
fun `a complete message passes through unchanged`() {
val m = LinkMessage(0x81, 5, bytes(1, 2, 3))
assertArrayEquals(bytes(1, 2, 3), reassembly.feed(m)!!.body)
}
@Test
fun `three fragments in order become one message with flags 0`() {
assertNull(reassembly.feed(fragment(1, 9, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 9, 6, 2, bytes(3, 4))))
val whole = reassembly.feed(fragment(3, 9, 6, 4, bytes(5, 6)))!!
assertArrayEquals(bytes(1, 2, 3, 4, 5, 6), whole.body)
assertEquals(0, whole.flags)
assertEquals(9, whole.sequence)
assertEquals(LinkOpcode_RAW_FRAME, whole.opcode)
}
@Test
fun `a gap, a duplicate and a changed total drop the stream`() {
assertNull(reassembly.feed(fragment(1, 1, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 1, 6, 4, bytes(5, 6)))) // skipped the middle
assertNull(reassembly.feed(fragment(3, 1, 6, 2, bytes(3, 4)))) // the stream is gone: nothing completes
assertNull(reassembly.feed(fragment(1, 2, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 2, 6, 0, bytes(1, 2)))) // the same offset twice
assertNull(reassembly.feed(fragment(1, 3, 6, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(2, 3, 8, 2, bytes(3, 4)))) // total changed
assertNull(reassembly.feed(fragment(2, 4, 6, 2, bytes(3, 4)))) // a middle without a first
assertTrue(reassembly.dropped >= 4)
}
@Test
fun `an unfinished stream is discarded after two seconds of silence`() {
assertNull(reassembly.feed(fragment(1, 7, 4, 0, bytes(1, 2))))
clock += 2_500
assertNull(reassembly.feed(fragment(3, 7, 4, 2, bytes(3, 4)))) // the first fragment is gone
assertNull(reassembly.feed(fragment(1, 8, 4, 0, bytes(1, 2))))
clock += 1_500 // still inside the window
assertNotNull(reassembly.feed(fragment(3, 8, 4, 2, bytes(3, 4))))
}
@Test
fun `at most eight streams are held and the ninth is refused`() {
for (s in 1..8) assertNull(reassembly.feed(fragment(1, s, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(1, 9, 4, 0, bytes(1, 2))))
assertNull(reassembly.feed(fragment(3, 9, 4, 2, bytes(3, 4)))) // refused, so nothing to complete
assertNotNull(reassembly.feed(fragment(3, 1, 4, 2, bytes(3, 4)))) // the held ones still finish
}
@Test
fun `an indication of 65535 octets is the largest, more is refused, a message of 2000 octets works`() {
val big = ByteArray(2000) { it.toByte() }
val chunk = 500
var out: LinkMessage? = null
var offset = 0
while (offset < big.size) {
val n = minOf(chunk, big.size - offset)
val flags = if (offset == 0) 1 else if (offset + n == big.size) 3 else 2
out = reassembly.feed(fragment(flags, 11, big.size, offset, big.copyOfRange(offset, offset + n)))
offset += n
}
assertArrayEquals(big, out!!.body)
assertNull(reassembly.feed(fragment(1, 12, 65_536 + 4, 0, bytes(1, 2))))
}
@Test
fun `different opcodes with the same sequence are separate streams`() {
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(1, 2), opcode = 0x85)))
assertNull(reassembly.feed(fragment(1, 5, 4, 0, bytes(9, 9), opcode = 0x81)))
val a = reassembly.feed(fragment(3, 5, 4, 2, bytes(3, 4), opcode = 0x85))!!
val b = reassembly.feed(fragment(3, 5, 4, 2, bytes(8, 8), opcode = 0x81))!!
assertArrayEquals(bytes(1, 2, 3, 4), a.body)
assertArrayEquals(bytes(9, 9, 8, 8), b.body)
}
// ---- RAW_FRAME record ------------------------------------------------------------------
private fun rawBody(frame: ByteArray, flags: Int = 0x02, rssi: Int = -61): ByteArray {
val h = java.io.ByteArrayOutputStream()
fun u8(v: Int) = h.write(v and 0xFF)
fun u16(v: Int) { u8(v); u8(v shr 8) }
fun u32(v: Long) { u16(v.toInt()); u16((v shr 16).toInt()) }
u32(42); u8(flags); u8(rssi)
h.write("ITS5".toByteArray())
u32(1_900_000_000L); u32(123_456); u16(frame.size)
h.write(frame)
return h.toByteArray()
}
@Test
fun `a RAW_FRAME body parses into its fields and frame`() {
val frame = ByteArray(30) { (it * 3).toByte() }
val r = RawFrame.parse(rawBody(frame))!!
assertEquals(42L, r.counter)
assertTrue(r.utcTime)
assertFalse(r.ownTransmission)
assertEquals(-61, r.rssiDbm)
assertEquals(1_900_000_000L, r.seconds)
assertEquals(123_456L, r.microseconds)
assertArrayEquals(frame, r.frame)
assertTrue(RawFrame.parse(rawBody(frame, flags = 0x01))!!.ownTransmission)
}
@Test
fun `a malformed RAW_FRAME is refused`() {
val good = rawBody(ByteArray(10))
assertNull(RawFrame.parse(good.copyOf(19))) // shorter than the header
assertNull(RawFrame.parse(good.copyOf(good.size - 1))) // length field says more
assertNull(RawFrame.parse(good + byteArrayOf(0))) // or less
val bad = good.copyOf(); bad[6] = 'X'.code.toByte()
assertNull(RawFrame.parse(bad)) // wrong magic
}
private companion object {
const val LinkOpcode_RAW_FRAME = 0x85
}
}