Skip to content

Colota - Android GPS Location tracker

feat: add Traccar JSON POST support and per-backend health checks (#242)

Max Dietrich13da05818869
diff --git a/apps/docs/docs/integrations/api-templates.md b/apps/docs/docs/integrations/api-templates.md
index 6e3c057c..ddc72dba 100644
--- a/apps/docs/docs/integrations/api-templates.md
+++ b/apps/docs/docs/integrations/api-templates.md
@@ -6,16 +6,16 @@ sidebar_position: 1
Colota includes built-in templates for popular backends. Select a template in **Settings > API Settings** to auto-configure field mappings and custom fields.
-| Template | HTTP Method | Bearing Field | Custom Fields | Notes |
-| -------------- | ----------- | ------------- | -------------------------------- | --------------------------------- |
-| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks-compatible format |
-| **OwnTracks** | POST | `cog` | `_type: "location"`, `tid: "AA"` | Standard OwnTracks HTTP format |
-| **GeoPulse** | POST | `bear` | _(none)_ | Native Colota format |
-| **PhoneTrack** | POST | `bearing` | `useragent: "Colota"` | Nextcloud PhoneTrack format |
-| **Reitti** | POST | `bear` | `_type: "location"` | Standard field names |
-| **Traccar** | GET | `bearing` | `id: "colota"` | OsmAnd protocol with query params |
-| **Custom** | POST | `bear` | _(none)_ | Fully user-defined |
+| Template | HTTP Method | Bearing Field | Custom Fields | Notes |
+| --- | --- | --- | --- | --- |
+| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks-compatible format |
+| **OwnTracks** | POST | `cog` | `_type: "location"`, `tid: "AA"` | Standard OwnTracks HTTP format |
+| **GeoPulse** | POST | `bear` | _(none)_ | Native Colota format |
+| **PhoneTrack** | POST | `bearing` | `useragent: "Colota"` | Nextcloud PhoneTrack format |
+| **Reitti** | POST | `bear` | `_type: "location"` | Standard field names |
+| **Traccar** | GET or POST | `bearing` | `id: "colota"` | GET: OsmAnd query params, POST: Traccar JSON |
+| **Custom** | POST | `bear` | _(none)_ | Fully user-defined |
All templates share the same base fields (`lat`, `lon`, `acc`, `alt`, `vel`, `batt`, `bs`, `tst`) with different field names. Key differences are the HTTP method, bearing field name, and auto-included custom fields.
-When you select a template, field mapping, custom fields, and HTTP method are automatically configured. You can still customize individual fields or switch the HTTP method after applying a template - doing so switches the template to "Custom".
+When you select a template, field mapping, custom fields, and HTTP method are automatically configured. You can still customize individual fields or switch the HTTP method after applying a template.
diff --git a/apps/docs/docs/integrations/traccar.md b/apps/docs/docs/integrations/traccar.md
index 7ed9b632..970d0efa 100644
--- a/apps/docs/docs/integrations/traccar.md
+++ b/apps/docs/docs/integrations/traccar.md
@@ -4,49 +4,101 @@ sidebar_position: 6
# Traccar
-[Traccar](https://www.traccar.org/) is an open source GPS tracking platform.
+[Traccar](https://www.traccar.org/) is an open source GPS tracking platform. Colota supports two Traccar protocols:
-Colota connects to Traccar using the OsmAnd protocol, which sends location data as HTTP GET query parameters.
+- **OsmAnd (GET)** - sends location as HTTP GET query parameters. Works with all Traccar versions.
+- **Traccar JSON (POST)** - sends a structured JSON body. Requires Traccar 6.7.0+.
-## Setup
+## Prerequisites
1. **Install Traccar** - follow the [Traccar documentation](https://www.traccar.org/documentation/)
-2. **Create a device** in the Traccar web interface and note the device identifier
-3. **Configure Colota**:
- - Go to **Settings > API Settings**
- - Select the **Traccar** template (this auto-selects GET as HTTP method)
- - Set the `id` custom field to your Traccar device identifier
- - Set your endpoint:
- ```
- https://traccar.yourdomain.com:5055/
- ```
-
-The default OsmAnd protocol port is **5055**. Adjust if you changed it in your Traccar configuration.
+2. **Enable the OsmAnd protocol** in Traccar - both GET and POST use port 5055 via the OsmAnd listener. In your `traccar.xml` config, ensure the OsmAnd port is active (it is by default on standard installs)
+3. **Create a device** in the Traccar web interface - the Identifier you enter must match what Colota sends (see below)
+
+## Setup in Colota
+
+1. Go to **Settings > API Settings**
+2. Select the **Traccar** template
+3. Choose your HTTP method:
+ - **GET** - OsmAnd protocol, compatible with all Traccar versions
+ - **POST** - Traccar JSON format, requires Traccar 6.7.0+
+4. Set your endpoint:
+ ```
+ http://traccar.yourdomain.com:5055
+ ```
+
+## Device Identifier
+
+Traccar identifies devices by a unique identifier. Add a custom field with key `id` and set it to your Traccar device identifier - this is used for both GET and POST.
+
+| Method | Field sent to Traccar | Source |
+| ------ | ------------------------ | ------------------------------------------------------------- |
+| GET | `id` query parameter | custom field `id` |
+| POST | `device_id` in JSON body | custom field `id` (or `device_id` if set, otherwise `colota`) |
+
+The current value is visible in the example payload on the API Settings screen.
+
+In Traccar, open **Settings > Devices**, create a new device, and set the **Identifier** to the same value Colota is sending.
## Request Format
-The Traccar template uses HTTP GET with query parameters:
+### GET (OsmAnd)
```
-GET https://traccar.yourdomain.com:5055/?id=colota&lat=51.495065&lon=-0.043945&accuracy=12&altitude=519&speed=0&batt=85&charge=2&timestamp=1704067200&bearing=180.5
+GET http://traccar.yourdomain.com:5055/?id=my-phone&lat=52.12345&lon=-2.12345&accuracy=15&altitude=380&speed=5&batt=85&charge=2&timestamp=1739362800&bearing=180.0
+```
+
+### POST (Traccar JSON)
+
+```json
+{
+ "location": {
+ "timestamp": "2025-02-12T13:00:00Z",
+ "coords": {
+ "latitude": 52.12345,
+ "longitude": -2.12345,
+ "accuracy": 15,
+ "altitude": 380,
+ "speed": 5,
+ "heading": 180
+ },
+ "battery": {
+ "level": 0.85,
+ "is_charging": false
+ }
+ },
+ "device_id": "colota"
+}
```
## Field Mapping
-| Colota Field | Traccar Parameter | Description |
-| ------------ | ----------------- | --------------------- |
-| `lat` | `lat` | Latitude |
-| `lon` | `lon` | Longitude |
-| `acc` | `accuracy` | GPS accuracy (meters) |
-| `alt` | `altitude` | Altitude (meters) |
-| `vel` | `speed` | Speed (m/s) |
-| `batt` | `batt` | Battery level (0-100) |
-| `bs` | `charge` | Charging status |
-| `tst` | `timestamp` | Unix timestamp |
-| `bear` | `bearing` | Bearing (degrees) |
-
-## Notes
-
-- The `id` custom field is required - Traccar uses it to identify the device
-- Traccar also supports POST with JSON, but the OsmAnd GET protocol is the simplest integration
-- If you need POST, switch the HTTP method to POST and adjust field names as needed
+### GET
+
+| Traccar parameter | Description |
+| ----------------- | --------------------- |
+| `id` | Device identifier |
+| `lat` | Latitude |
+| `lon` | Longitude |
+| `accuracy` | GPS accuracy (meters) |
+| `altitude` | Altitude (meters) |
+| `speed` | Speed (m/s) |
+| `batt` | Battery level (0-100) |
+| `charge` | Charging status |
+| `timestamp` | Unix timestamp |
+| `bearing` | Bearing (degrees) |
+
+### POST
+
+| JSON field | Description |
+| ------------------------------ | ---------------------- |
+| `device_id` | Device identifier |
+| `location.timestamp` | ISO 8601 UTC timestamp |
+| `location.coords.latitude` | Latitude |
+| `location.coords.longitude` | Longitude |
+| `location.coords.accuracy` | GPS accuracy (meters) |
+| `location.coords.altitude` | Altitude (meters) |
+| `location.coords.speed` | Speed (m/s) |
+| `location.coords.heading` | Bearing (degrees) |
+| `location.battery.level` | Battery level (0-1) |
+| `location.battery.is_charging` | Charging state |
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index 1b0b5c5a..73ac7e1a 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
@@ -461,7 +461,8 @@ class LocationForegroundService : Service() {
location,
battery,
batteryStatus,
- currentFieldMap,
+ // 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
)
@@ -595,7 +596,8 @@ class LocationForegroundService : Service() {
syntheticLocation,
battery,
batteryStatus,
- currentFieldMap,
+ // 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
)
@@ -775,7 +777,8 @@ class LocationForegroundService : Service() {
isOfflineMode = config.isOfflineMode,
isWifiOnlySync = config.isWifiOnlySync,
authHeaders = secureStorage.getAuthHeaders(),
- httpMethod = config.httpMethod
+ httpMethod = config.httpMethod,
+ apiFormat = config.apiFormat
)
}
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 96995265..af1f3d33 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
@@ -6,8 +6,9 @@
package com.Colota.service
import android.content.Intent
-import com.Colota.data.DatabaseHelper
import android.os.Bundle
+import com.Colota.data.DatabaseHelper
+import com.Colota.sync.NetworkManager
import com.facebook.react.bridge.ReadableMap
import org.json.JSONObject
@@ -28,12 +29,16 @@ data class ServiceConfig(
val pauseWhenStationary: Boolean = true,
val fieldMap: String? = null,
val customFields: String? = null,
- val httpMethod: String = "POST"
+ val httpMethod: String = "POST",
+ val apiFormat: String = ""
) {
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 ""
+
return ServiceConfig(
endpoint = saved["endpoint"] ?: "",
interval = saved["interval"]?.toLongOrNull() ?: 5000L,
@@ -48,7 +53,8 @@ data class ServiceConfig(
pauseWhenStationary = saved["pauseWhenStationary"]?.toBoolean() ?: true,
fieldMap = saved["fieldMap"],
customFields = saved["customFields"],
- httpMethod = saved["httpMethod"] ?: "POST"
+ httpMethod = httpMethod,
+ apiFormat = apiFormat
)
}
@@ -75,6 +81,10 @@ data class ServiceConfig(
json.toString()
}
+ val httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod
+ val apiTemplate = config.getStringOrNull("apiTemplate") ?: ""
+ val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") NetworkManager.FORMAT_TRACCAR_JSON else ""
+
return ServiceConfig(
endpoint = config.getStringOrNull("endpoint") ?: dbConfig.endpoint,
interval = config.getDoubleOrNull("interval")?.toLong() ?: dbConfig.interval,
@@ -89,7 +99,8 @@ data class ServiceConfig(
pauseWhenStationary = config.getBooleanOrNull("pauseWhenStationary") ?: dbConfig.pauseWhenStationary,
fieldMap = fieldMapJson ?: dbConfig.fieldMap,
customFields = customFieldsJson ?: dbConfig.customFields,
- httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod
+ httpMethod = httpMethod,
+ apiFormat = apiFormat
)
}
@@ -111,7 +122,8 @@ data class ServiceConfig(
pauseWhenStationary = extras.getBooleanOrDefault("pauseWhenStationary", dbConfig.pauseWhenStationary),
fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap),
customFields = extras.getStringOrDefault("customFields", dbConfig.customFields),
- httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST"
+ httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST",
+ apiFormat = extras.getStringOrDefault("apiFormat", dbConfig.apiFormat) ?: ""
)
}
}
@@ -132,6 +144,7 @@ data class ServiceConfig(
fieldMap?.let { putExtra("fieldMap", it) }
customFields?.let { putExtra("customFields", it) }
putExtra("httpMethod", httpMethod)
+ putExtra("apiFormat", apiFormat)
}
}
}
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 6a6b5524..2741fbd2 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
@@ -23,6 +23,7 @@ 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
@@ -48,7 +49,8 @@ class NetworkManager(private val context: Context) {
payload: JSONObject,
endpoint: String,
extraHeaders: Map<String, String> = emptyMap(),
- httpMethod: String = "POST"
+ httpMethod: String = "POST",
+ apiFormat: String = ""
): Boolean = withContext(Dispatchers.IO) {
if (endpoint.isBlank()) {
AppLogger.d(TAG, "Empty endpoint provided")
@@ -72,10 +74,15 @@ class NetworkManager(private val context: Context) {
return@withContext false
}
+ val transformedPayload = when (apiFormat) {
+ FORMAT_TRACCAR_JSON -> buildTraccarJsonPayload(payload)
+ else -> payload
+ }
+
val isGet = httpMethod.equals("GET", ignoreCase = true)
val targetUrl = if (isGet) {
- val query = buildQueryString(payload)
+ val query = buildQueryString(transformedPayload)
val separator = if (url.query != null) "&" else "?"
URL("$endpoint$separator$query")
} else {
@@ -110,13 +117,13 @@ class NetworkManager(private val context: Context) {
AppLogger.d(TAG, "$key: ${masked.joinToString()}")
}
if (!isGet) {
- AppLogger.d(TAG, "Body: ${payload.toString(2)}")
+ AppLogger.d(TAG, "Body: ${transformedPayload.toString(2)}")
}
AppLogger.d(TAG, "===================")
}
if (!isGet) {
- val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)
+ val bodyBytes = transformedPayload.toString().toByteArray(StandardCharsets.UTF_8)
connection.setFixedLengthStreamingMode(bodyBytes.size)
connection.outputStream.use { it.write(bodyBytes) }
}
@@ -216,6 +223,44 @@ class NetworkManager(private val context: Context) {
}
}
+ /**
+ * Transforms a flat Colota payload to the Traccar JSON format (Traccar 6.7.0+).
+ * https://www.traccar.org/osmand/
+ */
+ private fun buildTraccarJsonPayload(flat: JSONObject): JSONObject {
+ val coords = JSONObject().apply {
+ put("latitude", flat.optDouble("lat", 0.0))
+ put("longitude", flat.optDouble("lon", 0.0))
+ if (flat.has("acc")) put("accuracy", flat.optDouble("acc"))
+ if (flat.has("alt")) put("altitude", flat.optDouble("alt"))
+ if (flat.has("vel")) put("speed", flat.optDouble("vel"))
+ if (flat.has("bear")) put("heading", flat.optDouble("bear"))
+ }
+
+ val tst = flat.optLong("tst", System.currentTimeMillis() / 1000)
+ val timestamp = java.time.Instant.ofEpochSecond(tst).toString()
+
+ val location = JSONObject().apply {
+ put("timestamp", timestamp)
+ put("coords", coords)
+ val batt = flat.optInt("batt", -1)
+ if (batt >= 0) {
+ val bs = flat.optInt("bs", 0)
+ put("battery", JSONObject().apply {
+ put("level", batt / 100.0)
+ put("is_charging", bs == 2 || bs == 3) // 2=charging, 3=full (both plugged in)
+ })
+ }
+ }
+
+ return JSONObject().apply {
+ put("location", location)
+ // Prefer "id" (Traccar OsmAnd GET custom field) so both modes share the same identifier
+ val deviceId = flat.optString("id", "").ifBlank { flat.optString("device_id", "colota") }
+ put("device_id", deviceId)
+ }
+ }
+
private fun buildQueryString(payload: JSONObject): String {
val params = mutableListOf<String>()
val keys = payload.keys()
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 b92075f2..f4bfbb6b 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,6 +34,7 @@ class SyncManager(
@Volatile private var isWifiOnlySync: Boolean = false
@Volatile private var authHeaders: Map<String, String> = emptyMap()
@Volatile private var httpMethod: String = "POST"
+ @Volatile private var apiFormat: String = ""
private var syncJob: Job? = null
@Volatile private var lastSyncTime: Long = 0
@@ -52,7 +53,8 @@ class SyncManager(
isOfflineMode: Boolean,
isWifiOnlySync: Boolean,
authHeaders: Map<String, String>,
- httpMethod: String = "POST"
+ httpMethod: String = "POST",
+ apiFormat: String = ""
) {
this.endpoint = endpoint
this.syncIntervalSeconds = syncIntervalSeconds
@@ -62,6 +64,7 @@ class SyncManager(
this.isWifiOnlySync = isWifiOnlySync
this.authHeaders = authHeaders
this.httpMethod = httpMethod
+ this.apiFormat = apiFormat
}
fun startPeriodicSync() {
@@ -142,7 +145,7 @@ class SyncManager(
if (syncIntervalSeconds == 0 && networkManager.isNetworkAvailable() &&
!(isWifiOnlySync && !networkManager.isUnmeteredConnection())) {
AppLogger.d(TAG, "Instant send")
- val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod)
+ val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod, apiFormat)
if (success) {
dbHelper.markLocationSent(locationId)
@@ -194,6 +197,7 @@ class SyncManager(
val currentEndpoint = endpoint
val currentAuthHeaders = authHeaders
val currentHttpMethod = httpMethod
+ val currentApiFormat = apiFormat
val currentMaxRetries = maxRetries // 0 = retry forever, >0 = give up after N attempts
var totalProcessed = 0
@@ -236,7 +240,8 @@ class SyncManager(
JSONObject(item.payload),
currentEndpoint,
currentAuthHeaders,
- currentHttpMethod
+ currentHttpMethod,
+ currentApiFormat
)
item.queueId to success
}
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 d6b08637..1f28ff41 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
@@ -125,6 +125,27 @@ class ServiceConfigTest {
assertEquals("""[{"key":"_type","value":"location"}]""", config.customFields)
}
+ @Test
+ 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)
+ }
+
+ @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)
+ }
+
+ @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)
+ }
+
// --- data class defaults ---
@Test
@@ -221,6 +242,7 @@ class ServiceConfigTest {
every { getString("fieldMap") } returns """{"lat":"latitude"}"""
every { getString("customFields") } returns """{"_type":"location"}"""
every { getString("httpMethod") } returns "GET"
+ every { getString("apiFormat") } returns "traccar_json"
}
val intent = mockk<Intent> {
every { extras } returns bundle
@@ -241,6 +263,7 @@ class ServiceConfigTest {
assertFalse(config.pauseWhenStationary)
assertEquals("""{"lat":"latitude"}""", config.fieldMap)
assertEquals("GET", config.httpMethod)
+ assertEquals("traccar_json", config.apiFormat)
}
// --- toIntent ---
@@ -344,6 +367,39 @@ class ServiceConfigTest {
assertEquals("GET", config.httpMethod)
}
+ @Test
+ fun `fromReadableMap derives apiFormat traccar_json for traccar template with POST`() {
+ val db = mockDbHelper(baseSettings)
+ val map = JavaOnlyMap().apply {
+ putString("apiTemplate", "traccar")
+ putString("httpMethod", "POST")
+ }
+ val config = ServiceConfig.fromReadableMap(map, db)
+ assertEquals("traccar_json", config.apiFormat)
+ }
+
+ @Test
+ fun `fromReadableMap derives empty apiFormat for traccar template with GET`() {
+ val db = mockDbHelper(baseSettings)
+ val map = JavaOnlyMap().apply {
+ putString("apiTemplate", "traccar")
+ putString("httpMethod", "GET")
+ }
+ val config = ServiceConfig.fromReadableMap(map, db)
+ assertEquals("", config.apiFormat)
+ }
+
+ @Test
+ fun `fromReadableMap derives empty apiFormat for non-traccar template`() {
+ val db = mockDbHelper(baseSettings)
+ val map = JavaOnlyMap().apply {
+ putString("apiTemplate", "dawarich")
+ putString("httpMethod", "POST")
+ }
+ val config = ServiceConfig.fromReadableMap(map, db)
+ assertEquals("", config.apiFormat)
+ }
+
@Test
fun `fromReadableMap reads accuracy settings`() {
val db = mockDbHelper(baseSettings)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
index d854923e..bb8270bd 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
@@ -179,6 +179,113 @@ class NetworkManagerTest {
assertEquals("Bear***", result)
}
+ // --- buildTraccarJsonPayload ---
+
+ @Test
+ fun `buildTraccarJsonPayload maps lat and lon to coords`() {
+ val flat = JSONObject().apply {
+ put("lat", 52.12345)
+ put("lon", -2.12345)
+ put("tst", 1739362800L)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val coords = result.getJSONObject("location").getJSONObject("coords")
+ assertEquals(52.12345, coords.getDouble("latitude"), 0.0001)
+ assertEquals(-2.12345, coords.getDouble("longitude"), 0.0001)
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload uses id field as device_id`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("id", "my-phone")
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ assertEquals("my-phone", result.getString("device_id"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload falls back to device_id field when id absent`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("device_id", "my-device")
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ assertEquals("my-device", result.getString("device_id"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload defaults device_id to colota`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ assertEquals("colota", result.getString("device_id"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload includes optional coords fields when present`() {
+ val flat = JSONObject().apply {
+ put("lat", 52.0); put("lon", 13.0); put("tst", 1000L)
+ put("acc", 15.0)
+ put("alt", 380.0)
+ put("vel", 5.5)
+ put("bear", 90.0)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val coords = result.getJSONObject("location").getJSONObject("coords")
+ assertEquals(15.0, coords.getDouble("accuracy"), 0.001)
+ assertEquals(380.0, coords.getDouble("altitude"), 0.001)
+ assertEquals(5.5, coords.getDouble("speed"), 0.001)
+ assertEquals(90.0, coords.getDouble("heading"), 0.001)
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload omits optional coords fields when absent`() {
+ val flat = JSONObject().apply {
+ put("lat", 52.0); put("lon", 13.0); put("tst", 1000L)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val coords = result.getJSONObject("location").getJSONObject("coords")
+ assertFalse(coords.has("accuracy"))
+ assertFalse(coords.has("altitude"))
+ assertFalse(coords.has("speed"))
+ assertFalse(coords.has("heading"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload includes battery when batt present`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 85)
+ put("bs", 2) // charging
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val battery = result.getJSONObject("location").getJSONObject("battery")
+ assertEquals(0.85, battery.getDouble("level"), 0.001)
+ assertTrue(battery.getBoolean("is_charging"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload omits battery when batt absent`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ assertFalse(result.getJSONObject("location").has("battery"))
+ }
+
+ @Test
+ fun `buildTraccarJsonPayload formats timestamp as ISO 8601`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0)
+ put("tst", 1739362800L)
+ }
+ val result = invokeBuildTraccarJsonPayload(flat)
+ val timestamp = result.getJSONObject("location").getString("timestamp")
+ assertTrue("Expected ISO 8601 format, got: $timestamp", timestamp.contains("T") && timestamp.endsWith("Z"))
+ }
+
// --- buildQueryString ---
@Test
@@ -241,6 +348,13 @@ class NetworkManagerTest {
return method.invoke(manager, headerName, headerValue) as String
}
+ private fun invokeBuildTraccarJsonPayload(flat: JSONObject): JSONObject {
+ val method = NetworkManager::class.java.getDeclaredMethod("buildTraccarJsonPayload", JSONObject::class.java)
+ method.isAccessible = true
+ val manager = createNetworkManagerViaReflection()
+ return method.invoke(manager, flat) as JSONObject
+ }
+
private fun invokeBuildQueryString(payload: JSONObject): String {
val method = NetworkManager::class.java.getDeclaredMethod("buildQueryString", JSONObject::class.java)
method.isAccessible = true
diff --git a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
index a2cacbc2..5f69efa3 100644
--- a/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
+++ b/apps/mobile/src/components/features/dashboard/ConnectionStatus.tsx
@@ -13,6 +13,7 @@ import { ServerStatus, ConnectionStatusProps } from "../../../types/global"
import { fonts } from "../../../styles/typography"
import NativeLocationService from "../../../services/NativeLocationService"
import { SERVER_TIMEOUT, SERVER_CHECK_INTERVAL } from "../../../constants"
+import { resolveHealthUrls } from "../../../utils/healthCheck"
export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps) {
const { colors } = useTheme()
@@ -54,31 +55,15 @@ export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps
// proceed without auth headers
}
- const healthUrl = endpoint.replace(/\/api\/locations$/, "/health")
-
- let response = await fetch(healthUrl, {
- method: "HEAD",
- signal: controller.signal,
- headers: authHeaders
- })
-
- if (response.status === 404 || response.status === 405) {
- response = await fetch(endpoint, {
+ const healthUrls = resolveHealthUrls(endpoint, settings.apiTemplate)
+ let response!: Response
+ for (const url of healthUrls) {
+ response = await fetch(url, {
method: "HEAD",
signal: controller.signal,
headers: authHeaders
})
- }
-
- if (!response.ok) {
- const match = endpoint.match(/^(https?:\/\/[^/]+)/)
- if (match) {
- response = await fetch(match[1], {
- method: "GET",
- signal: controller.signal,
- headers: authHeaders
- })
- }
+ if (response.ok || (response.status !== 404 && response.status !== 405)) break
}
setServerStatus(response.ok ? "connected" : "error")
@@ -89,7 +74,7 @@ export function ConnectionStatus({ endpoint, navigation }: ConnectionStatusProps
} finally {
clearTimeout(timeoutId)
}
- }, [endpoint, isOffline])
+ }, [endpoint, isOffline, settings.apiTemplate])
useFocusEffect(
useCallback(() => {
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
index df7a0c32..8003b667 100644
--- a/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
+++ b/apps/mobile/src/components/features/dashboard/__tests__/ConnectionStatus.test.tsx
@@ -17,7 +17,8 @@ jest.mock("../../../../hooks/useTheme", () => ({
}))
const mockSettings = {
- isOfflineMode: false
+ isOfflineMode: false,
+ apiTemplate: "custom" as const
}
jest.mock("../../../../contexts/TrackingProvider", () => ({
useTracking: () => ({
@@ -152,11 +153,10 @@ describe("ConnectionStatus", () => {
expect(mockFetch).toHaveBeenCalledTimes(2)
})
- it("falls back to base URL when endpoint also fails", async () => {
+ it("falls back to origin when /health returns 404", async () => {
mockFetch
- .mockResolvedValueOnce({ ok: false, status: 404 }) // /health
- .mockResolvedValueOnce({ ok: false, status: 500 }) // endpoint
- .mockResolvedValueOnce({ ok: true, status: 200 }) // base URL
+ .mockResolvedValueOnce({ ok: false, status: 404 }) // origin/health
+ .mockResolvedValueOnce({ ok: true, status: 200 }) // origin
const { getByText } = render(
<ConnectionStatus endpoint="https://example.com/api/locations" navigation={mockNavigation} />
@@ -166,7 +166,7 @@ describe("ConnectionStatus", () => {
expect(getByText("Connected")).toBeTruthy()
})
- expect(mockFetch).toHaveBeenCalledTimes(3)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
})
it("displays the host portion of the endpoint URL", async () => {
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index 214648f9..c7359588 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -9,6 +9,7 @@ import { CheckCircle, ChevronRight } from "lucide-react-native"
import { Settings, ThemeColors } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
import { isPrivateHost, isEndpointAllowed } from "../../../utils/settingsValidation"
+import { buildTraccarJsonPayload, isTraccarJsonFormat } from "../../../utils/apiPayload"
import { ensureLocalNetworkPermission } from "../../../services/LocationServicePermission"
import { fonts } from "../../../styles/typography"
import { SettingRow } from "../../ui/SettingRow"
@@ -138,6 +139,20 @@ export function ConnectionSettings({
}
const method = settings.httpMethod ?? "POST"
+ const isTraccarJson = isTraccarJsonFormat(settings.apiTemplate, method)
+ const body = isTraccarJson
+ ? buildTraccarJsonPayload({
+ latitude: recentLocation.latitude,
+ longitude: recentLocation.longitude,
+ accuracy: recentLocation.accuracy,
+ altitude: recentLocation.altitude ?? 0,
+ speed: recentLocation.speed ?? 0,
+ heading: recentLocation.bearing ?? 0,
+ batteryLevel: (recentLocation.battery ?? 0) / 100,
+ isCharging: false,
+ deviceId: settings.customFields.find((f) => f.key === "device_id")?.value ?? "colota"
+ })
+ : payload
const params = new URLSearchParams(Object.entries(payload).map(([k, v]) => [k, String(v)]))
const url =
method === "GET" ? `${endpointInput}${endpointInput.includes("?") ? "&" : "?"}${params}` : endpointInput
@@ -146,7 +161,7 @@ export function ConnectionSettings({
const response = await fetch(url, {
method,
headers: method === "GET" ? authHeaders : { "Content-Type": "application/json", ...authHeaders },
- ...(method === "GET" ? {} : { body: JSON.stringify(payload) }),
+ ...(method === "GET" ? {} : { body: JSON.stringify(body) }),
signal: controller.signal
})
timeout.clear()
diff --git a/apps/mobile/src/screens/ApiSettingsScreen.tsx b/apps/mobile/src/screens/ApiSettingsScreen.tsx
index 0aa8d106..4a7eb0e7 100644
--- a/apps/mobile/src/screens/ApiSettingsScreen.tsx
+++ b/apps/mobile/src/screens/ApiSettingsScreen.tsx
@@ -22,6 +22,7 @@ import NativeLocationService from "../services/NativeLocationService"
import { fonts } from "../styles/typography"
import { SectionTitle, FloatingSaveIndicator, Container, Divider, ChipGroup } from "../components"
import { findDuplicates } from "../utils/settingsValidation"
+import { buildTraccarJsonPayload, isTraccarJsonFormat } from "../utils/apiPayload"
type LocalCustomField = CustomField & { id: number }
@@ -113,6 +114,28 @@ export function ApiSettingsScreen({}: ScreenProps) {
/** Example payload string showing all fields */
const examplePayload = useMemo(() => {
+ const isTraccarJson = isTraccarJsonFormat(localTemplate, localHttpMethod)
+
+ if (isTraccarJson) {
+ const deviceId = localCustomFields.find((f) => f.key === "device_id")?.value ?? "colota"
+ return JSON.stringify(
+ buildTraccarJsonPayload({
+ latitude: 52.12345,
+ longitude: -2.12345,
+ accuracy: 15,
+ altitude: 380,
+ speed: 5,
+ heading: 180,
+ batteryLevel: 0.85,
+ isCharging: false,
+ deviceId,
+ timestamp: "2025-02-12T13:00:00Z"
+ }),
+ null,
+ 2
+ )
+ }
+
const params: { key: string; value: string }[] = []
// Custom static fields first
@@ -138,7 +161,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
const entries = params.map((p) => ` "${p.key}": ${isNaN(Number(p.value)) ? `"${p.value}"` : p.value}`)
return "{\n" + entries.join(",\n") + "\n}"
- }, [localFieldMap, localCustomFields, localHttpMethod])
+ }, [localFieldMap, localCustomFields, localHttpMethod, localTemplate])
/**
* Build sanitized settings from current field map, custom fields, and template.
@@ -323,11 +346,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
const handleHttpMethodChange = useCallback(
(method: HttpMethod) => {
setLocalHttpMethod(method)
-
- const newTemplate = localTemplate !== "custom" ? "custom" : localTemplate
- if (newTemplate !== localTemplate) setLocalTemplate(newTemplate)
-
- saveImmediately(localFieldMap, localCustomFields, newTemplate, method)
+ saveImmediately(localFieldMap, localCustomFields, localTemplate, method)
},
[localFieldMap, localCustomFields, localTemplate, saveImmediately]
)
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 64dcb164..34ba1319 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -73,6 +73,7 @@ class NativeLocationService {
isOfflineMode: settings.isOfflineMode,
isWifiOnlySync: settings.isWifiOnlySync,
httpMethod: settings.httpMethod,
+ apiTemplate: settings.apiTemplate,
customFields: Object.fromEntries(settings.customFields.filter((f) => f.key).map((f) => [f.key, f.value]))
}
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index 16c1675c..d8540230 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -128,12 +128,13 @@ describe("NativeLocationService", () => {
expect.objectContaining({
interval: 5000,
minUpdateDistance: 10,
- httpMethod: "POST"
+ httpMethod: "POST",
+ apiTemplate: "custom"
})
)
})
- it("passes httpMethod GET to native", async () => {
+ it("passes apiTemplate and httpMethod GET to native for traccar template", async () => {
const settings = {
interval: 5,
distance: 10,
@@ -158,7 +159,39 @@ describe("NativeLocationService", () => {
expect(nativeMock.startService).toHaveBeenCalledWith(
expect.objectContaining({
- httpMethod: "GET"
+ httpMethod: "GET",
+ apiTemplate: "traccar"
+ })
+ )
+ })
+
+ it("passes apiTemplate and httpMethod POST to native for traccar JSON format", async () => {
+ const settings = {
+ interval: 5,
+ distance: 10,
+ endpoint: "http://192.168.1.1:5055/",
+ fieldMap: { lat: "lat", lon: "lon", acc: "acc" },
+ syncInterval: 0,
+ retryInterval: 30,
+ maxRetries: 5,
+ filterInaccurateLocations: false,
+ accuracyThreshold: 50,
+ isOfflineMode: false,
+ isWifiOnlySync: false,
+ customFields: [],
+ apiTemplate: "traccar" as const,
+ syncPreset: "instant" as const,
+ httpMethod: "POST" as const,
+ hasCompletedSetup: false,
+ pauseWhenStationary: true
+ }
+
+ await NativeLocationService.start(settings)
+
+ expect(nativeMock.startService).toHaveBeenCalledWith(
+ expect.objectContaining({
+ httpMethod: "POST",
+ apiTemplate: "traccar"
})
)
})
diff --git a/apps/mobile/src/utils/__tests__/apiPayload.test.ts b/apps/mobile/src/utils/__tests__/apiPayload.test.ts
new file mode 100644
index 00000000..7aa5b659
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/apiPayload.test.ts
@@ -0,0 +1,63 @@
+import { buildTraccarJsonPayload } from "../apiPayload"
+
+describe("buildTraccarJsonPayload", () => {
+ const baseParams = {
+ latitude: 52.12345,
+ longitude: -2.12345,
+ accuracy: 15,
+ altitude: 380,
+ speed: 5,
+ heading: 180,
+ batteryLevel: 0.85,
+ isCharging: false,
+ deviceId: "my-phone"
+ }
+
+ it("produces correct nested structure", () => {
+ const result = buildTraccarJsonPayload(baseParams) as any
+ expect(result).toHaveProperty("location")
+ expect(result).toHaveProperty("device_id", "my-phone")
+ expect(result.location).toHaveProperty("coords")
+ expect(result.location).toHaveProperty("battery")
+ expect(result.location).toHaveProperty("timestamp")
+ })
+
+ it("maps coords correctly", () => {
+ const result = buildTraccarJsonPayload(baseParams) as any
+ expect(result.location.coords.latitude).toBe(52.12345)
+ expect(result.location.coords.longitude).toBe(-2.12345)
+ expect(result.location.coords.accuracy).toBe(15)
+ expect(result.location.coords.altitude).toBe(380)
+ expect(result.location.coords.speed).toBe(5)
+ expect(result.location.coords.heading).toBe(180)
+ })
+
+ it("maps battery correctly", () => {
+ const result = buildTraccarJsonPayload(baseParams) as any
+ expect(result.location.battery.level).toBe(0.85)
+ expect(result.location.battery.is_charging).toBe(false)
+ })
+
+ it("sets is_charging true when charging", () => {
+ const result = buildTraccarJsonPayload({ ...baseParams, isCharging: true }) as any
+ expect(result.location.battery.is_charging).toBe(true)
+ })
+
+ it("uses provided timestamp", () => {
+ const result = buildTraccarJsonPayload({ ...baseParams, timestamp: "2025-02-12T13:00:00.000Z" }) as any
+ expect(result.location.timestamp).toBe("2025-02-12T13:00:00.000Z")
+ })
+
+ it("defaults timestamp to current time when not provided", () => {
+ const before = new Date().toISOString()
+ const result = buildTraccarJsonPayload(baseParams) as any
+ const after = new Date().toISOString()
+ expect(result.location.timestamp >= before).toBe(true)
+ expect(result.location.timestamp <= after).toBe(true)
+ })
+
+ it("uses provided device_id", () => {
+ const result = buildTraccarJsonPayload({ ...baseParams, deviceId: "colota" }) as any
+ expect(result.device_id).toBe("colota")
+ })
+})
diff --git a/apps/mobile/src/utils/__tests__/healthCheck.test.ts b/apps/mobile/src/utils/__tests__/healthCheck.test.ts
new file mode 100644
index 00000000..287bd112
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/healthCheck.test.ts
@@ -0,0 +1,56 @@
+import { resolveHealthUrls } from "../healthCheck"
+
+describe("resolveHealthUrls", () => {
+ it("traccar: primary is port 8082/api/server, fallback is origin", () => {
+ expect(resolveHealthUrls("http://192.168.1.1:5055", "traccar")).toEqual([
+ "http://192.168.1.1:8082/api/server",
+ "http://192.168.1.1:8082"
+ ])
+ })
+
+ it("dawarich: primary is /api/v1/health, fallback is origin", () => {
+ expect(resolveHealthUrls("https://dawarich.example.com:3000/api/v1/points", "dawarich")).toEqual([
+ "https://dawarich.example.com:3000/api/v1/health",
+ "https://dawarich.example.com:3000"
+ ])
+ })
+
+ it("owntracks: tries /api/0/version then origin", () => {
+ expect(resolveHealthUrls("http://owntracks.local/pub", "owntracks")).toEqual([
+ "http://owntracks.local/api/0/version",
+ "http://owntracks.local"
+ ])
+ })
+
+ it("phonetrack: primary is /status.php, fallback is origin", () => {
+ expect(resolveHealthUrls("https://nextcloud.example.com/apps/phonetrack", "phonetrack")).toEqual([
+ "https://nextcloud.example.com/status.php",
+ "https://nextcloud.example.com"
+ ])
+ })
+
+ it("geopulse: tries /health then origin", () => {
+ expect(resolveHealthUrls("http://geopulse.local/ingest", "geopulse")).toEqual([
+ "http://geopulse.local/health",
+ "http://geopulse.local"
+ ])
+ })
+
+ it("reitti: tries /health then origin", () => {
+ expect(resolveHealthUrls("http://reitti.local/api/locations", "reitti")).toEqual([
+ "http://reitti.local/health",
+ "http://reitti.local"
+ ])
+ })
+
+ it("custom: tries /health then origin regardless of endpoint path", () => {
+ expect(resolveHealthUrls("https://custom.example.com/track", "custom")).toEqual([
+ "https://custom.example.com/health",
+ "https://custom.example.com"
+ ])
+ })
+
+ it("returns only endpoint on invalid URL", () => {
+ expect(resolveHealthUrls("not-a-url", "custom")).toEqual(["not-a-url"])
+ })
+})
diff --git a/apps/mobile/src/utils/apiPayload.ts b/apps/mobile/src/utils/apiPayload.ts
new file mode 100644
index 00000000..3f1c3fb9
--- /dev/null
+++ b/apps/mobile/src/utils/apiPayload.ts
@@ -0,0 +1,40 @@
+/** Returns true when the active settings require Traccar JSON POST format. */
+export function isTraccarJsonFormat(apiTemplate: string, httpMethod: string): boolean {
+ return apiTemplate === "traccar" && httpMethod === "POST"
+}
+
+/**
+ * Builds a Traccar JSON payload (Traccar 6.7.0+ OsmAnd POST format).
+ * Used for both the example payload preview and the test connection request.
+ */
+export function buildTraccarJsonPayload(params: {
+ latitude: number
+ longitude: number
+ accuracy: number
+ altitude: number
+ speed: number
+ heading: number
+ batteryLevel: number
+ isCharging: boolean
+ deviceId: string
+ timestamp?: string
+}): object {
+ return {
+ location: {
+ timestamp: params.timestamp ?? new Date().toISOString(),
+ coords: {
+ latitude: params.latitude,
+ longitude: params.longitude,
+ accuracy: params.accuracy,
+ altitude: params.altitude,
+ speed: params.speed,
+ heading: params.heading
+ },
+ battery: {
+ level: params.batteryLevel,
+ is_charging: params.isCharging
+ }
+ },
+ device_id: params.deviceId
+ }
+}
diff --git a/apps/mobile/src/utils/healthCheck.ts b/apps/mobile/src/utils/healthCheck.ts
new file mode 100644
index 00000000..93672d68
--- /dev/null
+++ b/apps/mobile/src/utils/healthCheck.ts
@@ -0,0 +1,36 @@
+import { ApiTemplateName } from "../types/global"
+
+/**
+ * Resolves an ordered list of URLs to try for server health/reachability checks.
+ * Each backend exposes connectivity differently - known endpoints are tried first,
+ * with the origin root as a final fallback to confirm basic connectivity.
+ */
+export function resolveHealthUrls(endpoint: string, apiTemplate: ApiTemplateName): string[] {
+ try {
+ const origin = new URL(endpoint).origin
+
+ switch (apiTemplate) {
+ case "traccar": {
+ // Prefer Traccar web API port; fall back to OsmAnd port (returns 400 but confirms reachability)
+ const match = endpoint.match(/^(https?:\/\/[^/:]+)/)
+ const host = match ? match[1] : origin
+ return [`${host}:8082/api/server`, `${host}:8082`]
+ }
+ case "dawarich":
+ return [`${origin}/api/v1/health`, origin]
+ case "owntracks":
+ // /api/0/version for OwnTracks Recorder; Home Assistant responds at root if that 404s
+ return [`${origin}/api/0/version`, origin]
+ case "phonetrack":
+ // PhoneTrack is a Nextcloud app - use Nextcloud's status endpoint
+ return [`${origin}/status.php`, origin]
+ case "geopulse":
+ case "reitti":
+ case "custom":
+ default:
+ return [`${origin}/health`, origin]
+ }
+ } catch {
+ return [endpoint]
+ }
+}