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:
@@ -42,7 +42,7 @@ hardware_paths:
|
|||||||
messages_received: V2X_RX (0x90), signed or not, up to 494 octets
|
messages_received: V2X_RX (0x90), signed or not, up to 494 octets
|
||||||
messages_sent: signed or unsigned per setting (Settings > Connection > ESP32-C5)
|
messages_sent: signed or unsigned per setting (Settings > Connection > ESP32-C5)
|
||||||
credentials: throwaway demo chain in app/src/main/assets/demo-chain.vcr
|
credentials: throwaway demo chain in app/src/main/assets/demo-chain.vcr
|
||||||
tests: 131 JVM unit tests, no emulator needed (domain/ has no Android imports)
|
tests: 145 JVM unit tests, no emulator needed (domain/ has no Android imports)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Project goal
|
## Project goal
|
||||||
@@ -124,7 +124,7 @@ tools/ Bench scripts: STATUS watcher, bench-listener tally, MAPEM
|
|||||||
docs/ Requirements traceability, signed ITS / VAM / BLE design, architecture diagrams
|
docs/ Requirements traceability, signed ITS / VAM / BLE design, architecture diagrams
|
||||||
```
|
```
|
||||||
|
|
||||||
The `domain/` packages contain no Android imports. That is what makes the 131-test JVM suite possible without an emulator or instrumentation.
|
The `domain/` packages contain no Android imports. That is what makes the 145-test JVM suite possible without an emulator or instrumentation.
|
||||||
|
|
||||||
## Connectivity
|
## Connectivity
|
||||||
|
|
||||||
@@ -156,6 +156,17 @@ Whether an active BLE connection costs 5.9 GHz reception has not been measured y
|
|||||||
|
|
||||||
vanetza-idf verifies strictly and would drop anything unsigned or signed under another root, i.e. the bench car and every RSU. So every captured frame also goes through `gn_unwrap.c`, which strips 802.11, LLC/SNAP, GeoNetworking (single-hop and GeoBroadcast), an IEEE 1609.2 signed envelope if there is one, and BTP, and forwards the ITS payload for BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM. Signatures are not checked on this path; the message is flagged "signed, not verified". A payload over 494 bytes does not fit one link message and is dropped and counted.
|
vanetza-idf verifies strictly and would drop anything unsigned or signed under another root, i.e. the bench car and every RSU. So every captured frame also goes through `gn_unwrap.c`, which strips 802.11, LLC/SNAP, GeoNetworking (single-hop and GeoBroadcast), an IEEE 1609.2 signed envelope if there is one, and BTP, and forwards the ITS payload for BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM. Signatures are not checked on this path; the message is flagged "signed, not verified". A payload over 494 bytes does not fit one link message and is dropped and counted.
|
||||||
|
|
||||||
|
**Two receive paths, switchable** (Settings > Connection > ESP32-C5 > Receive path). Both end in the same decoded messages, so nothing above the link changes:
|
||||||
|
|
||||||
|
| | V2X_RX (default) | Raw frames |
|
||||||
|
|---|---|---|
|
||||||
|
| Source | the MicrOBU extension, opcode 0x90 | the spec's `RAW_FRAME` (0x85), switched on with `RAW_CAPTURE` |
|
||||||
|
| Who unpacks the frame | the board (`gn_unwrap.c`) | the app (`GnUnwrap.kt`, a port tested frame by frame against the C code) |
|
||||||
|
| Size | up to 494 octets | not limited: fragments are reassembled (`LinkReassembly`, as the spec defines) |
|
||||||
|
| Reliability | normal indication | debug copy: can be dropped when the link is busy, more bandwidth, especially over BLE |
|
||||||
|
|
||||||
|
The board always sends `V2X_RX`; the app consumes one path and ignores the other. Changing the setting takes effect at once on a configured station (`RAW_CAPTURE` mode 3 = on and broadcast frames only, mode 0 = off). `GnUnwrapTest` checks the Kotlin unwrapper against `obu-firmware/test/host/dump_corpus.c`'s output for 602 recorded, cut and corrupted frames.
|
||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|
||||||
The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path, which is the highest-risk code in the project. Round-trip tests through the project's own codecs structurally cannot catch a shared mistake about a field's bit width, and this project shipped exactly that bug three times (`CurvatureCalculationMode`, the GeoNetworking reserved bytes, `yawRateConfidence`). Phone and ESP32 agreed with each other and with nothing else.
|
The app hand-encodes and decodes ETSI messages bit by bit on the ESP32-C5 path, which is the highest-risk code in the project. Round-trip tests through the project's own codecs structurally cannot catch a shared mistake about a field's bit width, and this project shipped exactly that bug three times (`CurvatureCalculationMode`, the GeoNetworking reserved bytes, `yawRateConfidence`). Phone and ESP32 agreed with each other and with nothing else.
|
||||||
|
|||||||
@@ -23,6 +23,11 @@ on the bench with the COM3 board as a listener:
|
|||||||
|
|
||||||
Still open:
|
Still open:
|
||||||
|
|
||||||
|
- [x] Receive path switch (2026-11-11, over BLE): `Raw frames` gave `RAW_CAPTURE mode 3 -> accepted` and the simulated car kept
|
||||||
|
arriving through the app's own unwrapper; back to `V2X_RX` gave mode 0 and it kept arriving.
|
||||||
|
- [ ] Fragmentation on air: a RAW_FRAME above one link message (a large MAPEM or SPATEM from a road RSU) reassembled in the
|
||||||
|
app over BLE and over USB; only unit-tested so far.
|
||||||
|
- [ ] Count both paths on the same traffic to see how many frames the raw copy drops on a busy link.
|
||||||
- [x] Bond persistence (2026-11-11): the board was reflashed (MTU 517) with its NVS kept; the phone reconnected to
|
- [x] Bond persistence (2026-11-11): the board was reflashed (MTU 517) with its NVS kept; the phone reconnected to
|
||||||
micrOBU-66AA without a pairing prompt.
|
micrOBU-66AA without a pairing prompt.
|
||||||
- [ ] Verify a captured signature with `test/verify_signed_pcap.py` (needs the sniffer firmware).
|
- [ ] Verify a captured signature with `test/verify_signed_pcap.py` (needs the sniffer firmware).
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
||||||
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
||||||
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
||||||
|
val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
|
||||||
// Received hazards and live signal state, for the Dashboard's V2X summary cards.
|
// Received hazards and live signal state, for the Dashboard's V2X summary cards.
|
||||||
// Both flows already expire their own entries on a clock, so nothing here has to
|
// Both flows already expire their own entries on a clock, so nothing here has to
|
||||||
// decide when a hazard or a traffic light has gone stale.
|
// decide when a hazard or a traffic light has gone stale.
|
||||||
@@ -328,6 +329,8 @@ class MainActivity : AppCompatActivity() {
|
|||||||
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
|
onEsp32TransportChange = mqttViewModel::setEsp32Transport,
|
||||||
outgoingMessage = outgoingMessage,
|
outgoingMessage = outgoingMessage,
|
||||||
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
|
onOutgoingMessageChange = mqttViewModel::setOutgoingMessage,
|
||||||
|
esp32RxPath = esp32RxPath,
|
||||||
|
onEsp32RxPathChange = mqttViewModel::setEsp32RxPath,
|
||||||
signOutgoing = signOutgoing,
|
signOutgoing = signOutgoing,
|
||||||
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
|
onSignOutgoingChange = mqttViewModel::setSignOutgoing,
|
||||||
onBack = { navController.popBackStack() },
|
onBack = { navController.popBackStack() },
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.edit
|
|||||||
import androidx.datastore.preferences.core.longPreferencesKey
|
import androidx.datastore.preferences.core.longPreferencesKey
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
import androidx.datastore.preferences.preferencesDataStore
|
import androidx.datastore.preferences.preferencesDataStore
|
||||||
|
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||||
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
||||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||||
@@ -38,6 +39,7 @@ class ObuHardwarePreferences @Inject constructor(
|
|||||||
// ESP32-C5 only.
|
// ESP32-C5 only.
|
||||||
val ESP32_TRANSPORT = stringPreferencesKey("esp32_transport")
|
val ESP32_TRANSPORT = stringPreferencesKey("esp32_transport")
|
||||||
val OUTGOING_MESSAGE = stringPreferencesKey("outgoing_message")
|
val OUTGOING_MESSAGE = stringPreferencesKey("outgoing_message")
|
||||||
|
val ESP32_RX_PATH = stringPreferencesKey("esp32_rx_path")
|
||||||
val SIGN_OUTGOING = booleanPreferencesKey("sign_outgoing")
|
val SIGN_OUTGOING = booleanPreferencesKey("sign_outgoing")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +60,15 @@ class ObuHardwarePreferences @Inject constructor(
|
|||||||
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_TRANSPORT] = transport.id }
|
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_TRANSPORT] = transport.id }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Where received ITS messages come from on the ESP32-C5 path: V2X_RX (default) or the RAW_FRAME debug capture. */
|
||||||
|
val esp32RxPathFlow: Flow<Esp32RxPath> = context.obuHardwareDataStore.data.map { prefs ->
|
||||||
|
Esp32RxPath.entries.firstOrNull { it.id == prefs[Keys.ESP32_RX_PATH] } ?: Esp32RxPath.V2X_RX
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun setEsp32RxPath(path: Esp32RxPath) {
|
||||||
|
context.obuHardwareDataStore.edit { prefs -> prefs[Keys.ESP32_RX_PATH] = path.id }
|
||||||
|
}
|
||||||
|
|
||||||
/** What the ESP32-C5 path transmits while recording: CAM (default) or VAM. */
|
/** What the ESP32-C5 path transmits while recording: CAM (default) or VAM. */
|
||||||
val outgoingMessageFlow: Flow<OutgoingMessage> = context.obuHardwareDataStore.data.map { prefs ->
|
val outgoingMessageFlow: Flow<OutgoingMessage> = context.obuHardwareDataStore.data.map { prefs ->
|
||||||
OutgoingMessage.entries.firstOrNull { it.id == prefs[Keys.OUTGOING_MESSAGE] } ?: OutgoingMessage.CAM
|
OutgoingMessage.entries.firstOrNull { it.id == prefs[Keys.OUTGOING_MESSAGE] } ?: OutgoingMessage.CAM
|
||||||
|
|||||||
@@ -39,6 +39,21 @@ enum class Esp32LinkState { DISCONNECTED, DEVICE_ATTACHED, PERMISSION_REQUESTED,
|
|||||||
/** Which physical link the phone uses to reach the ESP32-C5 (Settings). */
|
/** Which physical link the phone uses to reach the ESP32-C5 (Settings). */
|
||||||
enum class Esp32Transport(val id: String) { USB("usb"), BLE("ble") }
|
enum class Esp32Transport(val id: String) { USB("usb"), BLE("ble") }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where the app takes received ITS messages from (Settings > Connection > ESP32-C5 > Receive path).
|
||||||
|
*
|
||||||
|
* - [V2X_RX]: the MicrOBU extension (opcode 0x90). The board unwraps every received frame itself and
|
||||||
|
* sends the finished ITS message, signed or not. Small, always on, the default.
|
||||||
|
* - [RAW_FRAME]: the station-link `RAW_FRAME` debug capture of docs/station-link.pdf (opcode 0x85,
|
||||||
|
* switched on with `RAW_CAPTURE`). The board sends the whole 802.11 frame, possibly fragmented, and
|
||||||
|
* the app unwraps it with [GnUnwrap]. Spec-defined and not limited to 494 octets, but best effort:
|
||||||
|
* copies can be dropped when the link is busy, and it costs more bandwidth, especially over BLE.
|
||||||
|
*
|
||||||
|
* Both reach the rest of the app as the same [SerialFrameType.V2X_RX] frames, so nothing above this
|
||||||
|
* class changes with the setting. The board keeps sending `V2X_RX` regardless; the app uses one path.
|
||||||
|
*/
|
||||||
|
enum class Esp32RxPath(val id: String) { V2X_RX("v2x_rx"), RAW_FRAME("raw_frame") }
|
||||||
|
|
||||||
/** What the phone transmits while a trip records (Settings). */
|
/** What the phone transmits while a trip records (Settings). */
|
||||||
enum class OutgoingMessage(val id: String) { CAM("cam"), VAM("vam") }
|
enum class OutgoingMessage(val id: String) { CAM("cam"), VAM("vam") }
|
||||||
|
|
||||||
@@ -96,6 +111,8 @@ class Esp32Link @Inject constructor(
|
|||||||
private const val TAG = "Esp32Link"
|
private const val TAG = "Esp32Link"
|
||||||
private const val REPLY_TIMEOUT_MS = 3_000L
|
private const val REPLY_TIMEOUT_MS = 3_000L
|
||||||
private const val STATUS_POLL_MS = 1_000L
|
private const val STATUS_POLL_MS = 1_000L
|
||||||
|
/** RAW_CAPTURE mode: on (bit 0) and broadcast frames only (bit 1): every ITS-G5 frame, no unicast noise. */
|
||||||
|
private const val RAW_CAPTURE_ON_BROADCAST = 0x03
|
||||||
/** Applying a bundle verifies the chain and rebuilds the stack on the C5: seconds, not ms. */
|
/** Applying a bundle verifies the chain and rebuilds the stack on the C5: seconds, not ms. */
|
||||||
private const val PROVISION_TIMEOUT_MS = 15_000L
|
private const val PROVISION_TIMEOUT_MS = 15_000L
|
||||||
private const val SEGMENT_SIZE = 240
|
private const val SEGMENT_SIZE = 240
|
||||||
@@ -124,6 +141,17 @@ class Esp32Link @Inject constructor(
|
|||||||
val transport: StateFlow<Esp32Transport> =
|
val transport: StateFlow<Esp32Transport> =
|
||||||
prefs.esp32TransportFlow.stateIn(scope, SharingStarted.Eagerly, Esp32Transport.USB)
|
prefs.esp32TransportFlow.stateIn(scope, SharingStarted.Eagerly, Esp32Transport.USB)
|
||||||
|
|
||||||
|
/** Which received-message path is in use. See [Esp32RxPath]. */
|
||||||
|
val rxPath: StateFlow<Esp32RxPath> =
|
||||||
|
prefs.esp32RxPathFlow.stateIn(scope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
|
||||||
|
|
||||||
|
/** Fragments of RAW_FRAME (and any other large indication) in flight; reset with every session. */
|
||||||
|
private val reassembly = LinkReassembly()
|
||||||
|
|
||||||
|
/** RAW_FRAME bodies seen, unwrapped to an ITS message, and not an ITS message (the usual case on air). */
|
||||||
|
@Volatile private var rawSeen = 0L
|
||||||
|
@Volatile private var rawForwarded = 0L
|
||||||
|
|
||||||
val state: StateFlow<Esp32LinkState> = combine(transport, usb.state, ble.state) { t, u, b ->
|
val state: StateFlow<Esp32LinkState> = combine(transport, usb.state, ble.state) { t, u, b ->
|
||||||
if (t == Esp32Transport.USB) u else b
|
if (t == Esp32Transport.USB) u else b
|
||||||
}.stateIn(scope, SharingStarted.Eagerly, Esp32LinkState.DISCONNECTED)
|
}.stateIn(scope, SharingStarted.Eagerly, Esp32LinkState.DISCONNECTED)
|
||||||
@@ -185,12 +213,15 @@ class Esp32Link @Inject constructor(
|
|||||||
_linkStatus.value = null
|
_linkStatus.value = null
|
||||||
pending.values.forEach { it.cancel() }
|
pending.values.forEach { it.cancel() }
|
||||||
pending.clear()
|
pending.clear()
|
||||||
|
reassembly.reset()
|
||||||
} else if (transport.value == Esp32Transport.BLE) {
|
} else if (transport.value == Esp32Transport.BLE) {
|
||||||
_protocol.value = Esp32Protocol.STATION_LINK // BLE exists only on the current firmware
|
_protocol.value = Esp32Protocol.STATION_LINK // BLE exists only on the current firmware
|
||||||
scope.launch { ensureConfigured(null) }
|
scope.launch { ensureConfigured(null) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A change of receive path in Settings takes effect at once on a configured station.
|
||||||
|
scope.launch { rxPath.collect { scope.launch { applyRxPath() } } }
|
||||||
scope.launch { ble.detail.collect { if (transport.value == Esp32Transport.BLE) _detail.value = it } }
|
scope.launch { ble.detail.collect { if (transport.value == Esp32Transport.BLE) _detail.value = it } }
|
||||||
// Switching transport in Settings closes the other one; connecting stays a user action.
|
// Switching transport in Settings closes the other one; connecting stays a user action.
|
||||||
scope.launch {
|
scope.launch {
|
||||||
@@ -287,9 +318,36 @@ class Esp32Link @Inject constructor(
|
|||||||
}
|
}
|
||||||
configured = config
|
configured = config
|
||||||
_detail.value = null
|
_detail.value = null
|
||||||
|
scope.launch { applyRxPath() } // a (re)configured station starts with raw capture off
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Switches the station's raw capture to match [rxPath]: on (receive only, broadcast frames) for
|
||||||
|
* [Esp32RxPath.RAW_FRAME], off for [Esp32RxPath.V2X_RX]. RAW_CAPTURE needs a started radio, so it
|
||||||
|
* is sent only once the station is configured; a station that restarted forgets it and is
|
||||||
|
* configured again, which sends it again.
|
||||||
|
*/
|
||||||
|
private suspend fun applyRxPath() {
|
||||||
|
if (_protocol.value != Esp32Protocol.STATION_LINK || state.value != Esp32LinkState.CONNECTED) return
|
||||||
|
if (configured == null) return
|
||||||
|
val mode = if (rxPath.value == Esp32RxPath.RAW_FRAME) RAW_CAPTURE_ON_BROADCAST else 0
|
||||||
|
val result = request(LinkOpcode.RAW_CAPTURE, byteArrayOf(mode.toByte()), REPLY_TIMEOUT_MS)
|
||||||
|
Log.i(TAG, "receive path ${rxPath.value}: RAW_CAPTURE mode $mode -> ${result?.let { LinkResultCode.name(it.code) } ?: "no reply"}")
|
||||||
|
if (result != null && !result.accepted && mode != 0) _detail.value = "Raw capture refused: ${LinkResultCode.name(result.code)}"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One RAW_FRAME: unwrap it to the ITS message inside and hand it on like a V2X_RX message. */
|
||||||
|
private fun onRawFrame(body: ByteArray) {
|
||||||
|
val raw = RawFrame.parse(body) ?: return
|
||||||
|
if (raw.ownTransmission) return
|
||||||
|
rawSeen++
|
||||||
|
val unwrapped = GnUnwrap.unwrap(raw.frame) ?: return
|
||||||
|
val v2xRx = GnUnwrap.toV2xRxBody(unwrapped, raw.rssiDbm) ?: return
|
||||||
|
rawForwarded++
|
||||||
|
_incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, v2xRx))
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun provisionDemoCredentials(): Boolean {
|
private suspend fun provisionDemoCredentials(): Boolean {
|
||||||
_detail.value = "Provisioning the demo credentials"
|
_detail.value = "Provisioning the demo credentials"
|
||||||
val bundle = runCatching { context.assets.open(DEMO_BUNDLE_ASSET).use { it.readBytes() } }.getOrElse {
|
val bundle = runCatching { context.assets.open(DEMO_BUNDLE_ASSET).use { it.readBytes() } }.getOrElse {
|
||||||
@@ -370,9 +428,13 @@ class Esp32Link @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun onLinkMessage(octets: ByteArray) {
|
private fun onLinkMessage(octets: ByteArray) {
|
||||||
val message = LinkMessage.decode(octets) ?: return
|
// Fragments are put back together first (flags 1-3 of docs/station-link.pdf); a complete
|
||||||
|
// message, the usual case, passes straight through.
|
||||||
|
val message = reassembly.feed(LinkMessage.decode(octets) ?: return) ?: return
|
||||||
when (message.opcode) {
|
when (message.opcode) {
|
||||||
LinkOpcode.V2X_RX -> _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
|
LinkOpcode.V2X_RX ->
|
||||||
|
if (rxPath.value == Esp32RxPath.V2X_RX) _incomingFrames.tryEmit(DecodedFrame(SerialFrameType.V2X_RX, message.body))
|
||||||
|
LinkOpcode.RAW_FRAME -> if (rxPath.value == Esp32RxPath.RAW_FRAME) onRawFrame(message.body)
|
||||||
LinkOpcode.CONFIRM -> {
|
LinkOpcode.CONFIRM -> {
|
||||||
val result = LinkResult.decode(message.body) ?: return
|
val result = LinkResult.decode(message.body) ?: return
|
||||||
val waiting = pending.remove(message.sequence)
|
val waiting = pending.remove(message.sequence)
|
||||||
|
|||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package com.hawhamburg.micr0bu.data.transport
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kotlin counterpart of obu-firmware's `gn_unwrap.c`: takes one received 802.11 data frame down
|
||||||
|
* through LLC/SNAP, GeoNetworking and BTP-B to the ITS message inside, signed or not.
|
||||||
|
*
|
||||||
|
* It exists so the app can consume the station's `RAW_FRAME` debug capture the way it consumes
|
||||||
|
* `V2X_RX` (which the board builds with the C version). The two are tested against each other on the
|
||||||
|
* same frames (`GnUnwrapTest`, corpus from the C code), so they accept and reject the same frames and
|
||||||
|
* return the same fields.
|
||||||
|
*
|
||||||
|
* What it does and does not do, as in the C version:
|
||||||
|
* - Plain Data frames only, QoS or not, no WDS; LLC/SNAP with the GeoNetworking ethertype 0x8947.
|
||||||
|
* - Single-hop broadcast (TSB subtype 0) and GeoBroadcast; BTP-B on ports 2001-2004 and 2018.
|
||||||
|
* - A secured packet (TS 103 097 / IEEE 1609.2 `signedData` or `unsecuredData`, protocolVersion 3) is
|
||||||
|
* unwrapped WITHOUT verifying the signature or certificate; the result says it was signed.
|
||||||
|
* Encrypted and legacy v1.2.1 envelopes are rejected.
|
||||||
|
* - The payload is exactly as long as the Common Header declares, not what is left of the frame.
|
||||||
|
*/
|
||||||
|
object GnUnwrap {
|
||||||
|
|
||||||
|
/** An unwrapped ITS message. [payload] is its UPER encoding. */
|
||||||
|
class Result(
|
||||||
|
val btpPort: Int,
|
||||||
|
val payload: ByteArray,
|
||||||
|
val hasGeoArea: Boolean,
|
||||||
|
val areaLatTenMicroDeg: Int,
|
||||||
|
val areaLonTenMicroDeg: Int,
|
||||||
|
val areaDistanceAMeters: Int,
|
||||||
|
/** The packet carried a signature envelope; it was not checked. */
|
||||||
|
val signedUnverified: Boolean,
|
||||||
|
/** The frame ended before the payload its headers declare; [payload] is only what arrived. */
|
||||||
|
val truncated: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
private const val GN_ETHERTYPE = 0x8947
|
||||||
|
private const val LLC_SNAP_HEADER_LEN = 8
|
||||||
|
private const val IEEE80211_HEADER_LEN = 24
|
||||||
|
private const val IEEE80211_QOS_CTRL_LEN = 2
|
||||||
|
private const val FC_TYPE_DATA = 2
|
||||||
|
private const val FC_QOS_SUBTYPE_BIT = 0x08
|
||||||
|
private const val GN_BASIC_HEADER_LEN = 4
|
||||||
|
private const val GN_COMMON_HEADER_LEN = 8
|
||||||
|
private const val BTP_B_HEADER_LEN = 4
|
||||||
|
private const val GN_SHB_EXT_HEADER_LEN = 28
|
||||||
|
private const val GN_GBC_EXT_HEADER_LEN = 44
|
||||||
|
private const val GBC_AREA_LAT_OFFSET = 28
|
||||||
|
private const val GBC_AREA_LON_OFFSET = 32
|
||||||
|
private const val GBC_AREA_DIST_A_OFFSET = 36
|
||||||
|
private const val GN_HEADER_TYPE_GBC = 4
|
||||||
|
private const val GN_HEADER_TYPE_TSB = 5
|
||||||
|
private const val GN_HEADER_SUBTYPE_SINGLE_HOP = 0
|
||||||
|
private const val GN_NEXT_HEADER_COMMON = 1
|
||||||
|
private const val GN_NEXT_HEADER_SECURED = 2
|
||||||
|
private const val GN_COMMON_NEXT_HEADER_BTP_B = 2
|
||||||
|
private const val GN_COMMON_PAYLOAD_LEN_OFFSET = 4
|
||||||
|
private const val IEEE1609DOT2_VERSION = 3
|
||||||
|
private const val CONTENT_TAG_UNSECURED_DATA = 0x80
|
||||||
|
private const val CONTENT_TAG_SIGNED_DATA = 0x81
|
||||||
|
private const val SIGNED_PAYLOAD_HAS_DATA = 0x40
|
||||||
|
|
||||||
|
private val BTP_PORTS = setOf(2001, 2002, 2003, 2004, 2018)
|
||||||
|
private val LLC_SNAP_PREFIX = intArrayOf(0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00)
|
||||||
|
|
||||||
|
private fun ByteArray.u8(i: Int) = this[i].toInt() and 0xFF
|
||||||
|
private fun ByteArray.be16(i: Int) = (u8(i) shl 8) or u8(i + 1)
|
||||||
|
private fun ByteArray.be32(i: Int) = (u8(i) shl 24) or (u8(i + 1) shl 16) or (u8(i + 2) shl 8) or u8(i + 3)
|
||||||
|
|
||||||
|
/** COER length determinant: returns (octets used, length), or null when it does not fit. */
|
||||||
|
private fun coerLength(f: ByteArray, at: Int, avail: Int): Pair<Int, Int>? {
|
||||||
|
if (avail < 1) return null
|
||||||
|
val first = f.u8(at)
|
||||||
|
if (first < 0x80) return 1 to first
|
||||||
|
val n = first and 0x7F
|
||||||
|
if (n < 1 || n > 2 || avail < 1 + n) return null
|
||||||
|
var v = 0
|
||||||
|
for (i in 1..n) v = (v shl 8) or f.u8(at + i)
|
||||||
|
return (1 + n) to v
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the Common Header offset inside the envelope, the end of the envelope's inner packet
|
||||||
|
* and whether it was signed; null for anything this does not handle.
|
||||||
|
*/
|
||||||
|
private fun unwrapSecured(f: ByteArray, offset: Int, frameLen: Int): Triple<Int, Int, Boolean>? {
|
||||||
|
val avail = frameLen - offset
|
||||||
|
if (avail < 2 || f.u8(offset) != IEEE1609DOT2_VERSION) return null
|
||||||
|
val i: Int
|
||||||
|
val signed: Boolean
|
||||||
|
if (f.u8(offset + 1) == CONTENT_TAG_SIGNED_DATA) {
|
||||||
|
if (avail < 6 ||
|
||||||
|
f.u8(offset + 2) >= 0x80 ||
|
||||||
|
(f.u8(offset + 3) and SIGNED_PAYLOAD_HAS_DATA) == 0 ||
|
||||||
|
f.u8(offset + 4) != IEEE1609DOT2_VERSION ||
|
||||||
|
f.u8(offset + 5) != CONTENT_TAG_UNSECURED_DATA
|
||||||
|
) return null
|
||||||
|
i = 6
|
||||||
|
signed = true
|
||||||
|
} else if (f.u8(offset + 1) == CONTENT_TAG_UNSECURED_DATA) {
|
||||||
|
i = 2
|
||||||
|
signed = false
|
||||||
|
} else {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val (used, len) = coerLength(f, offset + i, avail - i) ?: return null
|
||||||
|
val innerStart = offset + i + used
|
||||||
|
return Triple(innerStart, offset + i + used + len, signed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unwraps one 802.11 frame; null when it is not an ITS message this handles (the common case on air). */
|
||||||
|
fun unwrap(frame: ByteArray): Result? {
|
||||||
|
val frameLen = frame.size
|
||||||
|
if (frameLen < IEEE80211_HEADER_LEN) return null
|
||||||
|
val fc0 = frame.u8(0)
|
||||||
|
val fc1 = frame.u8(1)
|
||||||
|
val type = (fc0 shr 2) and 0x03
|
||||||
|
val subtype = (fc0 shr 4) and 0x0F
|
||||||
|
val toDs = (fc1 and 0x01) != 0
|
||||||
|
val fromDs = (fc1 and 0x02) != 0
|
||||||
|
if (type != FC_TYPE_DATA || (toDs && fromDs)) return null
|
||||||
|
|
||||||
|
var offset = IEEE80211_HEADER_LEN
|
||||||
|
if ((subtype and FC_QOS_SUBTYPE_BIT) != 0) offset += IEEE80211_QOS_CTRL_LEN
|
||||||
|
|
||||||
|
if (frameLen < offset + LLC_SNAP_HEADER_LEN) return null
|
||||||
|
for (k in LLC_SNAP_PREFIX.indices) if (frame.u8(offset + k) != LLC_SNAP_PREFIX[k]) return null
|
||||||
|
if (frame.be16(offset + 6) != GN_ETHERTYPE) return null
|
||||||
|
offset += LLC_SNAP_HEADER_LEN
|
||||||
|
|
||||||
|
if (frameLen < offset + GN_BASIC_HEADER_LEN) return null
|
||||||
|
val basicNextHeader = frame.u8(offset) and 0x0F
|
||||||
|
offset += GN_BASIC_HEADER_LEN
|
||||||
|
|
||||||
|
var limit = frameLen
|
||||||
|
var envelopeEnd = -1
|
||||||
|
var signed = false
|
||||||
|
if (basicNextHeader == GN_NEXT_HEADER_SECURED) {
|
||||||
|
val (inner, end, isSigned) = unwrapSecured(frame, offset, frameLen) ?: return null
|
||||||
|
offset = inner
|
||||||
|
envelopeEnd = end
|
||||||
|
signed = isSigned
|
||||||
|
if (envelopeEnd < limit) limit = envelopeEnd
|
||||||
|
} else if (basicNextHeader != GN_NEXT_HEADER_COMMON) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (limit < offset + GN_COMMON_HEADER_LEN) return null
|
||||||
|
val nextHeader = (frame.u8(offset) shr 4) and 0x0F
|
||||||
|
val headerType = (frame.u8(offset + 1) shr 4) and 0x0F
|
||||||
|
val headerSubtype = frame.u8(offset + 1) and 0x0F
|
||||||
|
val gnPayloadLen = frame.be16(offset + GN_COMMON_PAYLOAD_LEN_OFFSET)
|
||||||
|
if (nextHeader != GN_COMMON_NEXT_HEADER_BTP_B) return null
|
||||||
|
offset += GN_COMMON_HEADER_LEN
|
||||||
|
|
||||||
|
val extLen: Int
|
||||||
|
var isGbc = false
|
||||||
|
if (headerType == GN_HEADER_TYPE_TSB && headerSubtype == GN_HEADER_SUBTYPE_SINGLE_HOP) {
|
||||||
|
extLen = GN_SHB_EXT_HEADER_LEN
|
||||||
|
} else if (headerType == GN_HEADER_TYPE_GBC) {
|
||||||
|
extLen = GN_GBC_EXT_HEADER_LEN
|
||||||
|
isGbc = true
|
||||||
|
} else {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (limit < offset + extLen) return null
|
||||||
|
var areaLat = 0
|
||||||
|
var areaLon = 0
|
||||||
|
var areaDist = 0
|
||||||
|
if (isGbc) {
|
||||||
|
areaLat = frame.be32(offset + GBC_AREA_LAT_OFFSET)
|
||||||
|
areaLon = frame.be32(offset + GBC_AREA_LON_OFFSET)
|
||||||
|
areaDist = frame.be16(offset + GBC_AREA_DIST_A_OFFSET)
|
||||||
|
}
|
||||||
|
offset += extLen
|
||||||
|
|
||||||
|
if (limit < offset + BTP_B_HEADER_LEN) return null
|
||||||
|
val destPort = frame.be16(offset)
|
||||||
|
if (destPort !in BTP_PORTS) return null
|
||||||
|
|
||||||
|
if (gnPayloadLen <= BTP_B_HEADER_LEN) return null
|
||||||
|
val payloadStart = offset + BTP_B_HEADER_LEN
|
||||||
|
val payloadEnd = offset + gnPayloadLen
|
||||||
|
if (envelopeEnd >= 0 && payloadEnd > envelopeEnd) return null
|
||||||
|
val truncated = payloadEnd > frameLen
|
||||||
|
val payloadLen = (if (truncated) frameLen else payloadEnd) - payloadStart
|
||||||
|
if (payloadLen <= 0) return null
|
||||||
|
|
||||||
|
return Result(
|
||||||
|
btpPort = destPort,
|
||||||
|
payload = frame.copyOfRange(payloadStart, payloadStart + payloadLen),
|
||||||
|
hasGeoArea = isGbc,
|
||||||
|
areaLatTenMicroDeg = areaLat,
|
||||||
|
areaLonTenMicroDeg = areaLon,
|
||||||
|
areaDistanceAMeters = areaDist,
|
||||||
|
signedUnverified = signed,
|
||||||
|
truncated = truncated,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `V2X_RX` body for [result] (the layout [V2xRxFrame.parse] reads and the firmware's
|
||||||
|
* `encode_v2x_rx` writes): `u16 port, i8 rssi, u8 flags (bit 0 GBC area, bit 1 signed), i32 lat,
|
||||||
|
* i32 lon, u16 distance_a, payload`. Null for a truncated message, which must not be forwarded.
|
||||||
|
*/
|
||||||
|
fun toV2xRxBody(result: Result, rssiDbm: Int): ByteArray? {
|
||||||
|
if (result.truncated || result.payload.isEmpty()) return null
|
||||||
|
val out = java.io.ByteArrayOutputStream(V2xRxFrame.PREFIX_SIZE + result.payload.size)
|
||||||
|
fun u8(v: Int) = out.write(v and 0xFF)
|
||||||
|
fun u16(v: Int) { u8(v); u8(v shr 8) }
|
||||||
|
fun i32(v: Int) { u16(v); u16(v shr 16) }
|
||||||
|
u16(result.btpPort)
|
||||||
|
u8(rssiDbm.coerceIn(-128, 127))
|
||||||
|
u8((if (result.hasGeoArea) 0x01 else 0) or (if (result.signedUnverified) 0x02 else 0))
|
||||||
|
i32(result.areaLatTenMicroDeg)
|
||||||
|
i32(result.areaLonTenMicroDeg)
|
||||||
|
u16(result.areaDistanceAMeters)
|
||||||
|
out.write(result.payload)
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package com.hawhamburg.micr0bu.data.transport
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reassembles fragmented station-link messages (docs/station-link.pdf, "Fragmented messages").
|
||||||
|
*
|
||||||
|
* A body too large for one transport message is split in order, every fragment carrying the same
|
||||||
|
* opcode and sequence and `flags` 1 (first), 2 (middle) or 3 (last). Each fragment's body starts with
|
||||||
|
* `total_length u16` and `body_offset u16`, then the data. The complete body is handed on once the
|
||||||
|
* last fragment brings it to exactly `total_length`.
|
||||||
|
*
|
||||||
|
* Validation follows the spec: gaps, duplicates, wrong order and a changed total drop the stream;
|
||||||
|
* an unfinished stream is discarded after [IDLE_TIMEOUT_MS] of silence; at most [MAX_PENDING] streams
|
||||||
|
* are held; a complete body is at most [MAX_BODY] octets (the largest station-to-host indication).
|
||||||
|
*
|
||||||
|
* One instance per link session (USB and BLE keep separate streams in the spec; the app uses one
|
||||||
|
* transport at a time and starts a new instance when the session restarts).
|
||||||
|
*/
|
||||||
|
class LinkReassembly(private val nowMs: () -> Long = { System.currentTimeMillis() }) {
|
||||||
|
|
||||||
|
private class Stream(val opcode: Int, val sequence: Int, val total: Int, var lastMs: Long) {
|
||||||
|
val bytes = java.io.ByteArrayOutputStream()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val streams = ArrayList<Stream>()
|
||||||
|
|
||||||
|
/** Fragments dropped for any validation reason since this instance was created. */
|
||||||
|
var dropped: Int = 0
|
||||||
|
private set
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feeds one received message. Returns it unchanged when it is complete (`flags` 0), the
|
||||||
|
* reassembled message (`flags` 0) when [message] was the last fragment, and null otherwise.
|
||||||
|
*/
|
||||||
|
fun feed(message: LinkMessage): LinkMessage? {
|
||||||
|
val now = nowMs()
|
||||||
|
streams.removeAll { now - it.lastMs > IDLE_TIMEOUT_MS }
|
||||||
|
if (message.flags == 0) {
|
||||||
|
// A complete message supersedes any unfinished stream with the same key.
|
||||||
|
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
val flags = message.flags
|
||||||
|
val body = message.body
|
||||||
|
if (flags > FLAG_LAST || body.size <= FRAGMENT_HEADER) return drop(message)
|
||||||
|
fun u16(i: Int) = (body[i].toInt() and 0xFF) or ((body[i + 1].toInt() and 0xFF) shl 8)
|
||||||
|
val total = u16(0)
|
||||||
|
val offset = u16(2)
|
||||||
|
val length = body.size - FRAGMENT_HEADER
|
||||||
|
if (total == 0 || total > MAX_BODY || offset + length > total) return drop(message)
|
||||||
|
// the last fragment ends exactly at the declared total, and only the last one does
|
||||||
|
if ((flags == FLAG_LAST) != (offset + length == total)) return drop(message)
|
||||||
|
|
||||||
|
var stream = streams.firstOrNull { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||||
|
if (flags == FLAG_FIRST) {
|
||||||
|
if (offset != 0) return drop(message)
|
||||||
|
stream?.let { streams.remove(it) } // a restarted stream replaces the old one
|
||||||
|
if (streams.size >= MAX_PENDING) return drop(message)
|
||||||
|
stream = Stream(message.opcode, message.sequence, total, now)
|
||||||
|
streams.add(stream)
|
||||||
|
} else if (stream == null) {
|
||||||
|
return drop(message) // a middle or last fragment without a first
|
||||||
|
}
|
||||||
|
if (stream.total != total || stream.bytes.size() != offset) {
|
||||||
|
streams.remove(stream) // changed total, a gap or a duplicate
|
||||||
|
return drop(message)
|
||||||
|
}
|
||||||
|
stream.bytes.write(body, FRAGMENT_HEADER, length)
|
||||||
|
stream.lastMs = now
|
||||||
|
if (flags != FLAG_LAST) return null
|
||||||
|
streams.remove(stream)
|
||||||
|
return LinkMessage(message.opcode, message.sequence, stream.bytes.toByteArray(), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forgets every unfinished stream (a new session, a reconnect). */
|
||||||
|
fun reset() = streams.clear()
|
||||||
|
|
||||||
|
private fun drop(message: LinkMessage): LinkMessage? {
|
||||||
|
dropped++
|
||||||
|
streams.removeAll { it.opcode == message.opcode && it.sequence == message.sequence }
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val FLAG_FIRST = 1
|
||||||
|
const val FLAG_MIDDLE = 2
|
||||||
|
const val FLAG_LAST = 3
|
||||||
|
const val FRAGMENT_HEADER = 4
|
||||||
|
const val IDLE_TIMEOUT_MS = 2_000L
|
||||||
|
const val MAX_PENDING = 8
|
||||||
|
const val MAX_BODY = 65_535
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.hawhamburg.micr0bu.data.transport
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Body of the station-link `RAW_FRAME` (0x85, docs/station-link.pdf, "Raw capture"): a debug copy of
|
||||||
|
* a radio frame the station received (or, with the own-transmission option, sent).
|
||||||
|
*
|
||||||
|
* u32 counter, u8 flags (bit 0 own transmission, bit 1 UTC time stamp), i8 rssi,
|
||||||
|
* ITS5 record: "ITS5", u32 seconds, u32 microseconds, u16 frame_length, frame[frame_length]
|
||||||
|
*
|
||||||
|
* The frame is the 802.11 MPDU without its FCS. [GnUnwrap] turns it into the ITS message.
|
||||||
|
*/
|
||||||
|
data class RawFrame(
|
||||||
|
val counter: Long,
|
||||||
|
val ownTransmission: Boolean,
|
||||||
|
/** The record time is UTC (the station's clock was synchronised) rather than time since boot. */
|
||||||
|
val utcTime: Boolean,
|
||||||
|
val rssiDbm: Int,
|
||||||
|
val seconds: Long,
|
||||||
|
val microseconds: Long,
|
||||||
|
val frame: ByteArray,
|
||||||
|
) {
|
||||||
|
override fun equals(other: Any?): Boolean = other is RawFrame && counter == other.counter &&
|
||||||
|
ownTransmission == other.ownTransmission && utcTime == other.utcTime && rssiDbm == other.rssiDbm &&
|
||||||
|
seconds == other.seconds && microseconds == other.microseconds && frame.contentEquals(other.frame)
|
||||||
|
|
||||||
|
override fun hashCode(): Int = 31 * counter.hashCode() + frame.contentHashCode()
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** `[counter 4][flags 1][rssi 1]` before the record, `["ITS5" 4][sec 4][usec 4][len 2]` in it. */
|
||||||
|
const val HEADER_SIZE = 6 + 14
|
||||||
|
|
||||||
|
private val MAGIC = byteArrayOf('I'.code.toByte(), 'T'.code.toByte(), 'S'.code.toByte(), '5'.code.toByte())
|
||||||
|
|
||||||
|
/** Returns null for a body that is not a well-formed RAW_FRAME (short, wrong magic, bad length). */
|
||||||
|
fun parse(body: ByteArray): RawFrame? {
|
||||||
|
if (body.size < HEADER_SIZE) return null
|
||||||
|
for (i in 0 until 4) if (body[6 + i] != MAGIC[i]) return null
|
||||||
|
fun u8(i: Int) = body[i].toInt() and 0xFF
|
||||||
|
fun u16(i: Int) = u8(i) or (u8(i + 1) shl 8)
|
||||||
|
fun u32(i: Int) = (u16(i).toLong()) or (u16(i + 2).toLong() shl 16)
|
||||||
|
val length = u16(18)
|
||||||
|
if (body.size != HEADER_SIZE + length) return null
|
||||||
|
val flags = u8(4)
|
||||||
|
return RawFrame(
|
||||||
|
counter = u32(0),
|
||||||
|
ownTransmission = (flags and 0x01) != 0,
|
||||||
|
utcTime = (flags and 0x02) != 0,
|
||||||
|
rssiDbm = body[5].toInt(),
|
||||||
|
seconds = u32(10),
|
||||||
|
microseconds = u32(14),
|
||||||
|
frame = body.copyOfRange(HEADER_SIZE, body.size),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,8 +32,12 @@ object LinkOpcode {
|
|||||||
const val CREDENTIALS_PROVISION = 0x04
|
const val CREDENTIALS_PROVISION = 0x04
|
||||||
const val CREDENTIALS_ERASE = 0x05
|
const val CREDENTIALS_ERASE = 0x05
|
||||||
const val STATUS_REQUEST = 0x0C
|
const val STATUS_REQUEST = 0x0C
|
||||||
|
/** Debug path: body is one mode octet (bit 0 on, bit 1 broadcast only, bit 2 own transmissions); 0 switches it off. */
|
||||||
|
const val RAW_CAPTURE = 0x0D
|
||||||
const val CONFIRM = 0x80
|
const val CONFIRM = 0x80
|
||||||
const val BTP_DATA_INDICATION = 0x81
|
const val BTP_DATA_INDICATION = 0x81
|
||||||
|
/** Raw 802.11 frame copy of the RAW_CAPTURE debug path, fragmented when large: see [RawFrame]. */
|
||||||
|
const val RAW_FRAME = 0x85
|
||||||
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
|
/** MicrOBU extension: body is exactly the old [SerialFrameType.V2X_RX] payload ([V2xRxFrame]). 0x85 is the spec's RAW_FRAME, 0x86 reserved. */
|
||||||
const val V2X_RX = 0x90
|
const val V2X_RX = 0x90
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.core.os.LocaleListCompat
|
import androidx.core.os.LocaleListCompat
|
||||||
import com.hawhamburg.micr0bu.R
|
import com.hawhamburg.micr0bu.R
|
||||||
import com.hawhamburg.micr0bu.data.mqtt.MqttPrefs
|
import com.hawhamburg.micr0bu.data.mqtt.MqttPrefs
|
||||||
|
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||||
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
import com.hawhamburg.micr0bu.data.transport.ObuHardware
|
||||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||||
@@ -171,6 +172,8 @@ fun ConnectionSettingsScreen(
|
|||||||
onEsp32TransportChange: (Esp32Transport) -> Unit = {},
|
onEsp32TransportChange: (Esp32Transport) -> Unit = {},
|
||||||
outgoingMessage: OutgoingMessage = OutgoingMessage.CAM,
|
outgoingMessage: OutgoingMessage = OutgoingMessage.CAM,
|
||||||
onOutgoingMessageChange: (OutgoingMessage) -> Unit = {},
|
onOutgoingMessageChange: (OutgoingMessage) -> Unit = {},
|
||||||
|
esp32RxPath: Esp32RxPath = Esp32RxPath.V2X_RX,
|
||||||
|
onEsp32RxPathChange: (Esp32RxPath) -> Unit = {},
|
||||||
signOutgoing: Boolean = true,
|
signOutgoing: Boolean = true,
|
||||||
onSignOutgoingChange: (Boolean) -> Unit = {},
|
onSignOutgoingChange: (Boolean) -> Unit = {},
|
||||||
onBack: () -> Unit,
|
onBack: () -> Unit,
|
||||||
@@ -248,6 +251,21 @@ fun ConnectionSettingsScreen(
|
|||||||
onSecond = { onOutgoingMessageChange(OutgoingMessage.VAM) },
|
onSecond = { onOutgoingMessageChange(OutgoingMessage.VAM) },
|
||||||
)
|
)
|
||||||
Divider()
|
Divider()
|
||||||
|
TwoWayChoice(
|
||||||
|
label = stringResource(R.string.settings_esp32_rx_path),
|
||||||
|
first = stringResource(R.string.settings_esp32_rx_v2x),
|
||||||
|
second = stringResource(R.string.settings_esp32_rx_raw),
|
||||||
|
firstSelected = esp32RxPath == Esp32RxPath.V2X_RX,
|
||||||
|
onFirst = { onEsp32RxPathChange(Esp32RxPath.V2X_RX) },
|
||||||
|
onSecond = { onEsp32RxPathChange(Esp32RxPath.RAW_FRAME) },
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(if (esp32RxPath == Esp32RxPath.V2X_RX) R.string.settings_esp32_rx_v2x_note else R.string.settings_esp32_rx_raw_note),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(bottom = 8.dp),
|
||||||
|
)
|
||||||
|
Divider()
|
||||||
SettingToggleRow(
|
SettingToggleRow(
|
||||||
label = stringResource(R.string.settings_esp32_sign),
|
label = stringResource(R.string.settings_esp32_sign),
|
||||||
checked = signOutgoing,
|
checked = signOutgoing,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import com.hawhamburg.micr0bu.data.transport.TransportType
|
|||||||
import com.hawhamburg.micr0bu.data.transport.UsbNetworkDetector
|
import com.hawhamburg.micr0bu.data.transport.UsbNetworkDetector
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
import com.hawhamburg.micr0bu.data.transport.Esp32Link
|
||||||
|
import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
|
||||||
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
import com.hawhamburg.micr0bu.data.transport.Esp32Transport
|
||||||
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
||||||
import com.hawhamburg.micr0bu.data.transport.StationStatus
|
import com.hawhamburg.micr0bu.data.transport.StationStatus
|
||||||
@@ -117,6 +118,13 @@ class MqttViewModel @Inject constructor(
|
|||||||
viewModelScope.launch { obuHardwarePrefs.setOutgoingMessage(message) }
|
viewModelScope.launch { obuHardwarePrefs.setOutgoingMessage(message) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val esp32RxPath: StateFlow<Esp32RxPath> = obuHardwarePrefs.esp32RxPathFlow
|
||||||
|
.stateIn(viewModelScope, SharingStarted.Eagerly, Esp32RxPath.V2X_RX)
|
||||||
|
|
||||||
|
fun setEsp32RxPath(path: Esp32RxPath) {
|
||||||
|
viewModelScope.launch { obuHardwarePrefs.setEsp32RxPath(path) }
|
||||||
|
}
|
||||||
|
|
||||||
val signOutgoing: StateFlow<Boolean> = obuHardwarePrefs.signOutgoingFlow
|
val signOutgoing: StateFlow<Boolean> = obuHardwarePrefs.signOutgoingFlow
|
||||||
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
||||||
|
|
||||||
|
|||||||
@@ -323,7 +323,12 @@
|
|||||||
<string name="v2x_spat_countdown">%1$.0f s</string>
|
<string name="v2x_spat_countdown">%1$.0f s</string>
|
||||||
<string name="settings_esp32_link">ESP32-C5-Verbindung</string>
|
<string name="settings_esp32_link">ESP32-C5-Verbindung</string>
|
||||||
<string name="settings_esp32_link_ble">Bluetooth</string>
|
<string name="settings_esp32_link_ble">Bluetooth</string>
|
||||||
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, wählt die App den stärksten. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
|
<string name="settings_esp32_link_ble_note">Beim ersten Verbinden wird das Koppeln mit micrOBU-XXXX angefragt: Passkey 123456 eingeben. Sind mehrere micrOBUs in der Nähe, zuerst das richtige in den Android-Bluetooth-Einstellungen koppeln. BLE teilt sich das Funk-Frontend mit ITS-G5; die Platine hält jedes ITS-G5-Paket aus den BLE-Verbindungsfenstern heraus.</string>
|
||||||
|
<string name="settings_esp32_rx_path">Empfangspfad</string>
|
||||||
|
<string name="settings_esp32_rx_v2x">V2X_RX</string>
|
||||||
|
<string name="settings_esp32_rx_raw">Rohframes</string>
|
||||||
|
<string name="settings_esp32_rx_v2x_note">Die Platine entpackt jedes empfangene Frame und sendet die fertige Nachricht, signiert oder nicht (MicrOBU-Erweiterung, bis 494 Byte). Klein und immer aktiv.</string>
|
||||||
|
<string name="settings_esp32_rx_raw_note">Debug: Die Platine sendet das ganze Funkframe (RAW_FRAME aus der Spezifikation, bei Bedarf fragmentiert) und die App entpackt es. Keine 494-Byte-Grenze, aber Frames können bei ausgelastetem Link verloren gehen und es braucht mehr Bandbreite, besonders über Bluetooth.</string>
|
||||||
<string name="settings_esp32_message">Senden während der Aufzeichnung</string>
|
<string name="settings_esp32_message">Senden während der Aufzeichnung</string>
|
||||||
<string name="settings_esp32_message_cam">CAM</string>
|
<string name="settings_esp32_message_cam">CAM</string>
|
||||||
<string name="settings_esp32_message_vam">VAM</string>
|
<string name="settings_esp32_message_vam">VAM</string>
|
||||||
|
|||||||
@@ -330,7 +330,12 @@
|
|||||||
<string name="trip_review_title">Trip Review</string>
|
<string name="trip_review_title">Trip Review</string>
|
||||||
<string name="settings_esp32_link">ESP32-C5 link</string>
|
<string name="settings_esp32_link">ESP32-C5 link</string>
|
||||||
<string name="settings_esp32_link_ble">Bluetooth</string>
|
<string name="settings_esp32_link_ble">Bluetooth</string>
|
||||||
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. If several micrOBUs are nearby the app picks the strongest one. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
|
<string name="settings_esp32_link_ble_note">The first connection asks to pair with micrOBU-XXXX: enter passkey 123456. With several micrOBUs nearby, pair the right one in Android\'s Bluetooth settings first. BLE shares the radio front end with ITS-G5; the board holds each ITS-G5 frame out of the BLE connection-event windows.</string>
|
||||||
|
<string name="settings_esp32_rx_path">Receive path</string>
|
||||||
|
<string name="settings_esp32_rx_v2x">V2X_RX</string>
|
||||||
|
<string name="settings_esp32_rx_raw">Raw frames</string>
|
||||||
|
<string name="settings_esp32_rx_v2x_note">The board unpacks every received frame and sends the finished message, signed or not (MicrOBU extension, up to 494 bytes). Small and always on.</string>
|
||||||
|
<string name="settings_esp32_rx_raw_note">Debug: the board sends the whole radio frame (the spec\'s RAW_FRAME, fragmented if large) and the app unpacks it. No 494-byte limit, but frames can be lost when the link is busy and it needs more bandwidth, especially over Bluetooth.</string>
|
||||||
<string name="settings_esp32_message">Transmit while recording</string>
|
<string name="settings_esp32_message">Transmit while recording</string>
|
||||||
<string name="settings_esp32_message_cam">CAM</string>
|
<string name="settings_esp32_message_cam">CAM</string>
|
||||||
<string name="settings_esp32_message_vam">VAM</string>
|
<string name="settings_esp32_message_vam">VAM</string>
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -86,6 +86,7 @@ firmware is what counts; the current spec table lists the same UUIDs).
|
|||||||
| phone → board | `STATUS_REQUEST` | once a second; the answer is the heartbeat |
|
| phone → board | `STATUS_REQUEST` | once a second; the answer is the heartbeat |
|
||||||
| board → phone | `CONFIRM` | answer to a request; for `STATUS_REQUEST` its detail is the 131-octet snapshot: counters, tickets, signed/refused counts, battery |
|
| board → phone | `CONFIRM` | answer to a request; for `STATUS_REQUEST` its detail is the 131-octet snapshot: counters, tickets, signed/refused counts, battery |
|
||||||
| board → phone | `V2X_RX` (0x90, MicrOBU) | every ITS message heard on air |
|
| board → phone | `V2X_RX` (0x90, MicrOBU) | every ITS message heard on air |
|
||||||
|
| board → phone | `RAW_FRAME` (0x85, spec) | debug copy of each radio frame, only while `RAW_CAPTURE` is on; the app can use it instead of `V2X_RX` (Settings > Receive path) |
|
||||||
|
|
||||||
The app side is `Esp32Link.kt` (session), `StationLink.kt` (codec, pinned by unit tests to bytes
|
The app side is `Esp32Link.kt` (session), `StationLink.kt` (codec, pinned by unit tests to bytes
|
||||||
from Niklas Dathe's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
|
from Niklas Dathe's Python implementation), `UsbSerialTransport.kt` and `BleLinkTransport.kt`.
|
||||||
@@ -95,6 +96,9 @@ spec retires but the station still decodes, and revision 2 documents): a ride ro
|
|||||||
pinger keeps one fixed MAC, and a new MAC reconfigures the station. Without one a signed station takes its address from the
|
pinger keeps one fixed MAC, and a new MAC reconfigures the station. Without one a signed station takes its address from the
|
||||||
ticket and an unsigned one draws a random MAC per configuration. With one, signed and unsigned frames both leave from it.
|
ticket and an unsigned one draws a random MAC per configuration. With one, signed and unsigned frames both leave from it.
|
||||||
|
|
||||||
|
The app also **reassembles fragmented link messages** (flags 1-3 of the spec) and has two receive paths: `V2X_RX`
|
||||||
|
(default) and `RAW_FRAME`, which it unwraps itself with `GnUnwrap.kt`; see the README for the comparison.
|
||||||
|
|
||||||
## Redundancy and recovery
|
## Redundancy and recovery
|
||||||
|
|
||||||
| Situation | What notices | What happens |
|
| Situation | What notices | What happens |
|
||||||
|
|||||||
@@ -101,6 +101,15 @@ eFuse-based gates, an on-device TS 102 941 client (enrolment and authorisation r
|
|||||||
update), the `RAW_CAPTURE` debug path, fragmentation of link messages, the XIAO and `mainboard-v5` boards, and the
|
update), the `RAW_CAPTURE` debug path, fragmentation of link messages, the XIAO and `mainboard-v5` boards, and the
|
||||||
battery reading.
|
battery reading.
|
||||||
|
|
||||||
|
### Both receive paths stay
|
||||||
|
|
||||||
|
`V2X_RX` (ours) and `RAW_FRAME` / `RAW_CAPTURE` (Niklas Dathe's, in the spec) both stay in the firmware, and the app has a switch
|
||||||
|
(Settings > Connection > ESP32-C5 > Receive path) that chooses which one it consumes. The firmware does not know which: it
|
||||||
|
always sends `V2X_RX`, and sends `RAW_FRAME` while `RAW_CAPTURE` is on (the app turns it on, mode 0x03, only in raw mode). In raw
|
||||||
|
mode the app unwraps the frame itself with `GnUnwrap.kt`, a port of `gn_unwrap.c` that `GnUnwrapTest` checks against the C code
|
||||||
|
on a corpus (`make corpus` in `test/host` writes `app/src/test/resources/gn_unwrap_corpus.tsv`). The app also reassembles
|
||||||
|
fragmented link messages as the spec defines them, so a raw frame or an indication above one link message works.
|
||||||
|
|
||||||
### Measured on the bench, 2026-11-11
|
### Measured on the bench, 2026-11-11
|
||||||
|
|
||||||
Production XIAO on COM10, Pixel 9 Pro on BLE, COM3 board as an on-air listener (details and open points in `TODO.md`):
|
Production XIAO on COM10, Pixel 9 Pro on BLE, COM3 board as an on-air listener (details and open points in `TODO.md`):
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ CFLAGS = -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW) -I. \
|
|||||||
FW_SRCS = $(FW)/geonet.c dot11p.c $(FW)/gn_unwrap.c
|
FW_SRCS = $(FW)/geonet.c dot11p.c $(FW)/gn_unwrap.c
|
||||||
DEPS = test_util.c test_util.h dot11p.h $(FW_SRCS) $(wildcard $(FW)/*.h)
|
DEPS = test_util.c test_util.h dot11p.h $(FW_SRCS) $(wildcard $(FW)/*.h)
|
||||||
|
|
||||||
.PHONY: all check chain replay fuzz battery firmware clean
|
.PHONY: all check chain replay fuzz battery firmware corpus clean
|
||||||
|
|
||||||
all: check
|
all: check
|
||||||
|
|
||||||
@@ -82,3 +82,14 @@ $(BUILD)/test_firmware$(EXE): test_firmware.cpp $(FW_CXX_SRCS) $(wildcard $(FW)/
|
|||||||
|
|
||||||
firmware: $(BUILD)/test_firmware$(EXE)
|
firmware: $(BUILD)/test_firmware$(EXE)
|
||||||
$(BUILD)/test_firmware$(EXE)
|
$(BUILD)/test_firmware$(EXE)
|
||||||
|
|
||||||
|
# Corpus for the app's GnUnwrapTest (the Kotlin port of gn_unwrap.c): recorded frames, cut and corrupted copies of
|
||||||
|
# them, with the verdict and fields of the firmware's own code. Writes ../../../app/src/test/resources/gn_unwrap_corpus.tsv
|
||||||
|
CORPUS_OUT = ../../../app/src/test/resources/gn_unwrap_corpus.tsv
|
||||||
|
|
||||||
|
$(BUILD)/dump_corpus$(EXE): dump_corpus.c test_util.c test_util.h $(FW)/gn_unwrap.c $(FW)/gn_unwrap.h | $(BUILD)
|
||||||
|
$(CC) $(CFLAGS) -o $@ dump_corpus.c test_util.c $(FW)/gn_unwrap.c
|
||||||
|
|
||||||
|
corpus: $(BUILD)/dump_corpus$(EXE)
|
||||||
|
mkdir -p $(dir $(CORPUS_OUT))
|
||||||
|
$(BUILD)/dump_corpus$(EXE) $(CORPUS_OUT) $(RECORDINGS)
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Writes a corpus for the app's GnUnwrapTest: frames from recorded captures, cut and corrupted copies of
|
||||||
|
// them, and what gn_unwrap_its (the firmware's own code) makes of each. The Kotlin port must give the
|
||||||
|
// same verdict and the same fields for every line.
|
||||||
|
//
|
||||||
|
// dump_corpus <out.tsv> <capture.pcap>...
|
||||||
|
//
|
||||||
|
// One line per frame, tab separated:
|
||||||
|
// frame hex | A (accepted) or R (rejected) | port | flags (bit 0 GBC area, bit 1 signed) |
|
||||||
|
// area lat | area lon | area distance A | truncated 0/1 | payload hex (empty when rejected)
|
||||||
|
//
|
||||||
|
// Selection is deterministic (fixed counts per category and a fixed-seed generator), so the file is
|
||||||
|
// reproducible. Build and run: `make corpus` in this folder.
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "gn_unwrap.h"
|
||||||
|
#include "test_util.h"
|
||||||
|
|
||||||
|
#define MAX_PER_CATEGORY 20
|
||||||
|
#define MAX_REJECTED 60
|
||||||
|
#define MAX_MUTATED 250
|
||||||
|
|
||||||
|
static FILE *out;
|
||||||
|
static unsigned rng_state = 12345u;
|
||||||
|
static int accepted_total, rejected_total, mutated_total, cut_total;
|
||||||
|
static int category_count[5 * 2 * 2 + 5]; // port index * 4 + signed * 2 + gbc
|
||||||
|
static int seen_accepted;
|
||||||
|
|
||||||
|
static unsigned rng(void) { rng_state = rng_state * 1664525u + 1013904223u; return rng_state >> 8; }
|
||||||
|
|
||||||
|
static int port_index(int port) {
|
||||||
|
switch (port) { case 2001: return 0; case 2002: return 1; case 2003: return 2; case 2004: return 3; default: return 4; }
|
||||||
|
}
|
||||||
|
|
||||||
|
static void emit(const uint8_t *frame, int len) {
|
||||||
|
gn_rx_t rx;
|
||||||
|
const bool ok = gn_unwrap_its(frame, len, &rx);
|
||||||
|
for (int i = 0; i < len; i++) fprintf(out, "%02x", frame[i]);
|
||||||
|
if (!ok) { fprintf(out, "\tR\t0\t0\t0\t0\t0\t0\t\n"); return; }
|
||||||
|
fprintf(out, "\tA\t%u\t%d\t%d\t%d\t%u\t%d\t", rx.btp_dest_port, (rx.has_geo_area ? 1 : 0) | (rx.signed_unverified ? 2 : 0),
|
||||||
|
(int)rx.geo_area_lat_tenmicrodeg, (int)rx.geo_area_lon_tenmicrodeg, (unsigned)rx.geo_area_distance_a_m,
|
||||||
|
rx.truncated ? 1 : 0);
|
||||||
|
for (int i = 0; i < rx.payload_len; i++) fprintf(out, "%02x", rx.payload[i]);
|
||||||
|
fprintf(out, "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_frame(const uint8_t *frame, int len, int index, void *ctx) {
|
||||||
|
(void)ctx; (void)index;
|
||||||
|
gn_rx_t rx;
|
||||||
|
if (!gn_unwrap_its(frame, len, &rx)) {
|
||||||
|
if (rejected_total < MAX_REJECTED && (rng() % 7) == 0) { emit(frame, len); ++rejected_total; }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
++seen_accepted;
|
||||||
|
const int cat = port_index(rx.btp_dest_port) * 4 + (rx.signed_unverified ? 2 : 0) + (rx.has_geo_area ? 1 : 0);
|
||||||
|
if (category_count[cat] < MAX_PER_CATEGORY) {
|
||||||
|
++category_count[cat];
|
||||||
|
emit(frame, len);
|
||||||
|
++accepted_total;
|
||||||
|
// a few cut copies: the frame ends inside the payload, inside the headers, and at odd places
|
||||||
|
const int cuts[] = {len - 3, len - 17, len / 2, len / 3, 40, 70};
|
||||||
|
for (unsigned c = 0; c < sizeof cuts / sizeof cuts[0]; c++)
|
||||||
|
if (cuts[c] > 0 && cuts[c] < len && (rng() % 3) == 0) { emit(frame, cuts[c]); ++cut_total; }
|
||||||
|
}
|
||||||
|
// corrupted copies of frames taken at a steady rate: a few flipped bytes, anywhere
|
||||||
|
if (mutated_total < MAX_MUTATED && (seen_accepted % 40) == 0) {
|
||||||
|
uint8_t *copy = malloc((size_t)len);
|
||||||
|
if (!copy) return;
|
||||||
|
memcpy(copy, frame, (size_t)len);
|
||||||
|
const int flips = 1 + (int)(rng() % 4);
|
||||||
|
for (int k = 0; k < flips; k++) copy[rng() % (unsigned)len] ^= (uint8_t)(1u << (rng() % 8));
|
||||||
|
emit(copy, len);
|
||||||
|
free(copy);
|
||||||
|
++mutated_total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
if (argc < 3) { fprintf(stderr, "usage: dump_corpus <out.tsv> <capture.pcap>...\n"); return 2; }
|
||||||
|
out = fopen(argv[1], "w");
|
||||||
|
if (!out) { perror(argv[1]); return 2; }
|
||||||
|
for (int i = 2; i < argc; i++) {
|
||||||
|
const int n = tu_pcap_foreach(argv[i], on_frame, NULL);
|
||||||
|
if (n < 0) { fprintf(stderr, "cannot read %s\n", argv[i]); return 2; }
|
||||||
|
}
|
||||||
|
fclose(out);
|
||||||
|
printf("corpus: %d accepted, %d cut, %d corrupted, %d rejected (of %d accepted frames seen)\n", accepted_total, cut_total,
|
||||||
|
mutated_total, rejected_total, seen_accepted);
|
||||||
|
for (int p = 0; p < 5; p++)
|
||||||
|
printf(" port index %d: unsigned SHB %d, unsigned GBC %d, signed SHB %d, signed GBC %d\n", p, category_count[p * 4],
|
||||||
|
category_count[p * 4 + 1], category_count[p * 4 + 2], category_count[p * 4 + 3]);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user