Skip to content

Colota - Android GPS Location tracker

feat(profiles): add a Bluetooth device tracking condition (#955)

Berezovskyi Oleksandrd00fe89f69b5
diff --git a/README.md b/README.md
index bf511381..8cf1b40c 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su
- **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 automatically stop recording locations.
-- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, Wi-Fi, speed or stationary detection.
+- **Tracking Profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, Wi-Fi, a Bluetooth device, speed or stationary detection.
- **Flexible Sync** - Instant, batch or offline modes. Restrict sync to Wi-Fi, a specific SSID or VPN.
- **App Shortcuts** - Long-press the app icon to start or stop tracking directly from the home screen, compatible with automation apps like Tasker and Samsung Routines.
- **Quick Setup** - Configure devices via `colota://setup` deep links or QR codes.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 1864ea07..fee26ab3 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -264,11 +264,11 @@ Database access layer for tracking profiles and trip events. Maintains a `TimedC
### ConditionMonitor
-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: on every Wi-Fi network that comes or goes and when Location comes back on, because a name read while Location was off is blank. Forwards state changes to `ProfileManager` for condition evaluation.
+Monitors charging state via `BroadcastReceiver`, Android Auto connection via the `CarConnection` API, Bluetooth device connections via the ACL `BroadcastReceiver` (seeded once from the A2DP and headset profile proxies, since ACL broadcasts report changes only), and Wi-Fi transport changes from `NetworkManager`, reading the network name one-shot when a named-network profile needs it: on every Wi-Fi network that comes or goes and when Location comes back on, because a name read while Location was off is blank. Forwards state changes to `ProfileManager` for condition evaluation.
### ProfileConstants
-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.
+Centralized constants for condition type strings (`charging`, `android_auto`, `speed_above`, `speed_below`, `stationary`, `wifi_any`, `wifi_ssid`, `bluetooth_device`), 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 06462001..741b1249 100644
--- a/apps/docs/docs/guides/deep-link-setup.md
+++ b/apps/docs/docs/guides/deep-link-setup.md
@@ -103,8 +103,10 @@ 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`, `wifi_any`, `wifi_ssid`, `speed_above`, `speed_below`, or `stationary` |
+| `condition.type` | string | (required) | `charging`, `android_auto`, `bluetooth_device`, `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.bluetoothAddress` | string | - | Required for `bluetooth_device`. The paired device's MAC address, e.g. `AA:BB:CC:DD:EE:FF` |
+| `condition.bluetoothName` | string | - | Optional for `bluetooth_device`. Label shown in the app; matching uses the address only |
| `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 b7df5eff..0dc8e729 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -13,7 +13,7 @@ A tracking profile is a rule: while a condition holds, such as charging, Android
## Use Cases
- **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
+- **Driving** - Switch to frequent updates when Android Auto or your car's Bluetooth 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
@@ -37,20 +37,23 @@ 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 |
-| **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) |
+| Condition | Trigger |
+| -------------------- | --------------------------------------------------------- |
+| **Charging** | Phone is plugged in to a power source |
+| **Android Auto** | Android Auto is connected |
+| **Bluetooth device** | Connected to the paired device you pick, such as your car |
+| **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.
+The Bluetooth device condition is for cars without Android Auto: pick the car's audio system from your paired devices and the profile applies while the phone is connected to it. The device is matched by its address, so renaming it does not break the profile. Listing paired devices and seeing connections needs the **Nearby devices** permission (Android 12+), which the editor offers to grant when you pick the condition. Without it the condition never matches. Like Wi-Fi, a disconnect deactivates after the profile's deactivation delay, which also rides out a short drop when the car restarts.
+
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]
@@ -112,6 +115,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 |
+| Car | Bluetooth device | 5s | 0m | 30 | 0s | 60s | Detailed route in a car without Android Auto |
| 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 |
@@ -139,4 +143,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. Sharing a **Wi-Fi network** profile also shares the network name it watches.
+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, and sharing a **Bluetooth device** profile shares the device's name and address. A shared Bluetooth profile only matches on a phone paired with that same device.
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index c1fe4b5e..795223cb 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, Wi-Fi, speed or stationary detection.
+- **Tracking profiles** - Automatically adjust GPS interval, distance filter and sync settings based on conditions like charging, Android Auto, Wi-Fi, a Bluetooth device, 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/pages/index.tsx b/apps/docs/src/pages/index.tsx
index 38abc921..d132faac 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, Wi-Fi, speed or stationary detection. One profile for hiking, another for the commute."
+ "Multiple GPS configs that auto-switch on charging, Android Auto, Wi-Fi, a Bluetooth device, 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 3f30b19c..14bda87e 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), 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.
+When tracking profiles are enabled, the App monitors charging state, car mode (Android Auto), Bluetooth device connections, GPS speed derived from location updates, and Wi-Fi connectivity to automatically switch tracking configurations. For a Bluetooth device profile the App reads the list of paired devices while you pick one, and stores the picked device's name and address in the local profile database; which devices are connected is checked on the device only and is not stored. 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
@@ -144,6 +144,8 @@ Since all data is stored locally on your device, you have full control:
| 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 |
+| Nearby Devices (Android 12+) | Bluetooth device condition for tracking profiles |
+| Bluetooth (Android 11 and lower) | Bluetooth device condition for tracking profiles |
| Battery Optimization Exemption | Optional, prevents system from restricting the app |
## Children's Privacy
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index fc10f5af..547aad7d 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -30,6 +30,12 @@
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
+ <!-- Bluetooth permissions -->
+ <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+ <!-- BLUETOOTH implies a required Bluetooth feature, which would hide the app from devices without one -->
+ <uses-feature android:name="android.hardware.bluetooth" android:required="false" />
+
<!-- Boot Receiver -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
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 0bfcc40d..e4328dd4 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
@@ -5,7 +5,9 @@
package com.Colota.bridge
+import android.annotation.SuppressLint
import android.app.Activity
+import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -54,6 +56,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import android.os.Build
import android.os.Environment
import android.os.StatFs
import java.lang.ref.WeakReference
@@ -710,6 +713,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))
config.getDouble("speedThreshold").toFloat() else null,
wifiSsid = config.getStringOrNull("wifiSsid")?.takeIf { it.isNotBlank() },
+ bluetoothAddress = config.bluetoothAddressOrNull(),
+ bluetoothName = config.getStringOrNull("bluetoothName")?.takeIf { it.isNotBlank() },
deactivationDelaySeconds = config.getInt("deactivationDelaySeconds"),
activationDelaySeconds = config.getInt("activationDelaySeconds"),
)
@@ -732,6 +737,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
hasSpeedThreshold = config.hasKey("speedThreshold"),
wifiSsid = config.getStringOrNull("wifiSsid")?.takeIf { it.isNotBlank() },
hasWifiSsid = config.hasKey("wifiSsid"),
+ bluetoothAddress = config.bluetoothAddressOrNull(),
+ bluetoothName = config.getStringOrNull("bluetoothName")?.takeIf { it.isNotBlank() },
+ hasBluetoothDevice = config.hasKey("bluetoothAddress"),
deactivationDelaySeconds = config.getIntOrNull("deactivationDelaySeconds"),
activationDelaySeconds = config.getIntOrNull("activationDelaySeconds"),
enabled = config.getBooleanOrNull("enabled"),
@@ -747,6 +755,35 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
changed
}
+ /** Uppercase, the form the connection broadcasts report, so the stored address compares directly. */
+ private fun ReadableMap.bluetoothAddressOrNull(): String? =
+ getStringOrNull("bluetoothAddress")?.trim()?.uppercase()?.takeIf { it.isNotBlank() }
+
+ /** Resolves an empty list without the Nearby devices permission; the editor asks for it first. */
+ @SuppressLint("MissingPermission")
+ @ReactMethod
+ fun getBondedBluetoothDevices(promise: Promise) {
+ val array = Arguments.createArray()
+ try {
+ val adapter = (reactApplicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
+ adapter?.bondedDevices.orEmpty()
+ .map { device ->
+ val alias = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) device.alias else null
+ (alias ?: device.name ?: device.address) to device.address.uppercase()
+ }
+ .sortedBy { it.first.lowercase() }
+ .forEach { (name, address) ->
+ array.pushMap(Arguments.createMap().apply {
+ putString("name", name)
+ putString("address", address)
+ })
+ }
+ } catch (e: SecurityException) {
+ AppLogger.w(TAG, "Reading paired Bluetooth devices denied: ${e.message}")
+ }
+ promise.resolve(array)
+ }
+
@ReactMethod
fun getActiveProfile(promise: Promise) {
val name = activeProfileName
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 ce03a8cd..acbe7aab 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 = 8
+ const val DATABASE_VERSION = 9
const val TABLE_LOCATIONS = "locations"
const val TABLE_QUEUE = "queue"
@@ -64,6 +64,8 @@ class DatabaseHelper private constructor(context: Context) :
condition_type TEXT NOT NULL,
speed_threshold REAL,
wifi_ssid TEXT,
+ bluetooth_address TEXT,
+ bluetooth_name TEXT,
deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,
activation_delay_seconds INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
@@ -260,6 +262,10 @@ class DatabaseHelper private constructor(context: Context) :
if (oldVersion < 8) {
db.execSQL("ALTER TABLE $TABLE_PROFILES ADD COLUMN wifi_ssid TEXT")
}
+ if (oldVersion < 9) {
+ db.execSQL("ALTER TABLE $TABLE_PROFILES ADD COLUMN bluetooth_address TEXT")
+ db.execSQL("ALTER TABLE $TABLE_PROFILES ADD COLUMN bluetooth_name 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 f3fa9e2b..91653256 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
@@ -30,6 +30,8 @@ class ProfileHelper(private val context: Context) {
val speedThreshold: Float?,
/** The network the profile matches by name; null for every other condition. */
val wifiSsid: String? = null,
+ /** The paired device's MAC address the profile matches; null for every other condition. */
+ val bluetoothAddress: String? = null,
val deactivationDelaySeconds: Int,
val activationDelaySeconds: Int,
)
@@ -53,7 +55,7 @@ class ProfileHelper(private val context: Context) {
arrayOf(
"id", "name", "interval_ms", "min_update_distance",
"sync_interval_seconds", "priority", "condition_type",
- "speed_threshold", "wifi_ssid", "deactivation_delay_seconds",
+ "speed_threshold", "wifi_ssid", "bluetooth_address", "deactivation_delay_seconds",
"activation_delay_seconds",
),
"enabled = 1",
@@ -69,6 +71,7 @@ class ProfileHelper(private val context: Context) {
val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
val wifiSsidIdx = cursor.getColumnIndexOrThrow("wifi_ssid")
+ val btAddressIdx = cursor.getColumnIndexOrThrow("bluetooth_address")
val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")
@@ -83,6 +86,7 @@ class ProfileHelper(private val context: Context) {
conditionType = cursor.getString(conditionIdx),
speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),
wifiSsid = if (cursor.isNull(wifiSsidIdx)) null else cursor.getString(wifiSsidIdx),
+ bluetoothAddress = if (cursor.isNull(btAddressIdx)) null else cursor.getString(btAddressIdx),
deactivationDelaySeconds = cursor.getInt(delayIdx),
activationDelaySeconds = cursor.getInt(activationDelayIdx),
))
@@ -113,6 +117,8 @@ class ProfileHelper(private val context: Context) {
val conditionIdx = cursor.getColumnIndexOrThrow("condition_type")
val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")
val wifiSsidIdx = cursor.getColumnIndexOrThrow("wifi_ssid")
+ val btAddressIdx = cursor.getColumnIndexOrThrow("bluetooth_address")
+ val btNameIdx = cursor.getColumnIndexOrThrow("bluetooth_name")
val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")
val activationDelayIdx = cursor.getColumnIndexOrThrow("activation_delay_seconds")
val enabledIdx = cursor.getColumnIndexOrThrow("enabled")
@@ -137,6 +143,16 @@ class ProfileHelper(private val context: Context) {
} else {
putString("wifiSsid", cursor.getString(wifiSsidIdx))
}
+ if (cursor.isNull(btAddressIdx)) {
+ putNull("bluetoothAddress")
+ } else {
+ putString("bluetoothAddress", cursor.getString(btAddressIdx))
+ }
+ if (cursor.isNull(btNameIdx)) {
+ putNull("bluetoothName")
+ } else {
+ putString("bluetoothName", cursor.getString(btNameIdx))
+ }
putInt("deactivationDelaySeconds", cursor.getInt(delayIdx))
putInt("activationDelaySeconds", cursor.getInt(activationDelayIdx))
putBoolean("enabled", cursor.getInt(enabledIdx) == 1)
@@ -160,6 +176,8 @@ class ProfileHelper(private val context: Context) {
conditionType: String,
speedThreshold: Float?,
wifiSsid: String?,
+ bluetoothAddress: String?,
+ bluetoothName: String?,
deactivationDelaySeconds: Int,
activationDelaySeconds: Int,
): Int {
@@ -172,6 +190,8 @@ class ProfileHelper(private val context: Context) {
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")
+ if (bluetoothAddress != null) put("bluetooth_address", bluetoothAddress) else putNull("bluetooth_address")
+ if (bluetoothName != null) put("bluetooth_name", bluetoothName) else putNull("bluetooth_name")
put("deactivation_delay_seconds", deactivationDelaySeconds)
put("activation_delay_seconds", activationDelaySeconds)
put("enabled", 1)
@@ -200,6 +220,9 @@ class ProfileHelper(private val context: Context) {
hasSpeedThreshold: Boolean = false,
wifiSsid: String? = null,
hasWifiSsid: Boolean = false,
+ bluetoothAddress: String? = null,
+ bluetoothName: String? = null,
+ hasBluetoothDevice: Boolean = false,
deactivationDelaySeconds: Int? = null,
activationDelaySeconds: Int? = null,
enabled: Boolean? = null,
@@ -217,6 +240,10 @@ class ProfileHelper(private val context: Context) {
if (hasWifiSsid) {
if (wifiSsid != null) put("wifi_ssid", wifiSsid) else putNull("wifi_ssid")
}
+ if (hasBluetoothDevice) {
+ if (bluetoothAddress != null) put("bluetooth_address", bluetoothAddress) else putNull("bluetooth_address")
+ if (bluetoothName != null) put("bluetooth_name", bluetoothName) else putNull("bluetooth_name")
+ }
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 0a4ec89a..ffe5546e 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
@@ -5,6 +5,13 @@
package com.Colota.service
+import android.Manifest
+import android.annotation.SuppressLint
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.content.pm.PackageManager
import android.os.Build
import android.content.BroadcastReceiver
import android.content.Context
@@ -19,7 +26,7 @@ import com.Colota.sync.NetworkManager
import com.Colota.util.AppLogger
/**
- * Monitors device conditions (charging state, Android Auto connection, Wi-Fi)
+ * Monitors device conditions (charging state, Android Auto connection, Wi-Fi, Bluetooth)
* and notifies ProfileManager when conditions change.
*
* Android Auto is detected via the [CarConnection] API, which reliably
@@ -27,6 +34,7 @@ import com.Colota.util.AppLogger
* 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.
+ * Bluetooth devices are tracked by their ACL connection broadcasts.
*
* All observers are registered programmatically so they only run while
* the foreground service is active.
@@ -47,6 +55,10 @@ class ConditionMonitor(
// Main thread only: invalidates in-flight SSID probes when a newer network change arrives.
private var wifiPushGeneration = 0
private var wifiMonitorActive = false
+ private var bluetoothReceiver: BroadcastReceiver? = null
+ // Main thread only: the receiver and the profile proxy callbacks both land there.
+ private val connectedBluetoothAddresses = mutableSetOf<String>()
+ private var bluetoothGeneration = 0
fun start() {
// Unregister first to prevent duplicate observers on repeated start() calls
@@ -68,6 +80,10 @@ class ConditionMonitor(
startWifiMonitor()
}
+ if (ProfileConstants.CONDITION_BLUETOOTH_DEVICE in needed) {
+ startBluetoothMonitor()
+ }
+
AppLogger.d(TAG, "Condition monitors started for: ${needed.ifEmpty { setOf("none") }}")
}
@@ -76,6 +92,8 @@ class ConditionMonitor(
stopCarConnectionMonitor()
networkManager.setWifiStateListener(null)
wifiMonitorActive = false
+ bluetoothReceiver = unregisterSafely(bluetoothReceiver)
+ bluetoothGeneration++
AppLogger.d(TAG, "Condition monitors stopped")
}
@@ -186,6 +204,135 @@ class ConditionMonitor(
}
}
+ /**
+ * ACL broadcasts carry changes only, so the devices already connected when tracking starts are
+ * read once from the A2DP and headset proxies, the two profiles a car head unit connects with.
+ * The generation drops proxy results that arrive after stop().
+ */
+ private fun startBluetoothMonitor() {
+ connectedBluetoothAddresses.clear()
+ if (!hasBluetoothPermission()) {
+ AppLogger.w(TAG, "Bluetooth condition needs the Nearby devices permission")
+ profileManager.onBluetoothDevicesChanged(emptySet())
+ return
+ }
+ val adapter = bluetoothAdapter()
+ if (adapter == null) {
+ AppLogger.w(TAG, "Bluetooth unavailable on this device")
+ profileManager.onBluetoothDevicesChanged(emptySet())
+ return
+ }
+
+ registerBluetoothReceiver()
+ seedConnectedBluetoothDevices(adapter)
+ }
+
+ private fun registerBluetoothReceiver() {
+ bluetoothReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ when (intent.action) {
+ BluetoothDevice.ACTION_ACL_CONNECTED -> {
+ val address = deviceAddressOf(intent) ?: return
+ AppLogger.d(TAG, "Bluetooth device connected")
+ connectedBluetoothAddresses.add(address)
+ pushBluetoothState()
+ }
+ BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
+ val address = deviceAddressOf(intent) ?: return
+ AppLogger.d(TAG, "Bluetooth device disconnected")
+ connectedBluetoothAddresses.remove(address)
+ pushBluetoothState()
+ }
+ BluetoothAdapter.ACTION_STATE_CHANGED -> {
+ val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
+ if (state == BluetoothAdapter.STATE_TURNING_OFF || state == BluetoothAdapter.STATE_OFF) {
+ AppLogger.d(TAG, "Bluetooth turned off")
+ connectedBluetoothAddresses.clear()
+ pushBluetoothState()
+ }
+ }
+ }
+ }
+ }
+
+ val filter = IntentFilter().apply {
+ addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
+ addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
+ addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
+ }
+ // Exported on purpose: the Bluetooth module sends these as its own uid, not as system, so a
+ // not-exported receiver never gets them. They are protected broadcasts no other app can send.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ context.registerReceiver(bluetoothReceiver, filter, Context.RECEIVER_EXPORTED)
+ } else {
+ context.registerReceiver(bluetoothReceiver, filter)
+ }
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun seedConnectedBluetoothDevices(adapter: BluetoothAdapter) {
+ if (!adapter.isEnabled) {
+ pushBluetoothState()
+ return
+ }
+
+ val generation = bluetoothGeneration
+ val profiles = listOf(BluetoothProfile.A2DP, BluetoothProfile.HEADSET)
+ var pending = profiles.size
+ fun settle() {
+ if (--pending == 0 && generation == bluetoothGeneration) pushBluetoothState()
+ }
+
+ val listener = object : BluetoothProfile.ServiceListener {
+ @SuppressLint("MissingPermission")
+ override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
+ try {
+ if (generation == bluetoothGeneration) {
+ proxy.connectedDevices.forEach { connectedBluetoothAddresses.add(it.address.uppercase()) }
+ }
+ } catch (e: SecurityException) {
+ AppLogger.w(TAG, "Reading connected Bluetooth devices denied: ${e.message}")
+ } finally {
+ try { adapter.closeProfileProxy(profile, proxy) } catch (_: Exception) {}
+ }
+ settle()
+ }
+
+ override fun onServiceDisconnected(profile: Int) {}
+ }
+
+ profiles.forEach { profile ->
+ val requested = try {
+ adapter.getProfileProxy(context, listener, profile)
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Bluetooth profile $profile proxy unavailable: ${e.message}")
+ false
+ }
+ if (!requested) settle()
+ }
+ }
+
+ private fun pushBluetoothState() {
+ profileManager.onBluetoothDevicesChanged(connectedBluetoothAddresses.toSet())
+ }
+
+ private fun deviceAddressOf(intent: Intent): String? {
+ val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
+ }
+ return device?.address?.uppercase()
+ }
+
+ private fun bluetoothAdapter(): BluetoothAdapter? =
+ (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
+
+ private fun hasBluetoothPermission(): Boolean =
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
+ context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
+
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/ProfileConstants.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileConstants.kt
index 5e12c392..5940cf96 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
@@ -13,6 +13,7 @@ object ProfileConstants {
const val CONDITION_STATIONARY = "stationary"
const val CONDITION_WIFI_ANY = "wifi_any"
const val CONDITION_WIFI_SSID = "wifi_ssid"
+ const val CONDITION_BLUETOOTH_DEVICE = "bluetooth_device"
/**
* 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 358a4c8e..6b47f168 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
@@ -64,6 +64,7 @@ class ProfileManager(
@Volatile private var isCarMode = false
@Volatile private var isWifiConnected = false
@Volatile private var currentSsid: String = ""
+ @Volatile private var connectedBluetoothAddresses: Set<String> = emptySet()
@Volatile var isStationary = false
private set
// The current still run, timed by location.time and written without the lock.
@@ -92,6 +93,12 @@ class ProfileManager(
evaluate()
}
+ /** Called on the main thread with the uppercase MAC addresses of the connected Bluetooth devices. */
+ fun onBluetoothDevicesChanged(addresses: Set<String>) {
+ connectedBluetoothAddresses = addresses
+ evaluate()
+ }
+
/** Called by the motion sensor when the device starts moving while stationary. */
fun onMotionDetected() {
if (!isStationary) return
@@ -244,6 +251,10 @@ class ProfileManager(
val target = profile.wifiSsid
isWifiConnected && !target.isNullOrBlank() && target.equals(currentSsid, ignoreCase = true)
}
+ ProfileConstants.CONDITION_BLUETOOTH_DEVICE -> {
+ val target = profile.bluetoothAddress
+ !target.isNullOrBlank() && target.uppercase() in connectedBluetoothAddresses
+ }
else -> false
}
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 bbcc485a..b4520b46 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
@@ -561,7 +561,7 @@ class LocationServiceModuleTest {
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
+ every { helper.insertProfile(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 7
awaitPromise { promise ->
module.createProfile(
@@ -581,7 +581,7 @@ class LocationServiceModuleTest {
)
}
- verify { helper.insertProfile("Home", 60000L, 10f, 300, 15, "wifi_ssid", null, "HomeNet", 60, 0) }
+ verify { helper.insertProfile("Home", 60000L, 10f, 300, 15, "wifi_ssid", null, "HomeNet", null, null, 60, 0) }
}
@Test
@@ -604,7 +604,72 @@ class LocationServiceModuleTest {
verify {
helper.updateProfile(
any(), any(), any(), any(), any(), any(), any(), any(), any(),
- isNull(), eq(true), any(), any(), any()
+ isNull(), eq(true), any(), any(), any(), any(), any(), any()
+ )
+ }
+ }
+
+ // ========================================================================
+ // Tracking profiles — Bluetooth device plumbing
+ // ========================================================================
+
+ @Test
+ fun `createProfile forwards the Bluetooth device with the address uppercased`() {
+ 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(), any(), any()) } returns 8
+
+ awaitPromise { promise ->
+ module.createProfile(
+ JavaOnlyMap().apply {
+ putString("name", "Car")
+ putDouble("intervalMs", 5000.0)
+ putDouble("minUpdateDistance", 0.0)
+ putInt("syncIntervalSeconds", 60)
+ putInt("priority", 20)
+ putString("conditionType", "bluetooth_device")
+ putNull("speedThreshold")
+ putNull("wifiSsid")
+ putString("bluetoothAddress", " aa:bb:cc:dd:ee:ff ")
+ putString("bluetoothName", "My Car")
+ putInt("deactivationDelaySeconds", 60)
+ putInt("activationDelaySeconds", 0)
+ },
+ promise
+ )
+ }
+
+ verify {
+ helper.insertProfile(
+ "Car", 5000L, 0f, 60, 20, "bluetooth_device", null, null,
+ "AA:BB:CC:DD:EE:FF", "My Car", 60, 0
+ )
+ }
+ }
+
+ @Test
+ fun `updateProfile carries the hasBluetoothDevice tri-state so the columns 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("bluetoothAddress")
+ putNull("bluetoothName")
+ },
+ promise
+ )
+ }
+
+ verify {
+ helper.updateProfile(
+ any(), any(), any(), any(), any(), any(), any(), any(), any(),
+ any(), any(), isNull(), isNull(), eq(true), any(), any(), any()
)
}
}
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 4e48ede0..9f6f6559 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
@@ -109,6 +109,69 @@ class DatabaseHelperSQLiteTest {
assertTrue(columns.contains("wifi_ssid"))
}
+ @Test
+ fun `tracking_profiles table includes the bluetooth columns`() {
+ val columns = queryColumnNames("tracking_profiles")
+ assertTrue(columns.contains("bluetooth_address"))
+ assertTrue(columns.contains("bluetooth_name"))
+ }
+
+ // ========================================================================
+ // Migration v8 -> v9: bluetooth_address, bluetooth_name
+ // ========================================================================
+
+ @Test
+ fun `migration from v8 adds the bluetooth columns and leaves existing profiles untouched`() {
+ val candidate = File.createTempFile("candidate-v8", ".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,
+ 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,
+ created_at INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ old.execSQL(
+ """
+ INSERT INTO tracking_profiles
+ (name, interval_ms, min_update_distance, sync_interval_seconds,
+ priority, condition_type, wifi_ssid, deactivation_delay_seconds, created_at)
+ VALUES ('Home', 60000, 10, 300, 15, 'wifi_ssid', 'HomeNet', 60, 0)
+ """.trimIndent()
+ )
+ old.version = 8
+ }
+
+ DatabaseHelper.migrateCandidate(candidate)
+
+ SQLiteDatabase.openDatabase(candidate.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { migrated ->
+ assertEquals(9, migrated.version)
+ migrated.rawQuery(
+ "SELECT wifi_ssid, bluetooth_address, bluetooth_name FROM tracking_profiles WHERE name = 'Home'",
+ null
+ ).use { cursor ->
+ assertTrue(cursor.moveToFirst())
+ assertEquals("HomeNet", cursor.getString(0))
+ assertTrue(cursor.isNull(1))
+ assertTrue(cursor.isNull(2))
+ }
+ }
+
+ candidate.delete()
+ }
+
// ========================================================================
// Migration v7 -> v8: wifi_ssid
// ========================================================================
@@ -151,7 +214,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(8, migrated.version)
+ assertEquals(9, migrated.version)
migrated.rawQuery("PRAGMA table_info(tracking_profiles)", null).use { cursor ->
val columns = mutableSetOf<String>()
while (cursor.moveToNext()) columns.add(cursor.getString(1))
@@ -211,7 +274,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(8, migrated.version)
+ assertEquals(9, 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)
@@ -252,7 +315,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(8, migrated.version)
+ assertEquals(9, 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 66f8af5b..98b753f4 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
@@ -63,8 +63,8 @@ class ProfileHelperTest {
val columns = listOf(
"id", "name", "interval_ms", "min_update_distance",
"sync_interval_seconds", "priority", "condition_type",
- "speed_threshold", "wifi_ssid", "deactivation_delay_seconds", "activation_delay_seconds",
- "enabled", "created_at"
+ "speed_threshold", "wifi_ssid", "bluetooth_address", "bluetooth_name",
+ "deactivation_delay_seconds", "activation_delay_seconds", "enabled", "created_at"
)
for ((idx, col) in columns.withIndex()) {
@@ -144,6 +144,7 @@ class ProfileHelperTest {
assertEquals("charging", profiles[0].conditionType)
assertNull(profiles[0].speedThreshold)
assertNull(profiles[0].wifiSsid)
+ assertNull(profiles[0].bluetoothAddress)
}
@Test
@@ -284,6 +285,58 @@ class ProfileHelperTest {
}
}
+ @Test
+ fun `getEnabledProfiles reads the Bluetooth device address`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Car", "interval_ms" to 5000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 60,
+ "priority" to 20, "condition_type" to "bluetooth_device",
+ "speed_threshold" to null, "wifi_ssid" to null,
+ "bluetooth_address" to "AA:BB:CC:DD:EE:FF", "bluetooth_name" to "My Car",
+ "deactivation_delay_seconds" to 60
+ )
+ ))
+
+ every { mockDb.query(any(), any(), eq("enabled = 1"), any(), any(), any(), any()) } returns cursor
+
+ val profiles = ProfileHelper(mockk(relaxed = true)).getEnabledProfiles()
+
+ assertEquals(1, profiles.size)
+ assertEquals("bluetooth_device", profiles[0].conditionType)
+ assertEquals("AA:BB:CC:DD:EE:FF", profiles[0].bluetoothAddress)
+ }
+
+ @Test
+ fun `getProfilesAsArray reads the Bluetooth device`() {
+ val cursor = mockCursorWithProfiles(listOf(
+ mapOf(
+ "id" to 1, "name" to "Car", "interval_ms" to 5000L,
+ "min_update_distance" to 0f, "sync_interval_seconds" to 60,
+ "priority" to 20, "condition_type" to "bluetooth_device",
+ "speed_threshold" to null, "wifi_ssid" to null,
+ "bluetooth_address" to "AA:BB:CC:DD:EE:FF", "bluetooth_name" to "My Car",
+ "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("bluetoothAddress", "AA:BB:CC:DD:EE:FF") }
+ verify { map.putString("bluetoothName", "My Car") }
+ } 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 b1aa8158..1cfb73f8 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
@@ -5,6 +5,10 @@
package com.Colota.service
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -279,6 +283,125 @@ class ConditionMonitorTest {
verify(exactly = 2) { mockNetworkManager.setWifiStateListener(isNull()) }
}
+ // ========================================================================
+ // Bluetooth condition source
+ // ========================================================================
+
+ @Test
+ fun `start reports no devices when the phone has no Bluetooth`() {
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_BLUETOOTH_DEVICE)
+ every { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) } returns null
+
+ monitor.start()
+
+ verify { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
+ assertNull(getField(monitor, "bluetoothReceiver"))
+ }
+
+ @Test
+ fun `start seeds the devices already connected over A2DP and headset`() {
+ val adapter = mockBluetoothAdapter(enabled = true)
+ val car = mockBluetoothDevice("aa:bb:cc:dd:ee:ff")
+ every { adapter.getProfileProxy(any(), any(), any()) } answers {
+ val profile = thirdArg<Int>()
+ val devices = if (profile == BluetoothProfile.HEADSET) listOf(car) else emptyList()
+ val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns devices }
+ secondArg<BluetoothProfile.ServiceListener>().onServiceConnected(profile, proxy)
+ true
+ }
+
+ monitor.start()
+
+ verify { adapter.getProfileProxy(mockContext, any(), BluetoothProfile.A2DP) }
+ verify { adapter.getProfileProxy(mockContext, any(), BluetoothProfile.HEADSET) }
+ verify(exactly = 2) { adapter.closeProfileProxy(any(), any()) }
+ // Pushed once, after both proxies answered, so a half-read set never deactivates the profile.
+ verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF")) }
+ verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(any()) }
+ }
+
+ @Test
+ fun `start still reports when a profile proxy is unavailable`() {
+ val adapter = mockBluetoothAdapter(enabled = true)
+ every { adapter.getProfileProxy(any(), any(), any()) } returns false
+
+ monitor.start()
+
+ verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
+ }
+
+ @Test
+ fun `proxy results arriving after stop are dropped`() {
+ val adapter = mockBluetoothAdapter(enabled = true)
+ val listeners = mutableListOf<Pair<Int, BluetoothProfile.ServiceListener>>()
+ every { adapter.getProfileProxy(any(), any(), any()) } answers {
+ listeners.add(thirdArg<Int>() to secondArg<BluetoothProfile.ServiceListener>())
+ true
+ }
+ monitor.start()
+ monitor.stop()
+
+ val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns listOf(mockBluetoothDevice("AA:BB:CC:DD:EE:FF")) }
+ listeners.forEach { (profile, listener) -> listener.onServiceConnected(profile, proxy) }
+
+ verify(exactly = 0) { mockProfileManager.onBluetoothDevicesChanged(any()) }
+ verify(exactly = 2) { adapter.closeProfileProxy(any(), proxy) }
+ }
+
+ @Test
+ fun `bluetooth receiver tracks devices connecting and disconnecting`() {
+ mockBluetoothAdapter(enabled = false)
+ monitor.start()
+ val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
+
+ receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "aa:bb:cc:dd:ee:ff"))
+ verify { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF")) }
+
+ receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "11:22:33:44:55:66"))
+ verify { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF", "11:22:33:44:55:66")) }
+
+ receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_DISCONNECTED, "AA:BB:CC:DD:EE:FF"))
+ verify { mockProfileManager.onBluetoothDevicesChanged(setOf("11:22:33:44:55:66")) }
+ }
+
+ @Test
+ fun `turning Bluetooth off clears every connected device`() {
+ mockBluetoothAdapter(enabled = false)
+ monitor.start()
+ val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
+ receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "AA:BB:CC:DD:EE:FF"))
+
+ val off = mockk<Intent> {
+ every { action } returns BluetoothAdapter.ACTION_STATE_CHANGED
+ every { getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) } returns BluetoothAdapter.STATE_TURNING_OFF
+ }
+ receiver.onReceive(mockContext, off)
+
+ // Once from the disabled adapter at start, once from the state change.
+ verify(exactly = 2) { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
+ }
+
+ @Test
+ fun `stop unregisters the bluetooth receiver`() {
+ mockBluetoothAdapter(enabled = false)
+ monitor.start()
+ val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
+
+ monitor.stop()
+
+ verify { mockContext.unregisterReceiver(receiver) }
+ assertNull(getField(monitor, "bluetoothReceiver"))
+ }
+
+ @Test
+ fun `start does not touch Bluetooth without a Bluetooth condition`() {
+ mockBatteryStatus(BatteryManager.BATTERY_STATUS_DISCHARGING)
+ monitor.start()
+
+ verify(exactly = 0) { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) }
+ assertNull(getField(monitor, "bluetoothReceiver"))
+ }
+
// ========================================================================
// Charging receiver — power events
// ========================================================================
@@ -433,6 +556,7 @@ class ConditionMonitorTest {
setField(spy, "networkManager", mockNetworkManager)
setField(spy, "profileManager", mockProfileManager)
setField(spy, "mainHandler", mockHandler)
+ setField(spy, "connectedBluetoothAddresses", mutableSetOf<String>())
// Stub car connection methods — CarConnection cannot be constructed in unit tests
// because CarConnectionTypeLiveData's static initializer uses Uri.Builder which
@@ -443,6 +567,29 @@ class ConditionMonitorTest {
return spy
}
+ private fun mockBluetoothAdapter(enabled: Boolean): BluetoothAdapter {
+ every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_BLUETOOTH_DEVICE)
+ val btAdapter = mockk<BluetoothAdapter>(relaxed = true) {
+ every { isEnabled } returns enabled
+ }
+ val manager = mockk<BluetoothManager> { every { adapter } returns btAdapter }
+ every { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) } returns manager
+ return btAdapter
+ }
+
+ private fun mockBluetoothDevice(address: String) = mockk<BluetoothDevice> {
+ every { [email protected] } returns address
+ }
+
+ private fun aclIntent(action: String, address: String): Intent {
+ val device = mockBluetoothDevice(address)
+ return mockk {
+ every { [email protected] } returns action
+ @Suppress("DEPRECATION")
+ every { getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) } returns device
+ }
+ }
+
private fun mockBatteryStatus(status: Int) {
val batteryIntent = mockk<Intent> {
every { getIntExtra(BatteryManager.EXTRA_STATUS, -1) } returns status
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 bdf77e2b..eb3c9ca0 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
@@ -164,6 +164,26 @@ class ProfileManagerTest {
activationDelaySeconds = activationDelay
)
+ private fun bluetoothProfile(
+ id: Int = 7,
+ address: String? = "AA:BB:CC:DD:EE:FF",
+ priority: Int = 20,
+ deactivationDelay: Int = 60,
+ activationDelay: Int = 0
+ ) = ProfileHelper.CachedProfile(
+ id = id,
+ name = "Car",
+ intervalMs = 5000,
+ minUpdateDistance = 0f,
+ syncIntervalSeconds = 60,
+ priority = priority,
+ conditionType = ProfileConstants.CONDITION_BLUETOOTH_DEVICE,
+ speedThreshold = null,
+ bluetoothAddress = address,
+ deactivationDelaySeconds = deactivationDelay,
+ activationDelaySeconds = activationDelay
+ )
+
private fun mockLocation(speed: Float, hasSpeed: Boolean = true, timeMs: Long = t0): Location {
return mockk {
every { [email protected] } returns speed
@@ -370,6 +390,72 @@ class ProfileManagerTest {
assertNull(switchedProfileName)
}
+ // --- Bluetooth condition ---
+
+ @Test
+ fun `activates the bluetooth profile while its device is connected`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(bluetoothProfile())
+
+ val manager = createManager()
+ manager.onBluetoothDevicesChanged(setOf("11:22:33:44:55:66", "AA:BB:CC:DD:EE:FF"))
+
+ assertEquals("Car", switchedProfileName)
+ assertEquals(5000L, switchedInterval)
+ }
+
+ @Test
+ fun `matches a stored lowercase address against the uppercase connected set`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(bluetoothProfile(address = "aa:bb:cc:dd:ee:ff"))
+
+ val manager = createManager()
+ manager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF"))
+
+ assertEquals("Car", switchedProfileName)
+ }
+
+ @Test
+ fun `does not activate the bluetooth profile for another device or none`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(bluetoothProfile())
+
+ val manager = createManager()
+ manager.onBluetoothDevicesChanged(setOf("11:22:33:44:55:66"))
+ assertNull(switchedProfileName)
+
+ manager.onBluetoothDevicesChanged(emptySet())
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `a bluetooth profile without an address never matches`() = runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(bluetoothProfile(address = null))
+
+ val manager = createManager()
+ manager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF"))
+
+ assertNull(switchedProfileName)
+ }
+
+ @Test
+ fun `deactivates the bluetooth profile after its deactivation delay when the device disconnects`() = testScope.runTest {
+ every { profileHelper.getEnabledProfiles() } returns listOf(bluetoothProfile(deactivationDelay = 30))
+
+ val manager = createManager()
+ manager.defaultInterval = 10000L
+ manager.defaultDistance = 0f
+ manager.defaultSyncInterval = 0
+
+ manager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF"))
+ assertEquals("Car", switchedProfileName)
+
+ manager.onBluetoothDevicesChanged(emptySet())
+ assertEquals("Car", switchedProfileName)
+
+ advanceTimeBy(31_000)
+
+ assertNull(switchedProfileName)
+ assertEquals(10000L, switchedInterval)
+ }
+
// --- Speed conditions ---
@Test
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 74cafacf..035f67f1 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, Wifi } from "lucide-react-native"
+import { Zap, Car, ArrowUp, ArrowDown, Pause, Wifi, Bluetooth } from "lucide-react-native"
// Timing
export const AUTOSAVE_DEBOUNCE_MS = 1500
@@ -95,6 +95,7 @@ export const PROFILE_CONDITIONS: {
[
["charging", Zap],
["android_auto", Car],
+ ["bluetooth_device", Bluetooth],
["wifi_any", Wifi],
["wifi_ssid", Wifi],
["speed_above", ArrowUp],
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index 56f1d1d6..f2131fc2 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -253,6 +253,11 @@
"condition.android_auto.clause": "on Android Auto",
"condition.android_auto.description": "Android Auto is connected",
"condition.android_auto.list": "On Android Auto",
+ "condition.bluetooth_device": "Bluetooth device",
+ "condition.bluetooth_device.clause": "connected to \"{{device}}\"",
+ "condition.bluetooth_device.description": "Connected to a paired device, such as your car",
+ "condition.bluetooth_device.list": "Connected to \"{{device}}\"",
+ "condition.bluetooth_device.listUnset": "When connected to a Bluetooth device",
"condition.charging": "Charging",
"condition.charging.clause": "when charging",
"condition.charging.description": "Phone is plugged in",
@@ -736,6 +741,13 @@
"profileEditor.activation": "Activation delay",
"profileEditor.activation.hint": "How long the condition must hold first. 0 switches at once, longer ignores a brief plug or unplug.",
"profileEditor.activation.hintStationary": "How long every fix must read as still; 0 switches at the first still fix. Moving again ends the profile at once.",
+ "profileEditor.bluetooth.allow": "Allow Nearby devices",
+ "profileEditor.bluetooth.empty": "Pick a device or the profile can't match",
+ "profileEditor.bluetooth.hint": "Matches while the phone is connected to this device, such as your car's audio system.",
+ "profileEditor.bluetooth.noDevices": "No paired devices. Pair one in Bluetooth settings, then come back.",
+ "profileEditor.bluetooth.openSettings": "Open app settings",
+ "profileEditor.bluetooth.permission": "Colota needs the Nearby devices permission to list your paired devices and notice when one connects.",
+ "profileEditor.bluetooth.unpaired": "No longer paired",
"profileEditor.create": "Create profile",
"profileEditor.deactivation": "Deactivation delay",
"profileEditor.deactivation.hint": "How long the profile stays on after its condition ends. Longer rides out a brief gap.",
diff --git a/apps/mobile/src/i18n/locales/es.json b/apps/mobile/src/i18n/locales/es.json
index befbc090..66b8f3d2 100644
--- a/apps/mobile/src/i18n/locales/es.json
+++ b/apps/mobile/src/i18n/locales/es.json
@@ -253,6 +253,11 @@
"condition.android_auto.clause": "en Android Auto",
"condition.android_auto.description": "Android Auto está conectado",
"condition.android_auto.list": "En Android Auto",
+ "condition.bluetooth_device": "Dispositivo Bluetooth",
+ "condition.bluetooth_device.clause": "conectado a \"{{device}}\"",
+ "condition.bluetooth_device.description": "Conectado a un dispositivo vinculado, como tu coche",
+ "condition.bluetooth_device.list": "Conectado a \"{{device}}\"",
+ "condition.bluetooth_device.listUnset": "Al conectar un dispositivo Bluetooth",
"condition.charging": "Cargando",
"condition.charging.clause": "al cargar",
"condition.charging.description": "El teléfono está conectado a la corriente",
@@ -736,6 +741,13 @@
"profileEditor.activation": "Retraso de activación",
"profileEditor.activation.hint": "Cuánto tiempo debe cumplirse la condición primero. 0 cambia de inmediato; un valor más alto ignora una conexión o desconexión breve.",
"profileEditor.activation.hintStationary": "Cuánto tiempo cada posición debe indicar quietud; 0 cambia en la primera posición quieta. Volver a moverse termina el perfil de inmediato.",
+ "profileEditor.bluetooth.allow": "Permitir dispositivos cercanos",
+ "profileEditor.bluetooth.empty": "Elige un dispositivo o el perfil no podrá aplicarse",
+ "profileEditor.bluetooth.hint": "Se aplica mientras el teléfono esté conectado a este dispositivo, como el sistema de audio de tu coche.",
+ "profileEditor.bluetooth.noDevices": "No hay dispositivos vinculados. Vincula uno en los ajustes de Bluetooth y vuelve.",
+ "profileEditor.bluetooth.openSettings": "Abrir ajustes de la app",
+ "profileEditor.bluetooth.permission": "Colota necesita el permiso de dispositivos cercanos para ver tus dispositivos vinculados y saber cuándo se conecta uno.",
+ "profileEditor.bluetooth.unpaired": "Ya no está vinculado",
"profileEditor.create": "Crear perfil",
"profileEditor.deactivation": "Retraso de desactivación",
"profileEditor.deactivation.hint": "Cuánto tiempo sigue activo el perfil después de que su condición termina. Un valor más alto tolera una interrupción breve.",
diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsx
index 961e5917..803b343b 100644
--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx
+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx
@@ -4,14 +4,19 @@
*/
import React, { useState, useEffect, useLayoutEffect, useCallback } from "react"
-import { View, Text, StyleSheet, ScrollView, AppState } from "react-native"
+import { View, Text, StyleSheet, ScrollView, AppState, Linking } 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 {
+ checkBluetoothPermission,
+ requestBluetoothPermission,
+ type BluetoothPermissionResult
+} from "../services/LocationServicePermission"
import { showAlert, showConfirm } from "../services/modalService"
-import { TrackingProfile, ProfileConditionType } from "../types/global"
+import { TrackingProfile, ProfileConditionType, BluetoothDeviceInfo } from "../types/global"
import { fontSizes, fonts, lineHeights } from "../styles/typography"
import { SyncIntervalPicker } from "../components/features/settings/SyncIntervalPicker"
import {
@@ -71,6 +76,10 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
})
const [saving, setSaving] = useState(false)
const [currentSsid, setCurrentSsid] = useState("")
+ const [btPermission, setBtPermission] = useState<BluetoothPermissionResult | null>(null)
+ const [pairedDevices, setPairedDevices] = useState<BluetoothDeviceInfo[]>([])
+ // Survives a switch to another condition and back, like the typed network name.
+ const [pickedDevice, setPickedDevice] = useState<BluetoothDeviceInfo | null>(null)
const [text, setText] = useState({
interval: String(settings.interval),
distance: String(metersToInput(settings.distance)),
@@ -100,6 +109,24 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
return () => sub.remove()
}, [profile.condition.type])
+ const refreshPairedDevices = useCallback(async () => {
+ const granted = await checkBluetoothPermission()
+ // A denial already seen stays "blocked", so the button keeps pointing at app settings.
+ setBtPermission((prev) => (granted ? "granted" : prev === "blocked" ? "blocked" : "denied"))
+ setPairedDevices(granted ? await NativeLocationService.getBondedBluetoothDevices() : [])
+ }, [])
+
+ useEffect(() => {
+ if (profile.condition.type !== "bluetooth_device") return
+
+ refreshPairedDevices()
+ // Pairing a device or granting the permission in settings and coming back should list it.
+ const sub = AppState.addEventListener("change", (state) => {
+ if (state === "active") refreshPairedDevices()
+ })
+ return () => sub.remove()
+ }, [profile.condition.type, refreshPairedDevices])
+
useLayoutEffect(() => {
navigation.setOptions({ headerTitle: isEditing ? t("profileEditor.titleEdit") : t("profileEditor.titleNew") })
}, [navigation, isEditing, t])
@@ -121,6 +148,12 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
deactivationDelay: existing.deactivationDelay,
enabled: existing.enabled
})
+ if (existing.condition.bluetoothAddress) {
+ setPickedDevice({
+ address: existing.condition.bluetoothAddress,
+ name: existing.condition.bluetoothName ?? existing.condition.bluetoothAddress
+ })
+ }
setText({
interval: String(existing.interval),
distance: String(metersToInput(existing.distance)),
@@ -144,6 +177,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const isSpeed = isSpeedType(type)
const isStationary = type === "stationary"
const isWifiSsid = type === "wifi_ssid"
+ const isBluetooth = type === "bluetooth_device"
const conditionLabel = t(conditionOf(profile).labelKey)
const store = useCallback((key: NumericKey, value: number) => {
@@ -185,6 +219,33 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
const ssidError = isWifiSsid && text.ssid.trim() === "" ? t("profileEditor.wifi.empty") : undefined
const offerCurrentSsid = currentSsid !== "" && currentSsid.trim().toLowerCase() !== text.ssid.trim().toLowerCase()
+ const handleDevice = (device: BluetoothDeviceInfo) => {
+ setPickedDevice(device)
+ setProfile((prev) => ({
+ ...prev,
+ condition: { ...prev.condition, bluetoothAddress: device.address, bluetoothName: device.name }
+ }))
+ }
+ const deviceError = isBluetooth && !pickedDevice ? t("profileEditor.bluetooth.empty") : undefined
+ // A picked device that was unpaired since still shows, so the profile never loses it silently.
+ const deviceRows =
+ pickedDevice && !pairedDevices.some((d) => d.address === pickedDevice.address)
+ ? [
+ { ...pickedDevice, unpaired: btPermission === "granted" },
+ ...pairedDevices.map((d) => ({ ...d, unpaired: false }))
+ ]
+ : pairedDevices.map((d) => ({ ...d, unpaired: false }))
+
+ const handleAllowBluetooth = async () => {
+ if (btPermission === "blocked") {
+ Linking.openSettings()
+ return
+ }
+ const result = await requestBluetoothPermission()
+ setBtPermission(result)
+ if (result === "granted") refreshPairedDevices()
+ }
+
const priorityError =
text.priority !== "" && parseWholeNumber(text.priority) === null ? t("validation.wholeNumber") : undefined
const handlePriority = (value: string) => {
@@ -212,6 +273,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
// 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
+ const device = next === "bluetooth_device" && pickedDevice ? pickedDevice : undefined
setProfile((prev) => ({
...prev,
...delays,
@@ -220,7 +282,8 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
condition: {
type: next,
...(speedThreshold !== undefined ? { speedThreshold } : {}),
- ...(ssid !== undefined ? { ssid } : {})
+ ...(ssid !== undefined ? { ssid } : {}),
+ ...(device ? { bluetoothAddress: device.address, bluetoothName: device.name } : {})
}
}))
setText((prev) => ({
@@ -257,6 +320,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
(!isStationary && !!errorOf("distance")) ||
(isSpeed && !!errorOf("speed")) ||
!!ssidError ||
+ !!deviceError ||
!!errorOf("activationDelay") ||
(!isStationary && !!errorOf("deactivationDelay"))
@@ -352,6 +416,47 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof
)}
</View>
)}
+ {opt.type === "bluetooth_device" && type === opt.type && (
+ <View style={styles.reveal}>
+ {btPermission !== null && btPermission !== "granted" && (
+ <>
+ <FieldMessage>{t("profileEditor.bluetooth.permission")}</FieldMessage>
+ <Button
+ variant="secondary"
+ title={
+ btPermission === "blocked"
+ ? t("profileEditor.bluetooth.openSettings")
+ : t("profileEditor.bluetooth.allow")
+ }
+ testID="bluetooth-allow"
+ onPress={handleAllowBluetooth}
+ style={styles.ssidUse}
+ />
+ </>
+ )}
+ {btPermission === "granted" && pairedDevices.length === 0 && (
+ <FieldMessage>{t("profileEditor.bluetooth.noDevices")}</FieldMessage>
+ )}
+ {deviceRows.length > 0 && (
+ <View accessibilityRole="radiogroup">
+ {deviceRows.map((device) => (
+ <RadioRow
+ key={device.address}
+ testID={`bluetooth-device-${device.address}`}
+ label={device.name}
+ sub={device.unpaired ? t("profileEditor.bluetooth.unpaired") : device.address}
+ selected={pickedDevice?.address === device.address}
+ onPress={() => handleDevice({ name: device.name, address: device.address })}
+ />
+ ))}
+ </View>
+ )}
+ {deviceError && btPermission === "granted" && pairedDevices.length > 0 ? (
+ <FieldMessage variant="error">{deviceError}</FieldMessage>
+ ) : null}
+ <FieldMessage>{t("profileEditor.bluetooth.hint")}</FieldMessage>
+ </View>
+ )}
</React.Fragment>
))}
</View>
diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
index 2ae2fd0f..74beb597 100644
--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx
@@ -27,6 +27,18 @@ const mockProfiles: TrackingProfile[] = [
activationDelay: 0,
deactivationDelay: 60,
enabled: true
+ },
+ {
+ id: 3,
+ name: "Car",
+ interval: 5,
+ distance: 0,
+ syncInterval: 60,
+ priority: 20,
+ condition: { type: "bluetooth_device", bluetoothAddress: "00:11:22:33:44:55", bluetoothName: "Old Car" },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true
}
]
@@ -45,11 +57,30 @@ jest.mock("../../services/ProfileService", () => ({
}))
const mockGetCurrentSsid = jest.fn().mockResolvedValue("HomeNet")
+const mockGetBondedBluetoothDevices = jest.fn()
jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
- default: { getCurrentSsid: () => mockGetCurrentSsid() }
+ default: {
+ getCurrentSsid: () => mockGetCurrentSsid(),
+ getBondedBluetoothDevices: () => mockGetBondedBluetoothDevices()
+ }
}))
+const mockCheckBluetoothPermission = jest.fn()
+const mockRequestBluetoothPermission = jest.fn()
+jest.mock("../../services/LocationServicePermission", () => ({
+ checkBluetoothPermission: () => mockCheckBluetoothPermission(),
+ requestBluetoothPermission: () => mockRequestBluetoothPermission()
+}))
+
+const mockOpenSettings = jest.fn()
+jest.spyOn(require("react-native").Linking, "openSettings").mockImplementation(() => mockOpenSettings())
+
+const PAIRED = [
+ { name: "My Car", address: "AA:BB:CC:DD:EE:FF" },
+ { name: "Earbuds", address: "11:22:33:44:55:66" }
+]
+
const mockShowAlert = jest.fn()
const mockShowConfirm = jest.fn()
jest.mock("../../services/modalService", () => ({
@@ -208,6 +239,8 @@ describe("ProfileEditorScreen", () => {
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(getByText("Bluetooth device")).toBeTruthy()
+ expect(getByText("Connected to a paired device, such as your car")).toBeTruthy()
expect(getByTestId("condition-charging").props.accessibilityState.checked).toBe(true)
})
@@ -304,6 +337,113 @@ describe("ProfileEditorScreen", () => {
})
})
+ describe("bluetooth device", () => {
+ beforeEach(() => {
+ mockCheckBluetoothPermission.mockResolvedValue(true)
+ mockRequestBluetoothPermission.mockResolvedValue("granted")
+ mockGetBondedBluetoothDevices.mockResolvedValue(PAIRED)
+ })
+
+ it("lists the paired devices and blocks Save until one is picked", async () => {
+ const { getByTestId, findByTestId, getByText } = renderNew()
+
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
+
+ expect(getByText("Earbuds")).toBeTruthy()
+ expect(getByText("Pick a device or the profile can't match")).toBeTruthy()
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ "When connected to a Bluetooth device, track every 5 s, any movement and sync each fix."
+ )
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(true)
+
+ fireEvent.press(getByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF"))
+ expect(getByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF").props.accessibilityState.checked).toBe(true)
+ expect(getByTestId("profile-sentence").props.children).toBe(
+ 'Connected to "My Car", track every 5 s, any movement and sync each fix.'
+ )
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
+ })
+
+ it("saves the picked device's address and name", async () => {
+ const { getByTestId, findByTestId } = renderNew()
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ fireEvent.press(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF"))
+ fireEvent.press(getByTestId("save-profile-btn"))
+
+ await waitFor(() =>
+ expect(mockCreateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF", bluetoothName: "My Car" }
+ })
+ )
+ )
+ })
+
+ it("asks for the Nearby devices permission before it can list anything", async () => {
+ mockCheckBluetoothPermission.mockResolvedValueOnce(false)
+ const { getByTestId, findByTestId, queryByTestId } = renderNew()
+
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ const allow = await findByTestId("bluetooth-allow")
+ expect(queryByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeNull()
+ expect(mockGetBondedBluetoothDevices).not.toHaveBeenCalled()
+
+ fireEvent.press(allow)
+ await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
+ expect(mockRequestBluetoothPermission).toHaveBeenCalled()
+ expect(queryByTestId("bluetooth-allow")).toBeNull()
+ })
+
+ it("sends a blocked permission to app settings", async () => {
+ mockCheckBluetoothPermission.mockResolvedValue(false)
+ mockRequestBluetoothPermission.mockResolvedValue("blocked")
+ const { getByTestId, findByTestId, findByText } = renderNew()
+
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ fireEvent.press(await findByTestId("bluetooth-allow"))
+ await findByText("Open app settings")
+
+ fireEvent.press(getByTestId("bluetooth-allow"))
+ expect(mockOpenSettings).toHaveBeenCalled()
+ })
+
+ it("says how to pair a device when none is paired", async () => {
+ mockGetBondedBluetoothDevices.mockResolvedValue([])
+ const { getByTestId, findByText } = renderNew()
+
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ expect(await findByText("No paired devices. Pair one in Bluetooth settings, then come back.")).toBeTruthy()
+ })
+
+ it("keeps a stored device that is no longer paired, and the pick across a condition round trip", async () => {
+ const { getByTestId, findByTestId, getByText } = renderEdit(3)
+ const stored = await findByTestId("bluetooth-device-00:11:22:33:44:55")
+ expect(stored.props.accessibilityState.checked).toBe(true)
+ expect(getByText("No longer paired")).toBeTruthy()
+
+ fireEvent.press(getByTestId("condition-charging"))
+ fireEvent.press(getByTestId("condition-bluetooth_device"))
+ await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")
+ expect(getByTestId("bluetooth-device-00:11:22:33:44:55").props.accessibilityState.checked).toBe(true)
+ expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)
+ })
+
+ it("clears the stored device when saved under another condition", async () => {
+ const { findByTestId, getByTestId } = renderEdit(3)
+ await findByTestId("bluetooth-device-00:11:22:33:44:55")
+
+ fireEvent.press(getByTestId("condition-charging"))
+ fireEvent.press(getByTestId("save-profile-btn"))
+
+ await waitFor(() =>
+ expect(mockUpdateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 3, condition: { type: "charging" } })
+ )
+ )
+ })
+ })
+
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 6058443f..65e2e378 100644
--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
@@ -690,6 +690,38 @@ describe("SetupImportScreen", () => {
)
})
+ it("rejects a Bluetooth profile without a valid device address", () => {
+ for (const condition of [
+ { type: "bluetooth_device" },
+ { type: "bluetooth_device", bluetoothAddress: "My Car" }
+ ]) {
+ const { getByText, unmount } = renderScreen(encode({ profiles: [{ ...validProfile, condition }] }))
+ expect(getByText("Invalid configuration")).toBeTruthy()
+ unmount()
+ }
+ })
+
+ it("imports a Bluetooth profile with its address uppercased and its name trimmed", async () => {
+ const config = {
+ profiles: [
+ {
+ ...validProfile,
+ condition: { type: "bluetooth_device", bluetoothAddress: " aa:bb:cc:dd:ee:ff ", bluetoothName: " My Car " }
+ }
+ ]
+ }
+ const { getByText } = renderScreen(encode(config))
+
+ fireEvent.press(getByText("Apply configuration"))
+
+ await waitFor(() => expect(mockCreateProfile).toHaveBeenCalledTimes(1))
+ expect(mockCreateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF", bluetoothName: "My Car" }
+ })
+ )
+ })
+
it("accepts the any-network condition without extra fields", () => {
const config = { profiles: [{ ...validProfile, condition: { type: "wifi_any" } }] }
const { getByText } = renderScreen(encode(config))
diff --git a/apps/mobile/src/services/LocationServicePermission.ts b/apps/mobile/src/services/LocationServicePermission.ts
index ead7b7c0..b166484d 100644
--- a/apps/mobile/src/services/LocationServicePermission.ts
+++ b/apps/mobile/src/services/LocationServicePermission.ts
@@ -29,6 +29,11 @@ const ANDROID_13 = 33
/** Android 17 (API 37) - local network enforced via ACCESS_LOCAL_NETWORK */
const ANDROID_LOCAL_NETWORK = 37
+/** Android 12 (API 31) - Bluetooth connections need BLUETOOTH_CONNECT (Nearby devices) */
+const ANDROID_12 = 31
+
+export type BluetoothPermissionResult = "granted" | "denied" | "blocked"
+
/**
* Callback registered by LocationDisclosureModal to show the themed disclosure.
* Without one nothing is requested: the reviewed disclosure is the only one Colota shows.
@@ -213,3 +218,26 @@ export async function ensureLocalNetworkPermission(): Promise<boolean> {
return false
}
}
+
+export async function checkBluetoothPermission(): Promise<boolean> {
+ if (Platform.OS !== "android") return true
+ if (getAndroidVersion() < ANDROID_12) return true
+ return await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT)
+}
+
+/**
+ * Requests the Nearby devices permission the Bluetooth profile condition needs.
+ * "blocked" means Android no longer shows the dialog, so only app settings can grant it.
+ */
+export async function requestBluetoothPermission(): Promise<BluetoothPermissionResult> {
+ if (await checkBluetoothPermission()) return "granted"
+
+ try {
+ const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT)
+ if (result === PermissionsAndroid.RESULTS.GRANTED) return "granted"
+ return result === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN ? "blocked" : "denied"
+ } catch (err) {
+ logger.error("[PermissionService] Bluetooth permission request failed:", err)
+ return "denied"
+ }
+}
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 14a2544d..597d4e98 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -6,6 +6,7 @@
import { NativeModules } from "react-native"
import {
AuthConfig,
+ BluetoothDeviceInfo,
ClientCertInfo,
ClientCertInfoResult,
DailyStat,
@@ -484,7 +485,9 @@ class NativeLocationService {
condition: {
type: p.conditionType,
...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {}),
- ...(p.wifiSsid != null ? { ssid: p.wifiSsid } : {})
+ ...(p.wifiSsid != null ? { ssid: p.wifiSsid } : {}),
+ ...(p.bluetoothAddress != null ? { bluetoothAddress: p.bluetoothAddress } : {}),
+ ...(p.bluetoothName != null ? { bluetoothName: p.bluetoothName } : {})
},
activationDelay: p.activationDelaySeconds,
deactivationDelay: p.deactivationDelaySeconds,
@@ -509,6 +512,8 @@ class NativeLocationService {
conditionType: profile.condition.type,
speedThreshold: profile.condition.speedThreshold ?? null,
wifiSsid: profile.condition.ssid ?? null,
+ bluetoothAddress: profile.condition.bluetoothAddress ?? null,
+ bluetoothName: profile.condition.bluetoothName ?? null,
deactivationDelaySeconds: profile.deactivationDelay,
activationDelaySeconds: profile.activationDelay
})
@@ -531,6 +536,8 @@ class NativeLocationService {
config.conditionType = update.condition.type
config.speedThreshold = update.condition.speedThreshold ?? null
config.wifiSsid = update.condition.ssid ?? null
+ config.bluetoothAddress = update.condition.bluetoothAddress ?? null
+ config.bluetoothName = update.condition.bluetoothName ?? null
}
if (update.deactivationDelay !== undefined) config.deactivationDelaySeconds = update.deactivationDelay
if (update.activationDelay !== undefined) config.activationDelaySeconds = update.activationDelay
@@ -658,6 +665,18 @@ class NativeLocationService {
return this.safeExecute(() => LocationServiceModule.getCurrentSsid(), "", "getCurrentSsid failed")
}
+ /**
+ * Returns the paired Bluetooth devices, or an empty list without the Nearby devices permission.
+ */
+ static async getBondedBluetoothDevices(): Promise<BluetoothDeviceInfo[]> {
+ this.ensureModule()
+ return this.safeExecute(
+ () => LocationServiceModule.getBondedBluetoothDevices(),
+ [],
+ "getBondedBluetoothDevices failed"
+ )
+ }
+
/**
* Returns available device storage in MB, or -1 if the check fails.
*/
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index b5eb839a..0a73ee89 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -494,6 +494,8 @@ describe("NativeLocationService", () => {
conditionType: "wifi_ssid",
speedThreshold: null,
wifiSsid: "HomeNet",
+ bluetoothAddress: null,
+ bluetoothName: null,
deactivationDelaySeconds: 60,
activationDelaySeconds: 0,
enabled: true,
@@ -513,6 +515,23 @@ describe("NativeLocationService", () => {
activationDelaySeconds: 0,
enabled: true,
createdAt: 1700000000
+ },
+ {
+ id: 3,
+ name: "Car",
+ intervalMs: 5000,
+ minUpdateDistance: 0,
+ syncIntervalSeconds: 60,
+ priority: 20,
+ conditionType: "bluetooth_device",
+ speedThreshold: null,
+ wifiSsid: null,
+ bluetoothAddress: "AA:BB:CC:DD:EE:FF",
+ bluetoothName: "My Car",
+ deactivationDelaySeconds: 60,
+ activationDelaySeconds: 0,
+ enabled: true,
+ createdAt: 1700000000
}
])
@@ -522,6 +541,12 @@ describe("NativeLocationService", () => {
expect(profiles[0].interval).toBe(60)
expect(profiles[1].condition).toEqual({ type: "speed_above", speedThreshold: 13.89 })
expect(profiles[1].condition).not.toHaveProperty("ssid")
+ expect(profiles[0].condition).not.toHaveProperty("bluetoothAddress")
+ expect(profiles[2].condition).toEqual({
+ type: "bluetooth_device",
+ bluetoothAddress: "AA:BB:CC:DD:EE:FF",
+ bluetoothName: "My Car"
+ })
})
it("sends the SSID on create", async () => {
@@ -542,6 +567,36 @@ describe("NativeLocationService", () => {
)
})
+ it("sends the Bluetooth device on create", async () => {
+ await NativeLocationService.createProfile({
+ name: "Car",
+ interval: 5,
+ distance: 0,
+ syncInterval: 60,
+ priority: 20,
+ condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF", bluetoothName: "My Car" },
+ activationDelay: 0,
+ deactivationDelay: 60,
+ enabled: true
+ })
+
+ expect(nativeMock.createProfile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ conditionType: "bluetooth_device",
+ bluetoothAddress: "AA:BB:CC:DD:EE:FF",
+ bluetoothName: "My Car"
+ })
+ )
+ })
+
+ it("clears the stored Bluetooth device when the condition no longer names one", async () => {
+ await NativeLocationService.updateProfile({ id: 1, condition: { type: "charging" } })
+
+ expect(nativeMock.updateProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ conditionType: "charging", bluetoothAddress: null, bluetoothName: null })
+ )
+ })
+
it("clears the stored SSID when the condition no longer names one", async () => {
await NativeLocationService.updateProfile({ id: 1, condition: { type: "charging" } })
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index a34a2c50..0b4df8c1 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -390,7 +390,14 @@ export const DEFAULT_AUTH_CONFIG: AuthConfig = {
// ============================================================================
export type ProfileConditionType =
- "charging" | "android_auto" | "speed_above" | "speed_below" | "stationary" | "wifi_any" | "wifi_ssid"
+ | "charging"
+ | "android_auto"
+ | "bluetooth_device"
+ | "speed_above"
+ | "speed_below"
+ | "stationary"
+ | "wifi_any"
+ | "wifi_ssid"
export interface ProfileCondition {
type: ProfileConditionType
@@ -398,6 +405,16 @@ export interface ProfileCondition {
speedThreshold?: number
/** Wi-Fi network name in the user's own casing (only for wifi_ssid conditions) */
ssid?: string
+ /** Paired device MAC address, uppercase (only for bluetooth_device conditions) */
+ bluetoothAddress?: string
+ /** Device name when it was picked, for display only; matching uses the address (only for bluetooth_device conditions) */
+ bluetoothName?: string
+}
+
+/** A paired Bluetooth device as the profile editor lists it */
+export interface BluetoothDeviceInfo {
+ name: string
+ address: 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 051ce9f6..637fff43 100644
--- a/apps/mobile/src/utils/__tests__/profileRow.test.ts
+++ b/apps/mobile/src/utils/__tests__/profileRow.test.ts
@@ -76,6 +76,14 @@ const wifi = profile({
distance: 5,
condition: { type: "wifi_any" }
})
+const carAudio = profile({
+ id: 7,
+ name: "Car audio",
+ interval: 5,
+ distance: 0,
+ syncInterval: 60,
+ condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF", bluetoothName: "My Car" }
+})
const settings = { interval: 30, distance: 2, syncInterval: 300, isOfflineMode: false }
describe("profileRowSub", () => {
@@ -131,6 +139,19 @@ describe("profileRowSub", () => {
await units("metric")
})
+ it("names the Bluetooth device, by address when it has no name, and stays generic before one is picked", () => {
+ expect(profileRowSub(carAudio, false, false)).toBe(
+ 'Connected to "My Car" · Every 5 s, any movement · syncs every 1 min'
+ )
+ expect(profileRowSub(carAudio, true, false)).toBe(
+ 'Active · connected to "My Car" · Every 5 s, any movement · syncs every 1 min'
+ )
+ expect(conditionText({ condition: { type: "bluetooth_device", bluetoothAddress: "AA:BB:CC:DD:EE:FF" } })).toBe(
+ 'Connected to "AA:BB:CC:DD:EE:FF"'
+ )
+ expect(conditionText({ condition: { type: "bluetooth_device" } })).toBe("When connected to a Bluetooth device")
+ })
+
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")
diff --git a/apps/mobile/src/utils/profileRow.ts b/apps/mobile/src/utils/profileRow.ts
index 1b964c75..ff34eebd 100644
--- a/apps/mobile/src/utils/profileRow.ts
+++ b/apps/mobile/src/utils/profileRow.ts
@@ -26,13 +26,21 @@ const speedOf = (profile: Pick<TrackingProfile, "condition">) =>
const networkOf = (profile: Pick<TrackingProfile, "condition">) => profile.condition.ssid?.trim() ?? ""
+const deviceOf = (profile: Pick<TrackingProfile, "condition">) =>
+ profile.condition.bluetoothName?.trim() || profile.condition.bluetoothAddress || ""
+
+const unsetKey = (profile: Pick<TrackingProfile, "condition">) => {
+ const { type } = profile.condition
+ if (type === "wifi_ssid" && networkOf(profile) === "") return "condition.wifi_any.list"
+ if (type === "bluetooth_device" && deviceOf(profile) === "") return "condition.bluetooth_device.listUnset"
+ return null
+}
+
/** "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 {
- 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 editor's live sentence before a network or device is named; saved profiles always carry one.
+ const key = unsetKey(profile) ?? conditionOf(profile).listKey
+ return t(key, { speed: speedOf(profile), network: networkOf(profile), device: deviceOf(profile) })
}
/** The recording half; a stationary profile forces the distance to 0, so "any movement" would mislead. */
@@ -55,7 +63,11 @@ export function recordingPhrase(profile: ProfileLike): string {
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), network: networkOf(profile) })
+ condition: t(conditionOf(profile).clauseKey, {
+ speed: speedOf(profile),
+ network: networkOf(profile),
+ device: deviceOf(profile)
+ })
})
: conditionText(profile)
const parts = [condition, recordingClause(profile)]
diff --git a/apps/mobile/src/utils/setupConfig.ts b/apps/mobile/src/utils/setupConfig.ts
index d8f80871..51d1c9ce 100644
--- a/apps/mobile/src/utils/setupConfig.ts
+++ b/apps/mobile/src/utils/setupConfig.ts
@@ -66,6 +66,7 @@ const VALID_DAWARICH_MODES: DawarichMode[] = ["single", "batch"]
const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]
const VALID_PROFILE_CONDITIONS = PROFILE_CONDITIONS.map((c) => c.type)
+const BLUETOOTH_ADDRESS = /^[0-9A-F]{2}(:[0-9A-F]{2}){5}$/i
export function detectPreset(settings: Partial<Settings>): SyncPreset {
for (const [name, config] of Object.entries(TRACKING_PRESETS)) {
@@ -440,11 +441,26 @@ export function validateConfig(raw: unknown): ValidationResult {
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 needsDevice = condType === "bluetooth_device"
+ if (
+ needsDevice &&
+ (typeof condRaw.bluetoothAddress !== "string" || !BLUETOOTH_ADDRESS.test(condRaw.bluetoothAddress.trim()))
+ ) {
+ continue
+ }
const condition: TrackingProfile["condition"] = needsSpeed
? { type: condType, speedThreshold: condRaw.speedThreshold as number }
: needsSsid
? { type: condType, ssid: (condRaw.ssid as string).trim() }
- : { type: condType }
+ : needsDevice
+ ? {
+ type: condType,
+ bluetoothAddress: (condRaw.bluetoothAddress as string).trim().toUpperCase(),
+ ...(typeof condRaw.bluetoothName === "string" && condRaw.bluetoothName.trim() !== ""
+ ? { bluetoothName: condRaw.bluetoothName.trim() }
+ : {})
+ }
+ : { type: condType }
const delays = defaultProfileDelays(condType)
profiles.push({
diff --git a/fastlane/metadata/android/en-US/changelogs/53.txt b/fastlane/metadata/android/en-US/changelogs/53.txt
index 0399acc2..70054721 100644
--- a/fastlane/metadata/android/en-US/changelogs/53.txt
+++ b/fastlane/metadata/android/en-US/changelogs/53.txt
@@ -1,3 +1,4 @@
+- Tracking profiles can switch on a paired Bluetooth device, such as your car or headphones
- Less memory used when opening a day with many points and when sending a large upload backlog
- Fixed a trip's average speed and its speed and elevation charts being skewed towards stretches recorded with more points
- Positioning accuracy setting in Tracking & sync: High accuracy (default) or Lower accuracy to save battery