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
@@ -54,11 +54,12 @@ import com.hawhamburg.micr0bu.ui.screens.LanguageSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.MqttSettingsScreen
import com.hawhamburg.micr0bu.ui.screens.SensorsSettingsScreen
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.V2xLogSettingsScreen
import com.hawhamburg.micr0bu.ui.theme.MicrOBUTheme
import com.hawhamburg.micr0bu.viewmodel.MqttViewModel
import com.hawhamburg.micr0bu.viewmodel.RideSettingsViewModel
import com.hawhamburg.micr0bu.viewmodel.SensorViewModel
import com.hawhamburg.micr0bu.viewmodel.TripRecordingViewModel
import com.hawhamburg.micr0bu.viewmodel.V2xLogViewModel
@@ -71,6 +72,7 @@ class MainActivity : AppCompatActivity() {
private val mqttViewModel: MqttViewModel by viewModels()
private val tripViewModel: TripRecordingViewModel by viewModels()
private val logViewModel: V2xLogViewModel by viewModels()
private val rideViewModel: RideSettingsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
@@ -97,6 +99,8 @@ class MainActivity : AppCompatActivity() {
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
val outgoingMessage by mqttViewModel.outgoingMessage.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()
// 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
@@ -304,7 +308,7 @@ class MainActivity : AppCompatActivity() {
onOpenLanguage = { navController.navigate(Screen.SettingsLanguage.route) },
onOpenAppearance = { navController.navigate(Screen.SettingsAppearance.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) },
onOpenMqtt = { navController.navigate(Screen.SettingsMqtt.route) },
onOpenUseCaseAlerts = { navController.navigate(Screen.SettingsUseCaseAlerts.route) },
@@ -357,11 +361,13 @@ class MainActivity : AppCompatActivity() {
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsUnits.route) {
UnitsSettingsScreen(
useMetric = state.useMetric,
onUseMetric = viewModel::setUseMetric,
onBack = { navController.popBackStack() },
composable(Screen.SettingsRide.route) {
RideSettingsScreen(
phoneMount = phoneMount,
onPhoneMount = rideViewModel::setPhoneMount,
fusionLogging = fusionLogging,
onFusionLogging = rideViewModel::setFusionLogging,
onBack = { navController.popBackStack() },
)
}
composable(Screen.SettingsMqtt.route) {
@@ -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.SensorManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Handler
import android.os.SystemClock
import com.google.android.gms.location.LocationCallback
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
* default suits the sensor screen; the transmit path asks for `SENSOR_DELAY_GAME`.
*/
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
fun accelerometerFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs)
fun gyroscopeFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
sensorFlow(Sensor.TYPE_GYROSCOPE, samplingPeriodUs, handler)
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 bike's own accelerations and vibration.
*/
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs)
fun gravityFlow(samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI, handler: Handler? = null): Flow<ImuReading> =
if (hasSensor(Sensor.TYPE_GRAVITY)) sensorFlow(Sensor.TYPE_GRAVITY, samplingPeriodUs, handler)
else sensorFlow(Sensor.TYPE_ACCELEROMETER, samplingPeriodUs, handler)
fun barometerFlow(): Flow<Float> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE)
@@ -120,11 +123,36 @@ class SensorRepository(private val context: Context) {
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
/**
* @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(
type: Int,
samplingPeriodUs: Int = SensorManager.SENSOR_DELAY_UI,
handler: Handler? = null,
): Flow<ImuReading> = callbackFlow {
val sensor = sensorManager.getDefaultSensor(type)
if (sensor == null) {
@@ -143,7 +171,7 @@ class SensorRepository(private val context: Context) {
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}
sensorManager.registerListener(listener, sensor, samplingPeriodUs)
sensorManager.registerListener(listener, sensor, samplingPeriodUs, handler)
awaitClose { sensorManager.unregisterListener(listener) }
}
}
@@ -15,6 +15,13 @@ data class LogGnss(
val accuracyM: Double? = null,
/** Epoch ms the fix was taken, so a stale fix shows as one instead of passing for current. */
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. */
@@ -45,6 +52,18 @@ class LogMessage(
/** 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)
/**
* 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
* 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
* 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.
*
* 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>) {
private val db: SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null)
private val insertMessage: SQLiteStatement
private val insertGnss: SQLiteStatement
private val insertImu: SQLiteStatement
private val insertClock: SQLiteStatement
init {
db.execSQL(
@@ -121,11 +147,39 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
speed_mps REAL,
heading_deg 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()
)
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.
db.execSQL(
"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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
)
insertGnss = db.compileStatement(
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms) " +
"VALUES (?,?,?,?,?,?,?,?,?)"
"INSERT INTO gnss (ts_ms, source, lat, lon, alt_m, speed_mps, heading_deg, accuracy_m, fix_ms, " +
"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))
}
/** Writes [messages] and [gnss] in one transaction. */
fun writeBatch(messages: List<LogMessage>, gnss: List<LogGnssSample>) {
if (messages.isEmpty() && gnss.isEmpty()) return
/** Writes all rows in one transaction. */
fun writeBatch(
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()
try {
for (m in messages) bindAndRun(m)
for (g in gnss) bindAndRun(g)
for (i in imu) bindAndRun(i)
for (c in clock) bindAndRun(c)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
@@ -169,6 +236,8 @@ class V2xLogWriter(val file: File, meta: Map<String, String>) {
fun close() {
runCatching { insertMessage.close() }
runCatching { insertGnss.close() }
runCatching { insertImu.close() }
runCatching { insertClock.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(8, g.fix.accuracyM)
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()
}
@@ -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) }
companion object {
const val SCHEMA_VERSION = 1
const val SCHEMA_VERSION = 2
}
}
@@ -1,9 +1,16 @@
package com.hawhamburg.micr0bu.data.log
import android.content.Context
import android.hardware.Sensor
import android.location.LocationManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
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.cam.CamUseCaseRepository
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.SpatemUperCodec
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.classifyItsPdu
import dagger.hilt.android.qualifiers.ApplicationContext
@@ -32,14 +40,18 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import java.io.File
import java.time.DateTimeException
import java.text.SimpleDateFormat
import java.util.Date
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 SOURCE_ESP32 = "esp32"
private const val SOURCE_CIT_ONE = "cit_one"
/** The phone's fused location (Google Play services). */
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"
/** 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. */
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. */
val phoneFixAgeMs: 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. */
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
* 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]
* 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 camUseCaseRepository: CamUseCaseRepository,
private val camCodec: RealAsn1UperCodec,
private val ridePreferences: RidePreferences,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -127,15 +161,22 @@ class V2xLogger @Inject constructor(
private var rows = Channel<Any>(Channel.UNLIMITED)
@Volatile private var phoneFix: LogGnss? = null
@Volatile private var phoneGpsFix: LogGnss? = null
@Volatile private var obuFix: LogGnss? = null
fun start() {
if (session?.isActive == true) return
val startedMs = System.currentTimeMillis()
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 {
V2xLogWriter(file, metaFor(startedMs, hardware))
V2xLogWriter(file, metaFor(startedMs, hardware, mount, fusion, sensors))
} catch (e: Exception) {
Log.e(TAG, "cannot create ${file.name}", e)
file.delete()
@@ -143,22 +184,36 @@ class V2xLogger @Inject constructor(
return
}
phoneFix = null
phoneGpsFix = null
obuFix = null
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()
// 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 {
val sources = listOf(
val sources = mutableListOf(
launch { collectEsp32() },
launch { collectCitOneRaw() },
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 {
runWriter(writer, file)
} finally {
sources.forEach { it.cancel() }
sensorThread?.quitSafely()
runCatching { writer.setMeta("ended_ms", System.currentTimeMillis().toString()) }
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
* leave every row without a phone position for the whole run.
*/
private suspend fun collectPhoneGnss() {
val sensors = SensorRepository(context)
private suspend fun collectPhoneGnss(sensors: SensorRepository) {
while (true) {
runCatching {
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 ──────────────────────────────────────────────────────────────────
private fun enqueueRaw(
@@ -344,20 +442,23 @@ class V2xLogger @Inject constructor(
var failure: String? = null
val messages = ArrayList<LogMessage>()
val gnss = ArrayList<LogGnssSample>()
val imu = ArrayList<LogImuSample>()
val clock = ArrayList<LogClockSample>()
var imuTotal = 0L
while (true) {
// 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
// element it was handing over, which a logger must not do.
val first = rows.receiveCatching().getOrNull() ?: break
add(first, messages, gnss)
add(first, messages, gnss, imu, clock)
delay(FLUSH_INTERVAL_MS)
while (true) {
val next = rows.tryReceive().getOrNull() ?: break
add(next, messages, gnss)
add(next, messages, gnss, imu, clock)
}
try {
writer.writeBatch(messages, gnss)
writer.writeBatch(messages, gnss, imu, clock)
} catch (e: Exception) {
// Disk full or the file went away. Say so on screen rather than logging into a void.
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)
total += messages.size
messages.clear(); gnss.clear()
imuTotal += imu.size
messages.clear(); gnss.clear(); imu.clear(); clock.clear()
val now = System.currentTimeMillis()
_state.update {
@@ -375,16 +477,26 @@ class V2xLogger @Inject constructor(
counts = counts.toMap(), total = total, fileBytes = file.length(),
phoneFixAgeMs = phoneFix?.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) }
}
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) {
is LogMessage -> messages += row
is LogGnssSample -> gnss += row
is LogImuSample -> imu += row
is LogClockSample -> clock += row
}
}
@@ -402,23 +514,54 @@ class V2xLogger @Inject constructor(
latitude = latitude, longitude = longitude, altitudeM = altitude,
speedMps = speedMs.toDouble(), headingDeg = bearingDeg.toDouble(),
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 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(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.getOrDefault("?"),
"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.",
)
private fun metaFor(
startedMs: Long,
hardware: ObuHardware,
mount: PhoneMount,
fusion: Boolean,
sensors: SensorRepository,
): Map<String, String> {
val meta = linkedMapOf(
"started_ms" to startedMs.toString(),
"hardware" to if (hardware == ObuHardware.ESP32_C5) "esp32_c5" else "cit_one",
"phone" to "${Build.MANUFACTURER} ${Build.MODEL}",
"android_sdk" to Build.VERSION.SDK_INT.toString(),
"app_version" to runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "?"
}.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. " +
"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 SettingsAppearance : Screen("settings/appearance", R.string.settings_appearance)
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 SettingsMqtt : Screen("settings/mqtt", R.string.settings_mqtt_section)
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.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.ObuHardware
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.UseCaseType
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -69,7 +71,7 @@ fun SettingsScreen(
onOpenLanguage: () -> Unit,
onOpenAppearance: () -> Unit,
onOpenSensors: () -> Unit,
onOpenUnits: () -> Unit,
onOpenRide: () -> Unit,
onOpenConnection: () -> Unit,
onOpenMqtt: () -> Unit,
onOpenUseCaseAlerts: () -> Unit,
@@ -100,7 +102,7 @@ fun SettingsScreen(
RowDivider()
MenuRow(stringResource(R.string.settings_sensors), onOpenSensors)
RowDivider()
MenuRow(stringResource(R.string.settings_units), onOpenUnits)
MenuRow(stringResource(R.string.settings_ride), onOpenRide)
RowDivider()
MenuRow(stringResource(R.string.settings_connection), onOpenConnection)
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
fun UnitsSettingsScreen(
useMetric: Boolean,
onUseMetric: (Boolean) -> Unit,
fun RideSettingsScreen(
phoneMount: PhoneMount,
onPhoneMount: (PhoneMount) -> Unit,
fusionLogging: Boolean,
onFusionLogging: (Boolean) -> 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 {
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
fun MqttSettingsScreen(
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
private fun RowDivider() = HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
@@ -150,6 +150,21 @@ fun V2xLogSettingsScreen(
stringResource(R.string.v2xlog_obu_gnss),
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) {
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 gnssEnabled: Boolean = true,
val developerMode: Boolean = true,
val useMetric: 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)
}
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) }
}
+13 -2
View File
@@ -169,8 +169,14 @@
<string name="settings_gyro">Gyroskop</string>
<string name="settings_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_units">Einheiten</string>
<string name="settings_metric">Metrisch (m, km/h, hPa)</string>
<string name="settings_ride">Fahrt</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_broker_ip">Broker-IP</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_phone_gnss">Telefon-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_no_fix">kein Fix</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_magnet">Magnetometer</string>
<string name="settings_baro">Barometer</string>
<string name="settings_units">Units</string>
<string name="settings_metric">Metric (m, km/h, hPa)</string>
<string name="settings_ride">Ride</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_broker_ip">Broker IP</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_phone_gnss">Phone 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_no_fix">no fix</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"))
}
}