Skip to content

Colota - Android GPS Location tracker

fix: stationary heartbeat reliability and geofence editor UX (#284)

Max Dietrich4663ae4baf86
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 957cb128..0781751b 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -133,7 +133,7 @@ HTTP client. Validates endpoints, enforces HTTPS for public hosts, injects auth
### GeofenceHelper
-Manages pause zones using the **haversine formula** for distance calculations. Maintains an in-memory cache of geofences that invalidates on CRUD changes.
+Manages pause zones using the **haversine formula** for distance calculations. Reads geofences directly from SQLite on each lookup.
Each geofence supports three independent GPS pause modes, configured per zone:
@@ -175,7 +175,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A
| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |
| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |
| `ServiceConfig` | Centralized configuration data class |
-| `TimedCache` | Generic TTL cache used for queue count, device info, geofences, profiles, and network state |
+| `TimedCache` | Generic TTL cache used for queue count, device info, profiles, and network state |
| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |
| `AppLogger` | Centralized logger - always active, all tags prefixed with `Colota.` for logcat filtering |
| `AutoExportWorker` | WorkManager `CoroutineWorker` for scheduled exports - checks `AutoExportConfig.isExportDue()` on each run, streams chunked writes, verifies output, and cleans up old files beyond retention limit |
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 7ae88b79..6c7083bc 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -43,7 +43,7 @@ Stops GPS after no device motion is detected for a configurable time (default 10
### 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 sends the geofence center as a synthetic anchor point (no GPS wake), bypassing normal sync conditions like Wi-Fi only. Configure the interval in minutes (default 15).
+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 sends the geofence center as a synthetic anchor point (no GPS wake), bypassing normal sync conditions like Wi-Fi only. The first heartbeat fires immediately on zone entry, then repeats at the configured interval. Minimum 1 minute, default 15.
### Combined behavior
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 963de040..93e87fed 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
@@ -379,10 +379,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- /** Invalidates the geofence cache and asks the service to re-evaluate pause zones so the change takes effect immediately. */
+ /** Asks the service to re-evaluate pause zones so the geofence change takes effect immediately. */
private fun afterGeofenceMutation(changed: Boolean) {
if (!changed) return
- geofenceHelper.invalidateCache()
triggerZoneRecheck()
}
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 57965389..ed86dccd 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
@@ -9,7 +9,6 @@ import android.content.ContentValues
import android.content.Context
import android.location.Location
import com.Colota.util.AppLogger
-import com.Colota.util.TimedCache
import com.Colota.util.geo.haversineDistance
import com.Colota.util.geo.isWithinRadius
import com.facebook.react.bridge.Arguments
@@ -19,8 +18,6 @@ class GeofenceHelper(private val context: Context) {
private val dbHelper by lazy { DatabaseHelper.getInstance(context) }
- private val geofenceCache = TimedCache(CACHE_TTL_MS) { loadGeofencesFromDB() }
-
/** Runtime view of an enabled pause-tracking geofence (what the service reads). */
data class CachedGeofence(
val name: String,
@@ -36,15 +33,13 @@ class GeofenceHelper(private val context: Context) {
companion object {
private const val TAG = "GeofenceHelper"
- private const val CACHE_TTL_MS = 30_000L
}
fun getGeofenceByName(name: String): CachedGeofence? =
- geofenceCache.get().find { it.name == name }
+ loadGeofencesFromDB().find { it.name == name }
fun getPauseZone(location: Location): CachedGeofence? {
- val fences = getGeofences()
- val match = fences.find {
+ val match = loadGeofencesFromDB().find {
isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)
}
if (match != null) {
@@ -54,13 +49,6 @@ class GeofenceHelper(private val context: Context) {
return match
}
- fun invalidateCache() {
- geofenceCache.invalidate()
- AppLogger.d(TAG, "Geofence cache invalidated")
- }
-
- private fun getGeofences(): List<CachedGeofence> = geofenceCache.get()
-
private fun loadGeofencesFromDB(): List<CachedGeofence> {
return try {
val fences = mutableListOf<CachedGeofence>()
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 1ac1c38a..e83b7e7c 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
@@ -391,8 +391,6 @@ class LocationForegroundService : Service() {
}
private fun handleZoneRecheckAction() {
- geofenceHelper.invalidateCache()
-
val cachedLoc = lastKnownLocation
val now = System.currentTimeMillis()
@@ -833,24 +831,27 @@ class LocationForegroundService : Service() {
}
/**
- * Starts a periodic heartbeat that sends a location update to the server
- * at a relaxed interval while paused in a geofence zone.
+ * Starts a heartbeat that sends a location update to the server at a relaxed
+ * interval while paused in a geofence zone. Fires one send immediately so the
+ * backend sees zone entry without waiting a full interval.
*/
private fun startHeartbeat(intervalMinutes: Int) {
- heartbeatJob?.cancel()
- AppLogger.d(TAG, "Heartbeat started: ${intervalMinutes}min interval")
+ cancelHeartbeat()
+ AppLogger.i(TAG, "Heartbeat started: ${intervalMinutes}min interval")
heartbeatJob = serviceScope?.launch {
- while (isActive && insidePauseZone) {
+ sendHeartbeatLocation()
+ while (isActive) {
delay(intervalMinutes * 60_000L)
- if (!insidePauseZone) break
sendHeartbeatLocation()
}
}
}
private fun cancelHeartbeat() {
+ if (heartbeatJob == null) return
heartbeatJob?.cancel()
heartbeatJob = null
+ AppLogger.i(TAG, "Heartbeat cancelled")
}
private suspend fun sendHeartbeatLocation() {
@@ -904,7 +905,7 @@ class LocationForegroundService : Service() {
)
dbHelper.markLocationsSent(listOf(locationId))
LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
- AppLogger.d(TAG, "Heartbeat sent: lat=${location.latitude}, lon=${location.longitude}")
+ AppLogger.i(TAG, "Heartbeat sent for zone '${zone.name}'")
} else {
AppLogger.d(TAG, "Heartbeat failed: server unreachable, will retry next cycle")
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
index 2f7d323d..bd8596be 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/GeofenceHelperTest.kt
@@ -91,7 +91,6 @@ class GeofenceHelperTest {
it.moveToFirst(); it.getInt(0)
}
helper.updateGeofence(id, enabled = false)
- helper.invalidateCache()
assertNull(helper.getGeofenceByName("Home"))
}
@@ -157,7 +156,6 @@ class GeofenceHelperTest {
it.moveToFirst(); it.getInt(0)
}
helper.updateGeofence(id, enabled = false)
- helper.invalidateCache()
val location = mockLocation(52.5, 13.4)
assertNull(helper.getPauseZone(location))
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 abcc539b..e2670ecb 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
@@ -589,7 +589,6 @@ class LocationForegroundServiceTest {
invokeHandleZoneRecheckAction()
- verify { geofenceHelper.invalidateCache() }
assertFalse(getField("insidePauseZone"))
assertEquals(parkGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@@ -601,7 +600,6 @@ class LocationForegroundServiceTest {
invokeHandleZoneRecheckAction()
- verify { geofenceHelper.invalidateCache() }
verify { locationProvider.getLastLocation(any(), any()) }
}
@@ -1926,6 +1924,7 @@ class LocationForegroundServiceTest {
invokeSendHeartbeatLocation()
coVerify { networkManager.sendToEndpoint(any(), "https://example.com", any(), any(), any()) }
+ verify { AppLogger.i("LocationService", "Heartbeat sent for zone 'Home'") }
}
@Test
diff --git a/apps/mobile/src/screens/GeofenceEditorScreen.tsx b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
index 7f40df91..a906c6cb 100644
--- a/apps/mobile/src/screens/GeofenceEditorScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceEditorScreen.tsx
@@ -22,6 +22,7 @@ import { Container, SectionTitle, Card, SettingRow, Button } from "../components
import { Check, Trash2 } from "lucide-react-native"
import { logger } from "../utils/logger"
import { shortDistanceUnit, inputToMeters, metersToInput } from "../utils/geo"
+import { parsePositiveInt, isPositiveInt } from "../utils/settingsValidation"
export function GeofenceEditorScreen({ navigation, route }: any) {
const { colors } = useTheme()
@@ -35,10 +36,8 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
const [pauseTracking, setPauseTracking] = useState(true)
const [pauseOnWifi, setPauseOnWifi] = useState(false)
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)
@@ -48,9 +47,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking: true,
pauseOnWifi: false,
pauseOnMotionless: false,
- motionlessTimeoutMinutes: 10,
+ motionlessTimeoutStr: "10",
heartbeatEnabled: false,
- heartbeatIntervalMinutes: 15
+ heartbeatIntervalStr: "15"
})
const hasChanges = useMemo(() => {
@@ -61,9 +60,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking !== s.pauseTracking ||
pauseOnWifi !== s.pauseOnWifi ||
pauseOnMotionless !== s.pauseOnMotionless ||
- motionlessTimeoutMinutes !== s.motionlessTimeoutMinutes ||
+ parsePositiveInt(motionlessTimeoutStr, 10) !== parsePositiveInt(s.motionlessTimeoutStr, 10) ||
heartbeatEnabled !== s.heartbeatEnabled ||
- heartbeatIntervalMinutes !== s.heartbeatIntervalMinutes
+ parsePositiveInt(heartbeatIntervalStr, 15) !== parsePositiveInt(s.heartbeatIntervalStr, 15)
)
}, [
name,
@@ -71,9 +70,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes,
+ motionlessTimeoutStr,
heartbeatEnabled,
- heartbeatIntervalMinutes
+ heartbeatIntervalStr
])
useEffect(() => {
@@ -90,10 +89,8 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
setPauseTracking(existing.pauseTracking)
setPauseOnWifi(existing.pauseOnWifi)
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,
@@ -101,9 +98,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking: existing.pauseTracking,
pauseOnWifi: existing.pauseOnWifi,
pauseOnMotionless: existing.pauseOnMotionless,
- motionlessTimeoutMinutes: existing.motionlessTimeoutMinutes,
+ motionlessTimeoutStr: String(existing.motionlessTimeoutMinutes),
heartbeatEnabled: existing.heartbeatEnabled ?? false,
- heartbeatIntervalMinutes: existing.heartbeatIntervalMinutes ?? 15
+ heartbeatIntervalStr: String(existing.heartbeatIntervalMinutes ?? 15)
}
}
})
@@ -123,18 +120,6 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
if (!isNaN(num) && num > 0) setRadius(inputToMeters(num))
}, [])
- const handleTimeoutChange = useCallback((val: string) => {
- setMotionlessTimeoutStr(val)
- const num = parseInt(val, 10)
- 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")
@@ -144,10 +129,8 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
showAlert("Invalid Radius", "Please enter a valid radius.", "warning")
return
}
- if (heartbeatEnabled && heartbeatIntervalMinutes < 1) {
- showAlert("Invalid Heartbeat", "Heartbeat interval must be at least 1 minute.", "warning")
- return
- }
+ const effectiveHeartbeat = parsePositiveInt(heartbeatIntervalStr, 15)
+ const effectiveTimeout = parsePositiveInt(motionlessTimeoutStr, 10)
setSaving(true)
try {
@@ -159,9 +142,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes,
+ motionlessTimeoutMinutes: effectiveTimeout,
heartbeatEnabled,
- heartbeatIntervalMinutes
+ heartbeatIntervalMinutes: effectiveHeartbeat
})
} else {
const lat = route?.params?.lat as number
@@ -175,9 +158,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes,
+ motionlessTimeoutMinutes: effectiveTimeout,
heartbeatEnabled,
- heartbeatIntervalMinutes
+ heartbeatIntervalMinutes: effectiveHeartbeat
})
}
DeviceEventEmitter.emit("geofenceUpdated")
@@ -194,9 +177,9 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
pauseTracking,
pauseOnWifi,
pauseOnMotionless,
- motionlessTimeoutMinutes,
+ motionlessTimeoutStr,
heartbeatEnabled,
- heartbeatIntervalMinutes,
+ heartbeatIntervalStr,
isEditing,
geofenceId,
navigation,
@@ -304,12 +287,15 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
testID="motionless-timeout-input"
style={[inputStyle, styles.numInput]}
value={motionlessTimeoutStr}
- onChangeText={handleTimeoutChange}
+ onChangeText={setMotionlessTimeoutStr}
placeholder="10"
placeholderTextColor={colors.placeholder}
- keyboardType="numeric"
+ keyboardType="number-pad"
/>
</SettingRow>
+ {!isPositiveInt(motionlessTimeoutStr) && (
+ <Text style={[styles.fieldError, { color: colors.error }]}>Must be at least 1 minute</Text>
+ )}
</View>
)}
@@ -335,12 +321,15 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
testID="heartbeat-interval-input"
style={[inputStyle, styles.numInput]}
value={heartbeatIntervalStr}
- onChangeText={handleHeartbeatIntervalChange}
+ onChangeText={setHeartbeatIntervalStr}
placeholder="15"
placeholderTextColor={colors.placeholder}
- keyboardType="numeric"
+ keyboardType="number-pad"
/>
</SettingRow>
+ {!isPositiveInt(heartbeatIntervalStr) && (
+ <Text style={[styles.fieldError, { color: colors.error }]}>Must be at least 1 minute</Text>
+ )}
</View>
)}
@@ -356,7 +345,12 @@ export function GeofenceEditorScreen({ navigation, route }: any) {
<Button
title={saving ? "Saving..." : "Save Geofence"}
onPress={handleSave}
- disabled={saving || (isEditing && !hasChanges)}
+ disabled={
+ saving ||
+ (isEditing && !hasChanges) ||
+ (heartbeatEnabled && !isPositiveInt(heartbeatIntervalStr)) ||
+ (pauseOnMotionless && !isPositiveInt(motionlessTimeoutStr))
+ }
icon={Check}
/>
{isEditing && <Button title="Delete Geofence" onPress={handleDelete} variant="danger" icon={Trash2} />}
@@ -389,5 +383,10 @@ const styles = StyleSheet.create({
...fonts.regular,
lineHeight: 17,
fontStyle: "italic"
+ },
+ fieldError: {
+ fontSize: 12,
+ ...fonts.regular,
+ marginTop: 4
}
})
diff --git a/apps/mobile/src/utils/__tests__/settingsValidation.test.ts b/apps/mobile/src/utils/__tests__/settingsValidation.test.ts
index c634106f..1f32d8aa 100644
--- a/apps/mobile/src/utils/__tests__/settingsValidation.test.ts
+++ b/apps/mobile/src/utils/__tests__/settingsValidation.test.ts
@@ -1,4 +1,4 @@
-import { isEndpointAllowed } from "../settingsValidation"
+import { isEndpointAllowed, isPositiveInt, parsePositiveInt } from "../settingsValidation"
describe("isEndpointAllowed", () => {
it("allows valid http and https URLs", () => {
@@ -19,3 +19,38 @@ describe("isEndpointAllowed", () => {
expect(isEndpointAllowed("ws://example.com")).toBe(false)
})
})
+
+describe("isPositiveInt", () => {
+ it("accepts integers >= 1", () => {
+ expect(isPositiveInt("1")).toBe(true)
+ expect(isPositiveInt("15")).toBe(true)
+ expect(isPositiveInt("999")).toBe(true)
+ })
+
+ it("rejects 0 and negatives", () => {
+ expect(isPositiveInt("0")).toBe(false)
+ expect(isPositiveInt("-5")).toBe(false)
+ })
+
+ it("rejects empty and non-numeric input", () => {
+ expect(isPositiveInt("")).toBe(false)
+ expect(isPositiveInt("abc")).toBe(false)
+ })
+})
+
+describe("parsePositiveInt", () => {
+ it("returns the parsed value when valid", () => {
+ expect(parsePositiveInt("5", 99)).toBe(5)
+ expect(parsePositiveInt("1", 99)).toBe(1)
+ })
+
+ it("returns the fallback when invalid", () => {
+ expect(parsePositiveInt("0", 10)).toBe(10)
+ expect(parsePositiveInt("", 10)).toBe(10)
+ expect(parsePositiveInt("abc", 10)).toBe(10)
+ })
+
+ it("truncates floats via parseInt", () => {
+ expect(parsePositiveInt("5.9", 99)).toBe(5)
+ })
+})
diff --git a/apps/mobile/src/utils/settingsValidation.ts b/apps/mobile/src/utils/settingsValidation.ts
index 849c59fe..af957f91 100644
--- a/apps/mobile/src/utils/settingsValidation.ts
+++ b/apps/mobile/src/utils/settingsValidation.ts
@@ -20,3 +20,14 @@ export function findDuplicates(values: string[]): Set<string> {
export function isEndpointAllowed(url: string) {
return /^https?:\/\/[^/:]+/.test(url)
}
+
+// Parses a string to a positive integer (>= 1), or returns fallback if invalid.
+export function parsePositiveInt(str: string, fallback: number): number {
+ const n = parseInt(str, 10)
+ return n >= 1 ? n : fallback
+}
+
+// Returns true if the string parses to an integer >= 1.
+export function isPositiveInt(str: string): boolean {
+ return parseInt(str, 10) >= 1
+}