Skip to content

Colota - Android GPS Location tracker

feat: add stationary tracking profile condition

Max Dietrichff170fe8e9f6
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 68e742bf..482afff3 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -15,7 +15,7 @@ Tracking profiles automatically adjust GPS interval, distance filter, and sync s
- **Charging** - Increase tracking frequency while plugged in (battery isn't a concern)
- **Driving** - Switch to frequent updates when Android Auto connects or speed exceeds a threshold
- **Walking** - Use longer intervals at low speeds to conserve battery
-- **Parked** - Reduce updates when stationary with a speed-below profile
+- **Stationary** - Record a periodic heartbeat point (e.g. every 30 min) as proof-of-presence while not moving
## Setup
@@ -34,8 +34,11 @@ Tracking profiles automatically adjust GPS interval, distance filter, and sync s
| **Car Mode** | Android Auto is connected |
| **Speed Above** | Average speed exceeds the configured threshold (km/h) |
| **Speed Below** | Average speed drops below the configured threshold (km/h) |
+| **Stationary** | Device not moving for approximately 60 seconds |
-Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes.
+Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes. The stationary condition uses a fixed speed threshold (0.3 m/s) with a 60-second timeout for reliable detection - unlike speed-below, it does not flap on GPS noise near zero.
+
+:::tip Stationary profile When the device becomes stationary, the hardware significant motion sensor is armed. Even with a long GPS interval (e.g. 30 min), the profile deactivates the moment the device moves without waiting for the next GPS fix. The deactivation delay setting is not shown for stationary profiles since the motion sensor handles instant resume. Set the distance filter to **0m** so points are recorded at every interval regardless of GPS drift. :::
## Profile Settings
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 86862b81..457d19da 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -15,9 +15,9 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
- **Offline Maps** - Download map areas to your device for use without an internet connection.
- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.
- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.
-- **Reliable Tracking** - Foreground service, auto-start on boot, exponential backoff retry and automatic GPS pause when stationary.
+- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.
- **Geofencing** - Pause zones that stop recording locations. Optionally stop GPS entirely when on WiFi or when the device is motionless.
-- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, car mode or speed.
+- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, car mode, speed or stationary detection.
- **Flexible Sync** - Instant, batch, Wi-Fi only or offline modes.
- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.
- **Quick Setup** - Configure devices via `colota://setup` deep links or QR codes.
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index afb3fa57..4a1fd2e7 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -64,7 +64,8 @@ const features = [
},
{
title: "Tracking Profiles",
- description: "Multiple GPS configs that switch automatically based on charging state, Android Auto, or speed."
+ description:
+ "Multiple GPS configs that switch automatically based on charging state, Android Auto, speed or stationary detection."
},
{
title: "Maps & Geofencing",
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index 991f9b8b..27dc22d1 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
@@ -50,8 +50,6 @@ class LocationForegroundService : Service() {
@Volatile private var serviceScope: CoroutineScope? = null
@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null
@Volatile private var locationRestartJob: Job? = null
- @Volatile private var stationaryJob: Job? = null
- @Volatile private var isStationary = false
@Volatile private var motionDetector: MotionDetector? = null
@Volatile private var insidePauseZone = false
@Volatile private var isWifiPaused = false
@@ -73,10 +71,6 @@ class LocationForegroundService : Service() {
companion object {
private const val TAG = "LocationService"
- /** Speed threshold below which the device is considered stationary (m/s). ~1 km/h */
- private const val STATIONARY_SPEED_THRESHOLD = 0.3f
- /** How long speed must stay below threshold before pausing GPS (ms). */
- private const val STATIONARY_TIMEOUT_MS = 60_000L
/** Multiplier applied to the tracking interval for the geofence entry delay. */
private const val ENTRY_DELAY_MULTIPLIER = 3.5
/** Debounce before resuming GPS after unmetered network is lost (ms). */
@@ -110,9 +104,13 @@ class LocationForegroundService : Service() {
secureStorage = SecureStorageHelper.getInstance(this)
syncManager = SyncManager(dbHelper, networkManager, serviceScope!!)
profileHelper = ProfileHelper(this)
- profileManager = ProfileManager(profileHelper, serviceScope!!) { interval, distance, syncInterval, _, _ ->
- applyProfileConfig(interval, distance, syncInterval)
- }
+ profileManager = ProfileManager(
+ profileHelper, serviceScope!!,
+ onConfigSwitch = { interval, distance, syncInterval, _, _ ->
+ applyProfileConfig(interval, distance, syncInterval)
+ },
+ onStationaryChanged = ::handleStationaryChanged
+ )
conditionMonitor = ConditionMonitor(this, profileManager)
notificationHelper = NotificationHelper(this, notificationManager)
@@ -255,7 +253,6 @@ class LocationForegroundService : Service() {
AppLogger.d(TAG, "Service destroyed")
motionDetector?.disarm()
- stationaryJob?.cancel()
entryDelayJob?.cancel()
entryDelayJob = null
pendingPauseZone = null
@@ -467,10 +464,6 @@ class LocationForegroundService : Service() {
applySpeedFallback(location)
- // Evaluated before the distance filter so stationary detection works regardless
- // of movement threshold - the distance filter is for recording quality, not motion state.
- evaluateStationaryState(location)
-
// Software-side distance filter (FLP bypasses the OS-level distance filter for some fixes)
// Bypassed during geofence entry delay so stationary arrival points are logged
if (pendingPauseZone == null && config.minUpdateDistance > 0f && prev != null) {
@@ -546,8 +539,6 @@ class LocationForegroundService : Service() {
*/
private fun startEntryDelay(geofence: GeofenceHelper.CachedGeofence) {
entryDelayJob?.cancel()
- stationaryJob?.cancel()
- stationaryJob = null
pendingPauseZone = geofence
val scope = serviceScope ?: run {
@@ -737,7 +728,7 @@ class LocationForegroundService : Service() {
private fun clearMotionlessPauseState() {
isMotionlessPaused = false
dbHelper.saveSetting("pause_zone_motionless_active", "false")
- motionDetector?.disarm()
+ if (!profileManager.isStationary) motionDetector?.disarm()
}
/**
@@ -842,7 +833,7 @@ class LocationForegroundService : Service() {
activeProfileName = profileManager.getActiveProfileName(),
forceUpdate = forceUpdate,
isOfflineMode = offline,
- isStationary = isStationary,
+ isStationary = profileManager.isStationary,
isWifiPaused = isWifiPaused,
isMotionlessPaused = isMotionlessPaused
)
@@ -872,88 +863,21 @@ class LocationForegroundService : Service() {
stopSelf()
}
- // ── Stationary detection ──────────────────────────────────────────────
-
- /**
- * Called from handleLocationUpdate to evaluate whether the device has
- * become stationary. If speed stays below [STATIONARY_SPEED_THRESHOLD]
- * for [STATIONARY_TIMEOUT_MS], active GPS is paused and the significant
- * motion sensor is armed to wake it back up.
- */
- private fun evaluateStationaryState(location: android.location.Location) {
- if (!config.pauseWhenStationary || motionDetector?.isAvailable != true) return
- if (pendingPauseZone != null) return // keep GPS running until arrival points are logged
- if (insidePauseZone) return // keep GPS running so zone exit can be detected
-
- // Treat missing speed as 0 (stationary) - network/fused providers often omit speed
- val speed = if (location.hasSpeed()) location.speed else 0f
-
- if (speed >= STATIONARY_SPEED_THRESHOLD) {
- // Moving - cancel any pending stationary timer
- stationaryJob?.cancel()
- stationaryJob = null
- if (isStationary) {
- resumeFromStationary()
- }
- return
- }
-
- // Speed below threshold - start countdown if not already running
- if (!isStationary && stationaryJob?.isActive != true) {
- stationaryJob = serviceScope?.launch {
- delay(STATIONARY_TIMEOUT_MS)
- withContext(Dispatchers.Main) {
- enterStationary()
- }
- }
- }
- }
-
- private fun enterStationary() {
- if (isStationary) return
- isStationary = true
-
- AppLogger.i(TAG, "Device stationary - pausing active GPS, arming motion sensor")
-
- // Stop active GPS but keep the service running
- stopLocationUpdates()
-
- motionDetector?.arm()
-
- val loc = lastKnownLocation
- updateNotification(
- lat = loc?.latitude,
- lon = loc?.longitude,
- forceUpdate = true
- )
- }
-
/** Called by MotionDetector when the device starts moving again. */
private fun onMotionDetected() {
if (isMotionlessPaused) {
resumeFromMotionlessPause()
- return
}
- if (!isStationary) return
- AppLogger.i(TAG, "Motion detected - resuming active GPS")
- resumeFromStationary()
+ profileManager.onMotionDetected()
}
- private fun resumeFromStationary() {
- isStationary = false
- stationaryJob?.cancel()
- stationaryJob = null
- motionDetector?.disarm()
-
- // Restart active GPS with current config
- setupLocationUpdates()
-
- val loc = lastKnownLocation
- updateNotification(
- lat = loc?.latitude,
- lon = loc?.longitude,
- forceUpdate = true
- )
+ /** Arms or disarms the motion sensor when the stationary profile state changes. */
+ private fun handleStationaryChanged(stationary: Boolean) {
+ if (stationary) {
+ motionDetector?.arm()
+ } else if (!isMotionlessPaused) {
+ motionDetector?.disarm()
+ }
}
// ── Profile hot-swap ────────────────────────────────────────────────
@@ -968,12 +892,6 @@ class LocationForegroundService : Service() {
pushConfigToSyncManager()
- // Resume from stationary if a profile switch happens (e.g. charging)
- if (isStationary) {
- resumeFromStationary()
- return
- }
-
// Synchronous restart on Main thread to avoid duplicate locations from
// the old listener firing during an async coroutine window.
locationRestartJob?.cancel()
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.kt
index 1a45930a..7a0d3473 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
@@ -10,8 +10,11 @@ object ProfileConstants {
const val CONDITION_ANDROID_AUTO = "android_auto"
const val CONDITION_SPEED_ABOVE = "speed_above"
const val CONDITION_SPEED_BELOW = "speed_below"
+ const val CONDITION_STATIONARY = "stationary"
const val CACHE_TTL_MS = 30_000L
const val SPEED_BUFFER_SIZE = 5
const val MIN_INTERVAL_MS = 1000L
+ const val STATIONARY_SPEED_THRESHOLD = 0.3f
+ const val STATIONARY_TIMEOUT_MS = 60_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.kt
index e2facbe0..673aa05c 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
@@ -24,7 +24,8 @@ import kotlinx.coroutines.*
class ProfileManager(
private val profileHelper: ProfileHelper,
private val scope: CoroutineScope,
- private val onConfigSwitch: (interval: Long, distance: Float, syncInterval: Int, profileName: String?, profileId: Int?) -> Unit
+ private val onConfigSwitch: (interval: Long, distance: Float, syncInterval: Int, profileName: String?, profileId: Int?) -> Unit,
+ private val onStationaryChanged: ((stationary: Boolean) -> Unit)? = null
) {
companion object {
private const val TAG = "ProfileManager"
@@ -42,6 +43,9 @@ class ProfileManager(
// Condition states
@Volatile private var isCharging = false
@Volatile private var isCarMode = false
+ @Volatile var isStationary = false
+ private set
+ @Volatile private var stationaryJob: Job? = null
// Speed rolling average buffer
private val speedBuffer = ArrayDeque<Float>()
@@ -58,6 +62,17 @@ class ProfileManager(
evaluate()
}
+ /** Called by the motion sensor when the device starts moving while stationary. */
+ fun onMotionDetected() {
+ if (!isStationary) return
+ stationaryJob?.cancel()
+ stationaryJob = null
+ isStationary = false
+ onStationaryChanged?.invoke(false)
+ AppLogger.d(TAG, "Motion detected - device no longer stationary")
+ evaluate()
+ }
+
fun onLocationUpdate(location: android.location.Location) {
if (location.hasSpeed()) {
synchronized(speedLock) {
@@ -67,6 +82,7 @@ class ProfileManager(
speedBuffer.addLast(location.speed)
}
}
+ evaluateStationaryState(location)
evaluate()
}
@@ -141,6 +157,7 @@ class ProfileManager(
val threshold = profile.speedThreshold
avgSpeed != null && threshold != null && avgSpeed < threshold
}
+ ProfileConstants.CONDITION_STATIONARY -> isStationary
else -> false
}
@@ -211,6 +228,33 @@ class ProfileManager(
deactivationJob = null
}
+ private fun evaluateStationaryState(location: android.location.Location) {
+ if (ProfileConstants.CONDITION_STATIONARY !in getNeededConditionTypes()) return
+
+ val speed = if (location.hasSpeed()) location.speed else 0f
+
+ if (speed >= ProfileConstants.STATIONARY_SPEED_THRESHOLD) {
+ stationaryJob?.cancel()
+ stationaryJob = null
+ if (isStationary) {
+ isStationary = false
+ onStationaryChanged?.invoke(false)
+ AppLogger.d(TAG, "Device no longer stationary (speed=${String.format("%.1f", speed)}m/s)")
+ }
+ return
+ }
+
+ if (!isStationary && stationaryJob?.isActive != true) {
+ stationaryJob = scope.launch {
+ delay(ProfileConstants.STATIONARY_TIMEOUT_MS)
+ isStationary = true
+ onStationaryChanged?.invoke(true)
+ AppLogger.d(TAG, "Device stationary (speed below threshold for ${ProfileConstants.STATIONARY_TIMEOUT_MS / 1000}s)")
+ evaluate()
+ }
+ }
+ }
+
private fun deactivateToDefault() {
val previousProfile = activeProfile ?: return
activeProfile = null
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
index 6223347a..60f17bec 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
@@ -26,7 +26,6 @@ data class ServiceConfig(
val retryIntervalSeconds: Int = 30,
val isOfflineMode: Boolean = false,
val isWifiOnlySync: Boolean = false,
- val pauseWhenStationary: Boolean = false,
val fieldMap: String? = null,
val customFields: String? = null,
val httpMethod: String = "POST",
@@ -50,7 +49,6 @@ data class ServiceConfig(
retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 30,
isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false,
isWifiOnlySync = saved["isWifiOnlySync"]?.toBoolean() ?: false,
- pauseWhenStationary = saved["pauseWhenStationary"]?.toBoolean() ?: false,
fieldMap = saved["fieldMap"],
customFields = saved["customFields"],
httpMethod = httpMethod,
@@ -96,7 +94,6 @@ data class ServiceConfig(
retryIntervalSeconds = config.getIntOrNull("retryInterval") ?: dbConfig.retryIntervalSeconds,
isOfflineMode = config.getBooleanOrNull("isOfflineMode") ?: dbConfig.isOfflineMode,
isWifiOnlySync = config.getBooleanOrNull("isWifiOnlySync") ?: dbConfig.isWifiOnlySync,
- pauseWhenStationary = config.getBooleanOrNull("pauseWhenStationary") ?: dbConfig.pauseWhenStationary,
fieldMap = fieldMapJson ?: dbConfig.fieldMap,
customFields = customFieldsJson ?: dbConfig.customFields,
httpMethod = httpMethod,
@@ -119,7 +116,6 @@ data class ServiceConfig(
retryIntervalSeconds = extras.getIntOrDefault("retryInterval", dbConfig.retryIntervalSeconds),
isOfflineMode = extras.getBooleanOrDefault("isOfflineMode", dbConfig.isOfflineMode),
isWifiOnlySync = extras.getBooleanOrDefault("isWifiOnlySync", dbConfig.isWifiOnlySync),
- pauseWhenStationary = extras.getBooleanOrDefault("pauseWhenStationary", dbConfig.pauseWhenStationary),
fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap),
customFields = extras.getStringOrDefault("customFields", dbConfig.customFields),
httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST",
@@ -140,7 +136,6 @@ data class ServiceConfig(
putExtra("retryInterval", retryIntervalSeconds)
putExtra("isOfflineMode", isOfflineMode)
putExtra("isWifiOnlySync", isWifiOnlySync)
- putExtra("pauseWhenStationary", pauseWhenStationary)
fieldMap?.let { putExtra("fieldMap", it) }
customFields?.let { putExtra("customFields", it) }
putExtra("httpMethod", httpMethod)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index 54533fba..9ce718b7 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -1493,18 +1493,15 @@ class LocationForegroundServiceTest {
}
@Test
- fun `onMotionDetected motionless path takes priority over stationary`() = testScope.runTest {
+ fun `onMotionDetected triggers motionless resume`() = testScope.runTest {
val motionDetector = mockk<MotionDetector>(relaxed = true)
setField("motionDetector", motionDetector)
setField("isMotionlessPaused", true)
- setField("isStationary", true)
setField("currentZoneGeofence", homeGeofence)
invokeOnMotionDetected()
- // Motionless path fires, not stationary path
assertFalse(getField<Boolean>("isMotionlessPaused"))
- assertTrue(getField<Boolean>("isStationary")) // stationary unchanged
}
// =========================================================================
@@ -1706,215 +1703,6 @@ class LocationForegroundServiceTest {
method.invoke(service, geofence)
}
- // =========================================================================
- // evaluateStationaryState - motion detection
- // =========================================================================
-
- @Test
- fun `evaluateStationaryState skips when pauseWhenStationary is disabled`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = false,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
-
- val location = mockLocation(speed = 0.1f)
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNull("Should not start stationary timer when disabled", stationaryJob)
- }
-
- @Test
- fun `evaluateStationaryState skips when motion sensor unavailable`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns false
- setField("motionDetector", motionDetector)
-
- val location = mockLocation(speed = 0.1f)
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNull("Should not start timer when sensor unavailable", stationaryJob)
- }
-
- @Test
- fun `evaluateStationaryState skips when entry delay is pending`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
- setField("pendingPauseZone", homeGeofence)
-
- val location = mockLocation(speed = 0.1f)
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNull("Should not start stationary timer during entry delay", stationaryJob)
- }
-
- @Test
- fun `evaluateStationaryState skips timer when inside pause zone`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
- setField("insidePauseZone", true)
-
- val location = mockLocation(speed = 0.1f)
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNull("Should not start stationary timer inside pause zone - GPS must stay running for exit detection", stationaryJob)
- }
-
- @Test
- fun `evaluateStationaryState starts timer when speed below threshold`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
-
- val location = mockLocation(speed = 0.1f) // below 0.3 m/s threshold
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNotNull("Should start stationary timer", stationaryJob)
- assertTrue("Timer should be active", stationaryJob!!.isActive)
- }
-
- @Test
- fun `evaluateStationaryState cancels timer when speed above threshold`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
-
- // First: trigger timer with low speed
- val slowLocation = mockLocation(speed = 0.1f)
- invokeEvaluateStationaryState(slowLocation)
- val job: Job? = getField("stationaryJob")
- assertNotNull("Timer should exist", job)
-
- // Then: cancel with movement
- val fastLocation = mockLocation(speed = 5.0f)
- invokeEvaluateStationaryState(fastLocation)
- val cancelledJob: Job? = getField("stationaryJob")
- assertNull("Timer should be cancelled", cancelledJob)
- }
-
- @Test
- fun `evaluateStationaryState treats missing speed as stationary`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- pauseWhenStationary = true,
- filterInaccurateLocations = true,
- accuracyThreshold = 50.0f
- ))
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- every { motionDetector.isAvailable } returns true
- setField("motionDetector", motionDetector)
-
- val location = mockLocation(hasSpeed = false)
- invokeEvaluateStationaryState(location)
-
- val stationaryJob: Job? = getField("stationaryJob")
- assertNotNull("Should start stationary timer when speed is missing", stationaryJob)
- }
-
- @Test
- fun `enterStationary stops location updates and arms motion sensor`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
-
- val callback = mockk<LocationUpdateCallback>(relaxed = true)
- setField("locationUpdateCallback", callback)
-
- invokeEnterStationary()
-
- assertTrue(getField<Boolean>("isStationary"))
- verify { locationProvider.removeLocationUpdates(callback) }
- verify { motionDetector.arm() }
- assertNull(getField<LocationUpdateCallback?>("locationUpdateCallback"))
- }
-
- @Test
- fun `enterStationary arms sensor when inside pause zone`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("insidePauseZone", true)
-
- invokeEnterStationary()
-
- assertTrue(getField<Boolean>("isStationary"))
- verify { motionDetector.arm() }
- }
-
- @Test
- fun `onMotionDetected resumes GPS when stationary`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isStationary", true)
-
- invokeOnMotionDetected()
-
- assertFalse(getField<Boolean>("isStationary"))
- verify { motionDetector.disarm() }
- }
-
- @Test
- fun `onMotionDetected ignores when not stationary`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isStationary", false)
-
- invokeOnMotionDetected()
-
- verify(exactly = 0) { motionDetector.disarm() }
- }
-
- @Test
- fun `applyProfileConfig resumes from stationary`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isStationary", true)
-
- invokeApplyProfileConfig(10000L, 5.0f, 300)
-
- assertFalse(getField<Boolean>("isStationary"))
- verify { motionDetector.disarm() }
- }
-
// =========================================================================
// Reflection helpers
// =========================================================================
@@ -1933,20 +1721,6 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
- private fun invokeEvaluateStationaryState(location: Location) {
- val method = LocationForegroundService::class.java.getDeclaredMethod(
- "evaluateStationaryState", Location::class.java
- )
- method.isAccessible = true
- method.invoke(service, location)
- }
-
- private fun invokeEnterStationary() {
- val method = LocationForegroundService::class.java.getDeclaredMethod("enterStationary")
- method.isAccessible = true
- method.invoke(service)
- }
-
private fun invokeOnMotionDetected() {
val method = LocationForegroundService::class.java.getDeclaredMethod("onMotionDetected")
method.isAccessible = true
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.kt
index e3f6bba6..31dc3579 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
@@ -29,16 +29,23 @@ class ProfileManagerTest {
private var switchedProfileName: String? = null
private var switchedProfileId: Int? = null
private var switchCount = 0
+ private var lastStationaryCallback: Boolean? = null
private fun createManager(): ProfileManager {
- return ProfileManager(profileHelper, testScope) { interval, distance, sync, name, id ->
- switchedInterval = interval
- switchedDistance = distance
- switchedSyncInterval = sync
- switchedProfileName = name
- switchedProfileId = id
- switchCount++
- }
+ return ProfileManager(
+ profileHelper, testScope,
+ onConfigSwitch = { interval, distance, sync, name, id ->
+ switchedInterval = interval
+ switchedDistance = distance
+ switchedSyncInterval = sync
+ switchedProfileName = name
+ switchedProfileId = id
+ switchCount++
+ },
+ onStationaryChanged = { stationary ->
+ lastStationaryCallback = stationary
+ }
+ )
}
private fun chargingProfile(
@@ -127,6 +134,7 @@ class ProfileManagerTest {
switchedSyncInterval = 0
switchedProfileName = null
switchedProfileId = null
+ lastStationaryCallback = null
mockkObject(com.Colota.bridge.LocationServiceModule)
every { com.Colota.bridge.LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true
@@ -497,6 +505,180 @@ class ProfileManagerTest {
assertEquals(5000L, switchedInterval)
}
+ // --- Stationary condition ---
+
+ private fun stationaryProfile(
+ id: Int = 5,
+ name: String = "Stationary",
+ intervalMs: Long = 30000,
+ priority: Int = 10,
+ deactivationDelay: Int = 30
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = name,
+ intervalMs = intervalMs,
+ minUpdateDistance = 0f,
+ syncIntervalSeconds = 0,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_STATIONARY,
+ speedThreshold = null,
+ deactivationDelaySeconds = deactivationDelay
+ )
+
+ @Test
+ fun `activates stationary profile after timeout`() = 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))
+ assertEquals(0, switchCount)
+
+ // Advance past stationary timeout
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+
+ assertEquals("Stationary", switchedProfileName)
+ assertEquals(30000L, switchedInterval)
+ }
+
+ @Test
+ fun `does not activate stationary profile when speed above threshold`() = testScope.runTest {
+ val profile = stationaryProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ repeat(5) { manager.onLocationUpdate(mockLocation(5f)) }
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `deactivates stationary profile when device starts moving`() = testScope.runTest {
+ val profile = stationaryProfile(deactivationDelay = 10)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Become stationary
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertEquals("Stationary", switchedProfileName)
+
+ // Start moving
+ manager.onLocationUpdate(mockLocation(5f))
+
+ // Wait past deactivation delay
+ advanceTimeBy(11_000)
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `stationary timer resets 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)
+
+ // Speed goes above threshold - should cancel timer
+ manager.onLocationUpdate(mockLocation(5f))
+ advanceTimeBy(40_000)
+
+ // Should not have activated
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `treats missing speed as stationary`() = testScope.runTest {
+ val profile = stationaryProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ // Location without speed data
+ manager.onLocationUpdate(mockLocation(0f, hasSpeed = false))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+
+ assertEquals("Stationary", switchedProfileName)
+ }
+
+ @Test
+ fun `isStationary reflects current state`() = testScope.runTest {
+ val profile = stationaryProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ assertFalse(manager.isStationary)
+
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertTrue(manager.isStationary)
+
+ manager.onLocationUpdate(mockLocation(5f))
+ assertFalse(manager.isStationary)
+ }
+
+ @Test
+ fun `onStationaryChanged callback fires on state transitions`() = testScope.runTest {
+ val profile = stationaryProfile()
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertEquals(true, lastStationaryCallback)
+
+ manager.onLocationUpdate(mockLocation(5f))
+ assertEquals(false, lastStationaryCallback)
+ }
+
+ @Test
+ fun `onMotionDetected deactivates stationary profile immediately`() = testScope.runTest {
+ val profile = stationaryProfile(deactivationDelay = 0)
+ every { profileHelper.getEnabledProfiles() } returns listOf(profile)
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ // Become stationary
+ manager.onLocationUpdate(mockLocation(0.1f))
+ advanceTimeBy(ProfileConstants.STATIONARY_TIMEOUT_MS + 100)
+ assertEquals("Stationary", switchedProfileName)
+ assertTrue(manager.isStationary)
+
+ // Motion sensor fires
+ manager.onMotionDetected()
+
+ assertFalse(manager.isStationary)
+ assertEquals(false, lastStationaryCallback)
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `onMotionDetected ignores when not stationary`() = testScope.runTest {
+ every { profileHelper.getEnabledProfiles() } returns emptyList()
+
+ val manager = createManager()
+ manager.onMotionDetected()
+
+ assertNull(lastStationaryCallback)
+ }
+
// --- Unknown condition type ---
@Test
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
index 1f28ff41..569d9d2b 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
@@ -238,7 +238,6 @@ class ServiceConfigTest {
every { getInt("retryInterval") } returns 60
every { getBoolean("isOfflineMode") } returns true
every { getBoolean("isWifiOnlySync") } returns true
- every { getBoolean("pauseWhenStationary") } returns false
every { getString("fieldMap") } returns """{"lat":"latitude"}"""
every { getString("customFields") } returns """{"_type":"location"}"""
every { getString("httpMethod") } returns "GET"
@@ -260,7 +259,6 @@ class ServiceConfigTest {
assertEquals(60, config.retryIntervalSeconds)
assertTrue(config.isOfflineMode)
assertTrue(config.isWifiOnlySync)
- assertFalse(config.pauseWhenStationary)
assertEquals("""{"lat":"latitude"}""", config.fieldMap)
assertEquals("GET", config.httpMethod)
assertEquals("traccar_json", config.apiFormat)
diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
index 28c63d81..0615801b 100644
--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
@@ -189,21 +189,6 @@ export function SyncStrategySettings({
hint="Only record if moved more than this distance"
colors={colors}
/>
-
- <SettingRow
- label="Pause GPS when stationary"
- hint="Stops active GPS after 60s without movement and resumes on motion"
- >
- <Switch
- value={settings.pauseWhenStationary}
- onValueChange={(value) => onImmediateSave({ ...settings, pauseWhenStationary: value })}
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.pauseWhenStationary ? colors.primary : colors.border}
- />
- </SettingRow>
</View>
{!settings.isOfflineMode && (
diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
index 3d0b2804..6c8c3f48 100644
--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
@@ -243,8 +243,7 @@ describe("SyncStrategySettings", () => {
fireEvent.press(getByText("Advanced Settings"))
- // Retry Failed Uploads is the second switch (after Pause GPS when stationary)
- const retrySwitch = getAllByRole("switch")[1]
+ const retrySwitch = getAllByRole("switch")[0]
fireEvent(retrySwitch, "valueChange", true)
@@ -262,8 +261,7 @@ describe("SyncStrategySettings", () => {
fireEvent.press(getByText("Advanced Settings"))
- // Retry Failed Uploads is the second switch (after Pause GPS when stationary)
- const retrySwitch = getAllByRole("switch")[1]
+ const retrySwitch = getAllByRole("switch")[0]
fireEvent(retrySwitch, "valueChange", false)
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 5623f8bb..7949b750 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -4,7 +4,7 @@
*/
import type { ProfileConditionType } from "../types/global"
-import { Zap, Car, ArrowUp, ArrowDown } from "lucide-react-native"
+import { Zap, Car, ArrowUp, ArrowDown, Pause } from "lucide-react-native"
// Timing
export const AUTOSAVE_DEBOUNCE_MS = 1500
@@ -57,6 +57,13 @@ export const PROFILE_CONDITIONS: {
listLabel: "Speed below",
icon: ArrowDown,
description: "Moving slower than threshold"
+ },
+ {
+ type: "stationary",
+ label: "Stationary",
+ listLabel: "When stationary",
+ icon: Pause,
+ description: "Not moving for ~60 seconds"
}
]
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index d463e0ba..a7ddb992 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -54,7 +54,6 @@ function parseRawSettings(allRaw: Record<string, string>): Settings {
isOfflineMode: allRaw.isOfflineMode === "true",
isWifiOnlySync: allRaw.isWifiOnlySync === "true",
- pauseWhenStationary: allRaw.pauseWhenStationary === "true",
endpoint: allRaw.endpoint ?? DEFAULT_SETTINGS.endpoint,
syncPreset: (allRaw.syncPreset as any) ?? DEFAULT_SETTINGS.syncPreset,
filterInaccurateLocations: allRaw.filterInaccurateLocations === "true",
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index fd0b49b7..760e30d0 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -98,13 +98,16 @@ export function ProfileEditorScreen({ navigation, route }: any) {
const setConditionType = useCallback(
(type: ProfileConditionType) => {
const isSpeed = type === "speed_above" || type === "speed_below"
+ const newDelay = type === "stationary" ? 0 : 60
setProfile((prev) => ({
...prev,
+ deactivationDelay: prev.condition.type !== type ? newDelay : prev.deactivationDelay,
condition: {
type,
...(isSpeed ? { speedThreshold: Number(speedKmh) / MS_TO_KMH } : {})
}
}))
+ if (type === "stationary") setDelayStr("0")
},
[speedKmh]
)
@@ -376,26 +379,39 @@ export function ProfileEditorScreen({ navigation, route }: any) {
)}
</Card>
- {/* Deactivation Delay */}
- <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>
- <Card>
- <SettingRow
- label="Deactivation Delay"
- hint="Wait before reverting to default settings after the condition stops matching. Prevents rapid switching."
- >
- <View style={styles.inputWithUnit}>
- <TextInput
- style={inputStyle}
- keyboardType="numeric"
- value={delayStr}
- onChangeText={(val) => handleNumericChange(setDelayStr, "deactivationDelay", val, 0)}
- placeholder="60"
- placeholderTextColor={colors.placeholder}
- />
- <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>
- </View>
- </SettingRow>
- </Card>
+ {profile.condition.type === "stationary" ? (
+ <>
+ <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>
+ <Card>
+ <Text style={[styles.conditionHint, { color: colors.textLight }]}>
+ Activates after ~60s without movement. Resumes instantly via the hardware motion sensor when the device
+ moves.
+ </Text>
+ </Card>
+ </>
+ ) : (
+ <>
+ <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>
+ <Card>
+ <SettingRow
+ label="Deactivation Delay"
+ hint="Wait before reverting to default settings after the condition stops matching. Prevents rapid switching."
+ >
+ <View style={styles.inputWithUnit}>
+ <TextInput
+ style={inputStyle}
+ keyboardType="numeric"
+ value={delayStr}
+ onChangeText={(val) => handleNumericChange(setDelayStr, "deactivationDelay", val, 0)}
+ placeholder="60"
+ placeholderTextColor={colors.placeholder}
+ />
+ <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>
+ </View>
+ </SettingRow>
+ </Card>
+ </>
+ )}
{/* Save Button */}
<Pressable
@@ -457,6 +473,7 @@ const styles = StyleSheet.create({
},
conditionLabel: { fontSize: 13, ...fonts.semiBold },
conditionDesc: { fontSize: 11, ...fonts.regular, textAlign: "center" },
+ conditionHint: { fontSize: 13, ...fonts.regular, paddingHorizontal: 16, paddingVertical: 12 },
syncLabelRow: { marginBottom: 8 },
settingLabel: { fontSize: 16, ...fonts.semiBold, marginBottom: 2 },
settingHint: { fontSize: 13, ...fonts.regular, lineHeight: 18 },
diff --git a/apps/mobile/src/services/SettingsService.ts b/apps/mobile/src/services/SettingsService.ts
index d4ca6651..d15a0dbe 100644
--- a/apps/mobile/src/services/SettingsService.ts
+++ b/apps/mobile/src/services/SettingsService.ts
@@ -50,7 +50,6 @@ export const SettingsService = {
case "filterInaccurateLocations":
case "isOfflineMode":
case "isWifiOnlySync":
- case "pauseWhenStationary":
// Boolean → "true"/"false"
stringValue = String(value)
break
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index de1a328d..cf725e3b 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -118,8 +118,7 @@ describe("NativeLocationService", () => {
apiTemplate: "custom" as const,
syncPreset: "instant" as const,
httpMethod: "POST" as const,
- hasCompletedSetup: false,
- pauseWhenStationary: true
+ hasCompletedSetup: false
}
await NativeLocationService.start(settings)
@@ -151,8 +150,7 @@ describe("NativeLocationService", () => {
apiTemplate: "traccar" as const,
syncPreset: "instant" as const,
httpMethod: "GET" as const,
- hasCompletedSetup: false,
- pauseWhenStationary: true
+ hasCompletedSetup: false
}
await NativeLocationService.start(settings)
@@ -182,8 +180,7 @@ describe("NativeLocationService", () => {
apiTemplate: "traccar" as const,
syncPreset: "instant" as const,
httpMethod: "POST" as const,
- hasCompletedSetup: false,
- pauseWhenStationary: true
+ hasCompletedSetup: false
}
await NativeLocationService.start(settings)
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 18052107..bb10eea2 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -292,8 +292,6 @@ export interface Settings {
maxRetries: number
isOfflineMode: boolean
isWifiOnlySync: boolean
- pauseWhenStationary: boolean
-
// UI State
syncPreset: SyncPreset
hasCompletedSetup: boolean
@@ -314,7 +312,6 @@ export const DEFAULT_SETTINGS: Settings = {
maxRetries: 5,
isOfflineMode: false,
isWifiOnlySync: false,
- pauseWhenStationary: false,
hasCompletedSetup: false,
httpMethod: "POST"
} as const
@@ -345,7 +342,7 @@ export const DEFAULT_AUTH_CONFIG: AuthConfig = {
// TRACKING PROFILES
// ============================================================================
-export type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below"
+export type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary"
export interface ProfileCondition {
type: ProfileConditionType