Skip to content

Colota - Android GPS Location tracker

feat: add stationary heartbeat for geofence pause zones

Max Dietrich868966d6b639
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index acba9baf..751e1c4b 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -141,6 +141,8 @@ Each geofence supports three independent GPS pause modes, configured per zone:
- **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.
+A per-zone **stationary heartbeat** can send periodic location updates while paused. It requests a fresh GPS fix, sends it immediately (bypassing sync conditions) and powers GPS back down. Configured via `heartbeatEnabled` and `heartbeatIntervalMinutes` per geofence.
+
When both WiFi and motionless pause are enabled, GPS only resumes when both conditions clear - WiFi disconnected **and** motion detected. Changes made in the editor take effect immediately even when already inside the zone, via `applyZoneSettingsIfChanged` on the next zone recheck.
### ProfileManager
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 0ae26aa0..4790ce01 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -39,6 +39,10 @@ Stops GPS entirely when connected to an unmetered network (home WiFi, Ethernet).
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.
+### Stationary heartbeat
+
+Sends a periodic location update to your server while paused inside the zone. Useful as a proof-of-presence signal so your backend knows the device is still there. The heartbeat requests a fresh GPS fix, sends it immediately (bypassing normal sync conditions like Wi-Fi only) and then powers GPS back down. Configure the interval in minutes (default 15).
+
### Combined behavior
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.
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 24c33453..38b5baa1 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -35,7 +35,7 @@ Colota has eighteen screens, each focused on a specific task:
| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |
| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |
| **Geofences** | Create pause zones by tapping the map, view all zones with pause option indicators |
-| **Geofence Editor** | Configure pause options per zone: record pause, WiFi pause, motionless pause, and delete |
+| **Geofence Editor** | Configure pause options per zone: record pause, WiFi pause, motionless pause, stationary heartbeat and delete |
| **Offline Maps** | Download map areas to the device for use without an internet connection |
| **Tracking Profiles** | Create and manage condition-based profiles that automatically adjust tracking settings |
| **Profile Editor** | Configure profile name, condition trigger, GPS interval, distance filter, sync interval, priority, and deactivation delay |
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 8ed86441..c93e0ee9 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -30,7 +30,7 @@ The App also collects:
### Geofence Data
-If you create pause zones (geofences), the App stores zone names, coordinates, radii and per-zone settings (enabled state, tracking pause, WiFi pause, motionless pause, motionless timeout and entry/exit notifications) in the local database.
+If you create pause zones (geofences), the App stores zone names, coordinates, radii and per-zone settings (enabled state, tracking pause, WiFi pause, motionless pause, motionless timeout, heartbeat enabled, heartbeat interval and entry/exit notifications) in the local database.
### Condition Monitoring
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 6d5488be..cfb71f28 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -629,9 +629,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
pauseOnWifi: Boolean,
pauseOnMotionless: Boolean,
motionlessTimeoutMinutes: Int,
+ heartbeatEnabled: Boolean,
+ heartbeatIntervalMinutes: Int,
promise: Promise
) = executeAsync(promise) {
- val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)
+ val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes, heartbeatEnabled, heartbeatIntervalMinutes)
if (result > 0) {
geofenceHelper.invalidateCache()
triggerZoneRecheck()
@@ -660,9 +662,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
pauseOnWifi: Boolean?,
pauseOnMotionless: Boolean?,
motionlessTimeoutMinutes: Int?,
+ heartbeatEnabled: Boolean?,
+ heartbeatIntervalMinutes: Int?,
promise: Promise
) = executeAsync(promise) {
- val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes)
+ val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes, heartbeatEnabled, heartbeatIntervalMinutes)
if (result) {
geofenceHelper.invalidateCache()
triggerZoneRecheck()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index a7f32c53..5c248951 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -32,7 +32,7 @@ class DatabaseHelper private constructor(context: Context) :
companion object {
private const val DATABASE_NAME = "Colota.db"
- private const val DATABASE_VERSION = 4
+ private const val DATABASE_VERSION = 5
const val TABLE_LOCATIONS = "locations"
const val TABLE_QUEUE = "queue"
@@ -118,6 +118,8 @@ class DatabaseHelper private constructor(context: Context) :
pause_on_wifi INTEGER DEFAULT 0,
pause_on_motionless INTEGER DEFAULT 0,
motionless_timeout_minutes INTEGER DEFAULT 10,
+ heartbeat_enabled INTEGER DEFAULT 0,
+ heartbeat_interval_minutes INTEGER DEFAULT 15,
notify_enter INTEGER DEFAULT 0,
notify_exit INTEGER DEFAULT 0,
created_at INTEGER NOT NULL
@@ -226,6 +228,10 @@ class DatabaseHelper private constructor(context: Context) :
db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_motionless INTEGER NOT NULL DEFAULT 0")
db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN motionless_timeout_minutes INTEGER NOT NULL DEFAULT 10")
}
+ if (oldVersion < 5) {
+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_enabled INTEGER NOT NULL DEFAULT 0")
+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_interval_minutes INTEGER NOT NULL DEFAULT 15")
+ }
}
override fun onOpen(db: SQLiteDatabase) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
index 63355477..8cd5f698 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
@@ -27,7 +27,9 @@ class GeofenceHelper(private val context: Context) {
val radius: Double,
val pauseOnWifi: Boolean = false,
val pauseOnMotionless: Boolean = false,
- val motionlessTimeoutMinutes: Int = 10
+ val motionlessTimeoutMinutes: Int = 10,
+ val heartbeatEnabled: Boolean = false,
+ val heartbeatIntervalMinutes: Int = 15
)
companion object {
@@ -79,7 +81,7 @@ class GeofenceHelper(private val context: Context) {
val fences = mutableListOf<CachedGeofence>()
dbHelper.readableDatabase.query(
DatabaseHelper.TABLE_GEOFENCES,
- arrayOf("name", "latitude", "longitude", "radius", "pause_on_wifi", "pause_on_motionless", "motionless_timeout_minutes"),
+ arrayOf("name", "latitude", "longitude", "radius", "pause_on_wifi", "pause_on_motionless", "motionless_timeout_minutes", "heartbeat_enabled", "heartbeat_interval_minutes"),
"enabled = 1 AND pause_tracking = 1",
null, null, null, null
).use { cursor ->
@@ -90,6 +92,8 @@ class GeofenceHelper(private val context: Context) {
val wifiIdx = cursor.getColumnIndexOrThrow("pause_on_wifi")
val motionlessIdx = cursor.getColumnIndexOrThrow("pause_on_motionless")
val timeoutIdx = cursor.getColumnIndexOrThrow("motionless_timeout_minutes")
+ val heartbeatIdx = cursor.getColumnIndexOrThrow("heartbeat_enabled")
+ val heartbeatIntervalIdx = cursor.getColumnIndexOrThrow("heartbeat_interval_minutes")
while (cursor.moveToNext()) {
fences.add(CachedGeofence(
@@ -99,7 +103,9 @@ class GeofenceHelper(private val context: Context) {
cursor.getDouble(radIdx),
cursor.getInt(wifiIdx) == 1,
cursor.getInt(motionlessIdx) == 1,
- cursor.getInt(timeoutIdx)
+ cursor.getInt(timeoutIdx),
+ cursor.getInt(heartbeatIdx) == 1,
+ cursor.getInt(heartbeatIntervalIdx)
))
}
}
@@ -141,6 +147,8 @@ class GeofenceHelper(private val context: Context) {
putBoolean("pauseOnWifi", cursor.getInt(cursor.getColumnIndexOrThrow("pause_on_wifi")) == 1)
putBoolean("pauseOnMotionless", cursor.getInt(cursor.getColumnIndexOrThrow("pause_on_motionless")) == 1)
putInt("motionlessTimeoutMinutes", cursor.getInt(cursor.getColumnIndexOrThrow("motionless_timeout_minutes")))
+ putBoolean("heartbeatEnabled", cursor.getInt(cursor.getColumnIndexOrThrow("heartbeat_enabled")) == 1)
+ putInt("heartbeatIntervalMinutes", cursor.getInt(cursor.getColumnIndexOrThrow("heartbeat_interval_minutes")))
putDouble("createdAt", cursor.getLong(createdIdx).toDouble())
})
}
@@ -163,7 +171,9 @@ class GeofenceHelper(private val context: Context) {
pause: Boolean,
pauseOnWifi: Boolean = false,
pauseOnMotionless: Boolean = false,
- motionlessTimeoutMinutes: Int = 10
+ motionlessTimeoutMinutes: Int = 10,
+ heartbeatEnabled: Boolean = false,
+ heartbeatIntervalMinutes: Int = 15
): Int {
val values = ContentValues().apply {
put("name", name)
@@ -175,6 +185,8 @@ class GeofenceHelper(private val context: Context) {
put("pause_on_wifi", if (pauseOnWifi) 1 else 0)
put("pause_on_motionless", if (pauseOnMotionless) 1 else 0)
put("motionless_timeout_minutes", motionlessTimeoutMinutes)
+ put("heartbeat_enabled", if (heartbeatEnabled) 1 else 0)
+ put("heartbeat_interval_minutes", heartbeatIntervalMinutes)
put("created_at", System.currentTimeMillis() / 1000)
}
@@ -196,7 +208,9 @@ class GeofenceHelper(private val context: Context) {
pause: Boolean?,
pauseOnWifi: Boolean? = null,
pauseOnMotionless: Boolean? = null,
- motionlessTimeoutMinutes: Int? = null
+ motionlessTimeoutMinutes: Int? = null,
+ heartbeatEnabled: Boolean? = null,
+ heartbeatIntervalMinutes: Int? = null
): Boolean {
val values = ContentValues().apply {
name?.let { put("name", it) }
@@ -208,6 +222,8 @@ class GeofenceHelper(private val context: Context) {
pauseOnWifi?.let { put("pause_on_wifi", if (it) 1 else 0) }
pauseOnMotionless?.let { put("pause_on_motionless", if (it) 1 else 0) }
motionlessTimeoutMinutes?.let { put("motionless_timeout_minutes", it) }
+ heartbeatEnabled?.let { put("heartbeat_enabled", if (it) 1 else 0) }
+ heartbeatIntervalMinutes?.let { put("heartbeat_interval_minutes", it) }
}
if (values.size() == 0) return false
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 bb7ecf4d..7641d0d4 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
@@ -28,6 +28,7 @@ import com.Colota.location.LocationProvider
import com.Colota.location.LocationProviderFactory
import com.Colota.location.LocationUpdateCallback
import kotlinx.coroutines.*
+import kotlin.coroutines.resume
import java.util.Locale
/** Foreground service for continuous GPS tracking and location syncing. */
@@ -64,6 +65,7 @@ class LocationForegroundService : Service() {
@Volatile private var lastKnownLocation: android.location.Location? = null
@Volatile private var entryDelayJob: Job? = null
@Volatile private var pendingPauseZone: GeofenceHelper.CachedGeofence? = null
+ @Volatile private var heartbeatJob: Job? = null
@Volatile private lateinit var config: ServiceConfig
@Volatile private var fieldMap: Map<String, String>? = null
@@ -168,6 +170,10 @@ class LocationForegroundService : Service() {
motionDetector?.arm()
AppLogger.d(TAG, "Restored motionless pause state")
}
+ if (restoredGeofence?.heartbeatEnabled == true) {
+ startHeartbeat(restoredGeofence.heartbeatIntervalMinutes)
+ AppLogger.d(TAG, "Restored heartbeat: ${restoredGeofence.heartbeatIntervalMinutes}min")
+ }
}
}
@@ -258,6 +264,7 @@ class LocationForegroundService : Service() {
pendingPauseZone = null
unregisterWifiPause()
cancelMotionlessCountdown()
+ cancelHeartbeat()
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -371,6 +378,12 @@ class LocationForegroundService : Service() {
zoneName = currentZoneName,
forceUpdate = true
)
+ val reason = when {
+ isWifiPaused -> "wifi"
+ isMotionlessPaused -> "motionless"
+ else -> null
+ }
+ LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, reason)
return
}
@@ -391,6 +404,7 @@ class LocationForegroundService : Service() {
*/
private fun applyZoneSettingsIfChanged(zone: GeofenceHelper.CachedGeofence) {
val timeoutChanged = currentZoneGeofence?.motionlessTimeoutMinutes != zone.motionlessTimeoutMinutes
+ val heartbeatChanged = currentZoneGeofence?.heartbeatIntervalMinutes != zone.heartbeatIntervalMinutes
currentZoneGeofence = zone
if (zone.pauseOnWifi && wifiCallback == null) {
@@ -413,6 +427,12 @@ class LocationForegroundService : Service() {
maybeResumeGps()
}
}
+
+ if (zone.heartbeatEnabled && (heartbeatJob == null || heartbeatChanged)) {
+ startHeartbeat(zone.heartbeatIntervalMinutes)
+ } else if (!zone.heartbeatEnabled) {
+ cancelHeartbeat()
+ }
}
/**
@@ -597,6 +617,7 @@ class LocationForegroundService : Service() {
if (geofence.pauseOnWifi) registerWifiPause()
if (geofence.pauseOnMotionless) startMotionlessCountdown(geofence.motionlessTimeoutMinutes)
+ if (geofence.heartbeatEnabled) startHeartbeat(geofence.heartbeatIntervalMinutes)
profileManager.clearSpeedBuffer()
@@ -621,6 +642,7 @@ class LocationForegroundService : Service() {
unregisterWifiPause()
cancelMotionlessCountdown()
clearMotionlessPauseState()
+ cancelHeartbeat()
val anchorJob = exitedGeofence?.let { saveAnchorPoint(it) }
@@ -745,6 +767,107 @@ class LocationForegroundService : Service() {
if (!profileManager.isStationary) motionDetector?.disarm()
}
+ /**
+ * Starts a periodic heartbeat that sends a location update to the server
+ * at a relaxed interval while paused in a geofence zone.
+ */
+ private fun startHeartbeat(intervalMinutes: Int) {
+ heartbeatJob?.cancel()
+ AppLogger.d(TAG, "Heartbeat started: ${intervalMinutes}min interval")
+ heartbeatJob = serviceScope?.launch {
+ while (isActive && insidePauseZone) {
+ delay(intervalMinutes * 60_000L)
+ if (!insidePauseZone) break
+ sendHeartbeatLocation()
+ }
+ }
+ }
+
+ private fun cancelHeartbeat() {
+ heartbeatJob?.cancel()
+ heartbeatJob = null
+ }
+
+ /**
+ * Requests a single fresh GPS fix with a 30-second timeout.
+ * Falls back to [lastKnownLocation] if no fix arrives in time.
+ */
+ private suspend fun requestFreshLocation(): android.location.Location? =
+ withTimeoutOrNull(30_000L) {
+ suspendCancellableCoroutine { cont ->
+ val callback = object : LocationUpdateCallback {
+ override fun onLocationUpdate(location: android.location.Location) {
+ locationProvider.removeLocationUpdates(this)
+ if (cont.isActive) cont.resume(location)
+ }
+ }
+ cont.invokeOnCancellation { locationProvider.removeLocationUpdates(callback) }
+ locationProvider.requestLocationUpdates(
+ intervalMs = 1000L,
+ minDistanceMeters = 0f,
+ looper = android.os.Looper.getMainLooper(),
+ callback = callback
+ )
+ }
+ }
+
+ private suspend fun sendHeartbeatLocation() {
+ if (config.endpoint.isBlank() || !networkManager.isNetworkAvailable()) {
+ AppLogger.d(TAG, "Heartbeat skipped: no endpoint or no network")
+ return
+ }
+
+ val location = withContext(Dispatchers.Main) { requestFreshLocation() } ?: lastKnownLocation
+
+ if (location == null) {
+ AppLogger.d(TAG, "Heartbeat skipped: no location available")
+ return
+ }
+
+ lastKnownLocation = location
+
+ val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
+ val timestampSec = System.currentTimeMillis() / 1000
+ val currentFieldMap = fieldMap ?: emptyMap()
+
+ val payload = payloadBuilder.buildPayload(
+ location,
+ battery,
+ batteryStatus,
+ if (config.apiFormat == NetworkManager.FORMAT_TRACCAR_JSON) emptyMap() else currentFieldMap,
+ timestampSec,
+ customFields
+ )
+
+ // Send immediately regardless of sync condition - the whole point of
+ // a heartbeat is keeping the device visible on the server.
+ val sent = networkManager.sendToEndpoint(
+ payload, config.endpoint, secureStorage.getAuthHeaders(),
+ config.httpMethod, config.apiFormat
+ )
+
+ if (sent) {
+ // Only persist to DB on successful send
+ val locationId = dbHelper.saveLocation(
+ latitude = location.latitude,
+ longitude = location.longitude,
+ accuracy = location.accuracy.toDouble(),
+ altitude = if (location.hasAltitude()) location.altitude.toInt() else null,
+ speed = 0.0,
+ bearing = 0.0,
+ battery = battery,
+ battery_status = batteryStatus,
+ timestamp = timestampSec,
+ endpoint = config.endpoint
+ )
+ dbHelper.markLocationSent(locationId)
+ LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
+ AppLogger.d(TAG, "Heartbeat sent: lat=${location.latitude}, lon=${location.longitude}")
+ } else {
+ AppLogger.d(TAG, "Heartbeat failed: server unreachable, will retry next cycle")
+ }
+ }
+
/**
* 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.
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 3ff5fb70..2b956ef0 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
@@ -90,6 +90,7 @@ class LocationForegroundServiceTest {
mockkObject(LocationServiceModule)
every { LocationServiceModule.sendLocationEvent(any(), any(), any()) } returns true
every { LocationServiceModule.sendPauseZoneEvent(any(), any()) } returns true
+ every { LocationServiceModule.sendPauseZoneEvent(any(), any(), any()) } returns true
every { LocationServiceModule.sendTrackingStoppedEvent(any()) } returns true
every { LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true
@@ -949,6 +950,56 @@ class LocationForegroundServiceTest {
activeProfileName = any(),
forceUpdate = true
) }
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", null) }
+ }
+
+ @Test
+ fun `recheckZone sends wifi pause reason when wifi paused in same zone`() {
+ val wifiGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", wifiGeofence)
+ setField("isWifiPaused", true)
+ setField("wifiCallback", mockk<android.net.ConnectivityManager.NetworkCallback>(relaxed = true))
+ val location = mockLocation(lat = 52.0, lon = 13.0)
+ every { geofenceHelper.getPauseZone(location) } returns wifiGeofence
+
+ invokeRecheckZoneWithLocation(location)
+
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", "wifi") }
+ }
+
+ @Test
+ fun `recheckZone sends motionless pause reason when motionless paused in same zone`() {
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", motionlessGeofence)
+ setField("isMotionlessPaused", true)
+ val location = mockLocation(lat = 52.0, lon = 13.0)
+ every { geofenceHelper.getPauseZone(location) } returns motionlessGeofence
+
+ invokeRecheckZoneWithLocation(location)
+
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", "motionless") }
+ }
+
+ @Test
+ fun `recheckZone sends wifi reason when both wifi and motionless paused`() {
+ val bothGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnWifi = true, pauseOnMotionless = true)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", bothGeofence)
+ 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
+
+ invokeRecheckZoneWithLocation(location)
+
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", "wifi") }
}
@Test
diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
index 6d067f77..236c46cc 100644
--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
@@ -254,7 +254,9 @@ describe("buildGeofencesGeoJSON", () => {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
}
it("returns empty collections for no geofences", () => {
diff --git a/apps/mobile/src/screens/GeofenceEditorScreen.tsx b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
index 9fddb3da..b878db6e 100644
--- a/apps/mobile/src/screens/GeofenceEditorScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
@@ -28,6 +28,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
const [pauseOnMotionless, setPauseOnMotionless] = useState(false)
const [motionlessTimeoutMinutes, setMotionlessTimeoutMinutes] = useState(10)
const [motionlessTimeoutStr, setMotionlessTimeoutStr] = useState("10")
+ const [heartbeatEnabled, setHeartbeatEnabled] = useState(false)
+ const [heartbeatIntervalMinutes, setHeartbeatIntervalMinutes] = useState(15)
+ const [heartbeatIntervalStr, setHeartbeatIntervalStr] = useState("15")
const [saving, setSaving] = useState(false)
const savedState = useRef({
@@ -36,7 +39,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
})
const hasChanges = useMemo(() => {
@@ -47,9 +52,20 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking !== s.pauseTracking ||
pauseOnWifi !== s.pauseOnWifi ||
pauseOnMotionless !== s.pauseOnMotionless ||
- motionlessTimeoutMinutes !== s.motionlessTimeoutMinutes
+ motionlessTimeoutMinutes !== s.motionlessTimeoutMinutes ||
+ heartbeatEnabled !== s.heartbeatEnabled ||
+ heartbeatIntervalMinutes !== s.heartbeatIntervalMinutes
)
- }, [name, radius, pauseTracking, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes])
+ }, [
+ name,
+ radius,
+ pauseTracking,
+ pauseOnWifi,
+ pauseOnMotionless,
+ motionlessTimeoutMinutes,
+ heartbeatEnabled,
+ heartbeatIntervalMinutes
+ ])
useEffect(() => {
if (!geofenceId) return
@@ -66,13 +82,18 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
setPauseOnMotionless(existing.pauseOnMotionless)
setMotionlessTimeoutMinutes(existing.motionlessTimeoutMinutes)
setMotionlessTimeoutStr(String(existing.motionlessTimeoutMinutes))
+ setHeartbeatEnabled(existing.heartbeatEnabled ?? false)
+ setHeartbeatIntervalMinutes(existing.heartbeatIntervalMinutes ?? 15)
+ setHeartbeatIntervalStr(String(existing.heartbeatIntervalMinutes ?? 15))
savedState.current = {
name: existing.name,
radius: existing.radius,
pauseTracking: existing.pauseTracking,
pauseOnWifi: existing.pauseOnWifi,
pauseOnMotionless: existing.pauseOnMotionless,
- motionlessTimeoutMinutes: existing.motionlessTimeoutMinutes
+ motionlessTimeoutMinutes: existing.motionlessTimeoutMinutes,
+ heartbeatEnabled: existing.heartbeatEnabled ?? false,
+ heartbeatIntervalMinutes: existing.heartbeatIntervalMinutes ?? 15
}
}
})
@@ -95,6 +116,12 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
if (!isNaN(num) && num >= 1) setMotionlessTimeoutMinutes(num)
}, [])
+ const handleHeartbeatIntervalChange = useCallback((val: string) => {
+ setHeartbeatIntervalStr(val)
+ const num = parseInt(val, 10)
+ if (!isNaN(num) && num >= 1) setHeartbeatIntervalMinutes(num)
+ }, [])
+
const handleSave = useCallback(async () => {
if (!name.trim()) {
showAlert("Missing Name", "Please enter a name.", "warning")
@@ -115,7 +142,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes
+ motionlessTimeoutMinutes,
+ heartbeatEnabled,
+ heartbeatIntervalMinutes
})
} else {
const lat = route?.params?.lat as number
@@ -129,7 +158,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes
+ motionlessTimeoutMinutes,
+ heartbeatEnabled,
+ heartbeatIntervalMinutes
})
}
DeviceEventEmitter.emit("geofenceUpdated")
@@ -147,6 +178,8 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseOnWifi,
pauseOnMotionless,
motionlessTimeoutMinutes,
+ heartbeatEnabled,
+ heartbeatIntervalMinutes,
isEditing,
geofenceId,
navigation,
@@ -238,20 +271,51 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
</SettingRow>
{pauseOnMotionless && (
- <SettingRow
- label="Motionless timeout (min)"
- hint="GPS pauses after this many minutes without motion. Resumes automatically when the device moves again."
- >
- <TextInput
- testID="motionless-timeout-input"
- style={[inputStyle, styles.numInput]}
- value={motionlessTimeoutStr}
- onChangeText={handleTimeoutChange}
- placeholder="10"
- placeholderTextColor={colors.placeholder}
- keyboardType="numeric"
- />
- </SettingRow>
+ <View style={[styles.nestedSetting, { borderLeftColor: colors.border }]}>
+ <SettingRow
+ label="Motionless timeout (min)"
+ hint="GPS pauses after this many minutes without motion. Resumes automatically when the device moves again."
+ >
+ <TextInput
+ testID="motionless-timeout-input"
+ style={[inputStyle, styles.numInput]}
+ value={motionlessTimeoutStr}
+ onChangeText={handleTimeoutChange}
+ placeholder="10"
+ placeholderTextColor={colors.placeholder}
+ keyboardType="numeric"
+ />
+ </SettingRow>
+ </View>
+ )}
+
+ <SettingRow
+ label="Stationary heartbeat"
+ hint="Send periodic location updates to the server while paused in this zone"
+ >
+ <Switch
+ testID="heartbeat-toggle"
+ value={heartbeatEnabled}
+ onValueChange={setHeartbeatEnabled}
+ trackColor={{ false: colors.border, true: colors.primary + "80" }}
+ thumbColor={heartbeatEnabled ? colors.primary : colors.border}
+ />
+ </SettingRow>
+
+ {heartbeatEnabled && (
+ <View style={[styles.nestedSetting, { borderLeftColor: colors.border }]}>
+ <SettingRow label="Heartbeat interval (min)" hint="How often to send a location update to the server">
+ <TextInput
+ testID="heartbeat-interval-input"
+ style={[inputStyle, styles.numInput]}
+ value={heartbeatIntervalStr}
+ onChangeText={handleHeartbeatIntervalChange}
+ placeholder="15"
+ placeholderTextColor={colors.placeholder}
+ keyboardType="numeric"
+ />
+ </SettingRow>
+ </View>
)}
{pauseOnWifi && pauseOnMotionless && (
@@ -286,6 +350,7 @@ const styles = StyleSheet.create({
},
nameInput: { flex: 1 },
numInput: { width: 80, textAlign: "center" },
+ nestedSetting: { marginLeft: 16, paddingLeft: 12, borderLeftWidth: 3 },
combinedNote: {
marginTop: 8,
paddingTop: 12,
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 602651c9..8dd38a07 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -129,7 +129,9 @@ export function GeofenceScreen({ navigation }: ScreenProps) {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
})
await loadGeofences()
DeviceEventEmitter.emit("geofenceUpdated")
diff --git a/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
index 4ef3bfe7..84acb7e3 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceEditorScreen.test.tsx
@@ -108,7 +108,9 @@ const mockExistingGeofence: Geofence = {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
}
import { GeofenceEditorScreen } from "../GeofenceEditorScreen"
diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
index a59a7d78..b6c386bf 100644
--- a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx
@@ -173,7 +173,9 @@ const mockGeofences: Geofence[] = [
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
},
{
id: 2,
@@ -185,7 +187,9 @@ const mockGeofences: Geofence[] = [
pauseTracking: false,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
}
]
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index f9746f75..e5677218 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -295,7 +295,9 @@ class NativeLocationService {
geofence.pauseTracking,
geofence.pauseOnWifi ?? false,
geofence.pauseOnMotionless ?? false,
- geofence.motionlessTimeoutMinutes ?? 10
+ geofence.motionlessTimeoutMinutes ?? 10,
+ geofence.heartbeatEnabled ?? false,
+ geofence.heartbeatIntervalMinutes ?? 15
)
}
@@ -320,7 +322,9 @@ class NativeLocationService {
update.pauseTracking ?? null,
update.pauseOnWifi ?? null,
update.pauseOnMotionless ?? null,
- update.motionlessTimeoutMinutes ?? null
+ update.motionlessTimeoutMinutes ?? null,
+ update.heartbeatEnabled ?? null,
+ update.heartbeatIntervalMinutes ?? null
)
}
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index 5ab5c3b1..e3fa87d6 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -297,10 +297,12 @@ describe("NativeLocationService", () => {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10
+ motionlessTimeoutMinutes: 10,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
})
- expect(nativeMock.createGeofence).toHaveBeenCalledWith("Home", 48.1, 11.5, 100, true, false, false, 10)
+ expect(nativeMock.createGeofence).toHaveBeenCalledWith("Home", 48.1, 11.5, 100, true, false, false, 10, false, 15)
})
it("deleteGeofence passes id", async () => {
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index b9a0d9ba..928ebe50 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -41,6 +41,8 @@ export interface Geofence {
pauseOnWifi: boolean
pauseOnMotionless: boolean
motionlessTimeoutMinutes: number
+ heartbeatEnabled: boolean
+ heartbeatIntervalMinutes: number
createdAt?: number
}