Skip to content

Colota - Android GPS Location tracker

refactor: extract shared utils and deduplicate native code

Max Dietrichdb22e30b211b
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/DebugSeedData.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/DebugSeedData.kt
new file mode 100644
index 00000000..74ee9258
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/DebugSeedData.kt
@@ -0,0 +1,118 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.bridge
+
+import com.Colota.data.DatabaseHelper
+
+/**
+ * Debug-only DB seed: 7 days of plausible Berlin tracks
+ * (home -> supermarket -> gym -> home, plus an occasional evening walk)
+ * so the UI has something to render in development builds.
+ */
+object DebugSeedData {
+
+ // Home: Boxhagener Platz, Friedrichshain
+ // Supermarket: REWE on Warschauer Str (~1.2 km south)
+ // Gym: FitX Ostkreuz (~1.5 km SE of supermarket)
+ // Columns: lat, lon, alt, speed, accuracy
+ private val TRIP_HOME_TO_SUPERMARKET = arrayOf(
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0),
+ doubleArrayOf(52.51390, 13.45780, 37.0, 3.5, 5.0),
+ doubleArrayOf(52.51310, 13.45650, 36.0, 8.2, 4.0),
+ doubleArrayOf(52.51220, 13.45490, 35.0, 11.5, 3.5),
+ doubleArrayOf(52.51120, 13.45340, 35.0, 12.8, 3.0),
+ doubleArrayOf(52.50980, 13.45220, 34.0, 10.1, 4.0),
+ doubleArrayOf(52.50870, 13.45100, 34.0, 8.7, 3.5),
+ doubleArrayOf(52.50760, 13.44950, 33.0, 11.3, 3.0),
+ doubleArrayOf(52.50650, 13.44820, 33.0, 9.4, 4.0),
+ doubleArrayOf(52.50560, 13.44710, 33.0, 6.2, 4.5),
+ doubleArrayOf(52.50490, 13.44650, 32.0, 2.1, 5.0),
+ doubleArrayOf(52.50460, 13.44630, 32.0, 0.3, 4.0),
+ )
+
+ private val TRIP_SUPERMARKET_TO_GYM = arrayOf(
+ doubleArrayOf(52.50460, 13.44630, 32.0, 0.5, 4.0),
+ doubleArrayOf(52.50430, 13.44700, 32.0, 5.8, 4.5),
+ doubleArrayOf(52.50380, 13.44890, 33.0, 10.2, 3.5),
+ doubleArrayOf(52.50340, 13.45120, 33.0, 12.5, 3.0),
+ doubleArrayOf(52.50310, 13.45380, 34.0, 11.8, 3.5),
+ doubleArrayOf(52.50270, 13.45640, 34.0, 9.6, 4.0),
+ doubleArrayOf(52.50230, 13.45900, 35.0, 8.3, 4.0),
+ doubleArrayOf(52.50180, 13.46100, 35.0, 5.1, 4.5),
+ doubleArrayOf(52.50150, 13.46250, 35.0, 2.4, 5.0),
+ doubleArrayOf(52.50140, 13.46280, 35.0, 0.2, 4.0),
+ )
+
+ private val TRIP_GYM_TO_HOME = arrayOf(
+ doubleArrayOf(52.50140, 13.46280, 35.0, 0.4, 4.0),
+ doubleArrayOf(52.50190, 13.46180, 35.0, 4.2, 4.5),
+ doubleArrayOf(52.50280, 13.45980, 34.0, 9.7, 3.5),
+ doubleArrayOf(52.50390, 13.45820, 34.0, 11.4, 3.0),
+ doubleArrayOf(52.50510, 13.45700, 33.0, 12.1, 3.5),
+ doubleArrayOf(52.50630, 13.45590, 33.0, 10.5, 4.0),
+ doubleArrayOf(52.50740, 13.45480, 34.0, 8.9, 3.5),
+ doubleArrayOf(52.50860, 13.45360, 34.0, 11.0, 3.0),
+ doubleArrayOf(52.50970, 13.45280, 35.0, 9.3, 4.0),
+ doubleArrayOf(52.51080, 13.45370, 36.0, 10.8, 3.5),
+ doubleArrayOf(52.51190, 13.45490, 37.0, 8.2, 4.0),
+ doubleArrayOf(52.51290, 13.45620, 37.0, 6.5, 4.5),
+ doubleArrayOf(52.51370, 13.45740, 38.0, 3.1, 5.0),
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0),
+ )
+
+ private val EVENING_WALK = arrayOf(
+ doubleArrayOf(52.51420, 13.45830, 38.0, 1.2, 6.0),
+ doubleArrayOf(52.51450, 13.45900, 38.0, 1.4, 5.5),
+ doubleArrayOf(52.51480, 13.45970, 38.0, 1.3, 5.0),
+ doubleArrayOf(52.51500, 13.46050, 38.0, 1.5, 5.5),
+ doubleArrayOf(52.51480, 13.46130, 38.0, 1.4, 6.0),
+ doubleArrayOf(52.51450, 13.46080, 38.0, 1.3, 5.5),
+ doubleArrayOf(52.51430, 13.45970, 38.0, 1.2, 5.0),
+ doubleArrayOf(52.51420, 13.45830, 38.0, 0.3, 6.0),
+ )
+
+ fun insertDummyData(db: DatabaseHelper): Int {
+ val now = System.currentTimeMillis() / 1000
+ var count = 0
+
+ for (dayOffset in 6 downTo 0) {
+ val dayMidnight = now - (now % 86400) - (dayOffset * 86400L)
+ val battery = 92 - (dayOffset * 3)
+
+ count += insertTrip(db, TRIP_HOME_TO_SUPERMARKET, dayMidnight + 9 * 3600 + 1800, 30L, battery, 0, 1, now)
+ count += insertTrip(db, TRIP_SUPERMARKET_TO_GYM, dayMidnight + 10 * 3600 + 1200, 30L, battery, 15, 2, now)
+ count += insertTrip(db, TRIP_GYM_TO_HOME, dayMidnight + 12 * 3600, 30L, battery, 30, 1, now)
+
+ if (dayOffset % 2 == 0) continue
+ count += insertTrip(db, EVENING_WALK, dayMidnight + 18 * 3600, 75L, battery, 45, 1, now)
+ }
+ return count
+ }
+
+ private fun insertTrip(
+ db: DatabaseHelper,
+ trip: Array<DoubleArray>,
+ startTs: Long,
+ stepSeconds: Long,
+ batteryBase: Int,
+ batteryOffset: Int,
+ profileId: Int,
+ nowCeiling: Long,
+ ): Int {
+ var inserted = 0
+ for ((i, wp) in trip.withIndex()) {
+ val ts = startTs + (i * stepSeconds)
+ if (ts > nowCeiling) break
+ db.saveLocation(
+ wp[0], wp[1],
+ wp[4], wp[2].toInt(), wp[3],
+ null, batteryBase - batteryOffset - i, profileId, ts,
+ )
+ inserted++
+ }
+ return inserted
+ }
+}
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 8ec2e5e2..963de040 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
@@ -12,6 +12,7 @@ import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
import com.Colota.service.LocationForegroundService
+import com.Colota.data.SettingsKeys
import com.Colota.service.ProfileConstants
import com.Colota.service.ServiceConfig
import com.Colota.service.getDoubleOrNull
@@ -19,7 +20,6 @@ import com.Colota.service.getIntOrNull
import com.Colota.service.getStringOrNull
import com.Colota.service.getBooleanOrNull
import com.Colota.sync.NetworkManager
-import com.Colota.sync.PayloadBuilder
import com.Colota.util.DeviceInfoHelper
import com.Colota.export.AutoExportConfig
import com.Colota.export.AutoExportScheduler
@@ -35,8 +35,8 @@ import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
+import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
-import com.Colota.location.LocationProviderFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -55,7 +55,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext),
LifecycleEventListener {
- private val payloadBuilder = PayloadBuilder()
private val dbHelper = DatabaseHelper.getInstance(reactContext)
private val fileOps = FileOperations(reactContext)
private val deviceInfo = DeviceInfoHelper(reactContext)
@@ -98,6 +97,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
companion object {
private const val TAG = "LocationServiceModule"
+ /** JS config key -> secure storage key mapping for saveAuthConfig. */
+ private val AUTH_CONFIG_KEYS = listOf(
+ "authType" to SecureStorageHelper.KEY_AUTH_TYPE,
+ "username" to SecureStorageHelper.KEY_USERNAME,
+ "password" to SecureStorageHelper.KEY_PASSWORD,
+ "bearerToken" to SecureStorageHelper.KEY_BEARER_TOKEN,
+ "customHeaders" to SecureStorageHelper.KEY_CUSTOM_HEADERS,
+ )
+
private var reactContextRef: WeakReference<ReactApplicationContext> = WeakReference(null)
@Volatile
@@ -106,179 +114,84 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@Volatile
private var activeProfileName: String? = null
- /** Skips when app is backgrounded to avoid unnecessary bridge overhead. */
- @JvmStatic
- fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {
- if (!isAppInForeground) return false
-
+ private inline fun emit(event: String, build: WritableMap.() -> Unit): Boolean {
val context = reactContextRef.get() ?: return false
if (!context.hasActiveCatalystInstance()) return false
-
return try {
- val params = Arguments.createMap().apply {
- putDouble("latitude", location.latitude)
- putDouble("longitude", location.longitude)
- putDouble("accuracy", location.accuracy.toDouble())
-
- if (location.hasAltitude()) {
- putDouble("altitude", location.altitude)
- } else {
- putNull("altitude")
- }
-
- if (location.hasSpeed()) {
- putDouble("speed", location.speed.toDouble())
- } else {
- putNull("speed")
- }
- putDouble("bearing", if (location.hasBearing()) location.bearing.toDouble() else 0.0)
- putDouble("timestamp", location.time.toDouble())
- putInt("battery", battery)
- putInt("batteryStatus", batteryStatus)
- }
-
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onLocationUpdate", params)
+ val params = Arguments.createMap().apply(build)
+ context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
+ .emit(event, params)
true
} catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send location event", e)
+ AppLogger.e(TAG, "Failed to send $event", e)
false
}
}
- /** Fires when service stops for non-user reasons (OOM kill, system cleanup). */
+ /** Skips when app is backgrounded to avoid unnecessary bridge overhead. */
@JvmStatic
- fun sendTrackingStoppedEvent(reason: String): Boolean {
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
-
- return try {
- val params = Arguments.createMap().apply {
- putString("reason", reason)
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onTrackingStopped", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send tracking stopped event", e)
- false
+ fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {
+ if (!isAppInForeground) return false
+ return emit("onLocationUpdate") {
+ putDouble("latitude", location.latitude)
+ putDouble("longitude", location.longitude)
+ putDouble("accuracy", location.accuracy.toDouble())
+ if (location.hasAltitude()) putDouble("altitude", location.altitude) else putNull("altitude")
+ if (location.hasSpeed()) putDouble("speed", location.speed.toDouble()) else putNull("speed")
+ putDouble("bearing", if (location.hasBearing()) location.bearing.toDouble() else 0.0)
+ putDouble("timestamp", location.time.toDouble())
+ putInt("battery", battery)
+ putInt("batteryStatus", batteryStatus)
}
}
- /** Only fires after 3+ consecutive sync failures — see SyncManager.startPeriodicSync(). */
+ /** Fires when service stops for non-user reasons (OOM kill, system cleanup). */
@JvmStatic
- fun sendSyncErrorEvent(message: String, queuedCount: Int): Boolean {
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
+ fun sendTrackingStoppedEvent(reason: String): Boolean =
+ emit("onTrackingStopped") { putString("reason", reason) }
- return try {
- val params = Arguments.createMap().apply {
- putString("message", message)
- putInt("queuedCount", queuedCount)
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onSyncError", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send sync error event", e)
- false
+ /** Only fires after 3+ consecutive sync failures, see SyncManager.startPeriodicSync(). */
+ @JvmStatic
+ fun sendSyncErrorEvent(message: String, queuedCount: Int): Boolean =
+ emit("onSyncError") {
+ putString("message", message)
+ putInt("queuedCount", queuedCount)
}
- }
- /** Emits profile switch events to JS when a tracking profile activates/deactivates. */
@JvmStatic
fun sendProfileSwitchEvent(profileName: String?, profileId: Int?): Boolean {
activeProfileName = profileName
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
-
- return try {
- val params = Arguments.createMap().apply {
- if (profileName != null) putString("profileName", profileName)
- else putNull("profileName")
- if (profileId != null) putInt("profileId", profileId)
- else putNull("profileId")
- putBoolean("isDefault", profileName == null)
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onProfileSwitch", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send profile switch event", e)
- false
+ return emit("onProfileSwitch") {
+ if (profileName != null) putString("profileName", profileName) else putNull("profileName")
+ if (profileId != null) putInt("profileId", profileId) else putNull("profileId")
+ putBoolean("isDefault", profileName == null)
}
}
- /** Emits sync progress during manual flush so JS can show "5/127 synced". */
@JvmStatic
- fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int): Boolean {
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
-
- return try {
- val params = Arguments.createMap().apply {
- putInt("sent", sent)
- putInt("failed", failed)
- putInt("total", total)
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onSyncProgress", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send sync progress event", e)
- false
+ fun sendSyncProgressEvent(sent: Int, failed: Int, total: Int): Boolean =
+ emit("onSyncProgress") {
+ putInt("sent", sent)
+ putInt("failed", failed)
+ putInt("total", total)
}
- }
- /** Emits auto-export completion events to JS for real-time status updates. */
@JvmStatic
- fun sendAutoExportEvent(success: Boolean, fileName: String?, rowCount: Int, error: String?): Boolean {
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
-
- return try {
- val params = Arguments.createMap().apply {
- putBoolean("success", success)
- if (fileName != null) putString("fileName", fileName) else putNull("fileName")
- putInt("rowCount", rowCount)
- if (error != null) putString("error", error) else putNull("error")
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onAutoExportComplete", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send auto-export event", e)
- false
+ fun sendAutoExportEvent(success: Boolean, fileName: String?, rowCount: Int, error: String?): Boolean =
+ emit("onAutoExportComplete") {
+ putBoolean("success", success)
+ if (fileName != null) putString("fileName", fileName) else putNull("fileName")
+ putInt("rowCount", rowCount)
+ if (error != null) putString("error", error) else putNull("error")
}
- }
- /** Emits pause zone entry/exit events for the JS geofence UI. */
@JvmStatic
- fun sendPauseZoneEvent(entered: Boolean, zoneName: String?, pauseReason: String? = null): Boolean {
- val context = reactContextRef.get() ?: return false
- if (!context.hasActiveCatalystInstance()) return false
-
- return try {
- val params = Arguments.createMap().apply {
- putBoolean("entered", entered)
- putString("zoneName", zoneName)
- putString("pauseReason", pauseReason)
- }
- context
- .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
- .emit("onPauseZoneChange", params)
- true
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send pause zone event", e)
- false
+ fun sendPauseZoneEvent(entered: Boolean, zoneName: String?, pauseReason: String? = null): Boolean =
+ emit("onPauseZoneChange") {
+ putBoolean("entered", entered)
+ putString("zoneName", zoneName)
+ putString("pauseReason", pauseReason)
}
- }
}
override fun getName(): String = "LocationServiceModule"
@@ -302,12 +215,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
- /** Runs on IO thread and resolves/rejects the JS promise. */
+ /** Runs [operation] on Dispatchers.IO and resolves/rejects the JS promise. */
private fun executeAsync(promise: Promise, operation: suspend () -> Any?) {
moduleScope.launch {
try {
- val result = withContext(Dispatchers.IO) { operation() }
- promise.resolve(result)
+ promise.resolve(withContext(Dispatchers.IO) { operation() })
} catch (e: Exception) {
AppLogger.e(TAG, "Database operation failed", e)
promise.reject("DB_ERROR", e.message, e)
@@ -326,7 +238,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
try {
reactApplicationContext.startForegroundService(serviceIntent)
moduleScope.launch(Dispatchers.IO) {
- dbHelper.saveSetting("tracking_enabled", "true")
+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
}
promise.resolve(null)
} catch (e: Exception) {
@@ -343,7 +255,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
reactApplicationContext.stopService(intent)
moduleScope.launch(Dispatchers.IO) {
- dbHelper.saveSetting("tracking_enabled", "false")
+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
}
}
@@ -406,146 +318,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise.reject("ERR_NOT_DEBUG", "insertDummyData is only available in debug builds")
return
}
- executeAsync(promise) {
- val now = System.currentTimeMillis() / 1000
- var count = 0
-
- // Realistic scenario: Home (Friedrichshain) → Supermarket → Gym → Home
- // All locations follow real Berlin streets for plausible GPS tracks.
-
- // Home: Boxhagener Platz area, Friedrichshain
- // Supermarket: REWE on Warschauer Str (~1.2 km south)
- // Gym: FitX Ostkreuz (~1.5 km south-east of supermarket)
-
- // Trip 1: Home → Supermarket (driving, ~12 min)
- val trip1 = arrayOf(
- // lat lon alt speed acc
- doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0), // parked at home
- doubleArrayOf(52.51390, 13.45780, 37.0, 3.5, 5.0), // pulling out
- doubleArrayOf(52.51310, 13.45650, 36.0, 8.2, 4.0), // Grünberger Str
- doubleArrayOf(52.51220, 13.45490, 35.0, 11.5, 3.5), // heading south
- doubleArrayOf(52.51120, 13.45340, 35.0, 12.8, 3.0), // Revaler Str
- doubleArrayOf(52.50980, 13.45220, 34.0, 10.1, 4.0), // turning onto Warschauer
- doubleArrayOf(52.50870, 13.45100, 34.0, 8.7, 3.5), // Warschauer Str south
- doubleArrayOf(52.50760, 13.44950, 33.0, 11.3, 3.0), // passing S-Bahn bridge
- doubleArrayOf(52.50650, 13.44820, 33.0, 9.4, 4.0), // Stralauer Allee
- doubleArrayOf(52.50560, 13.44710, 33.0, 6.2, 4.5), // slowing down
- doubleArrayOf(52.50490, 13.44650, 32.0, 2.1, 5.0), // arriving
- doubleArrayOf(52.50460, 13.44630, 32.0, 0.3, 4.0) // parked at supermarket
- )
-
- // Trip 2: Supermarket → Gym (driving, ~8 min)
- val trip2 = arrayOf(
- doubleArrayOf(52.50460, 13.44630, 32.0, 0.5, 4.0), // leaving supermarket
- doubleArrayOf(52.50430, 13.44700, 32.0, 5.8, 4.5), // pulling out east
- doubleArrayOf(52.50380, 13.44890, 33.0, 10.2, 3.5), // Stralauer Allee east
- doubleArrayOf(52.50340, 13.45120, 33.0, 12.5, 3.0), // along the Spree
- doubleArrayOf(52.50310, 13.45380, 34.0, 11.8, 3.5), // heading east
- doubleArrayOf(52.50270, 13.45640, 34.0, 9.6, 4.0), // Modersohnstr area
- doubleArrayOf(52.50230, 13.45900, 35.0, 8.3, 4.0), // near Ostkreuz
- doubleArrayOf(52.50180, 13.46100, 35.0, 5.1, 4.5), // slowing for turn
- doubleArrayOf(52.50150, 13.46250, 35.0, 2.4, 5.0), // arriving at gym
- doubleArrayOf(52.50140, 13.46280, 35.0, 0.2, 4.0) // parked at gym
- )
-
- // Trip 3: Gym → Home (driving, ~14 min, slightly different route)
- val trip3 = arrayOf(
- doubleArrayOf(52.50140, 13.46280, 35.0, 0.4, 4.0), // leaving gym
- doubleArrayOf(52.50190, 13.46180, 35.0, 4.2, 4.5), // pulling out
- doubleArrayOf(52.50280, 13.45980, 34.0, 9.7, 3.5), // Sonntagstr north
- doubleArrayOf(52.50390, 13.45820, 34.0, 11.4, 3.0), // heading north-west
- doubleArrayOf(52.50510, 13.45700, 33.0, 12.1, 3.5), // Simplonstr
- doubleArrayOf(52.50630, 13.45590, 33.0, 10.5, 4.0), // crossing rail tracks
- doubleArrayOf(52.50740, 13.45480, 34.0, 8.9, 3.5), // Warschauer north
- doubleArrayOf(52.50860, 13.45360, 34.0, 11.0, 3.0), // RAW-Gelände area
- doubleArrayOf(52.50970, 13.45280, 35.0, 9.3, 4.0), // Revaler Str
- doubleArrayOf(52.51080, 13.45370, 36.0, 10.8, 3.5), // turning onto Grünberger
- doubleArrayOf(52.51190, 13.45490, 37.0, 8.2, 4.0), // Grünberger Str north
- doubleArrayOf(52.51290, 13.45620, 37.0, 6.5, 4.5), // approaching home
- doubleArrayOf(52.51370, 13.45740, 38.0, 3.1, 5.0), // slowing down
- doubleArrayOf(52.51420, 13.45830, 38.0, 0.2, 4.0) // back home
- )
-
- // Generate data for the past 7 days with slight daily variation
- for (dayOffset in 6 downTo 0) {
- val dayMidnight = now - (now % 86400) - (dayOffset * 86400L)
- val battery = 92 - (dayOffset * 3)
- // Small daily jitter so tracks aren't perfectly identical
- val jitterLat = (dayOffset * 0.00003) - 0.00009
- val jitterLon = (dayOffset * 0.00002) - 0.00006
-
- // Trip 1: Home → Supermarket, depart 09:30, ~30s between points
- val t1Start = dayMidnight + 9 * 3600 + 1800
- for ((i, wp) in trip1.withIndex()) {
- val ts = t1Start + (i * 30L)
- if (ts > now) break
- dbHelper.saveLocation(
- wp[0] + jitterLat, wp[1] + jitterLon,
- wp[4], wp[2].toInt(), wp[3],
- null, battery - i, 1, ts
- )
- count++
- }
-
- // Gap: 45 min at supermarket (triggers trip segmentation at 15-min threshold)
-
- // Trip 2: Supermarket → Gym, depart 10:20, ~30s between points
- val t2Start = dayMidnight + 10 * 3600 + 1200
- for ((i, wp) in trip2.withIndex()) {
- val ts = t2Start + (i * 30L)
- if (ts > now) break
- dbHelper.saveLocation(
- wp[0] + jitterLat, wp[1] + jitterLon,
- wp[4], wp[2].toInt(), wp[3],
- null, battery - 15 - i, 2, ts
- )
- count++
- }
-
- // Gap: 1h 30min at gym
-
- // Trip 3: Gym → Home, depart 12:00, ~30s between points
- val t3Start = dayMidnight + 12 * 3600
- for ((i, wp) in trip3.withIndex()) {
- val ts = t3Start + (i * 30L)
- if (ts > now) break
- dbHelper.saveLocation(
- wp[0] + jitterLat, wp[1] + jitterLon,
- wp[4], wp[2].toInt(), wp[3],
- null, battery - 30 - i, 1, ts
- )
- count++
- }
-
- // Skip afternoon trip on some days for variety
- if (dayOffset % 2 == 0) continue
-
- // Trip 4 (some days): Quick evening walk, depart 18:00
- // Short loop around Boxhagener Platz (~10 min walk)
- val walkTrip = arrayOf(
- doubleArrayOf(52.51420, 13.45830, 38.0, 1.2, 6.0),
- doubleArrayOf(52.51450, 13.45900, 38.0, 1.4, 5.5),
- doubleArrayOf(52.51480, 13.45970, 38.0, 1.3, 5.0),
- doubleArrayOf(52.51500, 13.46050, 38.0, 1.5, 5.5),
- doubleArrayOf(52.51480, 13.46130, 38.0, 1.4, 6.0),
- doubleArrayOf(52.51450, 13.46080, 38.0, 1.3, 5.5),
- doubleArrayOf(52.51430, 13.45970, 38.0, 1.2, 5.0),
- doubleArrayOf(52.51420, 13.45830, 38.0, 0.3, 6.0)
- )
- val t4Start = dayMidnight + 18 * 3600
- for ((i, wp) in walkTrip.withIndex()) {
- val ts = t4Start + (i * 75L)
- if (ts > now) break
- dbHelper.saveLocation(
- wp[0] + jitterLat, wp[1] + jitterLon,
- wp[4], wp[2].toInt(), wp[3],
- null, battery - 45 - i, 1, ts
- )
- count++
- }
- }
- count
- }
+ executeAsync(promise) { DebugSeedData.insertDummyData(dbHelper) }
}
@ReactMethod
@@ -559,35 +332,24 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- @ReactMethod
- fun clearSentHistory(promise: Promise) = executeAsync(promise) {
- val deleted = dbHelper.clearSentHistory()
- moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }
- deleted
+ @ReactMethod
+ fun clearSentHistory(promise: Promise) = executeAsync(promise) {
+ deleteThenVacuum { dbHelper.clearSentHistory() }
}
-
+
@ReactMethod
fun clearQueue(promise: Promise) = executeAsync(promise) {
- val deleted = dbHelper.clearQueue()
- refreshNotificationIfTracking()
- moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }
- deleted
+ deleteThenVacuum(refresh = true) { dbHelper.clearQueue() }
}
-
+
@ReactMethod
fun clearAllLocations(promise: Promise) = executeAsync(promise) {
- val deleted = dbHelper.clearAllLocations()
- refreshNotificationIfTracking()
- moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }
- deleted
+ deleteThenVacuum(refresh = true) { dbHelper.clearAllLocations() }
}
-
+
@ReactMethod
fun deleteOlderThan(days: Int, promise: Promise) = executeAsync(promise) {
- val deleted = dbHelper.deleteOlderThan(days)
- refreshNotificationIfTracking()
- moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }
- deleted
+ deleteThenVacuum(refresh = true) { dbHelper.deleteOlderThan(days) }
}
@ReactMethod
@@ -597,15 +359,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
private fun triggerZoneRecheck() {
+ val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
+ if (!isTracking) return
try {
startServiceWithAction(LocationForegroundService.ACTION_RECHECK_ZONE)
} catch (e: Exception) {
- AppLogger.e(TAG, "Failed to trigger zone recheck", e)
+ AppLogger.w(TAG, "Zone recheck skipped: service not running")
}
}
private fun refreshNotificationIfTracking() {
- val isTracking = dbHelper.getSetting("tracking_enabled", "false") == "true"
+ val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
if (isTracking) {
try {
startServiceWithAction(LocationForegroundService.ACTION_REFRESH_NOTIFICATION)
@@ -615,10 +379,28 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- /**
- * Creates a geofence and invalidates cache to ensure the
- * Foreground Service recognizes the change immediately.
- */
+ /** Invalidates the geofence cache and asks the service to re-evaluate pause zones so the change takes effect immediately. */
+ private fun afterGeofenceMutation(changed: Boolean) {
+ if (!changed) return
+ geofenceHelper.invalidateCache()
+ triggerZoneRecheck()
+ }
+
+ /** Invalidates the profile cache and asks the service to re-evaluate active profile so the change takes effect immediately. */
+ private fun afterProfileMutation(changed: Boolean) {
+ if (!changed) return
+ profileHelper.invalidateCache()
+ triggerProfileRecheck()
+ }
+
+ /** delete() runs inline; vacuum is fire-and-forget so callers return immediately. */
+ private fun deleteThenVacuum(refresh: Boolean = false, delete: () -> Int): Int {
+ val deleted = delete()
+ if (refresh) refreshNotificationIfTracking()
+ moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }
+ return deleted
+ }
+
@ReactMethod
fun createGeofence(
name: String,
@@ -633,21 +415,25 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
heartbeatIntervalMinutes: Int,
promise: Promise
) = executeAsync(promise) {
- val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes, heartbeatEnabled, heartbeatIntervalMinutes)
- if (result > 0) {
- geofenceHelper.invalidateCache()
- triggerZoneRecheck()
- }
- result
+ val id = geofenceHelper.insertGeofence(
+ name = name,
+ lat = lat,
+ lon = lon,
+ radius = radius,
+ pauseTracking = pause,
+ pauseOnWifi = pauseOnWifi,
+ pauseOnMotionless = pauseOnMotionless,
+ motionlessTimeoutMinutes = motionlessTimeoutMinutes,
+ heartbeatEnabled = heartbeatEnabled,
+ heartbeatIntervalMinutes = heartbeatIntervalMinutes,
+ )
+ afterGeofenceMutation(id > 0)
+ id
}
- /**
- * Fetches all geofences for the UI.
- * Does not invalidate cache as this is a read-only operation.
- */
@ReactMethod
- fun getGeofences(promise: Promise) = executeAsync(promise) {
- geofenceHelper.getGeofencesAsArray()
+ fun getGeofences(promise: Promise) = executeAsync(promise) {
+ geofenceHelper.getGeofencesAsArray()
}
@ReactMethod
@@ -666,75 +452,50 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
heartbeatIntervalMinutes: Int?,
promise: Promise
) = executeAsync(promise) {
- val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause, pauseOnWifi, pauseOnMotionless, motionlessTimeoutMinutes, heartbeatEnabled, heartbeatIntervalMinutes)
- if (result) {
- geofenceHelper.invalidateCache()
- triggerZoneRecheck()
- }
- result
+ val changed = geofenceHelper.updateGeofence(
+ id = id,
+ name = name,
+ lat = lat,
+ lon = lon,
+ radius = radius,
+ enabled = enabled,
+ pauseTracking = pause,
+ pauseOnWifi = pauseOnWifi,
+ pauseOnMotionless = pauseOnMotionless,
+ motionlessTimeoutMinutes = motionlessTimeoutMinutes,
+ heartbeatEnabled = heartbeatEnabled,
+ heartbeatIntervalMinutes = heartbeatIntervalMinutes,
+ )
+ afterGeofenceMutation(changed)
+ changed
}
- /**
- * Deletes a geofence and invalidates cache to ensure the
- * Foreground Service recognizes the change immediately.
- */
- @ReactMethod
- fun deleteGeofence(id: Int, promise: Promise) = executeAsync(promise) {
- val result = geofenceHelper.deleteGeofence(id)
- if (result) {
- geofenceHelper.invalidateCache()
- triggerZoneRecheck()
- }
- result
+ @ReactMethod
+ fun deleteGeofence(id: Int, promise: Promise) = executeAsync(promise) {
+ val changed = geofenceHelper.deleteGeofence(id)
+ afterGeofenceMutation(changed)
+ changed
}
+ /**
+ * Reads the current pause state from persisted settings written by the service
+ * on every enter/exit transition. Avoids the location API so opening screens that
+ * call this does not trigger Android's location-access indicator.
+ */
@ReactMethod
- fun checkCurrentPauseZone(promise: Promise) {
- val provider = LocationProviderFactory.create(reactApplicationContext)
+ fun checkCurrentPauseZone(promise: Promise) = executeAsync(promise) {
+ val zoneName = dbHelper.getSetting(SettingsKeys.PAUSE_ZONE_NAME)
+ if (zoneName.isNullOrBlank()) return@executeAsync null
- try {
- provider.getLastLocation(
- onSuccess = { loc ->
- if (loc == null) {
- promise.resolve(null)
- } else {
- moduleScope.launch {
- try {
- val zone = withContext(Dispatchers.IO) {
- geofenceHelper.getPauseZone(loc)
- }
- if (zone == null) {
- promise.resolve(null)
- } else {
- val db = DatabaseHelper.getInstance(reactApplicationContext)
- val reason = withContext(Dispatchers.IO) {
- when {
- db.getSetting("pause_zone_wifi_active") == "true" -> "wifi"
- db.getSetting("pause_zone_motionless_active") == "true" -> "motionless"
- else -> null
- }
- }
- val result = Arguments.createMap().apply {
- putString("zoneName", zone.name)
- putString("pauseReason", reason)
- }
- promise.resolve(result)
- }
- } catch (e: Exception) {
- AppLogger.e(TAG, "Pause zone check failed", e)
- promise.resolve(null)
- }
- }
- }
- },
- onFailure = { e ->
- AppLogger.e(TAG, "Failed to get location for pause zone check", e)
- promise.resolve(null)
- }
- )
- } catch (e: SecurityException) {
- AppLogger.e(TAG, "Location permission not granted", e)
- promise.resolve(null)
+ val reason = when {
+ dbHelper.getSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE) == "true" -> "wifi"
+ dbHelper.getSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE) == "true" -> "motionless"
+ else -> null
+ }
+
+ Arguments.createMap().apply {
+ putString("zoneName", zoneName)
+ putString("pauseReason", reason)
}
}
@@ -758,18 +519,15 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
conditionType = config.getString("conditionType") ?: ProfileConstants.CONDITION_CHARGING,
speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))
config.getDouble("speedThreshold").toFloat() else null,
- deactivationDelaySeconds = config.getInt("deactivationDelaySeconds")
+ deactivationDelaySeconds = config.getInt("deactivationDelaySeconds"),
)
- if (id > 0) {
- profileHelper.invalidateCache()
- triggerProfileRecheck()
- }
+ afterProfileMutation(id > 0)
id
}
@ReactMethod
fun updateProfile(config: ReadableMap, promise: Promise) = executeAsync(promise) {
- val result = profileHelper.updateProfile(
+ val changed = profileHelper.updateProfile(
id = config.getInt("id"),
name = config.getStringOrNull("name")?.trim(),
intervalMs = config.getDoubleOrNull("intervalMs")?.toLong(),
@@ -781,23 +539,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
config.getDouble("speedThreshold").toFloat() else null,
hasSpeedThreshold = config.hasKey("speedThreshold"),
deactivationDelaySeconds = config.getIntOrNull("deactivationDelaySeconds"),
- enabled = config.getBooleanOrNull("enabled")
+ enabled = config.getBooleanOrNull("enabled"),
)
- if (result) {
- profileHelper.invalidateCache()
- triggerProfileRecheck()
- }
- result
+ afterProfileMutation(changed)
+ changed
}
@ReactMethod
fun deleteProfile(id: Int, promise: Promise) = executeAsync(promise) {
- val result = profileHelper.deleteProfile(id)
- if (result) {
- profileHelper.invalidateCache()
- triggerProfileRecheck()
- }
- result
+ val changed = profileHelper.deleteProfile(id)
+ afterProfileMutation(changed)
+ changed
}
@ReactMethod
@@ -817,7 +569,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
private fun triggerProfileRecheck() {
- val isTracking = dbHelper.getSetting("tracking_enabled", "false") == "true"
+ val isTracking = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
if (isTracking) {
try {
startServiceWithAction(LocationForegroundService.ACTION_RECHECK_PROFILES)
@@ -983,20 +735,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun saveAuthConfig(config: ReadableMap, promise: Promise) = executeAsync(promise) {
- config.getString("authType")?.let {
- secureStorage.putString(SecureStorageHelper.KEY_AUTH_TYPE, it)
- }
- config.getString("username")?.let {
- secureStorage.putString(SecureStorageHelper.KEY_USERNAME, it)
- }
- config.getString("password")?.let {
- secureStorage.putString(SecureStorageHelper.KEY_PASSWORD, it)
- }
- config.getString("bearerToken")?.let {
- secureStorage.putString(SecureStorageHelper.KEY_BEARER_TOKEN, it)
- }
- config.getString("customHeaders")?.let {
- secureStorage.putString(SecureStorageHelper.KEY_CUSTOM_HEADERS, it)
+ AUTH_CONFIG_KEYS.forEach { (jsKey, storageKey) ->
+ config.getString(jsKey)?.let { secureStorage.putString(storageKey, it) }
}
true
}
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 5c248951..ca462061 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
@@ -8,13 +8,12 @@ package com.Colota.data
import android.content.ContentValues
import android.database.Cursor
import com.Colota.util.AppLogger
+import com.Colota.util.geo.haversineDistance
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
-import android.database.sqlite.SQLiteStatement
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import java.util.*
+import java.time.LocalDate
+import java.time.ZoneId
import org.json.JSONObject
/**
@@ -48,6 +47,24 @@ class DatabaseHelper private constructor(context: Context) :
private const val TAG = "LocationDB"
private const val TRIP_GAP_SECONDS = 900L // 15 min, matches JS segmentTrips
+ private const val CREATE_PROFILES_TABLE = """
+ CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ interval_ms INTEGER NOT NULL,
+ min_update_distance REAL NOT NULL,
+ sync_interval_seconds INTEGER NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 0,
+ condition_type TEXT NOT NULL,
+ speed_threshold REAL,
+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL
+ )
+ """
+ private const val CREATE_PROFILES_INDEX =
+ "CREATE INDEX IF NOT EXISTS idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)"
+
@Volatile
private var INSTANCE: DatabaseHelper? = null
@@ -65,8 +82,6 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- private var incrementRetryStmt: SQLiteStatement? = null
-
override fun onCreate(db: SQLiteDatabase) {
AppLogger.i(TAG, "Creating database v$DATABASE_VERSION")
db.execSQL("""
@@ -126,28 +141,14 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- db.execSQL("""
- CREATE TABLE $TABLE_PROFILES (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL,
- interval_ms INTEGER NOT NULL,
- min_update_distance REAL NOT NULL,
- sync_interval_seconds INTEGER NOT NULL,
- priority INTEGER NOT NULL DEFAULT 0,
- condition_type TEXT NOT NULL,
- speed_threshold REAL,
- deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
- enabled INTEGER NOT NULL DEFAULT 1,
- created_at INTEGER NOT NULL
- )
- """)
+ db.execSQL(CREATE_PROFILES_TABLE)
db.execSQL("CREATE INDEX idx_queue_created ON $TABLE_QUEUE(created_at)")
db.execSQL("CREATE INDEX idx_queue_location ON $TABLE_QUEUE(location_id)")
db.execSQL("CREATE INDEX idx_locations_timestamp ON $TABLE_LOCATIONS(timestamp DESC)")
db.execSQL("CREATE INDEX idx_locations_created ON $TABLE_LOCATIONS(created_at DESC)")
db.execSQL("CREATE INDEX idx_geofences_enabled ON $TABLE_GEOFENCES(enabled, pause_tracking)")
- db.execSQL("CREATE INDEX idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
+ db.execSQL(CREATE_PROFILES_INDEX)
db.execSQL("CREATE INDEX idx_queue_retry ON $TABLE_QUEUE(retry_count)")
prepopulateSettings(db)
@@ -169,7 +170,7 @@ class DatabaseHelper private constructor(context: Context) :
"syncSsid" to "",
"customFields" to "[]",
"hasCompletedSetup" to "false",
- "tracking_enabled" to "false",
+ SettingsKeys.TRACKING_ENABLED to "false",
"apiTemplate" to "custom",
"syncPreset" to "instant",
"httpMethod" to "POST"
@@ -201,22 +202,8 @@ class DatabaseHelper private constructor(context: Context) :
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
AppLogger.i(TAG, "Upgrading database from v$oldVersion to v$newVersion")
if (oldVersion < 2) {
- db.execSQL("""
- CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT NOT NULL,
- interval_ms INTEGER NOT NULL,
- min_update_distance REAL NOT NULL,
- sync_interval_seconds INTEGER NOT NULL,
- priority INTEGER NOT NULL DEFAULT 0,
- condition_type TEXT NOT NULL,
- speed_threshold REAL,
- deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
- enabled INTEGER NOT NULL DEFAULT 1,
- created_at INTEGER NOT NULL
- )
- """)
- db.execSQL("CREATE INDEX IF NOT EXISTS idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")
+ db.execSQL(CREATE_PROFILES_TABLE)
+ db.execSQL(CREATE_PROFILES_INDEX)
}
if (oldVersion < 3) {
db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN sent INTEGER NOT NULL DEFAULT 0")
@@ -240,16 +227,6 @@ class DatabaseHelper private constructor(context: Context) :
db.execSQL("PRAGMA synchronous = NORMAL") // faster writes, safe with WAL
db.execSQL("PRAGMA foreign_keys = ON")
}
-
- incrementRetryStmt = db.compileStatement(
- "UPDATE $TABLE_QUEUE SET retry_count = retry_count + 1, last_error = ? WHERE id = ?"
- )
- }
-
- override fun close() {
- incrementRetryStmt?.close()
- incrementRetryStmt = null
- super.close()
}
@@ -466,14 +443,11 @@ class DatabaseHelper private constructor(context: Context) :
writableDatabase.delete(TABLE_LOCATIONS, "id IN ($placeholders)", args)
}
- @Synchronized
fun incrementRetryCount(queueId: Long, error: String? = null) {
- val stmt = incrementRetryStmt ?: return // Exit if statement is null
-
- stmt.clearBindings()
- stmt.bindString(1, error ?: "")
- stmt.bindLong(2, queueId)
- stmt.executeUpdateDelete()
+ writableDatabase.execSQL(
+ "UPDATE $TABLE_QUEUE SET retry_count = retry_count + 1, last_error = ? WHERE id = ?",
+ arrayOf<Any>(error ?: "", queueId)
+ )
}
@@ -504,13 +478,6 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- fun markLocationSent(locationId: Long) {
- writableDatabase.execSQL(
- "UPDATE $TABLE_LOCATIONS SET sent = 1 WHERE id = ?",
- arrayOf(locationId)
- )
- }
-
fun markLocationsSent(locationIds: List<Long>) {
if (locationIds.isEmpty()) return
val placeholders = locationIds.joinToString(",") { "?" }
@@ -738,24 +705,8 @@ class DatabaseHelper private constructor(context: Context) :
return stats
}
- internal fun haversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
- val r = 6371000.0
- val dLat = Math.toRadians(lat2 - lat1)
- val dLon = Math.toRadians(lon2 - lon1)
- val a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
- Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
- Math.sin(dLon / 2) * Math.sin(dLon / 2)
- return r * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
- }
-
- private fun getTodayStartTimestamp(): Long {
- return Calendar.getInstance().apply {
- set(Calendar.HOUR_OF_DAY, 0)
- set(Calendar.MINUTE, 0)
- set(Calendar.SECOND, 0)
- set(Calendar.MILLISECOND, 0)
- }.timeInMillis / 1000 // convert to seconds
- }
+ private fun getTodayStartTimestamp(): Long =
+ LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond()
}
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 8cd5f698..57965389 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
@@ -6,20 +6,22 @@
package com.Colota.data
import android.content.ContentValues
-import com.Colota.util.AppLogger
-import com.Colota.util.TimedCache
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
import com.facebook.react.bridge.WritableArray
-import kotlin.math.*
class GeofenceHelper(private val context: Context) {
private val dbHelper by lazy { DatabaseHelper.getInstance(context) }
-
- private val geofenceCache = TimedCache(30000L) { loadGeofencesFromDB() }
+ 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,
val lat: Double,
@@ -29,29 +31,12 @@ class GeofenceHelper(private val context: Context) {
val pauseOnMotionless: Boolean = false,
val motionlessTimeoutMinutes: Int = 10,
val heartbeatEnabled: Boolean = false,
- val heartbeatIntervalMinutes: Int = 15
+ val heartbeatIntervalMinutes: Int = 15,
)
companion object {
private const val TAG = "GeofenceHelper"
- internal const val EARTH_RADIUS_METERS = 6371000.0
-
- /** Haversine formula — accurate at any distance on Earth. */
- internal fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
- val dLat = Math.toRadians(lat2 - lat1)
- val dLon = Math.toRadians(lon2 - lon1)
- val a = sin(dLat / 2).pow(2) +
- cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2).pow(2)
- return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))
- }
-
- internal fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radius: Double): Boolean {
- // Fast bounding-box rejection (lon degrees shrink at higher latitudes)
- val maxLatDeg = radius / 111000.0
- val maxLonDeg = radius / (111000.0 * cos(Math.toRadians(lat1)))
- if (Math.abs(lat1 - lat2) > maxLatDeg || Math.abs(lon1 - lon2) > maxLonDeg) return false
- return calculateDistance(lat1, lon1, lat2, lon2) <= radius
- }
+ private const val CACHE_TTL_MS = 30_000L
}
fun getGeofenceByName(name: String): CachedGeofence? =
@@ -63,12 +48,12 @@ class GeofenceHelper(private val context: Context) {
isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)
}
if (match != null) {
- val dist = calculateDistance(location.latitude, location.longitude, match.lat, match.lon)
+ val dist = haversineDistance(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
}
-
+
fun invalidateCache() {
geofenceCache.invalidate()
AppLogger.d(TAG, "Geofence cache invalidated")
@@ -81,7 +66,11 @@ 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", "heartbeat_enabled", "heartbeat_interval_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 ->
@@ -97,15 +86,15 @@ class GeofenceHelper(private val context: Context) {
while (cursor.moveToNext()) {
fences.add(CachedGeofence(
- cursor.getString(nameIdx),
- cursor.getDouble(latIdx),
- cursor.getDouble(lonIdx),
- cursor.getDouble(radIdx),
- cursor.getInt(wifiIdx) == 1,
- cursor.getInt(motionlessIdx) == 1,
- cursor.getInt(timeoutIdx),
- cursor.getInt(heartbeatIdx) == 1,
- cursor.getInt(heartbeatIntervalIdx)
+ name = cursor.getString(nameIdx),
+ lat = cursor.getDouble(latIdx),
+ lon = cursor.getDouble(lonIdx),
+ radius = cursor.getDouble(radIdx),
+ pauseOnWifi = cursor.getInt(wifiIdx) == 1,
+ pauseOnMotionless = cursor.getInt(motionlessIdx) == 1,
+ motionlessTimeoutMinutes = cursor.getInt(timeoutIdx),
+ heartbeatEnabled = cursor.getInt(heartbeatIdx) == 1,
+ heartbeatIntervalMinutes = cursor.getInt(heartbeatIntervalIdx),
))
}
}
@@ -130,9 +119,14 @@ class GeofenceHelper(private val context: Context) {
val nameIdx = cursor.getColumnIndexOrThrow("name")
val latIdx = cursor.getColumnIndexOrThrow("latitude")
val lonIdx = cursor.getColumnIndexOrThrow("longitude")
- val radiusIdx = cursor.getColumnIndexOrThrow("radius")
+ val radIdx = cursor.getColumnIndexOrThrow("radius")
val enabledIdx = cursor.getColumnIndexOrThrow("enabled")
val pauseIdx = cursor.getColumnIndexOrThrow("pause_tracking")
+ 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")
val createdIdx = cursor.getColumnIndexOrThrow("created_at")
while (cursor.moveToNext()) {
@@ -141,14 +135,14 @@ class GeofenceHelper(private val context: Context) {
putString("name", cursor.getString(nameIdx))
putDouble("lat", cursor.getDouble(latIdx))
putDouble("lon", cursor.getDouble(lonIdx))
- putDouble("radius", cursor.getDouble(radiusIdx))
+ putDouble("radius", cursor.getDouble(radIdx))
putBoolean("enabled", cursor.getInt(enabledIdx) == 1)
putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)
- 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")))
+ putBoolean("pauseOnWifi", cursor.getInt(wifiIdx) == 1)
+ putBoolean("pauseOnMotionless", cursor.getInt(motionlessIdx) == 1)
+ putInt("motionlessTimeoutMinutes", cursor.getInt(timeoutIdx))
+ putBoolean("heartbeatEnabled", cursor.getInt(heartbeatIdx) == 1)
+ putInt("heartbeatIntervalMinutes", cursor.getInt(heartbeatIntervalIdx))
putDouble("createdAt", cursor.getLong(createdIdx).toDouble())
})
}
@@ -160,28 +154,26 @@ class GeofenceHelper(private val context: Context) {
return array
}
- /**
- * Inserts a new geofence into the database.
- */
+ /** Inserts a geofence. Returns the new row id, or -1 on failure. */
fun insertGeofence(
name: String,
lat: Double,
lon: Double,
- rad: Double,
- pause: Boolean,
+ radius: Double,
+ pauseTracking: Boolean,
pauseOnWifi: Boolean = false,
pauseOnMotionless: Boolean = false,
motionlessTimeoutMinutes: Int = 10,
heartbeatEnabled: Boolean = false,
- heartbeatIntervalMinutes: Int = 15
+ heartbeatIntervalMinutes: Int = 15,
): Int {
val values = ContentValues().apply {
put("name", name)
put("latitude", lat)
put("longitude", lon)
- put("radius", rad)
+ put("radius", radius)
put("enabled", 1)
- put("pause_tracking", if (pause) 1 else 0)
+ put("pause_tracking", if (pauseTracking) 1 else 0)
put("pause_on_wifi", if (pauseOnWifi) 1 else 0)
put("pause_on_motionless", if (pauseOnMotionless) 1 else 0)
put("motionless_timeout_minutes", motionlessTimeoutMinutes)
@@ -189,61 +181,57 @@ class GeofenceHelper(private val context: Context) {
put("heartbeat_interval_minutes", heartbeatIntervalMinutes)
put("created_at", System.currentTimeMillis() / 1000)
}
-
+
return dbHelper.writableDatabase
.insert(DatabaseHelper.TABLE_GEOFENCES, null, values)
.toInt()
}
-
- /**
- * Updates geofence with only provided fields.
- */
+
+ /** PATCH-style update: null args leave the column untouched. Returns false if nothing changed. */
fun updateGeofence(
id: Int,
- name: String?,
- lat: Double?,
- lon: Double?,
- rad: Double?,
- en: Boolean?,
- pause: Boolean?,
+ name: String? = null,
+ lat: Double? = null,
+ lon: Double? = null,
+ radius: Double? = null,
+ enabled: Boolean? = null,
+ pauseTracking: Boolean? = null,
pauseOnWifi: Boolean? = null,
pauseOnMotionless: Boolean? = null,
motionlessTimeoutMinutes: Int? = null,
heartbeatEnabled: Boolean? = null,
- heartbeatIntervalMinutes: Int? = null
+ heartbeatIntervalMinutes: Int? = null,
): Boolean {
val values = ContentValues().apply {
name?.let { put("name", it) }
lat?.let { put("latitude", it) }
lon?.let { put("longitude", it) }
- rad?.let { put("radius", it) }
- en?.let { put("enabled", if (it) 1 else 0) }
- pause?.let { put("pause_tracking", if (it) 1 else 0) }
+ radius?.let { put("radius", it) }
+ enabled?.let { put("enabled", if (it) 1 else 0) }
+ pauseTracking?.let { put("pause_tracking", if (it) 1 else 0) }
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
-
+
return dbHelper.writableDatabase.update(
- DatabaseHelper.TABLE_GEOFENCES,
- values,
- "id = ?",
+ DatabaseHelper.TABLE_GEOFENCES,
+ values,
+ "id = ?",
arrayOf(id.toString())
) > 0
}
- /**
- * Deletes a geofence by ID.
- */
+ /** Deletes a geofence by id. */
fun deleteGeofence(id: Int): Boolean {
return dbHelper.writableDatabase.delete(
- DatabaseHelper.TABLE_GEOFENCES,
- "id = ?",
+ DatabaseHelper.TABLE_GEOFENCES,
+ "id = ?",
arrayOf(id.toString())
) > 0
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
index 4b074674..f5b72626 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
@@ -6,10 +6,10 @@
package com.Colota.data
import android.content.ContentValues
+import android.content.Context
import com.Colota.util.AppLogger
import com.Colota.service.ProfileConstants
import com.Colota.util.TimedCache
-import android.content.Context
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableArray
@@ -28,7 +28,7 @@ class ProfileHelper(private val context: Context) {
val priority: Int,
val conditionType: String,
val speedThreshold: Float?,
- val deactivationDelaySeconds: Int
+ val deactivationDelaySeconds: Int,
)
companion object {
@@ -42,21 +42,6 @@ class ProfileHelper(private val context: Context) {
fun getEnabledProfiles(): List<CachedProfile> = profileCache.get()
- private fun cursorToProfile(cursor: android.database.Cursor): CachedProfile {
- val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
- return CachedProfile(
- id = cursor.getInt(cursor.getColumnIndexOrThrow("id")),
- name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
- intervalMs = cursor.getLong(cursor.getColumnIndexOrThrow("interval_ms")),
- minUpdateDistance = cursor.getFloat(cursor.getColumnIndexOrThrow("min_update_distance")),
- syncIntervalSeconds = cursor.getInt(cursor.getColumnIndexOrThrow("sync_interval_seconds")),
- priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority")),
- conditionType = cursor.getString(cursor.getColumnIndexOrThrow("condition_type")),
- speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
- deactivationDelaySeconds = cursor.getInt(cursor.getColumnIndexOrThrow("deactivation_delay_seconds"))
- )
- }
-
private fun loadEnabledProfilesFromDB(): List<CachedProfile> {
return try {
val profiles = mutableListOf<CachedProfile>()
@@ -65,14 +50,34 @@ class ProfileHelper(private val context: Context) {
arrayOf(
"id", "name", "interval_ms", "min_update_distance",
"sync_interval_seconds", "priority", "condition_type",
- "speed_threshold", "deactivation_delay_seconds"
+ "speed_threshold", "deactivation_delay_seconds",
),
"enabled = 1",
null, null, null,
"priority DESC"
).use { cursor ->
+ val idIdx = cursor.getColumnIndexOrThrow("id")
+ val nameIdx = cursor.getColumnIndexOrThrow("name")
+ val intervalIdx = cursor.getColumnIndexOrThrow("interval_ms")
+ val minDistIdx = cursor.getColumnIndexOrThrow("min_update_distance")
+ val syncIdx = cursor.getColumnIndexOrThrow("sync_interval_seconds")
+ val priorityIdx = cursor.getColumnIndexOrThrow("priority")
+ val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
+ val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
+ val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
+
while (cursor.moveToNext()) {
- profiles.add(cursorToProfile(cursor))
+ profiles.add(CachedProfile(
+ id = cursor.getInt(idIdx),
+ name = cursor.getString(nameIdx),
+ intervalMs = cursor.getLong(intervalIdx),
+ minUpdateDistance = cursor.getFloat(minDistIdx),
+ syncIntervalSeconds = cursor.getInt(syncIdx),
+ priority = cursor.getInt(priorityIdx),
+ conditionType = cursor.getString(conditionIdx),
+ speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
+ deactivationDelaySeconds = cursor.getInt(delayIdx),
+ ))
}
}
profiles
@@ -94,10 +99,10 @@ class ProfileHelper(private val context: Context) {
val idIdx = cursor.getColumnIndexOrThrow("id")
val nameIdx = cursor.getColumnIndexOrThrow("name")
val intervalIdx = cursor.getColumnIndexOrThrow("interval_ms")
- val distIdx = cursor.getColumnIndexOrThrow("min_update_distance")
+ val minDistIdx = cursor.getColumnIndexOrThrow("min_update_distance")
val syncIdx = cursor.getColumnIndexOrThrow("sync_interval_seconds")
- val prioIdx = cursor.getColumnIndexOrThrow("priority")
- val condIdx = cursor.getColumnIndexOrThrow("condition_type")
+ val priorityIdx = cursor.getColumnIndexOrThrow("priority")
+ val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
val enabledIdx = cursor.getColumnIndexOrThrow("enabled")
@@ -108,10 +113,10 @@ class ProfileHelper(private val context: Context) {
putInt("id", cursor.getInt(idIdx))
putString("name", cursor.getString(nameIdx))
putDouble("intervalMs", cursor.getLong(intervalIdx).toDouble())
- putDouble("minUpdateDistance", cursor.getFloat(distIdx).toDouble())
+ putDouble("minUpdateDistance", cursor.getFloat(minDistIdx).toDouble())
putInt("syncIntervalSeconds", cursor.getInt(syncIdx))
- putInt("priority", cursor.getInt(prioIdx))
- putString("conditionType", cursor.getString(condIdx))
+ putInt("priority", cursor.getInt(priorityIdx))
+ putString("conditionType", cursor.getString(conditionIdx))
if (cursor.isNull(speedIdx)) {
putNull("speedThreshold")
} else {
@@ -138,7 +143,7 @@ class ProfileHelper(private val context: Context) {
priority: Int,
conditionType: String,
speedThreshold: Float?,
- deactivationDelaySeconds: Int
+ deactivationDelaySeconds: Int,
): Int {
val values = ContentValues().apply {
put("name", name)
@@ -147,11 +152,7 @@ class ProfileHelper(private val context: Context) {
put("sync_interval_seconds", syncIntervalSeconds)
put("priority", priority)
put("condition_type", conditionType)
- if (speedThreshold != null) {
- put("speed_threshold", speedThreshold)
- } else {
- putNull("speed_threshold")
- }
+ if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")
put("deactivation_delay_seconds", deactivationDelaySeconds)
put("enabled", 1)
put("created_at", System.currentTimeMillis() / 1000)
@@ -162,18 +163,23 @@ class ProfileHelper(private val context: Context) {
.toInt()
}
+ /**
+ * PATCH-style update: null args leave the column untouched. Returns false if nothing changed.
+ * [speedThreshold] is tri-state because null is a valid column value: set [hasSpeedThreshold]
+ * false to leave it alone, true+null to clear, true+value to write.
+ */
fun updateProfile(
id: Int,
- name: String?,
- intervalMs: Long?,
- minUpdateDistance: Float?,
- syncIntervalSeconds: Int?,
- priority: Int?,
- conditionType: String?,
- speedThreshold: Float?,
- hasSpeedThreshold: Boolean,
- deactivationDelaySeconds: Int?,
- enabled: Boolean?
+ name: String? = null,
+ intervalMs: Long? = null,
+ minUpdateDistance: Float? = null,
+ syncIntervalSeconds: Int? = null,
+ priority: Int? = null,
+ conditionType: String? = null,
+ speedThreshold: Float? = null,
+ hasSpeedThreshold: Boolean = false,
+ deactivationDelaySeconds: Int? = null,
+ enabled: Boolean? = null,
): Boolean {
val values = ContentValues().apply {
name?.let { put("name", it) }
@@ -183,11 +189,7 @@ class ProfileHelper(private val context: Context) {
priority?.let { put("priority", it) }
conditionType?.let { put("condition_type", it) }
if (hasSpeedThreshold) {
- if (speedThreshold != null) {
- put("speed_threshold", speedThreshold)
- } else {
- putNull("speed_threshold")
- }
+ if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")
}
deactivationDelaySeconds?.let { put("deactivation_delay_seconds", it) }
enabled?.let { put("enabled", if (it) 1 else 0) }
@@ -210,5 +212,4 @@ class ProfileHelper(private val context: Context) {
arrayOf(id.toString())
) > 0
}
-
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt
new file mode 100644
index 00000000..bec1a066
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt
@@ -0,0 +1,14 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.data
+
+/** Runtime state keys persisted via DatabaseHelper.saveSetting/getSetting. */
+object SettingsKeys {
+ const val TRACKING_ENABLED = "tracking_enabled"
+ const val PAUSE_ZONE_NAME = "pause_zone_name"
+ const val PAUSE_ZONE_WIFI_ACTIVE = "pause_zone_wifi_active"
+ const val PAUSE_ZONE_MOTIONLESS_ACTIVE = "pause_zone_motionless_active"
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
index 1f063ff1..dfe6222e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
@@ -24,14 +24,10 @@ import com.Colota.data.DatabaseHelper
import com.Colota.util.AppLogger
import java.io.File
import java.io.IOException
-import java.io.OutputStreamWriter
/**
- * WorkManager worker that performs automatic location data export.
- * Runs without the React Native JS runtime - uses native Kotlin converters.
- *
- * Scheduled as a daily periodic worker. On each run it checks whether an
- * export is actually due (daily/weekly/monthly) via AutoExportConfig.isExportDue().
+ * Runs daily and asks AutoExportConfig.isExportDue() whether the configured
+ * daily/weekly/monthly cadence has actually elapsed. Runs without the JS runtime.
*/
class AutoExportWorker(
private val appContext: Context,
@@ -43,8 +39,8 @@ class AutoExportWorker(
private const val CHANNEL_ID = "auto_export"
private const val NOTIFICATION_ID = 9001
private const val FOREGROUND_NOTIFICATION_ID = 9002
+ // OneTimeWorkRequest has no default retry cap - bound transient IO retries here.
private const val MAX_RETRIES = 3
- private const val PAGE_SIZE = 10_000
}
override suspend fun getForegroundInfo(): ForegroundInfo {
@@ -82,7 +78,6 @@ class AutoExportWorker(
return Result.failure()
}
- // One-time "run now" workers skip the due check
val isManualRun = tags.contains("colota_auto_export_now")
if (!isManualRun && !config.isExportDue()) {
AppLogger.d(TAG, "Export not yet due, skipping")
@@ -91,12 +86,11 @@ class AutoExportWorker(
AppLogger.i(TAG, "Starting auto-export: format=${config.format}, mode=${config.mode}")
- // Promote to foreground service to prevent OS from killing long exports
+ // Some OEMs (Samsung, Xiaomi) throw under aggressive background restrictions;
+ // the export often still completes.
try {
setForeground(getForegroundInfo())
} catch (e: Exception) {
- // Some OEMs (Samsung, Xiaomi) throw when background restrictions are aggressive.
- // Continue with the export anyway - it may still complete.
AppLogger.w(TAG, "Could not promote to foreground service: ${e.message}")
}
@@ -106,22 +100,21 @@ class AutoExportWorker(
.format(java.util.Date())
val fileName = "colota_export_$dateStr$ext"
- // Write to temp file first for atomic writes
+ // Write to cache first, then copy to SAF.
val tempFile = File(appContext.cacheDir, "auto_export_temp$ext")
return try {
val rowCount = if (config.mode == "incremental" && config.lastExportTimestamp > 0) {
val now = System.currentTimeMillis() / 1000
- writePaginatedExport(config.format, tempFile) { limit, offset ->
+ ExportConverters.exportToFile(config.format, tempFile, shouldCancel = { isStopped }) { limit, offset ->
db.getLocationsByDateRange(config.lastExportTimestamp, now, limit, offset)
}
} else {
- writePaginatedExport(config.format, tempFile) { limit, offset ->
+ ExportConverters.exportToFile(config.format, tempFile, shouldCancel = { isStopped }) { limit, offset ->
db.getLocationsChronological(limit, offset)
}
}
- // Check cancellation before copying
if (isStopped) {
tempFile.delete()
AppLogger.w(TAG, "Auto-export cancelled")
@@ -136,11 +129,9 @@ class AutoExportWorker(
return Result.success()
}
- // Atomic: copy completed temp file to SAF directory, then verify
val tempSize = tempFile.length()
val destDocFile = copyToSafDirectory(dirUri, fileName, tempFile, config.format)
- // Verify the destination file
val destSize = destDocFile.length()
if (!destDocFile.exists() || destSize == 0L) {
tempFile.delete()
@@ -155,7 +146,6 @@ class AutoExportWorker(
val now = System.currentTimeMillis() / 1000
config.saveLastExportTimestamp(db, now)
- // Clean up old export files beyond retention limit
cleanupOldExports(dirUri, config.retentionCount)
AppLogger.i(TAG, "Auto-export complete: $fileName ($rowCount locations)")
@@ -165,100 +155,71 @@ class AutoExportWorker(
"Exported $rowCount locations to $fileName",
dirUri
)
- sendExportBroadcast(true, fileName, rowCount, null)
+ LocationServiceModule.sendAutoExportEvent(true, fileName, rowCount, null)
Result.success()
} catch (e: SecurityException) {
- tempFile.delete()
- val error = "Directory permission lost"
- AppLogger.e(TAG, "Auto-export failed - permission denied", e)
config.saveEnabled(db, false)
config.savePermissionLost(db, true)
- config.saveLastError(db, error)
- showNotification("Auto-Export Failed", "$error. Please re-select the export directory.")
- sendExportBroadcast(false, null, 0, error)
- Result.failure()
+ handleExportFailure(
+ tempFile, config, db, e,
+ error = "Directory permission lost",
+ logMessage = "Auto-export failed - permission denied",
+ userMessage = "Directory permission lost. Please re-select the export directory.",
+ retry = false
+ )
} catch (e: IllegalArgumentException) {
- tempFile.delete()
- val error = "Invalid configuration: ${e.message}"
- AppLogger.e(TAG, "Auto-export failed - invalid configuration", e)
- config.saveLastError(db, error)
- showNotification("Auto-Export Failed", "Invalid export configuration: ${e.message}")
- sendExportBroadcast(false, null, 0, error)
- Result.failure()
+ handleExportFailure(
+ tempFile, config, db, e,
+ error = "Invalid configuration: ${e.message}",
+ logMessage = "Auto-export failed - invalid configuration",
+ userMessage = "Invalid export configuration: ${e.message}",
+ retry = false
+ )
} catch (e: IllegalStateException) {
- tempFile.delete()
- val error = "Directory access failed: ${e.message}"
- AppLogger.e(TAG, "Auto-export failed - directory access issue", e)
- config.saveLastError(db, error)
- showNotification("Auto-Export Failed", "Could not access export directory: ${e.message}")
- sendExportBroadcast(false, null, 0, error)
- Result.failure()
+ handleExportFailure(
+ tempFile, config, db, e,
+ error = "Directory access failed: ${e.message}",
+ logMessage = "Auto-export failed - directory access issue",
+ userMessage = "Could not access export directory: ${e.message}",
+ retry = false
+ )
} catch (e: IOException) {
- tempFile.delete()
- val error = "IO error: ${e.message}"
- AppLogger.e(TAG, "Auto-export failed - IO error, will retry", e)
- config.saveLastError(db, error)
- showNotification("Auto-Export Failed", "Could not save export file. Will retry.")
- sendExportBroadcast(false, null, 0, error)
- Result.retry()
+ handleExportFailure(
+ tempFile, config, db, e,
+ error = "IO error: ${e.message}",
+ logMessage = "Auto-export failed - IO error, will retry",
+ userMessage = "Could not save export file. Will retry.",
+ retry = true
+ )
} catch (e: Exception) {
- tempFile.delete()
- val error = "Export failed: ${e.message}"
- AppLogger.e(TAG, "Auto-export failed", e)
- config.saveLastError(db, error)
- showNotification("Auto-Export Failed", "Could not save export file. Will retry.")
- sendExportBroadcast(false, null, 0, error)
- Result.retry()
+ handleExportFailure(
+ tempFile, config, db, e,
+ error = "Export failed: ${e.message}",
+ logMessage = "Auto-export failed",
+ userMessage = "Could not save export file. Will retry.",
+ retry = true
+ )
}
}
- /**
- * Streams a paginated export to temp file, fetching rows via the provided lambda.
- * Checks isStopped between chunks for graceful cancellation.
- */
- private fun writePaginatedExport(
- format: String,
+ private fun handleExportFailure(
tempFile: File,
- fetchPage: (limit: Int, offset: Int) -> List<Map<String, Any?>>
- ): Int {
- val coordsCollector = if (format == "kml") KmlCoordsCollector(appContext.cacheDir) else null
- var totalRows = 0
- var offset = 0
-
- coordsCollector.use {
- OutputStreamWriter(tempFile.outputStream(), Charsets.UTF_8).use { writer ->
- ExportConverters.writeHeader(writer, format)
-
- while (true) {
- if (isStopped) {
- AppLogger.w(TAG, "Auto-export cancelled during write")
- break
- }
- val page = fetchPage(PAGE_SIZE, offset)
- if (page.isEmpty()) break
- ExportConverters.writeRows(writer, format, page, offset, coordsCollector)
- totalRows += page.size
- offset += PAGE_SIZE
- }
-
- if (!isStopped) {
- ExportConverters.writeFooter(writer, format, coordsCollector)
- }
- }
- }
-
- if (isStopped) {
- tempFile.delete()
- return 0
- }
-
- return totalRows
+ config: AutoExportConfig,
+ db: DatabaseHelper,
+ e: Throwable,
+ error: String,
+ logMessage: String,
+ userMessage: String,
+ retry: Boolean
+ ): Result {
+ tempFile.delete()
+ AppLogger.e(TAG, logMessage, e)
+ config.saveLastError(db, error)
+ showNotification("Auto-Export Failed", userMessage)
+ LocationServiceModule.sendAutoExportEvent(false, null, 0, error)
+ return if (retry) Result.retry() else Result.failure()
}
- /**
- * Copies temp file to SAF directory and returns the destination DocumentFile
- * for verification.
- */
private fun copyToSafDirectory(
dirUri: Uri,
fileName: String,
@@ -281,18 +242,15 @@ class AutoExportWorker(
return docFile
}
- /**
- * Deletes oldest export files beyond the retention limit.
- * Only touches files matching the colota_export_ prefix.
- */
private fun cleanupOldExports(dirUri: Uri, retentionCount: Int) {
if (retentionCount <= 0) return // 0 = unlimited
try {
val dir = DocumentFile.fromTreeUri(appContext, dirUri) ?: return
+ // File names embed a sortable timestamp, so lexicographic == chronological.
val exportFiles = dir.listFiles()
.filter { it.name?.startsWith("colota_export_") == true }
- .sortedBy { it.name } // lexicographic = chronological (timestamp in name)
+ .sortedBy { it.name }
val toDelete = exportFiles.size - retentionCount
if (toDelete <= 0) return
@@ -354,7 +312,4 @@ class AutoExportWorker(
nm.notify(NOTIFICATION_ID, builder.build())
}
- private fun sendExportBroadcast(success: Boolean, fileName: String?, rowCount: Int, error: String?) {
- LocationServiceModule.sendAutoExportEvent(success, fileName, rowCount, error)
- }
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
index f656f9e9..02d916b1 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
@@ -18,18 +18,7 @@ import java.util.Date
import java.util.Locale
import java.util.TimeZone
-/**
- * Native export converters for location data.
- * Used by AutoExportWorker (background) and manual export (via bridge).
- *
- * Streaming API (writeHeader/writeRows/writeFooter) for memory-efficient
- * chunked export. The in-memory convert() delegates to the streaming API.
- */
-/**
- * File-backed collector for KML LineString coordinates.
- * Writes coordinates to a temp file instead of accumulating in memory,
- * preventing OOM on large exports.
- */
+/** Spools KML LineString coords to a temp file to avoid OOM on large exports. */
class KmlCoordsCollector(cacheDir: File) : AutoCloseable {
private val tempFile = File(cacheDir, "kml_coords_temp.txt")
private val writer = BufferedWriter(FileWriter(tempFile))
@@ -59,7 +48,7 @@ class KmlCoordsCollector(cacheDir: File) : AutoCloseable {
object ExportConverters {
- private const val PAGE_SIZE = 10_000
+ const val PAGE_SIZE = 10_000
private fun isoTime(unixSeconds: Long): String {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
@@ -67,14 +56,12 @@ object ExportConverters {
return sdf.format(Date(unixSeconds * 1000))
}
- /** Formats a value as a valid JSON value (null-safe, properly escaped). */
private fun jsonValue(value: Any?): String = when (value) {
null -> "null"
is String -> "\"${escapeJson(value)}\""
else -> value.toString()
}
- /** Escapes special characters for JSON string values. */
private fun escapeJson(s: String): String = buildString(s.length) {
for (c in s) {
when (c) {
@@ -90,44 +77,83 @@ object ExportConverters {
}
}
- // -- Shared chunked export to file --
-
- /**
- * Exports all locations from the database to a file using streaming chunks.
- * Shared between AutoExportWorker and the manual export bridge method.
- *
- * @return Number of rows exported
- */
- fun exportToFile(db: DatabaseHelper, format: String, outputFile: File, pageSize: Int = PAGE_SIZE): Int {
- val coordsCollector = if (format == "kml") KmlCoordsCollector(outputFile.parentFile!!) else null
- var totalRows = 0
- var offset = 0
+ private data class ExportRow(
+ val ts: Long,
+ val lat: Double,
+ val lon: Double,
+ val altitude: Any?,
+ val accuracy: Any?,
+ val speed: Any?,
+ val battery: Any?,
+ ) {
+ companion object {
+ fun from(row: Map<String, Any?>): ExportRow = ExportRow(
+ ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000),
+ lat = (row["latitude"] as? Double) ?: 0.0,
+ lon = (row["longitude"] as? Double) ?: 0.0,
+ altitude = row["altitude"],
+ accuracy = row["accuracy"],
+ speed = row["speed"],
+ battery = row["battery"],
+ )
+ }
+ }
- coordsCollector.use {
- OutputStreamWriter(outputFile.outputStream(), Charsets.UTF_8).use { writer ->
- writeHeader(writer, format)
+ private sealed class FormatWriter(val extension: String, val mimeType: String) {
+ abstract fun writeHeader(w: Writer)
+ abstract fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?)
+ abstract fun writeFooter(w: Writer, kml: KmlCoordsCollector?)
+ open val usesKmlCoords: Boolean = false
- while (true) {
- val page = db.getLocationsChronological(pageSize, offset)
- if (page.isEmpty()) break
- writeRows(writer, format, page, offset, coordsCollector)
- totalRows += page.size
- offset += pageSize
- }
+ fun writeRows(w: Writer, rows: List<ExportRow>, globalOffset: Int, kml: KmlCoordsCollector?) {
+ rows.forEachIndexed { i, row -> writeRow(w, row, globalOffset + i, kml) }
+ }
+ }
- writeFooter(writer, format, coordsCollector)
- }
+ private object CsvFormat : FormatWriter(".csv", "text/csv") {
+ override fun writeHeader(w: Writer) {
+ w.write("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n")
}
- return totalRows
+ override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?) {
+ w.write(listOf(
+ globalIndex, row.ts, isoTime(row.ts), row.lat, row.lon,
+ row.accuracy ?: 0, row.altitude ?: 0, row.speed ?: 0, row.battery ?: 0
+ ).joinToString(","))
+ w.write("\n")
+ }
+ override fun writeFooter(w: Writer, kml: KmlCoordsCollector?) {}
}
- // -- Streaming interface for chunked export --
+ private object GeoJsonFormat : FormatWriter(".geojson", "application/json") {
+ override fun writeHeader(w: Writer) {
+ w.write("{\n \"type\": \"FeatureCollection\",\n \"features\": [\n")
+ }
+ override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?) {
+ if (globalIndex > 0) w.write(",\n")
+ w.write(""" {
+ "type": "Feature",
+ "geometry": {
+ "type": "Point",
+ "coordinates": [${row.lon}, ${row.lat}]
+ },
+ "properties": {
+ "id": $globalIndex,
+ "accuracy": ${jsonValue(row.accuracy)},
+ "altitude": ${jsonValue(row.altitude)},
+ "speed": ${jsonValue(row.speed)},
+ "battery": ${jsonValue(row.battery)},
+ "time": "${isoTime(row.ts)}"
+ }
+ }""")
+ }
+ override fun writeFooter(w: Writer, kml: KmlCoordsCollector?) {
+ w.write("\n ]\n}\n")
+ }
+ }
- fun writeHeader(writer: Writer, format: String) {
- when (format) {
- "csv" -> writer.write("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n")
- "geojson" -> writer.write("{\n \"type\": \"FeatureCollection\",\n \"features\": [\n")
- "gpx" -> writer.write("""<?xml version="1.0" encoding="UTF-8"?>
+ private object GpxFormat : FormatWriter(".gpx", "application/gpx+xml") {
+ override fun writeHeader(w: Writer) {
+ w.write("""<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
<metadata>
<name>Colota Location Export</name>
@@ -137,7 +163,33 @@ object ExportConverters {
<name>Colota Track Export</name>
<trkseg>
""")
- "kml" -> writer.write("""<?xml version="1.0" encoding="UTF-8"?>
+ }
+ override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?) {
+ val lat = String.format(Locale.US, "%.6f", row.lat)
+ val lon = String.format(Locale.US, "%.6f", row.lon)
+ w.write(""" <trkpt lat="$lat" lon="$lon">
+ <ele>${row.altitude ?: 0}</ele>
+ <time>${isoTime(row.ts)}</time>
+ <extensions>
+ <accuracy>${row.accuracy ?: 0}</accuracy>
+ <speed>${row.speed ?: 0}</speed>
+ <battery>${row.battery ?: 0}</battery>
+ </extensions>
+ </trkpt>
+""")
+ }
+ override fun writeFooter(w: Writer, kml: KmlCoordsCollector?) {
+ w.write(""" </trkseg>
+ </trk>
+</gpx>
+""")
+ }
+ }
+
+ private object KmlFormat : FormatWriter(".kml", "application/vnd.google-earth.kml+xml") {
+ override val usesKmlCoords: Boolean = true
+ override fun writeHeader(w: Writer) {
+ w.write("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Colota Location Export</name>
@@ -149,156 +201,128 @@ object ExportConverters {
</LineStyle>
</Style>
""")
- else -> throw IllegalArgumentException("Unknown export format: $format")
}
- }
-
- /**
- * Write a chunk of rows. For KML, coordsCollector writes LineString
- * coordinates to a temp file to avoid unbounded memory growth.
- */
- fun writeRows(
- writer: Writer,
- format: String,
- rows: List<Map<String, Any?>>,
- globalOffset: Int,
- coordsCollector: KmlCoordsCollector?
- ) {
- when (format) {
- "csv" -> {
- rows.forEachIndexed { i, row ->
- val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
- writer.write(listOf(
- globalOffset + i,
- ts,
- isoTime(ts),
- row["latitude"] ?: 0.0,
- row["longitude"] ?: 0.0,
- row["accuracy"] ?: 0,
- row["altitude"] ?: 0,
- row["speed"] ?: 0,
- row["battery"] ?: 0
- ).joinToString(","))
- writer.write("\n")
- }
- }
- "geojson" -> {
- rows.forEachIndexed { i, row ->
- if (globalOffset + i > 0) writer.write(",\n")
- val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
- val lon = row["longitude"] ?: 0.0
- val lat = row["latitude"] ?: 0.0
- writer.write(""" {
- "type": "Feature",
- "geometry": {
- "type": "Point",
- "coordinates": [$lon, $lat]
- },
- "properties": {
- "id": ${globalOffset + i},
- "accuracy": ${jsonValue(row["accuracy"])},
- "altitude": ${jsonValue(row["altitude"])},
- "speed": ${jsonValue(row["speed"])},
- "battery": ${jsonValue(row["battery"])},
- "time": "${isoTime(ts)}"
- }
- }""")
- }
- }
- "gpx" -> {
- for (row in rows) {
- val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
- val lat = (row["latitude"] as? Double)?.let { String.format(Locale.US, "%.6f", it) } ?: "0.000000"
- val lon = (row["longitude"] as? Double)?.let { String.format(Locale.US, "%.6f", it) } ?: "0.000000"
- writer.write(""" <trkpt lat="$lat" lon="$lon">
- <ele>${row["altitude"] ?: 0}</ele>
- <time>${isoTime(ts)}</time>
- <extensions>
- <accuracy>${row["accuracy"] ?: 0}</accuracy>
- <speed>${row["speed"] ?: 0}</speed>
- <battery>${row["battery"] ?: 0}</battery>
- </extensions>
- </trkpt>
-""")
- }
- }
- "kml" -> {
- for (row in rows) {
- coordsCollector?.add("${row["longitude"] ?: 0},${row["latitude"] ?: 0},${row["altitude"] ?: 0}")
- val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
- writer.write(""" <Placemark>
- <TimeStamp><when>${isoTime(ts)}</when></TimeStamp>
- <description>Accuracy: ${row["accuracy"] ?: 0}m, Speed: ${row["speed"] ?: 0}m/s</description>
+ override fun writeRow(w: Writer, row: ExportRow, globalIndex: Int, kml: KmlCoordsCollector?) {
+ kml?.add("${row.lon},${row.lat},${row.altitude ?: 0}")
+ w.write(""" <Placemark>
+ <TimeStamp><when>${isoTime(row.ts)}</when></TimeStamp>
+ <description>Accuracy: ${row.accuracy ?: 0}m, Speed: ${row.speed ?: 0}m/s</description>
<Point>
- <coordinates>${row["longitude"] ?: 0},${row["latitude"] ?: 0},${row["altitude"] ?: 0}</coordinates>
+ <coordinates>${row.lon},${row.lat},${row.altitude ?: 0}</coordinates>
</Point>
</Placemark>
""")
- }
- }
}
- }
-
- fun writeFooter(writer: Writer, format: String, coordsCollector: KmlCoordsCollector?) {
- when (format) {
- "csv" -> { /* no footer */ }
- "geojson" -> writer.write("\n ]\n}\n")
- "gpx" -> writer.write(""" </trkseg>
- </trk>
-</gpx>
-""")
- "kml" -> {
- writer.write(""" <Placemark>
+ override fun writeFooter(w: Writer, kml: KmlCoordsCollector?) {
+ w.write(""" <Placemark>
<name>Track Path</name>
<styleUrl>#pathStyle</styleUrl>
<LineString>
<tessellate>1</tessellate>
<coordinates>
""")
- coordsCollector?.writeTo(writer)
- writer.write("""
+ kml?.writeTo(w)
+ w.write("""
</coordinates>
</LineString>
</Placemark>
</Document>
</kml>
""")
- }
}
}
+ private fun forFormat(format: String): FormatWriter = when (format) {
+ "csv" -> CsvFormat
+ "geojson" -> GeoJsonFormat
+ "gpx" -> GpxFormat
+ "kml" -> KmlFormat
+ else -> throw IllegalArgumentException("Unknown export format: $format")
+ }
+
/**
- * Converts rows to the given format using the streaming API with a StringWriter.
- * Single source of truth for all format output.
+ * Streams a paginated export to file. On cancellation mid-write the footer
+ * is skipped and the partial row count is returned; file cleanup is the
+ * caller's job.
*/
+ fun exportToFile(
+ format: String,
+ outputFile: File,
+ pageSize: Int = PAGE_SIZE,
+ shouldCancel: () -> Boolean = { false },
+ fetchPage: (limit: Int, offset: Int) -> List<Map<String, Any?>>
+ ): Int {
+ val writer = forFormat(format)
+ val coordsCollector = if (writer.usesKmlCoords) KmlCoordsCollector(outputFile.parentFile!!) else null
+ var totalRows = 0
+ var offset = 0
+ var cancelled = false
+
+ coordsCollector.use {
+ OutputStreamWriter(outputFile.outputStream(), Charsets.UTF_8).use { w ->
+ writer.writeHeader(w)
+
+ while (true) {
+ if (shouldCancel()) { cancelled = true; break }
+ val page = fetchPage(pageSize, offset)
+ if (page.isEmpty()) break
+ writer.writeRows(w, page.map(ExportRow::from), offset, coordsCollector)
+ totalRows += page.size
+ offset += pageSize
+ }
+
+ if (!cancelled) writer.writeFooter(w, coordsCollector)
+ }
+ }
+ return totalRows
+ }
+
+ fun exportToFile(db: DatabaseHelper, format: String, outputFile: File, pageSize: Int = PAGE_SIZE): Int =
+ exportToFile(format, outputFile, pageSize) { limit, offset ->
+ db.getLocationsChronological(limit, offset)
+ }
+
+ fun writeHeader(writer: Writer, format: String) {
+ forFormat(format).writeHeader(writer)
+ }
+
+ /** `coordsCollector` is required for KML (spills LineString coords to disk). */
+ fun writeRows(
+ writer: Writer,
+ format: String,
+ rows: List<Map<String, Any?>>,
+ globalOffset: Int,
+ coordsCollector: KmlCoordsCollector?
+ ) {
+ forFormat(format).writeRows(writer, rows.map(ExportRow::from), globalOffset, coordsCollector)
+ }
+
+ fun writeFooter(writer: Writer, format: String, coordsCollector: KmlCoordsCollector?) {
+ forFormat(format).writeFooter(writer, coordsCollector)
+ }
+
fun convert(format: String, rows: List<Map<String, Any?>>): String {
+ val writer = forFormat(format)
val sw = java.io.StringWriter()
- val coordsCollector = if (format == "kml") {
- // In-memory: use a temp list to collect coords (small datasets only)
+ val coordsCollector = if (writer.usesKmlCoords) {
KmlCoordsCollector(java.io.File(System.getProperty("java.io.tmpdir")!!))
} else null
coordsCollector.use {
- writeHeader(sw, format)
- writeRows(sw, format, rows, 0, coordsCollector)
- writeFooter(sw, format, coordsCollector)
+ writer.writeHeader(sw)
+ writer.writeRows(sw, rows.map(ExportRow::from), 0, coordsCollector)
+ writer.writeFooter(sw, coordsCollector)
}
return sw.toString()
}
fun extensionFor(format: String): String = when (format) {
- "csv" -> ".csv"
- "geojson" -> ".geojson"
- "gpx" -> ".gpx"
- "kml" -> ".kml"
+ "csv", "geojson", "gpx", "kml" -> forFormat(format).extension
else -> ".txt"
}
fun mimeTypeFor(format: String): String = when (format) {
- "csv" -> "text/csv"
- "geojson" -> "application/json"
- "gpx" -> "application/gpx+xml"
- "kml" -> "application/vnd.google-earth.kml+xml"
+ "csv", "geojson", "gpx", "kml" -> forFormat(format).mimeType
else -> "text/plain"
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
index caf8739f..638d659b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
@@ -10,6 +10,7 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
import com.Colota.util.AppLogger
import com.Colota.util.DeviceInfoHelper
import kotlinx.coroutines.*
@@ -60,7 +61,7 @@ class LocationBootReceiver : BroadcastReceiver() {
repeat(MAX_DB_RETRIES) { attempt ->
try {
// Test database access
- dbHelper.getSetting("tracking_enabled")
+ dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED)
return true
} catch (e: Exception) {
AppLogger.d(TAG, "DB not ready, attempt ${attempt + 1}/$MAX_DB_RETRIES")
@@ -82,7 +83,7 @@ class LocationBootReceiver : BroadcastReceiver() {
return
}
- val isEnabled = dbHelper.getSetting("tracking_enabled", "false") == "true"
+ val isEnabled = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
if (!isEnabled) {
AppLogger.d(TAG, "Boot detected but tracking disabled")
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 a715f1a6..1ac1c38a 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
@@ -6,6 +6,7 @@
package com.Colota.service
import android.app.*
+import android.location.Location
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
@@ -15,6 +16,7 @@ import com.Colota.util.AppLogger
import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
+import com.Colota.data.SettingsKeys
import com.Colota.sync.NetworkManager
import com.Colota.sync.PayloadBuilder
import com.Colota.sync.SyncManager
@@ -38,7 +40,8 @@ class LocationForegroundService : Service() {
private lateinit var notificationManager: NotificationManager
private lateinit var notificationHelper: NotificationHelper
private lateinit var dbHelper: DatabaseHelper
- private lateinit var payloadBuilder: PayloadBuilder
+ @Volatile private var payloadFieldMap: Map<String, String> = emptyMap()
+ @Volatile private var payloadCustomFields: Map<String, String> = emptyMap()
private lateinit var deviceInfoHelper: DeviceInfoHelper
private lateinit var networkManager: NetworkManager
private lateinit var geofenceHelper: GeofenceHelper
@@ -48,30 +51,43 @@ class LocationForegroundService : Service() {
private lateinit var profileManager: ProfileManager
private lateinit var conditionMonitor: ConditionMonitor
+ // ── Service infrastructure ──
@Volatile private var serviceScope: CoroutineScope? = null
@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null
@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 lastKnownLocation: Location? = null
+
+ /**
+ * 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).
+ * - Read from any thread (location callbacks, notification builder, heartbeat IO coroutine).
+ * @Volatile exists for reader visibility, not mutation safety. Do NOT mutate off-Main.
+ */
@Volatile private var insidePauseZone = false
+ @Volatile private var currentZoneName: String? = null
+ @Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null
+ @Volatile private var pendingPauseZone: GeofenceHelper.CachedGeofence? = null
+ @Volatile private var entryDelayJob: Job? = null
+ @Volatile private var heartbeatJob: Job? = null
+
+ // WiFi pause sub-state (same Main-only mutation contract as above)
@Volatile private var isWifiPaused = false
- // Accessed exclusively on the main thread - @Volatile not needed and would be misleading
- private var unmeteredNetworkCount = 0
@Volatile private var wifiCallback: ConnectivityManager.NetworkCallback? = null
@Volatile private var wifiResumeJob: Job? = null
+ // Main-only reads + writes (no cross-thread reads), so @Volatile is unnecessary here
+ private var unmeteredNetworkCount = 0
+
+ // Motionless pause sub-state (same Main-only mutation contract as above)
@Volatile private var isMotionlessPaused = false
@Volatile private var motionlessJob: Job? = null
- @Volatile private var currentZoneName: String? = null
- @Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null
- @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
- @Volatile private var customFields: Map<String, String>? = null
companion object {
private const val TAG = "LocationService"
@@ -103,7 +119,6 @@ class LocationForegroundService : Service() {
locationProvider = LocationProviderFactory.create(this)
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
dbHelper = DatabaseHelper.getInstance(this)
- payloadBuilder = PayloadBuilder()
deviceInfoHelper = DeviceInfoHelper(this)
networkManager = NetworkManager(this)
geofenceHelper = GeofenceHelper(this)
@@ -112,8 +127,8 @@ class LocationForegroundService : Service() {
profileHelper = ProfileHelper(this)
profileManager = ProfileManager(
profileHelper, serviceScope!!,
- onConfigSwitch = { interval, distance, syncInterval, _, _ ->
- applyProfileConfig(interval, distance, syncInterval)
+ onConfigSwitch = { config ->
+ applyProfileConfig(config.interval, config.distance, config.syncInterval)
},
onStationaryChanged = ::handleStationaryChanged
)
@@ -133,7 +148,7 @@ class LocationForegroundService : Service() {
}
val savedSettings = dbHelper.getAllSettings()
- val shouldBeTracking = savedSettings["tracking_enabled"]?.toBoolean() ?: false
+ val shouldBeTracking = savedSettings[SettingsKeys.TRACKING_ENABLED]?.toBoolean() ?: false
// intent == null: Android restarted the service after OOM kill
if (intent == null && !shouldBeTracking) {
@@ -157,7 +172,7 @@ class LocationForegroundService : Service() {
// Restore pause zone state so a restart without a cached location fix doesn't incorrectly resume tracking
if (!insidePauseZone) {
- val savedZone = savedSettings["pause_zone_name"]
+ val savedZone = savedSettings[SettingsKeys.PAUSE_ZONE_NAME]
if (!savedZone.isNullOrBlank()) {
insidePauseZone = true
currentZoneName = savedZone
@@ -173,7 +188,7 @@ class LocationForegroundService : Service() {
// so setupLocationUpdates() won't start GPS before onAvailable fires.
registerWifiPause()
}
- if (savedSettings["pause_zone_motionless_active"]?.toBoolean() == true) {
+ if (savedSettings[SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE]?.toBoolean() == true) {
isMotionlessPaused = true
motionDetector?.arm()
AppLogger.d(TAG, "Restored motionless pause state")
@@ -210,60 +225,62 @@ class LocationForegroundService : Service() {
}
if (!isLightweight) {
- dbHelper.saveSetting("tracking_enabled", "true")
+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
}
when (action) {
- ACTION_REFRESH_NOTIFICATION -> {
- syncManager.invalidateQueueCache()
- val loc = lastKnownLocation
- updateNotification(
- lat = loc?.latitude,
- lon = loc?.longitude,
- forceUpdate = true
- )
- return START_STICKY
- }
- ACTION_RECHECK_ZONE -> {
- handleZoneRecheckAction()
- return START_STICKY
- }
- ACTION_RECHECK_PROFILES -> {
- profileManager.invalidateProfiles()
- conditionMonitor.start()
- profileManager.evaluate()
- return START_STICKY
- }
- ACTION_MANUAL_FLUSH -> {
- serviceScope?.launch {
- syncManager.manualFlush()
- }
- return START_STICKY
- }
- else -> {
- locationRestartJob?.cancel()
- locationRestartJob = serviceScope?.launch {
- withContext(Dispatchers.Main) {
- stopLocationUpdates()
- syncManager.stopPeriodicSync()
+ ACTION_REFRESH_NOTIFICATION -> handleRefreshNotification()
+ ACTION_RECHECK_ZONE -> handleZoneRecheckAction()
+ ACTION_RECHECK_PROFILES -> handleRecheckProfiles()
+ ACTION_MANUAL_FLUSH -> handleManualFlush()
+ else -> handleStart()
+ }
- setupLocationUpdates()
- syncManager.startPeriodicSync()
+ return START_STICKY
+ }
- // Start after setup so profile evaluations don't race
- // with setupLocationUpdates above
- conditionMonitor.start()
- }
+ private fun handleRefreshNotification() {
+ syncManager.invalidateQueueCache()
+ val loc = lastKnownLocation
+ updateNotification(
+ lat = loc?.latitude,
+ lon = loc?.longitude,
+ forceUpdate = true
+ )
+ }
- if (!config.isOfflineMode && config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank() &&
- syncManager.isSyncAllowed()) {
- syncManager.manualFlush()
- }
- }
- }
+ private fun handleRecheckProfiles() {
+ profileManager.invalidateProfiles()
+ conditionMonitor.start()
+ profileManager.evaluate()
+ }
+
+ private fun handleManualFlush() {
+ serviceScope?.launch {
+ syncManager.manualFlush()
}
+ }
- return START_STICKY
+ private fun handleStart() {
+ locationRestartJob?.cancel()
+ locationRestartJob = serviceScope?.launch {
+ withContext(Dispatchers.Main) {
+ stopLocationUpdates()
+ syncManager.stopPeriodicSync()
+
+ setupLocationUpdates()
+ syncManager.startPeriodicSync()
+
+ // Start after setup so profile evaluations don't race
+ // with setupLocationUpdates above
+ conditionMonitor.start()
+ }
+
+ if (!config.isOfflineMode && config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank() &&
+ syncManager.isSyncAllowed()) {
+ syncManager.manualFlush()
+ }
+ }
}
override fun onDestroy() {
@@ -294,7 +311,7 @@ class LocationForegroundService : Service() {
if (isWifiPaused || isMotionlessPaused) return // GPS intentionally stopped by a zone pause hold
val callback = object : LocationUpdateCallback {
- override fun onLocationUpdate(location: android.location.Location) {
+ override fun onLocationUpdate(location: Location) {
lastFixAtMs = SystemClock.elapsedRealtime()
handleLocationUpdate(location)
}
@@ -405,7 +422,7 @@ class LocationForegroundService : Service() {
}
- private fun recheckZoneWithLocation(location: android.location.Location) {
+ private fun recheckZoneWithLocation(location: Location) {
val zone = geofenceHelper.getPauseZone(location)
// Already inside this zone - refresh settings in case they changed via editor
@@ -414,8 +431,6 @@ class LocationForegroundService : Service() {
updateNotification(
lat = location.latitude,
lon = location.longitude,
- pausedInZone = true,
- zoneName = currentZoneName,
forceUpdate = true
)
val reason = when {
@@ -492,7 +507,7 @@ class LocationForegroundService : Service() {
}
/** Derives speed from consecutive GPS points when the device doesn't report it. */
- private fun applySpeedFallback(location: android.location.Location) {
+ private fun applySpeedFallback(location: Location) {
if (location.hasSpeed()) return
val prev = lastKnownLocation ?: return
@@ -508,7 +523,7 @@ class LocationForegroundService : Service() {
location.speed = calculatedSpeed
}
- private fun handleLocationUpdate(location: android.location.Location) {
+ private fun handleLocationUpdate(location: Location) {
if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
AppLogger.d(TAG, "Location filtered: accuracy ${location.accuracy}m > threshold ${config.accuracyThreshold}m")
return
@@ -560,7 +575,6 @@ class LocationForegroundService : Service() {
}
val timestampSec = location.time / 1000
- val currentFieldMap = fieldMap ?: emptyMap()
serviceScope?.launch {
anchorJob?.join()
@@ -579,15 +593,7 @@ class LocationForegroundService : Service() {
LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
- val payload = payloadBuilder.buildPayload(
- location,
- battery,
- batteryStatus,
- // emptyMap() keeps internal field names (lat/lon/vel/bear/...) so buildTraccarJsonPayload can read them directly
- if (config.apiFormat == NetworkManager.FORMAT_TRACCAR_JSON) emptyMap() else currentFieldMap,
- timestampSec,
- customFields
- )
+ val payload = PayloadBuilder.buildLocationPayload(location, timestampSec, battery, batteryStatus, payloadFieldMap, payloadCustomFields, config.apiFormat)
syncManager.queueAndSend(locationId, payload)
@@ -634,32 +640,19 @@ class LocationForegroundService : Service() {
pendingPauseZone = null
AppLogger.d(TAG, "Entry delay cancelled - left zone '${zone?.name}' before delay completed")
- val loc = lastKnownLocation
- updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
+ refreshNotificationForCurrentState()
}
private fun enterPauseZone(geofence: GeofenceHelper.CachedGeofence) {
insidePauseZone = true
currentZoneName = geofence.name
currentZoneGeofence = geofence
- dbHelper.saveSetting("pause_zone_name", geofence.name)
-
- val loc = lastKnownLocation
- updateNotification(
- lat = loc?.latitude,
- lon = loc?.longitude,
- pausedInZone = true,
- zoneName = geofence.name,
- forceUpdate = true
- )
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_NAME, geofence.name)
+ refreshNotificationForCurrentState()
LocationServiceModule.sendPauseZoneEvent(true, geofence.name)
- if (geofence.pauseOnWifi) registerWifiPause()
- if (geofence.pauseOnMotionless) startMotionlessCountdown(geofence.motionlessTimeoutMinutes)
- if (geofence.heartbeatEnabled) {
- startHeartbeat(geofence.heartbeatIntervalMinutes)
- }
+ startZoneHolds(geofence)
profileManager.clearSpeedBuffer()
@@ -675,40 +668,57 @@ class LocationForegroundService : Service() {
private fun exitPauseZone(): Job? {
val exitedGeofence = currentZoneGeofence
val exitedName = currentZoneName
+ val wasWifiPaused = isWifiPaused
+ val wasMotionlessPaused = isMotionlessPaused
insidePauseZone = false
currentZoneName = null
currentZoneGeofence = null
- dbHelper.saveSetting("pause_zone_name", "")
- val wasWifiPaused = isWifiPaused
- val wasMotionlessPaused = isMotionlessPaused
- unregisterWifiPause()
- cancelMotionlessCountdown()
- clearMotionlessPauseState()
- cancelHeartbeat()
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_NAME, "")
+
+ stopZoneHolds()
val anchorJob = exitedGeofence?.let { saveAnchorPoint(it) }
// Resume GPS if it was stopped by any zone pause hold
if (wasWifiPaused || wasMotionlessPaused) setupLocationUpdates()
- val loc = lastKnownLocation
- updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
-
+ refreshNotificationForCurrentState()
LocationServiceModule.sendPauseZoneEvent(false, exitedName)
AppLogger.d(TAG, "Exited pause zone: $exitedName")
return anchorJob
}
+ /**
+ * Starts any pause-zone holds (WiFi, motionless, heartbeat) that the zone has enabled.
+ * Must stay mirrored with [stopZoneHolds] - when adding a new hold, update both.
+ */
+ private fun startZoneHolds(zone: GeofenceHelper.CachedGeofence) {
+ if (zone.pauseOnWifi) registerWifiPause()
+ if (zone.pauseOnMotionless) startMotionlessCountdown(zone.motionlessTimeoutMinutes)
+ if (zone.heartbeatEnabled) startHeartbeat(zone.heartbeatIntervalMinutes)
+ }
+
+ /**
+ * Stops all pause-zone holds. Safe to call when a hold was never started (each sub-stop is idempotent).
+ * Must stay mirrored with [startZoneHolds].
+ */
+ private fun stopZoneHolds() {
+ unregisterWifiPause()
+ cancelMotionlessCountdown()
+ clearMotionlessPauseState()
+ cancelHeartbeat()
+ }
+
// ── WiFi pause ────────────────────────────────────────────────────────
/** Stops GPS and updates state when an unmetered network becomes active. */
private fun activateWifiPause() {
isWifiPaused = true
- dbHelper.saveSetting("pause_zone_wifi_active", "true")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE, "true")
stopLocationUpdates()
- updateNotification(forceUpdate = true)
+ refreshNotificationForCurrentState()
LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, "wifi")
AppLogger.i(TAG, "Unmetered network available - WiFi pause active")
}
@@ -753,7 +763,7 @@ class LocationForegroundService : Service() {
withContext(Dispatchers.Main) {
if (isWifiPaused && unmeteredNetworkCount == 0) {
isWifiPaused = false
- dbHelper.saveSetting("pause_zone_wifi_active", "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE, "false")
maybeResumeGps()
LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, if (isMotionlessPaused) "motionless" else null)
AppLogger.i(TAG, "GPS resumed after unmetered network lost")
@@ -776,7 +786,7 @@ class LocationForegroundService : Service() {
wifiResumeJob = null
unmeteredNetworkCount = 0
isWifiPaused = false
- dbHelper.saveSetting("pause_zone_wifi_active", "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE, "false")
val cb = wifiCallback ?: return
wifiCallback = null
try {
@@ -800,10 +810,10 @@ class LocationForegroundService : Service() {
motionlessJob = null
if (insidePauseZone && !isMotionlessPaused) {
isMotionlessPaused = true
- dbHelper.saveSetting("pause_zone_motionless_active", "true")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "true")
stopLocationUpdates()
motionDetector?.arm()
- updateNotification(forceUpdate = true)
+ refreshNotificationForCurrentState()
LocationServiceModule.sendPauseZoneEvent(true, currentZoneName, "motionless")
AppLogger.i(TAG, "Motionless timeout reached - GPS paused, motion sensor armed")
}
@@ -818,7 +828,7 @@ class LocationForegroundService : Service() {
private fun clearMotionlessPauseState() {
isMotionlessPaused = false
- dbHelper.saveSetting("pause_zone_motionless_active", "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "false")
if (!profileManager.isStationary) motionDetector?.disarm()
}
@@ -860,7 +870,7 @@ class LocationForegroundService : Service() {
return
}
- val location = android.location.Location("geofence").apply {
+ val location = Location("geofence").apply {
latitude = zone.lat
longitude = zone.lon
accuracy = zone.radius.toFloat()
@@ -870,16 +880,8 @@ class LocationForegroundService : Service() {
val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
val timestampSec = location.time / 1000
- val currentFieldMap = fieldMap ?: emptyMap()
-
- val payload = payloadBuilder.buildPayload(
- location,
- battery,
- batteryStatus,
- if (config.apiFormat == NetworkManager.FORMAT_TRACCAR_JSON) emptyMap() else currentFieldMap,
- timestampSec,
- customFields
- )
+
+ val payload = PayloadBuilder.buildLocationPayload(location, timestampSec, battery, batteryStatus, payloadFieldMap, payloadCustomFields, config.apiFormat)
val sent = networkManager.sendToEndpoint(
payload, config.endpoint, secureStorage.getAuthHeaders(),
@@ -900,7 +902,7 @@ class LocationForegroundService : Service() {
timestamp = timestampSec,
endpoint = config.endpoint
)
- dbHelper.markLocationSent(locationId)
+ dbHelper.markLocationsSent(listOf(locationId))
LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
AppLogger.d(TAG, "Heartbeat sent: lat=${location.latitude}, lon=${location.longitude}")
} else {
@@ -929,13 +931,13 @@ class LocationForegroundService : Service() {
* Use this instead of calling [setupLocationUpdates] directly in WiFi/motionless resume paths.
*/
private fun maybeResumeGps() {
- val geofence = currentZoneGeofence ?: run { setupLocationUpdates(); updateNotification(forceUpdate = true); return }
+ val geofence = currentZoneGeofence ?: run { setupLocationUpdates(); refreshNotificationForCurrentState(); return }
val wifiHold = geofence.pauseOnWifi && isWifiPaused
val motionHold = geofence.pauseOnMotionless && isMotionlessPaused
if (!wifiHold && !motionHold) {
AppLogger.i(TAG, "GPS resumed - all pause holds cleared")
setupLocationUpdates()
- updateNotification(forceUpdate = true)
+ refreshNotificationForCurrentState()
} else {
AppLogger.i(TAG, "GPS still held: wifi=$wifiHold motionless=$motionHold")
}
@@ -953,9 +955,8 @@ class LocationForegroundService : Service() {
val anchorTimeSec = anchorTimeMs / 1000
val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
- val currentFieldMap = fieldMap ?: emptyMap()
- val syntheticLocation = android.location.Location("geofence").apply {
+ val syntheticLocation = Location("geofence").apply {
latitude = geofence.lat
longitude = geofence.lon
accuracy = geofence.radius.toFloat()
@@ -976,15 +977,7 @@ class LocationForegroundService : Service() {
endpoint = config.endpoint
)
- val payload = payloadBuilder.buildPayload(
- syntheticLocation,
- battery,
- batteryStatus,
- // emptyMap() keeps internal field names (lat/lon/vel/bear/...) so buildTraccarJsonPayload can read them directly
- if (config.apiFormat == NetworkManager.FORMAT_TRACCAR_JSON) emptyMap() else currentFieldMap,
- anchorTimeSec,
- customFields
- )
+ val payload = PayloadBuilder.buildLocationPayload(syntheticLocation, anchorTimeSec, battery, batteryStatus, payloadFieldMap, payloadCustomFields, config.apiFormat)
syncManager.queueAndSend(locationId, payload)
@@ -992,22 +985,31 @@ class LocationForegroundService : Service() {
}
}
+ /**
+ * Forces a notification refresh using the current pause/zone state and last known location.
+ * Call after any pause-state change (enter/exit zone, wifi/motionless activate/clear, profile swap).
+ *
+ * Contract: this reads [insidePauseZone], [currentZoneName], and [lastKnownLocation] directly.
+ * Callers MUST mutate those fields (and persist pause-state settings when relevant)
+ * BEFORE invoking this — order is state → DB → refresh. Refreshing before the state
+ * is written will render a stale notification.
+ */
+ private fun refreshNotificationForCurrentState() {
+ val loc = lastKnownLocation
+ updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
+ }
+
private fun updateNotification(
lat: Double? = null,
lon: Double? = null,
- pausedInZone: Boolean = false,
- zoneName: String? = null,
forceUpdate: Boolean = false
) {
- val isCurrentlyPaused = pausedInZone || insidePauseZone
- val activeZone = zoneName ?: currentZoneName
-
val offline = ::config.isInitialized && config.isOfflineMode
notificationHelper.update(
lat = lat,
lon = lon,
- isPaused = isCurrentlyPaused,
- zoneName = activeZone,
+ isPaused = insidePauseZone,
+ zoneName = currentZoneName,
queuedCount = if (offline) 0 else syncManager.getCachedQueuedCount(),
lastSyncTime = if (offline) 0L else syncManager.lastSuccessfulSyncTime,
activeProfileName = profileManager.getActiveProfileName(),
@@ -1028,10 +1030,10 @@ class LocationForegroundService : Service() {
}
LocationServiceModule.sendTrackingStoppedEvent(reason)
- dbHelper.saveSetting("tracking_enabled", "false")
- dbHelper.saveSetting("pause_zone_name", "")
- dbHelper.saveSetting("pause_zone_wifi_active", "false")
- dbHelper.saveSetting("pause_zone_motionless_active", "false")
+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_NAME, "")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE, "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "false")
stopForeground(Service.STOP_FOREGROUND_DETACH)
@@ -1081,8 +1083,7 @@ class LocationForegroundService : Service() {
stopLocationUpdates()
setupLocationUpdates()
- val loc = lastKnownLocation
- updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
+ refreshNotificationForCurrentState()
AppLogger.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} - interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")
}
@@ -1115,19 +1116,16 @@ class LocationForegroundService : Service() {
profileManager.defaultDistance = config.minUpdateDistance
profileManager.defaultSyncInterval = config.syncIntervalSeconds
- config.fieldMap?.let {
- if (it.isNotBlank()) fieldMap = payloadBuilder.parseFieldMap(it)
- }
-
- config.customFields?.let {
- if (it.isNotBlank()) customFields = payloadBuilder.parseCustomFields(it)
- }
+ val parsedFieldMap = PayloadBuilder.parseFieldMap(config.fieldMap) ?: emptyMap()
+ val parsedCustomFields = PayloadBuilder.parseCustomFields(config.customFields) ?: emptyMap()
+ payloadFieldMap = parsedFieldMap
+ payloadCustomFields = parsedCustomFields
AppLogger.d(TAG, buildString {
append("Config loaded: interval=${config.interval}ms, distance=${config.minUpdateDistance}m, accuracy=${config.accuracyThreshold}m")
append(", endpoint=${if (config.endpoint.isBlank()) "NOT CONFIGURED" else config.endpoint}")
append(", offline=${config.isOfflineMode}, sync=${if (config.syncIntervalSeconds == 0) "instant" else "${config.syncIntervalSeconds}s"}")
- if (!fieldMap.isNullOrEmpty()) append(", fieldMap=${fieldMap!!.size} mappings")
+ if (parsedFieldMap.isNotEmpty()) append(", fieldMap=${parsedFieldMap.size} mappings")
})
}
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
index 8928f13d..bd29ca16 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
@@ -13,9 +13,9 @@ import com.Colota.MainActivity
import java.util.Locale
/**
- * Handles all notification-related logic for the location tracking service:
- * channel creation, notification building, status text generation,
- * throttling, movement filtering, and deduplication.
+ * Main-thread only. All callers run on Main (onStartCommand, FLP callback,
+ * or `withContext(Dispatchers.Main)` inside serviceScope), so state fields
+ * do not need @Volatile.
*/
class NotificationHelper(
private val context: Context,
@@ -66,7 +66,6 @@ class NotificationHelper(
.build()
}
- /** Returns the notification title, including the active profile name if one is set. */
fun buildTitle(activeProfileName: String?): String =
if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"
@@ -80,25 +79,20 @@ class NotificationHelper(
.build()
}
- /**
- * Returns the best status text for the initial startForeground notification.
- */
+ /** Status text for the initial startForeground notification, before any location arrives. */
fun getInitialStatus(
insidePauseZone: Boolean,
currentZoneName: String?,
lastKnownLocation: android.location.Location?
): String = when {
insidePauseZone -> "Paused: ${currentZoneName ?: "Unknown"}"
- lastKnownLocation != null -> String.format(
- Locale.US, "%.5f, %.5f",
- lastKnownLocation.latitude, lastKnownLocation.longitude
- )
+ lastKnownLocation != null -> formatCoords(lastKnownLocation.latitude, lastKnownLocation.longitude)
else -> "Searching GPS..."
}
- /**
- * Builds the notification status text from current tracking state.
- */
+ private fun formatCoords(lat: Double, lon: Double): String =
+ String.format(Locale.US, "%.5f, %.5f", lat, lon)
+
fun buildStatusText(
isPaused: Boolean,
zoneName: String?,
@@ -120,11 +114,11 @@ class NotificationHelper(
}
}
isStationary -> {
- val coords = if (lat != null && lon != null) String.format(Locale.US, "%.5f, %.5f", lat, lon) else ""
+ val coords = if (lat != null && lon != null) formatCoords(lat, lon) else ""
if (coords.isNotEmpty()) "Stationary - $coords" else "Stationary - GPS paused"
}
lat != null && lon != null -> {
- val coords = String.format(Locale.US, "%.5f, %.5f", lat, lon)
+ val coords = formatCoords(lat, lon)
if (isOfflineMode) {
coords
} else if (queuedCount > 0 && lastSyncTime > 0) {
@@ -140,9 +134,6 @@ class NotificationHelper(
else -> "Searching GPS..."
}
- /**
- * Formats elapsed time since last successful sync.
- */
fun formatTimeSinceSync(lastSyncTime: Long, now: Long = System.currentTimeMillis()): String {
if (lastSyncTime == 0L) return "Never"
@@ -158,16 +149,11 @@ class NotificationHelper(
}
}
- /** Returns true if the update should be suppressed (too soon since last update). */
fun shouldThrottle(now: Long): Boolean = (now - lastUpdateTime) < THROTTLE_MS
- /** Returns true if movement is below the minimum threshold. */
fun shouldFilterByMovement(distanceMeters: Float): Boolean = distanceMeters < MIN_MOVEMENT_METERS
- /**
- * Full notification update with throttle, movement filter, and dedup.
- * Returns true if the notification was actually posted.
- */
+ /** Runs throttle + movement filter + dedup. Returns true if the notification was posted. */
fun update(
lat: Double? = null,
lon: Double? = null,
@@ -186,8 +172,7 @@ class NotificationHelper(
val queueCountChanged = queuedCount != lastQueuedCount
- // Throttle + movement filter (zone changes always pass forceUpdate=true)
- // Bypass movement filter when queue count changed so status text stays current
+ // Bypass throttle/movement filter when queue count changed, so queue status stays current.
if (!forceUpdate && !queueCountChanged && lat != null && lon != null) {
if (shouldThrottle(now)) return false
@@ -208,8 +193,7 @@ class NotificationHelper(
val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary, isWifiPaused, isMotionlessPaused)
- // Dedup: skip if notification text hasn't changed (bypass on forceUpdate so state-change
- // notifications always reach Android even if text appears identical)
+ // forceUpdate bypasses dedup so state-change posts land even when the text is unchanged.
val cacheKey = "$statusText-$queuedCount-$activeProfileName"
if (!forceUpdate && cacheKey == lastText) return false
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
index 9f21ad57..f1a61dd4 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
@@ -19,32 +19,45 @@ import kotlinx.coroutines.*
*
* @param profileHelper CRUD access to profile database
* @param scope Coroutine scope for deactivation delay timers
- * @param onConfigSwitch Callback to apply new interval/distance/sync params
+ * @param onConfigSwitch Callback to apply the resolved profile config (or defaults when null-profile)
*/
class ProfileManager(
private val profileHelper: ProfileHelper,
private val scope: CoroutineScope,
- private val onConfigSwitch: (interval: Long, distance: Float, syncInterval: Int, profileName: String?, profileId: Int?) -> Unit,
+ private val onConfigSwitch: (ProfileConfig) -> Unit,
private val onStationaryChanged: ((stationary: Boolean) -> Unit)? = null
) {
companion object {
private const val TAG = "ProfileManager"
}
- // Default config values (set by the service after loading config)
+ data class ProfileConfig(
+ val interval: Long,
+ val distance: Float,
+ val syncInterval: Int,
+ val profileName: String?,
+ val profileId: Int?,
+ )
+
+ // Default config (written externally by the service, read inside @Synchronized deactivateToDefault)
@Volatile var defaultInterval: Long = 5000L
@Volatile var defaultDistance: Float = 0f
@Volatile var defaultSyncInterval: Int = 0
- // Current active profile (null = using default settings)
+ // Active profile: mutated only inside @Synchronized methods.
+ // @Volatile because getActiveProfileName() is read externally without the lock.
@Volatile private var activeProfile: ProfileHelper.CachedProfile? = null
- @Volatile private var deactivationJob: Job? = null
+ // Accessed only inside @Synchronized methods — the intrinsic lock covers visibility.
+ private var deactivationJob: Job? = null
- // Condition states
+ // Condition flags: written from broadcast callbacks, each write immediately followed by
+ // @Synchronized evaluate() which reads them. @Volatile makes the write visible to readers
+ // already holding the lock on another thread.
@Volatile private var isCharging = false
@Volatile private var isCarMode = false
@Volatile var isStationary = false
private set
+ // Written/read from location + motion callbacks without synchronization.
@Volatile private var stationaryJob: Job? = null
// Speed rolling average buffer
@@ -93,7 +106,7 @@ class ProfileManager(
fun getActiveProfileName(): String? = activeProfile?.name
fun getNeededConditionTypes(): Set<String> =
- profileHelper.getEnabledProfiles().map { it.conditionType }.toSet()
+ profileHelper.getEnabledProfiles().mapTo(HashSet()) { it.conditionType }
/**
* Re-evaluates all enabled profiles against current conditions.
@@ -198,13 +211,13 @@ class ProfileManager(
LocationServiceModule.sendProfileSwitchEvent(profile.name, profile.id)
// Apply config
- onConfigSwitch(
- profile.intervalMs,
- profile.minUpdateDistance,
- profile.syncIntervalSeconds,
- profile.name,
- profile.id
- )
+ onConfigSwitch(ProfileConfig(
+ interval = profile.intervalMs,
+ distance = profile.minUpdateDistance,
+ syncInterval = profile.syncIntervalSeconds,
+ profileName = profile.name,
+ profileId = profile.id,
+ ))
}
private fun scheduleDeactivation(profile: ProfileHelper.CachedProfile) {
@@ -275,6 +288,12 @@ class ProfileManager(
LocationServiceModule.sendProfileSwitchEvent(null, null)
// Revert to default config
- onConfigSwitch(defaultInterval, defaultDistance, defaultSyncInterval, null, null)
+ onConfigSwitch(ProfileConfig(
+ interval = defaultInterval,
+ distance = defaultDistance,
+ syncInterval = defaultSyncInterval,
+ profileName = null,
+ profileId = null,
+ ))
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
index 4a6f804a..daa58510 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
@@ -8,7 +8,7 @@ package com.Colota.service
import android.content.Intent
import android.os.Bundle
import com.Colota.data.DatabaseHelper
-import com.Colota.sync.NetworkManager
+import com.Colota.sync.ApiFormat
import com.facebook.react.bridge.ReadableMap
import org.json.JSONObject
@@ -29,14 +29,14 @@ data class ServiceConfig(
val fieldMap: String? = null,
val customFields: String? = null,
val httpMethod: String = "POST",
- val apiFormat: String = ""
+ val apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
) {
companion object {
fun fromDatabase(dbHelper: DatabaseHelper): ServiceConfig {
val saved = dbHelper.getAllSettings()
val httpMethod = saved["httpMethod"] ?: "POST"
val apiTemplate = saved["apiTemplate"] ?: ""
- val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") NetworkManager.FORMAT_TRACCAR_JSON else ""
+ val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") ApiFormat.TRACCAR_JSON else ApiFormat.FIELD_MAPPED
return ServiceConfig(
endpoint = saved["endpoint"] ?: "",
@@ -81,7 +81,7 @@ data class ServiceConfig(
val httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod
val apiTemplate = config.getStringOrNull("apiTemplate") ?: ""
- val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") NetworkManager.FORMAT_TRACCAR_JSON else ""
+ val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") ApiFormat.TRACCAR_JSON else ApiFormat.FIELD_MAPPED
return ServiceConfig(
endpoint = config.getStringOrNull("endpoint") ?: dbConfig.endpoint,
@@ -119,11 +119,13 @@ data class ServiceConfig(
fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap),
customFields = extras.getStringOrDefault("customFields", dbConfig.customFields),
httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST",
- apiFormat = extras.getStringOrDefault("apiFormat", dbConfig.apiFormat) ?: ""
+ apiFormat = if (extras.containsKey("apiFormat"))
+ ApiFormat.fromWire(extras.getString("apiFormat"))
+ else dbConfig.apiFormat
)
}
}
-
+
fun toIntent(intent: Intent): Intent {
return intent.apply {
putExtra("interval", interval)
@@ -139,7 +141,7 @@ data class ServiceConfig(
fieldMap?.let { putExtra("fieldMap", it) }
customFields?.let { putExtra("customFields", it) }
putExtra("httpMethod", httpMethod)
- putExtra("apiFormat", apiFormat)
+ putExtra("apiFormat", apiFormat.wireName)
}
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ShortcutHandlerActivity.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ShortcutHandlerActivity.kt
index edb35dca..a1e5380d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ShortcutHandlerActivity.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ShortcutHandlerActivity.kt
@@ -9,6 +9,7 @@ import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
import com.Colota.util.AppLogger
/**
@@ -38,8 +39,8 @@ class ShortcutHandlerActivity : Activity() {
}
ACTION_STOP -> {
AppLogger.d(TAG, "Shortcut: stop tracking")
- dbHelper.saveSetting("tracking_enabled", "false")
- dbHelper.saveSetting("pause_zone_name", "")
+ dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+ dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_NAME, "")
stopService(Intent(this, LocationForegroundService::class.java))
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/ApiFormat.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/ApiFormat.kt
new file mode 100644
index 00000000..8cfa7a70
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/ApiFormat.kt
@@ -0,0 +1,25 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.sync
+
+/**
+ * Supported outbound payload formats. FIELD_MAPPED applies the user's fieldMap;
+ * TRACCAR_JSON uses fixed internal field names so the wire transform in
+ * NetworkManager.buildTraccarJsonPayload can read them back unambiguously.
+ *
+ * Wire names are the string values persisted in settings and on the JS bridge.
+ */
+enum class ApiFormat(val wireName: String) {
+ FIELD_MAPPED(""),
+ TRACCAR_JSON("traccar_json");
+
+ val usesFixedFieldNames: Boolean get() = this == TRACCAR_JSON
+
+ companion object {
+ fun fromWire(wire: String?): ApiFormat =
+ values().firstOrNull { it.wireName == wire } ?: FIELD_MAPPED
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index b2109ce0..69b9da0f 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -31,7 +31,6 @@ class NetworkManager(private val context: Context) {
private const val CONNECTION_TIMEOUT = 10000
private const val READ_TIMEOUT = 10000
private const val NETWORK_CHECK_CACHE_MS = 5000L
- const val FORMAT_TRACCAR_JSON = "traccar_json"
}
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -43,33 +42,37 @@ class NetworkManager(private val context: Context) {
private val networkCallback = createNetworkCallback()
private fun createNetworkCallback(): ConnectivityManager.NetworkCallback {
+ fun update(caps: NetworkCapabilities) {
+ currentSsid = readSsid(caps)
+ isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
+ }
+ fun clear() {
+ currentSsid = ""
+ isVpn = false
+ }
+
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {
- override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) {
- val wifiInfo = caps.transportInfo as? WifiInfo
- currentSsid = wifiInfo?.ssid?.removeSurrounding("\"") ?: ""
- isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
- }
- override fun onLost(network: Network) {
- currentSsid = ""
- isVpn = false
- }
+ override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = update(caps)
+ override fun onLost(network: Network) = clear()
}
} else {
object : ConnectivityManager.NetworkCallback() {
- @Suppress("DEPRECATION")
- override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) {
- currentSsid = wifiManager?.connectionInfo?.ssid?.removeSurrounding("\"") ?: ""
- isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
- }
- override fun onLost(network: Network) {
- currentSsid = ""
- isVpn = false
- }
+ override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = update(caps)
+ override fun onLost(network: Network) = clear()
}
}
}
+ private fun readSsid(caps: NetworkCapabilities): String {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (caps.transportInfo as? WifiInfo)?.ssid?.removeSurrounding("\"") ?: ""
+ } else {
+ @Suppress("DEPRECATION")
+ wifiManager?.connectionInfo?.ssid?.removeSurrounding("\"") ?: ""
+ }
+ }
+
init {
try {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
@@ -100,7 +103,7 @@ class NetworkManager(private val context: Context) {
endpoint: String,
extraHeaders: Map<String, String> = emptyMap(),
httpMethod: String = "POST",
- apiFormat: String = ""
+ apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
): Boolean = withContext(Dispatchers.IO) {
if (endpoint.isBlank()) {
AppLogger.d(TAG, "Empty endpoint provided")
@@ -127,8 +130,8 @@ class NetworkManager(private val context: Context) {
}
val transformedPayload = when (apiFormat) {
- FORMAT_TRACCAR_JSON -> buildTraccarJsonPayload(payload)
- else -> payload
+ ApiFormat.TRACCAR_JSON -> buildTraccarJsonPayload(payload)
+ ApiFormat.FIELD_MAPPED -> payload
}
val isGet = httpMethod.equals("GET", ignoreCase = true)
@@ -143,54 +146,10 @@ class NetworkManager(private val context: Context) {
var connection: HttpURLConnection? = null
try {
- connection = targetUrl.openConnection() as HttpURLConnection
- connection.apply {
- requestMethod = if (isGet) "GET" else "POST"
- if (!isGet) {
- setRequestProperty("Content-Type", "application/json; charset=UTF-8")
- setRequestProperty("Accept", "application/json")
- doOutput = true
- }
- extraHeaders.forEach { (key, value) ->
- setRequestProperty(key, value)
- }
- connectTimeout = CONNECTION_TIMEOUT
- readTimeout = READ_TIMEOUT
- useCaches = false
- }
-
- if (BuildConfig.DEBUG) {
- AppLogger.d(TAG, "=== HTTP REQUEST ===")
- AppLogger.d(TAG, "Endpoint: ${if (isGet) targetUrl else resolvedEndpoint}")
- AppLogger.d(TAG, "Method: ${connection.requestMethod}")
- AppLogger.d(TAG, "Headers:")
- connection.requestProperties.forEach { (key, values) ->
- val masked = values.map { maskSensitiveHeaderValue(key, it) }
- AppLogger.d(TAG, "$key: ${masked.joinToString()}")
- }
- if (!isGet) {
- AppLogger.d(TAG, "Body: ${transformedPayload.toString(2)}")
- }
- AppLogger.d(TAG, "===================")
- }
-
- if (!isGet) {
- val bodyBytes = transformedPayload.toString().toByteArray(StandardCharsets.UTF_8)
- connection.setFixedLengthStreamingMode(bodyBytes.size)
- connection.outputStream.use { it.write(bodyBytes) }
- }
-
- val responseCode = connection.responseCode
- return@withContext if (responseCode in 200..299) {
- AppLogger.d(TAG, "Location successfully sent")
- true
- } else {
- val errorBody = try {
- connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"
- } catch (_: Exception) { "Could not read error body" }
- AppLogger.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")
- false
- }
+ connection = buildConnection(targetUrl, isGet, extraHeaders)
+ logRequest(connection, isGet, resolvedEndpoint, targetUrl, transformedPayload)
+ if (!isGet) writeBody(connection, transformedPayload)
+ return@withContext readResponse(connection)
} catch (e: java.net.SocketException) {
if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {
AppLogger.e(TAG, "Local network access denied - grant Local Network Access permission", e)
@@ -206,6 +165,64 @@ class NetworkManager(private val context: Context) {
}
}
+ private fun buildConnection(
+ targetUrl: URL,
+ isGet: Boolean,
+ extraHeaders: Map<String, String>,
+ ): HttpURLConnection = (targetUrl.openConnection() as HttpURLConnection).apply {
+ requestMethod = if (isGet) "GET" else "POST"
+ if (!isGet) {
+ setRequestProperty("Content-Type", "application/json; charset=UTF-8")
+ setRequestProperty("Accept", "application/json")
+ doOutput = true
+ }
+ extraHeaders.forEach { (key, value) -> setRequestProperty(key, value) }
+ connectTimeout = CONNECTION_TIMEOUT
+ readTimeout = READ_TIMEOUT
+ useCaches = false
+ }
+
+ private fun writeBody(connection: HttpURLConnection, payload: JSONObject) {
+ val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)
+ connection.setFixedLengthStreamingMode(bodyBytes.size)
+ connection.outputStream.use { it.write(bodyBytes) }
+ }
+
+ private fun readResponse(connection: HttpURLConnection): Boolean {
+ val responseCode = connection.responseCode
+ if (responseCode in 200..299) {
+ AppLogger.d(TAG, "Location successfully sent")
+ return true
+ }
+ val errorBody = try {
+ connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"
+ } catch (_: Exception) { "Could not read error body" }
+ AppLogger.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")
+ return false
+ }
+
+ private fun logRequest(
+ connection: HttpURLConnection,
+ isGet: Boolean,
+ resolvedEndpoint: String,
+ targetUrl: URL,
+ payload: JSONObject,
+ ) {
+ if (!BuildConfig.DEBUG) return
+ AppLogger.d(TAG, "=== HTTP REQUEST ===")
+ AppLogger.d(TAG, "Endpoint: ${if (isGet) targetUrl else resolvedEndpoint}")
+ AppLogger.d(TAG, "Method: ${connection.requestMethod}")
+ AppLogger.d(TAG, "Headers:")
+ connection.requestProperties.forEach { (key, values) ->
+ val masked = values.map { maskSensitiveHeaderValue(key, it) }
+ AppLogger.d(TAG, "$key: ${masked.joinToString()}")
+ }
+ if (!isGet) {
+ AppLogger.d(TAG, "Body: ${payload.toString(2)}")
+ }
+ AppLogger.d(TAG, "===================")
+ }
+
/**
* Returns true if the endpoint's host resolves to a private/local address.
* Performs DNS resolution and caches the result.
@@ -235,13 +252,13 @@ class NetworkManager(private val context: Context) {
return true
}
+ /** Per-hostname cache of the DNS lookup + private-range check. */
private val privateHostCache = java.util.concurrent.ConcurrentHashMap<String, Boolean>()
/**
* Checks if the given host is private or local.
* Matches Android's local network definition:
* loopback, site-local (RFC 1918), link-local, and CGNAT (100.64.0.0/10).
- * Results are cached to avoid repeated DNS lookups on every request.
*/
private fun isPrivateHost(host: String): Boolean {
if (host == "localhost") return true
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
index eb5dbe6c..61603d7b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
@@ -10,48 +10,43 @@ import com.Colota.util.AppLogger
import org.json.JSONObject
import kotlin.math.roundToInt
-/**
- * Builds and parses location payloads with dynamic field mapping.
- */
-class PayloadBuilder {
+/** Stateless builder for outgoing location payloads. */
+object PayloadBuilder {
- companion object {
- private const val TAG = "PayloadBuilder"
- }
+ private const val TAG = "PayloadBuilder"
- /**
- * Builds a JSON payload from location data, applying field name mapping and custom fields.
- */
- fun buildPayload(
+ fun buildLocationPayload(
location: Location,
+ timestamp: Long,
batteryLevel: Int,
batteryStatus: Int,
fieldMap: Map<String, String>,
- timestamp: Long,
- customFields: Map<String, String>? = null
+ customFields: Map<String, String>,
+ apiFormat: ApiFormat,
): JSONObject {
+ val effectiveFieldMap = if (apiFormat.usesFixedFieldNames) emptyMap() else fieldMap
return JSONObject().apply {
- customFields?.forEach { (key, value) ->
+ customFields.forEach { (key, value) ->
put(key, value)
}
- put(fieldMap["lat"] ?: "lat", location.latitude)
- put(fieldMap["lon"] ?: "lon", location.longitude)
- put(fieldMap["acc"] ?: "acc", location.accuracy.roundToInt())
+ put(effectiveFieldMap["lat"] ?: "lat", location.latitude)
+ put(effectiveFieldMap["lon"] ?: "lon", location.longitude)
+ put(effectiveFieldMap["acc"] ?: "acc", location.accuracy.roundToInt())
if (location.hasAltitude()) {
- put(fieldMap["alt"] ?: "alt", location.altitude.roundToInt())
+ put(effectiveFieldMap["alt"] ?: "alt", location.altitude.roundToInt())
}
if (location.hasSpeed()) {
- put(fieldMap["vel"] ?: "vel", Math.round(location.speed * 10.0f) / 10.0)
+ put(effectiveFieldMap["vel"] ?: "vel", Math.round(location.speed * 10.0f) / 10.0)
}
- put(fieldMap["batt"] ?: "batt", batteryLevel)
- put(fieldMap["bs"] ?: "bs", batteryStatus)
- put(fieldMap["tst"] ?: "tst", timestamp)
+ put(effectiveFieldMap["batt"] ?: "batt", batteryLevel)
+ put(effectiveFieldMap["bs"] ?: "bs", batteryStatus)
+ put(effectiveFieldMap["tst"] ?: "tst", timestamp)
if (location.hasBearing()) {
- put(fieldMap["bear"] ?: "bear", location.bearing.toDouble())
+ put(effectiveFieldMap["bear"] ?: "bear", location.bearing.toDouble())
}
}
}
@@ -95,4 +90,4 @@ class PayloadBuilder {
}
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
index 5a8d04b1..8332741d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
@@ -34,7 +34,7 @@ class SyncManager(
@Volatile private var syncSsid: String = ""
@Volatile private var authHeaders: Map<String, String> = emptyMap()
@Volatile private var httpMethod: String = "POST"
- @Volatile private var apiFormat: String = ""
+ @Volatile private var apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
private var syncJob: Job? = null
@Volatile private var lastSyncTime: Long = 0
@@ -54,7 +54,7 @@ class SyncManager(
syncSsid: String,
authHeaders: Map<String, String>,
httpMethod: String = "POST",
- apiFormat: String = ""
+ apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED,
) {
this.endpoint = endpoint
this.syncIntervalSeconds = syncIntervalSeconds
@@ -146,7 +146,7 @@ class SyncManager(
val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod, apiFormat)
if (success) {
- dbHelper.markLocationSent(locationId)
+ dbHelper.markLocationsSent(listOf(locationId))
dbHelper.removeFromQueueByLocationId(locationId)
invalidateQueueCache()
lastSuccessfulSyncTime = System.currentTimeMillis()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/geo/Geo.kt b/apps/mobile/android/app/src/main/java/com/colota/util/geo/Geo.kt
new file mode 100644
index 00000000..69eaf502
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/geo/Geo.kt
@@ -0,0 +1,31 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.util.geo
+
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.pow
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+const val EARTH_RADIUS_METERS = 6371000.0
+
+/** Haversine great-circle distance in meters. Accurate at any distance on Earth. */
+fun haversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
+ val dLat = Math.toRadians(lat2 - lat1)
+ val dLon = Math.toRadians(lon2 - lon1)
+ val a = sin(dLat / 2).pow(2) +
+ cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2).pow(2)
+ return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))
+}
+
+/** Fast bounding-box rejection followed by haversine check. */
+fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radius: Double): Boolean {
+ val maxLatDeg = radius / 111000.0
+ val maxLonDeg = radius / (111000.0 * cos(Math.toRadians(lat1)))
+ if (Math.abs(lat1 - lat2) > maxLatDeg || Math.abs(lon1 - lon2) > maxLonDeg) return false
+ return haversineDistance(lat1, lon1, lat2, lon2) <= radius
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
index bb33f493..e7a083c5 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
@@ -400,7 +400,7 @@ class DatabaseHelperSQLiteTest {
val queued = db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L)
val sent = db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 2000L)
db.addToQueue(queued, """{"lat":52.0}""")
- db.markLocationSent(sent)
+ db.markLocationsSent(listOf(sent))
val deleted = db.clearSentHistory()
assertEquals(1, deleted)
@@ -766,23 +766,6 @@ class DatabaseHelperSQLiteTest {
assertTrue("Distance should be < 40km, was $distance", distance < 40000)
}
- // ========================================================================
- // haversineDistance
- // ========================================================================
-
- @Test
- fun `haversineDistance Berlin to Munich is approximately 504 km`() {
- val distance = db.haversineDistance(52.52, 13.405, 48.1351, 11.582)
- assertTrue("Expected ~504km, got ${distance / 1000}km", distance > 500000)
- assertTrue("Expected ~504km, got ${distance / 1000}km", distance < 510000)
- }
-
- @Test
- fun `haversineDistance same point returns zero`() {
- val distance = db.haversineDistance(52.52, 13.405, 52.52, 13.405)
- assertEquals(0.0, distance, 0.001)
- }
-
// ========================================================================
// deleteOlderThan
// ========================================================================
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 7f9858ce..2f7d323d 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
@@ -41,99 +41,6 @@ class GeofenceHelperTest {
field.set(null, null)
}
- // Known reference distances (verified against online Haversine calculators):
- // Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km
- // New York (40.7128, -74.006) → London (51.5074, -0.1278) ≈ 5,570 km
- // Same point → 0 m
-
- @Test
- fun `calculateDistance returns zero for same point`() {
- val distance = GeofenceHelper.calculateDistance(52.52, 13.405, 52.52, 13.405)
- assertEquals(0.0, distance, 0.01)
- }
-
- @Test
- fun `calculateDistance Berlin to Munich is about 504 km`() {
- val distance = GeofenceHelper.calculateDistance(52.52, 13.405, 48.1351, 11.582)
- assertEquals(504_000.0, distance, 5000.0) // within 5 km tolerance
- }
-
- @Test
- fun `calculateDistance New York to London is about 5570 km`() {
- val distance = GeofenceHelper.calculateDistance(40.7128, -74.006, 51.5074, -0.1278)
- assertEquals(5_570_000.0, distance, 20_000.0) // within 20 km tolerance
- }
-
- @Test
- fun `calculateDistance is symmetric`() {
- val d1 = GeofenceHelper.calculateDistance(52.52, 13.405, 48.1351, 11.582)
- val d2 = GeofenceHelper.calculateDistance(48.1351, 11.582, 52.52, 13.405)
- assertEquals(d1, d2, 0.01)
- }
-
- @Test
- fun `calculateDistance across equator`() {
- // Quito (0.1807, -78.4678) → Bogota (4.711, -74.0721) ≈ 702 km
- val distance = GeofenceHelper.calculateDistance(0.1807, -78.4678, 4.711, -74.0721)
- assertEquals(702_000.0, distance, 5000.0)
- }
-
- @Test
- fun `calculateDistance across date line`() {
- // Auckland (−36.848, 174.763) → Fiji (−17.713, 177.986) ≈ 2160 km
- val distance = GeofenceHelper.calculateDistance(-36.848, 174.763, -17.713, 177.986)
- assertEquals(2_160_000.0, distance, 30_000.0)
- }
-
- @Test
- fun `isWithinRadius returns true for point inside`() {
- // 100m from Brandenburg Gate (52.5163, 13.3777) — a point 50m away
- val center = Pair(52.5163, 13.3777)
- // ~50m north ≈ +0.00045 degrees latitude
- assertTrue(GeofenceHelper.isWithinRadius(
- center.first, center.second,
- center.first + 0.00045, center.second,
- 100.0
- ))
- }
-
- @Test
- fun `isWithinRadius returns false for point outside`() {
- val center = Pair(52.5163, 13.3777)
- // ~200m north ≈ +0.0018 degrees latitude
- assertFalse(GeofenceHelper.isWithinRadius(
- center.first, center.second,
- center.first + 0.0018, center.second,
- 100.0
- ))
- }
-
- @Test
- fun `isWithinRadius returns true for point exactly on boundary`() {
- val center = Pair(52.5163, 13.3777)
- val distance = GeofenceHelper.calculateDistance(
- center.first, center.second,
- center.first + 0.0009, center.second
- )
- // Use the actual distance as radius — should be on boundary
- assertTrue(GeofenceHelper.isWithinRadius(
- center.first, center.second,
- center.first + 0.0009, center.second,
- distance
- ))
- }
-
- @Test
- fun `isWithinRadius same point is always within any radius`() {
- assertTrue(GeofenceHelper.isWithinRadius(52.52, 13.405, 52.52, 13.405, 1.0))
- }
-
- @Test
- fun `bounding box rejects distant points quickly`() {
- // Berlin to Munich (~504 km) with 1 km radius — should be rejected by bounding box
- assertFalse(GeofenceHelper.isWithinRadius(52.52, 13.405, 48.1351, 11.582, 1000.0))
- }
-
// =========================================================================
// getGeofenceByName
// =========================================================================
@@ -183,7 +90,7 @@ class GeofenceHelperTest {
val id = db.readableDatabase.query("geofences", arrayOf("id"), "name = ?", arrayOf("Home"), null, null, null).use {
it.moveToFirst(); it.getInt(0)
}
- helper.updateGeofence(id, en = false, name = null, lat = null, lon = null, rad = null, pause = null)
+ helper.updateGeofence(id, enabled = false)
helper.invalidateCache()
assertNull(helper.getGeofenceByName("Home"))
@@ -249,7 +156,7 @@ class GeofenceHelperTest {
val id = db.readableDatabase.query("geofences", arrayOf("id"), "name = ?", arrayOf("Home"), null, null, null).use {
it.moveToFirst(); it.getInt(0)
}
- helper.updateGeofence(id, en = false, name = null, lat = null, lon = null, rad = null, pause = null)
+ helper.updateGeofence(id, enabled = false)
helper.invalidateCache()
val location = mockLocation(52.5, 13.4)
@@ -321,4 +228,29 @@ class GeofenceHelperTest {
io.mockk.every { longitude } returns lon
}
}
+
+ /** Test-local convenience: maps test's `rad`/`pause` names to the helper's `radius`/`pauseTracking`. */
+ private fun GeofenceHelper.insertGeofence(
+ name: String,
+ lat: Double,
+ lon: Double,
+ rad: Double,
+ pause: Boolean,
+ pauseOnWifi: Boolean = false,
+ pauseOnMotionless: Boolean = false,
+ motionlessTimeoutMinutes: Int = 10,
+ heartbeatEnabled: Boolean = false,
+ heartbeatIntervalMinutes: Int = 15,
+ ): Int = insertGeofence(
+ name = name,
+ lat = lat,
+ lon = lon,
+ radius = rad,
+ pauseTracking = pause,
+ pauseOnWifi = pauseOnWifi,
+ pauseOnMotionless = pauseOnMotionless,
+ motionlessTimeoutMinutes = motionlessTimeoutMinutes,
+ heartbeatEnabled = heartbeatEnabled,
+ heartbeatIntervalMinutes = heartbeatIntervalMinutes,
+ )
}
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 2d146090..abcc539b 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
@@ -39,7 +39,6 @@ class LocationForegroundServiceTest {
private lateinit var dbHelper: DatabaseHelper
private lateinit var geofenceHelper: GeofenceHelper
private lateinit var syncManager: SyncManager
- private lateinit var payloadBuilder: PayloadBuilder
private lateinit var deviceInfoHelper: DeviceInfoHelper
private lateinit var notificationHelper: NotificationHelper
private lateinit var profileManager: ProfileManager
@@ -59,7 +58,6 @@ class LocationForegroundServiceTest {
dbHelper = mockk(relaxed = true)
geofenceHelper = mockk(relaxed = true)
syncManager = mockk(relaxed = true)
- payloadBuilder = mockk(relaxed = true)
deviceInfoHelper = mockk(relaxed = true)
notificationHelper = mockk(relaxed = true)
profileManager = mockk(relaxed = true)
@@ -77,7 +75,10 @@ class LocationForegroundServiceTest {
every { deviceInfoHelper.isBatteryCritical(any()) } returns false
every { deviceInfoHelper.isBatteryCritical() } returns false
every { geofenceHelper.getPauseZone(any()) } returns null
- every { payloadBuilder.buildPayload(any(), any(), any(), any(), any(), any()) } returns JSONObject()
+ mockkObject(PayloadBuilder)
+ every { PayloadBuilder.buildLocationPayload(any(), any(), any(), any(), any(), any(), any()) } returns JSONObject()
+ every { PayloadBuilder.parseFieldMap(any()) } returns null
+ every { PayloadBuilder.parseCustomFields(any()) } returns null
every { syncManager.getCachedQueuedCount() } returns 0
every { syncManager.lastSuccessfulSyncTime } returns 0L
every { profileManager.getActiveProfileName() } returns null
@@ -113,6 +114,7 @@ class LocationForegroundServiceTest {
testScope.cancel()
Dispatchers.resetMain()
unmockkObject(LocationServiceModule)
+ unmockkObject(PayloadBuilder)
unmockkObject(AppLogger)
unmockkStatic(android.os.Looper::class)
}
@@ -122,7 +124,6 @@ class LocationForegroundServiceTest {
setField("dbHelper", dbHelper)
setField("geofenceHelper", geofenceHelper)
setField("syncManager", syncManager)
- setField("payloadBuilder", payloadBuilder)
setField("deviceInfoHelper", deviceInfoHelper)
setField("notificationHelper", notificationHelper)
setField("profileManager", profileManager)
@@ -229,17 +230,13 @@ class LocationForegroundServiceTest {
}
@Test
- fun `handleLocationUpdate builds payload with field map and custom fields`() = testScope.runTest {
+ fun `handleLocationUpdate builds location payload from PayloadBuilder`() = testScope.runTest {
val location = mockLocation()
- val fieldMap = mapOf("lat" to "latitude", "lon" to "longitude")
- val customFields = mapOf("device" to "test")
- setField("fieldMap", fieldMap)
- setField("customFields", customFields)
every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
invokeHandleLocationUpdate(location)
- verify { payloadBuilder.buildPayload(location, 80, 2, fieldMap, any(), customFields) }
+ verify { PayloadBuilder.buildLocationPayload(location, any(), 80, 2, any(), any(), any()) }
}
@Test
@@ -527,17 +524,6 @@ class LocationForegroundServiceTest {
) }
}
- @Test
- fun `handleLocationUpdate uses empty field map when none configured`() = testScope.runTest {
- setField("fieldMap", null)
- val location = mockLocation()
- every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
-
- invokeHandleLocationUpdate(location)
-
- verify { payloadBuilder.buildPayload(any(), any(), any(), emptyMap(), any(), any()) }
- }
-
// =========================================================================
// setupLocationUpdates - error handling
// =========================================================================
@@ -1889,27 +1875,6 @@ class LocationForegroundServiceTest {
verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
}
- // =========================================================================
- // handleLocationUpdate - Traccar format uses empty field map
- // =========================================================================
-
- @Test
- fun `handleLocationUpdate uses empty field map when apiFormat is traccar_json`() = testScope.runTest {
- setField("config", ServiceConfig(
- endpoint = "https://example.com",
- interval = 5000L,
- filterInaccurateLocations = false,
- apiFormat = "traccar_json"
- ))
- setField("fieldMap", mapOf("lat" to "latitude", "lon" to "longitude"))
- val location = mockLocation()
- every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
-
- invokeHandleLocationUpdate(location)
-
- verify { payloadBuilder.buildPayload(any(), any(), any(), emptyMap(), any(), any()) }
- }
-
// =========================================================================
// enterPauseZone - flush respects sync condition
// =========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
index f054083c..6f0c7831 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
@@ -34,12 +34,12 @@ class ProfileManagerTest {
private fun createManager(): ProfileManager {
return ProfileManager(
profileHelper, testScope,
- onConfigSwitch = { interval, distance, sync, name, id ->
- switchedInterval = interval
- switchedDistance = distance
- switchedSyncInterval = sync
- switchedProfileName = name
- switchedProfileId = id
+ onConfigSwitch = { config ->
+ switchedInterval = config.interval
+ switchedDistance = config.distance
+ switchedSyncInterval = config.syncInterval
+ switchedProfileName = config.profileName
+ switchedProfileId = config.profileId
switchCount++
},
onStationaryChanged = { stationary ->
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
index a73b1283..ec559e7f 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
@@ -8,6 +8,7 @@ package com.Colota.service
import android.content.Intent
import android.os.Bundle
import com.Colota.data.DatabaseHelper
+import com.Colota.sync.ApiFormat
import com.facebook.react.bridge.JavaOnlyMap
import io.mockk.every
import io.mockk.mockk
@@ -125,21 +126,21 @@ class ServiceConfigTest {
fun `fromDatabase derives apiFormat traccar_json for traccar template with POST`() {
val db = mockDbHelper(baseSettings + mapOf("apiTemplate" to "traccar", "httpMethod" to "POST"))
val config = ServiceConfig.fromDatabase(db)
- assertEquals("traccar_json", config.apiFormat)
+ assertEquals(ApiFormat.TRACCAR_JSON, config.apiFormat)
}
@Test
fun `fromDatabase returns empty apiFormat for traccar template with GET`() {
val db = mockDbHelper(baseSettings + mapOf("apiTemplate" to "traccar", "httpMethod" to "GET"))
val config = ServiceConfig.fromDatabase(db)
- assertEquals("", config.apiFormat)
+ assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
@Test
fun `fromDatabase returns empty apiFormat for non-traccar template`() {
val db = mockDbHelper(baseSettings + mapOf("apiTemplate" to "dawarich", "httpMethod" to "POST"))
val config = ServiceConfig.fromDatabase(db)
- assertEquals("", config.apiFormat)
+ assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
// --- data class defaults ---
@@ -257,7 +258,7 @@ class ServiceConfigTest {
assertEquals("wifi_any", config.syncCondition)
assertEquals("""{"lat":"latitude"}""", config.fieldMap)
assertEquals("GET", config.httpMethod)
- assertEquals("traccar_json", config.apiFormat)
+ assertEquals(ApiFormat.TRACCAR_JSON, config.apiFormat)
}
// --- toIntent ---
@@ -368,7 +369,7 @@ class ServiceConfigTest {
putString("httpMethod", "POST")
}
val config = ServiceConfig.fromReadableMap(map, db)
- assertEquals("traccar_json", config.apiFormat)
+ assertEquals(ApiFormat.TRACCAR_JSON, config.apiFormat)
}
@Test
@@ -379,7 +380,7 @@ class ServiceConfigTest {
putString("httpMethod", "GET")
}
val config = ServiceConfig.fromReadableMap(map, db)
- assertEquals("", config.apiFormat)
+ assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
@Test
@@ -390,7 +391,7 @@ class ServiceConfigTest {
putString("httpMethod", "POST")
}
val config = ServiceConfig.fromReadableMap(map, db)
- assertEquals("", config.apiFormat)
+ assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
@Test
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
index bccb72cf..007427a5 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
@@ -11,12 +11,8 @@ import org.junit.Test
class PayloadBuilderTest {
- private lateinit var builder: PayloadBuilder
-
@Before
fun setUp() {
- builder = PayloadBuilder()
-
mockkObject(AppLogger)
every { AppLogger.d(any(), any()) } just Runs
every { AppLogger.i(any(), any()) } just Runs
@@ -29,13 +25,13 @@ class PayloadBuilderTest {
unmockkObject(AppLogger)
}
- // --- buildPayload tests ---
+ // --- buildLocationPayload tests ---
@Test
- fun `buildPayload uses default field names when no mapping`() {
+ fun `buildLocationPayload uses default field names when no mapping`() {
val location = createMockLocation(lat = 52.52, lon = 13.405, acc = 10.5f, speed = 1.2f)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 85,
batteryStatus = 2,
@@ -53,11 +49,34 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload applies field name mapping`() {
+ fun `buildLocationPayload ignores user fieldMap when apiFormat is TRACCAR_JSON`() {
+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
+
+ val userFieldMap = mapOf("lat" to "latitude", "lon" to "longitude", "tst" to "timestamp")
+ val payload = buildPayload(
+ location = location,
+ batteryLevel = 50,
+ batteryStatus = 1,
+ fieldMap = userFieldMap,
+ timestamp = 1700000000L,
+ apiFormat = ApiFormat.TRACCAR_JSON
+ )
+
+ // Must use internal names so NetworkManager.buildTraccarJsonPayload can read them back.
+ assertEquals(52.0, payload.getDouble("lat"), 0.001)
+ assertEquals(13.0, payload.getDouble("lon"), 0.001)
+ assertEquals(1700000000L, payload.getLong("tst"))
+ assertFalse(payload.has("latitude"))
+ assertFalse(payload.has("longitude"))
+ assertFalse(payload.has("timestamp"))
+ }
+
+ @Test
+ fun `buildLocationPayload applies field name mapping`() {
val location = createMockLocation(lat = 48.0, lon = 11.0, acc = 5.0f, speed = 0.0f)
val fieldMap = mapOf("lat" to "latitude", "lon" to "longitude", "tst" to "timestamp")
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 50,
batteryStatus = 1,
@@ -73,13 +92,13 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload includes altitude when available`() {
+ fun `buildLocationPayload includes altitude when available`() {
val location = createMockLocation(
lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f,
hasAltitude = true, altitude = 35.7
)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -91,10 +110,10 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload excludes altitude when not available`() {
+ fun `buildLocationPayload excludes altitude when not available`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -106,10 +125,10 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload excludes speed when not available`() {
+ fun `buildLocationPayload excludes speed when not available`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f, hasSpeed = false)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -121,10 +140,10 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload includes zero speed when hasSpeed is true`() {
+ fun `buildLocationPayload includes zero speed when hasSpeed is true`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f, hasSpeed = true)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -137,33 +156,33 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload rounds speed to one decimal without float precision artifacts`() {
+ fun `buildLocationPayload rounds speed to one decimal without float precision artifacts`() {
val location049 = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.049f)
- val payload049 = builder.buildPayload(location049, 80, 2, emptyMap(), 1700000000L)
+ val payload049 = buildPayload(location049, 80, 2, emptyMap(), 1700000000L)
assertEquals(0.0, payload049.getDouble("vel"), 0.001) // 0.049 rounds down
val location050 = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.05f)
- val payload050 = builder.buildPayload(location050, 80, 2, emptyMap(), 1700000000L)
+ val payload050 = buildPayload(location050, 80, 2, emptyMap(), 1700000000L)
assertEquals(0.1, payload050.getDouble("vel"), 0.001) // 0.05 rounds up
val location127 = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 1.27f)
- val payload127 = builder.buildPayload(location127, 80, 2, emptyMap(), 1700000000L)
+ val payload127 = buildPayload(location127, 80, 2, emptyMap(), 1700000000L)
assertEquals(1.3, payload127.getDouble("vel"), 0.001) // 1.27 rounds to 1.3
// Verify no float precision artifacts like 0.10000000149011612
val location010 = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.1f)
- val payload010 = builder.buildPayload(location010, 80, 2, emptyMap(), 1700000000L)
+ val payload010 = buildPayload(location010, 80, 2, emptyMap(), 1700000000L)
assertEquals("0.1", payload010.getDouble("vel").toString())
}
@Test
- fun `buildPayload includes bearing when available`() {
+ fun `buildLocationPayload includes bearing when available`() {
val location = createMockLocation(
lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f,
hasBearing = true, bearing = 180.5f
)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -175,10 +194,10 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload excludes bearing when not available`() {
+ fun `buildLocationPayload excludes bearing when not available`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -190,11 +209,11 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload includes custom fields`() {
+ fun `buildLocationPayload includes custom fields`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
val customFields = mapOf("_type" to "location", "device" to "phone1")
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -211,19 +230,19 @@ class PayloadBuilderTest {
@Test
fun `parseFieldMap returns null for null input`() {
- assertNull(builder.parseFieldMap(null))
+ assertNull(PayloadBuilder.parseFieldMap(null))
}
@Test
fun `parseFieldMap returns null for blank input`() {
- assertNull(builder.parseFieldMap(""))
- assertNull(builder.parseFieldMap(" "))
+ assertNull(PayloadBuilder.parseFieldMap(""))
+ assertNull(PayloadBuilder.parseFieldMap(" "))
}
@Test
fun `parseFieldMap parses valid JSON`() {
val json = """{"lat":"latitude","lon":"longitude","tst":"timestamp"}"""
- val result = builder.parseFieldMap(json)
+ val result = PayloadBuilder.parseFieldMap(json)
assertNotNull(result)
assertEquals("latitude", result!!["lat"])
@@ -233,30 +252,30 @@ class PayloadBuilderTest {
@Test
fun `parseFieldMap returns null for invalid JSON`() {
- assertNull(builder.parseFieldMap("not json"))
+ assertNull(PayloadBuilder.parseFieldMap("not json"))
}
// --- parseCustomFields tests ---
@Test
fun `parseCustomFields returns null for null input`() {
- assertNull(builder.parseCustomFields(null))
+ assertNull(PayloadBuilder.parseCustomFields(null))
}
@Test
fun `parseCustomFields returns null for blank input`() {
- assertNull(builder.parseCustomFields(""))
+ assertNull(PayloadBuilder.parseCustomFields(""))
}
@Test
fun `parseCustomFields returns null for empty array`() {
- assertNull(builder.parseCustomFields("[]"))
+ assertNull(PayloadBuilder.parseCustomFields("[]"))
}
@Test
fun `parseCustomFields parses valid JSON array`() {
val json = """[{"key":"_type","value":"location"},{"key":"device","value":"phone1"}]"""
- val result = builder.parseCustomFields(json)
+ val result = PayloadBuilder.parseCustomFields(json)
assertNotNull(result)
assertEquals("location", result!!["_type"])
@@ -265,13 +284,13 @@ class PayloadBuilderTest {
@Test
fun `parseCustomFields returns null for invalid JSON`() {
- assertNull(builder.parseCustomFields("not json"))
+ assertNull(PayloadBuilder.parseCustomFields("not json"))
}
- // --- buildPayload custom fields edge-case tests ---
+ // --- buildLocationPayload custom fields edge-case tests ---
@Test
- fun `buildPayload includes multiple custom fields`() {
+ fun `buildLocationPayload includes multiple custom fields`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
val customFields = mapOf(
"_type" to "location",
@@ -279,7 +298,7 @@ class PayloadBuilderTest {
"region" to "eu-west"
)
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -294,12 +313,12 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload custom field does not override standard fields`() {
+ fun `buildLocationPayload custom field does not override standard fields`() {
val location = createMockLocation(lat = 52.52, lon = 13.405, acc = 5.0f, speed = 0.0f)
// Custom field uses the same key "lat" as the standard latitude field
val customFields = mapOf("lat" to "999.0")
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -313,11 +332,11 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload with empty custom fields map`() {
+ fun `buildLocationPayload with empty custom fields map`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
val customFields = emptyMap<String, String>()
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -339,12 +358,12 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload includes blank custom field keys`() {
+ fun `buildLocationPayload includes blank custom field keys`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
// The implementation does not filter blank keys - they are passed through as-is
val customFields = mapOf("" to "some_value", "valid" to "data")
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -359,12 +378,12 @@ class PayloadBuilderTest {
}
@Test
- fun `buildPayload includes blank custom field values`() {
+ fun `buildLocationPayload includes blank custom field values`() {
val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)
// The implementation does not filter blank values - they are passed through as-is
val customFields = mapOf("myfield" to "", "other" to "ok")
- val payload = builder.buildPayload(
+ val payload = buildPayload(
location = location,
batteryLevel = 80,
batteryStatus = 2,
@@ -380,6 +399,18 @@ class PayloadBuilderTest {
// --- helpers ---
+ private fun buildPayload(
+ location: Location,
+ batteryLevel: Int,
+ batteryStatus: Int,
+ fieldMap: Map<String, String>,
+ timestamp: Long,
+ customFields: Map<String, String> = emptyMap(),
+ apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
+ ): JSONObject = PayloadBuilder.buildLocationPayload(
+ location, timestamp, batteryLevel, batteryStatus, fieldMap, customFields, apiFormat
+ )
+
private fun createMockLocation(
lat: Double,
lon: Double,
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
index 7d375347..15b36be5 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
@@ -3,6 +3,7 @@ package com.Colota.sync
import com.Colota.bridge.LocationServiceModule
import com.Colota.data.DatabaseHelper
import com.Colota.data.QueuedLocation
+import com.Colota.sync.ApiFormat
import com.Colota.util.AppLogger
import io.mockk.*
import kotlinx.coroutines.*
@@ -821,7 +822,7 @@ class SyncManagerTest {
syncSsid = "",
authHeaders = emptyMap(),
httpMethod = "POST",
- apiFormat = "traccar_json"
+ apiFormat = ApiFormat.TRACCAR_JSON
)
coEvery { networkManager.isNetworkAvailable() } returns true
@@ -829,7 +830,7 @@ class SyncManagerTest {
syncManager.queueAndSend(1L, JSONObject().put("lat", 52.0))
- coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", "traccar_json") }
+ coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", ApiFormat.TRACCAR_JSON) }
}
@Test
@@ -843,7 +844,7 @@ class SyncManagerTest {
syncSsid = "",
authHeaders = emptyMap(),
httpMethod = "POST",
- apiFormat = "traccar_json"
+ apiFormat = ApiFormat.TRACCAR_JSON
)
val item = QueuedLocation(1L, 100L, """{"lat":52.0}""", 0)
@@ -852,7 +853,7 @@ class SyncManagerTest {
syncManager.manualFlush()
- coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", "traccar_json") }
+ coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", ApiFormat.TRACCAR_JSON) }
}
// ========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/geo/GeoTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/geo/GeoTest.kt
new file mode 100644
index 00000000..542328cd
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/geo/GeoTest.kt
@@ -0,0 +1,97 @@
+package com.Colota.util.geo
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class GeoTest {
+
+ // Known reference distances (verified against online Haversine calculators):
+ // Berlin (52.52, 13.405) → Munich (48.1351, 11.582) ≈ 504 km
+ // New York (40.7128, -74.006) → London (51.5074, -0.1278) ≈ 5,570 km
+ // Same point → 0 m
+
+ @Test
+ fun `haversineDistance returns zero for same point`() {
+ val distance = haversineDistance(52.52, 13.405, 52.52, 13.405)
+ assertEquals(0.0, distance, 0.01)
+ }
+
+ @Test
+ fun `haversineDistance Berlin to Munich is about 504 km`() {
+ val distance = haversineDistance(52.52, 13.405, 48.1351, 11.582)
+ assertEquals(504_000.0, distance, 5000.0)
+ }
+
+ @Test
+ fun `haversineDistance New York to London is about 5570 km`() {
+ val distance = haversineDistance(40.7128, -74.006, 51.5074, -0.1278)
+ assertEquals(5_570_000.0, distance, 20_000.0)
+ }
+
+ @Test
+ fun `haversineDistance is symmetric`() {
+ val d1 = haversineDistance(52.52, 13.405, 48.1351, 11.582)
+ val d2 = haversineDistance(48.1351, 11.582, 52.52, 13.405)
+ assertEquals(d1, d2, 0.01)
+ }
+
+ @Test
+ fun `haversineDistance across equator`() {
+ // Quito (0.1807, -78.4678) → Bogota (4.711, -74.0721) ≈ 702 km
+ val distance = haversineDistance(0.1807, -78.4678, 4.711, -74.0721)
+ assertEquals(702_000.0, distance, 5000.0)
+ }
+
+ @Test
+ fun `haversineDistance across date line`() {
+ // Auckland (-36.848, 174.763) → Fiji (-17.713, 177.986) ≈ 2160 km
+ val distance = haversineDistance(-36.848, 174.763, -17.713, 177.986)
+ assertEquals(2_160_000.0, distance, 30_000.0)
+ }
+
+ @Test
+ fun `isWithinRadius returns true for point inside`() {
+ val center = Pair(52.5163, 13.3777)
+ // ~50m north ~ +0.00045 degrees latitude
+ assertTrue(isWithinRadius(
+ center.first, center.second,
+ center.first + 0.00045, center.second,
+ 100.0
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius returns false for point outside`() {
+ val center = Pair(52.5163, 13.3777)
+ // ~200m north ~ +0.0018 degrees latitude
+ assertFalse(isWithinRadius(
+ center.first, center.second,
+ center.first + 0.0018, center.second,
+ 100.0
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius returns true for point exactly on boundary`() {
+ val center = Pair(52.5163, 13.3777)
+ val distance = haversineDistance(
+ center.first, center.second,
+ center.first + 0.0009, center.second
+ )
+ assertTrue(isWithinRadius(
+ center.first, center.second,
+ center.first + 0.0009, center.second,
+ distance
+ ))
+ }
+
+ @Test
+ fun `isWithinRadius same point is always within any radius`() {
+ assertTrue(isWithinRadius(52.52, 13.405, 52.52, 13.405, 1.0))
+ }
+
+ @Test
+ fun `bounding box rejects distant points quickly`() {
+ assertFalse(isWithinRadius(52.52, 13.405, 48.1351, 11.582, 1000.0))
+ }
+}