diff --git a/TODO.md b/TODO.md index 0e71b70..233d60d 100644 --- a/TODO.md +++ b/TODO.md @@ -5,6 +5,25 @@ Engineering to-do list. The reviewer-facing open items live in ## 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). + ### 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 diff --git a/app/src/main/java/com/hawhamburg/micr0bu/data/GnssTimeSource.kt b/app/src/main/java/com/hawhamburg/micr0bu/data/GnssTimeSource.kt index f11028c..4905bde 100644 --- a/app/src/main/java/com/hawhamburg/micr0bu/data/GnssTimeSource.kt +++ b/app/src/main/java/com/hawhamburg/micr0bu/data/GnssTimeSource.kt @@ -58,6 +58,20 @@ object GnssTimeSource { 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) { val usingGnss = gnssNow != null if (lastUsedGnss == usingGnss) return diff --git a/app/src/main/java/com/hawhamburg/micr0bu/data/SensorRepository.kt b/app/src/main/java/com/hawhamburg/micr0bu/data/SensorRepository.kt index 9aa67a6..9c7e7c0 100644 --- a/app/src/main/java/com/hawhamburg/micr0bu/data/SensorRepository.kt +++ b/app/src/main/java/com/hawhamburg/micr0bu/data/SensorRepository.kt @@ -6,6 +6,7 @@ import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.location.Location +import android.os.SystemClock import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest 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.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( val x: Float, val y: 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( val latitude: Double, val longitude: Double, @@ -29,7 +52,11 @@ data class GnssReading( val speedMs: Float, val bearingDeg: 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) { @@ -37,12 +64,30 @@ class SensorRepository(private val context: Context) { private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager private val fusedLocation = LocationServices.getFusedLocationProviderClient(context) - fun accelerometerFlow(): Flow = 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 = + sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs) - fun gyroscopeFlow(): Flow = sensorFlow(Sensor.TYPE_GYROSCOPE) + fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow = + sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs) fun magnetometerFlow(): Flow = 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 = + if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs) + else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs) + fun barometerFlow(): Flow = callbackFlow { val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) if (sensor == null) { @@ -77,7 +122,10 @@ class SensorRepository(private val context: Context) { fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null - private fun sensorFlow(type: Int): Flow = callbackFlow { + private fun sensorFlow( + type: Int, + samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, + ): Flow = callbackFlow { val sensor = sensorManager.getDefaultSensor(type) if (sensor == null) { close() @@ -85,20 +133,42 @@ class SensorRepository(private val context: Context) { } val listener = object : SensorEventListener { 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) {} } - sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI) + sensorManager.registerListener(listener, sensor, samplingPeriodUs) awaitClose { sensorManager.unregisterListener(listener) } } } -private fun Location.toReading() = GnssReading( - latitude = latitude, - longitude = longitude, - altitude = altitude, - speedMs = speed, - bearingDeg = bearing, - accuracyM = accuracy -) +/** + * 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, + longitude = longitude, + altitude = altitude, + speedMs = speed, + bearingDeg = bearing, + accuracyM = accuracy, + timestamp = wallClockMsAt(fixNanos), + elapsedRealtimeNanos = fixNanos, + speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond else null, + bearingAccuracyDeg = if (hasBearingAccuracy()) bearingAccuracyDegrees else null, + provider = provider, + ) +} diff --git a/app/src/main/java/com/hawhamburg/micr0bu/domain/cam/PhoneCamBuilder.kt b/app/src/main/java/com/hawhamburg/micr0bu/domain/cam/PhoneCamBuilder.kt index 4886c53..64ab7f1 100644 --- a/app/src/main/java/com/hawhamburg/micr0bu/domain/cam/PhoneCamBuilder.kt +++ b/app/src/main/java/com/hawhamburg/micr0bu/domain/cam/PhoneCamBuilder.kt @@ -12,18 +12,19 @@ import kotlin.math.abs * * `PhoneCamBuilder.build(...)` → `RealAsn1UperCodec.encodeCam(...)` → `Esp32Link` (write). * - * Position/speed/heading come straight from GNSS. Yaw rate is derived from the gyroscope's - * z-axis reading (rotation about the vertical axis while the phone is roughly flat/mounted - * upright) rather than from GNSS heading deltas, which are noisy at low speed — same rationale - * already used for remote-vehicle turn detection in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine]. + * Position/speed/heading come straight from GNSS. Yaw rate comes from the gyroscope projected + * onto gravity ([com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]), so it is the rotation + * about the true vertical however the phone is mounted, rather than from GNSS heading deltas, + * which are noisy at low speed — same rationale already used for remote-vehicle turn detection + * in [com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionEngine]. */ object PhoneCamBuilder { /** - * @param gnss latest phone GNSS fix. - * @param gyroZRadPerSec latest gyroscope z-axis reading, rad/s (device frame). Positive per - * Android's convention is counter-clockwise around +Z; converted to the clockwise-positive - * yaw rate convention already used by [Cam.yawRateDps] to match OBU/remote CAM data. + * @param gnss latest phone GNSS fix, its timestamp already on the time base to transmit. + * @param yawRateDps yaw rate about the vertical, deg/s, in the convention of [Cam.yawRateDps] + * (positive = clockwise), from [com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator]. + * Null encodes as the ASN.1 `unavailable` sentinel. * @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. * Receivers track a station across successive CAMs by this ID, which is why it only ever @@ -37,12 +38,10 @@ object PhoneCamBuilder { */ fun build( gnss: GnssReading, - gyroZRadPerSec: Float?, + yawRateDps: Double?, stationId: Long, longitudinalAccelMps2: Double? = null, ): Cam { - val yawRateDps = gyroZRadPerSec?.let { -it * RAD_TO_DEG } // negate: CCW+ -> CW+ convention - return Cam( stationId = stationId, stationType = StationType.CYCLIST, @@ -63,8 +62,6 @@ object PhoneCamBuilder { 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 * engineering estimate pending real-world tuning, same disclaimer as diff --git a/app/src/main/java/com/hawhamburg/micr0bu/domain/fusion/YawRateEstimator.kt b/app/src/main/java/com/hawhamburg/micr0bu/domain/fusion/YawRateEstimator.kt new file mode 100644 index 0000000..e228b64 --- /dev/null +++ b/app/src/main/java/com/hawhamburg/micr0bu/domain/fusion/YawRateEstimator.kt @@ -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 + } +} diff --git a/app/src/main/java/com/hawhamburg/micr0bu/service/CamPinger.kt b/app/src/main/java/com/hawhamburg/micr0bu/service/CamPinger.kt index 3b1beaf..93991bf 100644 --- a/app/src/main/java/com/hawhamburg/micr0bu/service/CamPinger.kt +++ b/app/src/main/java/com/hawhamburg/micr0bu/service/CamPinger.kt @@ -1,6 +1,7 @@ package com.hawhamburg.micr0bu.service import android.content.Context +import android.hardware.SensorManager import android.os.SystemClock import com.hawhamburg.micr0bu.data.GnssReading 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.cam.OwnStationIds import com.hawhamburg.micr0bu.domain.cam.PhoneCamBuilder +import com.hawhamburg.micr0bu.domain.fusion.YawRateEstimator import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -62,7 +64,7 @@ class CamPinger @Inject constructor( private var job: Job? = null @Volatile private var latestGnss: GnssReading? = null - @Volatile private var latestGyroZ: Float? = null + private val yawRate = YawRateEstimator() @Volatile private var previousGnss: GnssReading? = null private val _isActive = MutableStateFlow(false) @@ -102,16 +104,24 @@ class CamPinger @Inject constructor( private suspend fun runPingLoop() = coroutineScope { 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) { val gnss = latestGnss _hasFix.value = gnss != null if (gnss != null) { val cam = PhoneCamBuilder.build( - // Stamped on GNSS time rather than the phone clock; see GnssTimeSource. - gnss = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)), - gyroZRadPerSec = latestGyroZ, + // Stamped with the GNSS time of the fix itself; see GnssTimeSource.atElapsedRealtime. + gnss = gnss.copy(timestamp = GnssTimeSource.atElapsedRealtime(gnss.elapsedRealtimeNanos)), + yawRateDps = yawRate.yawRateDps(SystemClock.elapsedRealtimeNanos()), stationId = OwnStationIds.BENCH_PING, longitudinalAccelMps2 = longitudinalAccel(gnss), ) @@ -140,7 +150,7 @@ class CamPinger @Inject constructor( previousGnss = gnss 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 return (gnss.speedMs.toDouble() - prev.speedMs.toDouble()) / dtSec diff --git a/app/src/main/java/com/hawhamburg/micr0bu/service/CamTransmitLoop.kt b/app/src/main/java/com/hawhamburg/micr0bu/service/CamTransmitLoop.kt index c566a6d..f140969 100644 --- a/app/src/main/java/com/hawhamburg/micr0bu/service/CamTransmitLoop.kt +++ b/app/src/main/java/com/hawhamburg/micr0bu/service/CamTransmitLoop.kt @@ -1,6 +1,8 @@ package com.hawhamburg.micr0bu.service import android.content.Context +import android.hardware.SensorManager +import android.os.SystemClock import com.hawhamburg.micr0bu.data.GnssReading import com.hawhamburg.micr0bu.data.GnssTimeSource 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.cam.CamTransmitConfig 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.vam.VamGenerationRules import dagger.hilt.android.qualifiers.ApplicationContext @@ -73,7 +76,9 @@ class CamTransmitLoop @Inject constructor( private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) @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 /** 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. */ 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 { 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.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 // rotation fall cleanly between two frames instead of inside one. val pseudonym = pseudonymManager.current() - // Stamped on GNSS time rather than the phone clock; see GnssTimeSource. Only the - // outgoing CAM is: acceleration below still differences wall-clock samples. - val fix = gnss.copy(timestamp = GnssTimeSource.correct(gnss.timestamp)) - val cam = PhoneCamBuilder.build(fix, latestGyroZ, pseudonym.stationId, longitudinalAccel(gnss)) + val fix = onAirFix(gnss) + val cam = PhoneCamBuilder.build(fix, currentYawRateDps(), pseudonym.stationId, longitudinalAccel(gnss)) val bytes = codec.encodeCam(cam) esp32Link.send(OutgoingIts(OutgoingMessage.CAM, bytes, GnPositionVector.fromCam(cam, gnss.accuracyM, pseudonym.mac), gnss.accuracyM, signOutgoing)) } private suspend fun sendVamIfDue(gnss: GnssReading) { - val now = System.currentTimeMillis() + val now = nowMs() val kinematics = VamGenerationRules.Kinematics(gnss.latitude, gnss.longitude, gnss.speedMs.toDouble(), gnss.bearingDeg.toDouble()) if (!vamRules.due(now, kinematics)) return 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 // 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 bytes = VamUperCodec.encode(VamContent( stationId = pseudonym.stationId, @@ -198,15 +209,31 @@ class CamTransmitLoop @Inject constructor( previousGnss = gnss 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 val dv = gnss.speedMs.toDouble() - prev.speedMs.toDouble() 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 { - val now = System.currentTimeMillis() + val now = nowMs() val inGeofence = gnss != null && config.geofences.any { fence -> GeoMath.haversineMeters(gnss.latitude, gnss.longitude, fence.latitude, fence.longitude) <= fence.radiusM } diff --git a/app/src/test/java/com/hawhamburg/micr0bu/YawRateEstimatorTest.kt b/app/src/test/java/com/hawhamburg/micr0bu/YawRateEstimatorTest.kt new file mode 100644 index 0000000..2479b81 --- /dev/null +++ b/app/src/test/java/com/hawhamburg/micr0bu/YawRateEstimatorTest.kt @@ -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)) + } +}