Colota - Android GPS Location tracker
fix: log anchor point at geofence center on zone enter/exit
Max Dietrich1d3f23714ef4
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.ktindex 340a15cc..bb94568f 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@@ -638,7 +638,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :val zone = withContext(Dispatchers.IO) {geofenceHelper.getPauseZone(loc)}- promise.resolve(zone)+ promise.resolve(zone?.name)} catch (e: Exception) {AppLogger.e(TAG, "Pause zone check failed", e)promise.resolve(null)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.ktindex ad338931..e16f0ca1 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@@ -49,16 +49,16 @@ class GeofenceHelper(private val context: Context) {}}- fun getPauseZone(location: Location): String? {+ fun getPauseZone(location: Location): CachedGeofence? {val fences = getGeofences()val match = fences.find {isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)}- if (fences.isNotEmpty() && match != null) {+ if (match != null) {val dist = calculateDistance(location.latitude, location.longitude, match.lat, match.lon)AppLogger.d(TAG, "Inside zone '${match.name}' (${String.format("%.0f", dist)}m from center, radius=${match.radius}m)")}- return match?.name+ return match}fun invalidateCache() {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.ktindex 82eed6d8..eb262c54 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@@ -48,6 +48,7 @@ class LocationForegroundService : Service() {@Volatile private var locationRestartJob: Job? = null@Volatile private var insidePauseZone = false@Volatile private var currentZoneName: String? = null+ @Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null@Volatile private var lastKnownLocation: android.location.Location? = null@Volatile private lateinit var config: ServiceConfig@@ -249,8 +250,8 @@ class LocationForegroundService : Service() {onSuccess = { location ->location?.let {lastKnownLocation = it- geofenceHelper.getPauseZone(it)?.let { zoneName ->- enterPauseZone(zoneName)+ geofenceHelper.getPauseZone(it)?.let { zone ->+ enterPauseZone(zone)} ?: run {updateNotification(it.latitude, it.longitude, forceUpdate = true)}@@ -305,17 +306,17 @@ class LocationForegroundService : Service() {private fun recheckZoneWithLocation(location: android.location.Location) {- val zoneName = geofenceHelper.getPauseZone(location)+ val zone = geofenceHelper.getPauseZone(location)when {- zoneName != null && (!insidePauseZone || zoneName != currentZoneName) -> {- enterPauseZone(zoneName)+ zone != null && (!insidePauseZone || zone.name != currentZoneName) -> {+ enterPauseZone(zone)}- zoneName == null && insidePauseZone -> {+ zone == null && insidePauseZone -> {exitPauseZone()}// Same zone - refresh notification coords- zoneName != null && insidePauseZone && zoneName == currentZoneName -> {+ zone != null && insidePauseZone && zone.name == currentZoneName -> {updateNotification(lat = location.latitude,lon = location.longitude,@@ -376,14 +377,14 @@ class LocationForegroundService : Service() {lastKnownLocation = location- val zoneName = geofenceHelper.getPauseZone(location)+ val zone = geofenceHelper.getPauseZone(location)when {- zoneName != null && !insidePauseZone -> {- enterPauseZone(zoneName)+ zone != null && (!insidePauseZone || zone.name != currentZoneName) -> {+ enterPauseZone(zone)return}- zoneName == null && insidePauseZone -> exitPauseZone()- zoneName != null && insidePauseZone -> return+ zone == null && insidePauseZone -> exitPauseZone()+ zone != null && insidePauseZone -> return}val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()@@ -430,35 +431,95 @@ class LocationForegroundService : Service() {}}- private fun enterPauseZone(zoneName: String) {+ private fun enterPauseZone(geofence: GeofenceHelper.CachedGeofence) {+ if (!insidePauseZone) {+ saveAnchorPoint(geofence)+ }+insidePauseZone = true- currentZoneName = zoneName+ currentZoneName = geofence.name+ currentZoneGeofence = geofenceval loc = lastKnownLocationupdateNotification(lat = loc?.latitude,lon = loc?.longitude,pausedInZone = true,- zoneName = zoneName,+ zoneName = geofence.name,forceUpdate = true)- LocationServiceModule.sendPauseZoneEvent(true, zoneName)+ LocationServiceModule.sendPauseZoneEvent(true, geofence.name)- AppLogger.d(TAG, "Entered pause zone: $zoneName")+ AppLogger.d(TAG, "Entered pause zone: ${geofence.name}")}private fun exitPauseZone() {+ val exitedGeofence = currentZoneGeofence+ val exitedName = currentZoneName+insidePauseZone = false- val exited = currentZoneNamecurrentZoneName = null+ currentZoneGeofence = null++ if (exitedGeofence != null) {+ saveAnchorPoint(exitedGeofence)+ }val loc = lastKnownLocationupdateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)- LocationServiceModule.sendPauseZoneEvent(false, exited)- AppLogger.d(TAG, "Exited pause zone: $exited")+ LocationServiceModule.sendPauseZoneEvent(false, exitedName)+ AppLogger.d(TAG, "Exited pause zone: $exitedName")+ }++ /** Logs a synthetic location at the geofence center for clean track start/end points. */+ private fun saveAnchorPoint(geofence: GeofenceHelper.CachedGeofence) {+ if (!::config.isInitialized) {+ AppLogger.w(TAG, "Config not yet initialized, skipping anchor point for '${geofence.name}'")+ return+ }++ val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()+ val nowMs = System.currentTimeMillis()+ val timestampSec = nowMs / 1000+ val currentFieldMap = fieldMap ?: emptyMap()++ val syntheticLocation = android.location.Location("geofence").apply {+ latitude = geofence.lat+ longitude = geofence.lon+ accuracy = geofence.radius.toFloat()+ time = nowMs+ }++ serviceScope?.launch {+ val locationId = dbHelper.saveLocation(+ latitude = geofence.lat,+ longitude = geofence.lon,+ accuracy = geofence.radius,+ altitude = null,+ speed = null,+ bearing = null,+ battery = battery,+ battery_status = batteryStatus,+ timestamp = timestampSec,+ endpoint = config.endpoint+ )++ val payload = payloadBuilder.buildPayload(+ syntheticLocation,+ battery,+ batteryStatus,+ currentFieldMap,+ timestampSec,+ customFields+ )++ syncManager.queueAndSend(locationId, payload)++ AppLogger.d(TAG, "Anchor point saved at geofence '${geofence.name}' center (${geofence.lat}, ${geofence.lon})")+ }}private fun updateNotification(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.ktindex 483adcf3..2f3b8ad8 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@@ -432,7 +432,7 @@ class LocationForegroundServiceTest {@Testfun `handleLocationUpdate enters pause zone when location is in geofence`() = testScope.runTest {- every { geofenceHelper.getPauseZone(any()) } returns "Home"+ every { geofenceHelper.getPauseZone(any()) } returns homeGeofenceval location = mockLocation()invokeHandleLocationUpdate(location)@@ -440,18 +440,48 @@ class LocationForegroundServiceTest {assertTrue(getField("insidePauseZone"))assertEquals("Home", getField<String?>("currentZoneName"))verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }- verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ // Anchor point is saved at geofence center, but regular GPS location is not saved+ verify(exactly = 1) { dbHelper.saveLocation(+ latitude = homeGeofence.lat,+ longitude = homeGeofence.lon,+ accuracy = homeGeofence.radius,+ altitude = null,+ speed = null,+ bearing = null,+ battery = any(),+ battery_status = any(),+ timestamp = any(),+ endpoint = any()+ ) }}@Testfun `handleLocationUpdate skips saving when already inside pause zone`() = testScope.runTest {setField("insidePauseZone", true)setField("currentZoneName", "Home")- every { geofenceHelper.getPauseZone(any()) } returns "Home"+ setField("currentZoneGeofence", homeGeofence)+ every { geofenceHelper.getPauseZone(any()) } returns homeGeofence+ val location = mockLocation()++ invokeHandleLocationUpdate(location)++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }++ @Test+ fun `handleLocationUpdate updates zone when moving to different zone`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)+ every { geofenceHelper.getPauseZone(any()) } returns officeGeofenceval location = mockLocation()invokeHandleLocationUpdate(location)+ assertTrue(getField("insidePauseZone"))+ assertEquals("Office", getField<String?>("currentZoneName"))+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))+ // No anchor saved for zone-to-zone transitionverify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }}@@ -459,6 +489,7 @@ class LocationForegroundServiceTest {fun `handleLocationUpdate exits pause zone and resumes saving`() = testScope.runTest {setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)every { geofenceHelper.getPauseZone(any()) } returns nullval location = mockLocation()every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L@@ -468,8 +499,8 @@ class LocationForegroundServiceTest {assertFalse(getField("insidePauseZone"))assertNull(getField<String?>("currentZoneName"))verify { LocationServiceModule.sendPauseZoneEvent(false, "Home") }- verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }- coVerify { syncManager.queueAndSend(1L, any()) }+ // Anchor point + regular GPS location = 2 saves+ verify(atLeast = 2) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }}@Test@@ -527,6 +558,7 @@ class LocationForegroundServiceTest {fun `ACTION_FORCE_EXIT_ZONE rechecks zone after forced exit`() {setField("insidePauseZone", true)setField("currentZoneName", "Office")+ setField("currentZoneGeofence", officeGeofence)val location = mockLocation()setField("lastKnownLocation", location)every { geofenceHelper.getPauseZone(location) } returns null@@ -541,9 +573,10 @@ class LocationForegroundServiceTest {fun `ACTION_FORCE_EXIT_ZONE re-enters if still in zone after recheck`() {setField("insidePauseZone", true)setField("currentZoneName", "Office")+ setField("currentZoneGeofence", officeGeofence)val location = mockLocation()setField("lastKnownLocation", location)- every { geofenceHelper.getPauseZone(location) } returns "Office"+ every { geofenceHelper.getPauseZone(location) } returns officeGeofenceinvokeExitPauseZone()invokeRecheckZoneWithLocation(location)@@ -556,7 +589,7 @@ class LocationForegroundServiceTest {fun `ACTION_RECHECK_ZONE with fresh location rechecks immediately`() {val freshLocation = mockLocation(time = System.currentTimeMillis())setField("lastKnownLocation", freshLocation)- every { geofenceHelper.getPauseZone(freshLocation) } returns "Park"+ every { geofenceHelper.getPauseZone(freshLocation) } returns parkGeofenceinvokeHandleZoneRecheckAction()@@ -590,6 +623,7 @@ class LocationForegroundServiceTest {setField("lastKnownLocation", null)setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)every { locationProvider.getLastLocation(any(), any()) } answers {val onSuccess = firstArg<(Location?) -> Unit>()@@ -606,6 +640,7 @@ class LocationForegroundServiceTest {setField("lastKnownLocation", null)setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)every { locationProvider.getLastLocation(any(), any()) } answers {val onFailure = secondArg<(Exception) -> Unit>()@@ -642,19 +677,63 @@ class LocationForegroundServiceTest {val location = mockLocation()setField("lastKnownLocation", location)- invokeEnterPauseZone("Home")+ invokeEnterPauseZone(homeGeofence)assertTrue(getField("insidePauseZone"))assertEquals("Home", getField<String?>("currentZoneName"))+ assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }}+ @Test+ fun `enterPauseZone saves anchor point at geofence center`() = testScope.runTest {+ val location = mockLocation()+ setField("lastKnownLocation", location)++ invokeEnterPauseZone(homeGeofence)++ verify { dbHelper.saveLocation(+ latitude = homeGeofence.lat,+ longitude = homeGeofence.lon,+ accuracy = homeGeofence.radius,+ altitude = null,+ speed = null,+ bearing = null,+ battery = 80,+ battery_status = 2,+ timestamp = any(),+ endpoint = "https://example.com"+ ) }+ }++ @Test+ fun `enterPauseZone anchor queues sync after DB save`() = testScope.runTest {+ val location = mockLocation()+ setField("lastKnownLocation", location)+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 42L++ invokeEnterPauseZone(homeGeofence)++ coVerify { syncManager.queueAndSend(42L, any()) }+ }++ @Test+ fun `saveAnchorPoint skips when config not initialized`() = testScope.runTest {+ // Reset config to uninitialized (lateinit backs to null at JVM level)+ setField("config", null)++ invokeSaveAnchorPoint(homeGeofence)++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ verify { AppLogger.w("LocationService", match { it.contains("Config not yet initialized") }) }+ }+@Testfun `enterPauseZone updates notification with paused status`() {val location = mockLocation(lat = 52.0, lon = 13.0)setField("lastKnownLocation", location)- invokeEnterPauseZone("Office")+ invokeEnterPauseZone(officeGeofence)verify { notificationHelper.update(lat = 52.0,@@ -672,7 +751,7 @@ class LocationForegroundServiceTest {fun `enterPauseZone handles null lastKnownLocation`() {setField("lastKnownLocation", null)- invokeEnterPauseZone("Home")+ invokeEnterPauseZone(homeGeofence)verify { notificationHelper.update(lat = null,@@ -690,19 +769,55 @@ class LocationForegroundServiceTest {fun `exitPauseZone clears state and sends event`() {setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)invokeExitPauseZone()assertFalse(getField("insidePauseZone"))assertNull(getField<String?>("currentZoneName"))+ assertNull(getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))verify { LocationServiceModule.sendPauseZoneEvent(false, "Home") }}+ @Test+ fun `exitPauseZone saves anchor point from stored geofence`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)++ invokeExitPauseZone()++ verify { dbHelper.saveLocation(+ latitude = homeGeofence.lat,+ longitude = homeGeofence.lon,+ accuracy = homeGeofence.radius,+ altitude = null,+ speed = null,+ bearing = null,+ battery = 80,+ battery_status = 2,+ timestamp = any(),+ endpoint = "https://example.com"+ ) }+ }++ @Test+ fun `exitPauseZone skips anchor when no stored geofence`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", null)++ invokeExitPauseZone()++ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }+@Testfun `exitPauseZone updates notification without paused status`() {val location = mockLocation(lat = 52.0, lon = 13.0)setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)setField("lastKnownLocation", location)invokeExitPauseZone()@@ -721,24 +836,40 @@ class LocationForegroundServiceTest {@Testfun `zone transition enter then exit restores clean state`() {- invokeEnterPauseZone("Home")+ invokeEnterPauseZone(homeGeofence)assertTrue(getField("insidePauseZone"))invokeExitPauseZone()assertFalse(getField("insidePauseZone"))assertNull(getField<String?>("currentZoneName"))+ assertNull(getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))}@Testfun `zone change from one zone to another updates name`() {- invokeEnterPauseZone("Home")+ invokeEnterPauseZone(homeGeofence)assertEquals("Home", getField<String?>("currentZoneName"))- invokeEnterPauseZone("Office")+ invokeEnterPauseZone(officeGeofence)assertEquals("Office", getField<String?>("currentZoneName"))assertTrue(getField("insidePauseZone"))}+ @Test+ fun `zone-to-zone transition skips anchor for second zone`() = testScope.runTest {+ val location = mockLocation()+ setField("lastKnownLocation", location)++ invokeEnterPauseZone(homeGeofence)++ clearMocks(dbHelper, answers = false)++ invokeEnterPauseZone(officeGeofence)++ // No anchor saved when switching directly between zones (no trip in between)+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ }+// =========================================================================// recheckZoneWithLocation - zone recheck state machine// =========================================================================@@ -747,7 +878,7 @@ class LocationForegroundServiceTest {fun `recheckZone enters zone when not currently in zone`() {setField("insidePauseZone", false)val location = mockLocation()- every { geofenceHelper.getPauseZone(location) } returns "Park"+ every { geofenceHelper.getPauseZone(location) } returns parkGeofenceinvokeRecheckZoneWithLocation(location)@@ -759,6 +890,7 @@ class LocationForegroundServiceTest {fun `recheckZone exits zone when location leaves geofence`() {setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)val location = mockLocation()every { geofenceHelper.getPauseZone(location) } returns null@@ -771,8 +903,9 @@ class LocationForegroundServiceTest {fun `recheckZone changes zone when moving between zones`() {setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)val location = mockLocation()- every { geofenceHelper.getPauseZone(location) } returns "Office"+ every { geofenceHelper.getPauseZone(location) } returns officeGeofenceinvokeRecheckZoneWithLocation(location)@@ -780,12 +913,31 @@ class LocationForegroundServiceTest {assertEquals("Office", getField<String?>("currentZoneName"))}+ @Test+ fun `recheckZone zone-to-zone transition skips anchor for new zone`() = testScope.runTest {+ setField("insidePauseZone", true)+ setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)+ val location = mockLocation()+ every { geofenceHelper.getPauseZone(location) } returns officeGeofence++ clearMocks(dbHelper, answers = false)++ invokeRecheckZoneWithLocation(location)++ // No anchor saved when switching directly between zones (no trip in between)+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }+ // State should still update+ assertEquals("Office", getField<String?>("currentZoneName"))+ }+@Testfun `recheckZone updates notification when staying in same zone`() {setField("insidePauseZone", true)setField("currentZoneName", "Home")+ setField("currentZoneGeofence", homeGeofence)val location = mockLocation(lat = 52.0, lon = 13.0)- every { geofenceHelper.getPauseZone(location) } returns "Home"+ every { geofenceHelper.getPauseZone(location) } returns homeGeofenceinvokeRecheckZoneWithLocation(location)@@ -1035,12 +1187,12 @@ class LocationForegroundServiceTest {method.invoke(service, location)}- private fun invokeEnterPauseZone(zoneName: String) {+ private fun invokeEnterPauseZone(geofence: GeofenceHelper.CachedGeofence) {val method = LocationForegroundService::class.java.getDeclaredMethod(- "enterPauseZone", String::class.java+ "enterPauseZone", GeofenceHelper.CachedGeofence::class.java)method.isAccessible = true- method.invoke(service, zoneName)+ method.invoke(service, geofence)}private fun invokeExitPauseZone() {@@ -1084,4 +1236,19 @@ class LocationForegroundServiceTest {method.isAccessible = truemethod.invoke(service)}++ private fun invokeSaveAnchorPoint(geofence: GeofenceHelper.CachedGeofence) {+ val method = LocationForegroundService::class.java.getDeclaredMethod(+ "saveAnchorPoint", GeofenceHelper.CachedGeofence::class.java+ )+ method.isAccessible = true+ method.invoke(service, geofence)+ }++ private fun geofence(name: String, lat: Double = 52.52, lon: Double = 13.405, radius: Double = 100.0) =+ GeofenceHelper.CachedGeofence(name, lat, lon, radius)++ private val homeGeofence = geofence("Home", 52.50, 13.40, 150.0)+ private val officeGeofence = geofence("Office", 48.14, 11.58, 200.0)+ private val parkGeofence = geofence("Park", 52.51, 13.35, 100.0)}