Skip to content

Colota - Android GPS Location tracker

feat: replace motion timer with accelerometer variance detector

Max Dietrichb116735cb8b2
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index fb8e206e..43c6b85d 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -91,7 +91,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 discharging)
- Location accuracy filtering
-- Stationary detection - pauses GPS after 60s without movement and arms `MotionDetector` to resume on motion (suspended during entry delay and inside geofence pause zones)
+- 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.
- Queuing data for server sync
### NotificationHelper
@@ -139,7 +139,7 @@ Each geofence supports three independent GPS pause modes, configured per zone:
- **Pause tracking** - Stops saving and syncing locations inside the zone. GPS continues running to detect exit.
- **WiFi pause** - Stops GPS entirely when connected to an unmetered network (WiFi/Ethernet). Implemented via `ConnectivityManager.NetworkCallback`, which fires immediately on network availability changes. An active network counter handles devices with multiple simultaneous unmetered networks - GPS only resumes once all of them are gone, after a short debounce.
-- **Motionless pause** - Stops GPS after no device motion is detected for a configurable timeout. Uses the hardware motion sensor (via `MotionDetector`) to resume GPS when movement is detected again.
+- **Motionless pause** - Stops GPS after the device has been still for the configured per-zone dwell window (default 1 minute). Stillness is detected by `RawSensorMotionDetector` (batched accelerometer variance + parallel SIG_MOTION); any motion above the variance threshold resets the timer. The same detector fires GPS resume when movement returns.
A per-zone **stationary heartbeat** can send periodic location updates while paused. It sends the geofence center as a synthetic anchor point - no GPS wake required - bypassing sync conditions. Configured via `heartbeatEnabled` and `heartbeatIntervalMinutes` per geofence.
@@ -170,7 +170,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| Module | Purpose |
| --- | --- |
| `LocationBootReceiver` | Auto-restarts tracking after device reboot |
-| `MotionDetector` | Wraps `TYPE_SIGNIFICANT_MOTION` sensor - arms a one-shot hardware trigger that fires when the device starts moving, used to resume GPS after a stationary pause |
+| `MotionStateDetector` / `RawSensorMotionDetector` | Single detector behind a `MotionState { STATIONARY, MOVING }` interface. Backed by 30s-batched accelerometer variance (hysteresis: > 0.30 m/s² for 3s -> MOVING; < 0.15 m/s² for the configured per-zone dwell -> STATIONARY) and parallel `TYPE_SIGNIFICANT_MOTION` as a fast-path for sharp events. Fans out to both motionless-pause and stationary-profile exit consumers via one callback site in `LocationForegroundService.onMotionStateChange`. |
| `DeviceInfoHelper` | Device metadata and battery status with caching |
| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |
| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index bbf3197c..4a7520a8 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -76,7 +76,9 @@ By default, auto-export keeps the last **10** export files and deletes older one
- A notification is shown after each export with the file name and location count
- Old export files beyond the retention limit are cleaned up after each successful export
-:::note **Monthly** frequency uses a calendar month (e.g. Jan 15 to Feb 15), not a fixed 30-day interval. If the chosen day-of-month doesn't exist in a given month (e.g. day 31 in February), the export runs on the last day of that month instead. **Daily**, **Weekly** and **Monthly** intervals fire at the chosen wall-clock time via Android AlarmManager. Typical accuracy is within minutes.
+:::note
+
+**Monthly** frequency uses a calendar month (e.g. Jan 15 to Feb 15), not a fixed 30-day interval. If the chosen day-of-month doesn't exist in a given month (e.g. day 31 in February), the export runs on the last day of that month instead. **Daily**, **Weekly** and **Monthly** intervals fire at the chosen wall-clock time via Android AlarmManager. Typical accuracy is within minutes.
:::
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index c3278564..26ededa0 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -39,7 +39,7 @@ Stops GPS entirely when connected to an unmetered network (home WiFi, Ethernet).
### Pause when motionless
-Stops GPS after no device motion is detected for a configurable time (default 10 minutes). GPS resumes automatically when the device moves again. Useful for users who put their phone in airplane mode at night or sit still for long periods.
+Stops GPS after the device has been still for the configured time (default 1 minute, minimum 1 minute). Stillness is detected automatically via the accelerometer; any motion above the detection threshold resets the timer. GPS resumes within seconds when the device moves again. Useful for users who put their phone in airplane mode at night or sit still for long periods.
### Stationary heartbeat
@@ -49,7 +49,9 @@ Sends a periodic location update to your server while paused inside the zone. Us
When both **WiFi** and **motionless** pause are enabled, GPS only resumes when **both** conditions clear - WiFi must be disconnected **and** motion must be detected. Either condition alone is not enough to resume.
-:::tip Changes made in the editor take effect immediately, even when you are already inside the zone.
+:::tip
+
+Changes made in the editor take effect immediately, even when you are already inside the zone.
:::
diff --git a/apps/docs/docs/guides/tile-server.md b/apps/docs/docs/guides/tile-server.md
index 634d4532..3e7d7f28 100644
--- a/apps/docs/docs/guides/tile-server.md
+++ b/apps/docs/docs/guides/tile-server.md
@@ -22,7 +22,7 @@ Free to use. Normal usage means map tiles loading as you pan and zoom within the
If the default server is unavailable or you run into issues, you can either configure a custom tile server (see below) or open an issue on [GitHub](https://github.com/dietrichmax/colota/issues).
-:::tip Support the server
+:::tip[Support the server]
If you find Colota useful and want to help keep the default server running, contributions are welcome - the hosting runs at 17,94€/month. [mxd.codes/support](https://mxd.codes/support)
@@ -30,7 +30,7 @@ If you find Colota useful and want to help keep the default server running, cont
## Using a Custom Server
-:::note Offline maps
+:::note[Offline maps]
Offline map packs are downloaded from whichever tile server is configured at the time. Switching to a custom server won't affect packs you've already downloaded, but new downloads will come from the new server.
@@ -55,7 +55,7 @@ Any [MapLibre GL style](https://maplibre.org/maplibre-style-spec/) endpoint work
For a light/dark pair, use `bright` or `liberty` for light mode and `fiord` for dark mode.
-:::note Attribution
+:::note[Attribution]
When using the default server, the map shows **© OpenMapTiles · © OpenStreetMap contributors · © maps.mxd.codes** attribution. When a custom server is configured, attribution is read automatically from the style JSON served by your tile server.
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index d7a90e41..b4c4eebe 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -38,11 +38,15 @@ Tracking profiles automatically adjust GPS interval, distance filter, and sync s
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.
+:::tip
+
+Stationary profile When the device becomes stationary, the motion detector is started. It uses batched accelerometer variance plus the hardware significant motion sensor in parallel, so the profile deactivates within seconds of real movement regardless of the configured GPS interval (e.g. 30 min). The deactivation delay setting is not shown for stationary profiles since the motion detector handles instant resume. Set the distance filter to **0m** so points are recorded at every interval regardless of GPS drift.
:::
-:::caution Accuracy filtering matters for stationary detection The stationary condition triggers when GPS speed stays below 0.3 m/s for 60 seconds. If your default settings allow inaccurate locations (e.g. 40m+ accuracy) with a low distance filter (0m), GPS drift from noisy fixes can produce phantom speeds above the threshold - preventing the stationary profile from ever activating. To fix this, tighten your accuracy filter (e.g. 15m or less) so only clean fixes reach the speed check.
+:::caution
+
+Accuracy filtering matters for stationary detection The stationary condition triggers when GPS speed stays below 0.3 m/s for 60 seconds. If your default settings allow inaccurate locations (e.g. 40m+ accuracy) with a low distance filter (0m), GPS drift from noisy fixes can produce phantom speeds above the threshold - preventing the stationary profile from ever activating. To fix this, tighten your accuracy filter (e.g. 15m or less) so only clean fixes reach the speed check.
:::
@@ -62,7 +66,9 @@ When creating a new profile, GPS interval, distance filter, and sync interval ar
When multiple conditions match at the same time, the profile with the highest priority wins.
-:::tip If you use both a Speed Below and a Stationary profile, give Stationary the higher priority. Otherwise the speed profile keeps GPS running at its interval and the stationary heartbeat never kicks in.
+:::tip[Combining Profiles]
+
+If you use both a Speed Below and a Stationary profile, give Stationary the higher priority. Otherwise the speed profile keeps GPS running at its interval and the stationary heartbeat never kicks in.
:::
diff --git a/apps/docs/docs/integrations/phonetrack.md b/apps/docs/docs/integrations/phonetrack.md
index 49c18d22..40c8d9a6 100644
--- a/apps/docs/docs/integrations/phonetrack.md
+++ b/apps/docs/docs/integrations/phonetrack.md
@@ -19,7 +19,9 @@ sidebar_position: 5
- Select the **OwnTracks** template
- Paste the URL as your endpoint
-:::tip Which PhoneTrack URL to use? PhoneTrack offers several logging URLs (OwnTracks, GPS Logger, OpenGTS, etc.). Use the **OwnTracks** URL since Colota sends location data as a JSON POST body, which matches the OwnTracks protocol. The other URLs (like GPS Logger) expect query parameters and may not work correctly.
+:::tip
+
+Which PhoneTrack URL to use? PhoneTrack offers several logging URLs (OwnTracks, GPS Logger, OpenGTS, etc.). Use the **OwnTracks** URL since Colota sends location data as a JSON POST body, which matches the OwnTracks protocol. The other URLs (like GPS Logger) expect query parameters and may not work correctly.
:::
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 91435631..c4ea038f 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -4,7 +4,7 @@ title: Privacy Policy
# Privacy Policy
-**Last updated: April 29, 2026**
+**Last updated: May 11, 2026**
Colota ("the App") is a self-hosted GPS tracking application for Android, developed by Max Dietrich. This privacy policy explains what data the App collects, how it is used, and your rights regarding that data.
@@ -38,7 +38,7 @@ When tracking profiles are enabled, the App monitors charging state, car mode (A
### Sensor Data
-When motionless pause is enabled for a geofence zone, the App uses the device's significant motion sensor to detect motion. This data is processed in real time and is never stored or transmitted.
+When motionless pause is enabled for a geofence zone or a stationary tracking profile is active, the App reads the device's accelerometer (in low-power batched mode) and significant motion sensor to detect motion. Raw sensor values are processed in real time on-device and are never stored or transmitted.
### Network State
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 bc68b0ab..db1317f2 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
@@ -16,6 +16,7 @@ import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.core.content.ContextCompat
+import com.Colota.BuildConfig
import com.Colota.bridge.LocationServiceModule
import com.Colota.util.AppLogger
import com.Colota.data.DatabaseHelper
@@ -63,7 +64,7 @@ class LocationForegroundService : Service() {
@Volatile private var locationRestartJob: Job? = null
@Volatile private var trackingHeartbeatJob: Job? = null
@Volatile private var lastFixAtMs: Long = 0L
- @Volatile private var motionDetector: MotionDetector? = null
+ @Volatile private var motionDetector: MotionStateDetector? = null
@Volatile private var lastKnownLocation: Location? = null
/** Debounces the burst of PROVIDERS_CHANGED broadcasts when system Location toggles (one per provider). */
@@ -87,9 +88,9 @@ class LocationForegroundService : Service() {
/**
* Pause-zone state. Threading contract:
* - Mutated ONLY on the Main thread. Call sites: onStartCommand, enter/exitPauseZone,
- * activateWifiPause, unregisterWifiPause, clearMotionlessPauseState, and the bodies of
- * Main-dispatched coroutines (registerWifiPause's NetworkCallback uses Main Looper;
- * motionlessJob + wifiResumeJob switch to Dispatchers.Main before mutating).
+ * activateWifiPause, unregisterWifiPause, clearMotionlessPauseState, onMotionStateChange,
+ * and the bodies of Main-dispatched coroutines (registerWifiPause's NetworkCallback uses
+ * Main Looper; wifiResumeJob switches to Dispatchers.Main before mutating).
* - Read from any thread (location callbacks, notification builder, heartbeat IO coroutine).
* @Volatile exists for reader visibility, not mutation safety. Do NOT mutate off-Main.
*/
@@ -109,7 +110,6 @@ class LocationForegroundService : Service() {
// Motionless pause sub-state (same Main-only mutation contract as above)
@Volatile private var isMotionlessPaused = false
- @Volatile private var motionlessJob: Job? = null
@Volatile private lateinit var config: ServiceConfig
@@ -125,6 +125,8 @@ class LocationForegroundService : Service() {
const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"
const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"
const val ACTION_RECHECK_PROFILES = "com.Colota.RECHECK_PROFILES"
+ /** Debug-only: directly inject a MotionState transition. `--es state STATIONARY|MOVING`. */
+ const val ACTION_DEBUG_FORCE_MOTION = "com.Colota.DEBUG_FORCE_MOTION"
/** Actions that skip config reload and preserve current notification state. */
private val LIGHTWEIGHT_ACTIONS = setOf(
@@ -162,9 +164,14 @@ class LocationForegroundService : Service() {
notificationHelper = NotificationHelper(this, notificationManager)
notificationHelper.createChannel()
- motionDetector = MotionDetector(this) { onMotionDetected() }
+ motionDetector = RawSensorMotionDetector(this) {
+ currentZoneGeofence?.motionlessTimeoutMinutes
+ ?.let { it.coerceAtLeast(0) * 60_000L }
+ ?: RawSensorMotionDetector.DEFAULT_STATIONARY_DWELL_MS
+ }
registerLocationProvidersReceiver()
+ registerDebugMotionReceiver()
AppLogger.d(TAG, "Service created - provider: ${locationProvider.javaClass.simpleName}, motionSensor=${motionDetector?.isAvailable}")
}
@@ -226,16 +233,13 @@ class LocationForegroundService : Service() {
}
if (savedSettings[SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE]?.toBoolean() == true) {
isMotionlessPaused = true
- motionDetector?.arm()
AppLogger.d(TAG, "Restored motionless pause state")
- } else if (restoredGeofence?.pauseOnMotionless == true) {
- startMotionlessCountdown(restoredGeofence.motionlessTimeoutMinutes)
- AppLogger.d(TAG, "Restored motionless countdown: ${restoredGeofence.motionlessTimeoutMinutes}min")
}
if (restoredGeofence?.heartbeatEnabled == true) {
startHeartbeat(restoredGeofence.heartbeatIntervalMinutes)
AppLogger.d(TAG, "Restored heartbeat: ${restoredGeofence.heartbeatIntervalMinutes}min")
}
+ ensureMotionDetectorRunning()
}
}
@@ -330,14 +334,14 @@ class LocationForegroundService : Service() {
override fun onDestroy() {
AppLogger.d(TAG, "Service destroyed")
- motionDetector?.disarm()
+ motionDetector?.stop()
entryDelayJob?.cancel()
entryDelayJob = null
pendingPauseZone = null
unregisterWifiPause()
- cancelMotionlessCountdown()
cancelHeartbeat()
unregisterLocationProvidersReceiver()
+ unregisterDebugMotionReceiver()
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -516,7 +520,6 @@ class LocationForegroundService : Service() {
* Called on RECHECK when already inside the zone so editor changes take effect immediately.
*/
private fun applyZoneSettingsIfChanged(zone: GeofenceHelper.Geofence) {
- val timeoutChanged = currentZoneGeofence?.motionlessTimeoutMinutes != zone.motionlessTimeoutMinutes
val heartbeatChanged = currentZoneGeofence?.heartbeatIntervalMinutes != zone.heartbeatIntervalMinutes
currentZoneGeofence = zone
@@ -530,16 +533,11 @@ class LocationForegroundService : Service() {
unregisterWifiPause()
}
- if (zone.pauseOnMotionless && !isMotionlessPaused && (motionlessJob == null || timeoutChanged)) {
- if (timeoutChanged) cancelMotionlessCountdown()
- startMotionlessCountdown(zone.motionlessTimeoutMinutes)
- } else if (!zone.pauseOnMotionless) {
- cancelMotionlessCountdown()
- if (isMotionlessPaused) {
- clearMotionlessPauseState()
- maybeResumeGps()
- }
+ if (!zone.pauseOnMotionless && isMotionlessPaused) {
+ clearMotionlessPauseState()
+ maybeResumeGps()
}
+ ensureMotionDetectorRunning()
if (zone.heartbeatEnabled && (heartbeatJob == null || heartbeatChanged)) {
startHeartbeat(zone.heartbeatIntervalMinutes)
@@ -755,8 +753,8 @@ class LocationForegroundService : Service() {
*/
private fun startZoneHolds(zone: GeofenceHelper.Geofence) {
if (zone.pauseOnWifi) registerWifiPause()
- if (zone.pauseOnMotionless) startMotionlessCountdown(zone.motionlessTimeoutMinutes)
if (zone.heartbeatEnabled) startHeartbeat(zone.heartbeatIntervalMinutes)
+ ensureMotionDetectorRunning()
}
/**
@@ -765,9 +763,9 @@ class LocationForegroundService : Service() {
*/
private fun stopZoneHolds() {
unregisterWifiPause()
- cancelMotionlessCountdown()
clearMotionlessPauseState()
cancelHeartbeat()
+ ensureMotionDetectorRunning()
}
// ── WiFi pause ────────────────────────────────────────────────────────
@@ -856,39 +854,9 @@ class LocationForegroundService : Service() {
// ── Motionless pause ──────────────────────────────────────────────────
- /**
- * Starts the motionless timeout countdown for a zone with [pauseOnMotionless] enabled.
- * When the countdown completes without significant motion, GPS is stopped and the
- * motion sensor is armed to resume it when the device moves again.
- */
- private fun startMotionlessCountdown(timeoutMinutes: Int) {
- motionlessJob?.cancel()
- motionlessJob = serviceScope?.launch {
- delay(timeoutMinutes * 60_000L)
- withContext(Dispatchers.Main) {
- motionlessJob = null
- if (insidePauseZone && !isMotionlessPaused) {
- isMotionlessPaused = true
- dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "true")
- stopLocationUpdates()
- motionDetector?.arm()
- refreshNotificationForCurrentState()
- LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, "motionless")
- AppLogger.i(TAG, "Motionless timeout reached - GPS paused, motion sensor armed")
- }
- }
- }
- }
-
- private fun cancelMotionlessCountdown() {
- motionlessJob?.cancel()
- motionlessJob = null
- }
-
private fun clearMotionlessPauseState() {
isMotionlessPaused = false
dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "false")
- if (!profileManager.isStationary) motionDetector?.disarm()
}
/**
@@ -970,22 +938,6 @@ class LocationForegroundService : Service() {
}
}
- /**
- * Resumes GPS after motion is detected in a motionless-paused zone.
- * Re-arms the countdown so the zone can pause again if device becomes stationary again.
- */
- private fun resumeFromMotionlessPause() {
- clearMotionlessPauseState()
- val geofence = currentZoneGeofence
- maybeResumeGps()
- LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, if (isWifiPaused) "wifi" else null)
- // Restart countdown so the zone can pause again if device becomes stationary
- if (geofence?.pauseOnMotionless == true) {
- startMotionlessCountdown(geofence.motionlessTimeoutMinutes)
- }
- AppLogger.i(TAG, "Motion detected in pause zone - motionless hold cleared")
- }
-
/**
* Resumes GPS only if no pause holds are active.
* Use this instead of calling [setupLocationUpdates] directly in WiFi/motionless resume paths.
@@ -1107,21 +1059,81 @@ class LocationForegroundService : Service() {
stopSelf()
}
- /** Called by MotionDetector when the device starts moving again. */
- private fun onMotionDetected() {
- if (isMotionlessPaused) {
- resumeFromMotionlessPause()
+ /**
+ * STATIONARY: pause GPS if inside a `pauseOnMotionless` zone.
+ * MOVING: clear motionless pause and notify the profile manager.
+ */
+ private fun onMotionStateChange(state: MotionState) {
+ when (state) {
+ MotionState.STATIONARY -> {
+ if (insidePauseZone && currentZoneGeofence?.pauseOnMotionless == true && !isMotionlessPaused) {
+ isMotionlessPaused = true
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "true")
+ stopLocationUpdates()
+ refreshNotificationForCurrentState()
+ LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, "motionless")
+ AppLogger.i(TAG, "Motion detector reports STATIONARY in pause zone - GPS paused")
+ }
+ }
+ MotionState.MOVING -> {
+ if (isMotionlessPaused) {
+ clearMotionlessPauseState()
+ maybeResumeGps()
+ LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, if (isWifiPaused) "wifi" else null)
+ AppLogger.i(TAG, "Motion detector reports MOVING in pause zone - motionless hold cleared")
+ }
+ profileManager.onMotionDetected()
+ ensureMotionDetectorRunning()
+ }
+ }
+ }
+
+ /** Runs the detector when motionless pause is enabled inside the current zone or the profile is stationary. */
+ private fun ensureMotionDetectorRunning() {
+ val detector = motionDetector ?: return
+ val needForZone = insidePauseZone && currentZoneGeofence?.pauseOnMotionless == true
+ val needForProfile = profileManager.isStationary
+ if (needForZone || needForProfile) {
+ detector.start(::onMotionStateChange)
+ } else {
+ detector.stop()
}
- profileManager.onMotionDetected()
}
- /** 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()
+ ensureMotionDetectorRunning()
+ }
+
+ // ── Debug-only motion injection (BuildConfig.DEBUG) ───────────────────
+
+ private val debugMotionReceiver = if (BuildConfig.DEBUG) object : BroadcastReceiver() {
+ override fun onReceive(context: Context?, intent: Intent?) {
+ if (intent?.action != ACTION_DEBUG_FORCE_MOTION) return
+ val raw = intent.getStringExtra("state") ?: run {
+ AppLogger.w(TAG, "DEBUG_FORCE_MOTION: missing 'state' extra")
+ return
+ }
+ val state = try {
+ MotionState.valueOf(raw)
+ } catch (_: IllegalArgumentException) {
+ AppLogger.w(TAG, "DEBUG_FORCE_MOTION: invalid state '$raw' (expected STATIONARY|MOVING)")
+ return
+ }
+ (motionDetector as? RawSensorMotionDetector)?.forceState(state)
+ AppLogger.d(TAG, "DEBUG_FORCE_MOTION -> $state")
}
+ } else null
+
+ private fun registerDebugMotionReceiver() {
+ val receiver = debugMotionReceiver ?: return
+ ContextCompat.registerReceiver(
+ this, receiver, IntentFilter(ACTION_DEBUG_FORCE_MOTION), ContextCompat.RECEIVER_NOT_EXPORTED
+ )
+ }
+
+ private fun unregisterDebugMotionReceiver() {
+ val receiver = debugMotionReceiver ?: return
+ try { unregisterReceiver(receiver) } catch (_: IllegalArgumentException) {}
}
// ── Profile hot-swap ────────────────────────────────────────────────
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt b/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt
deleted file mode 100644
index ed224369..00000000
--- a/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Copyright (C) 2026 Max Dietrich
- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
- */
-
-package com.Colota.service
-
-import android.content.Context
-import android.hardware.Sensor
-import android.hardware.SensorManager
-import android.hardware.TriggerEvent
-import android.hardware.TriggerEventListener
-import com.Colota.util.AppLogger
-
-/**
- * Detects device motion using the hardware significant motion sensor.
- *
- * The significant motion sensor is a one-shot trigger: it fires once when
- * the device starts moving and then unregisters itself. After the callback
- * fires, [rearm] must be called to listen for the next motion event.
- *
- * This is extremely battery-efficient because the detection runs entirely
- * in hardware (the sensor hub), consuming near-zero power while idle.
- *
- * @param onMotionDetected Called on a sensor handler thread when motion is detected.
- */
-class MotionDetector(
- context: Context,
- private val onMotionDetected: () -> Unit
-) {
- companion object {
- private const val TAG = "MotionDetector"
- }
-
- private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
- private val motionSensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION)
-
- @Volatile private var armed = false
-
- private val triggerListener = object : TriggerEventListener() {
- override fun onTrigger(event: TriggerEvent?) {
- armed = false
- AppLogger.d(TAG, "Significant motion detected")
- onMotionDetected()
- }
- }
-
- /** Whether the device has a significant motion sensor. */
- val isAvailable: Boolean get() = motionSensor != null
-
- /**
- * Arms the sensor to fire on the next significant motion event.
- * Safe to call multiple times - will not double-register.
- */
- fun arm() {
- if (armed || motionSensor == null) return
- val success = sensorManager.requestTriggerSensor(triggerListener, motionSensor)
- armed = success
- AppLogger.d(TAG, "Sensor armed: $success")
- }
-
- /**
- * Disarms the sensor. Call when tracking stops or the feature is disabled.
- */
- fun disarm() {
- if (!armed || motionSensor == null) return
- sensorManager.cancelTriggerSensor(triggerListener, motionSensor)
- armed = false
- AppLogger.d(TAG, "Sensor disarmed")
- }
-}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/MotionStateDetector.kt b/apps/mobile/android/app/src/main/java/com/colota/service/MotionStateDetector.kt
new file mode 100644
index 00000000..250f50f8
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/MotionStateDetector.kt
@@ -0,0 +1,15 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+/** Reports STATIONARY/MOVING transitions for the foreground service to pause and resume GPS. */
+interface MotionStateDetector {
+ fun start(listener: (MotionState) -> Unit)
+ fun stop()
+ val isAvailable: Boolean
+}
+
+enum class MotionState { STATIONARY, MOVING }
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/RawSensorMotionDetector.kt b/apps/mobile/android/app/src/main/java/com/colota/service/RawSensorMotionDetector.kt
new file mode 100644
index 00000000..87c43508
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/RawSensorMotionDetector.kt
@@ -0,0 +1,184 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.hardware.TriggerEvent
+import android.hardware.TriggerEventListener
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
+import kotlin.math.sqrt
+
+/**
+ * Accelerometer variance (30s batched FIFO) plus TYPE_SIGNIFICANT_MOTION.
+ * Variance handles both STATIONARY and MOVING transitions with hysteresis and
+ * catches sustained low-amplitude vibration (still phone in a moving vehicle)
+ * that SIG_MOTION filters out. SIG_MOTION runs in parallel for instant wake on
+ * sharp events.
+ *
+ * @param getStationaryDwellMs read on each sample; lets the service inject the
+ * per-zone motionlessTimeoutMinutes without restarting the detector.
+ */
+class RawSensorMotionDetector(
+ context: Context,
+ private val getStationaryDwellMs: () -> Long = { DEFAULT_STATIONARY_DWELL_MS }
+) : MotionStateDetector {
+
+ companion object {
+ private const val TAG = "MotionDetector"
+
+ private const val MOVING_VARIANCE_THRESHOLD = 0.30
+ private const val STATIONARY_VARIANCE_THRESHOLD = 0.15
+ private const val MOVING_DWELL_MS = 3_000L
+ const val DEFAULT_STATIONARY_DWELL_MS = 60_000L
+ /** Sliding window over which accelerometer-magnitude variance is computed. Independent of dwell. */
+ private const val VARIANCE_WINDOW_MS = 60_000L
+ private const val MAX_REPORT_LATENCY_US = 30_000_000
+ private const val MIN_SAMPLES_FOR_VARIANCE = 8
+ }
+
+ private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
+ private val accelSensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
+ private val sigMotionSensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION)
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private val lifecycleLock = Any()
+
+ @Volatile private var listener: ((MotionState) -> Unit)? = null
+ @Volatile private var currentState: MotionState = MotionState.MOVING
+
+ private val sampleWindow = ArrayDeque<Sample>()
+ private var aboveThresholdSinceMs: Long = 0L
+ private var belowThresholdSinceMs: Long = 0L
+
+ private data class Sample(val timestampMs: Long, val magnitude: Double)
+
+ override val isAvailable: Boolean get() = accelSensor != null
+
+ private val accelListener = object : SensorEventListener {
+ override fun onSensorChanged(event: SensorEvent?) {
+ val e = event ?: return
+ val ax = e.values[0]
+ val ay = e.values[1]
+ val az = e.values[2]
+ val magnitude = sqrt((ax * ax + ay * ay + az * az).toDouble()) - SensorManager.GRAVITY_EARTH
+ processSample(SystemClock.elapsedRealtime(), magnitude)
+ }
+ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
+ }
+
+ private val sigMotionListener = object : TriggerEventListener() {
+ override fun onTrigger(event: TriggerEvent?) {
+ sigMotionSensor?.let { sensorManager.requestTriggerSensor(this, it) }
+ transitionTo(MotionState.MOVING, "sig_motion")
+ }
+ }
+
+ override fun start(listener: (MotionState) -> Unit) {
+ synchronized(lifecycleLock) {
+ if (this.listener != null) return
+ this.listener = listener
+ currentState = MotionState.MOVING
+ sampleWindow.clear()
+ aboveThresholdSinceMs = 0L
+ belowThresholdSinceMs = 0L
+
+ accelSensor?.let {
+ sensorManager.registerListener(accelListener, it, SensorManager.SENSOR_DELAY_NORMAL, MAX_REPORT_LATENCY_US)
+ }
+ sigMotionSensor?.let {
+ sensorManager.requestTriggerSensor(sigMotionListener, it)
+ }
+ }
+ AppLogger.d(TAG, "Started (accel=${accelSensor != null}, sigMotion=${sigMotionSensor != null}, batchUs=$MAX_REPORT_LATENCY_US)")
+ }
+
+ override fun stop() {
+ synchronized(lifecycleLock) {
+ if (listener == null) return
+ listener = null
+ accelSensor?.let { sensorManager.unregisterListener(accelListener, it) }
+ sigMotionSensor?.let { sensorManager.cancelTriggerSensor(sigMotionListener, it) }
+ sampleWindow.clear()
+ // Drop transition posts queued before stop arrived. The listener null-check in
+ // the posted lambda is the backstop if cancellation misses one.
+ mainHandler.removeCallbacksAndMessages(null)
+ }
+ AppLogger.d(TAG, "Stopped")
+ }
+
+ /** Test-build hook: directly inject a state transition (called from ADB-debug receiver). */
+ fun forceState(newState: MotionState) {
+ transitionTo(newState, "debug_force")
+ }
+
+ private fun processSample(nowMs: Long, magnitude: Double) {
+ sampleWindow.addLast(Sample(nowMs, magnitude))
+ while (sampleWindow.isNotEmpty() && nowMs - sampleWindow.first().timestampMs > VARIANCE_WINDOW_MS) {
+ sampleWindow.removeFirst()
+ }
+
+ if (sampleWindow.size < MIN_SAMPLES_FOR_VARIANCE) return
+
+ val variance = computeVariance(sampleWindow)
+ val stationaryDwellMs = getStationaryDwellMs().coerceAtLeast(0L)
+
+ if (BuildConfig.DEBUG) {
+ AppLogger.d(TAG, "t=$nowMs v=${"%.4f".format(variance)} n=${sampleWindow.size} state=$currentState")
+ }
+
+ when {
+ variance > MOVING_VARIANCE_THRESHOLD -> {
+ belowThresholdSinceMs = 0L
+ if (aboveThresholdSinceMs == 0L) aboveThresholdSinceMs = nowMs
+ if (currentState != MotionState.MOVING && nowMs - aboveThresholdSinceMs >= MOVING_DWELL_MS) {
+ transitionTo(MotionState.MOVING, "variance=${"%.3f".format(variance)}")
+ aboveThresholdSinceMs = 0L
+ }
+ }
+ variance < STATIONARY_VARIANCE_THRESHOLD -> {
+ aboveThresholdSinceMs = 0L
+ if (belowThresholdSinceMs == 0L) belowThresholdSinceMs = nowMs
+ if (currentState != MotionState.STATIONARY && nowMs - belowThresholdSinceMs >= stationaryDwellMs) {
+ transitionTo(MotionState.STATIONARY, "variance=${"%.3f".format(variance)} dwell=${stationaryDwellMs / 1000}s")
+ belowThresholdSinceMs = 0L
+ }
+ }
+ else -> {
+ // Ambiguous band between thresholds: drop both timers so a transition needs a fresh sustained period.
+ aboveThresholdSinceMs = 0L
+ belowThresholdSinceMs = 0L
+ }
+ }
+ }
+
+ private fun computeVariance(samples: ArrayDeque<Sample>): Double {
+ val n = samples.size
+ var sum = 0.0
+ for (s in samples) sum += s.magnitude
+ val mean = sum / n
+ var sumSquares = 0.0
+ for (s in samples) {
+ val d = s.magnitude - mean
+ sumSquares += d * d
+ }
+ return sumSquares / n
+ }
+
+ private fun transitionTo(newState: MotionState, reason: String) {
+ if (currentState == newState) return
+ currentState = newState
+ AppLogger.i(TAG, "State -> $newState ($reason)")
+ // Re-read listener at delivery: a stop() between post and run nulls it, and this exits.
+ mainHandler.post { listener?.invoke(newState) }
+ }
+}
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 e44d2479..638130f1 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
@@ -992,7 +992,6 @@ class LocationForegroundServiceTest {
setField("isWifiPaused", true)
setField("isMotionlessPaused", true)
setField("wifiCallback", mockk<android.net.ConnectivityManager.NetworkCallback>(relaxed = true))
- setField("motionlessJob", mockk<Job>(relaxed = true))
val location = mockLocation(lat = 52.0, lon = 13.0)
every { geofenceHelper.getPauseZone(location) } returns bothGeofence
@@ -1498,22 +1497,25 @@ class LocationForegroundServiceTest {
}
@Test
- fun `enterPauseZone with pauseOnMotionless starts countdown`() {
- val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 5)
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
+ fun `enterPauseZone with pauseOnMotionless starts motion detector`() {
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
invokeEnterPauseZone(motionlessGeofence)
- verify { service["startMotionlessCountdown"](5) }
+ verify { detector.start(any()) }
}
@Test
- fun `enterPauseZone without pauseOnMotionless skips countdown`() {
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
+ fun `enterPauseZone without pauseOnMotionless does not start motion detector`() {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ every { profileManager.isStationary } returns false
invokeEnterPauseZone(homeGeofence)
- verify(exactly = 0) { service["startMotionlessCountdown"](any<Int>()) }
+ verify(exactly = 0) { detector.start(any()) }
}
// =========================================================================
@@ -1565,136 +1567,145 @@ class LocationForegroundServiceTest {
}
// =========================================================================
- // startMotionlessCountdown
+ // onMotionStateChange - STATIONARY (motionless pause entry)
// =========================================================================
@Test
- fun `startMotionlessCountdown pauses GPS after timeout`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
+ fun `onMotionStateChange STATIONARY pauses GPS when in pauseOnMotionless zone`() = runServiceTest {
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", motionlessGeofence)
+ setField("isMotionlessPaused", false)
- invokeStartMotionlessCountdown(1)
- advanceTimeBy(60_001L)
+ invokeOnMotionStateChange(MotionState.STATIONARY)
assertTrue(getField<Boolean>("isMotionlessPaused"))
verify { dbHelper.saveSetting("pause_zone_motionless_active", "true") }
- verify { motionDetector.arm() }
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", "motionless") }
}
@Test
- fun `startMotionlessCountdown does not pause when zone exited before timeout`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("insidePauseZone", false)
+ fun `onMotionStateChange STATIONARY ignored when zone has no motionless setting`() = runServiceTest {
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", homeGeofence) // pauseOnMotionless=false
- invokeStartMotionlessCountdown(1)
- advanceTimeBy(60_001L)
+ invokeOnMotionStateChange(MotionState.STATIONARY)
assertFalse(getField<Boolean>("isMotionlessPaused"))
- verify(exactly = 0) { motionDetector.arm() }
+ verify(exactly = 0) { dbHelper.saveSetting("pause_zone_motionless_active", "true") }
}
@Test
- fun `startMotionlessCountdown does not pause when already motionless paused`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
+ fun `onMotionStateChange STATIONARY ignored when already motionless paused`() = runServiceTest {
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
setField("insidePauseZone", true)
+ setField("currentZoneGeofence", motionlessGeofence)
setField("isMotionlessPaused", true)
- invokeStartMotionlessCountdown(1)
- advanceTimeBy(60_001L)
+ invokeOnMotionStateChange(MotionState.STATIONARY)
- // arm should not be called a second time
- verify(exactly = 0) { motionDetector.arm() }
+ verify(exactly = 0) { dbHelper.saveSetting("pause_zone_motionless_active", "true") }
}
- // =========================================================================
- // resumeFromMotionlessPause
- // =========================================================================
-
@Test
- fun `resumeFromMotionlessPause clears state and saves to DB`() = runServiceTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isMotionlessPaused", true)
- setField("currentZoneGeofence", homeGeofence)
+ fun `onMotionStateChange STATIONARY ignored when not inside any pause zone`() = runServiceTest {
+ setField("insidePauseZone", false)
+ setField("currentZoneGeofence", null)
- invokeResumeFromMotionlessPause()
+ invokeOnMotionStateChange(MotionState.STATIONARY)
assertFalse(getField<Boolean>("isMotionlessPaused"))
- verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }
- verify { motionDetector.disarm() }
}
+ // =========================================================================
+ // onMotionStateChange - MOVING (motionless pause exit + profile notify)
+ // =========================================================================
+
@Test
- fun `resumeFromMotionlessPause resumes GPS when no wifi hold active`() = runServiceTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
+ fun `onMotionStateChange MOVING clears motionless pause and resumes GPS`() = runServiceTest {
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", motionlessGeofence)
setField("isMotionlessPaused", true)
- setField("isWifiPaused", false)
- setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true))
- invokeResumeFromMotionlessPause()
+ invokeOnMotionStateChange(MotionState.MOVING)
+ assertFalse(getField<Boolean>("isMotionlessPaused"))
+ verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }
verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
}
@Test
- fun `resumeFromMotionlessPause does not resume GPS when wifi hold still active`() = testScope.runTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
+ fun `onMotionStateChange MOVING does not resume GPS when wifi hold still active`() = runServiceTest {
+ val bothGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true)
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", bothGeofence)
setField("isMotionlessPaused", true)
setField("isWifiPaused", true)
- setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true))
- invokeResumeFromMotionlessPause()
+ invokeOnMotionStateChange(MotionState.MOVING)
+ assertFalse(getField<Boolean>("isMotionlessPaused"))
verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
}
@Test
- fun `resumeFromMotionlessPause restarts countdown when zone has pauseOnMotionless`() = runServiceTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isMotionlessPaused", true)
- val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 3)
- setField("currentZoneGeofence", motionlessGeofence)
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
+ fun `onMotionStateChange MOVING notifies profile manager`() = runServiceTest {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("isMotionlessPaused", false)
- invokeResumeFromMotionlessPause()
+ invokeOnMotionStateChange(MotionState.MOVING)
- verify { service["startMotionlessCountdown"](3) }
+ verify { profileManager.onMotionDetected() }
}
// =========================================================================
- // onMotionDetected - motionless pause path
+ // ensureMotionDetectorRunning - lifecycle
// =========================================================================
@Test
- fun `onMotionDetected resumes from motionless pause when isMotionlessPaused`() = runServiceTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isMotionlessPaused", true)
+ fun `ensureMotionDetectorRunning starts detector when in pauseOnMotionless zone`() {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
setField("insidePauseZone", true)
- setField("currentZoneGeofence", homeGeofence)
+ setField("currentZoneGeofence", geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true))
+ every { profileManager.isStationary } returns false
- invokeOnMotionDetected()
+ invokeEnsureMotionDetectorRunning()
- assertFalse(getField<Boolean>("isMotionlessPaused"))
- verify { dbHelper.saveSetting("pause_zone_motionless_active", "false") }
+ verify { detector.start(any()) }
}
@Test
- fun `onMotionDetected triggers motionless resume`() = runServiceTest {
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
- setField("isMotionlessPaused", true)
- setField("currentZoneGeofence", homeGeofence)
+ fun `ensureMotionDetectorRunning starts detector when profile is stationary`() {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("insidePauseZone", false)
+ every { profileManager.isStationary } returns true
- invokeOnMotionDetected()
+ invokeEnsureMotionDetectorRunning()
- assertFalse(getField<Boolean>("isMotionlessPaused"))
+ verify { detector.start(any()) }
+ }
+
+ @Test
+ fun `ensureMotionDetectorRunning stops detector when neither condition holds`() {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("insidePauseZone", false)
+ setField("currentZoneGeofence", null)
+ every { profileManager.isStationary } returns false
+
+ invokeEnsureMotionDetectorRunning()
+
+ verify { detector.stop() }
}
// =========================================================================
@@ -1773,8 +1784,8 @@ class LocationForegroundServiceTest {
@Test
fun `applyZoneSettingsIfChanged disables motionless hold and resumes GPS`() {
val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
- val motionDetector = mockk<MotionDetector>(relaxed = true)
- setField("motionDetector", motionDetector)
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
setField("currentZoneGeofence", motionlessGeofence)
setField("isMotionlessPaused", true)
@@ -1786,44 +1797,17 @@ class LocationForegroundServiceTest {
}
@Test
- fun `applyZoneSettingsIfChanged starts countdown when pauseOnMotionless toggled on`() {
+ fun `applyZoneSettingsIfChanged starts motion detector when pauseOnMotionless toggled on`() {
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("insidePauseZone", true)
setField("currentZoneGeofence", homeGeofence) // pauseOnMotionless=false
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
- val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 7)
+ every { profileManager.isStationary } returns false
+ val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
invokeApplyZoneSettingsIfChanged(updatedGeofence)
- verify { service["startMotionlessCountdown"](7) }
- }
-
- @Test
- fun `applyZoneSettingsIfChanged restarts countdown when timeout changes`() {
- val originalGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)
- setField("currentZoneGeofence", originalGeofence)
- setField("motionlessJob", mockk<Job>(relaxed = true))
- coEvery { service["cancelMotionlessCountdown"]() } returns Unit
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
- val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 3)
-
- invokeApplyZoneSettingsIfChanged(updatedGeofence)
-
- verifyOrder {
- service["cancelMotionlessCountdown"]()
- service["startMotionlessCountdown"](3)
- }
- }
-
- @Test
- fun `applyZoneSettingsIfChanged does not restart countdown when timeout unchanged`() {
- val originalGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)
- setField("currentZoneGeofence", originalGeofence)
- setField("motionlessJob", mockk<Job>(relaxed = true))
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
- val updatedGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true, motionlessTimeoutMinutes = 10)
-
- invokeApplyZoneSettingsIfChanged(updatedGeofence)
-
- verify(exactly = 0) { service["startMotionlessCountdown"](any<Int>()) }
+ verify { detector.start(any()) }
}
// =========================================================================
@@ -1956,14 +1940,15 @@ class LocationForegroundServiceTest {
@Test
fun `enterPauseZone with both WiFi and motionless registers both`() {
- val dualGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true, motionlessTimeoutMinutes = 5)
+ val dualGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true)
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
coEvery { service["registerWifiPause"]() } returns Unit
- coEvery { service["startMotionlessCountdown"](any<Int>()) } returns Unit
invokeEnterPauseZone(dualGeofence)
verify { service["registerWifiPause"]() }
- verify { service["startMotionlessCountdown"](5) }
+ verify { detector.start(any()) }
}
@Test
@@ -2095,20 +2080,16 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
- private fun invokeOnMotionDetected() {
- val method = LocationForegroundService::class.java.getDeclaredMethod("onMotionDetected")
- method.isAccessible = true
- method.invoke(service)
- }
-
- private fun invokeStartMotionlessCountdown(timeoutMinutes: Int) {
- val method = LocationForegroundService::class.java.getDeclaredMethod("startMotionlessCountdown", Int::class.java)
+ private fun invokeOnMotionStateChange(state: MotionState) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "onMotionStateChange", MotionState::class.java
+ )
method.isAccessible = true
- method.invoke(service, timeoutMinutes)
+ method.invoke(service, state)
}
- private fun invokeResumeFromMotionlessPause() {
- val method = LocationForegroundService::class.java.getDeclaredMethod("resumeFromMotionlessPause")
+ private fun invokeEnsureMotionDetectorRunning() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("ensureMotionDetectorRunning")
method.isAccessible = true
method.invoke(service)
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt
deleted file mode 100644
index c25b15be..00000000
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Copyright (C) 2026 Max Dietrich
- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
- */
-
-package com.Colota.service
-
-import android.content.Context
-import android.hardware.Sensor
-import android.hardware.SensorManager
-import android.hardware.TriggerEventListener
-import io.mockk.*
-import org.junit.Assert.*
-import org.junit.Before
-import org.junit.Test
-
-class MotionDetectorTest {
-
- private lateinit var context: Context
- private lateinit var sensorManager: SensorManager
- private lateinit var motionSensor: Sensor
- private var motionCallback = 0
-
- private fun makeDetector(sensorAvailable: Boolean = true): MotionDetector {
- context = mockk()
- sensorManager = mockk(relaxed = true)
- motionSensor = mockk()
-
- every { context.getSystemService(Context.SENSOR_SERVICE) } returns sensorManager
- every { sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION) } returns
- if (sensorAvailable) motionSensor else null
- every { sensorManager.requestTriggerSensor(any(), any()) } returns true
-
- motionCallback = 0
- return MotionDetector(context) { motionCallback++ }
- }
-
- @Test
- fun `isAvailable returns true when sensor exists`() {
- val detector = makeDetector(sensorAvailable = true)
- assertTrue(detector.isAvailable)
- }
-
- @Test
- fun `isAvailable returns false when sensor missing`() {
- val detector = makeDetector(sensorAvailable = false)
- assertFalse(detector.isAvailable)
- }
-
- @Test
- fun `arm registers trigger sensor`() {
- val detector = makeDetector()
- detector.arm()
- verify(exactly = 1) { sensorManager.requestTriggerSensor(any(), motionSensor) }
- }
-
- @Test
- fun `arm does nothing when sensor unavailable`() {
- val detector = makeDetector(sensorAvailable = false)
- detector.arm()
- verify(exactly = 0) { sensorManager.requestTriggerSensor(any(), any()) }
- }
-
- @Test
- fun `arm does not double-register when already armed`() {
- val detector = makeDetector()
- detector.arm()
- detector.arm()
- verify(exactly = 1) { sensorManager.requestTriggerSensor(any(), motionSensor) }
- }
-
- @Test
- fun `disarm cancels trigger sensor`() {
- val detector = makeDetector()
- detector.arm()
- detector.disarm()
- verify(exactly = 1) { sensorManager.cancelTriggerSensor(any(), motionSensor) }
- }
-
- @Test
- fun `disarm does nothing when not armed`() {
- val detector = makeDetector()
- detector.disarm()
- verify(exactly = 0) { sensorManager.cancelTriggerSensor(any(), any()) }
- }
-
- @Test
- fun `onTrigger invokes callback and resets armed state`() {
- val detector = makeDetector()
- val listenerSlot = slot<TriggerEventListener>()
- every { sensorManager.requestTriggerSensor(capture(listenerSlot), any()) } returns true
-
- detector.arm()
- listenerSlot.captured.onTrigger(null)
-
- assertEquals(1, motionCallback)
- // After trigger fires, armed should be false - disarm should not call cancel
- detector.disarm()
- verify(exactly = 0) { sensorManager.cancelTriggerSensor(any(), any()) }
- }
-}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/RawSensorMotionDetectorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/RawSensorMotionDetectorTest.kt
new file mode 100644
index 00000000..f9504a23
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/RawSensorMotionDetectorTest.kt
@@ -0,0 +1,361 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.hardware.TriggerEvent
+import android.hardware.TriggerEventListener
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import com.Colota.util.AppLogger
+import io.mockk.*
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+class RawSensorMotionDetectorTest {
+
+ private lateinit var context: Context
+ private lateinit var sensorManager: SensorManager
+ private lateinit var accelSensor: Sensor
+ private lateinit var sigMotionSensor: Sensor
+ private lateinit var accelListenerSlot: CapturingSlot<SensorEventListener>
+ private lateinit var sigListenerSlot: CapturingSlot<TriggerEventListener>
+
+ @Before
+ fun setUp() {
+ context = mockk()
+ sensorManager = mockk(relaxed = true)
+ accelSensor = mockk()
+ sigMotionSensor = mockk()
+ accelListenerSlot = slot()
+ sigListenerSlot = slot()
+
+ mockkObject(AppLogger)
+ every { AppLogger.d(any(), any()) } just Runs
+ every { AppLogger.i(any(), any()) } just Runs
+ every { AppLogger.w(any(), any()) } just Runs
+
+ // Detector constructs a Handler(Looper.getMainLooper()) — stub both.
+ mockkStatic(Looper::class)
+ every { Looper.getMainLooper() } returns mockk(relaxed = true)
+ mockkConstructor(Handler::class)
+ every { anyConstructed<Handler>().post(any()) } answers {
+ firstArg<Runnable>().run()
+ true
+ }
+
+ // SystemClock.elapsedRealtime is read inside accelListener.onSensorChanged; tests
+ // that drive synthetic sensor events stub it via stubElapsedRealtime() per sample.
+ mockkStatic(SystemClock::class)
+ every { SystemClock.elapsedRealtime() } returns 0L
+
+ every { context.getSystemService(Context.SENSOR_SERVICE) } returns sensorManager
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ unmockkStatic(Looper::class)
+ unmockkStatic(SystemClock::class)
+ unmockkConstructor(Handler::class)
+ }
+
+ private fun makeDetector(
+ accelAvailable: Boolean = true,
+ sigMotionAvailable: Boolean = true,
+ stationaryDwellMs: Long = RawSensorMotionDetector.DEFAULT_STATIONARY_DWELL_MS
+ ): RawSensorMotionDetector {
+ every { sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) } returns
+ if (accelAvailable) accelSensor else null
+ every { sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION) } returns
+ if (sigMotionAvailable) sigMotionSensor else null
+ every { sensorManager.requestTriggerSensor(capture(sigListenerSlot), any()) } returns true
+ every { sensorManager.registerListener(capture(accelListenerSlot), any<Sensor>(), any<Int>(), any<Int>()) } returns true
+ return RawSensorMotionDetector(context) { stationaryDwellMs }
+ }
+
+ /**
+ * Build a SensorEvent whose accelerometer-magnitude minus GRAVITY_EARTH equals [magnitude].
+ * The detector reads only event.values[0..2]; setting ay/az = 0 lets us encode the target
+ * magnitude directly into ax.
+ *
+ * SensorEvent.values is a public final Java field, not a Kotlin property, so mockk's
+ * `every { event.values } returns ...` cannot intercept the field read. We allocate a
+ * relaxed mock (skips constructor stub) and set the final field via reflection.
+ */
+ private fun sensorEvent(magnitude: Double): SensorEvent {
+ val ax = (magnitude + SensorManager.GRAVITY_EARTH).toFloat()
+ val event = mockk<SensorEvent>(relaxed = true)
+ SensorEvent::class.java.getDeclaredField("values").apply {
+ isAccessible = true
+ set(event, floatArrayOf(ax, 0f, 0f))
+ }
+ return event
+ }
+
+ private fun feedSample(magnitude: Double, atMs: Long) {
+ every { SystemClock.elapsedRealtime() } returns atMs
+ accelListenerSlot.captured.onSensorChanged(sensorEvent(magnitude))
+ }
+
+ @Test
+ fun `isAvailable true when accelerometer exists`() {
+ val detector = makeDetector(accelAvailable = true)
+ assertTrue(detector.isAvailable)
+ }
+
+ @Test
+ fun `isAvailable false when accelerometer missing`() {
+ val detector = makeDetector(accelAvailable = false)
+ assertFalse(detector.isAvailable)
+ }
+
+ @Test
+ fun `start registers accelerometer with batched FIFO and SIG_MOTION`() {
+ val detector = makeDetector()
+ detector.start { /* no-op */ }
+ verify { sensorManager.registerListener(any(), accelSensor, SensorManager.SENSOR_DELAY_NORMAL, 30_000_000) }
+ verify { sensorManager.requestTriggerSensor(any(), sigMotionSensor) }
+ }
+
+ @Test
+ fun `start is idempotent - second call does not re-register`() {
+ val detector = makeDetector()
+ detector.start { }
+ detector.start { }
+ verify(exactly = 1) { sensorManager.registerListener(any(), accelSensor, any(), any<Int>()) }
+ verify(exactly = 1) { sensorManager.requestTriggerSensor(any(), sigMotionSensor) }
+ }
+
+ @Test
+ fun `stop unregisters both sensors`() {
+ val detector = makeDetector()
+ detector.start { }
+ detector.stop()
+ verify { sensorManager.unregisterListener(any(), accelSensor) }
+ verify { sensorManager.cancelTriggerSensor(any(), sigMotionSensor) }
+ }
+
+ @Test
+ fun `stop without start is a no-op`() {
+ val detector = makeDetector()
+ detector.stop()
+ verify(exactly = 0) { sensorManager.unregisterListener(any(), any<Sensor>()) }
+ verify(exactly = 0) { sensorManager.cancelTriggerSensor(any(), any()) }
+ }
+
+ @Test
+ fun `start works when SIG_MOTION sensor is missing`() {
+ val detector = makeDetector(sigMotionAvailable = false)
+ detector.start { }
+ verify { sensorManager.registerListener(any(), accelSensor, any(), any<Int>()) }
+ verify(exactly = 0) { sensorManager.requestTriggerSensor(any(), any()) }
+ }
+
+ @Test
+ fun `forceState invokes listener with new state`() {
+ val detector = makeDetector()
+ var received: MotionState? = null
+ detector.start { received = it }
+ // Initial state is MOVING; force STATIONARY to observe a transition.
+ detector.forceState(MotionState.STATIONARY)
+ assertEquals(MotionState.STATIONARY, received)
+ }
+
+ @Test
+ fun `forceState does not invoke listener when state unchanged`() {
+ val detector = makeDetector()
+ var callCount = 0
+ detector.start { callCount++ }
+ // Initial state is MOVING; forcing MOVING should be a no-op.
+ detector.forceState(MotionState.MOVING)
+ assertEquals(0, callCount)
+ }
+
+ @Test
+ fun `stop drops any pending transition posts so late deliveries no-op`() {
+ // Capture posts instead of running them synchronously to simulate the async race:
+ // transition queued -> stop() -> post drains later.
+ val pending = mutableListOf<Runnable>()
+ every { anyConstructed<Handler>().post(any()) } answers {
+ pending += firstArg<Runnable>()
+ true
+ }
+
+ val detector = makeDetector()
+ var received: MotionState? = null
+ detector.start { received = it }
+
+ detector.forceState(MotionState.STATIONARY)
+ assertEquals(1, pending.size)
+
+ detector.stop()
+
+ // Drain the post that was queued before stop() ran. The defensive null-check
+ // in the posted lambda should make it a no-op now that listener is null.
+ pending.forEach { it.run() }
+ assertNull(received)
+ }
+
+ @Test
+ fun `stop cancels pending callbacks on the main handler`() {
+ val detector = makeDetector()
+ detector.start { /* no-op */ }
+ detector.stop()
+ verify { anyConstructed<Handler>().removeCallbacksAndMessages(null) }
+ }
+
+ // ── Algorithm: variance + hysteresis ──────────────────────────────────
+ //
+ // Timing notes for these tests:
+ // - variance is first computed when the deque holds >= MIN_SAMPLES_FOR_VARIANCE (8)
+ // - the threshold timestamp (`above`/`belowThresholdSinceMs`) is set on that first
+ // variance-computed sample, so a dwell of D ms requires extending the loop past
+ // `firstComputedSampleMs + D`
+ // - sliding variance window is 60s; tests that need to keep the deque populated
+ // sample at <= 1Hz to stay inside the window
+
+ @Test
+ fun `variance not computed below MIN_SAMPLES_FOR_VARIANCE`() {
+ val received = mutableListOf<MotionState>()
+ val detector = makeDetector()
+ detector.start { received += it }
+
+ // 7 samples < MIN_SAMPLES_FOR_VARIANCE (8). State stays at initial MOVING;
+ // no STATIONARY transition because variance was never evaluated.
+ var t = 0L
+ repeat(7) {
+ feedSample(magnitude = 0.0, atMs = t)
+ t += 1000L
+ }
+ assertTrue(received.isEmpty())
+ }
+
+ @Test
+ fun `low variance for full dwell transitions MOVING to STATIONARY`() {
+ val received = mutableListOf<MotionState>()
+ val detector = makeDetector()
+ detector.start { received += it }
+
+ // Constant magnitude -> variance = 0 < STATIONARY threshold (0.15).
+ // 8th sample lands at t=7000 -> belowThresholdSinceMs = 7000.
+ // Default dwell = 60_000ms -> transition fires at t >= 67000.
+ var t = 0L
+ while (t <= 68_000L) {
+ feedSample(magnitude = 0.0, atMs = t)
+ t += 1000L
+ }
+
+ assertEquals(listOf(MotionState.STATIONARY), received)
+ }
+
+ @Test
+ fun `low variance for less than dwell does not transition`() {
+ val received = mutableListOf<MotionState>()
+ val detector = makeDetector()
+ detector.start { received += it }
+
+ // 30s of low variance - half the default dwell. No transition.
+ var t = 0L
+ while (t <= 30_000L) {
+ feedSample(magnitude = 0.0, atMs = t)
+ t += 1000L
+ }
+
+ assertTrue(received.isEmpty())
+ }
+
+ @Test
+ fun `high variance for MOVING_DWELL transitions STATIONARY to MOVING`() {
+ val received = mutableListOf<MotionState>()
+ val detector = makeDetector()
+ detector.start { received += it }
+ detector.forceState(MotionState.STATIONARY)
+ received.clear()
+
+ // Alternating ±0.6 -> variance = 0.36 > MOVING threshold (0.30).
+ // 8th sample lands at t=700 -> aboveThresholdSinceMs = 700.
+ // MOVING_DWELL = 3_000ms -> transition fires at t >= 3700.
+ var t = 0L
+ var hi = true
+ while (t <= 4_000L) {
+ feedSample(magnitude = if (hi) 0.6 else -0.6, atMs = t)
+ hi = !hi
+ t += 100L
+ }
+
+ assertEquals(listOf(MotionState.MOVING), received)
+ }
+
+ @Test
+ fun `ambiguous-band variance does not transition either way`() {
+ val received = mutableListOf<MotionState>()
+ // Short 5s dwell so the test would clearly transition if ambiguous samples
+ // were treated as low-variance.
+ val detector = makeDetector(stationaryDwellMs = 5_000L)
+ detector.start { received += it }
+
+ // Alternating ±0.45 -> variance = 0.2025, sits between STATIONARY (0.15)
+ // and MOVING (0.30) thresholds. Sustained for 10s (twice the dwell).
+ var t = 0L
+ var hi = true
+ while (t <= 10_000L) {
+ feedSample(magnitude = if (hi) 0.45 else -0.45, atMs = t)
+ hi = !hi
+ t += 200L
+ }
+
+ assertTrue(received.isEmpty())
+ }
+
+ @Test
+ fun `SIG_MOTION trigger transitions STATIONARY to MOVING immediately`() {
+ val received = mutableListOf<MotionState>()
+ val detector = makeDetector()
+ detector.start { received += it }
+ detector.forceState(MotionState.STATIONARY)
+ received.clear()
+
+ sigListenerSlot.captured.onTrigger(mockk<TriggerEvent>(relaxed = true))
+
+ assertEquals(listOf(MotionState.MOVING), received)
+ }
+
+ @Test
+ fun `SIG_MOTION re-arms itself after firing`() {
+ val detector = makeDetector()
+ detector.start { /* no-op */ }
+
+ sigListenerSlot.captured.onTrigger(mockk<TriggerEvent>(relaxed = true))
+
+ // Initial registration in start() + re-arm inside onTrigger().
+ verify(exactly = 2) { sensorManager.requestTriggerSensor(any(), sigMotionSensor) }
+ }
+
+ @Test
+ fun `per-zone dwell override is honored`() {
+ val received = mutableListOf<MotionState>()
+ // Override default 60s with a 5s dwell - simulates a zone with motionlessTimeoutMinutes
+ // set very low. 8th sample at t=700 -> transition fires at t >= 5700.
+ val detector = makeDetector(stationaryDwellMs = 5_000L)
+ detector.start { received += it }
+
+ var t = 0L
+ while (t <= 6_000L) {
+ feedSample(magnitude = 0.0, atMs = t)
+ t += 100L
+ }
+
+ assertEquals(listOf(MotionState.STATIONARY), received)
+ }
+}
diff --git a/apps/mobile/src/screens/GeofenceEditorScreen.tsx b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
index 52ddb289..d52cb6b4 100644
--- a/apps/mobile/src/screens/GeofenceEditorScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
@@ -37,7 +37,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
const [pauseTracking, setPauseTracking] = useState(true)
const [pauseOnWifi, setPauseOnWifi] = useState(false)
const [pauseOnMotionless, setPauseOnMotionless] = useState(false)
- const [motionlessTimeoutStr, setMotionlessTimeoutStr] = useState("10")
+ const [motionlessTimeoutStr, setMotionlessTimeoutStr] = useState("1")
const [heartbeatEnabled, setHeartbeatEnabled] = useState(false)
const [heartbeatIntervalStr, setHeartbeatIntervalStr] = useState("15")
const [saving, setSaving] = useState(false)
@@ -48,7 +48,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutStr: "10",
+ motionlessTimeoutStr: "1",
heartbeatEnabled: false,
heartbeatIntervalStr: "15"
})
@@ -289,7 +289,7 @@ export function GeofenceEditorScreen({ navigation, route }: RootScreenProps<"Geo
style={[inputStyle, styles.numInput]}
value={motionlessTimeoutStr}
onChangeText={setMotionlessTimeoutStr}
- placeholder="10"
+ placeholder="1"
placeholderTextColor={colors.placeholder}
keyboardType="number-pad"
/>
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 3000de4c..902dd989 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -193,7 +193,7 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10,
+ motionlessTimeoutMinutes: 1,
heartbeatEnabled: false,
heartbeatIntervalMinutes: 15
})