Colota - Android GPS Location tracker
fix(profiles): require fixes before a stationary profile activates (#641)
Max Dietrichf3bcf21a9204
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex bccef1e3..3f658757 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -152,7 +152,7 @@ An Android foreground service that runs continuously for GPS tracking. Manages:- Anchor points - a synthetic location saved on zone exit as a clean start point for the departing trip, timestamped 1s before the first real GPS fix- Battery critical shutdown (below 5% while unplugged), detected via a battery-broadcast receiver so it fires even while GPS is paused in a zone- Location accuracy filtering-- Stationary detection - pauses GPS after 60s without movement; resume is driven by the shared `MotionStateDetector` (accelerometer variance, with SIG_MOTION as a fast-path for sharp wake events). Suspended during entry delay and inside geofence pause zones.+- Stationary detection - slows GPS to the profile's interval after 60s of fixes without movement; resume is driven by the shared `MotionStateDetector` (accelerometer variance, with SIG_MOTION as a fast-path for sharp wake events). It keeps working inside a pause zone and during an entry delay, since fixes reach `ProfileManager` before the in-zone drop; only a hold that stops the stream can prevent a verdict.- Queuing data for server sync**Alarms go through a receiver, not the service.** Each scheduler targets a `BroadcastReceiver`@@ -249,6 +249,8 @@ When both WiFi and motionless pause are enabled, GPS only resumes when both condEvaluates tracking profile conditions and switches GPS settings automatically. Supports five condition types: charging, Android Auto / car mode, speed above threshold, speed below threshold, and stationary. Uses a rolling speed buffer for averaged speed readings, deactivation delays (hysteresis) to prevent rapid toggling, and priority-based resolution when multiple profiles match.+The stationary condition is decided by the fixes and never by a timer. `evaluateStationaryState` tracks a run of consecutive fixes below 0.3 m/s and the verdict is reached by the fix that completes the window, so a stream that stops delivering cannot produce one. A gap restarts the run unless it is within three times the previous gap, or 60 seconds if that is larger, and no gap over 15 minutes is ever tolerated. Calibrating on the previous gap keeps a sparse Doze cadence usable while a fast stream that goes quiet is treated as unobserved time rather than stillness; the window length deliberately plays no part, or a long window would license a long blackout. The motion sensor discards a run in progress as well as an active verdict.+### ProfileHelperDatabase access layer for tracking profiles and trip events. Maintains a `TimedCache` of enabled profiles (30s TTL) and provides CRUD operations plus trip event logging.diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.ktindex cd8af4e9..e51e7619 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt@@ -28,4 +28,19 @@ object ProfileConstants {const val SPEED_BUFFER_SIZE = 5const val MIN_INTERVAL_MS = 1000Lconst val STATIONARY_SPEED_THRESHOLD = 0.3f++ /**+ * A run of fixes survives two consecutive missed ones; the third breaks it. Measured against the+ * most recent gap rather than the configured interval, which Doze and the provider ignore.+ */+ const val STATIONARY_GAP_TOLERANCE_FACTOR = 3++ /** Floor on that tolerance, for a run with no gap yet to measure against. */+ const val STATIONARY_MIN_GAP_TOLERANCE_MS = 60_000L++ /**+ * Ceiling on it, however sparse the last gap was. Sized off the app's own sparsest real cadence+ * (allow-while-idle alarms batch to roughly 9 minutes), not off what a stalled timer can reach.+ */+ const val STATIONARY_MAX_GAP_TOLERANCE_MS = 900_000L}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.ktindex 4b3d29ef..de6a18b1 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt@@ -60,8 +60,11 @@ class ProfileManager(@Volatile private var isCarMode = false@Volatile var isStationary = falseprivate set+ // The run of consecutive sub-threshold fixes, timed by location.time.// Written/read from location + motion callbacks without synchronization.- @Volatile private var stationaryJob: Job? = null+ @Volatile private var runStartedAtMs = 0L+ @Volatile private var lastSampleAtMs = 0L+ @Volatile private var lastSampleGapMs = 0L// Speed rolling average bufferprivate val speedBuffer = ArrayDeque<Float>()@@ -81,8 +84,8 @@ class ProfileManager(/** Called by the motion sensor when the device starts moving while stationary. */fun onMotionDetected() {if (!isStationary) return- stationaryJob?.cancel()- stationaryJob = null+ // Or the next still fix re-activates from the run this verdict already spent.+ runStartedAtMs = 0LisStationary = falseonStationaryChanged?.invoke(false)AppLogger.d(TAG, "Motion detected - device no longer stationary")@@ -315,14 +318,20 @@ class ProfileManager(pendingActivationProfileId = null}+ /** Only the fix that completes the window can conclude stillness; a stopped stream never does. */private fun evaluateStationaryState(location: android.location.Location) {if (ProfileConstants.CONDITION_STATIONARY !in getNeededConditionTypes()) return+ val sampleAtMs = location.time+ val gapMs = if (lastSampleAtMs == 0L) -1L else sampleAtMs - lastSampleAtMs+ val previousGapMs = lastSampleGapMs+ lastSampleAtMs = sampleAtMs+ if (gapMs >= 0) lastSampleGapMs = gapMs+val speed = if (location.hasSpeed()) location.speed else 0fif (speed >= ProfileConstants.STATIONARY_SPEED_THRESHOLD) {- stationaryJob?.cancel()- stationaryJob = null+ runStartedAtMs = 0Lif (isStationary) {isStationary = falseonStationaryChanged?.invoke(false)@@ -331,16 +340,33 @@ class ProfileManager(return}- if (!isStationary && stationaryJob?.isActive != true) {- val timeoutMs = stationaryTimeoutMs()- stationaryJob = scope.launch {- delay(timeoutMs)- isStationary = true- onStationaryChanged?.invoke(true)- AppLogger.d(TAG, "Device stationary (speed below threshold for ${timeoutMs / 1000}s)")- evaluate()- }+ if (isStationary) return++ val timeoutMs = stationaryTimeoutMs()+ if (runStartedAtMs == 0L || !runSurvivesGap(gapMs, previousGapMs)) {+ if (runStartedAtMs != 0L) AppLogger.d(TAG, "Stationary run restarted: ${gapMs}ms without a fix")+ runStartedAtMs = sampleAtMs}++ val stillForMs = sampleAtMs - runStartedAtMs+ if (stillForMs < timeoutMs) return++ isStationary = true+ onStationaryChanged?.invoke(true)+ AppLogger.d(TAG, "Device stationary (speed below threshold for ${stillForMs / 1000}s)")+ }++ /**+ * A gap is unobserved time, not stillness. The tolerance scales with the run's own spacing, and+ * deliberately not with the window: a long window must not make a long blackout count as stillness.+ */+ private fun runSurvivesGap(gapMs: Long, previousGapMs: Long): Boolean {+ if (gapMs < 0) return false+ val tolerance = maxOf(+ ProfileConstants.STATIONARY_MIN_GAP_TOLERANCE_MS,+ previousGapMs * ProfileConstants.STATIONARY_GAP_TOLERANCE_FACTOR+ )+ return gapMs <= minOf(tolerance, ProfileConstants.STATIONARY_MAX_GAP_TOLERANCE_MS)}// Stationary detection window = the profile's activation delay (the "still for this long" time).diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.ktindex 480f8718..6093f559 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt@@ -23,6 +23,8 @@ class ProfileManagerTest {private lateinit var profileHelper: ProfileHelperprivate lateinit var testScope: TestScope+ // Fix timestamps are wall-clock, so a run reads more clearly from a non-zero base.+ private val t0 = 1_000_000Lprivate var switchedInterval: Long = 0private var switchedDistance: Float = 0fprivate var switchedSyncInterval: Int = 0@@ -123,15 +125,33 @@ class ProfileManagerTest {activationDelaySeconds = activationDelay)- private fun mockLocation(speed: Float, hasSpeed: Boolean = true): Location {+ private fun mockLocation(speed: Float, hasSpeed: Boolean = true, timeMs: Long = t0): Location {return mockk {every { [email protected] } returns speedevery { [email protected]() } returns hasSpeed+ every { time } returns timeMsevery { latitude } returns 52.52every { longitude } returns 13.405}}+ /** Feeds sub-threshold fixes 6s apart until the run spans [spanMs]. */+ private fun feedStillRun(+ manager: ProfileManager,+ spanMs: Long = 60_000L,+ startAtMs: Long = t0,+ speed: Float = 0.1f,+ hasSpeed: Boolean = true+ ): Long {+ var t = startAtMs+ manager.onLocationUpdate(mockLocation(speed, hasSpeed, t))+ while (t - startAtMs < spanMs) {+ t += 6_000L+ manager.onLocationUpdate(mockLocation(speed, hasSpeed, t))+ }+ return t+ }+@Beforefun setup() {testScope = TestScope()@@ -735,18 +755,22 @@ class ProfileManagerTest {)@Test- fun `activates stationary profile after timeout`() = testScope.runTest {+ fun `activates stationary profile once the fixes span the window`() = testScope.runTest {val profile = stationaryProfile()every { profileHelper.getEnabledProfiles() } returns listOf(profile)val manager = createManager()- // Feed slow locations - should not activate immediately- manager.onLocationUpdate(mockLocation(0.1f))+ // One fix cannot show a minute of stillness, however long the app then waits+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))+ advanceTimeBy(60_000L + 100)+ assertEquals(0, switchCount)++ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 30_000))assertEquals(0, switchCount)- // Advance past stationary timeout- advanceTimeBy(60_000L + 100)+ // The verdict lands on the fix that completes the window+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 60_000))assertEquals("Stationary", switchedProfileName)assertEquals(30000L, switchedInterval)@@ -758,15 +782,15 @@ class ProfileManagerTest {every { profileHelper.getEnabledProfiles() } returns listOf(profile)val manager = createManager()- manager.onLocationUpdate(mockLocation(0.1f))- // Not stationary before the configured 30s- advanceTimeBy(29_000)+ // Not stationary before the configured 30s of fixes+ feedStillRun(manager, spanMs = 24_000)+ advanceTimeBy(60_000)assertNull(switchedProfileName)assertFalse(manager.isStationary)// Becomes stationary at its own window, not the built-in 60s- advanceTimeBy(2_000)+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 30_000))assertEquals("Stationary", switchedProfileName)assertTrue(manager.isStationary)}@@ -777,10 +801,9 @@ class ProfileManagerTest {every { profileHelper.getEnabledProfiles() } returns listOf(profile)val manager = createManager()- manager.onLocationUpdate(mockLocation(0.1f))- // 0 = no stillness window, same as every other delay: instant- advanceTimeBy(100)+ // 0 = no stillness window, same as every other delay: the first still fix decides+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))assertEquals("Stationary", switchedProfileName)}@@ -791,7 +814,7 @@ class ProfileManagerTest {val manager = createManager()- repeat(5) { manager.onLocationUpdate(mockLocation(5f)) }+ feedStillRun(manager, spanMs = 60_000, speed = 5f)advanceTimeBy(60_000L + 100)assertNull(switchedProfileName)@@ -808,12 +831,11 @@ class ProfileManagerTest {manager.defaultSyncInterval = 0// Become stationary- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ val stillUntil = feedStillRun(manager)assertEquals("Stationary", switchedProfileName)// Start moving- manager.onLocationUpdate(mockLocation(5f))+ manager.onLocationUpdate(mockLocation(5f, timeMs = stillUntil + 6_000))// Wait past deactivation delayadvanceTimeBy(11_000)@@ -822,22 +844,23 @@ class ProfileManagerTest {}@Test- fun `stationary timer resets when speed goes above threshold`() = testScope.runTest {+ fun `stationary run restarts when speed goes above threshold`() = testScope.runTest {val profile = stationaryProfile()every { profileHelper.getEnabledProfiles() } returns listOf(profile)val manager = createManager()- // Start countdown- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(30_000)+ // 30s of stillness, half the window+ feedStillRun(manager, spanMs = 30_000)- // Speed goes above threshold - should cancel timer- manager.onLocationUpdate(mockLocation(5f))- advanceTimeBy(40_000)+ // One fix above the threshold discards it+ manager.onLocationUpdate(mockLocation(5f, timeMs = t0 + 36_000))++ // 54s of stillness after it is still short of a fresh window+ feedStillRun(manager, spanMs = 54_000, startAtMs = t0 + 42_000)- // Should not have activatedassertNull(switchedProfileName)+ assertFalse(manager.isStationary)}@Test@@ -847,9 +870,8 @@ class ProfileManagerTest {val manager = createManager()- // Location without speed data- manager.onLocationUpdate(mockLocation(0f, hasSpeed = false))- advanceTimeBy(60_000L + 100)+ // Locations without speed data+ feedStillRun(manager, speed = 0f, hasSpeed = false)assertEquals("Stationary", switchedProfileName)}@@ -862,11 +884,10 @@ class ProfileManagerTest {val manager = createManager()assertFalse(manager.isStationary)- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ val stillUntil = feedStillRun(manager)assertTrue(manager.isStationary)- manager.onLocationUpdate(mockLocation(5f))+ manager.onLocationUpdate(mockLocation(5f, timeMs = stillUntil + 6_000))assertFalse(manager.isStationary)}@@ -877,11 +898,10 @@ class ProfileManagerTest {val manager = createManager()- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ val stillUntil = feedStillRun(manager)assertEquals(true, lastStationaryCallback)- manager.onLocationUpdate(mockLocation(5f))+ manager.onLocationUpdate(mockLocation(5f, timeMs = stillUntil + 6_000))assertEquals(false, lastStationaryCallback)}@@ -896,8 +916,7 @@ class ProfileManagerTest {manager.defaultSyncInterval = 0// Become stationary- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ feedStillRun(manager)assertEquals("Stationary", switchedProfileName)assertTrue(manager.isStationary)@@ -921,6 +940,144 @@ class ProfileManagerTest {assertNull(lastStationaryCallback)}+ // --- Stationary evidence: a verdict needs fixes behind it ---++ @Test+ fun `no stationary verdict without fixes`() = testScope.runTest {+ val profile = stationaryProfile()+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Bad reception is what silences the stream, so silence must not read as stillness.+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))+ advanceTimeBy(600_000L)++ assertFalse(manager.isStationary)+ assertEquals(0, switchCount)+ }++ @Test+ fun `a gap in the fixes restarts the stationary run`() = testScope.runTest {+ val profile = stationaryProfile()+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // 54s of stillness at a 6s cadence, one fix short of the window+ feedStillRun(manager, spanMs = 54_000)+ assertFalse(manager.isStationary)++ // The accuracy filter starves the detector for 9m54s: unobserved time is not stillness.+ val returnedAt = t0 + 54_000 + 594_000+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = returnedAt))+ assertFalse(manager.isStationary)++ manager.onLocationUpdate(mockLocation(0.1f, timeMs = returnedAt + 54_000))+ assertFalse(manager.isStationary)++ manager.onLocationUpdate(mockLocation(0.1f, timeMs = returnedAt + 60_000))+ assertTrue(manager.isStationary)+ }++ @Test+ fun `a sparse but unbroken stream still qualifies`() = testScope.runTest {+ val profile = stationaryProfile()+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Nine minutes apart is a dozing phone's cadence, not a gap, so it has to stay reachable.+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 540_000))+ assertFalse("the first spacing is what calibrates the run", manager.isStationary)++ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 1_080_000))+ assertTrue(manager.isStationary)+ }++ @Test+ fun `evidence sparser than the cap never qualifies`() = testScope.runTest {+ val profile = stationaryProfile()+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // The run's own spacing would tolerate 45 minutes. The cap does not.+ var t = t0+ repeat(4) {+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t))+ t += 2_700_000L+ }++ assertFalse(manager.isStationary)+ assertEquals(0, switchCount)+ }++ @Test+ fun `stillness is earned again after the motion sensor ends it`() = testScope.runTest {+ val profile = stationaryProfile(deactivationDelay = 0)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.defaultInterval = 5000L++ feedStillRun(manager)+ assertTrue(manager.isStationary)++ manager.onMotionDetected()+ assertFalse(manager.isStationary)++ // The spent run must not hand the verdict straight back on the next still fix+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 66_000))+ assertFalse(manager.isStationary)++ feedStillRun(manager, startAtMs = t0 + 72_000)+ assertTrue(manager.isStationary)+ }++ @Test+ fun `a blackout after movement does not conclude stillness`() = testScope.runTest {+ val profile = stationaryProfile()+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()+ manager.defaultInterval = 5000L++ // A legitimate sparse run leaves its wide spacing behind as the calibration+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 600_000))+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 1_200_000))+ assertTrue(manager.isStationary)++ // Movement ends it, then reception dies and the only fixes carry no speed. Inheriting the+ // still phone's spacing must not let two far-apart fixes rebuild a verdict while driving.+ manager.onLocationUpdate(mockLocation(5f, timeMs = t0 + 1_800_000))+ assertFalse(manager.isStationary)++ manager.onLocationUpdate(mockLocation(0f, hasSpeed = false, timeMs = t0 + 2_700_000))+ manager.onLocationUpdate(mockLocation(0f, hasSpeed = false, timeMs = t0 + 4_500_000))++ assertFalse(manager.isStationary)+ }++ @Test+ fun `a long activation delay does not widen what counts as stillness`() = testScope.runTest {+ val profile = stationaryProfile(activationDelay = 600)+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)++ val manager = createManager()++ // Activation Delay has no upper bound in the editor. A ten-minute window must not make a+ // nine-minute blackout count as nine minutes of stillness.+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0))+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 540_000))+ manager.onLocationUpdate(mockLocation(0.1f, timeMs = t0 + 600_000))++ assertFalse(manager.isStationary)+ assertEquals(0, switchCount)+ }+// --- Stationary + other conditions: priority interactions ---@Test@@ -932,8 +1089,7 @@ class ProfileManagerTest {val manager = createManager()// Become stationary first- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ feedStillRun(manager)assertEquals("Stationary", switchedProfileName)// Start charging - higher priority should take over@@ -953,8 +1109,7 @@ class ProfileManagerTest {manager.defaultSyncInterval = 0// Become stationary- manager.onLocationUpdate(mockLocation(0.1f))- advanceTimeBy(60_000L + 100)+ feedStillRun(manager)assertTrue(manager.isStationary)// Start charging - charging wins@@ -974,8 +1129,8 @@ class ProfileManagerTest {val manager = createManager()- // Feed slow locations - should not start stationary timer- manager.onLocationUpdate(mockLocation(0.1f))+ // Feed slow locations - the stationary state is never evaluated at all+ feedStillRun(manager)advanceTimeBy(60_000L + 100)assertFalse(manager.isStationary)