RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
USB: pick which WiFi, Bluetooth and SDR adapter to use, with a popup when several are plugged in
CIS-C09449c1cd3224
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex 6656534..5425f9b 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -107,7 +107,7 @@ object SdrRadio {@Volatile var onAircraft: ((List<com.rfsentinel.app.online.PoliceAircraft.Plane>, List<String>) -> Unit)? = nullfun isSdr(d: UsbDevice) = RtlSdr.isRtlSdr(d.vendorId, d.productId) || HackRf.isHackRf(d.vendorId, d.productId)- private fun labelOf(d: UsbDevice) = if (HackRf.isHackRf(d.vendorId, d.productId)) "HackRF" else "RTL-SDR"+ fun labelOf(d: UsbDevice) = if (HackRf.isHackRf(d.vendorId, d.productId)) "HackRF" else "RTL-SDR"@Synchronizedfun start(context: Context, events: (RadioWatch.Event) -> Unit) {@@ -181,7 +181,13 @@ object SdrRadio {UsbWifi.log("$deviceLabel: $name is gone - starting over")halt("")}- val d = runCatching { mgr.deviceList.values.firstOrNull { isSdr(it) } }.getOrNull() ?: return+ val all = runCatching { mgr.deviceList.values.toList() }.getOrDefault(emptyList())+ val d = com.rfsentinel.app.usb.UsbPick.pick(context, com.rfsentinel.app.usb.UsbPick.Kind.SDR, all) ?: run {+ com.rfsentinel.app.usb.UsbPick.waitingFor(context, com.rfsentinel.app.usb.UsbPick.Kind.SDR, all)?.let {+ status = "SDR: waiting for $it, picked in Settings"+ }+ return+ }deviceLabel = labelOf(d)if (!mgr.hasPermission(d)) {UsbWifi.log("%04x:%04x ($deviceLabel) plugged in - asking for USB access".format(d.vendorId, d.productId))diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 5b81018..ebf79e7 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -20,6 +20,7 @@ import com.rfsentinel.app.databinding.ActivitySettingsBindingimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.oui.OuiWatchlistimport com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.usb.UsbPickimport com.rfsentinel.app.util.Prefsimport com.rfsentinel.app.util.applySystemBarInsetsimport kotlinx.coroutines.launch@@ -399,6 +400,41 @@ class SettingsActivity : AppCompatActivity() {}}+ /** External hardware: the drop-downs picking which adapter each driver uses ([com.rfsentinel.app.usb.UsbPick]). */+ private val usbPickRows = ArrayList<View>()++ /** Rebuilt on every return to Settings, so they list what's plugged in now. */+ private fun updateUsbPickers() {+ usbPickRows.forEach { (it.parent as? android.view.ViewGroup)?.removeView(it) }+ usbPickRows.clear()+ val all = runCatching { getSystemService(android.hardware.usb.UsbManager::class.java)?.deviceList?.values?.toList() }+ .getOrNull().orEmpty()+ fun add(kind: UsbPick.Kind, under: View, label: String, about: String) {+ val saved = Prefs.usbPick(this, kind.key)+ val ids = mutableListOf<String?>(null)+ val names = mutableListOf("Auto")+ UsbPick.candidates(kind, all).distinctBy { UsbPick.id(it) }.forEach { ids += UsbPick.id(it); names += UsbPick.label(it) }+ if (saved != null && saved !in ids) { ids += saved; names += "${Prefs.usbPickName(this, kind.key) ?: saved} · unplugged" }+ val row = choiceRow(label, names, ids.indexOf(saved)) { i ->+ if (ids[i] == Prefs.usbPick(this, kind.key)) return@choiceRow+ Prefs.setUsbPick(this, kind.key, ids[i], names[i].removeSuffix(" · unplugged"))+ if (kind == UsbPick.Kind.BT) com.rfsentinel.app.usb.UsbBluetooth.pickChanged(this)+ }+ val parent = under.parent as android.view.ViewGroup+ val at = parent.indexOfChild(under) + 1+ parent.addView(row, at)+ info(row, "$about Only one runs at a time. Two of the same model can't be told apart: the first one found is used.", label)+ usbPickRows += parent.getChildAt(at)+ }+ add(UsbPick.Kind.WIFI, binding.usbWifiText, "WiFi adapter", "Which USB WiFi adapter to use when more than one is " ++ "plugged in. Auto takes the first one found. A new pick starts the next time scanning starts.")+ add(UsbPick.Kind.BT, binding.usbBtText, "Bluetooth adapter", "Which USB Bluetooth adapter to use when more than one is " ++ "plugged in. A combo WiFi + Bluetooth adapter (like the ALFA AWUS036AXML) only has the small antenna inside its " ++ "case for Bluetooth, so Auto takes a Bluetooth-only dongle first. A new pick takes over right away while scanning.")+ add(UsbPick.Kind.SDR, binding.sdrStatusText, "SDR", "Which RTL-SDR or HackRF to use when more than one is plugged in. " ++ "Auto takes the first one found. A new pick starts the next time scanning starts.")+ }+private fun updateEspStatus() {val s = com.rfsentinel.app.esp.EspBoards.statusbinding.espStatusText.text = s.ifBlank { "ESP32 board on USB: not connected" }@@ -2787,6 +2823,7 @@ class SettingsActivity : AppCompatActivity() {// Back from the theme maker: its themes may have changed.if (loaded) buildThemeList()updatePcap()+ updateUsbPickers()// The user may be coming back from Developer options.updateWifiThrottleHint()showNote(aircraftStatusText, com.rfsentinel.app.online.OnlineWatch.aircraftStatus)diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.ktindex d096e2b..d71b5d3 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.kt@@ -131,6 +131,12 @@ object UsbBluetooth {/** Tries again (firmware just downloaded, or the setting turned back on). */fun retry(context: Context) { if (receiver != null) connect(context.applicationContext) }+ /** Settings › External hardware: another adapter was picked; switches to it now while scanning. */+ fun pickChanged(context: Context) {+ if (runningDevice != null) stopAdapter("")+ retry(context)+ }+/** Settings › External hardware: the switch was flipped while scanning. */fun settingChanged(context: Context) {if (com.rfsentinel.app.util.Prefs.usbBluetooth(context)) retry(context)@@ -148,10 +154,14 @@ object UsbBluetooth {val mgr = context.getSystemService(UsbManager::class.java) ?: returnval all = runCatching { mgr.deviceList.values.toList() }.getOrDefault(emptyList())// Not RTL-SDR / HackRF sticks, which have no Bluetooth interface anyway.- val d = all.firstOrNull { btInterface(it) != null } ?: run { if (firmwareNeeded == null) status = ""; return }+ val d = UsbPick.pick(context, UsbPick.Kind.BT, all) ?: run {+ status = UsbPick.waitingFor(context, UsbPick.Kind.BT, all)?.let { "USB Bluetooth: waiting for $it, picked in Settings" }+ ?: if (firmwareNeeded == null) "" else status+ return+ }if (!mgr.hasPermission(d)) {- // The WiFi side of a combo adapter asks for access itself: one prompt, not two.- if (!ask || UsbWifi.chipOf(d) != null) { status = "USB Bluetooth found - allow USB access on the prompt"; return }+ // The WiFi side of a combo adapter asks for access itself, when it uses that adapter: one prompt, not two.+ if (!ask || UsbPick.chosen(context, UsbPick.Kind.WIFI, all)?.deviceName == d.deviceName) { status = "USB Bluetooth found - allow USB access on the prompt"; return }UsbWifi.log("BT: %04x:%04x plugged in - asking for USB access".format(d.vendorId, d.productId))val pi = PendingIntent.getBroadcast(context, 2, Intent(ACTION_PERMISSION).setPackage(context.packageName),PendingIntent.FLAG_MUTABLE)diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbPick.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbPick.ktnew file mode 100644index 0000000..23498a6--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbPick.kt@@ -0,0 +1,71 @@+package com.rfsentinel.app.usb++import android.content.Context+import android.hardware.usb.UsbDevice+import android.widget.Toast+import com.rfsentinel.app.sdr.SdrRadio+import com.rfsentinel.app.util.Prefs++/**+ * Settings › External hardware: which plugged-in adapter each driver uses when several of a kind are plugged in.+ * Saved by USB ID ("0bda:8771"). Auto takes the first one found - for Bluetooth, a Bluetooth-only dongle before the+ * Bluetooth side of a combo WiFi adapter, which only has the antenna inside its case.+ */+object UsbPick {++ enum class Kind(val key: String, val what: String) {+ WIFI("wifi", "WiFi adapters"), BT("bt", "Bluetooth adapters"), SDR("sdr", "SDRs")+ }++ fun id(d: UsbDevice) = "%04x:%04x".format(d.vendorId, d.productId)++ /** What [kind]'s driver can use, Auto's choice first. */+ fun candidates(kind: Kind, all: Collection<UsbDevice>): List<UsbDevice> = when (kind) {+ Kind.WIFI -> all.filter { UsbWifi.chipOf(it) != null }+ Kind.BT -> all.filter { UsbBluetooth.btInterface(it) != null }.sortedBy { UsbWifi.chipOf(it) != null }+ Kind.SDR -> all.filter { SdrRadio.isSdr(it) }+ }++ /** The saved device if it's plugged in (else null); with nothing saved (Auto), the first of [list]. */+ internal fun <T> choose(list: List<T>, saved: String?, id: (T) -> String): T? =+ if (saved == null) list.firstOrNull() else list.firstOrNull { id(it) == saved }++ /** The device [kind]'s driver should use, without telling anyone. */+ fun chosen(context: Context, kind: Kind, all: Collection<UsbDevice>): UsbDevice? =+ choose(candidates(kind, all), Prefs.usbPick(context, kind.key), ::id)++ /** [chosen], with a short popup the first time several of [kind] are plugged in together. */+ fun pick(context: Context, kind: Kind, all: Collection<UsbDevice>): UsbDevice? {+ val list = candidates(kind, all)+ val d = choose(list, Prefs.usbPick(context, kind.key), ::id)+ if (d != null && list.size > 1) tellOnce(context, kind, list, d)+ return d+ }++ /** The saved device's name when it's unplugged but others of [kind] are in: the driver waits for it. */+ fun waitingFor(context: Context, kind: Kind, all: Collection<UsbDevice>): String? {+ val saved = Prefs.usbPick(context, kind.key) ?: return null+ val list = candidates(kind, all)+ return if (list.isNotEmpty() && list.none { id(it) == saved }) Prefs.usbPickName(context, kind.key) ?: saved else null+ }++ /** "ALFA AWUS036AXML · MT7921AU"; the maker's name is only readable once USB access is allowed. */+ fun label(d: UsbDevice): String {+ val name = runCatching { listOfNotNull(d.manufacturerName, d.productName).joinToString(" ") }.getOrDefault("")+ val chip = UsbWifi.chipOf(d)?.name ?: if (SdrRadio.isSdr(d)) SdrRadio.labelOf(d) else null+ return listOfNotNull(name.ifBlank { null }, chip).joinToString(" · ").ifBlank { "USB device ${id(d)}" }+ }++ private val told = HashMap<Kind, String>()+ private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }++ @Synchronized+ private fun tellOnce(context: Context, kind: Kind, list: List<UsbDevice>, d: UsbDevice) {+ val key = list.joinToString { it.deviceName } + ">" + d.deviceName+ if (told[kind] == key) return+ told[kind] = key+ val msg = "${list.size} ${kind.what} plugged in · using ${label(d)}. Pick one in Settings › External hardware"+ val app = context.applicationContext+ main.post { Toast.makeText(app, msg, Toast.LENGTH_LONG).show() }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.ktindex 109f018..64be470 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt@@ -331,8 +331,9 @@ object UsbWifi {if (runningDevice != null) returnval mgr = context.getSystemService(UsbManager::class.java) ?: returnval all = runCatching { mgr.deviceList.values.toList() }.getOrDefault(emptyList())- val d = all.firstOrNull { chipOf(it) != null }+ val d = UsbPick.pick(context, UsbPick.Kind.WIFI, all)if (d == null) {+ UsbPick.waitingFor(context, UsbPick.Kind.WIFI, all)?.let { status = "USB WiFi: waiting for $it, picked in Settings"; return }val known = all.firstOrNull { knownOnly(it) != null }val newStatus = known?.let { "USB WiFi adapter (${knownOnly(it)}) found - this chip isn't supported yet" }.orEmpty()if (known != null && newStatus != status) log("%04x:%04x (%s) plugged in: not supported yet".format(known.vendorId, known.productId, knownOnly(known)))diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex cf64949..285caff 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -682,6 +682,14 @@ object Prefs {/** Scan Bluetooth with a USB adapter's Bluetooth part (dongle or combo adapter). */fun usbBluetooth(context: Context): Boolean = bool(context, "usb_bluetooth", true)fun setUsbBluetooth(context: Context, value: Boolean) = setBool(context, "usb_bluetooth", value)+ /** The USB ID of the adapter picked for [kind] ("wifi", "bt", "sdr"), null for Auto ([com.rfsentinel.app.usb.UsbPick]). */+ fun usbPick(context: Context, kind: String): String? = sp(context).getString("usb_pick_$kind", null)+ /** Its name, shown while it's unplugged. */+ fun usbPickName(context: Context, kind: String): String? = sp(context).getString("usb_pick_name_$kind", null)+ fun setUsbPick(context: Context, kind: String, id: String?, name: String?) = sp(context).edit {+ if (id == null) { remove("usb_pick_$kind"); remove("usb_pick_name_$kind") }+ else { putString("usb_pick_$kind", id); putString("usb_pick_name_$kind", name) }+ }fun setRtl8821au5g(context: Context, value: Boolean) = setBool(context, "rtl8821au_5g", value)/** Hide trusted (whitelisted) devices from the live list and radar (off by default). */diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.ktindex 5a6cb95..afdfa02 100644--- a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt+++ b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt@@ -69,7 +69,7 @@ class WazeScreensTest {// Waze alone adds four: alert range, map range, and one interval slider per source.assertTrue("sliders: ${sliders.size}", sliders.size >= 4)sliders.forEach { it.measure(exactly, atMost) } // throws if a value does not fit its steps- assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().count { it.contentDescription !in setOf("Snooze length", "Swipe right on an alert", "Swipe left on an alert", "Re-center after", "Alert from") })+ assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().count { it.contentDescription !in setOf("Snooze length", "Swipe right on an alert", "Swipe left on an alert", "Re-center after", "Alert from", "WiFi adapter", "Bluetooth adapter", "SDR") })val text = views.filterIsInstance<TextView>().joinToString("\n") { it.text }assertTrue(text.contains("Alert when a report is within"))assertTrue(text.contains("Show reports on the map within"))diff --git a/app/src/test/java/com/rfsentinel/app/usb/UsbPickTest.kt b/app/src/test/java/com/rfsentinel/app/usb/UsbPickTest.ktnew file mode 100644index 0000000..9ba7344--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/UsbPickTest.kt@@ -0,0 +1,17 @@+package com.rfsentinel.app.usb++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++class UsbPickTest {++ @Test+ fun theSavedAdapterOrNothingAutoTakesTheFirst() {+ val plugged = listOf("0e8d:7961", "0bda:8771") // a combo WiFi adapter and a Bluetooth dongle+ assertEquals("0e8d:7961", UsbPick.choose(plugged, null) { it })+ assertEquals("0bda:8771", UsbPick.choose(plugged, "0bda:8771") { it })+ // The picked one is unplugged: wait for it, never fall back to another.+ assertNull(UsbPick.choose(plugged, "2357:0138") { it })+ }+}