Skip to content

Colota - Android GPS Location tracker

feat(profiles): add Wi-Fi and Wi-Fi network tracking conditions (#937)

Adrian Groh69e8dcb1f3ae
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 463a2485..a63746e4 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -210,7 +210,7 @@ Orchestrates batch location uploads with:
### NetworkManager
-HTTP client. Injects auth headers, caches connectivity checks, and detects unmetered connections and VPN status for sync condition filtering. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the `wifi_ssid` condition is active or the SSID picker asks. Endpoint policy (HTTPS-for-public, private host detection) is delegated to `UrlSafety`.
+HTTP client. Injects auth headers, caches connectivity checks, and detects unmetered connections and VPN status for sync condition filtering. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the sync `wifi_ssid` condition is active; profile conditions read the name through a one-shot probe when the network changes. Connected Wi-Fi is tracked separately with a plain (unflagged) Wi-Fi-transport callback, so the profile conditions also see the network under a VPN. Endpoint policy (HTTPS-for-public, private host detection) is delegated to `UrlSafety`.
For mTLS-protected endpoints, builds the `HttpsURLConnection` with a custom `SSLSocketFactory` supplied by `ClientCertSslContextProvider` (per-instance, never `setDefaultSSLSocketFactory()` - the override is scoped to outbound location sync, not the whole process).
@@ -248,7 +248,7 @@ When both WiFi and motionless pause are enabled, GPS only resumes when both cond
### ProfileManager
-Evaluates tracking profile conditions and switches GPS settings automatically. Supports five condition types: charging, Android Auto / car mode, speed above threshold, speed below threshold, and stationary. Uses a rolling speed buffer for averaged speed readings, deactivation delays (hysteresis) to prevent rapid toggling, and priority-based resolution when multiple profiles match.
+Evaluates tracking profile conditions and switches GPS settings automatically. Supports seven condition types: charging, Android Auto / car mode, Wi-Fi (any network), Wi-Fi network (named SSID), speed above threshold, speed below threshold, and stationary. Uses a rolling speed buffer for averaged speed readings, deactivation delays (hysteresis) to prevent rapid toggling, and priority-based resolution when multiple profiles match.
The stationary condition is decided by the fixes and never by a timer. `evaluateStationaryState` tracks a run of consecutive fixes below 0.3 m/s and the verdict is reached by the fix that completes the window, so a stream that stops delivering cannot produce one. A gap restarts the run unless it is within three times the previous gap, or 60 seconds if that is larger, and no gap over 15 minutes is ever tolerated. Calibrating on the previous gap keeps a sparse Doze cadence usable while a fast stream that goes quiet is treated as unobserved time rather than stillness; the window length deliberately plays no part, or a long window would license a long blackout. The motion sensor discards a run in progress as well as an active verdict.
@@ -258,11 +258,11 @@ Database access layer for tracking profiles and trip events. Maintains a `TimedC
### ConditionMonitor
-Monitors charging state via `BroadcastReceiver` and Android Auto connection via the `CarConnection` API. Forwards state changes to `ProfileManager` for condition evaluation.
+Monitors charging state via `BroadcastReceiver`, Android Auto connection via the `CarConnection` API, and Wi-Fi transport changes from `NetworkManager`, reading the network name one-shot when a named-network profile needs it. Forwards state changes to `ProfileManager` for condition evaluation.
### ProfileConstants
-Centralized constants for condition type strings (`charging`, `android_auto`, `speed_above`, `speed_below`, `stationary`), event types (`activated`, `deactivated`), cache TTL, speed buffer size, and minimum interval.
+Centralized constants for condition type strings (`charging`, `android_auto`, `speed_above`, `speed_below`, `stationary`, `wifi_any`, `wifi_ssid`), event types (`activated`, `deactivated`), cache TTL, speed buffer size, and minimum interval.
### SecureStorageHelper
diff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.md
index d2fbf031..2df9ce48 100644
--- a/apps/docs/docs/guides/deep-link-setup.md
+++ b/apps/docs/docs/guides/deep-link-setup.md
@@ -102,7 +102,8 @@ Each entry in the `profiles` array describes one [tracking profile](tracking-pro
| `interval` | number | (required) | GPS interval in seconds (must be >= 1) |
| `distance` | number | (required) | Movement threshold in meters |
| `syncInterval` | number | (required) | Sync interval in seconds (0 = instant) |
-| `condition.type` | string | (required) | `charging`, `android_auto`, `speed_above`, `speed_below`, or `stationary` |
+| `condition.type` | string | (required) | `charging`, `android_auto`, `wifi_any`, `wifi_ssid`, `speed_above`, `speed_below`, or `stationary` |
+| `condition.ssid` | string | - | Required for `wifi_ssid`. Network name as shown in Wi-Fi settings |
| `condition.speedThreshold` | number | - | Required for `speed_above` / `speed_below`. Speed in m/s (divide km/h by 3.6) |
| `priority` | number | `10` | Higher value wins when multiple profiles match |
| `activationDelay` | number | `0` (stationary: `60`) | Seconds the condition must keep matching before the profile is applied (0 = immediate). For `stationary`, how long the device must be still before activating |
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 6f559020..691d289d 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -15,6 +15,7 @@ A tracking profile is a rule: while a condition holds, such as charging, Android
- **Charging** - Increase tracking frequency while plugged in (battery isn't a concern)
- **Driving** - Switch to frequent updates when Android Auto connects or speed exceeds a threshold
- **Walking** - Use longer intervals at low speeds to conserve battery
+- **At home or work** - Use longer intervals while on a trusted Wi-Fi network
- **Stationary** - Record a periodic heartbeat point (e.g. every 30 min) as proof-of-presence while not moving
## Setup
@@ -36,18 +37,32 @@ The list opens with a line that says which profile is in force and its values, "
## Condition Types
-| Condition | Trigger |
-| ---------------- | --------------------------------------------------------- |
-| **Charging** | Phone is plugged in to a power source |
-| **Android Auto** | Android Auto is connected |
-| **Speed above** | Average speed exceeds the speed you set (km/h or mph) |
-| **Speed below** | Average speed drops below the speed you set (km/h or mph) |
-| **Stationary** | Still for the activation delay (60 s by default) |
+| Condition | Trigger |
+| ----------------- | --------------------------------------------------------- |
+| **Charging** | Phone is plugged in to a power source |
+| **Android Auto** | Android Auto is connected |
+| **Wi-Fi** | Connected to a Wi-Fi network |
+| **Wi-Fi network** | Connected to the network you name (SSID) |
+| **Speed above** | Average speed exceeds the speed you set (km/h or mph) |
+| **Speed below** | Average speed drops below the speed you set (km/h or mph) |
+| **Stationary** | Still for the activation delay (60 s by default) |
A stationary profile records less often, but GPS stays on. To stop GPS while you stay somewhere, use a [geofence](geofencing) with WiFi pause or motionless pause.
+Wi-Fi conditions react to network changes as they happen. A lost connection deactivates after the profile's deactivation delay — set it to 0 if you want the profile to drop the instant the network disappears. New Wi-Fi / Wi-Fi network profiles get the usual 0 s activation and 60 s deactivation defaults.
+
Speed conditions use a rolling average of the last 5 GPS readings to avoid triggering on momentary speed spikes. The stationary condition uses a fixed speed threshold (0.3 m/s) that has to hold across 60 seconds of fixes, so unlike speed-below it does not flap on GPS noise near zero. The window is measured over the fixes themselves, so a stretch with no fixes at all is not counted as stillness and the profile waits for the stream instead of switching on.
+:::caution[Wi-Fi condition caveats]
+
+Reading a network name counts as location access, so a **Wi-Fi network** profile makes the location indicator flash briefly when the app checks the network after a change. It is not continuous: the name is read once per network change, not held for the session.
+
+**Wi-Fi** means the phone is connected to a Wi-Fi network, whether or not a VPN owns the traffic; Ethernet does not match.
+
+SSID matching is case-insensitive. Without location permission or with Location turned off, Android hides the network name and the **Wi-Fi network** condition does not match.
+
+:::
+
:::tip[Stationary profile]
Colota starts the motion detector when the device goes still. It watches accelerometer variance and the hardware significant motion sensor together, so moving again usually ends the profile within seconds rather than at the next fix. That is why the editor hides the deactivation delay here.
@@ -98,6 +113,7 @@ If you use both a Speed Below and a Stationary profile, give Stationary the high
| Stationary | Stationary | 1800s | 0m | 40 | 60s | n/a | Heartbeat while not moving |
| Driving | Android Auto | 10s | 1m | 30 | 0s | 30s | Detailed route while driving |
| Walking | Speed below 8 km/h | 60s | 2m | 20 | 20s | 45s | Battery-friendly on foot |
+| Home | Wi-Fi network | 300s | 10m | 25 | 0s | 60s | Relaxed updates on a trusted network |
| Charging | Charging | 15s | 0m | 10 | 0s | 30s | High accuracy while plugged in |
Note that Stationary has the highest priority so it takes over from Walking when you stop. Charging has the lowest priority so a more specific profile (e.g. Driving) wins when both match.
@@ -123,4 +139,4 @@ When a profile is active, Colota shows it in three places:
All of them clear when the profile deactivates (after the deactivation delay) or when tracking stops.
-A blank name saves as the condition's name, so two untouched charging profiles are both called "Charging"; a setup link import replaces a profile by name, so give profiles you share distinct names.
+A blank name saves as the condition's name, so two untouched charging profiles are both called "Charging"; a setup link import replaces a profile by name, so give profiles you share distinct names. Sharing a **Wi-Fi network** profile also shares the network name it watches.
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 6b3f5182..afbcf2c3 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -19,7 +19,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to
- **Import Your History** - Bring in existing tracks from GeoJSON, Google Timeline, GPX, KML or CSV.
- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.
- **Geofencing** - Pause zones that stop recording locations. Optionally stop GPS entirely when on WiFi or when the device is motionless.
-- **Tracking profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, speed or stationary detection.
+- **Tracking profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, Wi-Fi, speed or stationary detection.
- **Flexible Sync** - Instant, batch, Wi-Fi only or offline modes.
- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.
- **App Shortcuts** - Long-press the app icon to start or stop tracking from the home screen. Compatible with automation apps like Tasker and Samsung Routines.
diff --git a/apps/docs/src/components/DeepLinkGenerator.tsx b/apps/docs/src/components/DeepLinkGenerator.tsx
index 9f194d19..9ffe8da0 100644
--- a/apps/docs/src/components/DeepLinkGenerator.tsx
+++ b/apps/docs/src/components/DeepLinkGenerator.tsx
@@ -20,12 +20,14 @@ interface GeofenceRow {
heartbeatIntervalMinutes: string
}
-type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary"
+type ProfileConditionType =
+ "charging" | "android_auto" | "wifi_any" | "wifi_ssid" | "speed_above" | "speed_below" | "stationary"
interface ProfileRow {
name: string
conditionType: ProfileConditionType
speedKmh: string
+ ssid: string
interval: string
distance: string
syncInterval: string
@@ -41,6 +43,8 @@ const QR_MAX_SCANNABLE_LENGTH = 1200
const PROFILE_CONDITION_OPTIONS: { value: ProfileConditionType; label: string }[] = [
{ value: "charging", label: "Charging" },
{ value: "android_auto", label: "Android Auto / Car mode" },
+ { value: "wifi_any", label: "Wi-Fi" },
+ { value: "wifi_ssid", label: "Wi-Fi network" },
{ value: "speed_above", label: "Speed above threshold" },
{ value: "speed_below", label: "Speed below threshold" },
{ value: "stationary", label: "Stationary" }
@@ -189,6 +193,11 @@ export default function DeepLinkGenerator() {
if (!p.speedKmh || Number(p.speedKmh) <= 0) continue
condition.speedThreshold = Number(p.speedKmh) / 3.6
}
+ if (p.conditionType === "wifi_ssid") {
+ const ssid = p.ssid.trim()
+ if (!ssid) continue
+ condition.ssid = ssid
+ }
const entry: Record<string, unknown> = {
name: p.name,
@@ -338,6 +347,7 @@ export default function DeepLinkGenerator() {
name: "",
conditionType: "charging",
speedKmh: "",
+ ssid: "",
interval: "5",
distance: "0",
syncInterval: "0",
@@ -786,6 +796,7 @@ export default function DeepLinkGenerator() {
<div className={styles.keyValueList}>
{profiles.map((p, i) => {
const isSpeed = p.conditionType === "speed_above" || p.conditionType === "speed_below"
+ const isWifiSsid = p.conditionType === "wifi_ssid"
const isStationary = p.conditionType === "stationary"
return (
<div key={i} className={styles.geofenceCard}>
@@ -839,6 +850,17 @@ export default function DeepLinkGenerator() {
/>
</div>
)}
+ {isWifiSsid && (
+ <div className={styles.field}>
+ <label className={styles.label}>Wi-Fi SSID</label>
+ <input
+ className={styles.input}
+ placeholder="MyNetwork"
+ value={p.ssid}
+ onChange={(e) => updateProfile(i, "ssid", e.target.value)}
+ />
+ </div>
+ )}
</div>
<div className={styles.row}>
<div className={styles.field}>
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index 736c2bba..38abc921 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -73,7 +73,7 @@ const features = [
{
title: "Tracking profiles",
description:
- "Multiple GPS configs that auto-switch on charging, Android Auto, speed or stationary detection. One profile for hiking, another for the commute."
+ "Multiple GPS configs that auto-switch on charging, Android Auto, Wi-Fi, speed or stationary detection. One profile for hiking, another for the commute."
},
{
title: "Sync, backup and export",
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index de39c8f8..3f30b19c 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -34,7 +34,7 @@ If you create pause zones (geofences), the App stores zone names, coordinates, r
### Condition Monitoring
-When tracking profiles are enabled, the App monitors charging state, car mode (Android Auto) and GPS speed derived from location updates to automatically switch tracking configurations. These condition states are transient and are not stored in the database. The name of the currently active pause zone is persisted across service restarts to maintain continuity but is cleared when the zone is exited.
+When tracking profiles are enabled, the App monitors charging state, car mode (Android Auto), GPS speed derived from location updates, and Wi-Fi connectivity to automatically switch tracking configurations. For a named-network profile the App reads the connected network's name when the connection changes; the name you configure for the profile is stored in the local profile database, while the detected state itself is transient and is not stored. The name of the currently active pause zone is persisted across service restarts to maintain continuity but is cleared when the zone is exited.
### Sensor Data
@@ -42,7 +42,7 @@ When motionless pause is enabled for a geofence zone or a stationary tracking pr
### Network State
-When WiFi pause is enabled for a geofence zone, the App monitors whether the device is connected to an unmetered network (WiFi or Ethernet). Only the connection type is checked - no network names, SSIDs or IP addresses are collected or stored.
+When WiFi pause is enabled for a geofence zone, the App monitors whether the device is connected to an unmetered network (WiFi or Ethernet). That check looks only at the connection type - no network names or IP addresses are collected or stored by it. If you configure a tracking profile for a named Wi-Fi network, the network name you enter is stored in the local profile database and used to match the current connection; it is shared only if you share that profile.
All data is stored **locally on your device** and is never sent anywhere unless you configure a server. The App does not collect personal identifiers, advertising IDs, device identifiers (IMEI, serial number), usage analytics, telemetry, or crash reports.
@@ -130,21 +130,21 @@ Since all data is stored locally on your device, you have full control:
## Permissions
-| Permission | Purpose |
-| --------------------------------- | ------------------------------------------------------ |
-| Location (Precise) | GPS tracking |
-| Location (Approximate) | Required alongside precise location on Android |
-| Background Location (Android 10+) | Tracking while the app is not in the foreground |
-| Foreground Service | Background tracking with notification |
-| Foreground Service (Location) | Location access while tracking in the background |
-| Foreground Service (Data Sync) | Auto-export background processing |
-| Notification (Android 13+) | Foreground service notification |
-| Boot Completed | Auto-start tracking after device reboot |
-| Internet | Server sync and map tile loading |
-| Network State | Sync condition checks and WiFi pause in geofence zones |
-| Wi-Fi State | SSID detection for sync condition filtering |
-| Local Network (Android 17+) | Required for sync to servers on the local network |
-| Battery Optimization Exemption | Optional, prevents system from restricting the app |
+| Permission | Purpose |
+| --------------------------------- | ------------------------------------------------------- |
+| Location (Precise) | GPS tracking |
+| Location (Approximate) | Required alongside precise location on Android |
+| Background Location (Android 10+) | Tracking while the app is not in the foreground |
+| Foreground Service | Background tracking with notification |
+| Foreground Service (Location) | Location access while tracking in the background |
+| Foreground Service (Data Sync) | Auto-export background processing |
+| Notification (Android 13+) | Foreground service notification |
+| Boot Completed | Auto-start tracking after device reboot |
+| Internet | Server sync and map tile loading |
+| Network State | Sync condition checks and WiFi pause in geofence zones |
+| Wi-Fi State | SSID detection for sync and tracking-profile conditions |
+| Local Network (Android 17+) | Required for sync to servers on the local network |
+| Battery Optimization Exemption | Optional, prevents system from restricting the app |
## Children's Privacy
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 481b4d32..dabbe642 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -700,6 +700,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
conditionType = config.getString("conditionType") ?: ProfileConstants.CONDITION_CHARGING,
speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))
config.getDouble("speedThreshold").toFloat() else null,
+ wifiSsid = config.getStringOrNull("wifiSsid")?.takeIf { it.isNotBlank() },
deactivationDelaySeconds = config.getInt("deactivationDelaySeconds"),
activationDelaySeconds = config.getInt("activationDelaySeconds"),
)
@@ -720,6 +721,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))
config.getDouble("speedThreshold").toFloat() else null,
hasSpeedThreshold = config.hasKey("speedThreshold"),
+ wifiSsid = config.getStringOrNull("wifiSsid")?.takeIf { it.isNotBlank() },
+ hasWifiSsid = config.hasKey("wifiSsid"),
deactivationDelaySeconds = config.getIntOrNull("deactivationDelaySeconds"),
activationDelaySeconds = config.getIntOrNull("activationDelaySeconds"),
enabled = config.getBooleanOrNull("enabled"),
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 e5bd775d..cf4afbcd 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
@@ -32,7 +32,7 @@ class DatabaseHelper private constructor(context: Context) :
companion object {
const val DATABASE_NAME = "Colota.db"
- const val DATABASE_VERSION = 7
+ const val DATABASE_VERSION = 8
const val TABLE_LOCATIONS = "locations"
const val TABLE_QUEUE = "queue"
@@ -63,6 +63,7 @@ class DatabaseHelper private constructor(context: Context) :
priority INTEGER NOT NULL DEFAULT 0,
condition_type TEXT NOT NULL,
speed_threshold REAL,
+ wifi_ssid TEXT,
deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
activation_delay_seconds INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
@@ -256,6 +257,9 @@ class DatabaseHelper private constructor(context: Context) :
if (oldVersion < 7) {
db.execSQL(CREATE_BOUNDARY_OVERRIDES_TABLE)
}
+ if (oldVersion < 8) {
+ db.execSQL("ALTER TABLE $TABLE_PROFILES ADD COLUMN wifi_ssid TEXT")
+ }
}
@JvmStatic
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
index 8eaaeb29..f3fa9e2b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
@@ -28,6 +28,8 @@ class ProfileHelper(private val context: Context) {
val priority: Int,
val conditionType: String,
val speedThreshold: Float?,
+ /** The network the profile matches by name; null for every other condition. */
+ val wifiSsid: String? = null,
val deactivationDelaySeconds: Int,
val activationDelaySeconds: Int,
)
@@ -51,7 +53,7 @@ class ProfileHelper(private val context: Context) {
arrayOf(
"id", "name", "interval_ms", "min_update_distance",
"sync_interval_seconds", "priority", "condition_type",
- "speed_threshold", "deactivation_delay_seconds",
+ "speed_threshold", "wifi_ssid", "deactivation_delay_seconds",
"activation_delay_seconds",
),
"enabled = 1",
@@ -66,6 +68,7 @@ class ProfileHelper(private val context: Context) {
val priorityIdx = cursor.getColumnIndexOrThrow("priority")
val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
+ val wifiSsidIdx = cursor.getColumnIndexOrThrow("wifi_ssid")
val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")
@@ -79,6 +82,7 @@ class ProfileHelper(private val context: Context) {
priority = cursor.getInt(priorityIdx),
conditionType = cursor.getString(conditionIdx),
speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
+ wifiSsid = if (cursor.isNull(wifiSsidIdx)) null else cursor.getString(wifiSsidIdx),
deactivationDelaySeconds = cursor.getInt(delayIdx),
activationDelaySeconds = cursor.getInt(activationDelayIdx),
))
@@ -108,6 +112,7 @@ class ProfileHelper(private val context: Context) {
val priorityIdx = cursor.getColumnIndexOrThrow("priority")
val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
+ val wifiSsidIdx = cursor.getColumnIndexOrThrow("wifi_ssid")
val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")
val enabledIdx = cursor.getColumnIndexOrThrow("enabled")
@@ -127,6 +132,11 @@ class ProfileHelper(private val context: Context) {
} else {
putDouble("speedThreshold", cursor.getFloat(speedIdx).toDouble())
}
+ if (cursor.isNull(wifiSsidIdx)) {
+ putNull("wifiSsid")
+ } else {
+ putString("wifiSsid", cursor.getString(wifiSsidIdx))
+ }
putInt("deactivationDelaySeconds", cursor.getInt(delayIdx))
putInt("activationDelaySeconds", cursor.getInt(activationDelayIdx))
putBoolean("enabled", cursor.getInt(enabledIdx) == 1)
@@ -149,6 +159,7 @@ class ProfileHelper(private val context: Context) {
priority: Int,
conditionType: String,
speedThreshold: Float?,
+ wifiSsid: String?,
deactivationDelaySeconds: Int,
activationDelaySeconds: Int,
): Int {
@@ -160,6 +171,7 @@ class ProfileHelper(private val context: Context) {
put("priority", priority)
put("condition_type", conditionType)
if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")
+ if (wifiSsid != null) put("wifi_ssid", wifiSsid) else putNull("wifi_ssid")
put("deactivation_delay_seconds", deactivationDelaySeconds)
put("activation_delay_seconds", activationDelaySeconds)
put("enabled", 1)
@@ -186,6 +198,8 @@ class ProfileHelper(private val context: Context) {
conditionType: String? = null,
speedThreshold: Float? = null,
hasSpeedThreshold: Boolean = false,
+ wifiSsid: String? = null,
+ hasWifiSsid: Boolean = false,
deactivationDelaySeconds: Int? = null,
activationDelaySeconds: Int? = null,
enabled: Boolean? = null,
@@ -200,6 +214,9 @@ class ProfileHelper(private val context: Context) {
if (hasSpeedThreshold) {
if (speedThreshold != null) put("speed_threshold", speedThreshold) else putNull("speed_threshold")
}
+ if (hasWifiSsid) {
+ if (wifiSsid != null) put("wifi_ssid", wifiSsid) else putNull("wifi_ssid")
+ }
deactivationDelaySeconds?.let { put("deactivation_delay_seconds", it) }
activationDelaySeconds?.let { put("activation_delay_seconds", it) }
enabled?.let { put("enabled", if (it) 1 else 0) }
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
index b61e2c22..32031a77 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
@@ -15,20 +15,25 @@ import android.os.Handler
import android.os.Looper
import androidx.car.app.connection.CarConnection
import androidx.lifecycle.Observer
+import com.Colota.sync.NetworkManager
import com.Colota.util.AppLogger
/**
- * Monitors device conditions (charging state, Android Auto connection)
+ * Monitors device conditions (charging state, Android Auto connection, Wi-Fi)
* and notifies ProfileManager when conditions change.
*
* Android Auto is detected via the [CarConnection] API, which reliably
- * reports projection and native car connections.
+ * reports projection and native car connections. Wi-Fi transport changes come
+ * from the service's [NetworkManager], which tracks connected Wi-Fi networks
+ * with a plain (unflagged) callback; a named-network profile reads the name
+ * through a one-shot location-flagged probe when that transport changes.
*
* All observers are registered programmatically so they only run while
* the foreground service is active.
*/
class ConditionMonitor(
private val context: Context,
+ private val networkManager: NetworkManager,
private val profileManager: ProfileManager
) {
companion object {
@@ -39,6 +44,8 @@ class ConditionMonitor(
private var carConnection: CarConnection? = null
private var carConnectionObserver: Observer<Int>? = null
private val mainHandler = Handler(Looper.getMainLooper())
+ // Main thread only: invalidates in-flight SSID probes when a newer network change arrives.
+ private var wifiPushGeneration = 0
fun start() {
// Unregister first to prevent duplicate observers on repeated start() calls
@@ -56,12 +63,17 @@ class ConditionMonitor(
startCarConnectionMonitor()
}
+ if (ProfileConstants.CONDITION_WIFI_ANY in needed || ProfileConstants.CONDITION_WIFI_SSID in needed) {
+ startWifiMonitor()
+ }
+
AppLogger.d(TAG, "Condition monitors started for: ${needed.ifEmpty { setOf("none") }}")
}
fun stop() {
chargingReceiver = unregisterSafely(chargingReceiver)
stopCarConnectionMonitor()
+ networkManager.setWifiStateListener(null)
AppLogger.d(TAG, "Condition monitors stopped")
}
@@ -132,6 +144,40 @@ class ConditionMonitor(
carConnection = null
}
+ /**
+ * Forwards Wi-Fi state changes to the profile manager. The listener is registered before the
+ * first read, so a change landing in that window still arrives instead of being missed.
+ */
+ private fun startWifiMonitor() {
+ networkManager.setWifiStateListener {
+ mainHandler.post { pushWifiState() }
+ }
+ pushWifiState()
+ }
+
+ /**
+ * The transport-only listener above carries no location flag and can stay registered; the
+ * network name is read one-shot only when a named-network profile needs it, so the indicator
+ * lights for that moment instead of the whole session. The probe targets the Wi-Fi transport,
+ * so the name is readable under a VPN too. The generation drops probe results that a newer
+ * network change has already superseded.
+ */
+ private fun pushWifiState() {
+ val generation = ++wifiPushGeneration
+ val connected = networkManager.isWifiConnected()
+ if (connected && ProfileConstants.CONDITION_WIFI_SSID in profileManager.getNeededConditionTypes()) {
+ networkManager.readSsidOnce { ssid ->
+ mainHandler.post {
+ if (generation == wifiPushGeneration) {
+ profileManager.onWifiStateChanged(networkManager.isWifiConnected(), ssid)
+ }
+ }
+ }
+ } else {
+ profileManager.onWifiStateChanged(connected, "")
+ }
+ }
+
private fun readCurrentChargingState(): Boolean {
val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
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 d1ae63de..13b928f0 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
@@ -233,7 +233,7 @@ class LocationForegroundService : Service() {
},
onStationaryChanged = ::handleStationaryChanged
)
- conditionMonitor = ConditionMonitor(this, profileManager)
+ conditionMonitor = ConditionMonitor(this, networkManager, profileManager)
notificationHelper = NotificationHelper(this, notificationManager)
notificationHelper.createChannel()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
index e51e7619..5e12c392 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
@@ -11,6 +11,8 @@ object ProfileConstants {
const val CONDITION_SPEED_ABOVE = "speed_above"
const val CONDITION_SPEED_BELOW = "speed_below"
const val CONDITION_STATIONARY = "stationary"
+ const val CONDITION_WIFI_ANY = "wifi_any"
+ const val CONDITION_WIFI_SSID = "wifi_ssid"
/**
* Conditions whose re-evaluation depends on a fresh stream of location fixes.
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
index a55f7ade..c86d6baf 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
@@ -57,6 +57,8 @@ class ProfileManager(
// Written outside the lock, read by evaluate() under it.
@Volatile private var isCharging = false
@Volatile private var isCarMode = false
+ @Volatile private var isWifiConnected = false
+ @Volatile private var currentSsid: String = ""
@Volatile var isStationary = false
private set
// The current still run, timed by location.time and written without the lock.
@@ -78,6 +80,13 @@ class ProfileManager(
evaluate()
}
+ /** Called on the main thread when the default network's transport or SSID changes. */
+ fun onWifiStateChanged(connected: Boolean, ssid: String) {
+ isWifiConnected = connected
+ currentSsid = ssid
+ evaluate()
+ }
+
/** Called by the motion sensor when the device starts moving while stationary. */
fun onMotionDetected() {
if (!isStationary) return
@@ -223,6 +232,13 @@ class ProfileManager(
avgSpeed != null && threshold != null && avgSpeed < threshold
}
ProfileConstants.CONDITION_STATIONARY -> isStationary
+ ProfileConstants.CONDITION_WIFI_ANY -> isWifiConnected
+ ProfileConstants.CONDITION_WIFI_SSID -> {
+ // Both sides matter: the SSID may not be readable (Location off, or not yet read),
+ // and a profile may carry no name. Either way the condition does not match.
+ val target = profile.wifiSsid
+ isWifiConnected && !target.isNullOrBlank() && target.equals(currentSsid, ignoreCase = true)
+ }
else -> false
}
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 ebfe811a..8e3eb76a 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
@@ -13,6 +13,7 @@ import android.os.Looper
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
+import android.net.NetworkRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
@@ -22,6 +23,7 @@ import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.security.UnrecoverableKeyException
import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
@@ -40,14 +42,26 @@ class NetworkManager(private val context: Context) {
private const val NETWORK_CHECK_CACHE_MS = 5000L
private const val SSID_PROBE_TIMEOUT_MS = 3000L
private const val ERROR_BODY_MAX_CHARS = 200
+ /** What Android returns instead of the SSID without location permission or with Location off. */
+ private const val UNKNOWN_SSID = "<unknown ssid>"
private val WHITESPACE = Regex("\\s+")
}
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
- @Volatile private var currentSsid: String = ""
+ @Volatile var currentSsid: String = ""
+ private set
@Volatile private var isVpn: Boolean = false
+ @Volatile private var isWifi: Boolean = false
@Volatile private var ssidTracking: Boolean = false
+ /** Notified on the callback thread when the transport, VPN or SSID state actually changes. */
+ @Volatile private var wifiStateListener: (() -> Unit)? = null
+ // What the listener last saw; callbacks fire for bandwidth and validation churn too.
+ private var notifiedWifi = false
+ private var notifiedVpn = false
+ private var notifiedSsid = ""
+ /** Connected Wi-Fi networks, counted so losing one of several does not clear the state. */
+ private val availableWifiNetworks = AtomicInteger(0)
private val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager
// Lazy so existing unit tests that mock Context don't trigger EncryptedSharedPreferences init.
@@ -62,6 +76,38 @@ class NetworkManager(private val context: Context) {
private var networkCallback = createNetworkCallback(withSsid = false)
+ /**
+ * Tracks connected Wi-Fi networks by transport alone. It carries no location flag, so it can
+ * stay registered for the manager's lifetime without lighting the privacy indicator, and it
+ * sees Wi-Fi even when a VPN owns the default network.
+ */
+ private val wifiTransportCallback = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) {
+ availableWifiNetworks.incrementAndGet()
+ refreshWifiTransport()
+ }
+
+ override fun onLost(network: Network) {
+ availableWifiNetworks.updateAndGet { maxOf(0, it - 1) }
+ refreshWifiTransport()
+ }
+ }
+
+ /**
+ * The mockable android.jar cannot build a request, so a JVM test without a Builder mock gets
+ * null and skips the registration; on device this never fails.
+ */
+ private val wifiRequest: NetworkRequest? by lazy {
+ try {
+ NetworkRequest.Builder()
+ .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
+ .build()
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Wi-Fi transport request unavailable: ${e.message}")
+ null
+ }
+ }
+
/**
* The location-flagged callback notes FINE_LOCATION on every delivery, which lights the privacy
* indicator with GPS stopped. Register it only while the SSID is needed; VPN state needs no flag.
@@ -79,26 +125,41 @@ class NetworkManager(private val context: Context) {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
// Committed only once a callback is live, so a failed swap can be retried.
ssidTracking = enabled
- if (!enabled) currentSsid = ""
+ // A cleared cache must not notify later as if the name just changed.
+ if (!enabled) {
+ currentSsid = ""
+ notifiedSsid = ""
+ }
} catch (e: Exception) {
AppLogger.e(TAG, "Failed to register network callback", e)
}
}
- /** One-shot SSID read for the picker: the flagged callback is registered for this call only. */
+ /**
+ * One-shot SSID read: the flagged callback is registered for this call only. The probe asks for
+ * a Wi-Fi network rather than the default one, so it also reads the name under a VPN, where the
+ * default network is the tunnel and carries no Wi-Fi info.
+ */
fun readSsidOnce(onResult: (String) -> Unit) {
- if (ssidTracking) {
+ // A live value avoids a second flagged probe; a blank one still probes (VPN, or not yet read).
+ if (ssidTracking && currentSsid.isNotBlank()) {
onResult(currentSsid)
return
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
// Below S the SSID comes from WifiManager, not the callback, so waiting on one would
- // only stall and would return "" whenever there is no default network.
+ // only stall. WifiManager reports the connected network regardless of the VPN.
onResult(readSsid(null))
return
}
+ val request = wifiRequest
+ if (request == null) {
+ onResult("")
+ return
+ }
+
val done = AtomicBoolean(false)
var probe: ConnectivityManager.NetworkCallback? = null
fun finish(ssid: String) {
@@ -118,7 +179,7 @@ class NetworkManager(private val context: Context) {
}
try {
- connectivityManager.registerDefaultNetworkCallback(probe)
+ connectivityManager.registerNetworkCallback(request, probe)
} catch (e: Exception) {
AppLogger.e(TAG, "Failed to register SSID probe", e)
probe = null
@@ -132,10 +193,12 @@ class NetworkManager(private val context: Context) {
fun update(caps: NetworkCapabilities) {
if (withSsid) currentSsid = readSsid(caps)
isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
+ notifyWifiStateIfChanged()
}
fun clear() {
currentSsid = ""
isVpn = false
+ notifyWifiStateIfChanged()
}
return if (withSsid && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
@@ -152,12 +215,32 @@ class NetworkManager(private val context: Context) {
}
private fun readSsid(caps: NetworkCapabilities?): String {
- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- (caps?.transportInfo as? WifiInfo)?.ssid?.removeSurrounding("\"") ?: ""
+ val raw = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (caps?.transportInfo as? WifiInfo)?.ssid
} else {
@Suppress("DEPRECATION")
- wifiManager?.connectionInfo?.ssid?.removeSurrounding("\"") ?: ""
+ wifiManager?.connectionInfo?.ssid
}
+ val ssid = raw?.removeSurrounding("\"") ?: ""
+ // Android reports the placeholder without location permission or with Location off; treat
+ // it as no name so the condition simply does not match (and the picker cannot offer it).
+ return if (ssid == UNKNOWN_SSID) "" else ssid
+ }
+
+ private fun refreshWifiTransport() {
+ isWifi = availableWifiNetworks.get() > 0
+ notifyWifiStateIfChanged()
+ }
+
+ /** Profile evaluation is not free, so only real state changes reach the listener. */
+ @Synchronized
+ private fun notifyWifiStateIfChanged() {
+ val ssid = if (ssidTracking) currentSsid else ""
+ if (isWifi == notifiedWifi && isVpn == notifiedVpn && ssid == notifiedSsid) return
+ notifiedWifi = isWifi
+ notifiedVpn = isVpn
+ notifiedSsid = ssid
+ wifiStateListener?.invoke()
}
init {
@@ -166,6 +249,13 @@ class NetworkManager(private val context: Context) {
} catch (e: Exception) {
AppLogger.e(TAG, "Failed to register network callback", e)
}
+ wifiRequest?.let { request ->
+ try {
+ connectivityManager.registerNetworkCallback(request, wifiTransportCallback)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to register Wi-Fi transport callback", e)
+ }
+ }
}
private val networkCache = TimedCache(NETWORK_CHECK_CACHE_MS) {
@@ -534,6 +624,18 @@ class NetworkManager(private val context: Context) {
return currentSsid.equals(ssid, ignoreCase = true)
}
+ /** True while the default network is Wi-Fi. Needs no location-flagged callback. */
+ fun isWifiConnected(): Boolean = isWifi
+
+ /**
+ * Registers a callback for default-network transport / SSID changes. The listener runs on the
+ * ConnectivityManager callback thread; callers that touch app state must marshal it themselves.
+ * Used by the profile Wi-Fi conditions, which care about more than sync's one boolean.
+ */
+ fun setWifiStateListener(listener: (() -> Unit)?) {
+ wifiStateListener = listener
+ }
+
/**
* Returns true when the active network uses a VPN transport.
* Updated via NetworkCallback.
@@ -541,8 +643,12 @@ class NetworkManager(private val context: Context) {
fun isVpnConnected(): Boolean = isVpn
fun destroy() {
+ wifiStateListener = null
try {
connectivityManager.unregisterNetworkCallback(networkCallback)
} catch (_: Exception) {}
+ try {
+ connectivityManager.unregisterNetworkCallback(wifiTransportCallback)
+ } catch (_: Exception) {}
}
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
index 754e2516..1fadcc76 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
@@ -552,6 +552,63 @@ class LocationServiceModuleTest {
verify { module["startServiceWithAction"](LocationForegroundService.ACTION_RECHECK_ZONE) }
}
+ // ========================================================================
+ // Tracking profiles — Wi-Fi SSID plumbing
+ // ========================================================================
+
+ @Test
+ fun `createProfile forwards the wifi SSID to the helper`() {
+ val module = LocationServiceModule(mockContext)
+ val helper = mockk<ProfileHelper>(relaxed = true)
+ setField(module, "profileHelper", helper)
+ every { helper.insertProfile(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 7
+
+ awaitPromise { promise ->
+ module.createProfile(
+ JavaOnlyMap().apply {
+ putString("name", "Home")
+ putDouble("intervalMs", 60000.0)
+ putDouble("minUpdateDistance", 10.0)
+ putInt("syncIntervalSeconds", 300)
+ putInt("priority", 15)
+ putString("conditionType", "wifi_ssid")
+ putNull("speedThreshold")
+ putString("wifiSsid", "HomeNet")
+ putInt("deactivationDelaySeconds", 60)
+ putInt("activationDelaySeconds", 0)
+ },
+ promise
+ )
+ }
+
+ verify { helper.insertProfile("Home", 60000L, 10f, 300, 15, "wifi_ssid", null, "HomeNet", 60, 0) }
+ }
+
+ @Test
+ fun `updateProfile carries the hasWifiSsid tri-state so the column can be cleared`() {
+ val module = LocationServiceModule(mockContext)
+ val helper = mockk<ProfileHelper>(relaxed = true)
+ setField(module, "profileHelper", helper)
+
+ awaitPromise { promise ->
+ module.updateProfile(
+ JavaOnlyMap().apply {
+ putInt("id", 3)
+ putString("conditionType", "charging")
+ putNull("wifiSsid")
+ },
+ promise
+ )
+ }
+
+ verify {
+ helper.updateProfile(
+ any(), any(), any(), any(), any(), any(), any(), any(), any(),
+ isNull(), eq(true), any(), any(), any()
+ )
+ }
+ }
+
// ========================================================================
// stopService — intent is cleared before the service goes away
// ========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
index 01cc5826..2bc911ec 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt
@@ -102,6 +102,69 @@ class DatabaseHelperSQLiteTest {
assertTrue(columns.contains("activation_delay_seconds"))
}
+ @Test
+ fun `tracking_profiles table includes wifi_ssid column`() {
+ val columns = queryColumnNames("tracking_profiles")
+ assertTrue(columns.contains("wifi_ssid"))
+ }
+
+ // ========================================================================
+ // Migration v7 -> v8: wifi_ssid
+ // ========================================================================
+
+ @Test
+ fun `migration from v7 adds wifi_ssid and leaves existing profiles untouched`() {
+ val candidate = File.createTempFile("candidate-v7", ".db").also { it.delete() }
+ SQLiteDatabase.openOrCreateDatabase(candidate, null).use { old ->
+ old.execSQL(
+ """
+ CREATE TABLE tracking_profiles (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ interval_ms INTEGER NOT NULL,
+ min_update_distance REAL NOT NULL,
+ sync_interval_seconds INTEGER NOT NULL,
+ priority INTEGER NOT NULL DEFAULT 0,
+ condition_type TEXT NOT NULL,
+ speed_threshold REAL,
+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
+ activation_delay_seconds INTEGER NOT NULL DEFAULT 0,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ old.execSQL(
+ """
+ INSERT INTO tracking_profiles
+ (name, interval_ms, min_update_distance, sync_interval_seconds,
+ priority, condition_type, deactivation_delay_seconds, created_at)
+ VALUES ('Charging', 10000, 0, 0, 10, 'charging', 60, 0)
+ """.trimIndent()
+ )
+ old.version = 7
+ }
+
+ DatabaseHelper.migrateCandidate(candidate)
+
+ SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
+ // A literal on purpose: migrateCandidate stamps the constant, so comparing against it
+ // passes for any value and stops forcing a migration arm when the version moves.
+ assertEquals(8, migrated.version)
+ migrated.rawQuery("PRAGMA table_info(tracking_profiles)", null).use { cursor ->
+ val columns = mutableSetOf<String>()
+ while (cursor.moveToNext()) columns.add(cursor.getString(1))
+ assertTrue(columns.contains("wifi_ssid"))
+ }
+ migrated.rawQuery("SELECT wifi_ssid FROM tracking_profiles WHERE name = 'Charging'", null).use { cursor ->
+ assertTrue(cursor.moveToFirst())
+ assertTrue(cursor.isNull(0))
+ }
+ }
+
+ candidate.delete()
+ }
+
// ========================================================================
// Migration v5 -> v6: activation_delay_seconds
// ========================================================================
@@ -147,7 +210,7 @@ class DatabaseHelperSQLiteTest {
SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
// A literal on purpose: migrateCandidate stamps the constant, so comparing against it
// passes for any value and stops forcing a migration arm when the version moves.
- assertEquals(7, migrated.version)
+ assertEquals(8, migrated.version)
// migrateCandidate stamps the version unconditionally, so the version alone proves
// nothing about the v7 step. This is the restore-an-older-backup path.
assertMigratedTableExists(migrated, DatabaseHelper.TABLE_BOUNDARY_OVERRIDES)
@@ -188,7 +251,7 @@ class DatabaseHelperSQLiteTest {
SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
// A literal on purpose: migrateCandidate stamps the constant, so comparing against it
// passes for any value and stops forcing a migration arm when the version moves.
- assertEquals(7, migrated.version)
+ assertEquals(8, migrated.version)
assertMigratedTableExists(migrated, DatabaseHelper.TABLE_BOUNDARY_OVERRIDES)
migrated.rawQuery("PRAGMA table_info(locations)", null).use { locCursor ->
val locCols = mutableSetOf<String>()
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt
index 477bf72a..66f8af5b 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/ProfileHelperTest.kt
@@ -8,6 +8,8 @@ package com.Colota.data
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.Colota.util.AppLogger
+import com.facebook.react.bridge.Arguments
+import com.facebook.react.bridge.WritableMap
import io.mockk.*
import org.junit.After
import org.junit.Assert.*
@@ -61,7 +63,7 @@ class ProfileHelperTest {
val columns = listOf(
"id", "name", "interval_ms", "min_update_distance",
"sync_interval_seconds", "priority", "condition_type",
- "speed_threshold", "deactivation_delay_seconds", "activation_delay_seconds",
+ "speed_threshold", "wifi_ssid", "deactivation_delay_seconds", "activation_delay_seconds",
"enabled", "created_at"
)
@@ -141,6 +143,7 @@ class ProfileHelperTest {
assertEquals(10000L, profiles[0].intervalMs)
assertEquals("charging", profiles[0].conditionType)
assertNull(profiles[0].speedThreshold)
+ assertNull(profiles[0].wifiSsid)
}
@Test
@@ -230,6 +233,57 @@ class ProfileHelperTest {
assertEquals("speed_above", profiles[0].conditionType)
}
+ @Test
+ fun `getEnabledProfiles reads the wifi SSID`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Home", "interval_ms" to 60000L,
+ "min_update_distance" to 10f, "sync_interval_seconds" to 300,
+ "priority" to 15, "condition_type" to "wifi_ssid",
+ "speed_threshold" to null, "wifi_ssid" to "HomeNet",
+ "deactivation_delay_seconds" to 60
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor
+
+ val helper = ProfileHelper(mockk(relaxed = true))
+ val profiles = helper.getEnabledProfiles()
+
+ assertEquals(1, profiles.size)
+ assertEquals("wifi_ssid", profiles[0].conditionType)
+ assertEquals("HomeNet", profiles[0].wifiSsid)
+ }
+
+ @Test
+ fun `getProfilesAsArray reads the wifi SSID`() {
+ // The reader behind the profile list; a broken column read here only shows up on device.
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Home", "interval_ms" to 60000L,
+ "min_update_distance" to 10f, "sync_interval_seconds" to 300,
+ "priority" to 15, "condition_type" to "wifi_ssid",
+ "speed_threshold" to null, "wifi_ssid" to "HomeNet",
+ "deactivation_delay_seconds" to 60, "activation_delay_seconds" to 0,
+ "enabled" to 1, "created_at" to 0
+ )
+ ))
+ every { mockDb.query(any(), any(), any(), any(), any(), any(), any()) } returns cursor
+
+ mockkStatic(Arguments::class)
+ try {
+ val map = mockk<WritableMap>(relaxed = true)
+ every { Arguments.createArray() } returns mockk(relaxed = true)
+ every { Arguments.createMap() } returns map
+
+ ProfileHelper(mockk(relaxed = true)).getProfilesAsArray()
+
+ verify { map.putString("wifiSsid", "HomeNet") }
+ } finally {
+ unmockkStatic(Arguments::class)
+ }
+ }
+
@Test
fun `getEnabledProfiles reads activation delay`() {
val cursor = mockCursorWithProfiles(listOf(
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
index 65feecd6..349b2716 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
@@ -18,6 +18,7 @@ import io.mockk.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
+import com.Colota.sync.NetworkManager
import com.Colota.util.AppLogger
import org.junit.After
@@ -32,6 +33,7 @@ import org.junit.After
class ConditionMonitorTest {
private lateinit var mockContext: Context
+ private lateinit var mockNetworkManager: NetworkManager
private lateinit var mockProfileManager: ProfileManager
private lateinit var mockHandler: Handler
private lateinit var monitor: ConditionMonitor
@@ -39,6 +41,7 @@ class ConditionMonitorTest {
@Before
fun setUp() {
mockContext = mockk(relaxed = true)
+ mockNetworkManager = mockk(relaxed = true)
mockProfileManager = mockk(relaxed = true)
mockHandler = mockk(relaxed = true)
@@ -151,6 +154,83 @@ class ConditionMonitorTest {
verify { monitor["startCarConnectionMonitor"]() }
}
+ // ========================================================================
+ // Wi-Fi condition source
+ // ========================================================================
+
+ @Test
+ fun `start probes the SSID once when a profile watches the network`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_WIFI_SSID)
+ every { mockNetworkManager.isWifiConnected() } returns true
+ every { mockNetworkManager.readSsidOnce(any()) } answers {
+ firstArg<(String) -> Unit>().invoke("HomeNet")
+ }
+
+ monitor.start()
+
+ verify { mockNetworkManager.setWifiStateListener(any()) }
+ verify { mockNetworkManager.readSsidOnce(any()) }
+ verify { mockProfileManager.onWifiStateChanged(true, "HomeNet") }
+ }
+
+ @Test
+ fun `wifi changes re-read the SSID and reach the profile manager`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_WIFI_SSID)
+ // start() stops first (clearing the listener with null), so keep the last registration.
+ var listener: (() -> Unit)? = null
+ every { mockNetworkManager.setWifiStateListener(any()) } answers { listener = firstArg() }
+ every { mockNetworkManager.isWifiConnected() } returns false
+
+ monitor.start()
+ verify { mockProfileManager.onWifiStateChanged(false, "") }
+ assertNotNull(listener)
+
+ every { mockNetworkManager.isWifiConnected() } returns true
+ every { mockNetworkManager.readSsidOnce(any()) } answers {
+ firstArg<(String) -> Unit>().invoke("HomeNet")
+ }
+ listener!!.invoke()
+
+ verify { mockProfileManager.onWifiStateChanged(true, "HomeNet") }
+ }
+
+ @Test
+ fun `the any-wifi condition is pushed without touching the SSID`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_WIFI_ANY)
+ every { mockNetworkManager.isWifiConnected() } returns true
+
+ monitor.start()
+
+ verify { mockProfileManager.onWifiStateChanged(true, "") }
+ verify(exactly = 0) { mockNetworkManager.readSsidOnce(any()) }
+ }
+
+ @Test
+ fun `start does not register the wifi listener without a wifi condition`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+
+ monitor.start()
+
+ // stop() clears the listener first, so one call total and it is a clear, not a registration.
+ verify(exactly = 1) { mockNetworkManager.setWifiStateListener(isNull()) }
+ verify(exactly = 0) { mockNetworkManager.setWifiStateListener(isNull(inverse = true)) }
+ }
+
+ @Test
+ fun `stop clears the wifi listener`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_WIFI_SSID)
+
+ monitor.start()
+ monitor.stop()
+
+ // Once from start()'s stop-first and once from the explicit stop().
+ verify(exactly = 2) { mockNetworkManager.setWifiStateListener(isNull()) }
+ }
+
// ========================================================================
// Charging receiver — power events
// ========================================================================
@@ -302,6 +382,7 @@ class ConditionMonitorTest {
val spy = spyk(raw, recordPrivateCalls = true)
setField(spy, "context", mockContext)
+ setField(spy, "networkManager", mockNetworkManager)
setField(spy, "profileManager", mockProfileManager)
setField(spy, "mainHandler", mockHandler)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index 5ab8d3a5..20bbbab9 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -798,15 +798,19 @@ class LocationForegroundServiceTest {
}
@Test
- fun `only the wifi_ssid condition turns SSID tracking on`() {
+ fun `SSID tracking follows only the sync wifi_ssid condition`() {
// Reading the SSID is attributed as location access, so it must follow the condition needing it.
setField("config", ServiceConfig(endpoint = "https://example.com", syncCondition = "wifi_ssid"))
invokePushConfigToSyncManager()
- verify { networkManager.setSsidTracking(true) }
+ verify(exactly = 1) { networkManager.setSsidTracking(true) }
setField("config", ServiceConfig(endpoint = "https://example.com", syncCondition = "any"))
invokePushConfigToSyncManager()
- verify { networkManager.setSsidTracking(false) }
+ verify(exactly = 1) { networkManager.setSsidTracking(false) }
+
+ setField("config", ServiceConfig(endpoint = "https://example.com", syncCondition = "wifi_ssid"))
+ invokePushConfigToSyncManager()
+ verify(exactly = 2) { networkManager.setSsidTracking(true) }
}
@Test
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
index 1e996fe0..de2af937 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt
@@ -125,6 +125,44 @@ class ProfileManagerTest {
activationDelaySeconds = activationDelay
)
+ private fun wifiAnyProfile(
+ id: Int = 5,
+ priority: Int = 10,
+ deactivationDelay: Int = 60,
+ activationDelay: Int = 0
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = "Wi-Fi",
+ intervalMs = 30000,
+ minUpdateDistance = 5f,
+ syncIntervalSeconds = 0,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_WIFI_ANY,
+ speedThreshold = null,
+ deactivationDelaySeconds = deactivationDelay,
+ activationDelaySeconds = activationDelay
+ )
+
+ private fun wifiSsidProfile(
+ id: Int = 6,
+ ssid: String = "HomeNet",
+ priority: Int = 15,
+ deactivationDelay: Int = 60,
+ activationDelay: Int = 0
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = "Home",
+ intervalMs = 60000,
+ minUpdateDistance = 10f,
+ syncIntervalSeconds = 300,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_WIFI_SSID,
+ speedThreshold = null,
+ wifiSsid = ssid,
+ deactivationDelaySeconds = deactivationDelay,
+ activationDelaySeconds = activationDelay
+ )
+
private fun mockLocation(speed: Float, hasSpeed: Boolean = true, timeMs: Long = t0): Location {
return mockk {
every { [email protected] } returns speed
@@ -220,6 +258,117 @@ class ProfileManagerTest {
assertEquals(3000L, switchedInterval)
}
+ // --- Wi-Fi conditions ---
+
+ @Test
+ fun `activates wifi any profile while the default network is wifi`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiAnyProfile())
+
+ val manager = createManager()
+ manager.onWifiStateChanged(connected = true, ssid = "")
+
+ assertEquals("Wi-Fi", switchedProfileName)
+ assertEquals(30000L, switchedInterval)
+ }
+
+ @Test
+ fun `does not activate wifi any profile without wifi`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiAnyProfile())
+
+ val manager = createManager()
+ manager.onWifiStateChanged(connected = false, ssid = "")
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `activates wifi ssid profile on a case-insensitive match`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(ssid = "HomeNet"))
+
+ val manager = createManager()
+ manager.onWifiStateChanged(connected = true, ssid = "homenet")
+
+ assertEquals("Home", switchedProfileName)
+ assertEquals(60000L, switchedInterval)
+ }
+
+ @Test
+ fun `does not activate wifi ssid profile on another network or before the SSID arrives`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(ssid = "HomeNet"))
+
+ val manager = createManager()
+ manager.onWifiStateChanged(connected = true, ssid = "WorkNet")
+ assertNull(switchedProfileName)
+
+ manager.onWifiStateChanged(connected = true, ssid = "")
+ assertNull(switchedProfileName)
+
+ manager.onWifiStateChanged(connected = false, ssid = "HomeNet")
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `a profile without an SSID never matches`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(ssid = ""))
+
+ val manager = createManager()
+ manager.onWifiStateChanged(connected = true, ssid = "")
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `deactivates the wifi profile after its deactivation delay when the network drops`() = testScope.runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(deactivationDelay = 30))
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ manager.onWifiStateChanged(connected = true, ssid = "HomeNet")
+ assertEquals("Home", switchedProfileName)
+
+ manager.onWifiStateChanged(connected = false, ssid = "")
+ assertEquals("Home", switchedProfileName)
+
+ advanceTimeBy(31_000)
+
+ assertNull(switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `an active named-network profile deactivates when the SSID goes blank`() = testScope.runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(deactivationDelay = 0))
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onWifiStateChanged(connected = true, ssid = "HomeNet")
+ assertEquals("Home", switchedProfileName)
+
+ // A blank name means Location off or an unreadable network, so the condition cannot hold.
+ manager.onWifiStateChanged(connected = true, ssid = "")
+ advanceTimeBy(1_000)
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `an active named-network profile drops when another network is reported`() = testScope.runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(wifiSsidProfile(deactivationDelay = 0))
+
+ val manager = createManager()
+ manager.defaultInterval = 5000L
+ manager.onWifiStateChanged(connected = true, ssid = "HomeNet")
+ assertEquals("Home", switchedProfileName)
+
+ manager.onWifiStateChanged(connected = true, ssid = "WorkNet")
+ advanceTimeBy(1_000)
+
+ assertNull(switchedProfileName)
+ }
+
// --- Speed conditions ---
@Test
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 18129890..e3c37316 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
@@ -3,6 +3,7 @@ package com.Colota.sync
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
+import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import org.json.JSONObject
@@ -26,10 +27,17 @@ class NetworkManagerTest {
every { AppLogger.i(any(), any()) } just Runs
every { AppLogger.w(any(), any()) } just Runs
every { AppLogger.e(any(), any(), any()) } just Runs
+
+ // With returnDefaultValues the mocked Builder chain returns null and every NetworkManager
+ // construction would NPE. The real request is irrelevant to these tests.
+ mockkConstructor(NetworkRequest.Builder::class)
+ every { anyConstructed<NetworkRequest.Builder>().addTransportType(any()) } returns mockk(relaxed = true)
+ every { anyConstructed<NetworkRequest.Builder>().build() } returns mockk(relaxed = true)
}
@After
fun tearDown() {
+ unmockkConstructor(NetworkRequest.Builder::class)
unmockkObject(AppLogger)
}
@@ -89,10 +97,12 @@ class NetworkManagerTest {
slot.captured.onCapabilitiesChanged(mockk(relaxed = true), mockk(relaxed = true))
assertFalse(manager.isConnectedToSsid("HomeNet"))
+ assertEquals("", manager.currentSsid)
manager.setSsidTracking(true)
slot.captured.onCapabilitiesChanged(mockk(relaxed = true), mockk(relaxed = true))
assertTrue(manager.isConnectedToSsid("HomeNet"))
+ assertEquals("HomeNet", manager.currentSsid)
}
@Test
@@ -109,6 +119,112 @@ class NetworkManagerTest {
assertTrue(manager.isVpnConnected())
}
+ @Test
+ fun `the wifi transport callback notifies the listener on availability and loss`() {
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ val slot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerNetworkCallback(any<NetworkRequest>(), capture(slot)) } just Runs
+ val manager = newManagerWith(cm)
+ var changes = 0
+ manager.setWifiStateListener { changes++ }
+
+ slot.captured.onAvailable(mockk(relaxed = true))
+
+ assertTrue(manager.isWifiConnected())
+ assertEquals(1, changes)
+
+ slot.captured.onLost(mockk(relaxed = true))
+
+ assertFalse(manager.isWifiConnected())
+ assertEquals(2, changes)
+ }
+
+ @Test
+ fun `identical capability deliveries do not notify twice`() {
+ // Bandwidth and validation updates arrive without any transport or SSID change; each one
+ // used to run a full profile evaluation.
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ val slot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerDefaultNetworkCallback(capture(slot)) } just Runs
+ val manager = newManagerWith(cm)
+ var changes = 0
+ manager.setWifiStateListener { changes++ }
+
+ val caps = mockk<NetworkCapabilities>(relaxed = true)
+ every { caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) } returns true
+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), caps)
+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), caps)
+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), caps)
+
+ assertEquals(1, changes)
+ }
+
+ @Test
+ fun `a VPN default network does not hide an available Wi-Fi network`() {
+ // The VPN network reports the underlying transports on Android 14+, but the app's Wi-Fi
+ // transport callback sees the Wi-Fi network regardless of which network is the default.
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ val defaultSlot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerDefaultNetworkCallback(capture(defaultSlot)) } just Runs
+ val wifiSlot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerNetworkCallback(any<NetworkRequest>(), capture(wifiSlot)) } just Runs
+ val manager = newManagerWith(cm)
+ var changes = 0
+ manager.setWifiStateListener { changes++ }
+
+ wifiSlot.captured.onAvailable(mockk(relaxed = true))
+
+ assertTrue(manager.isWifiConnected())
+ assertEquals(1, changes)
+
+ val vpnCaps = mockk<NetworkCapabilities>(relaxed = true)
+ every { vpnCaps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) } returns true
+ every { vpnCaps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) } returns true
+ defaultSlot.captured.onCapabilitiesChanged(mockk(relaxed = true), vpnCaps)
+
+ assertTrue(manager.isVpnConnected())
+ assertTrue(manager.isWifiConnected())
+ assertEquals(2, changes)
+ }
+
+ @Test
+ fun `the unknown SSID placeholder reads as no name`() {
+ // Android returns "<unknown ssid>" without location permission or with Location off; that
+ // must not be saved as a network name or matched against one.
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ val slot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerDefaultNetworkCallback(capture(slot)) } just Runs
+ val info = mockk<WifiInfo>(relaxed = true)
+ every { info.ssid } returns "\"<unknown ssid>\""
+ val wifi = mockk<WifiManager>(relaxed = true)
+ every { wifi.connectionInfo } returns info
+ val ctx = mockk<Context>(relaxed = true)
+ every { ctx.getSystemService(Context.CONNECTIVITY_SERVICE) } returns cm
+ every { ctx.getSystemService(Context.WIFI_SERVICE) } returns wifi
+ val manager = NetworkManager(ctx)
+
+ manager.setSsidTracking(true)
+ slot.captured.onCapabilitiesChanged(mockk(relaxed = true), mockk(relaxed = true))
+
+ assertEquals("", manager.currentSsid)
+ assertFalse(manager.isConnectedToSsid("<unknown ssid>"))
+ }
+
+ @Test
+ fun `clearing the listener stops notifications`() {
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ val slot = slot<ConnectivityManager.NetworkCallback>()
+ every { cm.registerNetworkCallback(any<NetworkRequest>(), capture(slot)) } just Runs
+ val manager = newManagerWith(cm)
+ var changes = 0
+ manager.setWifiStateListener { changes++ }
+ manager.setWifiStateListener(null)
+
+ slot.captured.onAvailable(mockk(relaxed = true))
+
+ assertEquals(0, changes)
+ }
+
// --- buildQueryString ---
@Test
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index d2de5715..202800b8 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -5,7 +5,7 @@
import type { ProfileConditionType } from "../types/global"
import type { TranslationKey } from "../i18n/options"
-import { Zap, Car, ArrowUp, ArrowDown, Pause } from "lucide-react-native"
+import { Zap, Car, ArrowUp, ArrowDown, Pause, Wifi } from "lucide-react-native"
// Timing
export const AUTOSAVE_DEBOUNCE_MS = 1500
@@ -98,6 +98,8 @@ export const PROFILE_CONDITIONS: {
[
["charging", Zap],
["android_auto", Car],
+ ["wifi_any", Wifi],
+ ["wifi_ssid", Wifi],
["speed_above", ArrowUp],
["speed_below", ArrowDown],
["stationary", Pause]
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index 469b10d3..ca2b990c 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -269,6 +269,14 @@
"condition.stationary.clause": "when stationary",
"condition.stationary.description": "Phone stays still for the activation delay",
"condition.stationary.list": "When stationary",
+ "condition.wifi_any": "Wi-Fi",
+ "condition.wifi_any.clause": "on Wi-Fi",
+ "condition.wifi_any.description": "Phone is on a Wi-Fi network",
+ "condition.wifi_any.list": "On Wi-Fi",
+ "condition.wifi_ssid": "Wi-Fi network",
+ "condition.wifi_ssid.clause": "on Wi-Fi \"{{network}}\"",
+ "condition.wifi_ssid.description": "Connected to the network you named",
+ "condition.wifi_ssid.list": "On Wi-Fi \"{{network}}\"",
"connection.endpoint": "Server endpoint",
"connection.endpoint.helper": "https for public hosts, http only for private hosts.",
"connection.endpoint.key": "This address carries a key. It is stored with settings, not encrypted, and included in setup links. Use a header where the server allows it.",
@@ -754,6 +762,9 @@
"profileEditor.sync.hint": "Replaces the {{interval}} from Tracking & sync while this profile is active · shorter means more wake-ups",
"profileEditor.titleEdit": "Edit profile",
"profileEditor.titleNew": "New profile",
+ "profileEditor.wifi.empty": "Name a network or the profile can't match",
+ "profileEditor.wifi.hint": "Matches while connected to this network. Reading network names counts as location access.",
+ "profileEditor.wifi.ssid": "Network name",
"profiles.empty.hint": "A profile changes how you track while a condition holds, such as charging or driving",
"profiles.empty.title": "No profiles yet",
"profiles.intro": "Checked top to bottom while tracking runs. The first profile whose condition holds replaces the Tracking & sync values.",
diff --git a/apps/mobile/src/i18n/locales/es.json b/apps/mobile/src/i18n/locales/es.json
index a781b5a5..d406da06 100644
--- a/apps/mobile/src/i18n/locales/es.json
+++ b/apps/mobile/src/i18n/locales/es.json
@@ -269,6 +269,14 @@
"condition.stationary.clause": "en reposo",
"condition.stationary.description": "El teléfono permanece quieto durante el retraso de activación",
"condition.stationary.list": "En reposo",
+ "condition.wifi_any": "Wi-Fi",
+ "condition.wifi_any.clause": "con Wi-Fi",
+ "condition.wifi_any.description": "El teléfono está en una red Wi-Fi",
+ "condition.wifi_any.list": "Con Wi-Fi",
+ "condition.wifi_ssid": "Red Wi-Fi",
+ "condition.wifi_ssid.clause": "en la red Wi-Fi \"{{network}}\"",
+ "condition.wifi_ssid.description": "Conectado a la red que indiques",
+ "condition.wifi_ssid.list": "En la red Wi-Fi \"{{network}}\"",
"connection.endpoint": "Endpoint del servidor",
"connection.endpoint.helper": "https para hosts públicos, http solo para hosts privados.",
"connection.endpoint.key": "Esta dirección contiene una clave. Se guarda junto con la configuración, sin cifrar, y se incluye en los enlaces de configuración. Usa un encabezado donde el servidor lo permita.",
@@ -754,6 +762,9 @@
"profileEditor.sync.hint": "Reemplaza el {{interval}} de Seguimiento y sincronización mientras este perfil esté activo · más corto significa más activaciones",
"profileEditor.titleEdit": "Editar perfil",
"profileEditor.titleNew": "Perfil nuevo",
+ "profileEditor.wifi.empty": "Indica una red o el perfil no podrá aplicarse",
+ "profileEditor.wifi.hint": "Se aplica mientras estés conectado a esta red. Leer nombres de redes cuenta como acceso a la ubicación.",
+ "profileEditor.wifi.ssid": "Nombre de la red",
"profiles.empty.hint": "Un perfil cambia cómo registras mientras se cumple una condición, como estar cargando o conduciendo",
"profiles.empty.title": "Aún no hay perfiles",
"profiles.intro": "Se evalúan de arriba abajo mientras el seguimiento está activo. El primer perfil cuya condición se cumple reemplaza los valores de Seguimiento y sincronización.",
diff --git a/apps/mobile/src/i18n/options.ts b/apps/mobile/src/i18n/options.ts
index 3406d7ed..3c26062f 100644
--- a/apps/mobile/src/i18n/options.ts
+++ b/apps/mobile/src/i18n/options.ts
@@ -30,8 +30,8 @@ export function resolveLanguage(tag: string | undefined): SupportedLanguage {
/** Side-effect free so `jest.setup.js` can share it. Inline resources keep `init()` synchronous. */
export const I18N_OPTIONS = {
fallbackLng: FALLBACK_LANGUAGE,
- resources: {
- en: { translation: en },
+ resources: {
+ en: { translation: en },
es: { translation: es },
zh: { translation: zh }
},
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index 59c49f63..dc7389f1 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -4,11 +4,12 @@
*/
import React, { useState, useEffect, useLayoutEffect, useCallback } from "react"
-import { View, Text, StyleSheet, ScrollView } from "react-native"
+import { View, Text, StyleSheet, ScrollView, AppState } from "react-native"
import { useTheme } from "../hooks/useTheme"
import { useTracking } from "../contexts/TrackingProvider"
import { useTimeout } from "../hooks/useTimeout"
import { ProfileService } from "../services/ProfileService"
+import NativeLocationService from "../services/NativeLocationService"
import { showAlert, showConfirm } from "../services/modalService"
import { TrackingProfile, ProfileConditionType } from "../types/global"
import { fontSizes, fonts, lineHeights } from "../styles/typography"
@@ -70,17 +71,36 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
enabled: true
})
const [saving, setSaving] = useState(false)
+ const [currentSsid, setCurrentSsid] = useState("")
const [text, setText] = useState({
interval: String(settings.interval),
distance: String(metersToInput(settings.distance)),
speed: String(DEFAULT_SPEED_INPUT),
priority: String(DEFAULT_PRIORITY),
+ ssid: "",
activationDelay: String(defaultProfileDelays("charging").activationDelay),
deactivationDelay: String(defaultProfileDelays("charging").deactivationDelay)
})
const [note, setNote] = useState<{ key: NumericKey; text: string } | null>(null)
const noteTimer = useTimeout()
+ // Only fetched while the SSID field is open; the fallback keeps the offer button hidden.
+ useEffect(() => {
+ if (profile.condition.type !== "wifi_ssid") return
+
+ const fetchSsid = () =>
+ NativeLocationService.getCurrentSsid()
+ .then(setCurrentSsid)
+ .catch(() => setCurrentSsid(""))
+ fetchSsid()
+
+ // Connecting to a network in settings and coming back should reveal the offer.
+ const sub = AppState.addEventListener("change", (state) => {
+ if (state === "active") fetchSsid()
+ })
+ return () => sub.remove()
+ }, [profile.condition.type])
+
useLayoutEffect(() => {
navigation.setOptions({ headerTitle: isEditing ? t("profileEditor.titleEdit") : t("profileEditor.titleNew") })
}, [navigation, isEditing, t])
@@ -109,6 +129,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
existing.condition.speedThreshold ? speedToInput(existing.condition.speedThreshold) : DEFAULT_SPEED_INPUT
),
priority: String(existing.priority),
+ ssid: existing.condition.ssid ?? "",
activationDelay: String(existing.activationDelay),
deactivationDelay: String(existing.deactivationDelay)
})
@@ -123,6 +144,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const type = profile.condition.type
const isSpeed = isSpeedType(type)
const isStationary = type === "stationary"
+ const isWifiSsid = type === "wifi_ssid"
const conditionLabel = t(conditionOf(profile).labelKey)
const store = useCallback((key: NumericKey, value: number) => {
@@ -157,6 +179,13 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const errorOf = (key: NumericKey) => wholeNumberError(text[key], minOf(key), unitOf(key))
const noteOf = (key: NumericKey) => (note?.key === key ? note.text : undefined)
+ const handleSsid = (value: string) => {
+ setText((prev) => ({ ...prev, ssid: value }))
+ setProfile((prev) => ({ ...prev, condition: { ...prev.condition, ssid: value } }))
+ }
+ const ssidError = isWifiSsid && text.ssid.trim() === "" ? t("profileEditor.wifi.empty") : undefined
+ const offerCurrentSsid = currentSsid !== "" && currentSsid.trim().toLowerCase() !== text.ssid.trim().toLowerCase()
+
const priorityError =
text.priority !== "" && parseWholeNumber(text.priority) === null ? t("validation.wholeNumber") : undefined
const handlePriority = (value: string) => {
@@ -181,19 +210,27 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const speedThreshold = isSpeedType(next)
? (profile.condition.speedThreshold ?? inputToSpeed(parseWholeNumber(text.speed) ?? DEFAULT_SPEED_INPUT))
: undefined
+ // Like the speed threshold, the typed network survives a switch away and re-seeds on the way
+ // back; the stored column is cleared on save because the condition object drops it.
+ const ssid = next === "wifi_ssid" ? (profile.condition.ssid ?? text.ssid) : undefined
setProfile((prev) => ({
...prev,
...delays,
// A distance filter is ignored for a stationary profile; store 0 so UI, DB and runtime agree.
distance: next === "stationary" ? 0 : prev.distance,
- condition: { type: next, ...(speedThreshold !== undefined ? { speedThreshold } : {}) }
+ condition: {
+ type: next,
+ ...(speedThreshold !== undefined ? { speedThreshold } : {}),
+ ...(ssid !== undefined ? { ssid } : {})
+ }
}))
setText((prev) => ({
...prev,
distance: next === "stationary" ? "0" : prev.distance,
activationDelay: String(delays.activationDelay),
deactivationDelay: String(delays.deactivationDelay),
- speed: speedThreshold !== undefined ? String(speedToInput(speedThreshold)) : prev.speed
+ speed: speedThreshold !== undefined ? String(speedToInput(speedThreshold)) : prev.speed,
+ ssid: ssid ?? prev.ssid
}))
}
@@ -220,11 +257,16 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
!!errorOf("interval") ||
(!isStationary && !!errorOf("distance")) ||
(isSpeed && !!errorOf("speed")) ||
+ !!ssidError ||
!!errorOf("activationDelay") ||
(!isStationary && !!errorOf("deactivationDelay"))
const handleSave = useCallback(async () => {
- const next: Draft = { ...profile, name: profile.name.trim() || conditionLabel }
+ const next: Draft = {
+ ...profile,
+ name: profile.name.trim() || conditionLabel,
+ condition: isWifiSsid ? { ...profile.condition, ssid: text.ssid.trim() } : profile.condition
+ }
setSaving(true)
try {
if (isEditing && profileId) {
@@ -239,7 +281,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
} finally {
setSaving(false)
}
- }, [profile, conditionLabel, isEditing, profileId, navigation, t])
+ }, [profile, conditionLabel, isEditing, isWifiSsid, text.ssid, profileId, navigation, t])
const syncDefault = syncIntervalLabel(settings.syncInterval)
@@ -286,6 +328,31 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
/>
</View>
)}
+ {opt.type === "wifi_ssid" && type === opt.type && (
+ <View style={styles.reveal}>
+ <TextField
+ label={t("profileEditor.wifi.ssid")}
+ testID="wifi-ssid-input"
+ mono
+ value={text.ssid}
+ onChangeText={handleSsid}
+ placeholder={t("trackingSync.ssid.placeholder")}
+ autoCapitalize="none"
+ autoCorrect={false}
+ error={ssidError}
+ />
+ <FieldMessage>{t("profileEditor.wifi.hint")}</FieldMessage>
+ {offerCurrentSsid && (
+ <Button
+ variant="secondary"
+ title={t("trackingSync.ssid.use", { ssid: currentSsid })}
+ testID="wifi-ssid-use"
+ onPress={() => handleSsid(currentSsid)}
+ style={styles.ssidUse}
+ />
+ )}
+ </View>
+ )}
</React.Fragment>
))}
</View>
@@ -443,6 +510,7 @@ const styles = StyleSheet.create({
cardTop: { paddingTop: space.lg },
// The row above already pays space.lg below it; the field's own bottom margin is the card's tail.
reveal: { paddingLeft: size.iconColumn, marginTop: -space.xs },
+ ssidUse: { marginTop: space.sm, alignSelf: "flex-start" },
field: { paddingBottom: space.lg },
numInput: { width: size.numericField },
figure: { fontSize: fontSizes.input, ...fonts.medium, fontVariant: ["tabular-nums"] },
diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
index af09223e..7da0d536 100644
--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
@@ -15,6 +15,18 @@ const mockProfiles: TrackingProfile[] = [
activationDelay: 12,
deactivationDelay: 30,
enabled: true
+ },
+ {
+ id: 2,
+ name: "Home",
+ interval: 60,
+ distance: 10,
+ syncInterval: 300,
+ priority: 15,
+ condition: { type: "wifi_ssid", ssid: "HomeNet" },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true
}
]
@@ -32,6 +44,12 @@ jest.mock("../../services/ProfileService", () => ({
}
}))
+const mockGetCurrentSsid = jest.fn().mockResolvedValue("HomeNet")
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: { getCurrentSsid: () => mockGetCurrentSsid() }
+}))
+
const mockShowAlert = jest.fn()
const mockShowConfirm = jest.fn()
jest.mock("../../services/modalService", () => ({
@@ -185,8 +203,11 @@ describe("ProfileEditorScreen", () => {
expect(getByText("Android Auto")).toBeTruthy()
expect(getByText("Speed above")).toBeTruthy()
+ expect(getByText("Wi-Fi")).toBeTruthy()
+ expect(getByText("Wi-Fi network")).toBeTruthy()
expect(getByText("Phone is plugged in")).toBeTruthy()
expect(getByText("Average speed is above the speed you set")).toBeTruthy()
+ expect(getByText("Phone is on a Wi-Fi network")).toBeTruthy()
expect(getByTestId("condition-charging").props.accessibilityState.checked).toBe(true)
})
@@ -213,6 +234,76 @@ describe("ProfileEditorScreen", () => {
})
})
+ describe("wi-fi network", () => {
+ it("reveals the network field under a named-network condition and blocks Save until it is filled", async () => {
+ const { getByTestId, queryByTestId } = renderNew()
+ expect(queryByTestId("wifi-ssid-input")).toBeNull()
+
+ fireEvent.press(getByTestId("condition-wifi_ssid"))
+ // Let the current-SSID offer settle inside act before asserting.
+ await waitFor(() => expect(mockGetCurrentSsid).toHaveBeenCalled())
+
+ expect(getByTestId("wifi-ssid-input").props.value).toBe("")
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ "On Wi-Fi, track every 5 s, any movement and sync each fix."
+ )
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(true)
+
+ fireEvent.changeText(getByTestId("wifi-ssid-input"), "HomeNet")
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ 'On Wi-Fi "HomeNet", track every 5 s, any movement and sync each fix.'
+ )
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
+ })
+
+ it("offers the network the phone is on and saves the trimmed name", async () => {
+ const { getByTestId } = renderNew()
+ fireEvent.press(getByTestId("condition-wifi_ssid"))
+
+ const use = await waitFor(() => getByTestId("wifi-ssid-use"))
+ fireEvent.press(use)
+ expect(getByTestId("wifi-ssid-input").props.value).toBe("HomeNet")
+
+ fireEvent.changeText(getByTestId("wifi-ssid-input"), " HomeNet ")
+ fireEvent.press(getByTestId("save-profile-btn"))
+
+ await waitFor(() =>
+ expect(mockCreateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ condition: { type: "wifi_ssid", ssid: "HomeNet" } })
+ )
+ )
+ })
+
+ it("keeps the typed network across a condition round trip", async () => {
+ const { findByTestId, getByTestId } = renderEdit(2)
+ expect((await findByTestId("wifi-ssid-input")).props.value).toBe("HomeNet")
+ await waitFor(() => expect(mockGetCurrentSsid).toHaveBeenCalled())
+
+ fireEvent.press(getByTestId("condition-wifi_any"))
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ "On Wi-Fi, track every 1 min after 10 m and sync every 5 min."
+ )
+
+ fireEvent.press(getByTestId("condition-wifi_ssid"))
+ expect(getByTestId("wifi-ssid-input").props.value).toBe("HomeNet")
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
+ })
+
+ it("clears the stored network when saved under another condition", async () => {
+ const { findByTestId, getByTestId } = renderEdit(2)
+ await findByTestId("wifi-ssid-input")
+
+ fireEvent.press(getByTestId("condition-wifi_any"))
+ fireEvent.press(getByTestId("save-profile-btn"))
+
+ await waitFor(() =>
+ expect(mockUpdateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 2, condition: { type: "wifi_any" } })
+ )
+ )
+ })
+ })
+
describe("stationary", () => {
it("blocks the movement threshold with the reason instead of hiding it, and drops the deactivation delay", () => {
const { getByTestId, getByText, queryByTestId } = renderNew()
diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
index ccd8cd41..6058443f 100644
--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
@@ -670,6 +670,32 @@ describe("SetupImportScreen", () => {
expect(getByText("Invalid configuration")).toBeTruthy()
})
+ it("rejects a named-network profile without a network name", () => {
+ const config = { profiles: [{ ...validProfile, condition: { type: "wifi_ssid" } }] }
+ const { getByText } = renderScreen(encode(config))
+ expect(getByText("Invalid configuration")).toBeTruthy()
+ })
+
+ it("imports a named-network profile with its SSID, trimmed", async () => {
+ const config = {
+ profiles: [{ ...validProfile, condition: { type: "wifi_ssid", ssid: " HomeNet " } }]
+ }
+ const { getByText } = renderScreen(encode(config))
+
+ fireEvent.press(getByText("Apply configuration"))
+
+ await waitFor(() => expect(mockCreateProfile).toHaveBeenCalledTimes(1))
+ expect(mockCreateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ condition: { type: "wifi_ssid", ssid: "HomeNet" } })
+ )
+ })
+
+ it("accepts the any-network condition without extra fields", () => {
+ const config = { profiles: [{ ...validProfile, condition: { type: "wifi_any" } }] }
+ const { getByText } = renderScreen(encode(config))
+ expect(getByText("Driving")).toBeTruthy()
+ })
+
it("accepts a non-speed condition without speedThreshold", () => {
const config = {
profiles: [{ ...validProfile, condition: { type: "charging" } }]
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 7ef49a8f..edff23a3 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -482,7 +482,8 @@ class NativeLocationService {
priority: p.priority,
condition: {
type: p.conditionType,
- ...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {})
+ ...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {}),
+ ...(p.wifiSsid != null ? { ssid: p.wifiSsid } : {})
},
activationDelay: p.activationDelaySeconds,
deactivationDelay: p.deactivationDelaySeconds,
@@ -506,6 +507,7 @@ class NativeLocationService {
priority: profile.priority,
conditionType: profile.condition.type,
speedThreshold: profile.condition.speedThreshold ?? null,
+ wifiSsid: profile.condition.ssid ?? null,
deactivationDelaySeconds: profile.deactivationDelay,
activationDelaySeconds: profile.activationDelay
})
@@ -527,6 +529,7 @@ class NativeLocationService {
if (update.condition !== undefined) {
config.conditionType = update.condition.type
config.speedThreshold = update.condition.speedThreshold ?? null
+ config.wifiSsid = update.condition.ssid ?? null
}
if (update.deactivationDelay !== undefined) config.deactivationDelaySeconds = update.deactivationDelay
if (update.activationDelay !== undefined) config.activationDelaySeconds = update.activationDelay
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index f9c4b2da..298c188e 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -84,7 +84,11 @@ jest.mock("react-native", () => ({
isNetworkAvailable: jest.fn().mockResolvedValue(true),
isValidEndpointProtocol: jest.fn().mockResolvedValue(true),
isPrivateEndpoint: jest.fn().mockResolvedValue(false),
- getActiveProfile: jest.fn().mockResolvedValue(null)
+ getActiveProfile: jest.fn().mockResolvedValue(null),
+ getProfiles: jest.fn().mockResolvedValue([]),
+ createProfile: jest.fn().mockResolvedValue(3),
+ updateProfile: jest.fn().mockResolvedValue(true),
+ deleteProfile: jest.fn().mockResolvedValue(true)
},
BuildConfigModule: {
VERSION_NAME: "1.0.0",
@@ -446,6 +450,82 @@ describe("NativeLocationService", () => {
})
})
+ describe("tracking profiles", () => {
+ it("maps rows to the condition shape the editor uses, Wi-Fi SSID included", async () => {
+ nativeMock.getProfiles.mockResolvedValueOnce([
+ {
+ id: 1,
+ name: "Home",
+ intervalMs: 60000,
+ minUpdateDistance: 10,
+ syncIntervalSeconds: 300,
+ priority: 15,
+ conditionType: "wifi_ssid",
+ speedThreshold: null,
+ wifiSsid: "HomeNet",
+ deactivationDelaySeconds: 60,
+ activationDelaySeconds: 0,
+ enabled: true,
+ createdAt: 1700000000
+ },
+ {
+ id: 2,
+ name: "Speed",
+ intervalMs: 2000,
+ minUpdateDistance: 5,
+ syncIntervalSeconds: 0,
+ priority: 10,
+ conditionType: "speed_above",
+ speedThreshold: 13.89,
+ wifiSsid: null,
+ deactivationDelaySeconds: 60,
+ activationDelaySeconds: 0,
+ enabled: true,
+ createdAt: 1700000000
+ }
+ ])
+
+ const profiles = await NativeLocationService.getProfiles()
+
+ expect(profiles[0].condition).toEqual({ type: "wifi_ssid", ssid: "HomeNet" })
+ expect(profiles[0].interval).toBe(60)
+ expect(profiles[1].condition).toEqual({ type: "speed_above", speedThreshold: 13.89 })
+ expect(profiles[1].condition).not.toHaveProperty("ssid")
+ })
+
+ it("sends the SSID on create", async () => {
+ await NativeLocationService.createProfile({
+ name: "Home",
+ interval: 60,
+ distance: 10,
+ syncInterval: 300,
+ priority: 15,
+ condition: { type: "wifi_ssid", ssid: "HomeNet" },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true
+ })
+
+ expect(nativeMock.createProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ conditionType: "wifi_ssid", wifiSsid: "HomeNet" })
+ )
+ })
+
+ it("clears the stored SSID when the condition no longer names one", async () => {
+ await NativeLocationService.updateProfile({ id: 1, condition: { type: "charging" } })
+
+ expect(nativeMock.updateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ conditionType: "charging", wifiSsid: null })
+ )
+ })
+
+ it("leaves the SSID alone when the update does not carry a condition", async () => {
+ await NativeLocationService.updateProfile({ id: 1, enabled: false })
+
+ expect(nativeMock.updateProfile.mock.calls[0][0]).not.toHaveProperty("wifiSsid")
+ })
+ })
+
describe("deleteLocationsByIds", () => {
it("passes the ids to the native module", async () => {
const deleted = await NativeLocationService.deleteLocationsByIds([12, 34])
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index ef0fa755..84606daa 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -384,12 +384,15 @@ export const DEFAULT_AUTH_CONFIG: AuthConfig = {
// TRACKING PROFILES
// ============================================================================
-export type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary"
+export type ProfileConditionType =
+ "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary" | "wifi_any" | "wifi_ssid"
export interface ProfileCondition {
type: ProfileConditionType
/** Speed threshold in m/s (only for speed_above / speed_below conditions) */
speedThreshold?: number
+ /** Wi-Fi network name in the user's own casing (only for wifi_ssid conditions) */
+ ssid?: string
}
export interface TrackingProfile {
diff --git a/apps/mobile/src/utils/__tests__/profileRow.test.ts b/apps/mobile/src/utils/__tests__/profileRow.test.ts
index 683a34e0..051ce9f6 100644
--- a/apps/mobile/src/utils/__tests__/profileRow.test.ts
+++ b/apps/mobile/src/utils/__tests__/profileRow.test.ts
@@ -61,6 +61,21 @@ const car = profile({
syncInterval: 300,
condition: { type: "android_auto" }
})
+const home = profile({
+ id: 5,
+ name: "Home",
+ interval: 60,
+ distance: 10,
+ syncInterval: 300,
+ condition: { type: "wifi_ssid", ssid: "HomeNet" }
+})
+const wifi = profile({
+ id: 6,
+ name: "Wi-Fi",
+ interval: 30,
+ distance: 5,
+ condition: { type: "wifi_any" }
+})
const settings = { interval: 30, distance: 2, syncInterval: 300, isOfflineMode: false }
describe("profileRowSub", () => {
@@ -68,6 +83,8 @@ describe("profileRowSub", () => {
expect(profileRowSub(commute, false, false)).toBe("When charging · Every 5 s, any movement · syncs each fix")
expect(profileRowSub(driving, false, false)).toBe("Speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min")
expect(profileRowSub(car, false, false)).toBe("On Android Auto · Every 10 s after 5 m · syncs every 5 min")
+ expect(profileRowSub(home, false, false)).toBe('On Wi-Fi "HomeNet" · Every 1 min after 10 m · syncs every 5 min')
+ expect(profileRowSub(wifi, false, false)).toBe("On Wi-Fi · Every 30 s after 5 m · syncs each fix")
})
it("opens with Active and lower-cases the condition for the row in force", () => {
@@ -77,6 +94,9 @@ describe("profileRowSub", () => {
expect(profileRowSub(driving, true, false)).toBe(
"Active · speed above 50 km/h · Every 2 s after 10 m · syncs every 1 min"
)
+ expect(profileRowSub(home, true, false)).toBe(
+ 'Active · on Wi-Fi "HomeNet" · Every 1 min after 10 m · syncs every 5 min'
+ )
})
it("takes the in-sentence form from its own key, so a language that capitalises nouns keeps them", async () => {
@@ -110,6 +130,12 @@ describe("profileRowSub", () => {
expect(profileRowSub(driving, false, false)).toBe("Speed above 31 mph · Every 2 s after 33 ft · syncs every 1 min")
await units("metric")
})
+
+ it("reads the network name, and falls back to plain Wi-Fi while the field is still empty", () => {
+ expect(conditionText(home)).toBe('On Wi-Fi "HomeNet"')
+ expect(conditionText({ ...home, condition: { type: "wifi_ssid" } })).toBe("On Wi-Fi")
+ expect(conditionText(wifi)).toBe("On Wi-Fi")
+ })
})
describe("profileSentence", () => {
@@ -122,6 +148,7 @@ describe("profileSentence", () => {
expect(profileSentence({ ...driving, condition: { type: "speed_below", speedThreshold: 2.78 } }, false)).toBe(
"When slower than 10 km/h, track every 2 s after 10 m and sync every 1 min."
)
+ expect(profileSentence(home, false)).toBe('On Wi-Fi "HomeNet", track every 1 min after 10 m and sync every 5 min.')
})
it("stops after the recording clause in offline mode", () => {
diff --git a/apps/mobile/src/utils/__tests__/setupLink.test.ts b/apps/mobile/src/utils/__tests__/setupLink.test.ts
index 70af54e5..12a0b916 100644
--- a/apps/mobile/src/utils/__tests__/setupLink.test.ts
+++ b/apps/mobile/src/utils/__tests__/setupLink.test.ts
@@ -67,6 +67,19 @@ const profiles: TrackingProfile[] = [
deactivationDelay: 60,
enabled: true,
createdAt: 456
+ },
+ {
+ id: 3,
+ name: "Home",
+ interval: 300,
+ distance: 10,
+ syncInterval: 300,
+ priority: 15,
+ condition: { type: "wifi_ssid", ssid: "HomeNet" },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true,
+ createdAt: 789
}
]
@@ -101,8 +114,11 @@ describe("setupLink", () => {
// collections, with DB-only fields stripped
expect(result.config.geofences).toHaveLength(1)
expect(result.config.geofences[0].name).toBe("Home")
- expect(result.config.profiles).toHaveLength(1)
+ expect(result.config.profiles).toHaveLength(2)
expect(result.config.profiles[0].condition).toEqual({ type: "speed_above", speedThreshold: 8.33 })
+ // The network name has to survive the share; the import screen rejects the profile without it.
+ expect(result.config.profiles[1].condition).toEqual({ type: "wifi_ssid", ssid: "HomeNet" })
+ expect(result.config.profiles[1]).not.toHaveProperty("id")
})
it("omits credentials entirely when that category is unchecked", () => {
diff --git a/apps/mobile/src/utils/profileRow.ts b/apps/mobile/src/utils/profileRow.ts
index 84112d9d..1b964c75 100644
--- a/apps/mobile/src/utils/profileRow.ts
+++ b/apps/mobile/src/utils/profileRow.ts
@@ -24,9 +24,15 @@ export function conditionOf(profile: Pick<TrackingProfile, "condition">) {
const speedOf = (profile: Pick<TrackingProfile, "condition">) =>
`${speedToInput(profile.condition.speedThreshold ?? 0)} ${getSpeedUnit().unit}`
+const networkOf = (profile: Pick<TrackingProfile, "condition">) => profile.condition.ssid?.trim() ?? ""
+
/** "When charging", "Speed above 50 km/h": the clause a row and the editor's sentence open with. */
export function conditionText(profile: Pick<TrackingProfile, "condition">): string {
- return t(conditionOf(profile).listKey, { speed: speedOf(profile) })
+ const entry = conditionOf(profile)
+ const network = networkOf(profile)
+ // The editor's live sentence before a network is named; saved profiles always carry one.
+ const key = entry.type === "wifi_ssid" && network === "" ? "condition.wifi_any.list" : entry.listKey
+ return t(key, { speed: speedOf(profile), network })
}
/** The recording half; a stationary profile forces the distance to 0, so "any movement" would mislead. */
@@ -48,7 +54,9 @@ export function recordingPhrase(profile: ProfileLike): string {
/** The one line under a profile's name: [Active · ]condition · recording · sync. */
export function profileRowSub(profile: ProfileLike, inForce: boolean, isOfflineMode: boolean): string {
const condition = inForce
- ? t("profile.row.active", { condition: t(conditionOf(profile).clauseKey, { speed: speedOf(profile) }) })
+ ? t("profile.row.active", {
+ condition: t(conditionOf(profile).clauseKey, { speed: speedOf(profile), network: networkOf(profile) })
+ })
: conditionText(profile)
const parts = [condition, recordingClause(profile)]
if (!isOfflineMode) parts.push(syncSummary(profile.syncInterval))
diff --git a/apps/mobile/src/utils/setupConfig.ts b/apps/mobile/src/utils/setupConfig.ts
index 002a99b9..7bb603b7 100644
--- a/apps/mobile/src/utils/setupConfig.ts
+++ b/apps/mobile/src/utils/setupConfig.ts
@@ -426,9 +426,13 @@ export function validateConfig(raw: unknown): ValidationResult {
const condType = condRaw.type as ProfileConditionType
const needsSpeed = condType === "speed_above" || condType === "speed_below"
if (needsSpeed && (typeof condRaw.speedThreshold !== "number" || condRaw.speedThreshold <= 0)) continue
+ const needsSsid = condType === "wifi_ssid"
+ if (needsSsid && (typeof condRaw.ssid !== "string" || condRaw.ssid.trim() === "")) continue
const condition: TrackingProfile["condition"] = needsSpeed
? { type: condType, speedThreshold: condRaw.speedThreshold as number }
- : { type: condType }
+ : needsSsid
+ ? { type: condType, ssid: (condRaw.ssid as string).trim() }
+ : { type: condType }
const delays = defaultProfileDelays(condType)
profiles.push({
diff --git a/fastlane/metadata/android/en-US/changelogs/52.txt b/fastlane/metadata/android/en-US/changelogs/52.txt
index 75b860a8..654abfe5 100644
--- a/fastlane/metadata/android/en-US/changelogs/52.txt
+++ b/fastlane/metadata/android/en-US/changelogs/52.txt
@@ -4,3 +4,4 @@
- Sync stops early on a rate limit or an unreachable server instead of trying every queued point
- A setup link applied while tracking now takes effect at once instead of after the next start
- After a rate limit, sync waits as long as the server asks and Sync now says so
+- Tracking profiles can switch on Wi-Fi, either any network or one you name