Colota - Android GPS Location tracker
fix(profiles): show Bluetooth off in the device picker (#979)
Max Dietrich9344b0e65972
diff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.mdindex 9f1d5f6c..f8db63ad 100644--- a/apps/docs/docs/development/permissions.md+++ b/apps/docs/docs/development/permissions.md@@ -21,6 +21,8 @@ These are the permissions Colota uses and why. None are related to analytics, ad| Boot Completed | Yes | Auto-restart tracking after device reboot || Notifications | Optional | Show the tracking notification (Android 13+) || Local Network Access | Android 17+ | Access local network servers (self-hosted) |+| Nearby Devices | Optional | Bluetooth device condition in tracking profiles (Android 12+) |+| Bluetooth | Optional | Bluetooth device condition on Android 11 and lower || Battery Optimization Exemption | Optional | Prevent Android from killing the tracking service || Wake Lock | Yes | Briefly wake the CPU for the stationary heartbeat and background jobs |@@ -37,6 +39,8 @@ Only the two location permissions are required. The app does not request anythinThe **Local Network Permission** (Android 17+) is not part of this sequence. It is requested separately when you use **Test connection** with a local/private server endpoint.+The **Nearby Devices** permission (Android 12+) is not part of the sequence either. The profile editor asks for it when you pick the **Bluetooth device** condition.+## Detailed Explanations### Location Permissions@@ -99,6 +103,15 @@ On some Android 16 devices, local network access may be enforced early via secur:::+### Nearby Devices++```+android.permission.BLUETOOTH_CONNECT+android.permission.BLUETOOTH+```++Only the **Bluetooth device** condition in tracking profiles uses it. On Android 12 and later, **Nearby devices** (`BLUETOOTH_CONNECT`) lets Colota list your paired devices and see when one connects or disconnects. Colota does not scan for devices or connect to any. On Android 11 and lower the older `BLUETOOTH` permission does the same and is granted at install. Without it the condition never matches.+### Battery Optimization```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.ktindex e4328dd4..83a7f6dd 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@@ -759,13 +759,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :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. */+ /** Resolves null while Bluetooth is off, since the paired list reads empty then, and an empty list without the Nearby devices permission. */@SuppressLint("MissingPermission")@ReactMethodfun getBondedBluetoothDevices(promise: Promise) {val array = Arguments.createArray()try {val adapter = (reactApplicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter+ if (adapter != null && !adapter.isEnabled) {+ promise.resolve(null)+ return+ }adapter?.bondedDevices.orEmpty().map { device ->val alias = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) device.alias else nulldiff --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.ktindex b4520b46..b3b63b97 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@@ -5,6 +5,9 @@package com.Colota.bridge+import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothManagerimport android.content.Contextimport android.content.Intentimport android.net.ConnectivityManager@@ -785,10 +788,58 @@ class LocationServiceModuleTest {assertEquals(3, map.captured.getInt("id"))}+ // ========================================================================+ // getBondedBluetoothDevices+ // ========================================================================++ @Test+ fun `getBondedBluetoothDevices resolves null while Bluetooth is off, since the paired list reads empty then`() {+ every { Arguments.createArray() } answers { JavaOnlyArray() }+ stubBluetooth(enabled = false, bonded = setOf(mockBluetoothDevice("Car", "aa:bb:cc:dd:ee:ff")))+ val promise = mockk<Promise>(relaxed = true)++ LocationServiceModule(mockContext).getBondedBluetoothDevices(promise)++ verify { promise.resolve(null) }+ }++ @Test+ fun `getBondedBluetoothDevices lists the paired devices by name with the address uppercased`() {+ every { Arguments.createArray() } answers { JavaOnlyArray() }+ stubBluetooth(enabled = true, bonded = setOf(mockBluetoothDevice("Car", "aa:bb:cc:dd:ee:ff")))+ val promise = mockk<Promise>(relaxed = true)++ LocationServiceModule(mockContext).getBondedBluetoothDevices(promise)++ verify {+ promise.resolve(match {+ val rows = it as JavaOnlyArray+ rows.size() == 1 &&+ rows.getMap(0)?.getString("name") == "Car" &&+ rows.getMap(0)?.getString("address") == "AA:BB:CC:DD:EE:FF"+ })+ }+ }+// ========================================================================// Helpers// ========================================================================+ private fun stubBluetooth(enabled: Boolean, bonded: Set<BluetoothDevice>) {+ val btAdapter = mockk<BluetoothAdapter> {+ every { isEnabled } returns enabled+ every { bondedDevices } returns bonded+ }+ every { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) } returns mockk<BluetoothManager> {+ every { adapter } returns btAdapter+ }+ }++ private fun mockBluetoothDevice(name: String, address: String) = mockk<BluetoothDevice> {+ every { [email protected] } returns name+ every { [email protected] } returns address+ }+private fun createModule(): LocationServiceModule {val unsafeClass = Class.forName("sun.misc.Unsafe")val unsafeField = unsafeClass.getDeclaredField("theUnsafe")diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.tsindex 035f67f1..d2931a45 100644--- a/apps/mobile/src/constants/index.ts+++ b/apps/mobile/src/constants/index.ts@@ -17,6 +17,8 @@ export const RETENTION_PREVIEW_DEBOUNCE_MS = 300/** The log file grows off-thread, so the size is read once after the toggle settles. */export const LOG_SIZE_SETTLE_MS = 2000+/** Quick Settings often closes before Bluetooth has turned on, so the paired list is read again after this. */+export const BLUETOOTH_REREAD_MS = 2000export const LOG_FILTER_DEBOUNCE_MS = 200export const RETENTION_PRESET_DAYS = [30, 90, 365]diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.jsonindex f2131fc2..cfb8e594 100644--- a/apps/mobile/src/i18n/locales/en.json+++ b/apps/mobile/src/i18n/locales/en.json@@ -745,8 +745,9 @@"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.off": "Bluetooth is off. Turn it on to see your paired devices.","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.permission": "Colota needs the Nearby devices permission to see your paired devices and when one connects. It doesn't search for new devices or connect to any.","profileEditor.bluetooth.unpaired": "No longer paired","profileEditor.create": "Create profile","profileEditor.deactivation": "Deactivation delay",diff --git a/apps/mobile/src/i18n/locales/es.json b/apps/mobile/src/i18n/locales/es.jsonindex 66b8f3d2..8c5da147 100644--- a/apps/mobile/src/i18n/locales/es.json+++ b/apps/mobile/src/i18n/locales/es.json@@ -745,8 +745,9 @@"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.off": "El Bluetooth está desactivado. Actívalo para ver tus dispositivos vinculados.","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.permission": "Colota necesita el permiso de dispositivos cercanos para ver tus dispositivos vinculados y saber cuándo se conecta uno. No busca dispositivos nuevos ni se conecta a ninguno.","profileEditor.bluetooth.unpaired": "Ya no está vinculado","profileEditor.create": "Crear perfil","profileEditor.deactivation": "Retraso de desactivación",diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsxindex 803b343b..7b0cbf82 100644--- a/apps/mobile/src/screens/ProfileEditorScreen.tsx+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx@@ -38,6 +38,7 @@ import { formatDuration, syncIntervalLabel } from "../utils/dashboardState"import { conditionOf, profileSentence } from "../utils/profileRow"import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"import {+ BLUETOOTH_REREAD_MS,PROFILE_CONDITIONS,SAVE_SUCCESS_DISPLAY_MS,defaultProfileDelays,@@ -78,6 +79,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst [currentSsid, setCurrentSsid] = useState("")const [btPermission, setBtPermission] = useState<BluetoothPermissionResult | null>(null)const [pairedDevices, setPairedDevices] = useState<BluetoothDeviceInfo[]>([])+ const [bluetoothOff, setBluetoothOff] = useState(false)// Survives a switch to another condition and back, like the typed network name.const [pickedDevice, setPickedDevice] = useState<BluetoothDeviceInfo | null>(null)const [text, setText] = useState({@@ -91,6 +93,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof})const [note, setNote] = useState<{ key: NumericKey; text: string } | null>(null)const noteTimer = useTimeout()+ const bluetoothReread = useTimeout()// Only fetched while the SSID field is open; the fallback keeps the offer button hidden.useEffect(() => {@@ -113,7 +116,9 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst 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() : [])+ const devices = granted ? await NativeLocationService.getBondedBluetoothDevices() : []+ setBluetoothOff(devices === null)+ setPairedDevices(devices ?? [])}, [])useEffect(() => {@@ -124,8 +129,17 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst sub = AppState.addEventListener("change", (state) => {if (state === "active") refreshPairedDevices()})- return () => sub.remove()- }, [profile.condition.type, refreshPairedDevices])+ // Quick Settings opens over the app without pausing it, so only a focus event follows a toggle there.+ const focusSub = AppState.addEventListener("focus", () => {+ refreshPairedDevices()+ bluetoothReread.set(refreshPairedDevices, BLUETOOTH_REREAD_MS)+ })+ return () => {+ sub.remove()+ focusSub.remove()+ bluetoothReread.clear()+ }+ }, [profile.condition.type, refreshPairedDevices, bluetoothReread])useLayoutEffect(() => {navigation.setOptions({ headerTitle: isEditing ? t("profileEditor.titleEdit") : t("profileEditor.titleNew") })@@ -231,7 +245,7 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profconst deviceRows =pickedDevice && !pairedDevices.some((d) => d.address === pickedDevice.address)? [- { ...pickedDevice, unpaired: btPermission === "granted" },+ { ...pickedDevice, unpaired: btPermission === "granted" && !bluetoothOff },...pairedDevices.map((d) => ({ ...d, unpaired: false }))]: pairedDevices.map((d) => ({ ...d, unpaired: false }))@@ -434,7 +448,10 @@ export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Prof/></>)}- {btPermission === "granted" && pairedDevices.length === 0 && (+ {btPermission === "granted" && bluetoothOff && (+ <FieldMessage>{t("profileEditor.bluetooth.off")}</FieldMessage>+ )}+ {btPermission === "granted" && !bluetoothOff && pairedDevices.length === 0 && (<FieldMessage>{t("profileEditor.bluetooth.noDevices")}</FieldMessage>)}{deviceRows.length > 0 && (diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsxindex 74beb597..aa8dfc60 100644--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx@@ -1,7 +1,7 @@import React from "react"import { render, fireEvent, waitFor, act } from "@testing-library/react-native"import { TrackingProfile } from "../../types/global"-import { SAVE_SUCCESS_DISPLAY_MS } from "../../constants"+import { BLUETOOTH_REREAD_MS, SAVE_SUCCESS_DISPLAY_MS } from "../../constants"const mockProfiles: TrackingProfile[] = [{@@ -416,6 +416,39 @@ describe("ProfileEditorScreen", () => {expect(await findByText("No paired devices. Pair one in Bluetooth settings, then come back.")).toBeTruthy()})+ // null is the bridge's answer while Bluetooth is off.+ it("shows Bluetooth as off, not the saved device as unpaired", async () => {+ mockGetBondedBluetoothDevices.mockResolvedValue(null)+ const { findByText, getByTestId, queryByText } = renderEdit(3)++ expect(await findByText("Bluetooth is off. Turn it on to see your paired devices.")).toBeTruthy()+ expect(getByTestId("bluetooth-device-00:11:22:33:44:55").props.accessibilityState.checked).toBe(true)+ expect(queryByText("No longer paired")).toBeNull()+ expect(queryByText("No paired devices. Pair one in Bluetooth settings, then come back.")).toBeNull()+ })++ // The shade closes while Bluetooth is still turning on, so the read on focus still finds it off.+ it("reads the paired devices again after Quick Settings closes", async () => {+ const { AppState } = require("react-native")+ mockGetBondedBluetoothDevices.mockResolvedValueOnce(null).mockResolvedValueOnce(null)+ const { getByTestId, findByText, findByTestId, queryByTestId } = renderNew()+ fireEvent.press(getByTestId("condition-bluetooth_device"))+ await findByText("Bluetooth is off. Turn it on to see your paired devices.")++ jest.useFakeTimers()+ const onFocus = (AppState.addEventListener as jest.Mock).mock.calls+ .filter((call: unknown[]) => call[0] === "focus")+ .at(-1)[1]+ await act(async () => onFocus())+ expect(queryByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).toBeNull()++ await act(async () => {+ jest.advanceTimersByTime(BLUETOOTH_REREAD_MS)+ })+ jest.useRealTimers()+ expect(await findByTestId("bluetooth-device-AA:BB:CC:DD:EE:FF")).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")diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 597d4e98..fd2f9607 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -666,11 +666,11 @@ class NativeLocationService {}/**- * Returns the paired Bluetooth devices, or an empty list without the Nearby devices permission.+ * Returns the paired Bluetooth devices, null while Bluetooth is off, or an empty list without the Nearby devices permission.*/- static async getBondedBluetoothDevices(): Promise<BluetoothDeviceInfo[]> {+ static async getBondedBluetoothDevices(): Promise<BluetoothDeviceInfo[] | null> {this.ensureModule()- return this.safeExecute(+ return this.safeExecute<BluetoothDeviceInfo[] | null>(() => LocationServiceModule.getBondedBluetoothDevices(),[],"getBondedBluetoothDevices failed"diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 0a73ee89..4b3ef36f 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -88,7 +88,8 @@ jest.mock("react-native", () => ({getProfiles: jest.fn().mockResolvedValue([]),createProfile: jest.fn().mockResolvedValue(3),updateProfile: jest.fn().mockResolvedValue(true),- deleteProfile: jest.fn().mockResolvedValue(true)+ deleteProfile: jest.fn().mockResolvedValue(true),+ getBondedBluetoothDevices: jest.fn().mockResolvedValue([])},BuildConfigModule: {VERSION_NAME: "1.0.0",@@ -612,6 +613,18 @@ describe("NativeLocationService", () => {})})+ describe("getBondedBluetoothDevices", () => {+ it("passes null through, so the editor can tell Bluetooth off from no paired devices", async () => {+ nativeMock.getBondedBluetoothDevices.mockResolvedValueOnce(null)+ expect(await NativeLocationService.getBondedBluetoothDevices()).toBeNull()+ })++ it("returns an empty list when the native call fails", async () => {+ nativeMock.getBondedBluetoothDevices.mockRejectedValueOnce(new Error("Native error"))+ expect(await NativeLocationService.getBondedBluetoothDevices()).toEqual([])+ })+ })+describe("deleteLocationsByIds", () => {it("passes the ids to the native module", async () => {const deleted = await NativeLocationService.deleteLocationsByIds([12, 34])