Record motion sensors, raw GPS and clocks for sensor fusion, and add Ride settings

Phase 1 of GNSS/IMU sensor fusion: record what the filter needs, so it can
be built and tuned offline against real rides before it changes anything
on air (docs/07-sensor-fusion-logging.md).

Settings > Ride replaces Units, whose metric switch did nothing (the app is
metric throughout). It holds the phone position (handlebar, bag or pocket),
written into every V2X log as meta.phone_mount, and "Record motion
sensors", off by default.

With that switch on when a V2X log starts, the log (schema 2, file name
ending in _imu-<mount>) also records:
- accelerometer, gyroscope and gravity at 100 Hz into a new imu table, each
  sample with its own SensorEvent timestamp, collected on a background
  thread;
- raw GPS_PROVIDER fixes as gnss source phone_gps, next to the fused
  location, and for every phone fix its monotonic time, speed and bearing
  accuracy and provider;
- the monotonic, wall and GNSS clocks once a second into a new clock table,
  to line all timestamps up afterwards and show any phone clock step;
- the sensors' names and rates and the GNSS chip in meta.

Both settings are read once at the start, so one log is one mount and one
mode. The logger screen shows the mount, the motion sensor row count and
the raw GPS fix age while it runs.

tools/fusion_log_check.py checks a recorded log (sensor rates and gaps, both
phone sources, clock alignment and steps) and ends in PASS, WARN or FAIL.
Tested on synthetic logs built from V2xLogWriter's own table definitions;
the bench and ride checks on the Pixel 9 Pro are in TODO.
This commit is contained in:
Ashin Walpola
2026-11-19 15:17:02 +01:00
parent 275d382a1d
commit 7dd83dba3d
18 changed files with 971 additions and 64 deletions
+7 -3
View File
@@ -82,7 +82,9 @@ Both paths converge at `CamUseCaseRepository`, which normalises whatever arrived
**OBU status**; the ESP32-C5 card shows the link in use, signing (tickets, signed, refused, on air) and the board's battery voltage with a low/critical warning, which also appears in the top bar. **OBU status**; the ESP32-C5 card shows the link in use, signing (tickets, signed, refused, on air) and the board's battery voltage with a low/critical warning, which also appears in the top bar.
**V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside. **V2X data logger**; Settings > Developer. Records every V2X message received on either path, with the phone's GNSS fix, the OBU's fix where there is one, and RSSI, into one SQLite file per run (`files/v2x_logs/`). The UPER bytes are kept as received; CAM, DENM, SPATEM and MAPEM get a few fields decoded alongside. With Settings > Ride > Record motion sensors on, a log also records accelerometer, gyroscope and gravity at 100 Hz, raw GPS fixes next to the fused location, and the phone's clocks, for sensor fusion; `tools/fusion_log_check.py` checks such a log. See `docs/07-sensor-fusion-logging.md`.
**Ride settings**; Settings > Ride. Where the phone rides (handlebar, bag or pocket), recorded in every V2X log for sensor fusion, and the motion sensor recording switch above.
**Trip recording**; foreground service records all sensor streams and detects cycling manoeuvres (braking, turning, stopping) using orientation-independent signal processing. Works fully offline with no OBU connected. The detected manoeuvres are neither shown nor stored - their only effect is to raise the CAM transmit rate through the manoeuvre on the ESP32-C5 path. **Trip recording**; foreground service records all sensor streams and detects cycling manoeuvres (braking, turning, stopping) using orientation-independent signal processing. Works fully offline with no OBU connected. The detected manoeuvres are neither shown nor stored - their only effect is to raise the CAM transmit rate through the manoeuvre on the ESP32-C5 path.
@@ -98,13 +100,13 @@ MVVM with Repository pattern throughout. Jetpack Compose for all UI (no XML layo
app/src/main/java/com/hawhamburg/micr0bu/ app/src/main/java/com/hawhamburg/micr0bu/
ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor and map, Settings, V2X logger...) ui/screens/ Compose screens (Dashboard, Record, Trips, V2X Monitor and map, Settings, V2X logger...)
ui/navigation/ Navigation graph and bottom nav bar ui/navigation/ Navigation graph and bottom nav bar
viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel viewmodel/ MqttViewModel (V2X state, traffic lights), SensorViewModel, TripRecordingViewModel, V2xLogViewModel, RideSettingsViewModel
data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope data/mqtt/ MQTT repository, Paho client, exponential-backoff reconnection, CiT One protobuf envelope
data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport data/transport/ Esp32Link (station session), StationLink (link codec), UsbSerialTransport, BleLinkTransport
data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager data/cam/ CamUseCaseRepository, where both hardware paths converge; PseudonymManager
data/log/ V2xLogger, V2xLogWriter (the V2X data logger) data/log/ V2xLogger, V2xLogWriter (the V2X data logger)
data/db/ Room database (sessions, trips, V2X messages) data/db/ Room database (sessions, trips, V2X messages)
data/ SensorRepository, GnssTimeSource, TripRepository, CsvExporter, TripExporter data/ SensorRepository, GnssTimeSource, RidePreferences, TripRepository, CsvExporter, TripExporter
domain/asn1/ BitReader/BitWriter, ItsTime, and the CAM, DENM, SPATEM, MAPEM and VAM UPER codecs domain/asn1/ BitReader/BitWriter, ItsTime, and the CAM, DENM, SPATEM, MAPEM and VAM UPER codecs
domain/map/ MAPEM intersection geometry: lanes, nodes, connections, maneuvers domain/map/ MAPEM intersection geometry: lanes, nodes, connections, maneuvers
domain/spat/ SPATEM signal state, and TrafficLights (SPATEM on MAPEM lanes, the rider's approach) domain/spat/ SPATEM signal state, and TrafficLights (SPATEM on MAPEM lanes, the rider's approach)
@@ -112,6 +114,7 @@ app/src/main/java/com/hawhamburg/micr0bu/
domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath domain/usecase/ UseCaseDetectionEngine, UseCaseDetectionConfig, AlertLevel, GeoMath
domain/detection/ EventDetector, RunningStats sliding window (orientation-independent) domain/detection/ EventDetector, RunningStats sliding window (orientation-independent)
domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig, Pseudonym domain/cam/ Cam, CamParser, PhoneCamBuilder, CamTransmitConfig, Pseudonym
domain/fusion/ Sensor fusion: YawRateEstimator (yaw rate about the vertical), PhoneMount
service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService service/ TripRecordingService, CamTransmitLoop, CamPinger, V2xLogService
obu-firmware/ ESP32-C5 OBU on Niklas Dathe's microbu-firmware (station, signing, BTP, GeoNetworking, obu-firmware/ ESP32-C5 OBU on Niklas Dathe's microbu-firmware (station, signing, BTP, GeoNetworking,
@@ -205,6 +208,7 @@ Never regenerate a golden fixture from this project's own encoder output. See `a
| [docs/MicrOBU-Technical-Documentation.docx](docs/MicrOBU-Technical-Documentation.docx) | Supervisors and stakeholders. Architecture, message path, verification, results, decisions | | [docs/MicrOBU-Technical-Documentation.docx](docs/MicrOBU-Technical-Documentation.docx) | Supervisors and stakeholders. Architecture, message path, verification, results, decisions |
| [docs/01-requirements-traceability.md](docs/01-requirements-traceability.md) | Requirements chapters 0 to 13 mapped to implementation and evidence | | [docs/01-requirements-traceability.md](docs/01-requirements-traceability.md) | Requirements chapters 0 to 13 mapped to implementation and evidence |
| [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md) | Signed ITS messages, VAM and the BLE link: who does what, link protocol, recovery, verification | | [docs/06-signed-its-vam-ble.md](docs/06-signed-its-vam-ble.md) | Signed ITS messages, VAM and the BLE link: who does what, link protocol, recovery, verification |
| [docs/07-sensor-fusion-logging.md](docs/07-sensor-fusion-logging.md) | Sensor fusion phases 0 and 1: yaw rate and GNSS time inputs, Ride settings, the fusion log schema, `tools/fusion_log_check.py`, test rides |
| [docs/Architecture-signed-its.drawio.png](docs/Architecture-signed-its.drawio.png) | Block diagram of the signed-ITS architecture | | [docs/Architecture-signed-its.drawio.png](docs/Architecture-signed-its.drawio.png) | Block diagram of the signed-ITS architecture |
| [05-obu-bench-test-2026-08-25.md](05-obu-bench-test-2026-08-25.md) | Bench campaign T1 to T9, measured results | | [05-obu-bench-test-2026-08-25.md](05-obu-bench-test-2026-08-25.md) | Bench campaign T1 to T9, measured results |
| [04-transmit-setup.md](04-transmit-setup.md) | Transmitter bring-up, radio configuration diagnosis, the TX bypass | | [04-transmit-setup.md](04-transmit-setup.md) | Transmitter bring-up, radio configuration diagnosis, the TX bypass |
+22
View File
@@ -5,6 +5,28 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware ## Waiting on hardware
### Sensor fusion phase 1: logging and test rides (added 2026-11-18)
Settings > Ride (phone position, Record motion sensors) and the fusion data in the V2X data logger,
described in `docs/07-sensor-fusion-logging.md`. Unit-tested and built; `tools/fusion_log_check.py`
tested on synthetic logs only. On the Pixel 9 Pro:
- [ ] Settings > Ride: Units is gone, Ride is there; the position and the switch survive an app restart.
- [ ] One-minute bench log with Record motion sensors on: the logger screen shows the mount, the motion
sensor count climbing by about 300 a second, and a raw GPS fix age; the file is named
`..._imu-<mount>.db`; `fusion_log_check.py` on it gives no FAIL (accel, gyro, gravity at about
100 Hz, `phone` and `phone_gps` fixes with `elapsed_ns`, `clock` rows with GNSS time).
- [ ] Screen off for 5 minutes during a log: no motion sensor gap over 1 s in the check (the log
service holds the CPU awake; confirm the sensors keep coming too).
- [ ] Record motion sensors off: the log has empty `imu` and `clock` tables, no `phone_gps` rows,
and no `_imu-` in its name, but still `meta.phone_mount`.
- [ ] Rides, 20-30 minutes each, mount set before Start, each with left and right turns, a
roundabout, stops of 10 s or more and if possible a bridge or underpass. Run the check on each
and keep the files for phase 2:
- [ ] handlebar
- [ ] bag (on the bike)
- [ ] pocket or backpack
### Sensor fusion phase 0: yaw rate about the vertical, fix times on GNSS time (added 2026-11-18) ### 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 The phone's own CAM/VAM now take the yaw rate from the gyroscope projected onto gravity
@@ -54,11 +54,12 @@ import com.hawhamburg.micr0bu.ui.screens.LanguageSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SettingsScreen import com.hawhamburg.micr0bu.ui.screens.SettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UnitsSettingsScreen import com.hawhamburg.micr0bu.ui.screens.RideSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.UseCaseAlertsSettingsScreen import com.hawhamburg.micr0bu.ui.screens.UseCaseAlertsSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.V2xLogSettingsScreen import com.hawhamburg.micr0bu.ui.screens.V2xLogSettingsScreen
import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
import com.hawhamburg.micr0bu.viewmodel.RideSettingsViewModel
import com.hawhamburg.micr0bu.viewmodel.SensorViewModel import com.hawhamburg.micr0bu.viewmodel.SensorViewModel
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
@@ -71,6 +72,7 @@ class MainActivity : AppCompatActivity() {
private val mqttViewModel: MqttViewModel by viewModels() private val mqttViewModel: MqttViewModel by viewModels()
private val tripViewModel: TripRecordingViewModel by viewModels() private val tripViewModel: TripRecordingViewModel by viewModels()
private val logViewModel: V2xLogViewModel by viewModels() private val logViewModel: V2xLogViewModel by viewModels()
private val rideViewModel: RideSettingsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen() installSplashScreen()
@@ -97,6 +99,8 @@ class MainActivity : AppCompatActivity() {
val esp32Transport by mqttViewModel.esp32Transport.collectAsState() val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState() val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
val signOutgoing by mqttViewModel.signOutgoing.collectAsState() val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
val phoneMount by rideViewModel.phoneMount.collectAsState()
val fusionLogging by rideViewModel.fusionLogging.collectAsState()
val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState() val esp32RxPath by mqttViewModel.esp32RxPath.collectAsState()
// Received hazards and live signal state, for the Dashboard's V2X summary cards. // Received hazards and live signal state, for the Dashboard's V2X summary cards.
// Both flows already expire their own entries on a clock, so nothing here has to // Both flows already expire their own entries on a clock, so nothing here has to
@@ -304,7 +308,7 @@ class MainActivity : AppCompatActivity() {
onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) }, onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) },
onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.route) }, onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.route) },
onOpenSensors = { navController.navigate(Screen.SettingsSensors.route) }, onOpenSensors = { navController.navigate(Screen.SettingsSensors.route) },
onOpenUnits = { navController.navigate(Screen.SettingsUnits.route) }, onOpenRide = { navController.navigate(Screen.SettingsRide.route) },
onOpenConnection = { navController.navigate(Screen.SettingsConnection.route) }, onOpenConnection = { navController.navigate(Screen.SettingsConnection.route) },
onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) }, onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) },
onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) }, onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) },
@@ -357,10 +361,12 @@ class MainActivity : AppCompatActivity() {
onBack = { navController.popBackStack() }, onBack = { navController.popBackStack() },
) )
} }
composable(Screen.SettingsUnits.route) { composable(Screen.SettingsRide.route) {
UnitsSettingsScreen( RideSettingsScreen(
useMetric = state.useMetric, phoneMount = phoneMount,
onUseMetric = viewModel::setUseMetric, onPhoneMount = rideViewModel::setPhoneMount,
fusionLogging = fusionLogging,
onFusionLogging = rideViewModel::setFusionLogging,
onBack = { navController.popBackStack() }, onBack = { navController.popBackStack() },
) )
} }
@@ -0,0 +1,49 @@
package com.hawhamburg.micr0bu.data
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
private val Context.rideDataStore by preferencesDataStore(name = "ride_prefs")
/**
* Settings > Ride: where the phone rides ([PhoneMount]) and whether the V2X data logger also
* records the motion sensors and raw GPS for sensor fusion (see `docs/07-sensor-fusion-logging.md`).
*/
@Singleton
class RidePreferences @Inject constructor(
@ApplicationContext private val context: Context,
) {
private object Keys {
val PHONE_MOUNT = stringPreferencesKey("phone_mount")
val FUSION_LOGGING = booleanPreferencesKey("fusion_logging")
}
val phoneMountFlow: Flow<PhoneMount> = context.rideDataStore.data.map { prefs ->
PhoneMount.fromId(prefs[Keys.PHONE_MOUNT])
}
suspend fun setPhoneMount(mount: PhoneMount) {
context.rideDataStore.edit { it[Keys.PHONE_MOUNT] = mount.id }
}
/**
* Off by default: at 100 Hz the motion sensors add about 300 rows a second, tens of MB per
* hour, which only a fusion test ride needs.
*/
val fusionLoggingFlow: Flow<Boolean> = context.rideDataStore.data.map { prefs ->
prefs[Keys.FUSION_LOGGING] ?: false
}
suspend fun setFusionLogging(enabled: Boolean) {
context.rideDataStore.edit { it[Keys.FUSION_LOGGING] = enabled }
}
}
@@ -6,6 +6,9 @@ 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.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.SystemClock 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
@@ -68,11 +71,11 @@ class SensorRepository(private val context: Context) {
* @param samplingPeriodUs a `SensorManager.SENSOR_DELAY_*` constant or a period in µs. The * @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`. * default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
*/ */
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> = fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs) sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> = fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs) sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs, handler)
fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD) fun magnetometerFlow(): Flow<ImuReading> = sensorFlow(Sensor.TYPE_MAGNETIC_FIELD)
@@ -84,9 +87,9 @@ class SensorRepository(private val context: Context) {
* the gyroscope. On a phone without it the raw accelerometer stands in, which still carries * the gyroscope. On a phone without it the raw accelerometer stands in, which still carries
* the bike's own accelerations and vibration. * the bike's own accelerations and vibration.
*/ */
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> = fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs) if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs, handler)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs) else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun barometerFlow(): Flow<Float> = callbackFlow { fun barometerFlow(): Flow<Float> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
@@ -120,11 +123,36 @@ class SensorRepository(private val context: Context) {
awaitClose { fusedLocation.removeLocationUpdates(callback) } awaitClose { fusedLocation.removeLocationUpdates(callback) }
} }
/**
* Fixes from the platform's `GPS_PROVIDER` alone, next to [gnssFlow]'s fused location: no Wi-Fi
* or cell positions mixed in and no smoothing by Google Play services, so a fusion filter sees
* the GNSS chip's own errors. As fast as the chip delivers (minimum time and distance 0); on
* most phones that is 1 Hz.
*/
@Suppress("MissingPermission")
fun gpsProviderFlow(): Flow<GnssReading> = callbackFlow {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val listener = LocationListener { loc -> trySend(loc.toReading()) }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, listener, context.mainLooper)
awaitClose { locationManager.removeUpdates(listener) }
}
/** "name (vendor), max N Hz" for the sensor of [type], or null if the phone has none. For log metadata. */
fun describeSensor(type: Int): String? = sensorManager.getDefaultSensor(type)?.let { s ->
val maxHz = if (s.minDelay > 0) ", max ${1_000_000 / s.minDelay} Hz" else ""
"${s.name} (${s.vendor})$maxHz"
}
fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null fun hasSensor(type: Int): Boolean = sensorManager.getDefaultSensor(type) != null
/**
* @param handler where sensor callbacks run; null for the main thread. A high-rate consumer
* passes a background handler so 100 Hz callbacks neither wait on nor slow down the UI.
*/
private fun sensorFlow( private fun sensorFlow(
type: Int, type: Int,
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
handler: Handler? = null,
): Flow<ImuReading> = callbackFlow { ): Flow<ImuReading> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(type) val sensor = sensorManager.getDefaultSensor(type)
if (sensor == null) { if (sensor == null) {
@@ -143,7 +171,7 @@ class SensorRepository(private val context: Context) {
} }
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {} override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
} }
sensorManager.registerListener(listener, sensor, samplingPeriodUs) sensorManager.registerListener(listener, sensor, samplingPeriodUs, handler)
awaitClose { sensorManager.unregisterListener(listener) } awaitClose { sensorManager.unregisterListener(listener) }
} }
} }
@@ -15,6 +15,13 @@ data class LogGnss(
val accuracyM: Double? = null, val accuracyM: Double? = null,
/** Epoch ms the fix was taken, so a stale fix shows as one instead of passing for current. */ /** Epoch ms the fix was taken, so a stale fix shows as one instead of passing for current. */
val fixMs: Long, val fixMs: Long,
/** The fix's own monotonic time (`Location.getElapsedRealtimeNanos`); phone fixes only. */
val elapsedNs: Long? = null,
/** 1-sigma speed and bearing accuracy, where the provider gives them; phone fixes only. */
val speedAccuracyMps: Double? = null,
val bearingAccuracyDeg: Double? = null,
/** The location provider, e.g. `fused` or `gps`; phone fixes only. */
val provider: String? = null,
) )
/** One received V2X message, ready to be written. */ /** One received V2X message, ready to be written. */
@@ -45,6 +52,18 @@ class LogMessage(
/** One GNSS fix for the `gnss` table: the receiver's own track, independent of any message. */ /** One GNSS fix for the `gnss` table: the receiver's own track, independent of any message. */
class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss) class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss)
/**
* One motion sensor sample for the `imu` table (sensor fusion logging only). [sensor] is `accel`,
* `gyro` or `gravity`; [elapsedNs] the sample's own `SensorEvent.timestamp`.
*/
class LogImuSample(val sensor: String, val elapsedNs: Long, val tsMs: Long, val x: Float, val y: Float, val z: Float)
/**
* The phone's three clocks read together, for the `clock` table: what lines the monotonic sensor
* and fix times up with wall-clock and GNSS time afterwards. [gnssMs] is null without GNSS time.
*/
class LogClockSample(val elapsedNs: Long, val wallMs: Long, val gnssMs: Long?)
/** /**
* A V2X log: one self-contained SQLite file. Not Room, on purpose: a log is a file the developer * A V2X log: one self-contained SQLite file. Not Room, on purpose: a log is a file the developer
* pulls off the phone and opens in any SQLite tool or pandas, so it carries its own schema and * pulls off the phone and opens in any SQLite tool or pandas, so it carries its own schema and
@@ -57,12 +76,19 @@ class LogGnssSample(val tsMs: Long, val source: String, val fix: LogGnss)
* Columns that do not apply to a row are NULL rather than invented: `rssi_dbm` is NULL for the * Columns that do not apply to a row are NULL rather than invented: `rssi_dbm` is NULL for the
* CiT One, `obu_*` is NULL when no OBU position is available (always on the ESP32-C5, which has no * CiT One, `obu_*` is NULL when no OBU position is available (always on the ESP32-C5, which has no
* GNSS), and the `sender_*` fields are NULL for messages the app has no decoder for. * GNSS), and the `sender_*` fields are NULL for messages the app has no decoder for.
*
* Schema 2 (2026-11-18) adds what sensor fusion needs, described in
* `docs/07-sensor-fusion-logging.md`: the monotonic time, accuracies and provider of each phone fix
* in `gnss`, and the `imu` and `clock` tables. Those two stay empty unless Settings > Ride >
* "Record motion sensors" was on when the log started.
*/ */
class V2xLogWriter(val file: File, meta: Map<String, String>) { class V2xLogWriter(val file: File, meta: Map<String, String>) {
private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null) private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null)
private val insertMessage: SQLiteStatement private val insertMessage: SQLiteStatement
private val insertGnss: SQLiteStatement private val insertGnss: SQLiteStatement
private val insertImu: SQLiteStatement
private val insertClock: SQLiteStatement
init { init {
db.execSQL( db.execSQL(
@@ -121,11 +147,39 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
speed_mps REAL, speed_mps REAL,
heading_deg REAL, heading_deg REAL,
accuracy_m REAL, accuracy_m REAL,
fix_ms INTEGER NOT NULL fix_ms INTEGER NOT NULL,
elapsed_ns INTEGER,
speed_accuracy_mps REAL,
bearing_accuracy_deg REAL,
provider TEXT
) )
""".trimIndent() """.trimIndent()
) )
db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)") db.execSQL("CREATE INDEX idx_gnss_ts ON gnss(ts_ms)")
// No index: about 300 rows a second, read back in order by replay, never searched on the phone.
db.execSQL(
"""
CREATE TABLE imu (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sensor TEXT NOT NULL,
elapsed_ns INTEGER NOT NULL,
ts_ms INTEGER NOT NULL,
x REAL NOT NULL,
y REAL NOT NULL,
z REAL NOT NULL
)
""".trimIndent()
)
db.execSQL(
"""
CREATE TABLE clock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
elapsed_ns INTEGER NOT NULL,
wall_ms INTEGER NOT NULL,
gnss_ms INTEGER
)
""".trimIndent()
)
// Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI. // Same rows, with the timestamp also as readable UTC, for anyone browsing in a SQLite GUI.
db.execSQL( db.execSQL(
"CREATE VIEW messages_v AS SELECT *, " + "CREATE VIEW messages_v AS SELECT *, " +
@@ -144,8 +198,14 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
"obu_heading_deg, obu_fix_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" "obu_heading_deg, obu_fix_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
) )
insertGnss = db.compileStatement( insertGnss = db.compileStatement(
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms) " + "INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms, " +
"VALUES (?,?,?,?,?,?,?,?,?)" "elapsed_ns, speed_accuracy_mps, bearing_accuracy_deg, provider) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertImu = db.compileStatement(
"INSERT INTO imu (sensor, elapsed_ns, ts_ms, x, y, z) VALUES (?,?,?,?,?,?)"
)
insertClock = db.compileStatement(
"INSERT INTO clock (elapsed_ns, wall_ms, gnss_ms) VALUES (?,?,?)"
) )
} }
@@ -153,13 +213,20 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value)) db.execSQL("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", arrayOf(key, value))
} }
/** Writes [messages] and [gnss] in one transaction. */ /** Writes all rows in one transaction. */
fun writeBatch(messages: List<LogMessage>, gnss: List<LogGnssSample>) { fun writeBatch(
if (messages.isEmpty() && gnss.isEmpty()) return messages: List<LogMessage>,
gnss: List<LogGnssSample>,
imu: List<LogImuSample> = emptyList(),
clock: List<LogClockSample> = emptyList(),
) {
if (messages.isEmpty() && gnss.isEmpty() && imu.isEmpty() && clock.isEmpty()) return
db.beginTransaction() db.beginTransaction()
try { try {
for (m in messages) bindAndRun(m) for (m in messages) bindAndRun(m)
for (g in gnss) bindAndRun(g) for (g in gnss) bindAndRun(g)
for (i in imu) bindAndRun(i)
for (c in clock) bindAndRun(c)
db.setTransactionSuccessful() db.setTransactionSuccessful()
} finally { } finally {
db.endTransaction() db.endTransaction()
@@ -169,6 +236,8 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
fun close() { fun close() {
runCatching { insertMessage.close() } runCatching { insertMessage.close() }
runCatching { insertGnss.close() } runCatching { insertGnss.close() }
runCatching { insertImu.close() }
runCatching { insertClock.close() }
runCatching { db.close() } runCatching { db.close() }
} }
@@ -220,6 +289,31 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
s.bind(7, g.fix.headingDeg) s.bind(7, g.fix.headingDeg)
s.bind(8, g.fix.accuracyM) s.bind(8, g.fix.accuracyM)
s.bind(9, g.fix.fixMs) s.bind(9, g.fix.fixMs)
s.bind(10, g.fix.elapsedNs)
s.bind(11, g.fix.speedAccuracyMps)
s.bind(12, g.fix.bearingAccuracyDeg)
s.bind(13, g.fix.provider)
s.executeInsert()
}
private fun bindAndRun(i: LogImuSample) {
val s = insertImu
s.clearBindings()
s.bind(1, i.sensor)
s.bind(2, i.elapsedNs)
s.bind(3, i.tsMs)
s.bind(4, i.x.toDouble())
s.bind(5, i.y.toDouble())
s.bind(6, i.z.toDouble())
s.executeInsert()
}
private fun bindAndRun(c: LogClockSample) {
val s = insertClock
s.clearBindings()
s.bind(1, c.elapsedNs)
s.bind(2, c.wallMs)
s.bind(3, c.gnssMs)
s.executeInsert() s.executeInsert()
} }
@@ -230,6 +324,6 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
private fun SQLiteStatement.bind(i: Int, v: ByteArray?) { if (v != null) bindBlob(i, v) } private fun SQLiteStatement.bind(i: Int, v: ByteArray?) { if (v != null) bindBlob(i, v) }
companion object { companion object {
const val SCHEMA_VERSION = 1 const val SCHEMA_VERSION = 2
} }
} }
@@ -1,9 +1,16 @@
package com.hawhamburg.micr0bu.data.log package com.hawhamburg.micr0bu.data.log
import android.content.Context import android.content.Context
import android.hardware.Sensor
import android.location.LocationManager
import android.os.Build import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log import android.util.Log
import com.hawhamburg.micr0bu.data.GnssReading import com.hawhamburg.micr0bu.data.GnssReading
import com.hawhamburg.micr0bu.data.ImuReading
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.data.SensorRepository import com.hawhamburg.micr0bu.data.SensorRepository
import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository import com.hawhamburg.micr0bu.data.cam.CamUseCaseRepository
import com.hawhamburg.micr0bu.data.mqtt.MessageDirection import com.hawhamburg.micr0bu.data.mqtt.MessageDirection
@@ -23,6 +30,7 @@ import com.hawhamburg.micr0bu.domain.asn1.RealAsn1UperCodec
import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec import com.hawhamburg.micr0bu.domain.asn1.MapemUperCodec
import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec import com.hawhamburg.micr0bu.domain.asn1.SpatemUperCodec
import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser import com.hawhamburg.micr0bu.domain.cam.ObuGnssParser
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.log.ItsMessageKind import com.hawhamburg.micr0bu.domain.log.ItsMessageKind
import com.hawhamburg.micr0bu.domain.log.classifyItsPdu import com.hawhamburg.micr0bu.domain.log.classifyItsPdu
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
@@ -32,14 +40,18 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import java.io.File import java.io.File
import java.time.DateTimeException
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
@@ -52,9 +64,18 @@ private const val PROCESSED_PREFIX = "v2x-uca/output/json/"
private const val OBU_GNSS_TOPIC = "v2x/rx/obu_gnss" private const val OBU_GNSS_TOPIC = "v2x/rx/obu_gnss"
private const val SOURCE_ESP32 = "esp32" private const val SOURCE_ESP32 = "esp32"
private const val SOURCE_CIT_ONE = "cit_one" private const val SOURCE_CIT_ONE = "cit_one"
/** The phone's fused location (Google Play services). */
private const val SOURCE_PHONE = "phone" private const val SOURCE_PHONE = "phone"
/** The phone's raw `GPS_PROVIDER` fixes; sensor fusion logging only. */
private const val SOURCE_PHONE_GPS = "phone_gps"
private const val SOURCE_OBU = "obu" private const val SOURCE_OBU = "obu"
/** Motion sensor rate while sensor fusion logging is on: 10 000 us, 100 Hz. */
private const val IMU_PERIOD_US = 10_000
/** How often the three clocks are read together into the `clock` table. */
private const val CLOCK_INTERVAL_MS = 1_000L
/** How long the writer collects rows before it commits them. */ /** How long the writer collects rows before it commits them. */
private const val FLUSH_INTERVAL_MS = 250L private const val FLUSH_INTERVAL_MS = 250L
@@ -70,6 +91,13 @@ data class V2xLogState(
/** Age of the newest phone / OBU fix at the time of the last update; null if none yet. */ /** Age of the newest phone / OBU fix at the time of the last update; null if none yet. */
val phoneFixAgeMs: Long? = null, val phoneFixAgeMs: Long? = null,
val obuFixAgeMs: Long? = null, val obuFixAgeMs: Long? = null,
/** Whether this log records the motion sensors and raw GPS (Settings > Ride), and the mount it started with. */
val fusionLogging: Boolean = false,
val phoneMount: PhoneMount? = null,
/** Motion sensor rows written so far. */
val imuSamples: Long = 0L,
/** Age of the newest raw GPS_PROVIDER fix; null if none yet or not logging it. */
val phoneGpsFixAgeMs: Long? = null,
/** Set when the file could not be created or written. */ /** Set when the file could not be created or written. */
val error: String? = null, val error: String? = null,
) )
@@ -101,6 +129,11 @@ data class V2xLogFile(val file: File, val sizeBytes: Long, val modifiedMs: Long,
* BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only * BTP ports 2001-2004 and 2018 (see `gn_unwrap.c`; MAPEM and VAM since firmware d0fcb45), and only
* messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One. * messages of up to 494 bytes, so road MAPEMs often reach an ESP32 log only over the CiT One.
* *
* With Settings > Ride > "Record motion sensors" on when the log starts, it also records what sensor
* fusion needs (`docs/07-sensor-fusion-logging.md`): accelerometer, gyroscope and gravity at 100 Hz
* into `imu`, the raw `GPS_PROVIDER` fixes next to the fused ones in `gnss`, and the three phone
* clocks once a second into `clock`. The phone mount is recorded in `meta` either way.
*
* A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService] * A singleton, like the repositories it listens to. [com.hawhamburg.micr0bu.service.V2xLogService]
* keeps the process alive and the CPU awake while a log runs; this class does the work. * keeps the process alive and the CPU awake while a log runs; this class does the work.
*/ */
@@ -111,6 +144,7 @@ class V2xLogger @Inject constructor(
private val esp32Link: Esp32Link, private val esp32Link: Esp32Link,
private val camUseCaseRepository: CamUseCaseRepository, private val camUseCaseRepository: CamUseCaseRepository,
private val camCodec: RealAsn1UperCodec, private val camCodec: RealAsn1UperCodec,
private val ridePreferences: RidePreferences,
) { ) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -127,15 +161,22 @@ class V2xLogger @Inject constructor(
private var rows = Channel<Any>(Channel.UNLIMITED) private var rows = Channel<Any>(Channel.UNLIMITED)
@Volatile private var phoneFix: LogGnss? = null @Volatile private var phoneFix: LogGnss? = null
@Volatile private var phoneGpsFix: LogGnss? = null
@Volatile private var obuFix: LogGnss? = null @Volatile private var obuFix: LogGnss? = null
fun start() { fun start() {
if (session?.isActive == true) return if (session?.isActive == true) return
val startedMs = System.currentTimeMillis() val startedMs = System.currentTimeMillis()
val hardware = mqttRepository.obuHardware.value val hardware = mqttRepository.obuHardware.value
val file = File(logDir, fileNameFor(startedMs, hardware)) // Read once, at the start: a log is one mount and one mode, so changing either mid-log
// must not quietly mix two kinds of data in one file. DataStore answers in milliseconds.
val (mount, fusion) = runBlocking {
ridePreferences.phoneMountFlow.first() to ridePreferences.fusionLoggingFlow.first()
}
val sensors = SensorRepository(context)
val file = File(logDir, fileNameFor(startedMs, hardware, mount.takeIf { fusion }))
val writer = try { val writer = try {
V2xLogWriter(file, metaFor(startedMs, hardware)) V2xLogWriter(file, metaFor(startedMs, hardware, mount, fusion, sensors))
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "cannot create ${file.name}", e) Log.e(TAG, "cannot create ${file.name}", e)
file.delete() file.delete()
@@ -143,22 +184,36 @@ class V2xLogger @Inject constructor(
return return
} }
phoneFix = null phoneFix = null
phoneGpsFix = null
obuFix = null obuFix = null
rows = Channel(Channel.UNLIMITED) rows = Channel(Channel.UNLIMITED)
_state.value = V2xLogState(active = true, fileName = file.name, startedMs = startedMs) _state.value = V2xLogState(
active = true, fileName = file.name, startedMs = startedMs,
fusionLogging = fusion, phoneMount = mount,
)
refreshFiles() refreshFiles()
// Sensor callbacks at 100 Hz get a thread of their own, off the main thread.
val sensorThread = if (fusion) HandlerThread("V2xLogger-imu").apply { start() } else null
session = scope.launch { session = scope.launch {
val sources = listOf( val sources = mutableListOf(
launch { collectEsp32() }, launch { collectEsp32() },
launch { collectCitOneRaw() }, launch { collectCitOneRaw() },
launch { collectCitOneMessages() }, launch { collectCitOneMessages() },
launch { collectPhoneGnss() }, launch { collectPhoneGnss(sensors) },
) )
if (sensorThread != null) {
val handler = Handler(sensorThread.looper)
sources += launch { collectImu(sensors, handler) }
sources += launch { collectPhoneGps(sensors) }
sources += launch { collectClock() }
}
try { try {
runWriter(writer, file) runWriter(writer, file)
} finally { } finally {
sources.forEach { it.cancel() } sources.forEach { it.cancel() }
sensorThread?.quitSafely()
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) } runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
writer.close() writer.close()
} }
@@ -258,8 +313,7 @@ class V2xLogger @Inject constructor(
* can be started before the location permission is granted, and a single attempt would then * can be started before the location permission is granted, and a single attempt would then
* leave every row without a phone position for the whole run. * leave every row without a phone position for the whole run.
*/ */
private suspend fun collectPhoneGnss() { private suspend fun collectPhoneGnss(sensors: SensorRepository) {
val sensors = SensorRepository(context)
while (true) { while (true) {
runCatching { runCatching {
sensors.gnssFlow().collect { reading -> sensors.gnssFlow().collect { reading ->
@@ -272,6 +326,50 @@ class V2xLogger @Inject constructor(
} }
} }
/** Raw `GPS_PROVIDER` fixes, retried like [collectPhoneGnss] in case permission comes later. */
private suspend fun collectPhoneGps(sensors: SensorRepository) {
while (true) {
runCatching {
sensors.gpsProviderFlow().collect { reading ->
val fix = reading.toLogGnss()
phoneGpsFix = fix
rows.trySend(LogGnssSample(System.currentTimeMillis(), SOURCE_PHONE_GPS, fix))
}
}
delay(5_000L)
}
}
/** Accelerometer, gyroscope and gravity at 100 Hz, each sample with its own monotonic time. */
private suspend fun collectImu(sensors: SensorRepository, handler: Handler) = coroutineScope {
launch { sensors.accelerometerFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("accel")) } }
launch { sensors.gyroscopeFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gyro")) } }
// Only from the real TYPE_GRAVITY sensor: gravityFlow's accelerometer stand-in would only
// repeat the accel rows under another name.
if (sensors.hasSensor(Sensor.TYPE_GRAVITY)) {
launch { sensors.gravityFlow(IMU_PERIOD_US, handler).collect { rows.trySend(it.toLogImu("gravity")) } }
}
}
/**
* The monotonic, wall and GNSS clocks read back to back once a second. Sensor samples and fixes
* carry monotonic time, messages and OBU fixes wall time, and the transmit path GNSS time; these
* rows convert between them, and show the phone clock's error and any step in it.
*/
private suspend fun collectClock() {
while (true) {
val elapsedNs = SystemClock.elapsedRealtimeNanos()
val wallMs = System.currentTimeMillis()
val gnssMs = try {
SystemClock.currentGnssTimeClock().millis()
} catch (e: DateTimeException) {
null
}
rows.trySend(LogClockSample(elapsedNs, wallMs, gnssMs))
delay(CLOCK_INTERVAL_MS)
}
}
// ── Rows ────────────────────────────────────────────────────────────────── // ── Rows ──────────────────────────────────────────────────────────────────
private fun enqueueRaw( private fun enqueueRaw(
@@ -344,20 +442,23 @@ class V2xLogger @Inject constructor(
var failure: String? = null var failure: String? = null
val messages = ArrayList<LogMessage>() val messages = ArrayList<LogMessage>()
val gnss = ArrayList<LogGnssSample>() val gnss = ArrayList<LogGnssSample>()
val imu = ArrayList<LogImuSample>()
val clock = ArrayList<LogClockSample>()
var imuTotal = 0L
while (true) { while (true) {
// Block for the first row of a batch, give more a moment to arrive, then take // Block for the first row of a batch, give more a moment to arrive, then take
// whatever is queued. No timeout around receive: a cancelled receive can lose the // whatever is queued. No timeout around receive: a cancelled receive can lose the
// element it was handing over, which a logger must not do. // element it was handing over, which a logger must not do.
val first = rows.receiveCatching().getOrNull() ?: break val first = rows.receiveCatching().getOrNull() ?: break
add(first, messages, gnss) add(first, messages, gnss, imu, clock)
delay(FLUSH_INTERVAL_MS) delay(FLUSH_INTERVAL_MS)
while (true) { while (true) {
val next = rows.tryReceive().getOrNull() ?: break val next = rows.tryReceive().getOrNull() ?: break
add(next, messages, gnss) add(next, messages, gnss, imu, clock)
} }
try { try {
writer.writeBatch(messages, gnss) writer.writeBatch(messages, gnss, imu, clock)
} catch (e: Exception) { } catch (e: Exception) {
// Disk full or the file went away. Say so on screen rather than logging into a void. // Disk full or the file went away. Say so on screen rather than logging into a void.
Log.e(TAG, "write failed", e) Log.e(TAG, "write failed", e)
@@ -367,7 +468,8 @@ class V2xLogger @Inject constructor(
} }
for (m in messages) counts.merge(m.kind, 1, Int::plus) for (m in messages) counts.merge(m.kind, 1, Int::plus)
total += messages.size total += messages.size
messages.clear(); gnss.clear() imuTotal += imu.size
messages.clear(); gnss.clear(); imu.clear(); clock.clear()
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
_state.update { _state.update {
@@ -375,16 +477,26 @@ class V2xLogger @Inject constructor(
counts = counts.toMap(), total = total, fileBytes = file.length(), counts = counts.toMap(), total = total, fileBytes = file.length(),
phoneFixAgeMs = phoneFix?.let { f -> now - f.fixMs }, phoneFixAgeMs = phoneFix?.let { f -> now - f.fixMs },
obuFixAgeMs = obuFix?.let { f -> now - f.fixMs }, obuFixAgeMs = obuFix?.let { f -> now - f.fixMs },
imuSamples = imuTotal,
phoneGpsFixAgeMs = phoneGpsFix?.let { f -> now - f.fixMs },
) )
} }
} }
_state.update { it.copy(fileBytes = file.length(), error = failure ?: it.error, active = it.active && failure == null) } _state.update { it.copy(fileBytes = file.length(), error = failure ?: it.error, active = it.active && failure == null) }
} }
private fun add(row: Any, messages: MutableList<LogMessage>, gnss: MutableList<LogGnssSample>) { private fun add(
row: Any,
messages: MutableList<LogMessage>,
gnss: MutableList<LogGnssSample>,
imu: MutableList<LogImuSample>,
clock: MutableList<LogClockSample>,
) {
when (row) { when (row) {
is LogMessage -> messages += row is LogMessage -> messages += row
is LogGnssSample -> gnss += row is LogGnssSample -> gnss += row
is LogImuSample -> imu += row
is LogClockSample -> clock += row
} }
} }
@@ -402,15 +514,31 @@ class V2xLogger @Inject constructor(
latitude = latitude, longitude = longitude, altitudeM = altitude, latitude = latitude, longitude = longitude, altitudeM = altitude,
speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(), speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(),
accuracyM = accuracyM.toDouble(), fixMs = timestamp, accuracyM = accuracyM.toDouble(), fixMs = timestamp,
elapsedNs = elapsedRealtimeNanos,
speedAccuracyMps = speedAccuracyMps?.toDouble(),
bearingAccuracyDeg = bearingAccuracyDeg?.toDouble(),
provider = provider,
) )
private fun fileNameFor(startedMs: Long, hardware: ObuHardware): String { private fun ImuReading.toLogImu(sensor: String) =
LogImuSample(sensor, elapsedRealtimeNanos, timestamp, x, y, z)
/** `v2x_log_<start>_<hardware>.db`, with `_imu-<mount>` when it records sensor fusion data. */
private fun fileNameFor(startedMs: Long, hardware: ObuHardware, fusionMount: PhoneMount?): String {
val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(startedMs)) val stamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(startedMs))
val mode = if (hardware == ObuHardware.ESP32_C5) "esp32" else "citone" val mode = if (hardware == ObuHardware.ESP32_C5) "esp32" else "citone"
return "v2x_log_${stamp}_$mode.db" val fusion = fusionMount?.let { "_imu-${it.id}" }.orEmpty()
return "v2x_log_${stamp}_$mode$fusion.db"
} }
private fun metaFor(startedMs: Long, hardware: ObuHardware) = mapOf( private fun metaFor(
startedMs: Long,
hardware: ObuHardware,
mount: PhoneMount,
fusion: Boolean,
sensors: SensorRepository,
): Map<String, String> {
val meta = linkedMapOf(
"started_ms" to startedMs.toString(), "started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one", "hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}", "phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
@@ -418,7 +546,22 @@ class V2xLogger @Inject constructor(
"app_version" to runCatching { "app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?" context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"), }.getOrDefault("?"),
"phone_mount" to mount.id,
"fusion_logging" to fusion.toString(),
"note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " + "note" to "ts_ms is phone wall-clock epoch ms. payload is the ITS PDU as UPER bytes. " +
"rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5.", "rssi_dbm is NULL on the CiT One; obu_* is NULL on the ESP32-C5. gnss.source: phone = " +
"fused location, phone_gps = raw GPS_PROVIDER, obu = the CiT One's obu_gnss. " +
"elapsed_ns is SystemClock.elapsedRealtimeNanos; the clock table converts it to wall " +
"and GNSS time. See docs/07-sensor-fusion-logging.md.",
) )
if (fusion) {
meta["imu_period_us"] = IMU_PERIOD_US.toString()
sensors.describeSensor(Sensor.TYPE_ACCELEROMETER)?.let { meta["sensor_accel"] = it }
sensors.describeSensor(Sensor.TYPE_GYROSCOPE)?.let { meta["sensor_gyro"] = it }
meta["sensor_gravity"] = sensors.describeSensor(Sensor.TYPE_GRAVITY) ?: "none (not logged)"
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
meta["gnss_hardware"] = "${lm.gnssHardwareModelName ?: "?"} (year ${lm.gnssYearOfHardware})"
}
return meta
}
} }
@@ -0,0 +1,25 @@
package com.hawhamburg.micr0bu.domain.fusion
/**
* Where the phone rides, as set in Settings > Ride.
*
* The sensor fusion filter treats the motion sensors differently per mount: on the handlebar the
* phone is fixed to the bike (but turns with the steering), in a bag on the bike it is mostly fixed
* but can shift, and in a pocket or backpack it moves with the rider's body, so shoulder checks look
* like turns. Every V2X log records the setting (`meta.phone_mount`), so a recorded ride says which
* mount it was.
*
* [id] is what is stored and logged; it must not change once logs exist.
*/
enum class PhoneMount(val id: String) {
HANDLEBAR("handlebar"),
BAG("bag"),
POCKET("pocket");
companion object {
val DEFAULT = HANDLEBAR
/** The mount stored under [id], or [DEFAULT] for a missing or unknown value. */
fun fromId(id: String?): PhoneMount = entries.firstOrNull { it.id == id } ?: DEFAULT
}
}
@@ -46,7 +46,7 @@ sealed class Screen(val route: String, val labelRes: Int) {
data object SettingsLanguage : Screen("settings/language", R.string.settings_language) data object SettingsLanguage : Screen("settings/language", R.string.settings_language)
data object SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance) data object SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance)
data object SettingsSensors : Screen("settings/sensors", R.string.settings_sensors) data object SettingsSensors : Screen("settings/sensors", R.string.settings_sensors)
data object SettingsUnits : Screen("settings/units", R.string.settings_units) data object SettingsRide : Screen("settings/ride", R.string.settings_ride)
data object SettingsConnection : Screen("settings/connection", R.string.settings_connection) data object SettingsConnection : Screen("settings/connection", R.string.settings_connection)
data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section) data object SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts) data object SettingsUseCaseAlerts : Screen("settings/usecases", R.string.settings_usecase_alerts)
@@ -4,6 +4,7 @@ import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -51,6 +52,7 @@ import com.hawhamburg.micr0bu.data.transport.Esp32RxPath
import com.hawhamburg.micr0bu.data.transport.Esp32Transport import com.hawhamburg.micr0bu.data.transport.Esp32Transport
import com.hawhamburg.micr0bu.data.transport.ObuHardware import com.hawhamburg.micr0bu.data.transport.ObuHardware
import com.hawhamburg.micr0bu.data.transport.OutgoingMessage import com.hawhamburg.micr0bu.data.transport.OutgoingMessage
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionConfig import com.hawhamburg.micr0bu.domain.usecase.UseCaseDetectionConfig
import com.hawhamburg.micr0bu.domain.usecase.UseCaseType import com.hawhamburg.micr0bu.domain.usecase.UseCaseType
import com.hawhamburg.micr0bu.viewmodel.SensorUiState import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -69,7 +71,7 @@ fun SettingsScreen(
onOpenLanguage: () -> Unit, onOpenLanguage: () -> Unit,
onOpenAppearance: () -> Unit, onOpenAppearance: () -> Unit,
onOpenSensors: () -> Unit, onOpenSensors: () -> Unit,
onOpenUnits: () -> Unit, onOpenRide: () -> Unit,
onOpenConnection: () -> Unit, onOpenConnection: () -> Unit,
onOpenMqtt: () -> Unit, onOpenMqtt: () -> Unit,
onOpenUseCaseAlerts: () -> Unit, onOpenUseCaseAlerts: () -> Unit,
@@ -100,7 +102,7 @@ fun SettingsScreen(
RowDivider() RowDivider()
MenuRow(stringResource(R.string.settings_sensors), onOpenSensors) MenuRow(stringResource(R.string.settings_sensors), onOpenSensors)
RowDivider() RowDivider()
MenuRow(stringResource(R.string.settings_units), onOpenUnits) MenuRow(stringResource(R.string.settings_ride), onOpenRide)
RowDivider() RowDivider()
MenuRow(stringResource(R.string.settings_connection), onOpenConnection) MenuRow(stringResource(R.string.settings_connection), onOpenConnection)
RowDivider() RowDivider()
@@ -385,19 +387,51 @@ fun SensorsSettingsScreen(
} }
} }
/**
* Settings > Ride. Replaced the old Units screen: the app is metric throughout, so that switch had
* nothing to switch. Where the phone rides, and whether the V2X data logger also records the motion
* sensors and raw GPS for sensor fusion (`docs/07-sensor-fusion-logging.md`).
*/
@Composable @Composable
fun UnitsSettingsScreen( fun RideSettingsScreen(
useMetric: Boolean, phoneMount: PhoneMount,
onUseMetric: (Boolean) -> Unit, onPhoneMount: (PhoneMount) -> Unit,
fusionLogging: Boolean,
onFusionLogging: (Boolean) -> Unit,
onBack: () -> Unit, onBack: () -> Unit,
) { ) {
SubScreen(stringResource(R.string.settings_units), onBack) { SubScreen(stringResource(R.string.settings_ride), onBack) {
Text(
stringResource(R.string.settings_ride_mount_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard { SectionCard {
SettingToggleRow(stringResource(R.string.settings_metric), useMetric, onUseMetric) Choice(
label = stringResource(R.string.settings_ride_mount),
options = PhoneMount.entries.map { it to stringResource(phoneMountLabel(it)) },
selected = phoneMount,
onSelect = onPhoneMount,
)
}
Text(
stringResource(R.string.settings_ride_fusion_log_desc),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SectionCard {
SettingToggleRow(stringResource(R.string.settings_ride_fusion_log), fusionLogging, onFusionLogging)
} }
} }
} }
/** The display name of a [PhoneMount]; also used by the V2X logger screen. */
internal fun phoneMountLabel(mount: PhoneMount): Int = when (mount) {
PhoneMount.HANDLEBAR -> R.string.settings_ride_mount_handlebar
PhoneMount.BAG -> R.string.settings_ride_mount_bag
PhoneMount.POCKET -> R.string.settings_ride_mount_pocket
}
@Composable @Composable
fun MqttSettingsScreen( fun MqttSettingsScreen(
mqttPrefs: MqttPrefs, mqttPrefs: MqttPrefs,
@@ -717,6 +751,40 @@ private fun TwoWayChoice(
} }
} }
/** [TwoWayChoice] for any number of options: a labelled row of outlined buttons, the selected one filled. */
@Composable
private fun <T> Choice(
label: String,
options: List<Pair<T, String>>,
selected: T,
onSelect: (T) -> Unit,
) {
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
Spacer(Modifier.height(6.dp))
Row(
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
for ((value, text) in options) {
val isSelected = value == selected
OutlinedButton(
onClick = { onSelect(value) },
modifier = Modifier.weight(1f),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
),
) { Text(text, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, maxLines = 1) }
}
}
}
@Composable @Composable
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)) private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@@ -150,6 +150,21 @@ fun V2xLogSettingsScreen(
stringResource(R.string.v2xlog_obu_gnss), stringResource(R.string.v2xlog_obu_gnss),
if (isEsp32) stringResource(R.string.v2xlog_not_available) else fixAge(state.obuFixAgeMs), if (isEsp32) stringResource(R.string.v2xlog_not_available) else fixAge(state.obuFixAgeMs),
) )
Divider()
DisabledRow(
stringResource(R.string.v2xlog_fusion),
if (state.fusionLogging && state.phoneMount != null) {
stringResource(R.string.v2xlog_fusion_on, stringResource(phoneMountLabel(state.phoneMount)))
} else {
stringResource(R.string.v2xlog_fusion_off)
},
)
if (state.fusionLogging) {
Divider()
DisabledRow(stringResource(R.string.v2xlog_imu), state.imuSamples.toString())
Divider()
DisabledRow(stringResource(R.string.v2xlog_phone_gps), fixAge(state.phoneGpsFixAgeMs))
}
} }
if (state.total == 0) { if (state.total == 0) {
Text( Text(
@@ -0,0 +1,33 @@
package com.hawhamburg.micr0bu.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hawhamburg.micr0bu.data.RidePreferences
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Backs Settings > Ride. */
@HiltViewModel
class RideSettingsViewModel @Inject constructor(
private val prefs: RidePreferences,
) : ViewModel() {
val phoneMount: StateFlow<PhoneMount> =
prefs.phoneMountFlow.stateIn(viewModelScope, SharingStarted.Eagerly, PhoneMount.DEFAULT)
val fusionLogging: StateFlow<Boolean> =
prefs.fusionLoggingFlow.stateIn(viewModelScope, SharingStarted.Eagerly, false)
fun setPhoneMount(mount: PhoneMount) {
viewModelScope.launch { prefs.setPhoneMount(mount) }
}
fun setFusionLogging(enabled: Boolean) {
viewModelScope.launch { prefs.setFusionLogging(enabled) }
}
}
@@ -65,7 +65,6 @@ data class SensorUiState(
val barometerEnabled: Boolean = true, val barometerEnabled: Boolean = true,
val gnssEnabled: Boolean = true, val gnssEnabled: Boolean = true,
val developerMode: Boolean = true, val developerMode: Boolean = true,
val useMetric: Boolean = true,
val darkTheme: Boolean = true, val darkTheme: Boolean = true,
) )
@@ -295,6 +294,5 @@ class SensorViewModel(application: Application) : AndroidViewModel(application)
if (!v) _state.value = _state.value.copy(gnss = null) if (!v) _state.value = _state.value.copy(gnss = null)
} }
fun setDeveloperMode(v: Boolean) { _state.value = _state.value.copy(developerMode = v) } fun setDeveloperMode(v: Boolean) { _state.value = _state.value.copy(developerMode = v) }
fun setUseMetric(v: Boolean) { _state.value = _state.value.copy(useMetric = v) }
fun setDarkTheme(v: Boolean) { _state.value = _state.value.copy(darkTheme = v) } fun setDarkTheme(v: Boolean) { _state.value = _state.value.copy(darkTheme = v) }
} }
+13 -2
View File
@@ -169,8 +169,14 @@
<string name="settings_gyro">Gyroskop</string> <string name="settings_gyro">Gyroskop</string>
<string name="settings_magnet">Magnetometer</string> <string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string> <string name="settings_baro">Barometer</string>
<string name="settings_units">Einheiten</string> <string name="settings_ride">Fahrt</string>
<string name="settings_metric">Metrisch (m, km/h, hPa)</string> <string name="settings_ride_mount">Position des Telefons</string>
<string name="settings_ride_mount_handlebar">Lenker</string>
<string name="settings_ride_mount_bag">Tasche</string>
<string name="settings_ride_mount_pocket">Hosentasche</string>
<string name="settings_ride_mount_desc">Wo das Telefon mitfährt: in einer Lenkerhalterung, in einer Tasche am Fahrrad oder in einer Hosentasche bzw. einem Rucksack. Die Sensorfusion wertet die Bewegungssensoren je nach Position anders aus, und jedes V2X-Log hält sie fest.</string>
<string name="settings_ride_fusion_log">Bewegungssensoren aufzeichnen</string>
<string name="settings_ride_fusion_log_desc">Für Testfahrten zur Sensorfusion: Der V2X-Datenlogger zeichnet zusätzlich Beschleunigungssensor, Gyroskop und Schwerkraft mit 100 Hz auf, sowie rohe GPS-Positionen neben der fusionierten Position. Das sind einige zehn MB pro Stunde.</string>
<string name="settings_mqtt_section">MQTT-Broker</string> <string name="settings_mqtt_section">MQTT-Broker</string>
<string name="settings_broker_ip">Broker-IP</string> <string name="settings_broker_ip">Broker-IP</string>
<string name="settings_port">Port</string> <string name="settings_port">Port</string>
@@ -358,6 +364,11 @@
<string name="v2xlog_total_val">%1$d Nachrichten · %2$s</string> <string name="v2xlog_total_val">%1$d Nachrichten · %2$s</string>
<string name="v2xlog_phone_gnss">Telefon-GNSS</string> <string name="v2xlog_phone_gnss">Telefon-GNSS</string>
<string name="v2xlog_obu_gnss">OBU-GNSS</string> <string name="v2xlog_obu_gnss">OBU-GNSS</string>
<string name="v2xlog_fusion">Daten für Sensorfusion</string>
<string name="v2xlog_fusion_off">aus (Einstellungen > Fahrt)</string>
<string name="v2xlog_fusion_on">an · Telefon: %1$s</string>
<string name="v2xlog_imu">Bewegungssensor-Messwerte</string>
<string name="v2xlog_phone_gps">Telefon-GPS (roh)</string>
<string name="v2xlog_fix_age">Fix vor %1$d s</string> <string name="v2xlog_fix_age">Fix vor %1$d s</string>
<string name="v2xlog_no_fix">kein Fix</string> <string name="v2xlog_no_fix">kein Fix</string>
<string name="v2xlog_not_available">nicht verfügbar</string> <string name="v2xlog_not_available">nicht verfügbar</string>
+13 -2
View File
@@ -170,8 +170,14 @@
<string name="settings_gyro">Gyroscope</string> <string name="settings_gyro">Gyroscope</string>
<string name="settings_magnet">Magnetometer</string> <string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string> <string name="settings_baro">Barometer</string>
<string name="settings_units">Units</string> <string name="settings_ride">Ride</string>
<string name="settings_metric">Metric (m, km/h, hPa)</string> <string name="settings_ride_mount">Phone position</string>
<string name="settings_ride_mount_handlebar">Handlebar</string>
<string name="settings_ride_mount_bag">Bag</string>
<string name="settings_ride_mount_pocket">Pocket</string>
<string name="settings_ride_mount_desc">Where the phone rides: on a handlebar mount, in a bag on the bike, or in a pocket or backpack. Sensor fusion reads the motion sensors differently for each, and every V2X log records it.</string>
<string name="settings_ride_fusion_log">Record motion sensors</string>
<string name="settings_ride_fusion_log_desc">For sensor fusion test rides: the V2X data logger also records accelerometer, gyroscope and gravity at 100 Hz, and raw GPS fixes next to the fused location. Adds tens of MB per hour.</string>
<string name="settings_mqtt_section">MQTT Broker</string> <string name="settings_mqtt_section">MQTT Broker</string>
<string name="settings_broker_ip">Broker IP</string> <string name="settings_broker_ip">Broker IP</string>
<string name="settings_port">Port</string> <string name="settings_port">Port</string>
@@ -365,6 +371,11 @@
<string name="v2xlog_total_val">%1$d messages · %2$s</string> <string name="v2xlog_total_val">%1$d messages · %2$s</string>
<string name="v2xlog_phone_gnss">Phone GNSS</string> <string name="v2xlog_phone_gnss">Phone GNSS</string>
<string name="v2xlog_obu_gnss">OBU GNSS</string> <string name="v2xlog_obu_gnss">OBU GNSS</string>
<string name="v2xlog_fusion">Sensor fusion data</string>
<string name="v2xlog_fusion_off">off (Settings > Ride)</string>
<string name="v2xlog_fusion_on">on · phone on %1$s</string>
<string name="v2xlog_imu">Motion sensor samples</string>
<string name="v2xlog_phone_gps">Phone GPS (raw)</string>
<string name="v2xlog_fix_age">fix %1$d s ago</string> <string name="v2xlog_fix_age">fix %1$d s ago</string>
<string name="v2xlog_no_fix">no fix</string> <string name="v2xlog_no_fix">no fix</string>
<string name="v2xlog_not_available">not available</string> <string name="v2xlog_not_available">not available</string>
@@ -0,0 +1,25 @@
package com.hawhamburg.micr0bu
import com.hawhamburg.micr0bu.domain.fusion.PhoneMount
import org.junit.Assert.assertEquals
import org.junit.Test
/** The stored and logged ids of [PhoneMount] are a file format: logs on disk carry them. */
class PhoneMountTest {
@Test
fun `ids are the ones written to settings and logs`() {
assertEquals(listOf("handlebar", "bag", "pocket"), PhoneMount.entries.map { it.id })
}
@Test
fun `every id reads back as its mount`() {
PhoneMount.entries.forEach { assertEquals(it, PhoneMount.fromId(it.id)) }
}
@Test
fun `a missing or unknown id falls back to the handlebar`() {
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId(null))
assertEquals(PhoneMount.HANDLEBAR, PhoneMount.fromId("roof"))
}
}
+131
View File
@@ -0,0 +1,131 @@
# 07 – Sensor fusion, phase 0 and 1: inputs and logging (2026-11-18)
The goal is a GNSS/IMU fusion filter on the phone that gives the CAM and VAM a fresh position at
every send, plus a better heading, yaw rate and acceleration, on any phone mount. Phase 0 fixed the
inputs the transmit path already had. Phase 1 records everything the filter needs, so the filter can
be built and tuned offline against real rides before it touches what goes on air. Hardware checks
still to do are in `TODO.md` ("Sensor fusion ...").
## Phases
| Phase | What | State |
|---|---|---|
| 0 | Correct inputs: yaw rate about the vertical, fix times on GNSS time, monotonic clock for intervals | done (727c911, sign fix 6fa91d1) |
| 1 | Logging: motion sensors, both phone GNSS sources, clocks, phone mount | done, rides pending |
| 2 | Filter core: 5-state EKF (position, heading, speed, gyro bias), pure Kotlin, replayed on phase 1 logs | next |
| 3 | Any mount: forward-axis estimate, rigidity check, mount-dependent noise | after 2 |
| 4 | Offline tuning: GNSS outage drift, heading vs. course over ground, innovation statistics | with 2 and 3 |
| 5 | Into CAM/VAM, the confidence ellipse and the use-case engine, behind a switch | last |
## Phase 0 in short
- **Yaw rate** is the gyroscope projected onto gravity (`domain/fusion/YawRateEstimator`), the
rotation about the true vertical however the phone is held, averaged over 100 ms, at
`SENSOR_DELAY_GAME`. The gyroscope's z axis alone was only right with the phone flat, screen up.
- **Time on air** is the GNSS time of the fix itself: its monotonic age
(`Location.getElapsedRealtimeNanos`) taken off GNSS time now (`GnssTimeSource.atElapsedRealtime`).
The phone's clock setting, or a step of it, cannot reach the CAM or GN timestamps.
- **Intervals** (elevated CAM rate, VAM generation rules, acceleration from GNSS speed) use the
monotonic clock, so setting the phone clock back cannot hold VAMs off.
- **Yaw rate sign**: the CAM's YawRateValue is positive to the left; the app's `Cam.yawRateDps` is
positive to the right. `CamUperCodec` and `CamParser` flip it; the CiT One's `obu_gnss` sends it
right-positive already (checked against logged rides), so `ObuGnssParser` does not.
## Settings > Ride
Replaces the old Units screen (the app is metric throughout; that switch did nothing).
- **Phone position**: Handlebar, Bag (on the bike) or Pocket (also a backpack). Stored in
`RidePreferences` as `handlebar` / `bag` / `pocket` and written into every V2X log as
`meta.phone_mount`. The filter will use it to choose how much to trust the gyroscope: fixed to the
bike on the handlebar (but turning with the steering), mostly fixed in a bag, moving with the
rider's body in a pocket. It is a manual setting; detecting the mount from the sensors is phase 3
work, and these labelled logs are what it would be built and checked on.
- **Record motion sensors**: off by default. When on at the moment a V2X log starts, that log also
records the data below. It adds about 300 rows a second, tens of MB per hour.
Both are read once when a log starts, so one file is always one mount and one mode. Changing them
mid-log takes effect from the next log.
## What a fusion log contains
Settings > Developer > V2X data logger, with Record motion sensors on. File name
`v2x_log_<start>_<hardware>_imu-<mount>.db` (without the suffix when it is off). Schema version 2
(`meta.schema_version`, `PRAGMA user_version`); version 1 logs have no `imu` or `clock` table and
none of the new `gnss` columns.
### `imu` (new)
| Column | |
|---|---|
| `sensor` | `accel` (m/s², gravity included), `gyro` (rad/s), `gravity` (m/s², `TYPE_GRAVITY`, points up) |
| `elapsed_ns` | the sample's own `SensorEvent.timestamp`, on `SystemClock.elapsedRealtimeNanos` |
| `ts_ms` | the same instant as wall-clock epoch ms, for browsing only |
| `x`, `y`, `z` | device frame: x right, y up the screen, z out of the screen |
Requested at 100 Hz (`meta.imu_period_us` = 10000), on a background thread of its own. `gravity` is
only logged when the phone has a real `TYPE_GRAVITY` sensor (the Pixel 9 Pro does); the sensors'
names, vendors and maximum rates are in `meta.sensor_*`.
### `gnss` (new columns)
| Column | |
|---|---|
| `source` | `phone` = fused location (Google Play services, as before), `phone_gps` = raw `GPS_PROVIDER` (new, fusion logging only), `obu` = the CiT One's `obu_gnss` |
| `elapsed_ns` | the fix's own monotonic time; phone sources only. What fusion lines fixes up with sensor samples on |
| `speed_accuracy_mps`, `bearing_accuracy_deg` | 1-sigma, where the provider gives them |
| `provider` | `fused` or `gps` |
`fix_ms` is the fix's instant as wall-clock ms and `ts_ms` when the app received it, so
`ts_ms - fix_ms` is the delivery delay. The fused and the raw source are logged side by side because
the Pixel's fused location includes Google's city-street corrections while the raw one is the chip
alone and not pre-filtered; the rides decide which one the filter uses. `meta.gnss_hardware` names
the GNSS chip.
### `clock` (new)
Once a second, the three phone clocks read back to back: `elapsed_ns` (monotonic), `wall_ms` (the
phone clock), `gnss_ms` (`SystemClock.currentGnssTimeClock`, NULL without GNSS time). Sensor samples
and phone fixes carry monotonic time, received messages and OBU fixes wall time, and the transmit
path GNSS time; these rows convert between them, and show the phone clock's error and any step in it.
## Checking a log
```
py -3.11 tools/fusion_log_check.py v2x_log_..._imu-handlebar.db
```
Read-only, standard library only. Per file it prints the metadata, each sensor's sample count, rate,
interval distribution, gaps and magnitude, each GNSS source's rate, accuracy, delivery delay and
whether its fixes fall inside the sensor recording, the distance between the fused and raw fixes
(and the OBU's, on the CiT One), and the phone clock's error and steps. It ends with PASS, WARN or
FAIL lines, and exits with 1 if anything failed:
- FAIL: logging was off, no `imu`/`clock` table, a sensor missing, a sensor gap over 1 s, a phone
source missing, phone fixes without `elapsed_ns`.
- WARN: a sensor rate outside 80–130 Hz, gaps over 100 ms, an accelerometer or gravity magnitude far
from g, a GNSS gap over 5 s, fixes with no gyroscope sample within 20 ms, no GNSS time, a phone
clock step, a log that was not stopped cleanly.
Tested against synthetic logs built from `V2xLogWriter`'s own table definitions (a clean ride, an
injected 300 ms gyroscope gap, a 14-minute clock step, logging off, fixes without monotonic time);
not yet against a real ride.
## Test rides
Recorded per mount (handlebar, bag, pocket), 20–30 minutes each, with Record motion sensors on and the
phone mount set before pressing Start. Each ride should include left and right turns, a roundabout,
stops of at least 10 s (the filter estimates the gyroscope offset while standing), and if possible a
bridge or underpass for a real GNSS outage. The list to tick off is in `TODO.md`.
## Code
| | |
|---|---|
| `domain/fusion/PhoneMount.kt` | the mount setting and its stored ids |
| `data/RidePreferences.kt`, `viewmodel/RideSettingsViewModel.kt` | Settings > Ride storage and screen state |
| `ui/screens/SettingsScreen.kt` (`RideSettingsScreen`) | the screen |
| `data/SensorRepository.kt` | `gpsProviderFlow`, sensor flows on a chosen thread, `describeSensor` |
| `data/log/V2xLogger.kt`, `data/log/V2xLogWriter.kt` | the logging and the schema |
| `ui/screens/V2xLogSettingsScreen.kt` | shows mount, motion sensor row count and raw GPS fix age while logging |
| `tools/fusion_log_check.py` | the check above |
+244
View File
@@ -0,0 +1,244 @@
"""Checks a V2X log recorded with Settings > Ride > "Record motion sensors" on, before it is used for
sensor fusion: are the motion sensors complete and at their rate, are both phone GNSS sources there,
and do the clocks line up. See docs/07-sensor-fusion-logging.md.
py -3.11 tools/fusion_log_check.py LOG.db [LOG.db ...]
Pull a log off the phone with Share on the V2X data logger screen, or with
adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/<name>.db > <name>.db
Reads the file read-only. Prints a report per file and ends with PASS, WARN or FAIL lines; the exit
code is 1 if any file has a FAIL. Standard library only.
"""
import math
import sqlite3
import statistics
import sys
from bisect import bisect_left
from pathlib import Path
IMU_SENSORS = ('accel', 'gyro', 'gravity')
G = 9.80665
# What a usable fusion log looks like. Rates are what the logger asks for (100 Hz); the phone may
# deliver a little more or less.
IMU_RATE_MIN_HZ, IMU_RATE_MAX_HZ = 80.0, 130.0
IMU_GAP_WARN_MS, IMU_GAP_FAIL_MS = 100.0, 1000.0
GNSS_GAP_WARN_S = 5.0
class Report:
def __init__(self):
self.verdicts = []
def line(self, text=''):
print(text)
def verdict(self, level, text):
self.verdicts.append((level, text))
@property
def failed(self):
return any(level == 'FAIL' for level, _ in self.verdicts)
def pct(values, q):
"""The q-th percentile (0..100) of a non-empty list, nearest rank."""
s = sorted(values)
return s[min(len(s) - 1, max(0, math.ceil(q / 100 * len(s)) - 1))]
def haversine_m(lat1, lon1, lat2, lon2):
r = 6_371_000.0
p1, p2 = math.radians(lat1), math.radians(lat2)
a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
def tables(db):
return {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
def check_meta(db, rep):
meta = dict(db.execute('SELECT key, value FROM meta'))
rep.line('meta')
for key in ('schema_version', 'phone', 'android_sdk', 'app_version', 'hardware', 'phone_mount',
'fusion_logging', 'imu_period_us', 'sensor_accel', 'sensor_gyro', 'sensor_gravity',
'gnss_hardware', 'started_ms', 'ended_ms'):
if key in meta:
rep.line(f' {key:15} {meta[key]}')
if int(meta.get('schema_version', '1')) < 2:
rep.verdict('FAIL', 'schema version below 2: recorded before sensor fusion logging existed')
if meta.get('fusion_logging') != 'true':
rep.verdict('FAIL', 'fusion_logging is not on: turn on Settings > Ride > Record motion sensors before starting the log')
if 'ended_ms' not in meta:
rep.verdict('WARN', 'no ended_ms: the log was not stopped cleanly (app killed?); data up to the last batch is still usable')
return meta
def check_imu(db, rep):
rep.line('imu')
spans = {}
for sensor in IMU_SENSORS:
t = [r[0] for r in db.execute('SELECT elapsed_ns FROM imu WHERE sensor=? ORDER BY id', (sensor,))]
if not t:
level = 'WARN' if sensor == 'gravity' else 'FAIL'
rep.line(f' {sensor:8} no samples')
rep.verdict(level, f'imu {sensor}: no samples')
continue
backwards = sum(1 for a, b in zip(t, t[1:]) if b <= a)
ts = sorted(t)
dts = [(b - a) / 1e6 for a, b in zip(ts, ts[1:]) if b > a]
span_s = (ts[-1] - ts[0]) / 1e9
rate = (len(ts) - 1) / span_s if span_s > 0 else 0.0
max_gap = max(dts) if dts else 0.0
gaps = sum(1 for d in dts if d > IMU_GAP_WARN_MS)
spans[sensor] = (ts[0], ts[-1])
rep.line(f' {sensor:8} {len(ts):8d} samples over {span_s:7.1f} s = {rate:6.1f} Hz, '
f'dt median {statistics.median(dts):5.2f} ms, p99 {pct(dts, 99):6.2f} ms, max {max_gap:7.1f} ms, '
f'{gaps} gaps > {IMU_GAP_WARN_MS:.0f} ms, {backwards} out of order')
if not IMU_RATE_MIN_HZ <= rate <= IMU_RATE_MAX_HZ:
rep.verdict('WARN', f'imu {sensor}: {rate:.1f} Hz, expected about 100')
if max_gap > IMU_GAP_FAIL_MS:
rep.verdict('FAIL', f'imu {sensor}: a gap of {max_gap / 1000:.1f} s (screen off without the log service? app paused?)')
elif gaps:
rep.verdict('WARN', f'imu {sensor}: {gaps} gaps over {IMU_GAP_WARN_MS:.0f} ms')
if backwards:
rep.verdict('WARN', f'imu {sensor}: {backwards} samples not after the previous one in write order')
# Magnitudes: accelerometer and gravity should average to g; the gyroscope tells how much it turned.
mags = [math.sqrt(x * x + y * y + z * z) for x, y, z in
db.execute('SELECT x, y, z FROM imu WHERE sensor=?', (sensor,))]
unit = 'rad/s' if sensor == 'gyro' else 'm/s^2'
rep.line(f' {"":8} |v| median {statistics.median(mags):.3f} {unit}, p95 {pct(mags, 95):.3f}')
if sensor in ('accel', 'gravity') and abs(statistics.median(mags) - G) > 0.5:
rep.verdict('WARN', f'imu {sensor}: median magnitude {statistics.median(mags):.2f}, expected about {G:.2f}')
return spans
def check_gnss(db, rep, imu_spans):
rep.line('gnss')
sources = [r[0] for r in db.execute('SELECT DISTINCT source FROM gnss ORDER BY source')]
by_source = {}
imu_t = [r[0] for r in db.execute("SELECT elapsed_ns FROM imu WHERE sensor='gyro' ORDER BY elapsed_ns")]
for src in sources:
rows = list(db.execute(
'SELECT ts_ms, fix_ms, elapsed_ns, lat, lon, accuracy_m, speed_mps, speed_accuracy_mps, '
'bearing_accuracy_deg, provider FROM gnss WHERE source=? ORDER BY id', (src,)))
by_source[src] = rows
fix_ms = [r[1] for r in rows]
dts = [(b - a) / 1000 for a, b in zip(fix_ms, fix_ms[1:]) if b > a]
acc = [r[5] for r in rows if r[5] is not None]
latency = [r[0] - r[1] for r in rows]
with_elapsed = sum(1 for r in rows if r[2] is not None)
with_speed_acc = sum(1 for r in rows if r[7] is not None)
with_bearing_acc = sum(1 for r in rows if r[8] is not None)
providers = sorted({r[9] for r in rows if r[9]})
rate = 1 / statistics.median(dts) if dts else 0.0
rep.line(f' {src:9} {len(rows):6d} fixes, interval median {statistics.median(dts) if dts else 0:5.2f} s '
f'({rate:4.1f} Hz), max {max(dts) if dts else 0:6.1f} s, accuracy median '
f'{statistics.median(acc) if acc else float("nan"):5.1f} m p95 {pct(acc, 95) if acc else float("nan"):5.1f} m')
rep.line(f' {"":9} received after the fix: median {statistics.median(latency):.0f} ms, p95 {pct(latency, 95):.0f} ms; '
f'elapsed_ns {with_elapsed}/{len(rows)}, speed accuracy {with_speed_acc}, bearing accuracy {with_bearing_acc}; '
f'provider {", ".join(providers) or "-"}')
if dts and max(dts) > GNSS_GAP_WARN_S:
rep.verdict('WARN', f'gnss {src}: a gap of {max(dts):.1f} s between fixes')
if src in ('phone', 'phone_gps') and with_elapsed < len(rows):
rep.verdict('FAIL', f'gnss {src}: {len(rows) - with_elapsed} fixes without elapsed_ns, which fusion lines up on')
if src in ('phone', 'phone_gps') and imu_t:
inside = sum(1 for r in rows if r[2] is not None and imu_t[0] <= r[2] <= imu_t[-1])
covered = sum(1 for r in rows if r[2] is not None and _near(imu_t, r[2], 20_000_000))
rep.line(f' {"":9} {inside}/{len(rows)} fixes inside the gyro recording, {covered} with a gyro sample within 20 ms')
if inside and covered < inside:
rep.verdict('WARN', f'gnss {src}: {inside - covered} fixes inside the recording with no gyro sample within 20 ms')
for needed in ('phone', 'phone_gps'):
if needed not in by_source:
rep.verdict('FAIL', f'gnss: no {needed} fixes'
+ (' (location permission? GPS off?)' if needed == 'phone_gps' else ''))
if 'phone' in by_source and 'phone_gps' in by_source:
compare_sources(rep, by_source['phone_gps'], by_source['phone'], 'phone_gps vs phone (fused)')
if 'obu' in by_source and 'phone_gps' in by_source:
compare_sources(rep, by_source['phone_gps'], by_source['obu'], 'phone_gps vs obu', key=1, tol_ms=500)
def _near(sorted_t, t, tol):
i = bisect_left(sorted_t, t)
return any(0 <= j < len(sorted_t) and abs(sorted_t[j] - t) <= tol for j in (i - 1, i))
def compare_sources(rep, a_rows, b_rows, label, key=2, tol_ms=500):
"""Horizontal distance between two sources' fixes taken at about the same time (key: 2 = elapsed_ns, 1 = fix_ms)."""
scale = 1_000_000 if key == 2 else 1
b = sorted((r[key], r[3], r[4]) for r in b_rows if r[key] is not None)
bt = [x[0] for x in b]
d = []
for r in a_rows:
if r[key] is None:
continue
i = bisect_left(bt, r[key])
best = min((j for j in (i - 1, i) if 0 <= j < len(b)), key=lambda j: abs(bt[j] - r[key]), default=None)
if best is not None and abs(bt[best] - r[key]) <= tol_ms * scale:
d.append(haversine_m(r[3], r[4], b[best][1], b[best][2]))
if d:
rep.line(f' {label}: {len(d)} pairs within {tol_ms} ms, distance median {statistics.median(d):.1f} m, '
f'p95 {pct(d, 95):.1f} m, max {max(d):.1f} m')
def check_clock(db, rep):
rep.line('clock')
rows = list(db.execute('SELECT elapsed_ns, wall_ms, gnss_ms FROM clock ORDER BY id'))
if not rows:
rep.verdict('FAIL', 'clock: no rows')
return
with_gnss = [r for r in rows if r[2] is not None]
# Wall clock against the monotonic clock: a step shows up as a jump in their difference.
off = [r[1] - r[0] / 1e6 for r in rows]
steps = [(b - a) for a, b in zip(off, off[1:]) if abs(b - a) > 100]
rep.line(f' {len(rows)} rows, {len(with_gnss)} with GNSS time')
if with_gnss:
err = [r[1] - r[2] for r in with_gnss]
rep.line(f' phone clock minus GNSS time: median {statistics.median(err):+.0f} ms, '
f'range {min(err):+.0f} .. {max(err):+.0f} ms')
else:
rep.verdict('WARN', 'clock: no GNSS time at all (no fix for the whole log?)')
if steps:
rep.line(f' phone clock stepped {len(steps)} times: ' + ', '.join(f'{s:+.0f} ms' for s in steps[:10]))
rep.verdict('WARN', f'clock: the phone clock stepped {len(steps)} times; use elapsed_ns and the clock table, not ts_ms, to line data up')
def check(path):
rep = Report()
print(f'== {path}')
db = sqlite3.connect(f'file:{Path(path).as_posix()}?mode=ro', uri=True)
have = tables(db)
if 'meta' not in have:
rep.verdict('FAIL', 'not a MicrOBU V2X log (no meta table)')
else:
check_meta(db, rep)
if not {'imu', 'clock'} <= have:
rep.verdict('FAIL', 'no imu/clock tables: recorded with an app from before sensor fusion logging')
else:
spans = check_imu(db, rep)
check_gnss(db, rep, spans)
check_clock(db, rep)
db.close()
for level, text in rep.verdicts:
print(f'{level}: {text}')
if not rep.verdicts:
print('PASS: ready for sensor fusion')
elif not any(level in ('FAIL', 'WARN') for level, _ in rep.verdicts):
print('PASS')
print()
return rep.failed
def main(argv):
if not argv:
print(__doc__)
return 2
failed = [p for p in argv if check(p)]
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))