Compare commits
4
Commits
ecf16289a3
...
275d382a1d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
275d382a1d | ||
|
|
6fa91d1702 | ||
|
|
727c9116dd | ||
|
|
b4e3385721 |
@@ -5,6 +5,41 @@ Engineering to-do list. The reviewer-facing open items live in
|
|||||||
|
|
||||||
## Waiting on hardware
|
## Waiting on hardware
|
||||||
|
|
||||||
|
### Sensor fusion phase 0: yaw rate about the vertical, fix times on GNSS time (added 2026-11-18)
|
||||||
|
|
||||||
|
The phone's own CAM/VAM now take the yaw rate from the gyroscope projected onto gravity
|
||||||
|
(`domain/fusion/YawRateEstimator`, 100 ms average, gyro and gravity at `SENSOR_DELAY_GAME`) instead of
|
||||||
|
the raw z axis. They stamp the GNSS time of the fix itself, through its monotonic
|
||||||
|
`elapsedRealtimeNanos` (`GnssTimeSource.atElapsedRealtime`). The loop's own intervals (elevated rate, VAM
|
||||||
|
rules) run on `SystemClock.elapsedRealtime`. Unit-tested (`YawRateEstimatorTest`), not yet on the phone.
|
||||||
|
With the CAM pinger on and a listener that decodes yawRate:
|
||||||
|
|
||||||
|
- [ ] Turn the Pixel 9 Pro on an office chair at about 90°/s: flat, tilted about 50° as on the
|
||||||
|
handlebar, and upright. All three should read about the same yaw rate. The old z-axis value
|
||||||
|
fell to about 64 % tilted and to about 0 upright.
|
||||||
|
- [ ] Phone still on the desk: yaw rate stays inside the 1 °/s noise floor, so it goes out as 0.
|
||||||
|
- [ ] Set the phone's clock 10 minutes wrong by hand (automatic time off) with a GNSS fix: the CAM
|
||||||
|
generationDeltaTime and GN TST still match GNSS time. Then step the clock back mid-run: CAMs and
|
||||||
|
VAMs keep going at their rate, with no gap and no time_regression on the micrOBU.
|
||||||
|
- [ ] Ride with the phone on the handlebar, then in a bag: the yaw rate's sign and size match the
|
||||||
|
turns (left and right, roundabout).
|
||||||
|
- [ ] Yaw rate sign on air (fixed 2026-11-18: `CamUperCodec` and `CamParser` now flip the ETSI/CiT
|
||||||
|
left-positive value into the app's clockwise-positive one). Turn the pinging phone left: a
|
||||||
|
standard decoder (asn1tools, or the CiT One's `v2x-uca/output/json/cam`) shows a positive
|
||||||
|
YawRateValue, and the app's own decode of the same CAM reads a negative yaw rate (left, in the
|
||||||
|
app's clockwise-positive convention).
|
||||||
|
The logs in `databases/` (not committed) already settled the CiT One side: its CAM topic is
|
||||||
|
left-positive (316 of 316 turning samples), its `obu_gnss` `yawRate_degps` right-positive
|
||||||
|
despite the API document (27 of 27, bacospat ride of 2026-03-18). Only 27 samples from one
|
||||||
|
ride: re-check on the next CiT One ride with turns.
|
||||||
|
- [ ] CiT One JSON parsers (fixed 2026-11-18): `ObuGnssParser` returned null for every real `obu_gnss`
|
||||||
|
message (position is under `gnss`, it read `own_info`), and `CamParser` for every real CAM-topic
|
||||||
|
message (`stationType` is a name). So on the CiT One the ego state never came from `obu_gnss`,
|
||||||
|
the app's V2X logger wrote no OBU fixes, and the processed CAM fallback was dead. On the next
|
||||||
|
CiT One session: the use-case engine runs on `obu_gnss` (the phone GNSS fallback only kicks in
|
||||||
|
after 2.5 s without it), the own station ID is learned so own CAMs stop showing as remote, and
|
||||||
|
the V2X log has `obu` rows in its `gnss` table.
|
||||||
|
|
||||||
### obu-firmware on Niklas Dathe's microbu-firmware (added 2026-11-10, bench run 2026-11-11)
|
### obu-firmware on Niklas Dathe's microbu-firmware (added 2026-11-10, bench run 2026-11-11)
|
||||||
|
|
||||||
Flashed on the production XIAO (COM10) and the phone (Pixel 9 Pro, BLE) on 2026-11-11. Done, by hand
|
Flashed on the production XIAO (COM10) and the phone (Pixel 9 Pro, BLE) on 2026-11-11. Done, by hand
|
||||||
@@ -25,6 +60,8 @@ Still open:
|
|||||||
|
|
||||||
- [x] Receive path switch (2026-11-11, over BLE): `Raw frames` gave `RAW_CAPTURE mode 3 -> accepted` and the simulated car kept
|
- [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.
|
arriving through the app's own unwrapper; back to `V2X_RX` gave mode 0 and it kept arriving.
|
||||||
|
- [x] V2X data logger on both receive paths (2026-11-11, 33 s each, the simulated car): `V2X_RX` 103 CAMs, `Raw frames` 106 CAMs; the logger
|
||||||
|
listens to the same decoded frames for both, so it needs no change. It stores the decoded message, not the radio frame.
|
||||||
- [ ] Fragmentation on air: a RAW_FRAME above one link message (a large MAPEM or SPATEM from a road RSU) reassembled in the
|
- [ ] 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.
|
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.
|
- [ ] Count both paths on the same traffic to see how many frames the raw copy drops on a busy link.
|
||||||
|
|||||||
@@ -58,6 +58,20 @@ object GnssTimeSource {
|
|||||||
return ItsTime.onGnssTime(systemMs, lastErrorMs?.let { systemNow + it }, systemNow)
|
return ItsTime.onGnssTime(systemMs, lastErrorMs?.let { systemNow + it }, systemNow)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GNSS time of an instant given on the monotonic `elapsedRealtimeNanos` base, such as a fix's
|
||||||
|
* [GnssReading.elapsedRealtimeNanos]: GNSS time now, minus the instant's age.
|
||||||
|
*
|
||||||
|
* Prefer this to [correct] on a stored wall-clock stamp. The age comes from the monotonic
|
||||||
|
* clock, and the wall clock is only read now, inside [correct], where its error cancels out.
|
||||||
|
* A phone clock that is stepped between the fix and its transmission (automatic time catching
|
||||||
|
* up, or someone setting it) therefore cannot move the result.
|
||||||
|
*/
|
||||||
|
fun atElapsedRealtime(elapsedRealtimeNanos: Long): Long {
|
||||||
|
val ageMs = (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
|
||||||
|
return correct(System.currentTimeMillis() - ageMs)
|
||||||
|
}
|
||||||
|
|
||||||
private fun noteSource(gnssNow: Long?, systemNow: Long) {
|
private fun noteSource(gnssNow: Long?, systemNow: Long) {
|
||||||
val usingGnss = gnssNow != null
|
val usingGnss = gnssNow != null
|
||||||
if (lastUsedGnss == usingGnss) return
|
if (lastUsedGnss == usingGnss) return
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import android.hardware.SensorEvent
|
|||||||
import android.hardware.SensorEventListener
|
import android.hardware.SensorEventListener
|
||||||
import android.hardware.SensorManager
|
import android.hardware.SensorManager
|
||||||
import android.location.Location
|
import android.location.Location
|
||||||
|
import android.os.SystemClock
|
||||||
import com.google.android.gms.location.LocationCallback
|
import com.google.android.gms.location.LocationCallback
|
||||||
import com.google.android.gms.location.LocationRequest
|
import com.google.android.gms.location.LocationRequest
|
||||||
import com.google.android.gms.location.LocationResult
|
import com.google.android.gms.location.LocationResult
|
||||||
@@ -15,13 +16,35 @@ import kotlinx.coroutines.channels.awaitClose
|
|||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.callbackFlow
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One sample of a three-axis sensor.
|
||||||
|
*
|
||||||
|
* @property timestamp wall-clock ms of the moment the sample was taken (not of its delivery), for
|
||||||
|
* logs and the UI, which compare it with other wall-clock stamps.
|
||||||
|
* @property elapsedRealtimeNanos the sample's own `SensorEvent.timestamp`, on the
|
||||||
|
* `SystemClock.elapsedRealtimeNanos` base. Monotonic: use it for intervals and for lining samples
|
||||||
|
* up with GNSS fixes, never [timestamp], which jumps whenever the phone's clock is set.
|
||||||
|
*/
|
||||||
data class ImuReading(
|
data class ImuReading(
|
||||||
val x: Float,
|
val x: Float,
|
||||||
val y: Float,
|
val y: Float,
|
||||||
val z: Float,
|
val z: Float,
|
||||||
val timestamp: Long = System.currentTimeMillis()
|
val timestamp: Long = System.currentTimeMillis(),
|
||||||
|
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One location fix.
|
||||||
|
*
|
||||||
|
* @property timestamp wall-clock ms of the moment of the fix (not of its delivery), for in-app
|
||||||
|
* comparisons with other wall-clock stamps. What goes on air is GNSS time instead, from
|
||||||
|
* [GnssTimeSource.atElapsedRealtime] on [elapsedRealtimeNanos].
|
||||||
|
* @property elapsedRealtimeNanos `Location.getElapsedRealtimeNanos()`: the moment of the fix on the
|
||||||
|
* monotonic clock that sensor samples are also stamped with. Use it for intervals between fixes.
|
||||||
|
* @property speedAccuracyMps 1-sigma speed accuracy, null when the provider gives none.
|
||||||
|
* @property bearingAccuracyDeg 1-sigma bearing accuracy, null when the provider gives none.
|
||||||
|
* @property provider the location provider that produced the fix, e.g. "fused" or "gps".
|
||||||
|
*/
|
||||||
data class GnssReading(
|
data class GnssReading(
|
||||||
val latitude: Double,
|
val latitude: Double,
|
||||||
val longitude: Double,
|
val longitude: Double,
|
||||||
@@ -29,7 +52,11 @@ data class GnssReading(
|
|||||||
val speedMs: Float,
|
val speedMs: Float,
|
||||||
val bearingDeg: Float,
|
val bearingDeg: Float,
|
||||||
val accuracyM: Float,
|
val accuracyM: Float,
|
||||||
val timestamp: Long = System.currentTimeMillis()
|
val timestamp: Long = System.currentTimeMillis(),
|
||||||
|
val elapsedRealtimeNanos: Long = SystemClock.elapsedRealtimeNanos(),
|
||||||
|
val speedAccuracyMps: Float? = null,
|
||||||
|
val bearingAccuracyDeg: Float? = null,
|
||||||
|
val provider: String? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
class SensorRepository(private val context: Context) {
|
class SensorRepository(private val context: Context) {
|
||||||
@@ -37,12 +64,30 @@ class SensorRepository(private val context: Context) {
|
|||||||
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||||
private val fusedLocation = LocationServices.getFusedLocationProviderClient(context)
|
private val fusedLocation = LocationServices.getFusedLocationProviderClient(context)
|
||||||
|
|
||||||
fun accelerometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_ACCELEROMETER)
|
/**
|
||||||
|
* @param samplingPeriodUs a `SensorManager.SENSOR_DELAY_*` constant or a period in µs. The
|
||||||
|
* default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
|
||||||
|
*/
|
||||||
|
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
|
||||||
|
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
|
||||||
|
|
||||||
fun gyroscopeFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_GYROSCOPE)
|
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
|
||||||
|
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs)
|
||||||
|
|
||||||
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
|
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gravity in the device frame, m/s². Points up (it reads +9.81 on z with the phone flat, screen
|
||||||
|
* up), as the accelerometer does at rest.
|
||||||
|
*
|
||||||
|
* From the platform's `TYPE_GRAVITY` virtual sensor, which separates gravity from motion with
|
||||||
|
* the gyroscope. On a phone without it the raw accelerometer stands in, which still carries
|
||||||
|
* the bike's own accelerations and vibration.
|
||||||
|
*/
|
||||||
|
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
|
||||||
|
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs)
|
||||||
|
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
|
||||||
|
|
||||||
fun barometerFlow(): Flow<Float> = callbackFlow {
|
fun barometerFlow(): Flow<Float> = callbackFlow {
|
||||||
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
|
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
|
||||||
if (sensor == null) {
|
if (sensor == null) {
|
||||||
@@ -77,7 +122,10 @@ class SensorRepository(private val context: Context) {
|
|||||||
|
|
||||||
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
|
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
|
||||||
|
|
||||||
private fun sensorFlow(type: Int): Flow<ImuReading> = callbackFlow {
|
private fun sensorFlow(
|
||||||
|
type: Int,
|
||||||
|
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
|
||||||
|
): Flow<ImuReading> = callbackFlow {
|
||||||
val sensor = sensorManager.getDefaultSensor(type)
|
val sensor = sensorManager.getDefaultSensor(type)
|
||||||
if (sensor == null) {
|
if (sensor == null) {
|
||||||
close()
|
close()
|
||||||
@@ -85,20 +133,42 @@ class SensorRepository(private val context: Context) {
|
|||||||
}
|
}
|
||||||
val listener = object : SensorEventListener {
|
val listener = object : SensorEventListener {
|
||||||
override fun onSensorChanged(event: SensorEvent) {
|
override fun onSensorChanged(event: SensorEvent) {
|
||||||
trySend(ImuReading(event.values[0], event.values[1], event.values[2]))
|
trySend(ImuReading(
|
||||||
|
x = event.values[0],
|
||||||
|
y = event.values[1],
|
||||||
|
z = event.values[2],
|
||||||
|
timestamp = wallClockMsAt(event.timestamp),
|
||||||
|
elapsedRealtimeNanos = event.timestamp,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
|
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
|
||||||
}
|
}
|
||||||
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
|
sensorManager.registerListener(listener, sensor, samplingPeriodUs)
|
||||||
awaitClose { sensorManager.unregisterListener(listener) }
|
awaitClose { sensorManager.unregisterListener(listener) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Location.toReading() = GnssReading(
|
/**
|
||||||
|
* The wall-clock ms of an instant given on the `elapsedRealtimeNanos` base: now minus its age.
|
||||||
|
* Both clocks are read together, so a clock change only moves the result by the change itself.
|
||||||
|
*/
|
||||||
|
private fun wallClockMsAt(elapsedRealtimeNanos: Long): Long =
|
||||||
|
System.currentTimeMillis() - (SystemClock.elapsedRealtimeNanos() - elapsedRealtimeNanos) / 1_000_000L
|
||||||
|
|
||||||
|
private fun Location.toReading(): GnssReading {
|
||||||
|
// A fix without its own monotonic stamp (0, as some mock providers leave it) is taken as now.
|
||||||
|
val fixNanos = elapsedRealtimeNanos.takeIf { it > 0L } ?: SystemClock.elapsedRealtimeNanos()
|
||||||
|
return GnssReading(
|
||||||
latitude = latitude,
|
latitude = latitude,
|
||||||
longitude = longitude,
|
longitude = longitude,
|
||||||
altitude = altitude,
|
altitude = altitude,
|
||||||
speedMs = speed,
|
speedMs = speed,
|
||||||
bearingDeg = bearing,
|
bearingDeg = bearing,
|
||||||
accuracyM = accuracy
|
accuracyM = accuracy,
|
||||||
)
|
timestamp = wallClockMsAt(fixNanos),
|
||||||
|
elapsedRealtimeNanos = fixNanos,
|
||||||
|
speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond else null,
|
||||||
|
bearingAccuracyDeg = if (hasBearingAccuracy()) bearingAccuracyDegrees else null,
|
||||||
|
provider = provider,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -144,8 +144,11 @@ object CamUperCodec {
|
|||||||
bw.putBits(0, 1) // extension bit: value is in the root list
|
bw.putBits(0, 1) // extension bit: value is in the root list
|
||||||
bw.putBits(2, 2) // curvatureCalculationMode: unavailable(2)
|
bw.putBits(2, 2) // curvatureCalculationMode: unavailable(2)
|
||||||
|
|
||||||
|
// YawRateValue is positive to the LEFT (degSec-000-01ToLeft(1), TS 102 894-2), the opposite
|
||||||
|
// of Cam.yawRateDps (positive clockwise, i.e. to the right). Until 2026-11-18 neither side
|
||||||
|
// negated, so every CAM this phone sent turned the wrong way for a standard receiver.
|
||||||
val yawRateCentiDegS = cam.yawRateDps
|
val yawRateCentiDegS = cam.yawRateDps
|
||||||
?.let { (it * 100.0).roundToInt().coerceIn(-32766, 32766) }
|
?.let { (-it * 100.0).roundToInt().coerceIn(-32766, 32766) }
|
||||||
?: YAW_RATE_UNAVAILABLE
|
?: YAW_RATE_UNAVAILABLE
|
||||||
bw.putBits(yawRateCentiDegS - (-32766), 16)
|
bw.putBits(yawRateCentiDegS - (-32766), 16)
|
||||||
// YawRateConfidence has NINE enumerands (degSec-000-01(0) .. unavailable(8), see
|
// YawRateConfidence has NINE enumerands (degSec-000-01(0) .. unavailable(8), see
|
||||||
@@ -306,7 +309,8 @@ object CamUperCodec {
|
|||||||
|
|
||||||
val yawRateRaw = br.getBitsInt(16) + (-32766)
|
val yawRateRaw = br.getBitsInt(16) + (-32766)
|
||||||
br.getBits(4) // yawRateConfidence: 9 enumerands -> 4 bits, see the note in encode()
|
br.getBits(4) // yawRateConfidence: 9 enumerands -> 4 bits, see the note in encode()
|
||||||
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else yawRateRaw / 100.0
|
// Left-positive on air, clockwise-positive in Cam: negate, as encode() does.
|
||||||
|
val yawRateDps = if (yawRateRaw == YAW_RATE_UNAVAILABLE) null else -yawRateRaw / 100.0
|
||||||
|
|
||||||
// Everything after yawRate is deliberately left unread: the 7 optional high-frequency
|
// Everything after yawRate is deliberately left unread: the 7 optional high-frequency
|
||||||
// fields, then lowFrequencyContainer (vehicleRole / exteriorLights / pathHistory), then
|
// fields, then lowFrequencyContainer (vehicleRole / exteriorLights / pathHistory), then
|
||||||
|
|||||||
@@ -14,6 +14,20 @@ object StationType {
|
|||||||
* is 15 and not 12 - mapping by list position mislabels every RSU.
|
* is 15 and not 12 - mapping by list position mislabels every RSU.
|
||||||
*/
|
*/
|
||||||
const val ROAD_SIDE_UNIT = 15
|
const val ROAD_SIDE_UNIT = 15
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Use Case API's `stationType` string enum ("passengerCar") mapped to its ITS-G5 integer,
|
||||||
|
* per StationType in the ETSI CDD (CiT MQTT API v6, sections 2.1.1 and 2.2.3). Mapped by name,
|
||||||
|
* never by list position, because of the gap before [ROAD_SIDE_UNIT].
|
||||||
|
*/
|
||||||
|
private val BY_API_NAME = mapOf(
|
||||||
|
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
|
||||||
|
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
|
||||||
|
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The ITS-G5 integer for an API station type name, or null for a blank or unknown name. */
|
||||||
|
fun fromApiName(name: String?): Int? = name?.takeIf { it.isNotBlank() }?.let { BY_API_NAME[it] }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,8 +59,13 @@ data class Cam(
|
|||||||
val headingDeg: Double,
|
val headingDeg: Double,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Yaw rate, degrees per second, where available (positive = turning clockwise).
|
* Yaw rate, degrees per second, where available (positive = turning clockwise, to the right,
|
||||||
* Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and `v2x-uca/output/json/cam` (remote).
|
* like [headingDeg] increasing). Carried by both `v2x/rx/obu_gnss` (ego, ~4 Hz) and
|
||||||
|
* `v2x-uca/output/json/cam` (remote).
|
||||||
|
*
|
||||||
|
* The CAM's YawRateValue and the CiT One's CAM topic count the other way, positive to the
|
||||||
|
* left, so `CamUperCodec` and `CamParser` flip the sign. The CiT One's `obu_gnss` topic is
|
||||||
|
* already positive to the right in practice, despite its document, so `ObuGnssParser` does not.
|
||||||
* A much more direct "is this road user turning" signal than heading-delta heuristics —
|
* A much more direct "is this road user turning" signal than heading-delta heuristics —
|
||||||
* see [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
* see [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -27,17 +27,24 @@ object CamParser {
|
|||||||
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
val obj = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||||
|
|
||||||
val stationId = JsonFieldReader.firstLong(obj, "stationId", "stationID", "station_id") ?: return null
|
val stationId = JsonFieldReader.firstLong(obj, "stationId", "stationID", "station_id") ?: return null
|
||||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: return null
|
// The API sends the name ("passengerCar", CiT MQTT API v6 section 2.2.3); a number is still
|
||||||
|
// accepted. Until 2026-11-18 only a number was, so every real payload was dropped here.
|
||||||
|
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||||
|
?: StationType.fromApiName(obj.optString("stationType"))
|
||||||
|
?: return null
|
||||||
|
|
||||||
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
|
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
|
||||||
|
|
||||||
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
|
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
|
||||||
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
|
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
|
||||||
|
// Positive to the left on this topic (CiT MQTT API v6, v2x-uca/output/json/cam), as in the CAM
|
||||||
|
// itself; negated into Cam.yawRateDps, which is positive clockwise.
|
||||||
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
||||||
|
?.let { -it }
|
||||||
|
|
||||||
val driveDirection = JsonFieldReader.firstInt(obj, "driveDirection", "drive_direction")
|
val driveDirection = JsonFieldReader.firstInt(obj, "driveDirection", "drive_direction")
|
||||||
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength", "vehicle_length")
|
val vehicleLength = JsonFieldReader.firstDouble(obj, "vehicleLength_m", "vehicleLength", "vehicle_length")
|
||||||
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth", "vehicle_width")
|
val vehicleWidth = JsonFieldReader.firstDouble(obj, "vehicleWidth_m", "vehicleWidth", "vehicle_width")
|
||||||
val accel = JsonFieldReader.firstDouble(obj, "accelerationControl", "longitudinalAcceleration", "acceleration_mps2")
|
val accel = JsonFieldReader.firstDouble(obj, "accelerationControl", "longitudinalAcceleration", "acceleration_mps2")
|
||||||
|
|
||||||
// Own/remote: prefer an explicit flag if the API provides one; otherwise compare
|
// Own/remote: prefer an explicit flag if the API provides one; otherwise compare
|
||||||
|
|||||||
@@ -24,16 +24,34 @@ object ObuGnssParser {
|
|||||||
*/
|
*/
|
||||||
fun parseEgo(json: String, fallbackStationId: Long = 0L, timestamp: Long = System.currentTimeMillis()): Cam? {
|
fun parseEgo(json: String, fallbackStationId: Long = 0L, timestamp: Long = System.currentTimeMillis()): Cam? {
|
||||||
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||||
|
// Identity and yaw rate are in `own_info`, kinematics in `gnss` (CiT MQTT API v6 Listing 2.1,
|
||||||
|
// and every logged payload). Until 2026-11-18 everything was read from `own_info`, which
|
||||||
|
// has no position, so every real message was dropped and the ego state never came from
|
||||||
|
// here. A flat payload with everything on the root is still accepted.
|
||||||
val obj = root.optJSONObject("own_info") ?: root
|
val obj = root.optJSONObject("own_info") ?: root
|
||||||
|
val gnss = root.optJSONObject("gnss") ?: obj
|
||||||
|
|
||||||
val stationId = JsonFieldReader.firstLong(obj, "stationID", "stationId", "station_id") ?: fallbackStationId
|
val stationId = JsonFieldReader.firstLong(obj, "stationID", "stationId", "station_id") ?: fallbackStationId
|
||||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type") ?: StationType.CYCLIST
|
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||||
|
?: StationType.fromApiName(obj.optString("stationType"))
|
||||||
|
?: StationType.CYCLIST
|
||||||
|
|
||||||
val (lat, lon) = JsonFieldReader.firstLatLon(obj) ?: return null
|
val (lat, lon) = JsonFieldReader.firstLatLon(gnss) ?: JsonFieldReader.firstLatLon(obj) ?: return null
|
||||||
|
// 91 / 181 is the API's "no 2D fix" marker, not a place.
|
||||||
|
if (lat > 90.0 || lon > 180.0) return null
|
||||||
|
|
||||||
val speed = JsonFieldReader.firstDouble(obj, "speed_mps", "speed", "speedMps") ?: 0.0
|
// 163.82 m/s is the API's "invalid speed" marker; treated like a missing speed.
|
||||||
val heading = JsonFieldReader.firstDouble(obj, "heading_deg", "heading", "headingDeg") ?: 0.0
|
val speed = JsonFieldReader.firstDouble(gnss, "speed_mps", "speed", "speedMps")
|
||||||
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
?.takeIf { it < INVALID_SPEED_MPS } ?: 0.0
|
||||||
|
val heading = JsonFieldReader.firstDouble(gnss, "heading_deg", "heading", "headingDeg") ?: 0.0
|
||||||
|
val acceleration = JsonFieldReader.firstDouble(gnss, "acceleration_mpss")
|
||||||
|
// `yawRate_degps` is this topic's name (CiT MQTT API v6, Listing 2.1, own_info, and every
|
||||||
|
// logged payload). The document says positive to the left, but the CiT One sends it positive
|
||||||
|
// to the RIGHT: in the 2026-03-18 bacospat log, all 27 one-second windows of turning at over
|
||||||
|
// 4 m/s had it with the same sign as the clockwise heading change. That is already
|
||||||
|
// Cam.yawRateDps's convention, so it is taken as it is - unlike the CAM topic (CamParser),
|
||||||
|
// which the logs show is left-positive, as documented.
|
||||||
|
val yawRate = JsonFieldReader.firstDouble(obj, "yawRate_degps", "yawRate_dps", "yawRateDps", "yaw_rate_dps", "yawRate")
|
||||||
|
|
||||||
return Cam(
|
return Cam(
|
||||||
stationId = stationId,
|
stationId = stationId,
|
||||||
@@ -43,11 +61,17 @@ object ObuGnssParser {
|
|||||||
speedMps = speed,
|
speedMps = speed,
|
||||||
headingDeg = JsonFieldReader.normaliseHeadingDeg(heading),
|
headingDeg = JsonFieldReader.normaliseHeadingDeg(heading),
|
||||||
yawRateDps = yawRate,
|
yawRateDps = yawRate,
|
||||||
|
vehicleLengthM = JsonFieldReader.firstDouble(obj, "vehicleLength_m"),
|
||||||
|
vehicleWidthM = JsonFieldReader.firstDouble(obj, "vehicleWidth_m"),
|
||||||
|
accelerationMps2 = acceleration,
|
||||||
timestamp = timestamp,
|
timestamp = timestamp,
|
||||||
isOwn = true,
|
isOwn = true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The API's "invalid speed calculation" value (CiT MQTT API v6 section 2.1.1). */
|
||||||
|
private const val INVALID_SPEED_MPS = 163.82
|
||||||
|
|
||||||
/** Just the stationID/stationType, for when only identity (not a full fix) is needed. */
|
/** Just the stationID/stationType, for when only identity (not a full fix) is needed. */
|
||||||
fun parseOwnIdentity(json: String): Pair<Long, Int>? {
|
fun parseOwnIdentity(json: String): Pair<Long, Int>? {
|
||||||
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
|
||||||
|
|||||||
@@ -12,18 +12,19 @@ import kotlin.math.abs
|
|||||||
*
|
*
|
||||||
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
|
* `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write).
|
||||||
*
|
*
|
||||||
* Position/speed/heading come straight from GNSS. Yaw rate is derived from the gyroscope's
|
* Position/speed/heading come straight from GNSS. Yaw rate comes from the gyroscope projected
|
||||||
* z-axis reading (rotation about the vertical axis while the phone is roughly flat/mounted
|
* onto gravity ([com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]), so it is the rotation
|
||||||
* upright) rather than from GNSS heading deltas, which are noisy at low speed — same rationale
|
* about the true vertical however the phone is mounted, rather than from GNSS heading deltas,
|
||||||
* already used for remote-vehicle turn detection in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
* which are noisy at low speed — same rationale already used for remote-vehicle turn detection
|
||||||
|
* in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine].
|
||||||
*/
|
*/
|
||||||
object PhoneCamBuilder {
|
object PhoneCamBuilder {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param gnss latest phone GNSS fix.
|
* @param gnss latest phone GNSS fix, its timestamp already on the time base to transmit.
|
||||||
* @param gyroZRadPerSec latest gyroscope z-axis reading, rad/s (device frame). Positive per
|
* @param yawRateDps yaw rate about the vertical, deg/s, in the convention of [Cam.yawRateDps]
|
||||||
* Android's convention is counter-clockwise around +Z; converted to the clockwise-positive
|
* (positive = clockwise), from [com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator].
|
||||||
* yaw rate convention already used by [Cam.yawRateDps] to match OBU/remote CAM data.
|
* Null encodes as the ASN.1 `unavailable` sentinel.
|
||||||
* @param stationId the station ID to transmit under: the current pseudonym from
|
* @param stationId the station ID to transmit under: the current pseudonym from
|
||||||
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager], or the bench pinger's fixed ID.
|
* [com.hawhamburg.micr0bu.data.cam.PseudonymManager], or the bench pinger's fixed ID.
|
||||||
* Receivers track a station across successive CAMs by this ID, which is why it only ever
|
* Receivers track a station across successive CAMs by this ID, which is why it only ever
|
||||||
@@ -37,12 +38,10 @@ object PhoneCamBuilder {
|
|||||||
*/
|
*/
|
||||||
fun build(
|
fun build(
|
||||||
gnss: GnssReading,
|
gnss: GnssReading,
|
||||||
gyroZRadPerSec: Float?,
|
yawRateDps: Double?,
|
||||||
stationId: Long,
|
stationId: Long,
|
||||||
longitudinalAccelMps2: Double? = null,
|
longitudinalAccelMps2: Double? = null,
|
||||||
): Cam {
|
): Cam {
|
||||||
val yawRateDps = gyroZRadPerSec?.let { -it * RAD_TO_DEG } // negate: CCW+ -> CW+ convention
|
|
||||||
|
|
||||||
return Cam(
|
return Cam(
|
||||||
stationId = stationId,
|
stationId = stationId,
|
||||||
stationType = StationType.CYCLIST,
|
stationType = StationType.CYCLIST,
|
||||||
@@ -63,8 +62,6 @@ object PhoneCamBuilder {
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val RAD_TO_DEG = 180.0 / Math.PI
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gyro noise floor below which yaw rate is clamped to zero. Placeholder — initial
|
* Gyro noise floor below which yaw rate is clamped to zero. Placeholder — initial
|
||||||
* engineering estimate pending real-world tuning, same disclaimer as
|
* engineering estimate pending real-world tuning, same disclaimer as
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.hawhamburg.micr0bu.domain.denm
|
package com.hawhamburg.micr0bu.domain.denm
|
||||||
|
|
||||||
import com.hawhamburg.micr0bu.domain.cam.JsonFieldReader
|
import com.hawhamburg.micr0bu.domain.cam.JsonFieldReader
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.StationType
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,17 +124,6 @@ object DenmParser {
|
|||||||
*/
|
*/
|
||||||
fun causeCodeName(causeCode: Int?): String? = causeCode?.let { NAME_BY_CAUSE_CODE[it] }
|
fun causeCodeName(causeCode: Int?): String? = causeCode?.let { NAME_BY_CAUSE_CODE[it] }
|
||||||
|
|
||||||
/**
|
|
||||||
* The Use Case API's `stationType` string enum mapped to its ITS-G5 integer, per StationType in
|
|
||||||
* the ETSI CDD. Note roadSideUnit is **15**, not 12 - the enumeration has a gap after tram(11),
|
|
||||||
* so mapping by list position would silently mislabel every RSU.
|
|
||||||
*/
|
|
||||||
private val STATION_TYPE_BY_NAME = mapOf(
|
|
||||||
"unknown" to 0, "pedestrian" to 1, "cyclist" to 2, "moped" to 3, "motorcycle" to 4,
|
|
||||||
"passengerCar" to 5, "bus" to 6, "lightTruck" to 7, "heavyTruck" to 8, "trailer" to 9,
|
|
||||||
"specialVehicles" to 10, "tram" to 11, "roadSideUnit" to 15,
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses the API's RFC3339 timestamps ("2021-05-11T12:01:02+00:00") to epoch millis. The air
|
* Parses the API's RFC3339 timestamps ("2021-05-11T12:01:02+00:00") to epoch millis. The air
|
||||||
* path carries a binary TimestampIts instead, so the two transports arrive here in completely
|
* path carries a binary TimestampIts instead, so the two transports arrive here in completely
|
||||||
@@ -187,7 +177,7 @@ object DenmParser {
|
|||||||
val isTermination = obj.has("termination") && obj.optBoolean("termination", true)
|
val isTermination = obj.has("termination") && obj.optBoolean("termination", true)
|
||||||
|
|
||||||
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
val stationType = JsonFieldReader.firstInt(obj, "stationType", "station_type")
|
||||||
?: STATION_TYPE_BY_NAME[obj.optString("stationType").takeIf { it.isNotBlank() }]
|
?: StationType.fromApiName(obj.optString("stationType"))
|
||||||
|
|
||||||
return DenmEvent(
|
return DenmEvent(
|
||||||
stationId = stationId,
|
stationId = stationId,
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package com.hawhamburg.micr0bu.domain.fusion
|
||||||
|
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Yaw rate about the true vertical, whatever way up the phone is held.
|
||||||
|
*
|
||||||
|
* ## Why
|
||||||
|
* Yaw rate used to be the gyroscope's z axis alone. That is rotation about the screen's normal, so
|
||||||
|
* it is the yaw rate only with the phone lying flat, screen up. On a handlebar mount tilted towards
|
||||||
|
* the rider it is scaled down by the tilt and mixed with pitch and roll; with the phone upright,
|
||||||
|
* or loose in a bag, it is unrelated to the bike's turning at all.
|
||||||
|
*
|
||||||
|
* ## How
|
||||||
|
* Gravity (from `TYPE_GRAVITY`, in the device frame) gives the up direction. The rate about it is
|
||||||
|
* the gyroscope vector projected onto that unit vector: `ω · up`. That is the same number for any
|
||||||
|
* orientation of the phone, as long as the phone is held still relative to the bike.
|
||||||
|
*
|
||||||
|
* Samples are averaged over [windowNanos] ending at the newest gyroscope sample, rather than taking
|
||||||
|
* one raw sample: a single gyroscope sample on a bike is mostly vibration.
|
||||||
|
*
|
||||||
|
* A bike leans into a turn, and over a sustained turn `TYPE_GRAVITY` drifts toward the bike's own
|
||||||
|
* vertical. The result is then the turn rate scaled by the cosine of the lean, about 6 % low at
|
||||||
|
* 20° of lean. Small next to what the z-axis reading got wrong.
|
||||||
|
*
|
||||||
|
* All times are on the monotonic `SystemClock.elapsedRealtimeNanos` base (`SensorEvent.timestamp`),
|
||||||
|
* never the wall clock. Pure Kotlin, so it is tested apart from Android. Thread-safe: samples and
|
||||||
|
* reads may come from different threads.
|
||||||
|
*/
|
||||||
|
class YawRateEstimator(
|
||||||
|
private val windowNanos: Long = DEFAULT_WINDOW_NANOS,
|
||||||
|
private val staleNanos: Long = DEFAULT_STALE_NANOS,
|
||||||
|
) {
|
||||||
|
private val lock = Any()
|
||||||
|
|
||||||
|
private var upX = 0.0
|
||||||
|
private var upY = 0.0
|
||||||
|
private var upZ = 0.0
|
||||||
|
/** When the up direction was last measured; null until the first gravity sample. */
|
||||||
|
private var upAtNanos: Long? = null
|
||||||
|
|
||||||
|
private val times = LongArray(CAPACITY)
|
||||||
|
/** Rotation about up, rad/s, counter-clockwise seen from above (Android's sign convention). */
|
||||||
|
private val rates = DoubleArray(CAPACITY)
|
||||||
|
private var next = 0
|
||||||
|
private var count = 0
|
||||||
|
|
||||||
|
/** A gravity sample, m/s², device frame, pointing up. Ignored if too weak to give a direction. */
|
||||||
|
fun onGravity(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
|
||||||
|
val norm = sqrt(x.toDouble() * x + y.toDouble() * y + z.toDouble() * z)
|
||||||
|
if (norm < MIN_GRAVITY_MPS2) return // free fall or a broken sample: no direction to trust
|
||||||
|
synchronized(lock) {
|
||||||
|
upX = x / norm
|
||||||
|
upY = y / norm
|
||||||
|
upZ = z / norm
|
||||||
|
upAtNanos = elapsedRealtimeNanos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A gyroscope sample, rad/s, device frame. Dropped while the up direction is unknown or stale,
|
||||||
|
* since projecting onto an old up vector would report the phone's rotation since then as yaw.
|
||||||
|
*/
|
||||||
|
fun onGyro(x: Float, y: Float, z: Float, elapsedRealtimeNanos: Long) {
|
||||||
|
synchronized(lock) {
|
||||||
|
val upAt = upAtNanos ?: return
|
||||||
|
if (elapsedRealtimeNanos - upAt > staleNanos) return
|
||||||
|
times[next] = elapsedRealtimeNanos
|
||||||
|
rates[next] = x * upX + y * upY + z * upZ
|
||||||
|
next = (next + 1) % CAPACITY
|
||||||
|
if (count < CAPACITY) count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mean yaw rate over the last [windowNanos] of samples, deg/s, positive = turning clockwise
|
||||||
|
* seen from above: the convention of [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps].
|
||||||
|
* Null when there is no sample newer than [staleNanos] before [nowElapsedRealtimeNanos].
|
||||||
|
*/
|
||||||
|
fun yawRateDps(nowElapsedRealtimeNanos: Long): Double? {
|
||||||
|
synchronized(lock) {
|
||||||
|
if (count == 0) return null
|
||||||
|
val newestIndex = (next - 1 + CAPACITY) % CAPACITY
|
||||||
|
val newest = times[newestIndex]
|
||||||
|
if (nowElapsedRealtimeNanos - newest > staleNanos) return null
|
||||||
|
|
||||||
|
var sum = 0.0
|
||||||
|
var n = 0
|
||||||
|
for (k in 0 until count) {
|
||||||
|
val i = (newestIndex - k + CAPACITY) % CAPACITY
|
||||||
|
if (newest - times[i] > windowNanos) break
|
||||||
|
sum += rates[i]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
// Negate: counter-clockwise positive (Android) -> clockwise positive (Cam.yawRateDps).
|
||||||
|
return -(sum / n) * RAD_TO_DEG
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun reset() {
|
||||||
|
synchronized(lock) {
|
||||||
|
upAtNanos = null
|
||||||
|
next = 0
|
||||||
|
count = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** 100 ms: five samples at `SENSOR_DELAY_GAME` (about 50 Hz). */
|
||||||
|
const val DEFAULT_WINDOW_NANOS = 100_000_000L
|
||||||
|
|
||||||
|
/** Older than this, a gyroscope or gravity sample no longer describes the present. */
|
||||||
|
const val DEFAULT_STALE_NANOS = 500_000_000L
|
||||||
|
|
||||||
|
/** Room for the window at up to a few hundred Hz. */
|
||||||
|
private const val CAPACITY = 128
|
||||||
|
|
||||||
|
/** Well below 9.81: gravity this weak means free fall or a bad sample, not a direction. */
|
||||||
|
private const val MIN_GRAVITY_MPS2 = 3.0
|
||||||
|
|
||||||
|
private const val RAD_TO_DEG = 180.0 / Math.PI
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.hawhamburg.micr0bu.service
|
package com.hawhamburg.micr0bu.service
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.hardware.SensorManager
|
||||||
import android.os.SystemClock
|
import android.os.SystemClock
|
||||||
import com.hawhamburg.micr0bu.data.GnssReading
|
import com.hawhamburg.micr0bu.data.GnssReading
|
||||||
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
||||||
@@ -13,6 +14,7 @@ import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
|
|||||||
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
|
import com.hawhamburg.micr0bu.domain.cam.OwnStationIds
|
||||||
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
||||||
|
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -62,7 +64,7 @@ class CamPinger @Inject constructor(
|
|||||||
private var job: Job? = null
|
private var job: Job? = null
|
||||||
|
|
||||||
@Volatile private var latestGnss: GnssReading? = null
|
@Volatile private var latestGnss: GnssReading? = null
|
||||||
@Volatile private var latestGyroZ: Float? = null
|
private val yawRate = YawRateEstimator()
|
||||||
@Volatile private var previousGnss: GnssReading? = null
|
@Volatile private var previousGnss: GnssReading? = null
|
||||||
|
|
||||||
private val _isActive = MutableStateFlow(false)
|
private val _isActive = MutableStateFlow(false)
|
||||||
@@ -102,16 +104,24 @@ class CamPinger @Inject constructor(
|
|||||||
|
|
||||||
private suspend fun runPingLoop() = coroutineScope {
|
private suspend fun runPingLoop() = coroutineScope {
|
||||||
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
||||||
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
|
yawRate.reset()
|
||||||
|
launch {
|
||||||
|
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||||
|
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||||
|
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||||
|
}
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
val gnss = latestGnss
|
val gnss = latestGnss
|
||||||
_hasFix.value = gnss != null
|
_hasFix.value = gnss != null
|
||||||
if (gnss != null) {
|
if (gnss != null) {
|
||||||
val cam = PhoneCamBuilder.build(
|
val cam = PhoneCamBuilder.build(
|
||||||
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource.
|
// Stamped with the GNSS time of the fix itself; see GnssTimeSource.atElapsedRealtime.
|
||||||
gnss = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)),
|
gnss = gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos)),
|
||||||
gyroZRadPerSec = latestGyroZ,
|
yawRateDps = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos()),
|
||||||
stationId = OwnStationIds.BENCH_PING,
|
stationId = OwnStationIds.BENCH_PING,
|
||||||
longitudinalAccelMps2 = longitudinalAccel(gnss),
|
longitudinalAccelMps2 = longitudinalAccel(gnss),
|
||||||
)
|
)
|
||||||
@@ -140,7 +150,7 @@ class CamPinger @Inject constructor(
|
|||||||
previousGnss = gnss
|
previousGnss = gnss
|
||||||
if (prev == null) return null
|
if (prev == null) return null
|
||||||
|
|
||||||
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
|
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
|
||||||
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
||||||
|
|
||||||
return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec
|
return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.hawhamburg.micr0bu.service
|
package com.hawhamburg.micr0bu.service
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.hardware.SensorManager
|
||||||
|
import android.os.SystemClock
|
||||||
import com.hawhamburg.micr0bu.data.GnssReading
|
import com.hawhamburg.micr0bu.data.GnssReading
|
||||||
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
import com.hawhamburg.micr0bu.data.GnssTimeSource
|
||||||
import com.hawhamburg.micr0bu.data.SensorRepository
|
import com.hawhamburg.micr0bu.data.SensorRepository
|
||||||
@@ -16,6 +18,7 @@ import com.hawhamburg.micr0bu.domain.asn1.VamContent
|
|||||||
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
|
import com.hawhamburg.micr0bu.domain.asn1.VamUperCodec
|
||||||
import com.hawhamburg.micr0bu.domain.cam.CamTransmitConfig
|
import com.hawhamburg.micr0bu.domain.cam.CamTransmitConfig
|
||||||
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder
|
||||||
|
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||||
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
|
import com.hawhamburg.micr0bu.domain.usecase.GeoMath
|
||||||
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
|
import com.hawhamburg.micr0bu.domain.vam.VamGenerationRules
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
@@ -73,7 +76,9 @@ class CamTransmitLoop @Inject constructor(
|
|||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
|
||||||
@Volatile private var latestGnss: GnssReading? = null
|
@Volatile private var latestGnss: GnssReading? = null
|
||||||
@Volatile private var latestGyroZ: Float? = null
|
private val yawRate = YawRateEstimator()
|
||||||
|
|
||||||
|
/** [SystemClock.elapsedRealtime] until which the elevated rate holds; monotonic, see [nowMs]. */
|
||||||
@Volatile private var elevatedUntilMs: Long = 0L
|
@Volatile private var elevatedUntilMs: Long = 0L
|
||||||
|
|
||||||
/** Previous GNSS fix, kept only to derive along-track acceleration — see [longitudinalAccel]. */
|
/** Previous GNSS fix, kept only to derive along-track acceleration — see [longitudinalAccel]. */
|
||||||
@@ -89,7 +94,7 @@ class CamTransmitLoop @Inject constructor(
|
|||||||
* denser updates through the maneuver, not just at the instant it was detected.
|
* denser updates through the maneuver, not just at the instant it was detected.
|
||||||
*/
|
*/
|
||||||
fun onDetectedEvent() {
|
fun onDetectedEvent() {
|
||||||
elevatedUntilMs = System.currentTimeMillis() + ELEVATED_HOLD_MS
|
elevatedUntilMs = nowMs() + ELEVATED_HOLD_MS
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -118,7 +123,15 @@ class CamTransmitLoop @Inject constructor(
|
|||||||
|
|
||||||
private suspend fun runTransmitLoop() = coroutineScope {
|
private suspend fun runTransmitLoop() = coroutineScope {
|
||||||
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
launch { sensorRepository.gnssFlow().collect { latestGnss = it } }
|
||||||
launch { sensorRepository.gyroscopeFlow().collect { latestGyroZ = it.z } }
|
yawRate.reset()
|
||||||
|
launch {
|
||||||
|
sensorRepository.gravityFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||||
|
.collect { yawRate.onGravity(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
sensorRepository.gyroscopeFlow(SensorManager.SENSOR_DELAY_GAME)
|
||||||
|
.collect { yawRate.onGyro(it.x, it.y, it.z, it.elapsedRealtimeNanos) }
|
||||||
|
}
|
||||||
launch { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
|
launch { obuHardwarePrefs.signOutgoingFlow.collect { signOutgoing = it } }
|
||||||
launch {
|
launch {
|
||||||
obuHardwarePrefs.outgoingMessageFlow.collect {
|
obuHardwarePrefs.outgoingMessageFlow.collect {
|
||||||
@@ -143,25 +156,23 @@ class CamTransmitLoop @Inject constructor(
|
|||||||
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
|
// Asked for per CAM rather than once per trip: that is what lets a pseudonym
|
||||||
// rotation fall cleanly between two frames instead of inside one.
|
// rotation fall cleanly between two frames instead of inside one.
|
||||||
val pseudonym = pseudonymManager.current()
|
val pseudonym = pseudonymManager.current()
|
||||||
// Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the
|
val fix = onAirFix(gnss)
|
||||||
// outgoing CAM is: acceleration below still differences wall-clock samples.
|
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
|
||||||
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
|
|
||||||
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
|
|
||||||
val bytes = codec.encodeCam(cam)
|
val bytes = codec.encodeCam(cam)
|
||||||
esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes,
|
esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes,
|
||||||
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
|
GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing))
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun sendVamIfDue(gnss: GnssReading) {
|
private suspend fun sendVamIfDue(gnss: GnssReading) {
|
||||||
val now = System.currentTimeMillis()
|
val now = nowMs()
|
||||||
val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude,
|
val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude,
|
||||||
gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble())
|
gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble())
|
||||||
if (!vamRules.due(now, kinematics)) return
|
if (!vamRules.due(now, kinematics)) return
|
||||||
val pseudonym = pseudonymManager.current()
|
val pseudonym = pseudonymManager.current()
|
||||||
val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp))
|
val fix = onAirFix(gnss)
|
||||||
// The CAM view of this fix is built only for its position vector, so the GN header of a VAM
|
// The CAM view of this fix is built only for its position vector, so the GN header of a VAM
|
||||||
// follows exactly the rules a CAM's does. It is not transmitted.
|
// follows exactly the rules a CAM's does. It is not transmitted.
|
||||||
val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss))
|
val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss))
|
||||||
val withLowFrequency = vamRules.includeLowFrequency(now)
|
val withLowFrequency = vamRules.includeLowFrequency(now)
|
||||||
val bytes = VamUperCodec.encode(VamContent(
|
val bytes = VamUperCodec.encode(VamContent(
|
||||||
stationId = pseudonym.stationId,
|
stationId = pseudonym.stationId,
|
||||||
@@ -198,15 +209,31 @@ class CamTransmitLoop @Inject constructor(
|
|||||||
previousGnss = gnss
|
previousGnss = gnss
|
||||||
if (prev == null) return null
|
if (prev == null) return null
|
||||||
|
|
||||||
val dtSec = (gnss.timestamp - prev.timestamp) / 1000.0
|
val dtSec = (gnss.elapsedRealtimeNanos - prev.elapsedRealtimeNanos) / 1e9
|
||||||
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
if (dtSec < MIN_ACCEL_DT_SEC || dtSec > MAX_ACCEL_DT_SEC) return null
|
||||||
|
|
||||||
val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble()
|
val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble()
|
||||||
return dv / dtSec
|
return dv / dtSec
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [gnss] stamped with the GNSS time of the fix itself, for what goes on air: the fix's
|
||||||
|
* monotonic stamp moved onto GNSS time ([GnssTimeSource.atElapsedRealtime]). Neither the
|
||||||
|
* phone's clock setting nor a step of it between the fix and now can reach the result.
|
||||||
|
*/
|
||||||
|
private fun onAirFix(gnss: GnssReading): GnssReading =
|
||||||
|
gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos))
|
||||||
|
|
||||||
|
private fun currentYawRateDps(): Double? = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The clock for this loop's own intervals (elevated-rate hold, VAM generation rules). Monotonic,
|
||||||
|
* so a phone clock that is set back cannot hold transmission off until it catches up again.
|
||||||
|
*/
|
||||||
|
private fun nowMs(): Long = SystemClock.elapsedRealtime()
|
||||||
|
|
||||||
private fun currentRateHz(gnss: GnssReading?): Double {
|
private fun currentRateHz(gnss: GnssReading?): Double {
|
||||||
val now = System.currentTimeMillis()
|
val now = nowMs()
|
||||||
val inGeofence = gnss != null && config.geofences.any { fence ->
|
val inGeofence = gnss != null && config.geofences.any { fence ->
|
||||||
GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM
|
GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -349,7 +349,7 @@
|
|||||||
<string name="v2xlog_desc">Zeichnet jede empfangene V2X-Nachricht (CAM, DENM, SPATEM, MAPEM, VAM) in einer Datenbankdatei auf, mit Zeitstempel, der GNSS-Position des Telefons und, wenn vorhanden, der GNSS-Position der OBU und der Signalstärke (RSSI).</string>
|
<string name="v2xlog_desc">Zeichnet jede empfangene V2X-Nachricht (CAM, DENM, SPATEM, MAPEM, VAM) in einer Datenbankdatei auf, mit Zeitstempel, der GNSS-Position des Telefons und, wenn vorhanden, der GNSS-Position der OBU und der Signalstärke (RSSI).</string>
|
||||||
<string name="v2xlog_mode_esp32">ESP32-C5: protokolliert, was das Board über die Verbindung weiterleitet, mit RSSI. Das Board hat kein GNSS, daher gibt es keine OBU-Position.</string>
|
<string name="v2xlog_mode_esp32">ESP32-C5: protokolliert, was das Board über die Verbindung weiterleitet, mit RSSI. Das Board hat kein GNSS, daher gibt es keine OBU-Position.</string>
|
||||||
<string name="v2xlog_mode_cit">CiT One: protokolliert die MQTT-Topics. Die API liefert keine RSSI; die OBU-Position stammt aus v2x/rx/obu_gnss.</string>
|
<string name="v2xlog_mode_cit">CiT One: protokolliert die MQTT-Topics. Die API liefert keine RSSI; die OBU-Position stammt aus v2x/rx/obu_gnss.</string>
|
||||||
<string name="v2xlog_esp32_firmware_note">Die aktuelle ESP32-C5-Firmware leitet nur CAM, DENM und SPATEM weiter; MAPEM und VAM erscheinen erst, wenn die Firmware sie annimmt.</string>
|
<string name="v2xlog_esp32_firmware_note">Die Platine leitet CAM, DENM, SPATEM, MAPEM und VAM weiter. Auf dem Empfangspfad V2X_RX passt eine Nachricht über 494 Byte nicht in eine Link-Nachricht und wird verworfen; der Pfad Rohframes kennt diese Grenze nicht. Der Logger speichert auf beiden Pfaden die dekodierte Nachricht, nicht das Funkframe.</string>
|
||||||
<string name="v2xlog_start">Aufzeichnung starten</string>
|
<string name="v2xlog_start">Aufzeichnung starten</string>
|
||||||
<string name="v2xlog_stop">Aufzeichnung beenden</string>
|
<string name="v2xlog_stop">Aufzeichnung beenden</string>
|
||||||
<string name="v2xlog_error">Aufzeichnung fehlgeschlagen: %1$s</string>
|
<string name="v2xlog_error">Aufzeichnung fehlgeschlagen: %1$s</string>
|
||||||
|
|||||||
@@ -356,7 +356,7 @@
|
|||||||
<string name="v2xlog_desc">Records every V2X message received (CAM, DENM, SPATEM, MAPEM, VAM) into a database file, with a timestamp, the phone GNSS fix and, where available, the OBU GNSS fix and the signal strength (RSSI).</string>
|
<string name="v2xlog_desc">Records every V2X message received (CAM, DENM, SPATEM, MAPEM, VAM) into a database file, with a timestamp, the phone GNSS fix and, where available, the OBU GNSS fix and the signal strength (RSSI).</string>
|
||||||
<string name="v2xlog_mode_esp32">ESP32-C5: logging what the board forwards over the link, with RSSI. The board has no GNSS, so there is no OBU position.</string>
|
<string name="v2xlog_mode_esp32">ESP32-C5: logging what the board forwards over the link, with RSSI. The board has no GNSS, so there is no OBU position.</string>
|
||||||
<string name="v2xlog_mode_cit">CiT One: logging the MQTT topics. The API carries no RSSI; the OBU position comes from v2x/rx/obu_gnss.</string>
|
<string name="v2xlog_mode_cit">CiT One: logging the MQTT topics. The API carries no RSSI; the OBU position comes from v2x/rx/obu_gnss.</string>
|
||||||
<string name="v2xlog_esp32_firmware_note">The current ESP32-C5 firmware forwards only CAM, DENM and SPATEM, so MAPEM and VAM appear only once the firmware accepts them.</string>
|
<string name="v2xlog_esp32_firmware_note">The board forwards CAM, DENM, SPATEM, MAPEM and VAM. On the V2X_RX receive path a message over 494 bytes does not fit one link message and is dropped; the Raw frames path has no such limit. The logger stores the decoded message, not the radio frame, on either path.</string>
|
||||||
<string name="v2xlog_start">Start logging</string>
|
<string name="v2xlog_start">Start logging</string>
|
||||||
<string name="v2xlog_stop">Stop logging</string>
|
<string name="v2xlog_stop">Stop logging</string>
|
||||||
<string name="v2xlog_error">Logging failed: %1$s</string>
|
<string name="v2xlog_error">Logging failed: %1$s</string>
|
||||||
|
|||||||
@@ -61,6 +61,29 @@ class CamEncodeGoldenTest {
|
|||||||
assertEquals(expectedHex, encoded)
|
assertEquals(expectedHex, encoded)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [referenceCam] turning right at 12.34 deg/s, encoded by asn1tools with `yawRateValue` -1234:
|
||||||
|
* YawRateValue is positive to the LEFT (TS 102 894-2), while [Cam.yawRateDps] is positive
|
||||||
|
* clockwise. Only the yawRate bits differ from [expectedHex]. Generated 2026-11-18 by decoding
|
||||||
|
* [expectedHex] with asn1tools (cam_1_4_1 + cdd_1_3_1_1), setting the value, and re-encoding.
|
||||||
|
*/
|
||||||
|
private val rightTurnHex =
|
||||||
|
"0202000f423f4a88402ab215af6e286477dffffffc23b7743e0027ffc0d0fe0118329337fee9ecb2000000"
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a right turn goes on air as a negative YawRateValue`() {
|
||||||
|
val encoded = CamUperCodec.encode(referenceCam.copy(yawRateDps = 12.34))
|
||||||
|
.joinToString("") { "%02x".format(it) }
|
||||||
|
assertEquals(rightTurnHex, encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a negative YawRateValue from the air is a right turn`() {
|
||||||
|
val bytes = rightTurnHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||||
|
val cam = requireNotNull(CamUperCodec.decode(bytes, referenceCam.timestamp))
|
||||||
|
assertEquals(12.34, cam.yawRateDps!!, 1e-9)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `own decoder agrees with the encoder on every field it reads`() {
|
fun `own decoder agrees with the encoder on every field it reads`() {
|
||||||
// Self-consistency is necessary but NOT sufficient - see the class KDoc. This guards the
|
// Self-consistency is necessary but NOT sufficient - see the class KDoc. This guards the
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package com.hawhamburg.micr0bu
|
||||||
|
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.StationType
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The two CiT One JSON parsers against payloads shaped exactly like the ones the CiT One really
|
||||||
|
* sends (keys, nesting and types copied from the logged runs, values changed). Both parsers used to
|
||||||
|
* return null for every one of them: `obu_gnss` keeps its position under `gnss`, not `own_info`,
|
||||||
|
* and the CAM topic sends `stationType` as a name.
|
||||||
|
*/
|
||||||
|
class CitOneJsonParsersTest {
|
||||||
|
|
||||||
|
private val obuGnss = """
|
||||||
|
{ "type": "v2xgw-owninfo", "obu_timestamp_sec": 1773834329.0660601,
|
||||||
|
"gnss": { "latitude": 53.5551, "longitude": 10.0222, "altitude_m": 60.5, "speed_mps": 5.25,
|
||||||
|
"time_utc": "2026-03-18T11:45:29Z", "heading_deg": 87.5, "acceleration_mpss": -0.25,
|
||||||
|
"curvature": { "radiusOfCurve_m": 3276.0, "confidence": 100.0 },
|
||||||
|
"positionError_stdDev": { "posErrSemiMajorAxisLen_m": 0.446, "posErrSemiMinorAxisLen_m": 0.446,
|
||||||
|
"posErrSemiMajorAxisOrientation_deg": 0.0, "altitudeErr_m": 0.609, "headingErr_deg": 361.0,
|
||||||
|
"groundSpeedErr_mps": 0.077, "verticalSpeedErr_mps": -1.0, "DOP": -4.45e-25 },
|
||||||
|
"satInfo": { "fix": "3d", "numSatUsed": 14,
|
||||||
|
"numSatVisible": { "gps": 0, "gbas": 0, "sbas": 0, "gnss": 0 } } },
|
||||||
|
"own_info": { "stationID": 319450879, "stationType": 5, "vehicleRole": 0, "vehicleWidth_m": 1.8,
|
||||||
|
"vehicleLength_m": 4.26, "yawRate_degps": 6.5, "isBreaking": false },
|
||||||
|
"pathHistory": { "refLatitude": 53.5551, "refLongitude": 10.0222, "refAltitude": 60.5,
|
||||||
|
"pathPoints": [ { "deltaLatitude": -3.5e-06, "deltaLongitude": 1.31e-05,
|
||||||
|
"deltaAltitude_m": -5.0, "pathDeltaTime_ms": 834 } ] } }
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
private val processedCam = """
|
||||||
|
{"heading_deg":1.2,"pathHistory":{"path":{"coordinates":[[10.0258218,53.5526996,52.6],
|
||||||
|
[10.0258295,53.5524988,51.6]],"type":"LineString"}},"position":{"coordinates":[10.0258076,53.5528397,52.6],
|
||||||
|
"type":"Point"},"positionError_stdDev":{"altitudeErr_m":10.0,"groundSpeedErr_mps":0.105,"headingErr_deg":0.5,
|
||||||
|
"posErrSemiMajorAxisLen_m":1.57,"posErrSemiMajorAxisOrientation_deg":5.4,"posErrSemiMinorAxisLen_m":1.56},
|
||||||
|
"speed_mps":7.25,"stationId":3124041003,"stationType":"passengerCar","type":"v2x-cam",
|
||||||
|
"vehicleLength_m":4.9,"vehicleRole":"default","vehicleWidth_m":1.8,"yawRate_dps":-1.43}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `obu_gnss - kinematics from gnss, identity and yaw rate from own_info`() {
|
||||||
|
val ego = ObuGnssParser.parseEgo(obuGnss, timestamp = 1_000L)!!
|
||||||
|
assertEquals(319450879L, ego.stationId)
|
||||||
|
assertEquals(StationType.PASSENGER_CAR, ego.stationType)
|
||||||
|
assertEquals(53.5551, ego.latitude, 1e-9)
|
||||||
|
assertEquals(10.0222, ego.longitude, 1e-9)
|
||||||
|
assertEquals(5.25, ego.speedMps, 1e-9)
|
||||||
|
assertEquals(87.5, ego.headingDeg, 1e-9)
|
||||||
|
assertEquals(-0.25, ego.accelerationMps2!!, 1e-9)
|
||||||
|
// Right-positive on this topic in practice, as Cam.yawRateDps is: taken as it is.
|
||||||
|
assertEquals(6.5, ego.yawRateDps!!, 1e-9)
|
||||||
|
assertEquals(4.26, ego.vehicleLengthM!!, 1e-9)
|
||||||
|
assertEquals(1.8, ego.vehicleWidthM!!, 1e-9)
|
||||||
|
assertTrue(ego.isOwn)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `obu_gnss - the no-fix marker is not a position`() {
|
||||||
|
val noFix = obuGnss.replace("\"latitude\": 53.5551", "\"latitude\": 91.0")
|
||||||
|
.replace("\"longitude\": 10.0222", "\"longitude\": 181.0")
|
||||||
|
assertNull(ObuGnssParser.parseEgo(noFix))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `obu_gnss - the invalid speed marker reads as no speed`() {
|
||||||
|
val badSpeed = obuGnss.replace("\"speed_mps\": 5.25", "\"speed_mps\": 163.82")
|
||||||
|
assertEquals(0.0, ObuGnssParser.parseEgo(badSpeed)!!.speedMps, 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `CAM topic - station type name, vehicle size and a left-positive yaw rate`() {
|
||||||
|
val cam = CamParser.parse(processedCam, ownStationId = null)!!
|
||||||
|
assertEquals(3124041003L, cam.stationId)
|
||||||
|
assertEquals(StationType.PASSENGER_CAR, cam.stationType)
|
||||||
|
assertEquals(53.5528397, cam.latitude, 1e-9)
|
||||||
|
assertEquals(10.0258076, cam.longitude, 1e-9)
|
||||||
|
assertEquals(7.25, cam.speedMps, 1e-9)
|
||||||
|
assertEquals(1.2, cam.headingDeg, 1e-9)
|
||||||
|
// -1.43 on this left-positive topic is 1.43 deg/s to the right: +1.43 in Cam.yawRateDps.
|
||||||
|
assertEquals(1.43, cam.yawRateDps!!, 1e-9)
|
||||||
|
assertEquals(4.9, cam.vehicleLengthM!!, 1e-9)
|
||||||
|
assertEquals(1.8, cam.vehicleWidthM!!, 1e-9)
|
||||||
|
assertFalse(cam.isOwn)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `CAM topic - own CAM recognised by the station id learned from obu_gnss`() {
|
||||||
|
assertTrue(CamParser.parse(processedCam, ownStationId = 3124041003L)!!.isOwn)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `CAM topic - an unknown station type name is still rejected`() {
|
||||||
|
assertNull(CamParser.parse(processedCam.replace("passengerCar", "spaceship"), ownStationId = null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `station type names map by name, with the gap before roadSideUnit`() {
|
||||||
|
assertEquals(2, StationType.fromApiName("cyclist"))
|
||||||
|
assertEquals(11, StationType.fromApiName("tram"))
|
||||||
|
assertEquals(15, StationType.fromApiName("roadSideUnit"))
|
||||||
|
assertNull(StationType.fromApiName(""))
|
||||||
|
assertNull(StationType.fromApiName(null))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package com.hawhamburg.micr0bu
|
||||||
|
|
||||||
|
import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.sin
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The yaw rate must be the rotation about the true vertical whatever way up the phone is, which is
|
||||||
|
* what the old z-axis reading got wrong for anything but a phone lying flat, screen up.
|
||||||
|
*/
|
||||||
|
class YawRateEstimatorTest {
|
||||||
|
|
||||||
|
private val g = 9.81f
|
||||||
|
private val ms = 1_000_000L
|
||||||
|
private val radToDeg = 180.0 / Math.PI
|
||||||
|
|
||||||
|
/** Feeds [up] (a unit vector, device frame) as gravity and a pure yaw of [ccwRadPerSec] about it. */
|
||||||
|
private fun YawRateEstimator.yawAbout(up: DoubleArray, ccwRadPerSec: Double, startNanos: Long, samples: Int = 5) {
|
||||||
|
onGravity((up[0] * g).toFloat(), (up[1] * g).toFloat(), (up[2] * g).toFloat(), startNanos)
|
||||||
|
for (i in 0 until samples) {
|
||||||
|
onGyro(
|
||||||
|
(up[0] * ccwRadPerSec).toFloat(),
|
||||||
|
(up[1] * ccwRadPerSec).toFloat(),
|
||||||
|
(up[2] * ccwRadPerSec).toFloat(),
|
||||||
|
startNanos + i * 20 * ms,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `flat phone, left turn, is negative in the clockwise-positive convention`() {
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||||
|
// 0.5 rad/s counter-clockwise = turning left = -28.6 deg/s clockwise-positive, as the old z-axis path gave.
|
||||||
|
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `handlebar tilt does not shrink the yaw rate`() {
|
||||||
|
// Phone tilted 50 deg toward the rider about its x axis: up is (0, sin 50, cos 50) in the device frame.
|
||||||
|
val tilt = Math.toRadians(50.0)
|
||||||
|
val up = doubleArrayOf(0.0, sin(tilt), cos(tilt))
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.yawAbout(up, 0.5, 0L)
|
||||||
|
assertEquals(-0.5 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||||
|
// The z axis alone would have read only cos 50 = 64 % of it.
|
||||||
|
assertEquals(0.643, up[2], 1e-3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `upright phone, where the z axis reads nothing, still gives the yaw rate`() {
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.yawAbout(doubleArrayOf(0.0, 1.0, 0.0), -0.3, 0L)
|
||||||
|
assertEquals(0.3 * radToDeg, est.yawRateDps(80 * ms)!!, 1e-3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `rotation about a horizontal axis is not yaw`() {
|
||||||
|
// Flat phone pitching about its x axis, as on a bump: no yaw at all.
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.onGravity(0f, 0f, g, 0L)
|
||||||
|
for (i in 0 until 5) est.onGyro(1.0f, 0f, 0f, i * 20 * ms)
|
||||||
|
assertEquals(0.0, est.yawRateDps(80 * ms)!!, 1e-9)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `averages over the window ending at the newest sample`() {
|
||||||
|
val est = YawRateEstimator(windowNanos = 100 * ms)
|
||||||
|
est.onGravity(0f, 0f, g, 0L)
|
||||||
|
est.onGyro(0f, 0f, 10f, 0L) // 300 ms before the newest: outside the window
|
||||||
|
est.onGyro(0f, 0f, 0.2f, 220 * ms)
|
||||||
|
est.onGyro(0f, 0f, 0.4f, 260 * ms)
|
||||||
|
est.onGyro(0f, 0f, 0.6f, 300 * ms)
|
||||||
|
assertEquals(-0.4 * radToDeg, est.yawRateDps(300 * ms)!!, 1e-3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `no yaw rate before gravity is known`() {
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.onGyro(0f, 0f, 0.5f, 0L)
|
||||||
|
assertNull(est.yawRateDps(0L))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `no yaw rate once the gyroscope has gone quiet`() {
|
||||||
|
val est = YawRateEstimator(staleNanos = 500 * ms)
|
||||||
|
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||||
|
assertNotNull(est.yawRateDps(500 * ms))
|
||||||
|
assertNull(est.yawRateDps(600 * ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `gyroscope samples are dropped against a stale up direction`() {
|
||||||
|
val est = YawRateEstimator(staleNanos = 500 * ms)
|
||||||
|
est.onGravity(0f, 0f, g, 0L)
|
||||||
|
est.onGyro(0f, 0f, 0.5f, 900 * ms)
|
||||||
|
assertNull(est.yawRateDps(900 * ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `a gravity sample too weak to give a direction is ignored`() {
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.onGravity(0f, 0f, 0.5f, 0L)
|
||||||
|
est.onGyro(0f, 0f, 0.5f, 0L)
|
||||||
|
assertNull(est.yawRateDps(0L))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `reset forgets the up direction and the samples`() {
|
||||||
|
val est = YawRateEstimator()
|
||||||
|
est.yawAbout(doubleArrayOf(0.0, 0.0, 1.0), 0.5, 0L)
|
||||||
|
est.reset()
|
||||||
|
assertNull(est.yawRateDps(80 * ms))
|
||||||
|
est.onGyro(0f, 0f, 0.5f, 100 * ms)
|
||||||
|
assertNull(est.yawRateDps(100 * ms))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.hawhamburg.micr0bu
|
||||||
|
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.CamParser
|
||||||
|
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [com.hawhamburg.micr0bu.domain.cam.Cam.yawRateDps] is positive clockwise. The CiT One's CAM topic
|
||||||
|
* is positive to the left (documented, and 316 of 316 turning samples in the logged runs), so
|
||||||
|
* [CamParser] flips it. Its `obu_gnss` topic is documented as left-positive too, but the logs show
|
||||||
|
* it positive to the right (27 of 27), so [ObuGnssParser] keeps it.
|
||||||
|
*/
|
||||||
|
class YawRateJsonSignTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `CAM topic - positive is a left turn, so it becomes negative`() {
|
||||||
|
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02,
|
||||||
|
"yawRate_dps": 15.0}"""
|
||||||
|
assertEquals(-15.0, CamParser.parse(json, ownStationId = null)!!.yawRateDps!!, 1e-9)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `CAM topic - a missing yaw rate stays unavailable`() {
|
||||||
|
val json = """{"stationID": 42, "stationType": 5, "latitude": 53.55, "longitude": 10.02}"""
|
||||||
|
assertNull(CamParser.parse(json, ownStationId = null)!!.yawRateDps)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `obu_gnss - yawRate_degps is read as it is, since the CiT One sends it right-positive`() {
|
||||||
|
// own_info as in Listing 2.1, with the position placed where this parser reads it.
|
||||||
|
val json = """{"own_info": {"stationID": 1345678, "stationType": 2,
|
||||||
|
"latitude": 53.55, "longitude": 10.02, "yawRate_degps": -7.5}}"""
|
||||||
|
assertEquals(-7.5, ObuGnssParser.parseEgo(json)!!.yawRateDps!!, 1e-9)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user