Skip to content

Colota - Android GPS Location tracker

feat: support Overland batch upload (#347)

Max Dietrich93cc468fb477
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.md
index c6a7c35e..0931fe00 100644
--- a/apps/docs/docs/guides/deep-link-setup.md
+++ b/apps/docs/docs/guides/deep-link-setup.md
@@ -43,8 +43,10 @@ The `config` parameter is a base64-encoded JSON object. Only include the setting
| `isOfflineMode` | boolean | Store locally only, never sync |
| `syncCondition` | string | `any`, `wifi_any`, `wifi_ssid`, or `vpn` |
| `syncSsid` | string | Wi-Fi SSID to sync on (only used with `wifi_ssid`) |
-| `apiTemplate` | string | `custom`, `dawarich`, `geopulse`, `owntracks`, `phonetrack`, `reitti`, or `traccar` |
+| `apiTemplate` | string | `custom`, `dawarich`, `geopulse`, `overland`, `owntracks`, `phonetrack`, `reitti`, or `traccar` |
| `httpMethod` | string | `POST` or `GET` |
+| `dawarichMode` | string | `single` (OwnTracks endpoint) or `batch` (Overland endpoint). Only applies to `apiTemplate: dawarich`. |
+| `overlandBatchSize` | number | Points per batch POST for Overland format (1-500, default 50). Used by `apiTemplate: overland` and `dawarich` + `batch`. |
| `fieldMap` | object | Custom field name mapping for the JSON payload |
| `customFields` | array | Static key-value pairs added to every payload |
| `auth.type` | string | `none`, `basic`, or `bearer` |
diff --git a/apps/docs/docs/integrations/api-templates.md b/apps/docs/docs/integrations/api-templates.md
index ddc72dba..6bce7cdb 100644
--- a/apps/docs/docs/integrations/api-templates.md
+++ b/apps/docs/docs/integrations/api-templates.md
@@ -8,7 +8,8 @@ Colota includes built-in templates for popular backends. Select a template in **
| Template | HTTP Method | Bearing Field | Custom Fields | Notes |
| --- | --- | --- | --- | --- |
-| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks-compatible format |
+| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks single-point format. Optional Batch chip switches to Overland envelope (see [Dawarich integration](./dawarich.md)). |
+| **Overland** | POST | n/a (uses Overland format) | `device_id: "colota"` | Batch-only Overland GeoJSON envelope. For any backend that accepts the Overland format (Compass, Wayfinder, Dawarich, etc). |
| **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 |
diff --git a/apps/docs/docs/integrations/dawarich.md b/apps/docs/docs/integrations/dawarich.md
index 02f80448..c3e1d7ab 100644
--- a/apps/docs/docs/integrations/dawarich.md
+++ b/apps/docs/docs/integrations/dawarich.md
@@ -21,7 +21,11 @@ sidebar_position: 2
## Payload Format
-The Dawarich template auto-configures the following payload:
+The Dawarich template ships with two modes, picked via a chip in **Settings > API Settings** when the Dawarich template is selected.
+
+### Single point (default)
+
+Posts one OwnTracks-format point per request to `/api/v1/owntracks/points`. Best for small queues or near-real-time delivery.
```json
{
@@ -39,3 +43,36 @@ The Dawarich template auto-configures the following payload:
```
Note: Dawarich uses `cog` (course over ground) instead of `bear` for the bearing field.
+
+### Batch (Overland)
+
+Bundles up to N queued points into a single request to `/api/v1/overland/batches`, using the [Overland](https://github.com/aaronpk/Overland-iOS) GeoJSON format. Best for high-frequency tracking or flaky cellular networks.
+
+```json
+{
+ "locations": [
+ {
+ "type": "Feature",
+ "geometry": { "type": "Point", "coordinates": [-0.043945, 51.495065] },
+ "properties": {
+ "timestamp": "2026-05-09T12:34:56Z",
+ "horizontal_accuracy": 12,
+ "altitude": 519,
+ "speed": 0,
+ "course": 180.5,
+ "battery_level": 0.85,
+ "battery_state": "charging"
+ }
+ }
+ ],
+ "device_id": "colota"
+}
+```
+
+**Endpoint URL**: change the saved endpoint to `https://dawarich.yourdomain.com/api/v1/overland/batches?api_key=YOUR_API_KEY`. The chip only updates the placeholder hint, not your saved endpoint.
+
+**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & Sync > Advanced > Network Settings > Batch Size** (only shown when batch mode is active).
+
+**Requires non-zero sync interval**: batch mode is incompatible with instant sync. Pick a batched preset or set a custom sync interval before enabling. The chip is disabled when sync interval is 0.
+
+**Device identifier**: your Dawarich server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > API Settings > Custom Fields** if you run multiple devices.
diff --git a/apps/docs/docs/integrations/overland.md b/apps/docs/docs/integrations/overland.md
new file mode 100644
index 00000000..09e00e00
--- /dev/null
+++ b/apps/docs/docs/integrations/overland.md
@@ -0,0 +1,69 @@
+---
+sidebar_position: 3
+---
+
+# Overland
+
+Colota is a drop-in Android client for the [Overland](https://github.com/aaronpk/Overland-iOS) location-tracking format originally designed by Aaron Parecki for iOS. Overland is a portable JSON specification rather than a specific backend, so this template works with any server that accepts the format - including [Compass](https://github.com/aaronpk/Compass), [Dawarich](./dawarich.md)'s `/api/v1/overland/batches` endpoint, [Colota Forwarder](https://github.com/dietrichmax/colota-forwarder), or any custom service that follows the same JSON schema.
+
+## Setup
+
+1. **Pick the Overland template** in **Settings > API Settings**
+2. **Set your endpoint** to your Overland-compatible server's batch URL, e.g.:
+ ```
+ https://overland.yourdomain.com/
+ ```
+ Some implementations use a path like `/api/v1/overland/batches`. Check your server's docs.
+3. **Choose a batched sync preset** (Balanced or Power Saver). Instant sync is not supported because Overland is a batch-only protocol.
+4. **Set a `device_id`** in custom fields if you want to override the default `"colota"`.
+
+## Payload Format
+
+Each upload is a single POST containing one or more locations as GeoJSON Features:
+
+```json
+{
+ "locations": [
+ {
+ "type": "Feature",
+ "geometry": { "type": "Point", "coordinates": [-0.043945, 51.495065] },
+ "properties": {
+ "timestamp": "2026-05-09T12:34:56Z",
+ "horizontal_accuracy": 12,
+ "altitude": 519,
+ "speed": 0,
+ "course": 180.5,
+ "battery_level": 0.85,
+ "battery_state": "charging"
+ }
+ }
+ ],
+ "device_id": "colota"
+}
+```
+
+- `coordinates` follows GeoJSON order: `[longitude, latitude]`.
+- `battery_level` is a float 0.0-1.0 (not 0-100).
+- `battery_state` is one of `"unknown"`, `"unplugged"`, `"charging"`, `"full"`.
+- `device_id` and any other custom fields are placed at envelope level (matching the Overland iOS client), not inside per-Feature properties.
+
+## Configuration
+
+**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & Sync > Advanced > Network Settings > Batch Size**. Larger bundles mean fewer round trips but bigger payloads on flaky networks.
+
+**HTTP method**: POST only. The Overland protocol does not support GET; the option is hidden when this template is selected.
+
+**Sync interval**: must be non-zero. Picking instant sync auto-downgrades the format to single-point on the wire because the Overland endpoint expects bundles, not individual points.
+
+## Device Identifier
+
+Your server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > API Settings > Custom Fields** if you run multiple devices. If you previously set `tid` (OwnTracks) or `id` (Traccar) as a custom field, that value is reused so you don't have to reconfigure.
+
+## Dawarich Users
+
+If you're sending to Dawarich, you can pick either:
+
+- **Dawarich template + Batch mode** - same wire format, Dawarich-specific endpoint hints
+- **Overland template** - same wire format, generic endpoint hints (suited for non-Dawarich Overland-compatible backends)
+
+The data sent is identical. Pick whichever feels more natural for your setup.
diff --git a/apps/docs/docs/integrations/overview.md b/apps/docs/docs/integrations/overview.md
index d19b8111..9163a26f 100644
--- a/apps/docs/docs/integrations/overview.md
+++ b/apps/docs/docs/integrations/overview.md
@@ -12,6 +12,7 @@ Colota sends location data to a server you control. If you're not sure which bac
| ----------------------------------- | --------------------------------------------------------------------------- |
| [Dawarich](dawarich.md) | Location history, map visualization, stats and trip analysis |
| [GeoPulse](geopulse.md) | Location tracking with trip visualization and timeline |
+| [Overland](overland.md) | Any Overland-compatible server |
| [Home Assistant](home-assistant.md) | Home automation - use location as a trigger for automations and zones |
| [OwnTracks](owntracks.md) | Self-hosted location history using the OwnTracks Recorder |
| [Reitti](reitti.md) | Location history with automatic visit and trip detection and daily timeline |
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 321558c7..90b0a8e1 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -35,7 +35,7 @@ Colota has twenty-one screens, each focused on a specific task:
| **Connection** | Server endpoint URL, offline mode toggle and connection test |
| **Tracking & Sync** | GPS polling interval, distance filter, accuracy threshold and sync strategy preset |
| **Appearance** | Light/dark theme, unit system, time format and custom map tile URLs |
-| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |
+| **API Config** | Endpoint field mapping with templates for Dawarich, Overland, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |
| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |
| **Geofences** | Create pause zones by tapping the map, view all zones with pause option indicators |
| **Geofence Editor** | Configure a zone: name, radius, record pause, WiFi pause, motionless pause and timeout, stationary heartbeat |
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 656a0811..b98411a2 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -30,6 +30,7 @@ const sidebars: SidebarsConfig = {
"integrations/overview",
"integrations/api-templates",
"integrations/dawarich",
+ "integrations/overland",
"integrations/home-assistant",
"integrations/owntracks",
"integrations/geopulse",
diff --git a/apps/docs/src/components/DeepLinkGenerator.tsx b/apps/docs/src/components/DeepLinkGenerator.tsx
index ee14d2d7..e496ebdd 100644
--- a/apps/docs/src/components/DeepLinkGenerator.tsx
+++ b/apps/docs/src/components/DeepLinkGenerator.tsx
@@ -19,15 +19,28 @@ interface GeofenceRow {
heartbeatIntervalMinutes: string
}
-const API_TEMPLATES = ["custom", "dawarich", "geopulse", "owntracks", "phonetrack", "reitti", "traccar"] as const
+const API_TEMPLATES = [
+ "custom",
+ "dawarich",
+ "geopulse",
+ "overland",
+ "owntracks",
+ "phonetrack",
+ "reitti",
+ "traccar"
+] as const
const AUTH_TYPES = ["none", "basic", "bearer"] as const
const SYNC_CONDITIONS = ["any", "wifi_any", "wifi_ssid", "vpn"] as const
+const DAWARICH_MODES = ["single", "batch"] as const
+
export default function DeepLinkGenerator() {
// Connection
const [endpoint, setEndpoint] = useState("")
const [apiTemplate, setApiTemplate] = useState("")
const [httpMethod, setHttpMethod] = useState("")
+ const [dawarichMode, setDawarichMode] = useState("")
+ const [overlandBatchSize, setOverlandBatchSize] = useState("")
// Tracking
const [interval, setInterval_] = useState("")
@@ -73,6 +86,8 @@ export default function DeepLinkGenerator() {
if (endpoint) obj.endpoint = endpoint
if (apiTemplate) obj.apiTemplate = apiTemplate
if (httpMethod) obj.httpMethod = httpMethod
+ if (dawarichMode) obj.dawarichMode = dawarichMode
+ if (overlandBatchSize && Number(overlandBatchSize) > 0) obj.overlandBatchSize = Number(overlandBatchSize)
if (interval) obj.interval = Number(interval)
if (distance) obj.distance = Number(distance)
@@ -144,6 +159,8 @@ export default function DeepLinkGenerator() {
endpoint,
apiTemplate,
httpMethod,
+ dawarichMode,
+ overlandBatchSize,
interval,
distance,
accuracyThreshold,
@@ -287,6 +304,37 @@ export default function DeepLinkGenerator() {
</select>
</div>
</div>
+ {apiTemplate === "dawarich" && (
+ <div className={styles.row}>
+ <div className={styles.field}>
+ <label className={styles.label}>Dawarich Mode</label>
+ <select className={styles.select} value={dawarichMode} onChange={(e) => setDawarichMode(e.target.value)}>
+ <option value="">-- not set --</option>
+ {DAWARICH_MODES.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ )}
+ {(apiTemplate === "overland" || (apiTemplate === "dawarich" && dawarichMode === "batch")) && (
+ <div className={styles.row}>
+ <div className={styles.field}>
+ <label className={styles.label}>Batch size (1-500)</label>
+ <input
+ className={styles.input}
+ type="number"
+ min="1"
+ max="500"
+ placeholder="50"
+ value={overlandBatchSize}
+ onChange={(e) => setOverlandBatchSize(e.target.value)}
+ />
+ </div>
+ </div>
+ )}
</div>
{/* Tracking */}
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index 1e2d31f3..e26add7e 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -112,6 +112,7 @@ const homepageScreenshots = [
const integrations = [
{ label: "Dawarich", to: "/docs/integrations/dawarich" },
+ { label: "Overland", to: "/docs/integrations/overland" },
{ label: "OwnTracks", to: "/docs/integrations/owntracks" },
{ label: "Home Assistant", to: "/docs/integrations/home-assistant" },
{ label: "Traccar", to: "/docs/integrations/traccar" },
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 a30f7a6f..8eb5fbb1 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
@@ -173,7 +173,9 @@ class DatabaseHelper private constructor(context: Context) :
SettingsKeys.TRACKING_ENABLED to "false",
"apiTemplate" to "custom",
"syncPreset" to "instant",
- "httpMethod" to "POST"
+ "httpMethod" to "POST",
+ "dawarichMode" to "single",
+ "overlandBatchSize" to "50"
)
db.beginTransaction()
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 96595b78..bc68b0ab 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
@@ -22,6 +22,7 @@ import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
import com.Colota.data.SettingsKeys
+import com.Colota.sync.ApiFormat
import com.Colota.sync.NetworkManager
import com.Colota.sync.PayloadBuilder
import com.Colota.sync.SyncManager
@@ -1149,6 +1150,15 @@ class LocationForegroundService : Service() {
}
private fun pushConfigToSyncManager() {
+ // Instant mode bypasses the queue and posts one flat payload, which 4xxs
+ // forever against /api/v1/overland/batches. Defensive net under the UI guard.
+ val effectiveFormat = if (config.syncIntervalSeconds == 0 && config.apiFormat == ApiFormat.OVERLAND_BATCH) {
+ AppLogger.w(TAG, "Batch mode incompatible with instant sync (interval=0); downgrading to single-point")
+ ApiFormat.FIELD_MAPPED
+ } else {
+ config.apiFormat
+ }
+
syncManager.updateConfig(
endpoint = config.endpoint,
syncIntervalSeconds = config.syncIntervalSeconds,
@@ -1158,7 +1168,8 @@ class LocationForegroundService : Service() {
syncSsid = config.syncSsid,
authHeaders = secureStorage.getAuthHeaders(),
httpMethod = config.httpMethod,
- apiFormat = config.apiFormat
+ apiFormat = effectiveFormat,
+ overlandBatchSize = config.overlandBatchSize
)
}
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 daa58510..2b2eadda 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
@@ -29,14 +29,23 @@ data class ServiceConfig(
val fieldMap: String? = null,
val customFields: String? = null,
val httpMethod: String = "POST",
- val apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
+ val apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED,
+ val overlandBatchSize: Int = 50
) {
companion object {
+ internal fun deriveApiFormat(apiTemplate: String, httpMethod: String, dawarichMode: String): ApiFormat = when {
+ apiTemplate == "traccar" && httpMethod == "POST" -> ApiFormat.TRACCAR_JSON
+ apiTemplate == "overland" -> ApiFormat.OVERLAND_BATCH
+ apiTemplate == "dawarich" && dawarichMode == "batch" -> ApiFormat.OVERLAND_BATCH
+ else -> ApiFormat.FIELD_MAPPED
+ }
+
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") ApiFormat.TRACCAR_JSON else ApiFormat.FIELD_MAPPED
+ val dawarichMode = saved["dawarichMode"] ?: "single"
+ val apiFormat = deriveApiFormat(apiTemplate, httpMethod, dawarichMode)
return ServiceConfig(
endpoint = saved["endpoint"] ?: "",
@@ -52,7 +61,8 @@ data class ServiceConfig(
fieldMap = saved["fieldMap"],
customFields = saved["customFields"],
httpMethod = httpMethod,
- apiFormat = apiFormat
+ apiFormat = apiFormat,
+ overlandBatchSize = saved["overlandBatchSize"]?.toIntOrNull()?.coerceIn(1, 500) ?: 50
)
}
@@ -81,7 +91,8 @@ data class ServiceConfig(
val httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod
val apiTemplate = config.getStringOrNull("apiTemplate") ?: ""
- val apiFormat = if (apiTemplate == "traccar" && httpMethod == "POST") ApiFormat.TRACCAR_JSON else ApiFormat.FIELD_MAPPED
+ val dawarichMode = config.getStringOrNull("dawarichMode") ?: "single"
+ val apiFormat = deriveApiFormat(apiTemplate, httpMethod, dawarichMode)
return ServiceConfig(
endpoint = config.getStringOrNull("endpoint") ?: dbConfig.endpoint,
@@ -97,14 +108,15 @@ data class ServiceConfig(
fieldMap = fieldMapJson ?: dbConfig.fieldMap,
customFields = customFieldsJson ?: dbConfig.customFields,
httpMethod = httpMethod,
- apiFormat = apiFormat
+ apiFormat = apiFormat,
+ overlandBatchSize = (config.getIntOrNull("overlandBatchSize") ?: dbConfig.overlandBatchSize).coerceIn(1, 500)
)
}
fun fromIntent(intent: Intent, dbHelper: DatabaseHelper): ServiceConfig {
val extras = intent.extras ?: return fromDatabase(dbHelper)
val dbConfig = fromDatabase(dbHelper)
-
+
return ServiceConfig(
endpoint = extras.getString("endpoint") ?: dbConfig.endpoint,
interval = extras.getLongOrDefault("interval", dbConfig.interval),
@@ -121,7 +133,8 @@ data class ServiceConfig(
httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST",
apiFormat = if (extras.containsKey("apiFormat"))
ApiFormat.fromWire(extras.getString("apiFormat"))
- else dbConfig.apiFormat
+ else dbConfig.apiFormat,
+ overlandBatchSize = extras.getIntOrDefault("overlandBatchSize", dbConfig.overlandBatchSize).coerceIn(1, 500)
)
}
}
@@ -142,6 +155,7 @@ data class ServiceConfig(
customFields?.let { putExtra("customFields", it) }
putExtra("httpMethod", httpMethod)
putExtra("apiFormat", apiFormat.wireName)
+ putExtra("overlandBatchSize", overlandBatchSize)
}
}
}
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
index 8cfa7a70..b30cb18b 100644
--- 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
@@ -14,9 +14,10 @@ package com.Colota.sync
*/
enum class ApiFormat(val wireName: String) {
FIELD_MAPPED(""),
- TRACCAR_JSON("traccar_json");
+ TRACCAR_JSON("traccar_json"),
+ OVERLAND_BATCH("overland_batch");
- val usesFixedFieldNames: Boolean get() = this == TRACCAR_JSON
+ val usesFixedFieldNames: Boolean get() = this == TRACCAR_JSON || this == OVERLAND_BATCH
companion object {
fun fromWire(wire: String?): ApiFormat =
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.kt
new file mode 100644
index 00000000..6f935a1a
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.kt
@@ -0,0 +1,17 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.sync
+
+/**
+ * Distinguishes 4xx from 5xx so the caller can split-on-4xx (poison row) without
+ * amplifying 5xx outages into N more requests per cycle.
+ */
+sealed class BatchResult {
+ object Success : BatchResult()
+ data class ClientError(val code: Int) : BatchResult()
+ data class ServerError(val code: Int) : BatchResult()
+ object NetworkError : BatchResult()
+}
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 69b9da0f..a9a3667d 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
@@ -5,6 +5,7 @@ import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import com.Colota.BuildConfig
import com.Colota.util.AppLogger
+import com.Colota.util.BatteryStatus
import com.Colota.util.TimedCache
import android.os.Build
import android.net.ConnectivityManager
@@ -131,6 +132,7 @@ class NetworkManager(private val context: Context) {
val transformedPayload = when (apiFormat) {
ApiFormat.TRACCAR_JSON -> buildTraccarJsonPayload(payload)
+ ApiFormat.OVERLAND_BATCH -> buildOverlandBatchPayload(listOf(payload), emptyMap())
ApiFormat.FIELD_MAPPED -> payload
}
@@ -305,6 +307,150 @@ class NetworkManager(private val context: Context) {
}
}
+ suspend fun sendBatchToEndpoint(
+ items: List<JSONObject>,
+ customFields: Map<String, String>,
+ endpoint: String,
+ extraHeaders: Map<String, String> = emptyMap(),
+ ): BatchResult = withContext(Dispatchers.IO) {
+ if (items.isEmpty()) return@withContext BatchResult.Success
+ if (endpoint.isBlank()) {
+ AppLogger.d(TAG, "Empty endpoint provided")
+ return@withContext BatchResult.NetworkError
+ }
+
+ val resolvedEndpoint = resolveUrlVariables(endpoint, items.first())
+
+ val url = try {
+ URL(resolvedEndpoint)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Invalid URL: $resolvedEndpoint")
+ return@withContext BatchResult.NetworkError
+ }
+
+ if (!isValidProtocol(resolvedEndpoint)) {
+ AppLogger.e(TAG, "Protocol blocked or invalid: $endpoint")
+ return@withContext BatchResult.NetworkError
+ }
+
+ if (!isNetworkAvailable()) {
+ AppLogger.d(TAG, "Sync skipped: No internet")
+ return@withContext BatchResult.NetworkError
+ }
+
+ val envelope = buildOverlandBatchPayload(items, customFields)
+
+ var connection: HttpURLConnection? = null
+ try {
+ connection = buildConnection(url, isGet = false, extraHeaders)
+ logRequest(connection, isGet = false, resolvedEndpoint, url, envelope)
+ writeBody(connection, envelope)
+ return@withContext readBatchResponse(connection, items.size)
+ } 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)
+ } else {
+ AppLogger.e(TAG, "Network error: ${e.message}", e)
+ }
+ BatchResult.NetworkError
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Network error: ${e.message}", e)
+ BatchResult.NetworkError
+ } finally {
+ connection?.disconnect()
+ }
+ }
+
+ private fun readBatchResponse(connection: HttpURLConnection, batchSize: Int): BatchResult {
+ val responseCode = connection.responseCode
+ return when (responseCode) {
+ in 200..299 -> {
+ AppLogger.d(TAG, "Batch of $batchSize sent successfully")
+ BatchResult.Success
+ }
+ in 400..499 -> {
+ val errorBody = readErrorBody(connection)
+ AppLogger.w(TAG, "Batch rejected (4xx): $responseCode - $errorBody")
+ BatchResult.ClientError(responseCode)
+ }
+ in 500..599 -> {
+ val errorBody = readErrorBody(connection)
+ AppLogger.e(TAG, "Batch failed (5xx): $responseCode - $errorBody")
+ BatchResult.ServerError(responseCode)
+ }
+ else -> {
+ AppLogger.e(TAG, "Batch failed with unexpected code: $responseCode")
+ BatchResult.ServerError(responseCode)
+ }
+ }
+ }
+
+ private fun readErrorBody(connection: HttpURLConnection): String = try {
+ connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"
+ } catch (_: Exception) { "Could not read error body" }
+
+ /**
+ * Custom fields go at the envelope level (matches the Overland iOS client and
+ * what Dawarich's overland controller expects), NOT inside per-Feature properties.
+ *
+ * The `device_id` fallback chain (device_id -> tid -> id -> "colota") lets users
+ * migrating from OwnTracks (tid) or Traccar (id) keep their identity working
+ * without reconfiguring custom fields. Don't prune as dead code.
+ */
+ private fun buildOverlandBatchPayload(
+ items: List<JSONObject>,
+ customFields: Map<String, String>,
+ ): JSONObject {
+ val locations = org.json.JSONArray()
+ for (flat in items) {
+ locations.put(flatToOverlandFeature(flat))
+ }
+ return JSONObject().apply {
+ put("locations", locations)
+ customFields.forEach { (key, value) ->
+ if (key != "device_id" && key != "locations") put(key, value)
+ }
+ val firstPayload = items.firstOrNull() ?: JSONObject()
+ val deviceId = customFields["device_id"]?.ifBlank { null }
+ ?: firstPayload.optString("device_id", "").ifBlank { null }
+ ?: firstPayload.optString("tid", "").ifBlank { null }
+ ?: firstPayload.optString("id", "").ifBlank { null }
+ ?: "colota"
+ put("device_id", deviceId)
+ }
+ }
+
+ private fun flatToOverlandFeature(flat: JSONObject): JSONObject {
+ val coordinates = org.json.JSONArray().apply {
+ put(flat.optDouble("lon", 0.0)) // GeoJSON: [lon, lat], not lat/lon
+ put(flat.optDouble("lat", 0.0))
+ }
+ val geometry = JSONObject().apply {
+ put("type", "Point")
+ put("coordinates", coordinates)
+ }
+ val properties = JSONObject().apply {
+ // Guard against tst=0 from a corrupted row (optLong's default only fires on missing key).
+ val tstRaw = flat.optLong("tst", 0L)
+ val tst = if (tstRaw > 0) tstRaw else System.currentTimeMillis() / 1000
+ put("timestamp", java.time.Instant.ofEpochSecond(tst).toString())
+ if (flat.has("acc")) put("horizontal_accuracy", flat.optInt("acc"))
+ if (flat.has("alt")) put("altitude", flat.optInt("alt"))
+ if (flat.has("vel")) put("speed", flat.optDouble("vel"))
+ if (flat.has("bear")) put("course", flat.optDouble("bear"))
+ val batt = flat.optInt("batt", -1)
+ if (batt >= 0) {
+ put("battery_level", batt / 100.0)
+ put("battery_state", BatteryStatus.toOverlandString(flat.optInt("bs", BatteryStatus.UNKNOWN)))
+ }
+ }
+ return JSONObject().apply {
+ put("type", "Feature")
+ put("geometry", geometry)
+ put("properties", properties)
+ }
+ }
+
/**
* Transforms a flat Colota payload to the Traccar JSON format (Traccar 6.7.0+).
* https://www.traccar.org/osmand/
@@ -327,10 +473,10 @@ class NetworkManager(private val context: Context) {
put("coords", coords)
val batt = flat.optInt("batt", -1)
if (batt >= 0) {
- val bs = flat.optInt("bs", 0)
+ val bs = flat.optInt("bs", BatteryStatus.UNKNOWN)
put("battery", JSONObject().apply {
put("level", batt / 100.0)
- put("is_charging", bs == 2 || bs == 3) // 2=charging, 3=full (both plugged in)
+ put("is_charging", BatteryStatus.isPluggedIn(bs))
})
}
}
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 8332741d..f66f0ecd 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
@@ -35,6 +35,11 @@ class SyncManager(
@Volatile private var authHeaders: Map<String, String> = emptyMap()
@Volatile private var httpMethod: String = "POST"
@Volatile private var apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED
+ @Volatile private var overlandBatchSize: Int = 50
+
+ // Names PayloadBuilder writes when usesFixedFieldNames=true. Anything else in the payload
+ // is a user-configured custom field (device_id, tid, etc.) and lifts to envelope level.
+ private val canonicalLocationKeys = setOf("lat", "lon", "acc", "alt", "vel", "batt", "bs", "tst", "bear")
private var syncJob: Job? = null
@Volatile private var lastSyncTime: Long = 0
@@ -55,6 +60,7 @@ class SyncManager(
authHeaders: Map<String, String>,
httpMethod: String = "POST",
apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED,
+ overlandBatchSize: Int = 50,
) {
this.endpoint = endpoint
this.syncIntervalSeconds = syncIntervalSeconds
@@ -65,6 +71,7 @@ class SyncManager(
this.authHeaders = authHeaders
this.httpMethod = httpMethod
this.apiFormat = apiFormat
+ this.overlandBatchSize = overlandBatchSize.coerceIn(1, 500)
}
fun startPeriodicSync() {
@@ -210,13 +217,15 @@ class SyncManager(
val currentAuthHeaders = authHeaders
val currentHttpMethod = httpMethod
val currentApiFormat = apiFormat
+ val currentBatchSize = overlandBatchSize
var totalProcessed = 0
var totalSucceeded = 0
var totalFailed = 0
var batchNumber = 1
while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {
- val queued = dbHelper.getQueuedLocations(50)
+ val fetchSize = if (currentApiFormat == ApiFormat.OVERLAND_BATCH) currentBatchSize else 50
+ val queued = dbHelper.getQueuedLocations(fetchSize)
if (queued.isEmpty()) {
if (totalProcessed > 0) {
AppLogger.d(TAG, "Sync complete: $totalProcessed items in $batchNumber batches")
@@ -229,48 +238,60 @@ class SyncManager(
// Chunks of 10 concurrent HTTP requests to avoid flooding the server
val processedBefore = totalProcessed
- for (chunk in queued.chunked(10)) {
- val successfulIds = mutableListOf<Long>()
-
- val results = chunk.map { item ->
- async {
- try {
- val itemPayload = JSONObject(item.payload)
- val success = networkManager.sendToEndpoint(
- itemPayload,
- currentEndpoint,
- currentAuthHeaders,
- currentHttpMethod,
- currentApiFormat
- )
- item.queueId to success
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send item ${item.queueId}", e)
- item.queueId to false
+ if (currentApiFormat == ApiFormat.OVERLAND_BATCH) {
+ val result = sendBatchRecursive(queued, currentEndpoint, currentAuthHeaders)
+ totalProcessed += result.processed
+ totalSucceeded += result.processed
+ totalFailed += result.failed
+ if (result.processed > 0) onProgress?.invoke(totalSucceeded, totalFailed)
+ if (result.stop) {
+ AppLogger.d(TAG, "Sync pass aborted by transport failure")
+ break
+ }
+ } else {
+ for (chunk in queued.chunked(10)) {
+ val successfulIds = mutableListOf<Long>()
+
+ val results = chunk.map { item ->
+ async {
+ try {
+ val itemPayload = JSONObject(item.payload)
+ val success = networkManager.sendToEndpoint(
+ itemPayload,
+ currentEndpoint,
+ currentAuthHeaders,
+ currentHttpMethod,
+ currentApiFormat
+ )
+ item.queueId to success
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to send item ${item.queueId}", e)
+ item.queueId to false
+ }
+ }
+ }.awaitAll()
+
+ results.forEach { (queueId, success) ->
+ if (success) {
+ successfulIds.add(queueId)
+ } else {
+ dbHelper.incrementRetryCount(queueId, "Send failed")
+ totalFailed++
}
}
- }.awaitAll()
-
- results.forEach { (queueId, success) ->
- if (success) {
- successfulIds.add(queueId)
- } else {
- dbHelper.incrementRetryCount(queueId, "Send failed")
- totalFailed++
- }
- }
- if (successfulIds.isNotEmpty()) {
- val sentLocationIds = chunk.filter { it.queueId in successfulIds }.map { it.locationId }
- dbHelper.markLocationsSent(sentLocationIds)
- dbHelper.removeBatchFromQueue(successfulIds)
+ if (successfulIds.isNotEmpty()) {
+ val sentLocationIds = chunk.filter { it.queueId in successfulIds }.map { it.locationId }
+ dbHelper.markLocationsSent(sentLocationIds)
+ dbHelper.removeBatchFromQueue(successfulIds)
- totalProcessed += successfulIds.size
- totalSucceeded += successfulIds.size
- onProgress?.invoke(totalSucceeded, totalFailed)
- }
+ totalProcessed += successfulIds.size
+ totalSucceeded += successfulIds.size
+ onProgress?.invoke(totalSucceeded, totalFailed)
+ }
- yield()
+ yield()
+ }
}
// No items removed from queue. Stop re-fetching the same failing items
@@ -293,6 +314,91 @@ class SyncManager(
}
}
+ private data class BatchSendResult(val processed: Int, val failed: Int, val stop: Boolean)
+
+ /**
+ * Endpoint and auth headers are passed by parameter (not read from volatiles)
+ * so a settings change mid-pass cannot mix them across recursive calls.
+ */
+ private suspend fun sendBatchRecursive(
+ items: List<com.Colota.data.QueuedLocation>,
+ endpoint: String,
+ authHeaders: Map<String, String>,
+ ): BatchSendResult {
+ if (items.isEmpty()) return BatchSendResult(0, 0, false)
+
+ // Isolate corrupt rows so one bad payload doesn't poison the whole batch
+ // (matches the per-item path's per-item try/catch).
+ val parsed = items.mapNotNull { item ->
+ try {
+ item to JSONObject(item.payload)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Corrupt queue row ${item.queueId}, bumping retry counter", e)
+ dbHelper.incrementRetryCount(item.queueId, "Corrupt payload")
+ null
+ }
+ }
+ val corruptedFailed = items.size - parsed.size
+ if (parsed.isEmpty()) {
+ return BatchSendResult(processed = 0, failed = corruptedFailed, stop = false)
+ }
+
+ val parseableItems = parsed.map { it.first }
+ val payloads = parsed.map { it.second }
+ val customFields = extractEnvelopeCustomFields(payloads.first())
+
+ val result = networkManager.sendBatchToEndpoint(
+ items = payloads,
+ customFields = customFields,
+ endpoint = endpoint,
+ extraHeaders = authHeaders,
+ )
+
+ return when (result) {
+ BatchResult.Success -> {
+ dbHelper.markLocationsSent(parseableItems.map { it.locationId })
+ dbHelper.removeBatchFromQueue(parseableItems.map { it.queueId })
+ BatchSendResult(processed = parseableItems.size, failed = corruptedFailed, stop = false)
+ }
+ is BatchResult.ClientError -> {
+ if (parseableItems.size == 1) {
+ dbHelper.incrementRetryCount(parseableItems[0].queueId, "4xx: ${result.code}")
+ BatchSendResult(processed = 0, failed = 1 + corruptedFailed, stop = false)
+ } else {
+ val mid = parseableItems.size / 2
+ val left = sendBatchRecursive(parseableItems.take(mid), endpoint, authHeaders)
+ yield()
+ val right = sendBatchRecursive(parseableItems.drop(mid), endpoint, authHeaders)
+ BatchSendResult(
+ processed = left.processed + right.processed,
+ failed = left.failed + right.failed + corruptedFailed,
+ stop = left.stop || right.stop,
+ )
+ }
+ }
+ is BatchResult.ServerError -> {
+ parseableItems.forEach { dbHelper.incrementRetryCount(it.queueId, "5xx: ${result.code}") }
+ BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)
+ }
+ BatchResult.NetworkError -> {
+ parseableItems.forEach { dbHelper.incrementRetryCount(it.queueId, "network") }
+ BatchSendResult(processed = 0, failed = parseableItems.size + corruptedFailed, stop = true)
+ }
+ }
+ }
+
+ private fun extractEnvelopeCustomFields(payload: JSONObject): Map<String, String> {
+ val fields = mutableMapOf<String, String>()
+ val keys = payload.keys()
+ while (keys.hasNext()) {
+ val key = keys.next()
+ if (key !in canonicalLocationKeys) {
+ fields[key] = payload.optString(key, "")
+ }
+ }
+ return fields
+ }
+
private fun calculateNextSyncDelay(): Long {
if (syncIntervalSeconds <= 0) {
return if (getCachedQueuedCount() > 0) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/BatteryStatus.kt b/apps/mobile/android/app/src/main/java/com/colota/util/BatteryStatus.kt
new file mode 100644
index 00000000..7db67f33
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/BatteryStatus.kt
@@ -0,0 +1,40 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.util
+
+/**
+ * Single source of truth for Colota's compressed battery-status taxonomy.
+ *
+ * DeviceInfoHelper maps Android's raw BatteryManager.BATTERY_STATUS_* values into these
+ * four ints, which are then persisted as the `bs` field on every queued location and
+ * re-encoded for each backend's wire format (Traccar's `is_charging` boolean, Overland's
+ * `battery_state` string, etc).
+ */
+object BatteryStatus {
+ const val UNKNOWN = 0
+ const val DISCHARGING = 1
+ const val CHARGING = 2
+ const val FULL = 3
+
+ fun isPluggedIn(bs: Int): Boolean = bs == CHARGING || bs == FULL
+
+ /** Maps to the Overland-iOS `battery_state` string convention. */
+ fun toOverlandString(bs: Int): String = when (bs) {
+ DISCHARGING -> "unplugged"
+ CHARGING -> "charging"
+ FULL -> "full"
+ else -> "unknown"
+ }
+
+ /** Human-readable label for UI / log output. */
+ fun toDisplayString(bs: Int): String = when (bs) {
+ UNKNOWN -> "Unknown"
+ DISCHARGING -> "Unplugged/Discharging"
+ CHARGING -> "Charging"
+ FULL -> "Full"
+ else -> "Unknown ($bs)"
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
index c9abbb0e..a805d8f1 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
@@ -59,19 +59,12 @@ class DeviceInfoHelper(private val context: Context) {
fun getBatteryStatusString(): String {
val (level, status) = getCachedBatteryStatus()
- val statusText = when (status) {
- 0 -> "Unknown"
- 1 -> "Unplugged/Discharging"
- 2 -> "Charging"
- 3 -> "Full"
- else -> "Unknown ($status)"
- }
- return "$level% ($statusText)"
+ return "$level% (${BatteryStatus.toDisplayString(status)})"
}
fun isBatteryCritical(threshold: Int = 5): Boolean {
val (level, status) = getCachedBatteryStatus()
- return level < threshold && status == 1 // Discharging
+ return level < threshold && status == BatteryStatus.DISCHARGING
}
/** True when device is connected to any power source (AC, USB, wireless). */
@@ -86,11 +79,11 @@ class DeviceInfoHelper(private val context: Context) {
val pct = if (rawLevel >= 0 && scale > 0) (rawLevel * 100) / scale else 100
val rawStatus = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
val status = when (rawStatus) {
- BatteryManager.BATTERY_STATUS_CHARGING -> 2 // Charging
- BatteryManager.BATTERY_STATUS_FULL -> 3 // Full
- BatteryManager.BATTERY_STATUS_DISCHARGING -> 1 // Unplugged/Discharging
- BatteryManager.BATTERY_STATUS_NOT_CHARGING -> 1 // Unplugged/Discharging
- else -> 0 // Unknown
+ BatteryManager.BATTERY_STATUS_CHARGING -> BatteryStatus.CHARGING
+ BatteryManager.BATTERY_STATUS_FULL -> BatteryStatus.FULL
+ BatteryManager.BATTERY_STATUS_DISCHARGING -> BatteryStatus.DISCHARGING
+ BatteryManager.BATTERY_STATUS_NOT_CHARGING -> BatteryStatus.DISCHARGING
+ else -> BatteryStatus.UNKNOWN
}
val plugged = (intent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) ?: 0) != 0
return BatterySticky(pct, status, plugged)
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 ec559e7f..718a21b6 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
@@ -143,6 +143,63 @@ class ServiceConfigTest {
assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
+ @Test
+ fun `fromDatabase derives OVERLAND_BATCH for dawarich template with batch mode`() {
+ // Boot path coverage: BootCompletedReceiver loads from DB, must produce OVERLAND_BATCH
+ // so the foreground service uses the batch endpoint after a reboot.
+ val db = mockDbHelper(baseSettings + mapOf(
+ "apiTemplate" to "dawarich",
+ "dawarichMode" to "batch"
+ ))
+ val config = ServiceConfig.fromDatabase(db)
+ assertEquals(ApiFormat.OVERLAND_BATCH, config.apiFormat)
+ }
+
+ @Test
+ fun `fromDatabase derives OVERLAND_BATCH for overland template regardless of dawarichMode`() {
+ val singleDb = mockDbHelper(baseSettings + mapOf("apiTemplate" to "overland", "dawarichMode" to "single"))
+ assertEquals(ApiFormat.OVERLAND_BATCH, ServiceConfig.fromDatabase(singleDb).apiFormat)
+
+ val batchDb = mockDbHelper(baseSettings + mapOf("apiTemplate" to "overland", "dawarichMode" to "batch"))
+ assertEquals(ApiFormat.OVERLAND_BATCH, ServiceConfig.fromDatabase(batchDb).apiFormat)
+
+ val noModeDb = mockDbHelper(baseSettings + ("apiTemplate" to "overland"))
+ assertEquals(ApiFormat.OVERLAND_BATCH, ServiceConfig.fromDatabase(noModeDb).apiFormat)
+ }
+
+ @Test
+ fun `fromDatabase keeps FIELD_MAPPED for dawarich template with single mode`() {
+ val db = mockDbHelper(baseSettings + mapOf(
+ "apiTemplate" to "dawarich",
+ "dawarichMode" to "single"
+ ))
+ val config = ServiceConfig.fromDatabase(db)
+ assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
+ }
+
+ @Test
+ fun `fromDatabase reads overlandBatchSize`() {
+ val db = mockDbHelper(baseSettings + ("overlandBatchSize" to "100"))
+ val config = ServiceConfig.fromDatabase(db)
+ assertEquals(100, config.overlandBatchSize)
+ }
+
+ @Test
+ fun `fromDatabase defaults overlandBatchSize to 50 when missing`() {
+ val db = mockDbHelper(baseSettings)
+ val config = ServiceConfig.fromDatabase(db)
+ assertEquals(50, config.overlandBatchSize)
+ }
+
+ @Test
+ fun `fromDatabase clamps overlandBatchSize to valid range`() {
+ val tooLow = mockDbHelper(baseSettings + ("overlandBatchSize" to "0"))
+ assertEquals(1, ServiceConfig.fromDatabase(tooLow).overlandBatchSize)
+
+ val tooHigh = mockDbHelper(baseSettings + ("overlandBatchSize" to "9999"))
+ assertEquals(500, ServiceConfig.fromDatabase(tooHigh).overlandBatchSize)
+ }
+
// --- data class defaults ---
@Test
@@ -240,6 +297,7 @@ class ServiceConfigTest {
every { getString("customFields") } returns """{"_type":"location"}"""
every { getString("httpMethod") } returns "GET"
every { getString("apiFormat") } returns "traccar_json"
+ every { getInt("overlandBatchSize") } returns 50
}
val intent = mockk<Intent> {
every { extras } returns bundle
@@ -394,6 +452,27 @@ class ServiceConfigTest {
assertEquals(ApiFormat.FIELD_MAPPED, config.apiFormat)
}
+ @Test
+ fun `fromReadableMap derives OVERLAND_BATCH for dawarich template with batch mode`() {
+ val db = mockDbHelper(baseSettings)
+ val map = JavaOnlyMap().apply {
+ putString("apiTemplate", "dawarich")
+ putString("dawarichMode", "batch")
+ }
+ val config = ServiceConfig.fromReadableMap(map, db)
+ assertEquals(ApiFormat.OVERLAND_BATCH, config.apiFormat)
+ }
+
+ @Test
+ fun `fromReadableMap reads overlandBatchSize`() {
+ val db = mockDbHelper(baseSettings)
+ val map = JavaOnlyMap().apply {
+ putInt("overlandBatchSize", 200)
+ }
+ val config = ServiceConfig.fromReadableMap(map, db)
+ assertEquals(200, config.overlandBatchSize)
+ }
+
@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 87e93519..38b50067 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
@@ -465,6 +465,201 @@ class NetworkManagerTest {
assertFalse(result.getJSONObject("location").has("battery"))
}
+ // --- buildOverlandBatchPayload ---
+
+ @Test
+ fun `buildOverlandBatchPayload wraps single point in locations array`() {
+ val flat = JSONObject().apply {
+ put("lat", 51.5); put("lon", -0.04); put("acc", 12); put("alt", 519)
+ put("vel", 0.0); put("bear", 180.5); put("batt", 85); put("bs", 2)
+ put("tst", 1704067200L)
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+
+ assertTrue(result.has("locations"))
+ val locations = result.getJSONArray("locations")
+ assertEquals(1, locations.length())
+ val feature = locations.getJSONObject(0)
+ assertEquals("Feature", feature.getString("type"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload uses GeoJSON lon-lat coordinate order`() {
+ val flat = JSONObject().apply {
+ put("lat", 51.5); put("lon", -0.04); put("tst", 1704067200L)
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ val coords = result.getJSONArray("locations").getJSONObject(0)
+ .getJSONObject("geometry").getJSONArray("coordinates")
+ assertEquals(-0.04, coords.getDouble(0), 0.001) // lon first
+ assertEquals(51.5, coords.getDouble(1), 0.001) // lat second
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload bundles 50 features in one envelope`() {
+ val items = (1..50).map {
+ JSONObject().apply {
+ put("lat", it.toDouble()); put("lon", it.toDouble()); put("tst", 1704067200L + it)
+ }
+ }
+ val result = invokeBuildOverlandBatchPayload(items, emptyMap())
+ assertEquals(50, result.getJSONArray("locations").length())
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload formats timestamp as ISO 8601`() {
+ val flat = JSONObject().apply {
+ put("lat", 51.5); put("lon", -0.04); put("tst", 1704067200L)
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ val timestamp = result.getJSONArray("locations").getJSONObject(0)
+ .getJSONObject("properties").getString("timestamp")
+ assertTrue("Expected ISO 8601 format, got: $timestamp", timestamp.contains("T") && timestamp.endsWith("Z"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload scales battery_level from 0-100 to 0-1`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 85); put("bs", 2)
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ val props = result.getJSONArray("locations").getJSONObject(0).getJSONObject("properties")
+ assertEquals(0.85, props.getDouble("battery_level"), 0.001)
+ assertEquals("charging", props.getString("battery_state"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload maps battery_state correctly`() {
+ fun stateFor(bs: Int): String {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ put("batt", 50); put("bs", bs)
+ }
+ return invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ .getJSONArray("locations").getJSONObject(0)
+ .getJSONObject("properties").getString("battery_state")
+ }
+ // Mapping must match DeviceInfoHelper.kt: 0=default/unknown, 1=discharging or not charging
+ // (unplugged), 2=charging, 3=full. Out-of-range values default to "unknown" (safer than
+ // inventing a definite state).
+ assertEquals("unknown", stateFor(0))
+ assertEquals("unplugged", stateFor(1))
+ assertEquals("charging", stateFor(2))
+ assertEquals("full", stateFor(3))
+ assertEquals("unknown", stateFor(99))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload device_id falls back when explicit override is empty string`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L); put("tid", "AA")
+ }
+ // Empty-string override should not bypass the fallback chain.
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), mapOf("device_id" to ""))
+ assertEquals("AA", result.getString("device_id"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload does not clobber locations when custom field has reserved key`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ // A custom field named "locations" or "device_id" must not overwrite the envelope structure.
+ val result = invokeBuildOverlandBatchPayload(
+ listOf(flat),
+ mapOf("locations" to "evil", "device_id" to "my-pixel", "extra" to "ok")
+ )
+ // locations stays a JSONArray, not a string
+ val locations = result.getJSONArray("locations")
+ assertEquals(1, locations.length())
+ // device_id uses the explicit override (not literally "my-pixel" being clobbered)
+ assertEquals("my-pixel", result.getString("device_id"))
+ // Non-reserved custom fields still propagate
+ assertEquals("ok", result.getString("extra"))
+ }
+
+ @Test
+ fun `flatToOverlandFeature replaces tst=0 with current time`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 0L) // corrupted/zero timestamp
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ val timestamp = result.getJSONArray("locations").getJSONObject(0)
+ .getJSONObject("properties").getString("timestamp")
+ // Must NOT be 1970-01-01 - we substitute current time when the stored timestamp is invalid
+ assertFalse("timestamp should not be epoch zero, got: $timestamp", timestamp.startsWith("1970"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload omits optional properties when absent`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ val result = invokeBuildOverlandBatchPayload(listOf(flat), emptyMap())
+ val props = result.getJSONArray("locations").getJSONObject(0).getJSONObject("properties")
+ assertFalse(props.has("horizontal_accuracy"))
+ assertFalse(props.has("altitude"))
+ assertFalse(props.has("speed"))
+ assertFalse(props.has("course"))
+ assertFalse(props.has("battery_level"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload places custom fields at envelope level not per Feature`() {
+ val flat = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ val result = invokeBuildOverlandBatchPayload(
+ listOf(flat),
+ mapOf("device_id" to "my-pixel", "extra" to "value")
+ )
+ // Envelope has the custom fields
+ assertEquals("my-pixel", result.getString("device_id"))
+ assertEquals("value", result.getString("extra"))
+ // Feature properties do NOT have them
+ val props = result.getJSONArray("locations").getJSONObject(0).getJSONObject("properties")
+ assertFalse(props.has("device_id"))
+ assertFalse(props.has("extra"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload device_id falls back through device_id then tid then id then literal`() {
+ // Explicit envelope override wins
+ val withDeviceId = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L); put("device_id", "from-payload")
+ }
+ var result = invokeBuildOverlandBatchPayload(listOf(withDeviceId), emptyMap())
+ assertEquals("from-payload", result.getString("device_id"))
+
+ // tid fallback (OwnTracks user migrating to batch)
+ val withTid = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L); put("tid", "AA")
+ }
+ result = invokeBuildOverlandBatchPayload(listOf(withTid), emptyMap())
+ assertEquals("AA", result.getString("device_id"))
+
+ // id fallback (Traccar user migrating to batch)
+ val withId = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L); put("id", "trax")
+ }
+ result = invokeBuildOverlandBatchPayload(listOf(withId), emptyMap())
+ assertEquals("trax", result.getString("device_id"))
+
+ // Literal default when nothing set
+ val empty = JSONObject().apply {
+ put("lat", 1.0); put("lon", 1.0); put("tst", 1000L)
+ }
+ result = invokeBuildOverlandBatchPayload(listOf(empty), emptyMap())
+ assertEquals("colota", result.getString("device_id"))
+ }
+
+ @Test
+ fun `buildOverlandBatchPayload returns empty locations array for empty input`() {
+ val result = invokeBuildOverlandBatchPayload(emptyList(), emptyMap())
+ assertEquals(0, result.getJSONArray("locations").length())
+ }
+
// --- buildQueryString ---
@Test
@@ -544,6 +739,17 @@ class NetworkManagerTest {
return method.invoke(manager, flat) as JSONObject
}
+ private fun invokeBuildOverlandBatchPayload(items: List<JSONObject>, customFields: Map<String, String>): JSONObject {
+ val method = NetworkManager::class.java.getDeclaredMethod(
+ "buildOverlandBatchPayload",
+ List::class.java,
+ Map::class.java
+ )
+ method.isAccessible = true
+ val manager = createNetworkManagerViaReflection()
+ return method.invoke(manager, items, customFields) 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/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt
index 007427a5..53b31c80 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
@@ -71,6 +71,29 @@ class PayloadBuilderTest {
assertFalse(payload.has("timestamp"))
}
+ @Test
+ fun `buildLocationPayload ignores user fieldMap when apiFormat is OVERLAND_BATCH`() {
+ val location = createMockLocation(lat = 51.5, lon = -0.04, acc = 12.0f, speed = 0.0f)
+
+ val userFieldMap = mapOf("lat" to "latitude", "lon" to "longitude", "tst" to "ts")
+ val payload = buildPayload(
+ location = location,
+ batteryLevel = 85,
+ batteryStatus = 2,
+ fieldMap = userFieldMap,
+ timestamp = 1704067200L,
+ apiFormat = ApiFormat.OVERLAND_BATCH
+ )
+
+ // Must use canonical names so NetworkManager.buildOverlandBatchPayload can extract them.
+ assertEquals(51.5, payload.getDouble("lat"), 0.001)
+ assertEquals(-0.04, payload.getDouble("lon"), 0.001)
+ assertEquals(1704067200L, payload.getLong("tst"))
+ assertFalse(payload.has("latitude"))
+ assertFalse(payload.has("longitude"))
+ assertFalse(payload.has("ts"))
+ }
+
@Test
fun `buildLocationPayload applies field name mapping`() {
val location = createMockLocation(lat = 48.0, lon = 11.0, acc = 5.0f, speed = 0.0f)
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 15b36be5..3c749f38 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
@@ -856,6 +856,246 @@ class SyncManagerTest {
coVerify { networkManager.sendToEndpoint(any(), any(), any(), "POST", ApiFormat.TRACCAR_JSON) }
}
+ // ========================================================================
+ // OVERLAND_BATCH path
+ // ========================================================================
+
+ @Test
+ fun `batch path sends one POST and removes all rows on success`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ val items = (1L..50L).map {
+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)
+ }
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(items, emptyList())
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.Success
+
+ syncManager.manualFlush()
+
+ coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }
+ verify { dbHelper.markLocationsSent(items.map { it.locationId }) }
+ verify { dbHelper.removeBatchFromQueue(items.map { it.queueId }) }
+ }
+
+ @Test
+ fun `batch path bails on 5xx without splitting and bumps retry counts once each`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ val items = (1L..4L).map {
+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)
+ }
+ every { dbHelper.getQueuedLocations(50) } returns items
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.ServerError(503)
+
+ syncManager.manualFlush()
+
+ // Critical: exactly ONE HTTP call. NOT recursive splits, that would amplify the outage.
+ coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }
+ // Each row gets one retry bump
+ items.forEach { verify { dbHelper.incrementRetryCount(it.queueId, "5xx: 503") } }
+ }
+
+ @Test
+ fun `batch path bails on network error without splitting`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ val items = (1L..3L).map {
+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)
+ }
+ every { dbHelper.getQueuedLocations(50) } returns items
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } returns BatchResult.NetworkError
+
+ syncManager.manualFlush()
+
+ coVerify(exactly = 1) { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) }
+ items.forEach { verify { dbHelper.incrementRetryCount(it.queueId, "network") } }
+ }
+
+ @Test
+ fun `batch path splits on 4xx to isolate poison row`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ // 4 items: items 1, 2, 3 are good. Item 4 (queueId=4) is the poison row.
+ val items = (1L..4L).map {
+ QueuedLocation(it, it + 100, """{"lat":52.0,"lon":13.0,"tst":1700000000,"id":$it}""", 0)
+ }
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(items, emptyList())
+
+ // Server rejects any batch that contains the poison item (queueId 4)
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } answers {
+ val sent = arg<List<JSONObject>>(0)
+ val containsPoison = sent.any { it.optInt("id", -1) == 4 }
+ if (containsPoison) BatchResult.ClientError(400) else BatchResult.Success
+ }
+
+ // Capture every commit call so we can assert across all split-recovery calls
+ val sentLocationIds = mutableSetOf<Long>()
+ val removedQueueIds = mutableSetOf<Long>()
+ every { dbHelper.markLocationsSent(any()) } answers {
+ sentLocationIds.addAll(firstArg<List<Long>>())
+ }
+ every { dbHelper.removeBatchFromQueue(any()) } answers {
+ removedQueueIds.addAll(firstArg<List<Long>>())
+ }
+
+ syncManager.manualFlush()
+
+ // Poison row gets isolated to a 1-item batch that fails alone -> retry counter bumped
+ verify { dbHelper.incrementRetryCount(4L, "4xx: 400") }
+ // Good rows committed across one or more split-recovery calls
+ assertEquals(setOf(101L, 102L, 103L), sentLocationIds)
+ assertEquals(setOf(1L, 2L, 3L), removedQueueIds)
+ // Poison row was NOT committed
+ assertFalse(sentLocationIds.contains(104L))
+ assertFalse(removedQueueIds.contains(4L))
+ }
+
+ @Test
+ fun `batch path uses overlandBatchSize for the fetch limit`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 200
+ )
+
+ every { dbHelper.getQueuedLocations(any()) } returns emptyList()
+
+ syncManager.manualFlush()
+
+ // Plan called this out: overlandBatchSize must thread into the fetch limit, not just the wire bundle.
+ verify { dbHelper.getQueuedLocations(200) }
+ }
+
+ @Test
+ fun `batch path lifts custom fields to envelope and sends device_id`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ // Payload has a custom field (device_id) baked in by PayloadBuilder
+ val item = QueuedLocation(
+ 1L, 100L,
+ """{"device_id":"my-pixel","lat":52.0,"lon":13.0,"tst":1700000000}""",
+ 0
+ )
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(item), emptyList())
+
+ var capturedFields: Map<String, String>? = null
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } answers {
+ @Suppress("UNCHECKED_CAST")
+ capturedFields = arg<Map<String, String>>(1)
+ BatchResult.Success
+ }
+
+ syncManager.manualFlush()
+
+ // Custom fields must be extracted from the per-row payload and passed at envelope level.
+ // Canonical location keys must NOT be passed as custom fields.
+ val fields = checkNotNull(capturedFields)
+ assertEquals("my-pixel", fields["device_id"])
+ assertFalse("lat is a canonical key, not a custom field", fields.containsKey("lat"))
+ assertFalse("tst is a canonical key, not a custom field", fields.containsKey("tst"))
+ }
+
+ @Test
+ fun `batch path isolates corrupt payload without poisoning the bundle`() = scope.runTest {
+ syncManager.updateConfig(
+ endpoint = "https://dawarich.example/api/v1/overland/batches",
+ syncIntervalSeconds = 300,
+ retryIntervalSeconds = 30,
+ isOfflineMode = false,
+ syncCondition = "any",
+ syncSsid = "",
+ authHeaders = emptyMap(),
+ apiFormat = ApiFormat.OVERLAND_BATCH,
+ overlandBatchSize = 50
+ )
+
+ // Item 1 has a corrupted payload (not valid JSON). Items 2 and 3 are valid.
+ // Without isolation, JSONObject(item.payload) would throw and abort the whole pass,
+ // leaving the corrupt row to re-throw forever next cycle.
+ val corrupted = QueuedLocation(1L, 100L, "NOT_VALID_JSON{{{", 0)
+ val valid1 = QueuedLocation(2L, 101L, """{"lat":52.0,"lon":13.0,"tst":1700000000}""", 0)
+ val valid2 = QueuedLocation(3L, 102L, """{"lat":52.1,"lon":13.1,"tst":1700000001}""", 0)
+ every { dbHelper.getQueuedLocations(50) } returnsMany listOf(
+ listOf(corrupted, valid1, valid2),
+ emptyList()
+ )
+
+ var capturedItemCount = 0
+ coEvery { networkManager.sendBatchToEndpoint(any(), any(), any(), any()) } answers {
+ @Suppress("UNCHECKED_CAST")
+ capturedItemCount = arg<List<JSONObject>>(0).size
+ BatchResult.Success
+ }
+
+ syncManager.manualFlush()
+
+ // Corrupt row gets its retry counter bumped
+ verify { dbHelper.incrementRetryCount(1L, "Corrupt payload") }
+ // Only the 2 valid rows are bundled into the wire request
+ assertEquals(2, capturedItemCount)
+ // Valid rows are committed
+ verify { dbHelper.markLocationsSent(listOf(101L, 102L)) }
+ verify { dbHelper.removeBatchFromQueue(listOf(2L, 3L)) }
+ // Corrupt row is NOT removed from the queue (stays for next cycle, just deprioritized)
+ verify(exactly = 0) { dbHelper.removeBatchFromQueue(match { it.contains(1L) }) }
+ }
+
// ========================================================================
// Helpers
// ========================================================================
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index cd31b0c7..e86c45be 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -9,7 +9,12 @@ import { CheckCircle, ChevronRight } from "lucide-react-native"
import { Settings, ThemeColors } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
import { isEndpointAllowed } from "../../../utils/settingsValidation"
-import { buildTraccarJsonPayload, isTraccarJsonFormat } from "../../../utils/apiPayload"
+import {
+ buildTraccarJsonPayload,
+ buildOverlandBatchPayload,
+ isTraccarJsonFormat,
+ isOverlandFormat
+} from "../../../utils/apiPayload"
import { ensureLocalNetworkPermission } from "../../../services/LocationServicePermission"
import { fonts } from "../../../styles/typography"
import { SettingRow } from "../../ui/SettingRow"
@@ -161,19 +166,36 @@ 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 isOverland = isOverlandFormat(settings.apiTemplate, settings.dawarichMode ?? "single")
+
+ let body: object = payload
+ if (isOverland) {
+ body = buildOverlandBatchPayload({
+ latitude: recentLocation.latitude,
+ longitude: recentLocation.longitude,
+ accuracy: Math.round(recentLocation.accuracy),
+ altitude: recentLocation.altitude ?? 0,
+ speed: recentLocation.speed ?? 0,
+ course: recentLocation.bearing ?? 0,
+ batteryLevel: (recentLocation.battery ?? 0) / 100,
+ batteryState: "unplugged",
+ deviceId:
+ settings.customFields.find((f) => f.key === "device_id" || f.key === "tid" || f.key === "id")?.value ??
+ "colota"
+ })
+ } else if (isTraccarJson) {
+ body = 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"
+ })
+ }
const params = new URLSearchParams(Object.entries(payload).map(([k, v]) => [k, String(v)]))
const url =
method === "GET" ? `${endpointInput}${endpointInput.includes("?") ? "&" : "?"}${params}` : endpointInput
diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
index 190d08d7..68a35d54 100644
--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
@@ -8,10 +8,11 @@ import { Text, StyleSheet, Switch, View, Pressable, TextInput, AppState } from "
import { Lightbulb, ChevronDown, ChevronUp } from "lucide-react-native"
import { Settings, TRACKING_PRESETS, SelectablePreset, ThemeColors, SyncCondition } from "../../../types/global"
import { fonts, fontSizes } from "../../../styles/typography"
-import { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS } from "../../../constants"
+import { SYNC_INTERVAL_PRESETS, SYNC_INTERVAL_LABELS, OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX } from "../../../constants"
import { SectionTitle, Card, Divider, NumericInput, SettingRow } from "../../index"
import { PresetOption } from "./PresetOption"
import { shortDistanceUnit, inputToMeters, metersToInput } from "../../../utils/geo"
+import { isOverlandFormat } from "../../../utils/apiPayload"
import NativeLocationService from "../../../services/NativeLocationService"
interface SyncStrategySettingsProps {
@@ -35,7 +36,9 @@ export function SyncStrategySettings({
metersToInput(settings.accuracyThreshold).toString()
)
const [syncIntervalInput, setSyncIntervalInput] = useState(settings.syncInterval.toString())
+ const [overlandBatchSizeInput, setOverlandBatchSizeInput] = useState(settings.overlandBatchSize.toString())
const [showAdvanced, setShowAdvanced] = useState(false)
+ const showOverlandBatchSize = isOverlandFormat(settings.apiTemplate, settings.dawarichMode)
const [currentSsid, setCurrentSsid] = useState("")
useEffect(() => {
@@ -61,7 +64,14 @@ export function SyncStrategySettings({
setDistanceInput(metersToInput(settings.distance ?? 0).toString())
setAccuracyThresholdInput(metersToInput(settings.accuracyThreshold).toString())
setSyncIntervalInput(settings.syncInterval.toString())
- }, [settings.interval, settings.distance, settings.accuracyThreshold, settings.syncInterval])
+ setOverlandBatchSizeInput(settings.overlandBatchSize.toString())
+ }, [
+ settings.interval,
+ settings.distance,
+ settings.accuracyThreshold,
+ settings.syncInterval,
+ settings.overlandBatchSize
+ ])
const handleNumericChange = useCallback(
(key: "interval" | "distance" | "accuracyThreshold", value: string, min: number = 0) => {
@@ -302,6 +312,38 @@ export function SyncStrategySettings({
</View>
)}
+ {showOverlandBatchSize && (
+ <View style={styles.customSyncInput}>
+ <NumericInput
+ label="Batch Size"
+ value={overlandBatchSizeInput}
+ onChange={(val) => {
+ setOverlandBatchSizeInput(val)
+ const num = Number(val)
+ if (!isNaN(num) && num >= OVERLAND_BATCH_MIN && num <= OVERLAND_BATCH_MAX) {
+ const next = { ...settings, overlandBatchSize: num }
+ onDebouncedSave(next)
+ }
+ }}
+ onBlur={() => {
+ let val = Number(overlandBatchSizeInput)
+ if (isNaN(val) || val < OVERLAND_BATCH_MIN) val = OVERLAND_BATCH_MIN
+ if (val > OVERLAND_BATCH_MAX) val = OVERLAND_BATCH_MAX
+ if (val !== settings.overlandBatchSize || overlandBatchSizeInput !== val.toString()) {
+ setOverlandBatchSizeInput(val.toString())
+ const next = { ...settings, overlandBatchSize: val }
+ onSettingsChange(next)
+ onImmediateSave(next)
+ }
+ }}
+ unit="points"
+ placeholder="50"
+ hint={`Points/upload (${OVERLAND_BATCH_MIN}-${OVERLAND_BATCH_MAX}). Larger = fewer requests, bigger payloads.`}
+ colors={colors}
+ />
+ </View>
+ )}
+
{/* Sync Condition */}
<View style={styles.settingRowSpaced}>
<Text style={[styles.blockLabel, { color: colors.text }]}>Sync Only On</Text>
@@ -525,8 +567,7 @@ const styles = StyleSheet.create({
},
syncConditionChips: {
flexDirection: "row",
- gap: 6,
- marginTop: 8
+ gap: 6
},
syncConditionChip: {
paddingHorizontal: 12,
diff --git a/apps/mobile/src/components/ui/ChipGroup.tsx b/apps/mobile/src/components/ui/ChipGroup.tsx
index 564c9969..e644cdc0 100644
--- a/apps/mobile/src/components/ui/ChipGroup.tsx
+++ b/apps/mobile/src/components/ui/ChipGroup.tsx
@@ -13,21 +13,25 @@ interface ChipGroupProps<T extends string> {
selected: T
onSelect: (value: T) => void
colors: ThemeColors
+ disabled?: ReadonlySet<T>
}
-export function ChipGroup<T extends string>({ options, selected, onSelect, colors }: ChipGroupProps<T>) {
+export function ChipGroup<T extends string>({ options, selected, onSelect, colors, disabled }: ChipGroupProps<T>) {
return (
<View style={styles.row}>
{options.map(({ value, label }) => {
const isSelected = selected === value
+ const isDisabled = disabled?.has(value) ?? false
return (
<Pressable
key={value}
+ disabled={isDisabled}
style={({ pressed }) => [
styles.chip,
{ borderColor: colors.border, backgroundColor: colors.background },
isSelected && { borderColor: colors.primary, backgroundColor: colors.primary + "20" },
- pressed && { opacity: colors.pressedOpacity }
+ isDisabled && { opacity: 0.4 },
+ pressed && !isDisabled && { opacity: colors.pressedOpacity }
]}
onPress={() => onSelect(value)}
>
diff --git a/apps/mobile/src/components/ui/NumericInput.tsx b/apps/mobile/src/components/ui/NumericInput.tsx
index 56902009..389cc700 100644
--- a/apps/mobile/src/components/ui/NumericInput.tsx
+++ b/apps/mobile/src/components/ui/NumericInput.tsx
@@ -48,7 +48,7 @@ export function NumericInput({
<Text style={[styles.label, { color: colors.text }]}>{label}</Text>
{/* Hint (optional) */}
- {hint && <Text style={[styles.hint, { color: colors.textLight }]}>{hint}</Text>}
+ {hint && <Text style={[styles.hint, { color: colors.textSecondary }]}>{hint}</Text>}
{/* Input Row */}
<View style={styles.inputRow}>
@@ -84,9 +84,10 @@ const styles = StyleSheet.create({
marginBottom: 8
},
hint: {
- fontSize: 12,
- fontStyle: "italic",
- marginBottom: 12
+ fontSize: 13,
+ ...fonts.regular,
+ marginBottom: 12,
+ lineHeight: 18
},
inputRow: {
flexDirection: "row",
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 3e084f1c..3fa2f882 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -82,6 +82,10 @@ export const SYNC_INTERVAL_LABELS: Record<number, string> = {
900: "15 min"
}
+// Overland batch envelope (Dawarich + batch mode, Overland template)
+export const OVERLAND_BATCH_MIN = 1
+export const OVERLAND_BATCH_MAX = 500
+
// Thresholds
export const HIGH_QUEUE_THRESHOLD = 50
export const CRITICAL_QUEUE_THRESHOLD = 100
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index 42713c9c..efc1079e 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -5,10 +5,11 @@
import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from "react"
import { DeviceEventEmitter } from "react-native"
-import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName, HttpMethod } from "../types/global"
+import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName, HttpMethod, DawarichMode } from "../types/global"
import { useLocationTracking } from "../hooks/useLocationTracking"
import NativeLocationService from "../services/NativeLocationService"
import SettingsService from "../services/SettingsService"
+import { parsePositiveInt } from "../utils/settingsValidation"
import { LocationDisclosureModal } from "../components/ui/LocationDisclosureModal"
import { LocalNetworkDisclosureModal } from "../components/ui/LocalNetworkDisclosureModal"
import { AppModal } from "../components/ui/AppModal"
@@ -44,7 +45,7 @@ function parseJsonOr<T>(raw: string | undefined, fallback: T, key: string): T {
/**
* Parses raw SQLite settings (all strings) into typed Settings object
*/
-function parseRawSettings(allRaw: Record<string, string>): Settings {
+export function parseRawSettings(allRaw: Record<string, string>): Settings {
return {
...DEFAULT_SETTINGS,
// Convert Android milliseconds back to seconds (UNIX-Timestamp)
@@ -73,6 +74,8 @@ function parseRawSettings(allRaw: Record<string, string>): Settings {
apiTemplate: (allRaw.apiTemplate as ApiTemplateName) ?? DEFAULT_SETTINGS.apiTemplate,
httpMethod: (allRaw.httpMethod as HttpMethod) ?? DEFAULT_SETTINGS.httpMethod,
+ dawarichMode: (allRaw.dawarichMode as DawarichMode) ?? DEFAULT_SETTINGS.dawarichMode,
+ overlandBatchSize: parsePositiveInt(allRaw.overlandBatchSize ?? "", DEFAULT_SETTINGS.overlandBatchSize),
hasCompletedSetup: allRaw.hasCompletedSetup === "true"
}
diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
index 42c1d7df..59d003d7 100644
--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -55,7 +55,7 @@ jest.mock("../../utils/logger", () => ({
}
}))
-import { TrackingProvider, useTracking } from "../TrackingProvider"
+import { TrackingProvider, useTracking, parseRawSettings } from "../TrackingProvider"
import NativeLocationService from "../../services/NativeLocationService"
import SettingsService from "../../services/SettingsService"
import { logger } from "../../utils/logger"
@@ -339,3 +339,27 @@ describe("useTracking", () => {
expect(result.current.activeProfileName).toBe("Charging")
})
})
+
+describe("parseRawSettings", () => {
+ it("round-trips dawarichMode from raw SQLite", () => {
+ const settings = parseRawSettings({ dawarichMode: "batch" })
+ expect(settings.dawarichMode).toBe("batch")
+ })
+
+ it("round-trips overlandBatchSize from raw SQLite", () => {
+ const settings = parseRawSettings({ overlandBatchSize: "200" })
+ expect(settings.overlandBatchSize).toBe(200)
+ })
+
+ it("falls back to defaults when dawarich keys are missing", () => {
+ const settings = parseRawSettings({})
+ expect(settings.dawarichMode).toBe(DEFAULT_SETTINGS.dawarichMode)
+ expect(settings.overlandBatchSize).toBe(DEFAULT_SETTINGS.overlandBatchSize)
+ })
+
+ it("falls back to default when overlandBatchSize is non-numeric", () => {
+ const settings = parseRawSettings({ overlandBatchSize: "not-a-number" })
+ // parseInt("not-a-number", 10) returns NaN, but we should not propagate NaN
+ expect(Number.isFinite(settings.overlandBatchSize)).toBe(true)
+ })
+})
diff --git a/apps/mobile/src/screens/ApiSettingsScreen.tsx b/apps/mobile/src/screens/ApiSettingsScreen.tsx
index a56d6ecb..e39993e3 100644
--- a/apps/mobile/src/screens/ApiSettingsScreen.tsx
+++ b/apps/mobile/src/screens/ApiSettingsScreen.tsx
@@ -12,7 +12,8 @@ import {
CustomField,
ApiTemplateName,
API_TEMPLATES,
- HttpMethod
+ HttpMethod,
+ DawarichMode
} from "../types/global"
import { useTheme } from "../hooks/useTheme"
import { useAutoSave } from "../hooks/useAutoSave"
@@ -22,7 +23,12 @@ 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"
+import {
+ buildTraccarJsonPayload,
+ buildOverlandBatchPayload,
+ isTraccarJsonFormat,
+ isOverlandFormat
+} from "../utils/apiPayload"
type LocalCustomField = CustomField & { id: number }
@@ -52,6 +58,11 @@ const HTTP_METHOD_OPTIONS: { value: HttpMethod; label: string }[] = [
{ value: "GET", label: "GET" }
]
+const DAWARICH_MODE_OPTIONS: { value: DawarichMode; label: string }[] = [
+ { value: "single", label: "Single point" },
+ { value: "batch", label: "Batch" }
+]
+
/**
* Returns the reference field map for the current template.
* Used for "Modified" badge comparison and "Reset" actions.
@@ -83,7 +94,12 @@ export function ApiSettingsScreen({}: ScreenProps) {
)
const [localTemplate, setLocalTemplate] = useState<ApiTemplateName>(settings.apiTemplate || "custom")
const [localHttpMethod, setLocalHttpMethod] = useState<HttpMethod>(settings.httpMethod || "POST")
+ const [localDawarichMode, setLocalDawarichMode] = useState<DawarichMode>(settings.dawarichMode || "single")
const [copied, setCopied] = useState(false)
+ const isInstantSync = settings.syncInterval === 0
+ const isGetMethod = localHttpMethod === "GET"
+ const showDawarichChip = localTemplate === "dawarich"
+ const batchDisabled = isInstantSync || isGetMethod
const copiedTimeout = useTimeout()
const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
@@ -115,6 +131,28 @@ export function ApiSettingsScreen({}: ScreenProps) {
/** Example payload string showing all fields */
const examplePayload = useMemo(() => {
const isTraccarJson = isTraccarJsonFormat(localTemplate, localHttpMethod)
+ const isOverland = isOverlandFormat(localTemplate, localDawarichMode)
+
+ if (isOverland) {
+ const deviceId =
+ localCustomFields.find((f) => f.key === "device_id" || f.key === "tid" || f.key === "id")?.value ?? "colota"
+ return JSON.stringify(
+ buildOverlandBatchPayload({
+ latitude: 52.12345,
+ longitude: -2.12345,
+ accuracy: 15,
+ altitude: 380,
+ speed: 5,
+ course: 180,
+ batteryLevel: 0.85,
+ batteryState: "unplugged",
+ deviceId,
+ timestamp: "2025-02-12T13:00:00Z"
+ }),
+ null,
+ 2
+ )
+ }
if (isTraccarJson) {
const deviceId = localCustomFields.find((f) => f.key === "id" || f.key === "device_id")?.value ?? "colota"
@@ -161,7 +199,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, localTemplate])
+ }, [localFieldMap, localCustomFields, localHttpMethod, localTemplate, localDawarichMode])
/**
* Build sanitized settings from current field map, custom fields, and template.
@@ -172,7 +210,8 @@ export function ApiSettingsScreen({}: ScreenProps) {
newFieldMap: FieldMap,
newCustomFields: CustomField[],
newTemplate: ApiTemplateName,
- newHttpMethod: HttpMethod
+ newHttpMethod: HttpMethod,
+ newDawarichMode: DawarichMode
) => {
const sanitizedMap = Object.fromEntries(
Object.entries(newFieldMap).map(([key, value]) => [key, value.trim()])
@@ -200,7 +239,8 @@ export function ApiSettingsScreen({}: ScreenProps) {
fieldMap: sanitizedMap,
customFields: sanitizedCustomFields,
apiTemplate: newTemplate,
- httpMethod: newHttpMethod
+ httpMethod: newHttpMethod,
+ dawarichMode: newDawarichMode
}
},
[settings]
@@ -214,9 +254,16 @@ export function ApiSettingsScreen({}: ScreenProps) {
newFieldMap: FieldMap,
newCustomFields: CustomField[],
newTemplate: ApiTemplateName,
- newHttpMethod: HttpMethod
+ newHttpMethod: HttpMethod,
+ newDawarichMode: DawarichMode
) => {
- const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate, newHttpMethod)
+ const newSettings = buildSanitizedSettings(
+ newFieldMap,
+ newCustomFields,
+ newTemplate,
+ newHttpMethod,
+ newDawarichMode
+ )
if (!newSettings) return
debouncedSaveAndRestart(
@@ -235,9 +282,16 @@ export function ApiSettingsScreen({}: ScreenProps) {
newFieldMap: FieldMap,
newCustomFields: CustomField[],
newTemplate: ApiTemplateName,
- newHttpMethod: HttpMethod
+ newHttpMethod: HttpMethod,
+ newDawarichMode: DawarichMode
) => {
- const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate, newHttpMethod)
+ const newSettings = buildSanitizedSettings(
+ newFieldMap,
+ newCustomFields,
+ newTemplate,
+ newHttpMethod,
+ newDawarichMode
+ )
if (!newSettings) return
immediateSaveAndRestart(
@@ -255,8 +309,13 @@ export function ApiSettingsScreen({}: ScreenProps) {
(template: ApiTemplateName) => {
setLocalTemplate(template)
+ // Reset to "single" when leaving dawarich so the saved value doesn't silently
+ // flip behavior the next time the user picks dawarich again.
+ const nextDawarichMode: DawarichMode = template === "dawarich" ? localDawarichMode : "single"
+ if (nextDawarichMode !== localDawarichMode) setLocalDawarichMode(nextDawarichMode)
+
if (template === "custom") {
- saveImmediately(localFieldMap, localCustomFields, template, localHttpMethod)
+ saveImmediately(localFieldMap, localCustomFields, template, localHttpMethod, nextDawarichMode)
return
}
@@ -266,9 +325,9 @@ export function ApiSettingsScreen({}: ScreenProps) {
setLocalFieldMap(tmpl.fieldMap)
setLocalCustomFields(newCustomFields)
setLocalHttpMethod(method)
- saveImmediately(tmpl.fieldMap, newCustomFields, template, method)
+ saveImmediately(tmpl.fieldMap, newCustomFields, template, method, nextDawarichMode)
},
- [localFieldMap, localCustomFields, localHttpMethod, saveImmediately]
+ [localFieldMap, localCustomFields, localHttpMethod, localDawarichMode, saveImmediately]
)
/**
@@ -283,9 +342,9 @@ export function ApiSettingsScreen({}: ScreenProps) {
const newTemplate = localTemplate !== "custom" ? "custom" : localTemplate
if (newTemplate !== localTemplate) setLocalTemplate(newTemplate)
- debouncedSave(newFieldMap, localCustomFields, newTemplate, localHttpMethod)
+ debouncedSave(newFieldMap, localCustomFields, newTemplate, localHttpMethod, localDawarichMode)
},
- [localFieldMap, localCustomFields, localTemplate, localHttpMethod, debouncedSave]
+ [localFieldMap, localCustomFields, localTemplate, localHttpMethod, localDawarichMode, debouncedSave]
)
/**
@@ -295,9 +354,17 @@ export function ApiSettingsScreen({}: ScreenProps) {
(key: keyof FieldMap) => {
const newFieldMap = { ...localFieldMap, [key]: referenceFieldMap[key] }
setLocalFieldMap(newFieldMap)
- saveImmediately(newFieldMap, localCustomFields, localTemplate, localHttpMethod)
+ saveImmediately(newFieldMap, localCustomFields, localTemplate, localHttpMethod, localDawarichMode)
},
- [localFieldMap, localCustomFields, localTemplate, localHttpMethod, referenceFieldMap, saveImmediately]
+ [
+ localFieldMap,
+ localCustomFields,
+ localTemplate,
+ localHttpMethod,
+ localDawarichMode,
+ referenceFieldMap,
+ saveImmediately
+ ]
)
/**
@@ -307,8 +374,8 @@ export function ApiSettingsScreen({}: ScreenProps) {
const refFields = getReferenceCustomFields(localTemplate).map((f) => ({ ...f, id: assignId() }))
setLocalFieldMap(referenceFieldMap)
setLocalCustomFields(refFields)
- saveImmediately(referenceFieldMap, refFields, localTemplate, localHttpMethod)
- }, [referenceFieldMap, localTemplate, localHttpMethod, saveImmediately])
+ saveImmediately(referenceFieldMap, refFields, localTemplate, localHttpMethod, localDawarichMode)
+ }, [referenceFieldMap, localTemplate, localHttpMethod, localDawarichMode, saveImmediately])
// --- Custom Fields handlers ---
@@ -329,9 +396,9 @@ export function ApiSettingsScreen({}: ScreenProps) {
setLocalTemplate(newTemplate)
}
- debouncedSave(localFieldMap, newFields, newTemplate, localHttpMethod)
+ debouncedSave(localFieldMap, newFields, newTemplate, localHttpMethod, localDawarichMode)
},
- [localCustomFields, localFieldMap, localTemplate, localHttpMethod, debouncedSave]
+ [localCustomFields, localFieldMap, localTemplate, localHttpMethod, localDawarichMode, debouncedSave]
)
const handleRemoveCustomField = useCallback(
@@ -342,17 +409,44 @@ export function ApiSettingsScreen({}: ScreenProps) {
const newTemplate = localTemplate !== "custom" ? "custom" : localTemplate
if (newTemplate !== localTemplate) setLocalTemplate(newTemplate)
- saveImmediately(localFieldMap, newFields, newTemplate, localHttpMethod)
+ saveImmediately(localFieldMap, newFields, newTemplate, localHttpMethod, localDawarichMode)
},
- [localCustomFields, localFieldMap, localTemplate, localHttpMethod, saveImmediately]
+ [localCustomFields, localFieldMap, localTemplate, localHttpMethod, localDawarichMode, saveImmediately]
)
const handleHttpMethodChange = useCallback(
(method: HttpMethod) => {
setLocalHttpMethod(method)
- saveImmediately(localFieldMap, localCustomFields, localTemplate, method)
+
+ // Batch requires POST; revert to single if the user picks GET while in batch
+ // so the saved state matches the disabled chip.
+ const nextDawarichMode: DawarichMode =
+ method === "GET" && localDawarichMode === "batch" ? "single" : localDawarichMode
+ if (nextDawarichMode !== localDawarichMode) setLocalDawarichMode(nextDawarichMode)
+
+ saveImmediately(localFieldMap, localCustomFields, localTemplate, method, nextDawarichMode)
+ },
+ [localFieldMap, localCustomFields, localTemplate, localDawarichMode, saveImmediately]
+ )
+
+ const handleDawarichModeChange = useCallback(
+ (mode: DawarichMode) => {
+ setLocalDawarichMode(mode)
+
+ // Reseed the default custom field on mode flip, but only when the list still
+ // matches the previous mode's default (i.e. the user hasn't edited it).
+ const prevDefault = mode === "batch" ? "_type" : "device_id"
+ const nextDefault = mode === "batch" ? "device_id" : "_type"
+ const nextDefaultValue = mode === "batch" ? "colota" : "location"
+ const looksLikeOldDefault = localCustomFields.length === 1 && localCustomFields[0]?.key === prevDefault
+ const newCustomFields = looksLikeOldDefault
+ ? [{ key: nextDefault, value: nextDefaultValue, id: assignId() }]
+ : localCustomFields
+ if (looksLikeOldDefault) setLocalCustomFields(newCustomFields)
+
+ saveImmediately(localFieldMap, newCustomFields, localTemplate, localHttpMethod, mode)
},
- [localFieldMap, localCustomFields, localTemplate, saveImmediately]
+ [localFieldMap, localCustomFields, localTemplate, localHttpMethod, saveImmediately]
)
const handleCopyPayload = useCallback(async () => {
@@ -393,20 +487,52 @@ export function ApiSettingsScreen({}: ScreenProps) {
</View>
{/* HTTP Method Selector */}
- <View style={styles.section}>
- <SectionTitle>HTTP METHOD</SectionTitle>
- <ChipGroup
- options={HTTP_METHOD_OPTIONS}
- selected={localHttpMethod}
- onSelect={handleHttpMethodChange}
- colors={colors}
- />
- {localHttpMethod === "GET" && (
+ {/* Overland template is POST-only by spec; no need to expose the choice */}
+ {localTemplate !== "overland" && (
+ <View style={styles.section}>
+ <SectionTitle>HTTP METHOD</SectionTitle>
+ <ChipGroup
+ options={HTTP_METHOD_OPTIONS}
+ selected={localHttpMethod}
+ onSelect={handleHttpMethodChange}
+ colors={colors}
+ />
+ {localHttpMethod === "GET" && (
+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
+ Fields sent as URL query parameters instead of JSON body
+ </Text>
+ )}
+ </View>
+ )}
+
+ {/* Dawarich Mode Selector (Dawarich template only) */}
+ {showDawarichChip && (
+ <View style={styles.section}>
+ <SectionTitle>DAWARICH MODE</SectionTitle>
+ <ChipGroup
+ options={DAWARICH_MODE_OPTIONS}
+ selected={localDawarichMode}
+ onSelect={handleDawarichModeChange}
+ colors={colors}
+ disabled={batchDisabled ? new Set<DawarichMode>(["batch"]) : undefined}
+ />
<Text style={[styles.templateHint, { color: colors.textSecondary }]}>
- Fields sent as URL query parameters instead of JSON body
+ {localDawarichMode === "batch"
+ ? "Endpoint: /api/v1/overland/batches?api_key=YOUR_API_KEY"
+ : "Endpoint: /api/v1/owntracks/points?api_key=YOUR_API_KEY"}
</Text>
- )}
- </View>
+ {isInstantSync && (
+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
+ Batch mode requires a non-zero sync interval. Switch to a batched preset to enable it.
+ </Text>
+ )}
+ {isGetMethod && !isInstantSync && (
+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
+ Batch mode requires POST. Switch HTTP method to POST to enable batch.
+ </Text>
+ )}
+ </View>
+ )}
{/* Field Mapping Section */}
<View style={styles.fieldsSection}>
diff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsx
index 95787734..8d32dcc8 100644
--- a/apps/mobile/src/screens/SetupImportScreen.tsx
+++ b/apps/mobile/src/screens/SetupImportScreen.tsx
@@ -11,6 +11,7 @@ import { Container, Card, Button, SectionTitle } from "../components"
import { fonts } from "../styles/typography"
import { CircleAlert, CircleCheck, Import } from "lucide-react-native"
import SettingsService from "../services/SettingsService"
+import { OVERLAND_BATCH_MIN, OVERLAND_BATCH_MAX } from "../constants"
import { isEndpointAllowed } from "../utils/settingsValidation"
import NativeLocationService from "../services/NativeLocationService"
import { showAlert } from "../services/modalService"
@@ -24,6 +25,7 @@ import {
type CustomField,
type ApiTemplateName,
type HttpMethod,
+ type DawarichMode,
type SelectablePreset,
type SyncPreset,
type Geofence
@@ -63,12 +65,14 @@ const VALID_API_TEMPLATES: ApiTemplateName[] = [
"custom",
"dawarich",
"geopulse",
+ "overland",
"owntracks",
"phonetrack",
"reitti",
"traccar"
]
const VALID_HTTP_METHODS: HttpMethod[] = ["POST", "GET"]
+const VALID_DAWARICH_MODES: DawarichMode[] = ["single", "batch"]
const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]
function detectPreset(settings: Partial<Settings>): SyncPreset {
@@ -186,6 +190,25 @@ function validateConfig(raw: unknown): ValidationResult {
entries.push({ label: "HTTP method", value: obj.httpMethod, category: "api" })
}
+ if (
+ "dawarichMode" in obj &&
+ typeof obj.dawarichMode === "string" &&
+ VALID_DAWARICH_MODES.includes(obj.dawarichMode as DawarichMode)
+ ) {
+ settings.dawarichMode = obj.dawarichMode as DawarichMode
+ entries.push({ label: "Dawarich mode", value: obj.dawarichMode, category: "api" })
+ }
+
+ if (
+ "overlandBatchSize" in obj &&
+ typeof obj.overlandBatchSize === "number" &&
+ obj.overlandBatchSize >= OVERLAND_BATCH_MIN &&
+ obj.overlandBatchSize <= OVERLAND_BATCH_MAX
+ ) {
+ settings.overlandBatchSize = Math.floor(obj.overlandBatchSize)
+ entries.push({ label: "Overland batch size", value: String(settings.overlandBatchSize), category: "api" })
+ }
+
if ("fieldMap" in obj && typeof obj.fieldMap === "object" && obj.fieldMap !== null) {
const fm = obj.fieldMap as Record<string, unknown>
const validFieldMap: Partial<FieldMap> = {}
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 020aed29..87e0faa9 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -74,6 +74,8 @@ class NativeLocationService {
syncSsid: settings.syncSsid,
httpMethod: settings.httpMethod,
apiTemplate: settings.apiTemplate,
+ dawarichMode: settings.dawarichMode,
+ overlandBatchSize: settings.overlandBatchSize,
customFields: Object.fromEntries(settings.customFields.filter((f) => f.key).map((f) => [f.key, f.value]))
}
diff --git a/apps/mobile/src/types/__tests__/defaults.test.ts b/apps/mobile/src/types/__tests__/defaults.test.ts
index 1af64828..c1c056d8 100644
--- a/apps/mobile/src/types/__tests__/defaults.test.ts
+++ b/apps/mobile/src/types/__tests__/defaults.test.ts
@@ -55,6 +55,14 @@ describe("DEFAULT_SETTINGS", () => {
expect(DEFAULT_SETTINGS.httpMethod).toBe("POST")
})
+ it("defaults to single dawarichMode", () => {
+ expect(DEFAULT_SETTINGS.dawarichMode).toBe("single")
+ })
+
+ it("defaults overlandBatchSize to 50", () => {
+ expect(DEFAULT_SETTINGS.overlandBatchSize).toBe(50)
+ })
+
it("has all required Settings keys", () => {
const requiredKeys: (keyof Settings)[] = [
"interval",
@@ -69,7 +77,9 @@ describe("DEFAULT_SETTINGS", () => {
"syncPreset",
"filterInaccurateLocations",
"accuracyThreshold",
- "httpMethod"
+ "httpMethod",
+ "dawarichMode",
+ "overlandBatchSize"
]
for (const key of requiredKeys) {
@@ -125,7 +135,7 @@ describe("TRACKING_PRESETS", () => {
})
describe("API_TEMPLATES", () => {
- const templateNames = ["dawarich", "geopulse", "owntracks", "phonetrack", "reitti", "traccar"] as const
+ const templateNames = ["dawarich", "geopulse", "overland", "owntracks", "phonetrack", "reitti", "traccar"] as const
it.each(templateNames)("%s has valid fieldMap with required keys", (name) => {
const template = API_TEMPLATES[name]
@@ -134,7 +144,7 @@ describe("API_TEMPLATES", () => {
expect(template.fieldMap).toHaveProperty("acc")
})
- const templatesWithCustomFields = ["dawarich", "owntracks", "phonetrack", "reitti", "traccar"] as const
+ const templatesWithCustomFields = ["dawarich", "overland", "owntracks", "phonetrack", "reitti", "traccar"] as const
it.each(templatesWithCustomFields)("%s has non-empty customFields", (name) => {
expect(API_TEMPLATES[name].customFields.length).toBeGreaterThan(0)
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index 1d1edd28..a05aac14 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -106,7 +106,17 @@ export type HttpMethod = "POST" | "GET"
export type SyncCondition = "any" | "wifi_any" | "wifi_ssid" | "vpn"
-export type ApiTemplateName = "custom" | "dawarich" | "geopulse" | "owntracks" | "phonetrack" | "reitti" | "traccar"
+export type ApiTemplateName =
+ | "custom"
+ | "dawarich"
+ | "geopulse"
+ | "overland"
+ | "owntracks"
+ | "phonetrack"
+ | "reitti"
+ | "traccar"
+
+export type DawarichMode = "single" | "batch"
export interface ApiTemplate {
name: ApiTemplateName
@@ -152,6 +162,23 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTempla
},
customFields: [{ key: "_type", value: "location" }]
},
+ overland: {
+ name: "overland",
+ label: "Overland",
+ description: "Overland-compatible batch endpoint (GeoJSON Features)",
+ fieldMap: {
+ lat: "lat",
+ lon: "lon",
+ acc: "acc",
+ alt: "alt",
+ vel: "vel",
+ batt: "batt",
+ bs: "bs",
+ tst: "tst",
+ bear: "bear"
+ },
+ customFields: [{ key: "device_id", value: "colota" }]
+ },
owntracks: {
name: "owntracks",
label: "OwnTracks",
@@ -292,6 +319,8 @@ export interface Settings {
customFields: CustomField[]
apiTemplate: ApiTemplateName
httpMethod: HttpMethod
+ dawarichMode: DawarichMode
+ overlandBatchSize: number
// Sync & Upload
syncInterval: number
@@ -320,7 +349,9 @@ export const DEFAULT_SETTINGS: Settings = {
syncCondition: "any",
syncSsid: "",
hasCompletedSetup: false,
- httpMethod: "POST"
+ httpMethod: "POST",
+ dawarichMode: "single",
+ overlandBatchSize: 50
} as const
// ============================================================================
diff --git a/apps/mobile/src/utils/__tests__/apiPayload.test.ts b/apps/mobile/src/utils/__tests__/apiPayload.test.ts
index 7aa5b659..dae5675a 100644
--- a/apps/mobile/src/utils/__tests__/apiPayload.test.ts
+++ b/apps/mobile/src/utils/__tests__/apiPayload.test.ts
@@ -1,4 +1,9 @@
-import { buildTraccarJsonPayload } from "../apiPayload"
+import {
+ buildOverlandBatchPayload,
+ buildTraccarJsonPayload,
+ isOverlandFormat,
+ isTraccarJsonFormat
+} from "../apiPayload"
describe("buildTraccarJsonPayload", () => {
const baseParams = {
@@ -61,3 +66,78 @@ describe("buildTraccarJsonPayload", () => {
expect(result.device_id).toBe("colota")
})
})
+
+describe("isTraccarJsonFormat", () => {
+ it("is true only for traccar template with POST method", () => {
+ expect(isTraccarJsonFormat("traccar", "POST")).toBe(true)
+ expect(isTraccarJsonFormat("traccar", "GET")).toBe(false)
+ expect(isTraccarJsonFormat("dawarich", "POST")).toBe(false)
+ expect(isTraccarJsonFormat("custom", "POST")).toBe(false)
+ })
+})
+
+describe("isOverlandFormat", () => {
+ it("is true for dawarich template with batch mode", () => {
+ expect(isOverlandFormat("dawarich", "batch")).toBe(true)
+ expect(isOverlandFormat("dawarich", "single")).toBe(false)
+ })
+
+ it("is true for the overland template regardless of dawarichMode", () => {
+ expect(isOverlandFormat("overland", "single")).toBe(true)
+ expect(isOverlandFormat("overland", "batch")).toBe(true)
+ })
+
+ it("is false for unrelated templates", () => {
+ expect(isOverlandFormat("traccar", "batch")).toBe(false)
+ expect(isOverlandFormat("custom", "batch")).toBe(false)
+ expect(isOverlandFormat("owntracks", "single")).toBe(false)
+ })
+})
+
+describe("buildOverlandBatchPayload", () => {
+ const baseParams = {
+ latitude: 51.5,
+ longitude: -0.04,
+ accuracy: 12,
+ altitude: 519,
+ speed: 0,
+ course: 180.5,
+ batteryLevel: 0.85,
+ batteryState: "charging" as const,
+ deviceId: "my-pixel"
+ }
+
+ it("wraps a single feature in locations array", () => {
+ const result = buildOverlandBatchPayload(baseParams) as any
+ expect(Array.isArray(result.locations)).toBe(true)
+ expect(result.locations).toHaveLength(1)
+ expect(result.locations[0].type).toBe("Feature")
+ })
+
+ it("uses GeoJSON [lon, lat] coordinate order", () => {
+ const result = buildOverlandBatchPayload(baseParams) as any
+ expect(result.locations[0].geometry.coordinates).toEqual([-0.04, 51.5])
+ })
+
+ it("places device_id at envelope level not per Feature", () => {
+ const result = buildOverlandBatchPayload(baseParams) as any
+ expect(result.device_id).toBe("my-pixel")
+ expect(result.locations[0].properties.device_id).toBeUndefined()
+ })
+
+ it("maps properties correctly", () => {
+ const result = buildOverlandBatchPayload(baseParams) as any
+ const props = result.locations[0].properties
+ expect(props.horizontal_accuracy).toBe(12)
+ expect(props.altitude).toBe(519)
+ expect(props.speed).toBe(0)
+ expect(props.course).toBe(180.5)
+ expect(props.battery_level).toBe(0.85)
+ expect(props.battery_state).toBe("charging")
+ })
+
+ it("uses provided timestamp", () => {
+ const result = buildOverlandBatchPayload({ ...baseParams, timestamp: "2026-05-09T12:34:56Z" }) as any
+ expect(result.locations[0].properties.timestamp).toBe("2026-05-09T12:34:56Z")
+ })
+})
diff --git a/apps/mobile/src/utils/apiPayload.ts b/apps/mobile/src/utils/apiPayload.ts
index 3f1c3fb9..36f9b200 100644
--- a/apps/mobile/src/utils/apiPayload.ts
+++ b/apps/mobile/src/utils/apiPayload.ts
@@ -3,6 +3,50 @@ export function isTraccarJsonFormat(apiTemplate: string, httpMethod: string): bo
return apiTemplate === "traccar" && httpMethod === "POST"
}
+/** Returns true when the active settings require the Overland batch envelope. */
+export function isOverlandFormat(apiTemplate: string, dawarichMode: string): boolean {
+ return apiTemplate === "overland" || (apiTemplate === "dawarich" && dawarichMode === "batch")
+}
+
+/**
+ * Builds a Dawarich/Overland batch envelope for the example payload preview.
+ * Custom fields land at envelope level (matches the Overland iOS client).
+ */
+export function buildOverlandBatchPayload(params: {
+ latitude: number
+ longitude: number
+ accuracy: number
+ altitude: number
+ speed: number
+ course: number
+ batteryLevel: number
+ batteryState: "unknown" | "unplugged" | "charging" | "full"
+ deviceId: string
+ timestamp?: string
+}): object {
+ return {
+ locations: [
+ {
+ type: "Feature",
+ geometry: {
+ type: "Point",
+ coordinates: [params.longitude, params.latitude]
+ },
+ properties: {
+ timestamp: params.timestamp ?? new Date().toISOString(),
+ horizontal_accuracy: params.accuracy,
+ altitude: params.altitude,
+ speed: params.speed,
+ course: params.course,
+ battery_level: params.batteryLevel,
+ battery_state: params.batteryState
+ }
+ }
+ ],
+ device_id: params.deviceId
+ }
+}
+
/**
* Builds a Traccar JSON payload (Traccar 6.7.0+ OsmAnd POST format).
* Used for both the example payload preview and the test connection request.
diff --git a/apps/mobile/src/utils/healthCheck.ts b/apps/mobile/src/utils/healthCheck.ts
index f0cd2723..0db5f1a0 100644
--- a/apps/mobile/src/utils/healthCheck.ts
+++ b/apps/mobile/src/utils/healthCheck.ts
@@ -14,6 +14,9 @@ export function resolveHealthUrls(endpoint: string, apiTemplate: ApiTemplateName
}
case "dawarich":
return [`${origin}/api/v1/health`, origin]
+ case "overland":
+ // Portable format, no canonical server
+ return [origin]
case "owntracks":
// /api/0/version for OwnTracks Recorder; Home Assistant responds at root if that 404s
return [`${origin}/api/0/version`, origin]