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
2.31.0: USB Bluetooth adapters as a second BLE scanner, per-category alert ways, saved device pages, USB restart fixes; version 2.31.0 (63)
CIS-C0e792ded5ccca
diff --git a/README.md b/README.mdindex d2e5082..79d8daa 100644--- a/README.md+++ b/README.md@@ -178,7 +178,7 @@ Everything the app does, grouped by area.- **Fake cell tower signs** checked every 15 s, with persistence, call and border suppression (modelled on [EFF's Rayhunter](https://github.com/EFForg/rayhunter) as far as Android allows without root)- **Hidden WiFi networks** identified from WPS data, Cisco AP names and vendor elements, and linked to the visible network on the same router- Ordinary devices named precisely: exact AirPods / Beats model, device class, IEEE registrant; decoded Apple Continuity, iBeacon, Eddystone, Fast Pair-- Editable **watchlist** (exact addresses, prefixes of 24 to 44 bits picked with a slider, name, *name starts with*, vendor and Bluetooth advert-pattern rules; search, export and undo) with Global, Canada, US, France, UK, Portugal, Germany, Spain and Italy presets; per-category on/off switches+- Editable **watchlist** (exact addresses, prefixes of 24 to 44 bits picked with a slider, name, *name starts with*, vendor and Bluetooth advert-pattern rules; search, export and undo) with Global, Canada, US, France, UK, Portugal, Germany, Spain and Italy presets; per-category on/off switches, and for each category which ways it alerts you (banner, sound, voice, vibration, radar beep)- Bluetooth 5 extended advertising and LE Coded (long range) where the phone supports it- **I saw it:** on a device's page, tell the app what it is (e.g. pole camera on the bridge) and it learns that device - its exact address, and its Bluetooth advert pattern or WiFi probe fingerprint so it's recognised after its address changes. Patterns many devices share are refused, and a learned pattern only ever counts as probable- **Probe-rate clue** (USB WiFi adapter): non-stop wildcard probing from one fixed address backs up a fixed-camera match, shown on the device page@@ -222,7 +222,7 @@ Everything the app does, grouped by area.- **Sightings map:** on a device's page, every spot that device was heard, joined in time order for each encounter- The main screen's map and the full screen map show the same view (place, zoom, heading, tilt, following you) and the same place card and routes- **Snapshots:** menu ⋮ → *Save snapshot* keeps the device list exactly as shown, to look at again later (History → *Snapshots*, beside the recorded traces), on the map, or exported-- **Device history:** every device the app remembers, in range or not, searchable by address (with or without colons), name, vendor, type, your own name for it or your note, filtered to favorites, flagged before or seen today; tap one for its details page. History is kept as long as you set in Settings → Data+- **Device history:** every device the app remembers, in range or not, searchable by address (with or without colons), name, vendor, type, your own name for it or your note, filtered to favorites, flagged before or seen today; tap one for its details page, which shows everything it showed the last time the device was heard (identity, matches, Remote ID, raw data). History is kept as long as you set in Settings → Data</details>@@ -242,6 +242,7 @@ Everything the app does, grouped by area.- ESP32 boards over USB OTG (OUI-Spy, GhostESP, Marauder incl. dual-band ESP32-C5 boards, or through a Flipper Zero) or Bluetooth (OUI-SPY App-Controlled) add their detections and extend range- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812AU** (e.g. ALFA AWUS036ACH, 2.4 + 5 GHz, experimental), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **MT7921AU** (ALFA AWUS036AXML / AXM, WiFi 6E: 2.4 + 5 + **6 GHz**), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically- **Requested networks:** the WiFi names nearby devices ask for (probe requests), from a USB adapter or a Marauder board, in an optional list; **watch** a name to get an alert whenever any device asks for it+- **USB Bluetooth adapters** as a second Bluetooth LE scanner, no root: the Bluetooth part of an MT7921AU, RTL8821AU or RTL8822BU combo adapter, or a USB Bluetooth dongle (standard controllers, Realtek RTL8761B / 8761C and others), listening only, with LE Coded long range where the chip has it; devices it hears get a **USB BT** badge (Settings → External hardware)- **Record frames to .pcap** for Wireshark (Settings → External hardware): every frame a USB WiFi adapter or V2X board hears, with its channel and signal- The ALFA AWUS036ACS's light blinks with received traffic (Settings → External hardware switches it off, for the adapters whose light the app can control)- RTL-SDR and HackRF transmissions show on the **radar** too, for a minute after they were last heard@@ -352,7 +353,7 @@ A threat banner, the live list of everything in range, and the radar and map vie- **Scrolled to the top**, the list stays there as alerts arrive; scrolled down,a *New alert* pill takes you up.- **Filters and search:** All, Flagged, Trackers, Drones, Favorites, New,- Bluetooth, WiFi, Cells, External (heard by an ESP32 board or a USB WiFi+ Bluetooth, WiFi, Cells, External (heard by an ESP32 board, a USB Bluetooth adapter or a USB WiFiadapter), and by kind: Vehicles, Phones, Computers, Audio, Cameras, Routers,Hotspots, TVs & consoles, Smart home, Apple and Other (none of those). Adevice's kind comes from every clue: type, name, maker, WPS model and@@ -673,18 +674,35 @@ MT7921AU, 6 GHz on its 15 preferred scanning channels, where access points beacogo through RF Sentinel's own rules like everything else, with a purple**USB WIFI** badge.-| Chip | Example adapters | Status |+**USB Bluetooth:** the Bluetooth part of a combo WiFi + Bluetooth adapter+(MT7921AU, RTL8821AU, RTL8822BU), or a plain USB Bluetooth dongle (standard+controllers, Realtek RTL8761B / 8761C / 8723B / 8821C / 8822B and similar),+works as a second Bluetooth LE scanner next to the phone's own, listening only+(LE 1M, and LE Coded long range where the chip has it). Its devices get a+**USB BT** badge and count as external hardware. On a combo adapter WiFi and+Bluetooth share the antennas. Turn it off in **Settings → External hardware →+Scan Bluetooth with a USB adapter** to leave the adapter to WiFi only.+Realtek RTL8822CU / 8852 and Intel dongles aren't supported yet.++| Bluetooth chip | In RF Sentinel | Dongles with this chip ||---|---|---|-| Realtek RTL8811AU / RTL8821AU (`0bda:0811`) | ALFA AWUS036ACS | Supported (2.4 GHz; 5 GHz experimental, opt-in) |-| Realtek RTL8812AU (`0bda:8812`, `0bda:881a` and ~30 other IDs) | ALFA AWUS036ACH, TP-Link Archer T4U / T4UH, Netgear A6200v2, Edimax | Experimental (2.4 + 5 GHz): written from the Realtek driver, not yet tested on a real adapter |-| Realtek RTL8812BU / RTL8822BU (`0bda:b812`, `0bda:b82c` and ~35 other IDs) | TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, Wise Tiger AC1200 | Supported (2.4 + 5 GHz), tested on a Wise Tiger 8812BU |-| Realtek RTL8814AU (`0bda:8813` and 13 other IDs) | ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000 | Supported (2.4 + 5 GHz), not yet tested on hardware |-| MediaTek MT7612U / MT7632U (`0e8d:7612` and 16 other IDs) | ALFA AWUS036ACM, ASUS USB-AC55, Netgear A6210 | Supported (2.4 + 5 GHz), tested on an ALFA AWUS036ACM |-| MediaTek MT7921AU (`0e8d:7961` and 4 other IDs) | ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH | Supported (2.4 + 5 + 6 GHz), tested on an ALFA AWUS036AXML / AXM |-| Realtek RTL8187L / RTL8187B (`0bda:8187` and 20 other IDs) | ALFA AWUS036H, Netgear WG111v2/v3 | Supported (2.4 GHz), tested on an ALFA AWUS036H |-| Ralink RT3070 (`148f:3070` and 4 other IDs) | ALFA AWUS036NH / AWUS036NEH | Supported (2.4 GHz), tested on an ALFA AWUS036NEH |-| Atheros AR9271 (`0cf3:9271` and 17 other IDs) | ALFA AWUS036NHA, TP-Link TL-WN722N v1 | Experimental (2.4 GHz) |-| RTL8811CU / 8821CU, RT5370, MT7610U, AR7010 | | Detected and named, not supported yet |+| Generic USB Bluetooth (any standard controller, class e0) | Used, no firmware needed | CSR8510 A10 dongles and clones (TP-Link UB400, Avantree DG40S, many no-name "Bluetooth 4.0" dongles), Broadcom / Cypress BCM20702 (ASUS USB-BT400, Plugable USB-BT4LE, Kinivo BTD-400, IOGEAR GBU521) |+| Realtek RTL8761B / RTL8761C | Used, Realtek firmware | TP-Link UB500, ASUS USB-BT500, UGREEN CM390 / CM591, Maxuni and other "Bluetooth 5.0 / 5.1 / 5.3" dongles |+| Realtek RTL8723BU / 8821CU combo | Used, Realtek firmware | Edimax EW-7611ULB, many WiFi + Bluetooth nano adapters |+| Intel, RTL8822CU / 8852, Qualcomm with firmware | Not yet | Intel AX200 / AX210 USB kits, newer RTL8852-based dongles |++| Chip | WiFi in RF Sentinel | Bluetooth | Status | Adapters with this chip | USB IDs |+|---|---|---|---|---|---|+| Realtek RTL8811AU / RTL8821AU | 2.4 GHz (5 GHz experimental, opt-in) | 8821AU: Bluetooth 4.0 used (opt-out), not yet tested; 8811AU none | Supported | ALFA AWUS036ACS | `0bda:0811` |+| Realtek RTL8812AU | 2.4 + 5 GHz | None | Experimental: written from the Realtek driver, not yet tested on a real adapter | ALFA AWUS036ACH, TP-Link Archer T4U / T4UH, Netgear A6200v2, Linksys WUSB6300, Buffalo WI-U3-866D, Tenda U12, ASUS, D-Link, Edimax, TRENDnet, Belkin, ZyXEL, EnGenius, Planex, I-O DATA | `0bda:8812`, `0bda:881a` and ~30 other IDs |+| Realtek RTL8812BU / RTL8822BU | 2.4 + 5 GHz | 8822BU: Bluetooth used (opt-out), not yet tested; 8812BU none | Supported, tested on a Wise Tiger 8812BU | TP-Link Archer T3U / T4U v3, ASUS USB-AC53 / AC55 / AC58, Edimax EW-7822U*, Netgear A6150, Linksys WUSB6400M / WUSB3600 v2, Wise Tiger AC1200, D-Link, TRENDnet, Buffalo | `0bda:b812`, `0bda:b82c` and ~35 other IDs |+| Realtek RTL8814AU | 2.4 + 5 GHz | None | Supported, not yet tested on hardware | ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000, Edimax, ELECOM, D-Link, TRENDnet | `0bda:8813` and 13 other IDs |+| MediaTek MT7612U / MT7632U | 2.4 + 5 GHz | Not used | Supported, tested on an ALFA AWUS036ACM | ALFA AWUS036ACM, ASUS USB-AC54 / AC55 / N53 B1, Netgear A6210 / WNDA3100v3, Aukey USB-AC1200, Xbox One wireless adapter, TP-Link, Edimax, ELECOM | `0e8d:7612` and 16 other IDs |+| MediaTek MT7921AU (WiFi 6E) | 2.4 + 5 + 6 GHz | Bluetooth 5.2 used (opt-out, LE Coded long range), not yet tested | Supported, tested on an ALFA AWUS036AXML / AXM | ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH | `0e8d:7961` and 4 other IDs |+| Realtek RTL8187L / RTL8187B | 2.4 GHz | None | Supported, tested on an ALFA AWUS036H | ALFA AWUS036H, Netgear WG111v2 / v3, ASUS, HP, Belkin | `0bda:8187` and 20 other IDs |+| Ralink RT3070 | 2.4 GHz | None | Supported, tested on an ALFA AWUS036NEH | ALFA AWUS036NH / AWUS036NEH, Edimax | `148f:3070` and 4 other IDs |+| Atheros AR9271 | 2.4 GHz | None | Experimental | ALFA AWUS036NHA, TP-Link TL-WN722N v1, Netgear WNA1100, D-Link DWA-126 | `0cf3:9271` and 17 other IDs |+| RTL8811CU / 8821CU / 8812CU, RT5370 / 5372, RT3071 / 3072, MT7610U, AR7010 | Not yet | Not used | Detected and named, not supported yet | | |<details><summary><b>Receive-only, the adapter log and single-antenna dongles</b></summary>diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 9bfbdec..eb37e81 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -7,8 +7,8 @@ plugins {}// Bump both for every release. versionName ends up in the APK file name.-val appVersionCode = 62-val appVersionName = "2.30.2"+val appVersionCode = 63+val appVersionName = "2.31.0"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.diff --git a/app/src/full/assets/usbwifi/BT_RAM_CODE_MT7961_1_2_hdr.bin b/app/src/full/assets/usbwifi/BT_RAM_CODE_MT7961_1_2_hdr.binnew file mode 100644index 0000000..7fe2337Binary files /dev/null and b/app/src/full/assets/usbwifi/BT_RAM_CODE_MT7961_1_2_hdr.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8723b_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8723b_fw.binnew file mode 100644index 0000000..49b2a26Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8723b_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8761a_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8761a_fw.binnew file mode 100644index 0000000..ee4f201Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8761a_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8761bu_config.bin b/app/src/full/assets/usbwifi/bt_rtl8761bu_config.binnew file mode 100644index 0000000..91d3f44Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8761bu_config.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8761bu_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8761bu_fw.binnew file mode 100644index 0000000..1dc433eBinary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8761bu_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8761cu_config.bin b/app/src/full/assets/usbwifi/bt_rtl8761cu_config.binnew file mode 100644index 0000000..018dcf9Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8761cu_config.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8761cu_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8761cu_fw.binnew file mode 100644index 0000000..475320dBinary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8761cu_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8821a_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8821a_fw.binnew file mode 100644index 0000000..c7dffe9Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8821a_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8821c_config.bin b/app/src/full/assets/usbwifi/bt_rtl8821c_config.binnew file mode 100644index 0000000..bb15fcdBinary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8821c_config.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8821c_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8821c_fw.binnew file mode 100644index 0000000..e1e7820Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8821c_fw.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8822b_config.bin b/app/src/full/assets/usbwifi/bt_rtl8822b_config.binnew file mode 100644index 0000000..b00270eBinary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8822b_config.bin differdiff --git a/app/src/full/assets/usbwifi/bt_rtl8822b_fw.bin b/app/src/full/assets/usbwifi/bt_rtl8822b_fw.binnew file mode 100644index 0000000..5a46461Binary files /dev/null and b/app/src/full/assets/usbwifi/bt_rtl8822b_fw.bin differdiff --git a/app/src/main/assets/usbwifi/LICENCE.rtlwifi_firmware.txt b/app/src/main/assets/usbwifi/LICENCE.rtlwifi_firmware.txtnew file mode 100644index 0000000..d70921f--- /dev/null+++ b/app/src/main/assets/usbwifi/LICENCE.rtlwifi_firmware.txt@@ -0,0 +1,39 @@+Copyright (c) 2010, Realtek Semiconductor Corporation+All rights reserved.++Redistribution. Redistribution and use in binary form, without+modification, are permitted provided that the following conditions are+met:++* Redistributions must reproduce the above copyright notice and the+ following disclaimer in the documentation and/or other materials+ provided with the distribution.+* Neither the name of Realtek Semiconductor Corporation nor the names of its+ suppliers may be used to endorse or promote products derived from this+ software without specific prior written permission.+* No reverse engineering, decompilation, or disassembly of this software+ is permitted.++Limited patent license. Realtek Semiconductor Corporation grants a world-wide,+royalty-free, non-exclusive license under patents it now or hereafter+owns or controls to make, have made, use, import, offer to sell and+sell ("Utilize") this software, but solely to the extent that any+such patent is necessary to Utilize the software alone, or in+combination with an operating system licensed under an approved Open+Source license as listed by the Open Source Initiative at+http://opensource.org/licenses. The patent license shall not apply to+any other combinations which include this software. No hardware per+se is licensed hereunder.++DISCLAIMER. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE+COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR+TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE+USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH+DAMAGE.diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 9c72c6e..11cbb56 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -151,7 +151,8 @@ class MainActivity : AppCompatActivity() {}else DeviceActions.openDetails(this, it.mac)},- onLongPress = { if (listOf(CELL_ROW, WAZE_ROW, RADIO_ROW, AIRCRAFT_ROW).none { p -> it.mac.startsWith(p) }) DeviceActions.showQuickActions(this, it.mac) }+ onLongPress = { if (listOf(CELL_ROW, WAZE_ROW, RADIO_ROW, AIRCRAFT_ROW).none { p -> it.mac.startsWith(p) }) DeviceActions.showQuickActions(this, it.mac) },+ onMute = { row, forever -> toggleMute(row, forever) })binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapter@@ -490,6 +491,9 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let {com.rfsentinel.app.ui.StatusPanel.Hardware(it, { com.rfsentinel.app.usb.MonitorFrames.frameCount.get() }, " frames/s")},+ com.rfsentinel.app.usb.UsbBluetooth.status.takeIf { it.isNotBlank() }?.let {+ com.rfsentinel.app.ui.StatusPanel.Hardware(it, { com.rfsentinel.app.usb.UsbBluetooth.reportCount.get() }, " adverts/s")+ },com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let {com.rfsentinel.app.ui.StatusPanel.Hardware(it,if (it.contains("ADS-B")) ({ com.rfsentinel.app.sdr.SdrRadio.adsbMessages }) else null, " msg/s")@@ -522,6 +526,7 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.esp.OuiSpyBle.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +com.rfsentinel.app.esp.EspBoards.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() ++ com.rfsentinel.app.usb.UsbBluetooth.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }?.let { "\n$it" }.orEmpty() +@@ -985,16 +990,33 @@ class MainActivity : AppCompatActivity() {return com.rfsentinel.app.ui.DeviceRows.matchColor(this, best.category, best.tier)}+ /** A flagged row's mute button: no alerts from it for a while ([forever]: until unmuted); tapped while muted, unmutes. */+ private fun toggleMute(row: DeviceRow, forever: Boolean) {+ val mutes = com.rfsentinel.app.data.AlertMutes+ val name = row.title+ if (mutes.isMuted(this, row.mac) && !forever) {+ mutes.unmute(this, row.mac)+ android.widget.Toast.makeText(this, "Alerts back on for $name", android.widget.Toast.LENGTH_SHORT).show()+ } else {+ mutes.mute(this, row.mac, if (forever) mutes.FOREVER else System.currentTimeMillis() + mutes.TAP_MS)+ android.widget.Toast.makeText(this, if (forever) "$name muted until you unmute it (tap the button again)"+ else "$name muted for ${mutes.TAP_MS / 60_000} min (hold the button to mute it until you unmute it)", android.widget.Toast.LENGTH_LONG).show()+ }+ render()+ }+private fun toRow(s: DeviceRegistry.Snapshot, now: Long, threshold: Int): DeviceRow {val whitelisted = WhitelistCache.contains(s.mac)val best = s.bestval alert = best != null && !whitelisted+ val muted = alert && com.rfsentinel.app.data.AlertMutes.isMuted(this, s.mac, now)val ageSec = (now - s.lastSeen) / 1000val age = if (ageSec < 2) "now" else "${ageSec}s ago"val badges = buildList {if (s.following) add("FOLLOWING")if (Favorites.contains(s.mac)) add("★")if (s.isNew) add("NEW")+ if (muted) com.rfsentinel.app.data.AlertMutes.label(this@MainActivity, s.mac, now)?.let { add(it.uppercase()) }}val tag = when {whitelisted -> "WHITELISTED"@@ -1026,15 +1048,18 @@ class MainActivity : AppCompatActivity() {},highlight = if (alert) colorFor(s) else null,// Flashes only while still in range (like the beeps); a gone device keeps a steady tint.- flashing = alert && com.rfsentinel.app.ui.LiveWindow.inRange(s, now) &&+ flashing = alert && !muted && com.rfsentinel.app.ui.LiveWindow.inRange(s, now) &&(s.following || (best!!.confidence >= threshold && best.category != Category.TRACKER)),bold = alert,heardByEsp = com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac, now),heardByUsb = com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac, now),+ heardByUsbBt = com.rfsentinel.app.esp.HeardBy.usbBt.recent(s.mac, now),heardByPhone = com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac, now),heardByPeer = com.rfsentinel.app.esp.HeardBy.peer.via(s.mac, now),rssi = s.rssi,- confidence = best?.confidence?.takeIf { !whitelisted }+ confidence = best?.confidence?.takeIf { !whitelisted },+ canMute = alert,+ muted = muted)}diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.ktindex bd8a0e4..d08f5ad 100644--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt@@ -94,9 +94,10 @@ object CarUi {}}- /** Which radio heard it: an ESP32 board, a USB WiFi adapter, a linked Sentinel, or the phone (Bluetooth / WiFi). */+ /** Which radio heard it: an ESP32 board, a USB WiFi or Bluetooth adapter, a linked Sentinel, or the phone (Bluetooth / WiFi). */fun sourceTag(s: DeviceRegistry.Snapshot): String = when {com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac) -> "USB WiFi"+ com.rfsentinel.app.esp.HeardBy.usbBt.recent(s.mac) -> "USB Bluetooth"com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) -> "ESP32"!com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac) && com.rfsentinel.app.esp.HeardBy.peer.recent(s.mac) ->"via " + com.rfsentinel.app.esp.HeardBy.peer.via(s.mac)diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.ktindex 139a223..7a29f0d 100644--- a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt@@ -201,10 +201,12 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Liveprivate fun heardBy(s: DeviceRegistry.Snapshot): String = listOfNotNull(if (com.rfsentinel.app.esp.HeardBy.phone.recent(mac) || (!com.rfsentinel.app.esp.HeardBy.esp.recent(mac) &&- !com.rfsentinel.app.esp.HeardBy.usb.recent(mac) && !com.rfsentinel.app.esp.HeardBy.peer.recent(mac)))+ !com.rfsentinel.app.esp.HeardBy.usb.recent(mac) && !com.rfsentinel.app.esp.HeardBy.usbBt.recent(mac) &&+ !com.rfsentinel.app.esp.HeardBy.peer.recent(mac)))"phone " + if (s.source == com.rfsentinel.app.detect.Advert.Source.WIFI) "WiFi" else "Bluetooth" else null,if (com.rfsentinel.app.esp.HeardBy.esp.recent(mac)) "ESP32" else null,if (com.rfsentinel.app.esp.HeardBy.usb.recent(mac)) "USB WiFi" else null,+ if (com.rfsentinel.app.esp.HeardBy.usbBt.recent(mac)) "USB Bluetooth" else null,com.rfsentinel.app.esp.HeardBy.peer.via(mac)?.let { "Sentinel $it" }).joinToString(" + ")diff --git a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.ktindex 20b16d6..28e4d2c 100644--- a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt@@ -43,7 +43,9 @@ class HardwareScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =Triple("USB WiFi adapter", UsbWifi.status.ifBlank {if (running) "None connected (RTL8811AU / 8821AU or RTL8812BU / 8822BU)" else "Connects while scanning"}, R.drawable.ic_car_usb)- )+ ) + listOfNotNull(com.rfsentinel.app.usb.UsbBluetooth.status.takeIf { it.isNotBlank() }?.let {+ Triple("USB Bluetooth adapter", it, R.drawable.ic_car_usb)+ })}override fun contentKey(): Any = lines()diff --git a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.ktindex 6d949df..d0872a8 100644--- a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt+++ b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt@@ -217,6 +217,7 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {private fun hardwareSummary(): String = listOfNotNull(EspBoards.status.takeIf { it.isNotBlank() },UsbWifi.status.takeIf { it.isNotBlank() },+ com.rfsentinel.app.usb.UsbBluetooth.status.takeIf { it.isNotBlank() },SdrRadio.status.takeIf { it.isNotBlank() },OuiSpyBle.status.takeIf { it.isNotBlank() },com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() },diff --git a/app/src/main/java/com/rfsentinel/app/data/AlertMutes.kt b/app/src/main/java/com/rfsentinel/app/data/AlertMutes.ktnew file mode 100644index 0000000..0820067--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/data/AlertMutes.kt@@ -0,0 +1,96 @@+package com.rfsentinel.app.data++import android.content.Context+import androidx.core.content.edit+import com.rfsentinel.app.service.DeviceRegistry+import org.json.JSONObject+import java.util.concurrent.ConcurrentHashMap++/**+ * The ways an alert reaches you; each can be turned off per watchlist entry ([com.rfsentinel.app.oui.OuiEntry.alertsOff])+ * and per category ([com.rfsentinel.app.util.Prefs.categoryAlertsOff]).+ */+enum class AlertKind(val label: String) {+ /** The radar-detector ticks while it's near. */+ BEEP("Beep"),+ /** The alert sound. */+ SOUND("Sound"),+ /** The spoken alert. */+ VOICE("Voice"),+ VIBRATE("Vibrate"),+ /** The notification, the map card and the bubble's popup. */+ BANNER("Banner");++ companion object {+ fun parse(text: String?): Set<AlertKind> =+ text.orEmpty().split(',').mapNotNull { k -> entries.firstOrNull { it.name == k.trim() } }.toSet()++ fun format(off: Set<AlertKind>): String? = off.takeIf { it.isNotEmpty() }?.joinToString(",") { it.name }+ }+}++/**+ * Devices you acknowledged from the list: no alerts from them (sound, voice, vibration, banner, radar beep) for a+ * while, or until you unmute them. Still listed, coloured and logged.+ */+object AlertMutes {++ private const val PREFS = "alert_mutes"+ private const val KEY = "mutes"+ /** Muted until you unmute it. */+ const val FOREVER = Long.MAX_VALUE+ const val TAP_MS = 30 * 60_000L++ private val until = ConcurrentHashMap<String, Long>()+ @Volatile private var loaded = false++ private fun load(context: Context) {+ if (loaded) return+ synchronized(this) {+ if (loaded) return+ runCatching {+ val o = JSONObject(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: "{}")+ val now = System.currentTimeMillis()+ o.keys().forEach { mac -> o.optLong(mac).takeIf { it > now }?.let { until[mac] = it } }+ }+ loaded = true+ }+ }++ private fun save(context: Context) {+ val now = System.currentTimeMillis()+ val o = JSONObject()+ until.forEach { (mac, t) -> if (t > now) o.put(mac, t) }+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putString(KEY, o.toString()) }+ }++ /** When [mac]'s mute ends ([FOREVER] for never), or null when it isn't muted. Its earlier address counts too. */+ fun mutedUntil(context: Context, mac: String, now: Long = System.currentTimeMillis()): Long? {+ load(context)+ if (until.isEmpty()) return null+ return listOfNotNull(mac, DeviceRegistry.linkedFrom(mac)).firstNotNullOfOrNull { m -> until[m]?.takeIf { it > now } }+ }++ fun isMuted(context: Context, mac: String, now: Long = System.currentTimeMillis()) = mutedUntil(context, mac, now) != null++ fun mute(context: Context, mac: String, untilTime: Long) {+ load(context)+ until[mac] = untilTime+ save(context)+ }++ fun unmute(context: Context, mac: String) {+ load(context)+ until.remove(mac)+ DeviceRegistry.linkedFrom(mac)?.let { until.remove(it) }+ save(context)+ }++ /** "muted 29m" / "muted" for the list row; null when not muted. */+ fun label(context: Context, mac: String, now: Long = System.currentTimeMillis()): String? {+ val t = mutedUntil(context, mac, now) ?: return null+ if (t == FOREVER) return "muted"+ val min = ((t - now + 59_999) / 60_000).coerceAtLeast(1)+ return if (min >= 60) "muted ${min / 60}h${(min % 60).toString().padStart(2, '0')}" else "muted ${min}m"+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.ktindex 8c79d2d..9cbe655 100644--- a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt+++ b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt@@ -10,9 +10,9 @@ import androidx.sqlite.db.SupportSQLiteDatabase@Database(entities = [DetectionEntity::class, WhitelistEntity::class, KnownDeviceEntity::class,- TripEntity::class, TripPointEntity::class, TripDeviceEntity::class+ TripEntity::class, TripPointEntity::class, TripDeviceEntity::class, DeviceDetailsEntity::class],- version = 7,+ version = 8,exportSchema = false)abstract class AppDatabase : RoomDatabase() {@@ -20,6 +20,7 @@ abstract class AppDatabase : RoomDatabase() {abstract fun whitelistDao(): WhitelistDaoabstract fun knownDeviceDao(): KnownDeviceDaoabstract fun tripDao(): TripDao+ abstract fun deviceDetailsDao(): DeviceDetailsDaocompanion object {@Volatile private var INSTANCE: AppDatabase? = null@@ -99,13 +100,20 @@ abstract class AppDatabase : RoomDatabase() {}}+ /** v2.31: each device's page as last heard, so the device history shows it all once it's out of range. */+ val MIGRATION_7_8 = object : Migration(7, 8) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("CREATE TABLE IF NOT EXISTS device_details (mac TEXT NOT NULL PRIMARY KEY, savedAt INTEGER NOT NULL, json TEXT NOT NULL)")+ }+ }+fun getInstance(context: Context): AppDatabase {return INSTANCE ?: synchronized(this) {INSTANCE ?: Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"rfsentinel.db"- ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7).build().also { INSTANCE = it }+ ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8).build().also { INSTANCE = it }}}}diff --git a/app/src/main/java/com/rfsentinel/app/data/LastHeard.kt b/app/src/main/java/com/rfsentinel/app/data/LastHeard.ktnew file mode 100644index 0000000..67104e9--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/data/LastHeard.kt@@ -0,0 +1,138 @@+package com.rfsentinel.app.data++import android.content.Context+import androidx.room.Dao+import androidx.room.Entity+import androidx.room.PrimaryKey+import androidx.room.Query+import androidx.room.Upsert+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.ui.DeviceSections+import org.json.JSONArray+import org.json.JSONObject++/**+ * A device's page as it was when last heard ([LastHeard]): kept apart from [KnownDeviceEntity] so the+ * device history stays small and quick to search.+ */+@Entity(tableName = "device_details")+data class DeviceDetailsEntity(+ @PrimaryKey val mac: String,+ val savedAt: Long,+ val json: String+)++@Dao+interface DeviceDetailsDao {+ @Query("SELECT * FROM device_details WHERE mac = :mac")+ suspend fun get(mac: String): DeviceDetailsEntity?++ @Upsert+ suspend fun upsertAll(rows: List<DeviceDetailsEntity>)++ /** Details of devices the history no longer has (pruned or forgotten). */+ @Query("DELETE FROM device_details WHERE mac NOT IN (SELECT mac FROM known_devices)")+ suspend fun pruneOrphans(): Int++ /** Keeps the newest [keep] pages and those of your favourite, named or noted devices: every device heard gets one. */+ @Query("DELETE FROM device_details WHERE mac NOT IN (SELECT mac FROM device_details ORDER BY savedAt DESC LIMIT :keep) " ++ "AND mac NOT IN (SELECT mac FROM known_devices WHERE favorite = 1 OR alias IS NOT NULL OR note IS NOT NULL)")+ suspend fun keepNewest(keep: Int): Int+}++/**+ * Everything a device's page showed the last time it was heard - why it was flagged, identity, Remote ID, raw+ * advertisement, signal - so its page from the device history shows the same once it's out of range.+ */+object LastHeard {++ /** The last ones saved for a while; at most this many signal readings. */+ private const val MAX_SAMPLES = 120++ class Saved(+ val at: Long,+ val firstSeen: Long,+ val rssi: Int,+ val bestRssi: Int,+ val distanceM: Double,+ val sightings: Int,+ val following: Boolean,+ val hits: List<Hit>,+ val sections: List<com.rfsentinel.app.ui.DeviceSection>,+ val samples: List<DeviceRegistry.Sample>,+ /** Where the drone and its operator were, for the map buttons. */+ val drone: Pair<Double, Double>?,+ val operator: Pair<Double, Double>?,+ val uasId: String?+ ) {+ val best: Hit? get() = hits.firstOrNull()+ }++ fun of(context: Context, s: DeviceRegistry.Snapshot): Saved {+ val r = s.remoteId+ return Saved(+ at = s.lastSeen, firstSeen = s.firstSeen, rssi = s.rssi, bestRssi = s.bestRssi, distanceM = s.distanceM,+ sightings = s.sightings, following = s.following, hits = s.hits,+ sections = DeviceSections.build(context, s.mac, s, s.known, emptyList(), emptyList(), saving = true),+ samples = s.history.takeLast(MAX_SAMPLES),+ drone = r?.takeIf { it.hasPosition }?.let { it.latitude!! to it.longitude!! },+ operator = r?.takeIf { it.hasOperatorPosition }?.let { it.operatorLatitude!! to it.operatorLongitude!! },+ uasId = r?.uasId+ )+ }++ fun toJson(v: Saved): String = JSONObject().apply {+ put("at", v.at); put("firstSeen", v.firstSeen); put("rssi", v.rssi); put("bestRssi", v.bestRssi)+ put("distanceM", v.distanceM); put("sightings", v.sightings); put("following", v.following)+ put("hits", JSONArray().apply {+ v.hits.forEach { h ->+ put(JSONObject().put("category", h.category.name).put("label", h.label).put("confidence", h.confidence)+ .put("evidence", h.evidence).put("source", h.source))+ }+ })+ put("sections", JSONArray().apply {+ v.sections.forEach { (title, rows) ->+ put(JSONObject().put("title", title).put("rows", JSONArray().apply {+ rows.forEach { (k, value) -> put(JSONArray().put(k).put(value)) }+ }))+ }+ })+ // Times relative to the last reading, to keep it small.+ put("samples", JSONArray().apply { v.samples.forEach { put(JSONArray().put(v.at - it.time).put(it.rssi)) } })+ v.drone?.let { put("drone", JSONArray().put(it.first).put(it.second)) }+ v.operator?.let { put("operator", JSONArray().put(it.first).put(it.second)) }+ v.uasId?.let { put("uasId", it) }+ }.toString()++ fun fromJson(json: String): Saved? = runCatching {+ val o = JSONObject(json)+ fun point(key: String) = o.optJSONArray(key)?.let { it.getDouble(0) to it.getDouble(1) }+ val at = o.getLong("at")+ Saved(+ at = at, firstSeen = o.optLong("firstSeen", at), rssi = o.optInt("rssi", -127), bestRssi = o.optInt("bestRssi", -127),+ distanceM = o.optDouble("distanceM", 0.0), sightings = o.optInt("sightings"), following = o.optBoolean("following"),+ hits = o.optJSONArray("hits")?.let { a ->+ (0 until a.length()).map { i ->+ val h = a.getJSONObject(i)+ Hit(Category.parse(h.optString("category")) ?: Category.CUSTOM, h.getString("label"),+ h.optInt("confidence"), h.optString("evidence"), h.optString("source"))+ }+ }.orEmpty(),+ sections = o.optJSONArray("sections")?.let { a ->+ (0 until a.length()).map { i ->+ val sec = a.getJSONObject(i)+ val rows = sec.getJSONArray("rows")+ sec.getString("title") to (0 until rows.length()).map { j ->+ rows.getJSONArray(j).let { it.getString(0) to it.getString(1) }+ }+ }+ }.orEmpty(),+ samples = o.optJSONArray("samples")?.let { a ->+ (0 until a.length()).map { i -> a.getJSONArray(i).let { DeviceRegistry.Sample(at - it.getLong(0), it.getInt(1)) } }+ }.orEmpty(),+ drone = point("drone"), operator = point("operator"), uasId = o.optString("uasId").takeIf { o.has("uasId") }+ )+ }.getOrNull()+}diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.ktindex bcfdc57..98c0135 100644--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt@@ -126,7 +126,7 @@ object DeviceIntel {private val ROUTER_TYPE = Regex("^(home router|wifi access point|vehicle / cellular router|mesh router)|access point$", RegexOption.IGNORE_CASE)- /** True when a type is a router or a home / plain access point (the Routers chip); business access points aren't. */+ /** True when a type is a router or a home / plain access point (the Routers chip); business ones are Access points. */fun isRouter(type: String): Boolean = ROUTER_TYPE.containsMatchIn(type)/** The type of a hidden network another network of the same access point names: "<that type> (hidden network)". */diff --git a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.ktindex 39eec4b..8031d19 100644--- a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt+++ b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt@@ -62,6 +62,8 @@ object HeardBy {val esp = RecentMacs()/** A USB WiFi adapter in monitor mode. */val usb = RecentMacs()+ /** A USB Bluetooth adapter (dongle, or the Bluetooth half of a combo adapter). */+ val usbBt = RecentMacs()val phone = RecentMacs()/** Another Sentinel (Sentinel Link). */val peer = PeerMacs()diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt b/app/src/main/java/com/rfsentinel/app/link/MeshNode.ktindex 801efbd..af25818 100644--- a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt+++ b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt@@ -178,13 +178,14 @@ object MeshNode {return { runCatching { scanner.stopScan(cb) } }}- /** Pairs with the node now, while the user is looking: Android asks for its PIN (on its screen, or 123456). */- fun pair(context: Context, nodeAddress: String) {- runCatching {- val d = context.getSystemService(BluetoothManager::class.java)?.adapter?.getRemoteDevice(nodeAddress) ?: return- if (d.bondState == BluetoothDevice.BOND_NONE) d.createBond()- }- }+ /**+ * Pairs with the node now, while the user is looking (from a screen, so Android shows its PIN dialog+ * rather than a notification): the PIN is on the node's screen, or 123456. False when it's already paired.+ */+ fun pair(context: Context, nodeAddress: String): Boolean = runCatching {+ val d = context.getSystemService(BluetoothManager::class.java)?.adapter?.getRemoteDevice(nodeAddress) ?: return false+ d.bondState == BluetoothDevice.BOND_NONE && d.createBond()+ }.getOrDefault(false)// ---------------------------------------------------------------- connection@@ -199,21 +200,22 @@ object MeshNode {if (adapter == null || !adapter.isEnabled) { setStatus("Meshtastic node: Bluetooth is off"); scheduleRetry(); return }val device = runCatching { adapter.getRemoteDevice(addr) }.getOrNull()?: run { setStatus("Meshtastic node: choose the node again"); return }- // Meshtastic nodes want a paired phone (PIN on the node's screen, or 123456).+ // Meshtastic nodes want a paired phone (PIN on the node's screen, or 123456). Pairing asked from the+ // background only gets Android's small "pairing request" notification, often cut off with no PIN box:+ // ours opens Sentinel Link, which asks in the foreground so Android shows its PIN dialog.when (device.bondState) {BluetoothDevice.BOND_NONE -> {if (bondStarted == 0L || SystemClock.elapsedRealtime() - bondStarted > BOND_WAIT_MS) {bondStarted = SystemClock.elapsedRealtime()- runCatching { device.createBond() }- setStatus("Meshtastic node: pairing - enter the node's PIN if Android asks")- } else {- setStatus("Meshtastic node: not paired - enter the PIN Android asks for")+ com.rfsentinel.app.util.NotificationHelper.showMeshPairing(c)}+ setStatus("Meshtastic node: not paired - tap here to pair")scheduleRetry(5_000L)return}- BluetoothDevice.BOND_BONDING -> { setStatus("Meshtastic node: pairing…"); scheduleRetry(3_000L); return }+ BluetoothDevice.BOND_BONDING -> { setStatus("Meshtastic node: pairing - enter the PIN Android asks for"); scheduleRetry(3_000L); return }}+ if (bondStarted != 0L) com.rfsentinel.app.util.NotificationHelper.cancelMeshPairing(c)bondStarted = 0LsetStatus("Meshtastic node: connecting…")connectStarted = SystemClock.elapsedRealtime()diff --git a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.ktindex fd15657..68158c3 100644--- a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt@@ -89,16 +89,13 @@ class OnlineWatch(synchronized(loiter) {for (p in planes) {val circling = loiter.update(p, now)- val hit = PoliceAircraft.classify(p, registry, circling, PoliceAircraft.distance(p, me.latitude, me.longitude))+ val distanceM = PoliceAircraft.distance(p, me.latitude, me.longitude)+ val hit = PoliceAircraft.classify(p, registry, circling, distanceM)seen += PoliceAircraft.Seen(p, hit)if (hit == null) continue- if (best == null || hit.confidence > best!!.confidence) best = hit- // One report per aircraft per 20 minutes (or sooner if it starts circling).- val last = lastAircraftHit[p.hex] ?: 0L- if (now - last >= AIRCRAFT_REPEAT_MS) {- lastAircraftHit[p.hex] = now- onAlert(Alert(hit, p.lat, p.lon, "air:" + p.hex))- }+ val loud = PoliceAircraft.alerts(hit, distanceM)+ if (loud && (best == null || hit.confidence > best!!.confidence)) best = hit+ reportAircraft(hit, p.hex, p.lat, p.lon, loud, now)}loiter.prune(now)lastAircraftHit.entries.removeAll { now - it.value > AIRCRAFT_REPEAT_MS }@@ -107,7 +104,7 @@ class OnlineWatch(PoliceAircraft.latestAt = nowAmbientThreats.aircraft = best?.let { now to AmbientThreats.Threat(it.confidence, it.label, Category.AIRCRAFT) }aircraftStatus = "Updated ${clock(now)}: ${planes.size} aircraft within $radiusKm km" +- (best?.let { " · ${it.label}" } ?: ", none police")+ ((best ?: seen.mapNotNull { it.hit }.maxByOrNull { it.confidence })?.let { " · ${it.label}" } ?: ", none police")}/**@@ -121,33 +118,47 @@ class OnlineWatch(val registry = PoliceAircraft.load(context)val me = location()val seen = ArrayList<PoliceAircraft.Seen>(planes.size)+ var best: Hit? = nullsynchronized(loiter) {- fun report(hit: Hit, key: String, lat: Double, lon: Double) {- val last = lastAircraftHit[key] ?: 0L- if (now - last < AIRCRAFT_REPEAT_MS) return- lastAircraftHit[key] = now- onAlert(Alert(hit, lat, lon, "air:$key"))- }for (p in planes) {val circling = loiter.update(p, now)- val hit = PoliceAircraft.classify(p, registry, circling,- me?.let { PoliceAircraft.distance(p, it.latitude, it.longitude) }, PoliceAircraft.VIA_LOCAL)+ val distanceM = me?.let { PoliceAircraft.distance(p, it.latitude, it.longitude) }+ val hit = PoliceAircraft.classify(p, registry, circling, distanceM, PoliceAircraft.VIA_LOCAL)seen += PoliceAircraft.Seen(p, hit)- hit?.let { report(it, p.hex, p.lat, p.lon) }+ if (hit == null) continue+ val loud = PoliceAircraft.alerts(hit, distanceM)+ if (loud && (best == null || hit.confidence > best!!.confidence)) best = hit+ reportAircraft(hit, p.hex, p.lat, p.lon, loud, now)+ }+ // No position: logged where you are, which is where it was heard; its distance is unknown, so no alert.+ if (me != null) for (hex in unlocated) PoliceAircraft.heardNearby(hex, registry)?.let {+ reportAircraft(it, hex, me.latitude, me.longitude, false, now)}- // No position: logged where you are, which is where it was heard.- if (me != null) for (hex in unlocated) PoliceAircraft.heardNearby(hex, registry)?.let { report(it, hex, me.latitude, me.longitude) }loiter.prune(now)}PoliceAircraft.local = seenPoliceAircraft.localAt = now- seen.mapNotNull { it.hit }.maxByOrNull { it.confidence }?.let { best ->+ best?.let { best ->val cur = AmbientThreats.aircraftif (cur == null || now - cur.first > AIRCRAFT_MS || best.confidence >= cur.second.score)AmbientThreats.aircraft = now to AmbientThreats.Threat(best.confidence, best.label, Category.AIRCRAFT)}}+ /**+ * Logs an aircraft hit once per aircraft per 20 minutes; [loud] (strong and close, [PoliceAircraft.alerts]) also+ * alerts, once more when one that was only logged comes close. Called with [loiter] held.+ */+ private fun reportAircraft(hit: Hit, hex: String, lat: Double, lon: Double, loud: Boolean, now: Long) {+ val key = if (loud) "$hex!" else hex+ if (now - (lastAircraftHit[key] ?: 0L) < AIRCRAFT_REPEAT_MS) return+ // Logged already while it was far: the alert needn't log it again.+ val loggedRecently = loud && now - (lastAircraftHit[hex] ?: 0L) < AIRCRAFT_REPEAT_MS+ lastAircraftHit[key] = now+ lastAircraftHit[hex] = now+ onAlert(Alert(hit, lat, lon, "air:$hex", level = if (loud) WazePolice.Level.LOUD else WazePolice.Level.LOG, log = !loggedRecently))+ }+private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))companion object {diff --git a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.ktindex 96fc69a..5d8ce4f 100644--- a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt+++ b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt@@ -133,6 +133,13 @@ object PoliceAircraft {"FAA / Transport Canada aircraft registry; $VIA_LOCAL")}+ /** Closer than this (ground distance) a strong match alerts; farther, or weaker, it's only logged and listed. */+ const val ALERT_M = 5_000.0++ /** Whether a hit alerts (sound, voice, notification): a strong match within [ALERT_M]; otherwise it's only logged. */+ fun alerts(hit: Hit, distanceM: Double?): Boolean =+ hit.confidence >= com.rfsentinel.app.detect.Tier.STRONG.min && distanceM != null && distanceM <= ALERT_M+const val VIA_ONLINE = "ADS-B (adsb.fi / adsb.lol)"const val VIA_LOCAL = "ADS-B heard by your RTL-SDR"@@ -149,9 +156,12 @@ object PoliceAircraft {}/**- * Spots aircraft orbiting over one area: in the last 12 minutes it turned through at- * least one and a half full circles while staying within 4 km of its own average- * position, below 8,000 ft and slower than 180 kt (airliners and passing traffic don't).+ * Spots aircraft orbiting over one area: in the last 12 minutes it turned through at least one and a half+ * full circles while staying within 4 km of its own average position, below 8,000 ft and slower than 180 kt+ * (airliners and passing traffic don't). Its positions must also go all the way around that average spot:+ * the reported heading alone can't be trusted (a taxiing plane, a hovering helicopter or a jumpy heading+ * adds up turns while flying straight). Fixes on the ground, slower than 30 kt or without a new position+ * don't count.*/class LoiterTracker {private data class Fix(val time: Long, val lat: Double, val lon: Double, val track: Double)@@ -159,29 +169,43 @@ object PoliceAircraft {fun update(p: Plane, now: Long): Boolean {val q = tracks.getOrPut(p.hex) { ArrayDeque() }- p.trackDeg?.let { q.addLast(Fix(now, p.lat, p.lon, it)) }+ val airborne = (p.altitudeFt ?: 1) > 0 && (p.speedKt ?: MIN_SPEED_KT) >= MIN_SPEED_KT+ val last = q.lastOrNull()+ // The RTL-SDR's list repeats the last position every couple of seconds until a new one is decoded.+ val fresh = last == null || (now - last.time >= MIN_GAP_MS && (last.lat != p.lat || last.lon != p.lon))+ if (airborne && fresh) p.trackDeg?.let { q.addLast(Fix(now, p.lat, p.lon, it)) }while (q.isNotEmpty() && now - q.first().time > WINDOW_MS) q.removeFirst()- if (q.size < 6 || now - q.first().time < 5 * 60_000L) return false+ if (!airborne || q.size < 6 || now - q.first().time < 5 * 60_000L) return falseif ((p.altitudeFt ?: 0) > 8_000 || (p.speedKt ?: 0.0) > 180) return falsevar turned = 0.0- for (i in 1 until q.size) {- var d = q[i].track - q[i - 1].track- if (d > 180) d -= 360- if (d < -180) d += 360- turned += d- }+ for (i in 1 until q.size) turned += wrap(q[i].track - q[i - 1].track)val cLat = q.sumOf { it.lat } / q.sizeval cLon = q.sumOf { it.lon } / q.size- val spread = q.maxOf { DeviceRegistry.metersBetween(cLat, cLon, it.lat, it.lon) }- return abs(turned) >= 540 && spread <= 4_000+ val dist = q.map { DeviceRegistry.metersBetween(cLat, cLon, it.lat, it.lon) }+ if (dist.max() > 4_000 || dist.average() < MIN_RADIUS_M) return false+ // How far the positions went around the average spot (a straight pass sweeps under 180 degrees).+ var around = 0.0+ for (i in 1 until q.size) around += wrap(bearing(cLat, cLon, q[i]) - bearing(cLat, cLon, q[i - 1]))+ return abs(turned) >= 540 && abs(around) >= 360 && turned * around > 0}+ private fun wrap(d: Double): Double = when { d > 180 -> d - 360; d < -180 -> d + 360; else -> d }++ private fun bearing(lat: Double, lon: Double, f: Fix): Double =+ Math.toDegrees(kotlin.math.atan2((f.lon - lon) * kotlin.math.cos(Math.toRadians(lat)), f.lat - lat))+/** Forgets aircraft not heard for a while. */fun prune(now: Long) {tracks.entries.removeAll { (_, q) -> q.isEmpty() || now - q.last().time > WINDOW_MS }}- companion object { private const val WINDOW_MS = 12 * 60_000L }+ companion object {+ private const val WINDOW_MS = 12 * 60_000L+ private const val MIN_GAP_MS = 5_000L+ private const val MIN_SPEED_KT = 30.0+ /** Average distance from the middle of the orbit: a real one is wider than this. */+ private const val MIN_RADIUS_M = 150.0+ }}/** Ground distance in metres. */diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.javaindex 7c740c8..0c8888e 100644--- a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java@@ -67,6 +67,10 @@ public final class WazeRtFetcher {private static final long BACKOFF_BASE_MS = 30_000L;private static final long BACKOFF_MAX_MS = 10 * 60_000L;private static final long GENERIC_FAIL_BACKOFF_MS = 15_000L;+ /** A session only hears about removals while it lasts and is never re-sent what it already has, so a report+ * whose removal was missed (out of the boxes queried, a dropped poll) would stay forever. Logging in again+ * this often makes Waze re-send every report still active, and the cache drops the rest. */+ private static final long FULL_REFRESH_MS = 10 * 60_000L;private static final long DAY_MS = 24 * 3600_000L;/** One Waze police report, reduced to what RF Sentinel scores. */@@ -108,6 +112,8 @@ public final class WazeRtFetcher {private final WazeAlertCache cache = new WazeAlertCache();private WazeSession session;+ /** When {@link #session} logged in (elapsed realtime). */+ private long sessionStartedAt;private int consecutiveRejections = 0;private long backoffUntilMs = 0L;@@ -189,6 +195,8 @@ public final class WazeRtFetcher {"backing off " + ((backoffUntilMs - now) / 1000) + "s after a rejected session");}try {+ // The new session's first box replaces the cache (see queryArea), so a failed re-login keeps it meanwhile.+ if (session != null && now - sessionStartedAt >= FULL_REFRESH_MS) session = null;double[] at = snapToGrid(lat, lon);Diagnostics.sentLat = at[0];Diagnostics.sentLon = at[1];@@ -254,7 +262,10 @@ public final class WazeRtFetcher {// ── session + query ──────────────────────────────────────────────────────private void queryArea(double lat, double lon, double radiusMeters) throws Exception {- if (session == null) session = restoreOrCreateSession();+ if (session == null) {+ session = restoreOrCreateSession();+ sessionStartedAt = SystemClock.elapsedRealtime();+ }boolean wasUnregistered = session.getCredentials() == null;if (wasUnregistered && !canRegisterToday()) {throw new WazeExceptions.WazeOperationException(diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.ktindex c1d015c..f1b379d 100644--- a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt@@ -1,5 +1,6 @@package com.rfsentinel.app.oui+import com.rfsentinel.app.data.AlertKindimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.detect.Hit@@ -28,8 +29,12 @@ data class OuiEntry(/** 0-100; defaults from [confidence] when absent. */val score: Int? = null,/** A [Category] name; defaults to CUSTOM for user entries. */- val category: String? = null+ val category: String? = null,+ /** Your entries: the ways it doesn't alert you ([AlertKind] names, comma-separated); null = every way. */+ val alertsOff: String? = null) {+ val alertsOffSet: Set<AlertKind> get() = AlertKind.parse(alertsOff)+val isCustom get() = confidence == "custom"val isNameRule get() = prefix.startsWith(NAME, ignoreCase = true)val isStartsRule get() = prefix.startsWith(STARTS, ignoreCase = true)@@ -54,10 +59,12 @@ data class OuiEntry(label = label,confidence = effectiveScore,evidence = evidence,- source = if (isCustom) "Your watchlist" else source.ifEmpty { "Watchlist preset" }+ source = if (isCustom) YOURS else source.ifEmpty { "Watchlist preset" })companion object {+ /** The source of hits from your own entries. */+ const val YOURS = "Your watchlist"const val NAME = "name:"const val STARTS = "starts:"const val VENDOR = "vendor:"diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.ktindex c225584..e5f260f 100644--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt@@ -5,6 +5,7 @@ import androidx.core.content.editimport com.google.gson.Gsonimport com.google.gson.GsonBuilderimport com.google.gson.reflect.TypeToken+import com.rfsentinel.app.data.AlertKindimport com.rfsentinel.app.detect.Hitimport com.rfsentinel.app.util.MacUtilimport java.io.BufferedReader@@ -267,6 +268,18 @@ object OuiWatchlist {fun customEntry(prefix: String): OuiEntry? =state.all.firstOrNull { it.prefix == normalizeKey(prefix) && it.isCustom }+ /**+ * The ways a device doesn't alert you, from your own entries it matches ([OuiEntry.alertsOff]): its address+ * entry first, then the entries behind its watchlist matches.+ */+ fun alertsOff(mac: String, hits: List<Hit>): Set<AlertKind> {+ if (hits.isEmpty()) return emptySet()+ val all = state.all+ val entries = listOfNotNull(customAddressEntry(mac)) ++ hits.filter { it.source == OuiEntry.YOURS }.mapNotNull { h -> all.firstOrNull { it.isCustom && it.label == h.label } }+ return entries.firstOrNull { it.alertsOff != null }?.alertsOffSet.orEmpty()+ }+/** The user's own entry for this address or the longest of their prefixes it starts with, or null. */fun customAddressEntry(mac: String): OuiEntry? {val hex = MacUtil.hex(mac)diff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.ktindex c69aee0..53fee6e 100644--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt@@ -3,13 +3,18 @@ package com.rfsentinel.app.ouilistimport android.view.LayoutInflaterimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerView+import com.rfsentinel.app.data.AlertKindimport com.rfsentinel.app.databinding.ItemOuiEntryBindingimport com.rfsentinel.app.detect.Tierimport com.rfsentinel.app.oui.OuiEntry+import com.rfsentinel.app.ui.ChipStyle+import com.rfsentinel.app.ui.FitChipclass OuiAdapter(private val items: MutableList<OuiEntry>,- private val onRemove: (OuiEntry) -> Unit+ private val onRemove: (OuiEntry) -> Unit,+ /** One of your entries' alert chips was toggled: the ways it now doesn't alert you. */+ private val onAlertsOff: (OuiEntry, Set<AlertKind>) -> Unit) : RecyclerView.Adapter<OuiAdapter.VH>() {fun update(newItems: List<OuiEntry>) {@@ -47,6 +52,24 @@ class OuiAdapter(holder.binding.removeButton.visibility =if (item.confidence == "custom") android.view.View.VISIBLE else android.view.View.GONEholder.binding.removeButton.setOnClickListener { onRemove(item) }+ // Your entries: a chip per way it alerts you, on unless you turned it off.+ val chips = holder.binding.alertChips+ val vis = if (item.isCustom) android.view.View.VISIBLE else android.view.View.GONE+ chips.visibility = vis+ holder.binding.alertsLabel.visibility = vis+ chips.removeAllViews()+ if (item.isCustom) {+ val off = item.alertsOffSet+ AlertKind.entries.forEach { kind ->+ chips.addView(FitChip(chips.context).apply {+ text = kind.label; isCheckable = true+ ChipStyle.apply(this)+ isChecked = kind !in off+ contentDescription = "${kind.label} alerts for ${item.label}"+ setOnClickListener { onAlertsOff(item, if (isChecked) off - kind else off + kind) }+ })+ }+ }}override fun getItemCount() = items.sizediff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.ktindex 9ee48cd..db1abaf 100644--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt@@ -50,14 +50,17 @@ class OuiListActivity : AppCompatActivity() {title = "Watchlist & rules"supportActionBar?.setDisplayHomeAsUpEnabled(true)- adapter = OuiAdapter(mutableListOf()) { entry ->+ adapter = OuiAdapter(mutableListOf(), onRemove = { entry ->OuiWatchlist.removeCustomEntry(this, entry.prefix)refresh()com.rfsentinel.app.util.Undo.show(this, "Removed ${entry.label}") {OuiWatchlist.addCustomEntry(this, entry)refresh()}- }+ }, onAlertsOff = { entry, off ->+ OuiWatchlist.addCustomEntry(this, entry.copy(alertsOff = com.rfsentinel.app.data.AlertKind.format(off)))+ refresh()+ })binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapterbinding.searchInput.doAfterTextChanged { refresh() }diff --git a/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt b/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.ktindex 22225d0..7b4485f 100644--- a/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt+++ b/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt@@ -58,6 +58,67 @@ object AdvertFactory {)}+ /**+ * An advertising report from a USB Bluetooth controller ([com.rfsentinel.app.usb.UsbBluetooth]): its AD structures+ * read the way Android's ScanRecord reads them, so it looks the same as one the phone's own Bluetooth heard.+ */+ fun fromHci(r: com.rfsentinel.app.usb.UsbBluetooth.Report, now: Long = System.currentTimeMillis()): Advert {+ val mac = r.mac+ val mfg = HashMap<Int, ByteArray>()+ val uuids = ArrayList<java.util.UUID>()+ val serviceData = HashMap<java.util.UUID, ByteArray>()+ var name: String? = null+ var tx: Int? = null+ fun uuidLe(b: ByteArray, at: Int, len: Int): java.util.UUID = when (len) {+ 2 -> Advert.uuid16((b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8))+ 4 -> java.util.UUID.fromString(String.format("%08x", (b[at].toLong() and 0xff) or ((b[at + 1].toLong() and 0xff) shl 8) or+ ((b[at + 2].toLong() and 0xff) shl 16) or ((b[at + 3].toLong() and 0xff) shl 24)) + "-0000-1000-8000-00805f9b34fb")+ else -> {+ var msb = 0L; var lsb = 0L+ for (i in 0 until 8) lsb = lsb or ((b[at + i].toLong() and 0xff) shl (8 * i))+ for (i in 0 until 8) msb = msb or ((b[at + 8 + i].toLong() and 0xff) shl (8 * i))+ java.util.UUID(msb, lsb)+ }+ }+ for (ad in com.rfsentinel.app.detect.AdStructure.parse(r.data)) {+ val d = ad.data+ when (ad.type) {+ 0x02, 0x03 -> for (i in 0..d.size - 2 step 2) uuids += uuidLe(d, i, 2)+ 0x04, 0x05 -> for (i in 0..d.size - 4 step 4) uuids += uuidLe(d, i, 4)+ 0x06, 0x07 -> for (i in 0..d.size - 16 step 16) uuids += uuidLe(d, i, 16)+ 0x08, 0x09 -> if (name == null || ad.type == 0x09) name = String(d, Charsets.UTF_8)+ 0x0A -> if (d.isNotEmpty()) tx = d[0].toInt()+ 0x16 -> if (d.size >= 2) serviceData[uuidLe(d, 0, 2)] = d.copyOfRange(2, d.size)+ 0x20 -> if (d.size >= 4) serviceData[uuidLe(d, 0, 4)] = d.copyOfRange(4, d.size)+ 0x21 -> if (d.size >= 16) serviceData[uuidLe(d, 0, 16)] = d.copyOfRange(16, d.size)+ 0xFF -> if (d.size >= 2) mfg[(d[0].toInt() and 0xff) or ((d[1].toInt() and 0xff) shl 8)] = d.copyOfRange(2, d.size)+ }+ }+ // 0 public, 1 random, 2 / 3 the same resolved from a private address.+ val reported = when (r.addrType) {+ 0, 2 -> AddressType.PUBLIC+ 1, 3 -> AddressType.ofRandom(mac)+ else -> AddressType.UNKNOWN+ }+ val addressType = if (reported != AddressType.UNKNOWN) reported+ else AddressType.guess(mac, registered = VendorDb.macVendor(mac) != null, alwaysRandom = APPLE in mfg)+ return Advert(+ mac = mac,+ source = Advert.Source.BLE,+ rssi = if (r.rssi >= 127) -100 else r.rssi,+ name = name,+ manufacturerData = mfg,+ serviceUuids = uuids,+ serviceData = serviceData,+ rawBytes = r.data,+ txPower = tx,+ addressType = addressType,+ connectable = r.connectable,+ phy = r.phy,+ timestamp = now+ )+ }+fun fromWifi(r: WifiScanResult): Advert? {val bssid = r.BSSID ?: return nullval mac = MacUtil.normalize(bssid)diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex da96542..64b9cae 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -28,9 +28,12 @@ import androidx.core.content.ContextCompatimport com.rfsentinel.app.RFSentinelAppimport com.rfsentinel.app.alpr.AlprStoreimport com.rfsentinel.app.alpr.KnownCameras+import com.rfsentinel.app.data.AlertKindimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.DetectionEntity+import com.rfsentinel.app.data.DeviceDetailsEntityimport com.rfsentinel.app.data.KnownDeviceEntity+import com.rfsentinel.app.data.LastHeardimport com.rfsentinel.app.data.WhitelistCacheimport com.rfsentinel.app.detect.Advertimport com.rfsentinel.app.detect.Category@@ -75,6 +78,8 @@ class ScanForegroundService : Service() {/** The latest position's time and accuracy, for the GPS dot (null: none while scanning). */@Volatile var gpsAt = 0L; private set@Volatile var gpsAccuracyM: Float? = null; private set+ /** How old the latest position may get before the GPS dot calls it lost: fixes come every ~20 s on balanced. */+ @Volatile var gpsStaleMs = 10_000L; private set/** No fused fix this long after asking (precise / balanced): raw GPS and network fill in. */private const val FUSED_SILENT_FAST_MS = 15_000Lprivate const val FUSED_SILENT_MS = 30_000L@@ -105,6 +110,10 @@ class ScanForegroundService : Service() {/** Each periodic job holds a short wake lock only while it runs. */private const val WAKE_SLICE_MS = 10_000Lprivate const val HISTORY_FLUSH_MS = 60_000L+ /** A device page's details are saved at least this often while it's heard (and whenever its matches change). */+ private const val DETAILS_SAVE_MS = 5 * 60_000L+ /** Saved device pages kept (newest first, plus every favourite / named / noted device): a few KB each. */+ private const val DETAILS_KEEP = 10_000private const val DRONE_OVERHEAD_REPEAT_MS = 5 * 60_000Lprivate const val KNOWN_ALPR_REPEAT_MS = 30 * 60_000Lprivate const val CELL_CHECK_MS = 15_000L@@ -375,6 +384,8 @@ class ScanForegroundService : Service() {com.rfsentinel.app.esp.EspBoards.start(this) { list -> pipeline.post { list.forEach(::processEsp) } }// A USB WiFi adapter in monitor mode (e.g. AWUS036ACS): access points and client devices.com.rfsentinel.app.usb.UsbWifi.start(this) { list -> pipeline.post { list.forEach(::processUsbWifi) } }+ // A USB Bluetooth adapter (dongle or combo adapter), next to the phone's own Bluetooth (Settings › External hardware).+ com.rfsentinel.app.usb.UsbBluetooth.start(this) { list -> pipeline.post { list.forEach(::processUsbBt) } }com.rfsentinel.app.usb.DeauthWatch.onAttack = { a -> pipeline.post { onDeauth(a) } }com.rfsentinel.app.usb.KarmaWatch.onAttack = { a -> pipeline.post { onKarma(a) } }// An RTL-SDR dongle: strong two-way radio transmissions nearby (signal strength only),@@ -580,6 +591,7 @@ class ScanForegroundService : Service() {!fusedEverFixed -> locatingHandler.postDelayed(backstopCheck, if (fast) FUSED_SILENT_FAST_MS else FUSED_SILENT_MS)}} else requestFixes(lm, rawProviders(lm), locationListener)+ requestDotFixes(lm)locationListening = true}}@@ -626,8 +638,27 @@ class ScanForegroundService : Service() {requestFixes(lm, raw, backstopListener)}+ /**+ * Every fix the phone computes, with no distance filter: the requests above skip fixes until you move 5-25 m,+ * so standing still would leave the GPS dot red. Only refreshes the dot; the scan still uses [onFix].+ */+ private val dotListener = LocationListenerCompat {+ if (!it.hasAccuracy()) return@LocationListenerCompat+ if (it.provider == LocationManager.NETWORK_PROVIDER && System.currentTimeMillis() - lastRawGpsAt < RAW_GPS_PREFERRED_MS) return@LocationListenerCompat+ gpsAt = System.currentTimeMillis(); gpsAccuracyM = it.accuracy+ }++ @SuppressLint("MissingPermission") // only called from updateLocationUpdates(), which checks it+ private fun requestDotFixes(lm: LocationManager) {+ gpsStaleMs = if (locationMode >= 1) 10_000L else 60_000L+ if (!lm.allProviders.contains(LocationManager.PASSIVE_PROVIDER)) return+ runCatching { lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 1_000L, 0f, dotListener, Looper.getMainLooper()) }+ .onFailure { Log.w(TAG, "Passive location unavailable", it) }+ }+private fun stopLocationUpdates(lm: LocationManager) {locatingHandler.removeCallbacks(backstopCheck)+ runCatching { lm.removeUpdates(dotListener) }runCatching { lm.removeUpdates(locationListener) }runCatching { lm.removeUpdates(backstopListener) } // backstopOn stays: re-requested with the next modelocationListening = false@@ -706,7 +737,7 @@ class ScanForegroundService : Service() {noteLocating(mac)maybeLog(a, best, c.vendor, loc, now)- maybeAlert(a, best, now, via)+ maybeAlert(a, best, c.hits, now, via)// Following is about this phone: a device near another Sentinel isn't following it.if (via != null) return@@ -721,10 +752,12 @@ class ScanForegroundService : Service() {ownerPhone(mac, now) != nullif (loc != null && Prefs.followerAlerts(this) && !trackerPaused && !best.listOnly && !withOwner &&(DeviceRegistry.checkFollowing(mac, followMs, followM).also { if (it) placeFollow.alertedNow(mac, now) } ||- placeFollow.follower(mac, now, followMs, followM).also { if (it) DeviceRegistry.markFollowing(mac) })+ placeFollow.follower(mac, now, followMs, followM).also { if (it) DeviceRegistry.markFollowing(mac) }) &&+ !com.rfsentinel.app.data.AlertMutes.isMuted(this, mac, now)) {- NotificationHelper.sendAlert(this, mac, best, a.rssi, following = true)- AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best, following = true), following = true)+ val off = alertsOff(best.category, mac, c.hits)+ NotificationHelper.sendAlert(this, mac, best, a.rssi, following = true, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best, following = true), following = true, off = off)}}@@ -785,6 +818,15 @@ class ScanForegroundService : Service() {process(a, null)}+ /** A USB Bluetooth adapter's advertising report: the same as one the phone's Bluetooth heard, badged USB BT. */+ private fun processUsbBt(r: com.rfsentinel.app.usb.UsbBluetooth.Report) {+ val a = AdvertFactory.fromHci(r)+ com.rfsentinel.app.esp.HeardBy.usbBt.mark(a.mac, a.timestamp)+ com.rfsentinel.app.usb.AntennaCheck.heardBt(a.mac, a.name, a.rssi, a.timestamp)+ linkOutbox?.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, a))+ process(a)+ }+private fun processEsp(e: com.rfsentinel.app.esp.EspSighting) {val now = System.currentTimeMillis()com.rfsentinel.app.esp.HeardBy.esp.mark(e.mac, now)@@ -929,7 +971,7 @@ class ScanForegroundService : Service() {}// Heard here too: this phone's own reading (signal, place) is the one shown.if (heardBy.phone.within(mac, HEARD_HERE_MS, now) || heardBy.esp.within(mac, HEARD_HERE_MS, now) ||- heardBy.usb.within(mac, HEARD_HERE_MS, now)) continue+ heardBy.usb.within(mac, HEARD_HERE_MS, now) || heardBy.usbBt.within(mac, HEARD_HERE_MS, now)) continue// Heard by a Sentinel linked here over Bluetooth: this phone's node passes it on to the mesh.process(a, via = via, peerAt = at, toMesh = b.hops == 0)}@@ -1015,16 +1057,27 @@ class ScanForegroundService : Service() {}}- private fun maybeAlert(a: Advert, best: Hit, now: Long, via: String? = null) {+ /**+ * The ways not to alert you about this: what its category has turned off (Settings › What to detect)+ * plus what your watchlist entry for the device has.+ */+ private fun alertsOff(category: Category, mac: String? = null, hits: List<Hit> = emptyList()): Set<AlertKind> =+ Prefs.categoryAlertsOff(this, category) + (if (mac != null) OuiWatchlist.alertsOff(mac, hits) else emptySet())++ private fun maybeAlert(a: Advert, best: Hit, hits: List<Hit>, now: Long, via: String? = null) {// Someone else's tracker nearby is normal; trackers only alert when they follow you.if (best.category == Category.TRACKER) returnif (best.listOnly || best.confidence < Prefs.alertThreshold(this)) return+ // Acknowledged from the list: listed and logged, no alert.+ if (com.rfsentinel.app.data.AlertMutes.isMuted(this, a.mac, now)) returnval window = Prefs.dedupeWindowMs(this)val last = lastAlerted[a.mac] ?: 0Lif (now - last <= window) returnlastAlerted[a.mac] = now- NotificationHelper.sendAlert(this, a.mac, best, a.rssi, via = via)- AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best, via = via))+ // The ways your watchlist entry for it says not to alert.+ val off = alertsOff(best.category, a.mac, hits)+ NotificationHelper.sendAlert(this, a.mac, best, a.rssi, via = via, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best, via = via), off = off)}private fun knownAlprActive() = (Prefs.knownAlprAlerts(this) || Prefs.speedCameraAlerts(this)) &&@@ -1070,8 +1123,9 @@ class ScanForegroundService : Service() {". Mapped in OpenStreetMap" + (if (alpr) " - it may not broadcast any signal." else "."),"OpenStreetMap (" + (if (alpr) "surveillance:type=ALPR" else "highway=speed_camera / enforcement") + "), ODbL")- NotificationHelper.sendMapAlert(this, "alpr:" + cam.osmId, hit, lat = cam.lat, lon = cam.lon)- AlertPlayer.play(this, hit.tier, com.rfsentinel.app.util.Spoken.camera(this, cam))+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, "alpr:" + cam.osmId, hit, lat = cam.lat, lon = cam.lon, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, com.rfsentinel.app.util.Spoken.camera(this, cam), off = off)break // one warning per fix is enough}}@@ -1079,12 +1133,14 @@ class ScanForegroundService : Service() {/** Remote ID puts the drone within ~200 m of you: alert once per drone per 5 minutes. */private fun maybeAlertDroneOverhead(a: Advert, info: RemoteId.Info, loc: Location, now: Long) {if (!Prefs.categoryEnabled(this, Category.DRONE) || WhitelistCache.contains(a.mac)) return+ if (com.rfsentinel.app.data.AlertMutes.isMuted(this, a.mac, now)) returnval hit = DroneProximity.overheadHit(info, loc.latitude, loc.longitude) ?: returnval last = lastDroneOverhead[a.mac] ?: 0Lif (now - last < DRONE_OVERHEAD_REPEAT_MS) returnlastDroneOverhead[a.mac] = now- NotificationHelper.sendAlert(this, a.mac, hit, a.rssi)- AlertPlayer.play(this, hit.tier, "Drone overhead")+ val off = alertsOff(hit.category, a.mac)+ NotificationHelper.sendAlert(this, a.mac, hit, a.rssi, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, "Drone overhead", off = off)}// ---- History & housekeeping -----------------------------------------------@@ -1103,14 +1159,33 @@ class ScanForegroundService : Service() {runCatching { wakeLock?.acquire(WAKE_SLICE_MS) }}- /** Sightings to merge into known_devices, taken synchronously from memory. */- private class HistoryBatch(val seen: List<DeviceRegistry.Snapshot>, val sessionStart: Long)+ /** Sightings to merge into known_devices, and the pages to save ([LastHeard]), taken synchronously from memory. */+ private class HistoryBatch(val seen: List<DeviceRegistry.Snapshot>, val sessionStart: Long, val details: List<DeviceDetailsEntity>)++ /** When each device's page was last saved, and the matches it had then. */+ private val detailsSaved = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, Int>>()- private fun takeHistory(): HistoryBatch? {+ /** [final]: the scan is stopping, so every page with something newer is saved. */+ private fun takeHistory(final: Boolean = false): HistoryBatch? {val since = lastHistoryFlush- lastHistoryFlush = System.currentTimeMillis()+ val now = System.currentTimeMillis()+ lastHistoryFlush = now+ // Forget long-unsaved devices (rotating addresses): one heard again is just saved again.+ detailsSaved.values.removeIf { now - it.first > 2 * DETAILS_SAVE_MS }val seen = DeviceRegistry.summaries(since)- return if (seen.isEmpty()) null else HistoryBatch(seen, DeviceRegistry.sessionStart)+ if (seen.isEmpty()) return null+ // A page is saved when first heard, when its matches change, and otherwise every few minutes.+ val details = seen.mapNotNull { sum ->+ val (savedAt, hits) = detailsSaved[sum.mac] ?: (0L to 0)+ val due = savedAt == 0L || hits != sum.hits.hashCode() ||+ (if (final) sum.lastSeen > savedAt else now - savedAt >= DETAILS_SAVE_MS)+ if (!due) return@mapNotNull null+ val s = DeviceRegistry.get(sum.mac) ?: return@mapNotNull null+ runCatching { DeviceDetailsEntity(s.mac, now, LastHeard.toJson(LastHeard.of(this, s))) }+ .onFailure { Log.w(TAG, "Device page save failed", it) }.getOrNull()+ ?.also { detailsSaved[s.mac] = now to s.hits.hashCode() }+ }+ return HistoryBatch(seen, DeviceRegistry.sessionStart, details)}/** Merges this session's sightings into known_devices (throttled, batched). */@@ -1140,15 +1215,18 @@ class ScanForegroundService : Service() {)})}+ batch.details.chunked(200).forEach { AppDatabase.getInstance(this).deviceDetailsDao().upsertAll(it) }}private suspend fun pruneOldData() {+ val db = AppDatabase.getInstance(this)+ db.deviceDetailsDao().keepNewest(DETAILS_KEEP)val days = Prefs.retentionDays(this)if (days <= 0) returnval before = System.currentTimeMillis() - days * 24L * 60 * 60 * 1000- val db = AppDatabase.getInstance(this)db.detectionDao().prune(before)db.knownDeviceDao().prune(before)+ db.deviceDetailsDao().pruneOrphans()}private fun startHousekeeping() {@@ -1322,8 +1400,9 @@ class ScanForegroundService : Service() {(serving.operator?.let { " on $it" } ?: "") + (serving.dbm?.let { ", $it dBm" } ?: "") +". Normal while moving; a change while you're parked is worth a look."val hit = Hit(Category.CELL_ANOMALY, "Cell tower changed", 30, detail, "Android cell info")- NotificationHelper.sendMapAlert(this, "cellchange", hit, com.rfsentinel.app.ui.CellTowersActivity::class.java)- AlertPlayer.play(this, hit.tier, "Cell tower changed")+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, "cellchange", hit, com.rfsentinel.app.ui.CellTowersActivity::class.java, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, "Cell tower changed", off = off)val loc = lastLocationval tag = Prefs.gpsTaggingEnabled(this)serviceScope.launch {@@ -1403,7 +1482,9 @@ class ScanForegroundService : Service() {)}if (e.confidence >= threshold) {- NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java,+ banner = AlertKind.BANNER !in off)// Spoken: the frequency (and its name) when that's on, else the short phrase.val spoken = when {cell -> "Cellular transmitter nearby"@@ -1411,7 +1492,7 @@ class ScanForegroundService : Service() {e.tdma -> "TETRA radio nearby"else -> "Radio transmitting nearby"} + (via?.let { ", via $it" } ?: "")- AlertPlayer.play(this, hit.tier, spoken)+ AlertPlayer.play(this, hit.tier, spoken, off = off)}}@@ -1453,9 +1534,11 @@ class ScanForegroundService : Service() {}if (alert.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&hit.confidence >= Prefs.alertThreshold(this)) {- NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon, online = alert.key)+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon, online = alert.key,+ banner = AlertKind.BANNER !in off)if (alert.level == com.rfsentinel.app.online.WazePolice.Level.LOUD) {- AlertPlayer.play(this, hit.tier, alert.spoken ?: com.rfsentinel.app.util.Spoken.shortWord(hit))+ AlertPlayer.play(this, hit.tier, alert.spoken ?: com.rfsentinel.app.util.Spoken.shortWord(hit), off = off)}}}@@ -1490,8 +1573,9 @@ class ScanForegroundService : Service() {)}if (a.confidence >= Prefs.alertThreshold(this)) {- NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java)- AlertPlayer.play(this, hit.tier, a.title)+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, a.title, off = off)}}@@ -1555,8 +1639,9 @@ class ScanForegroundService : Service() {)}if (hit.confidence >= Prefs.alertThreshold(this)) {- NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)- AlertPlayer.play(this, hit.tier, spoken)+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, spoken, off = off)}}@@ -1579,8 +1664,9 @@ class ScanForegroundService : Service() {)}if (a.confidence >= Prefs.alertThreshold(this)) {- NotificationHelper.sendMapAlert(this, "cell:" + a.key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)- AlertPlayer.play(this, hit.tier, "Cell network warning")+ val off = alertsOff(hit.category)+ NotificationHelper.sendMapAlert(this, "cell:" + a.key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)+ AlertPlayer.play(this, hit.tier, "Cell network warning", off = off)}}@@ -1597,9 +1683,11 @@ class ScanForegroundService : Service() {val ctx = this@ScanForegroundServiceval now = System.currentTimeMillis()val target = if (!Prefs.radarBeep(ctx)) null else lastAlerted.entries- .filter { now - it.value in RADAR_QUIET_MS..RADAR_HOLD_MS && !WhitelistCache.contains(it.key) }+ .filter { now - it.value in RADAR_QUIET_MS..RADAR_HOLD_MS && !WhitelistCache.contains(it.key) &&+ !com.rfsentinel.app.data.AlertMutes.isMuted(ctx, it.key, now) }.mapNotNull { DeviceRegistry.get(it.key) }- .filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }+ .filter { s -> com.rfsentinel.app.ui.LiveWindow.alerting(s, now) &&+ AlertKind.BEEP !in (s.best?.let { alertsOff(it.category, s.mac, s.hits) } ?: OuiWatchlist.alertsOff(s.mac, s.hits)) }.maxByOrNull { it.rssi }if (target == null) delay(1_000L)else {@@ -1674,6 +1762,8 @@ class ScanForegroundService : Service() {}override fun onDestroy() {+ // Take the final history first, while the extra info its saved pages show (USB probes...) is still here.+ val history = runCatching { takeHistory(final = true) }.onFailure { Log.w(TAG, "History take failed", it) }.getOrNull()com.rfsentinel.app.ui.LiveRead.reset()com.rfsentinel.app.usb.DeauthWatch.onAttack = nullcom.rfsentinel.app.usb.DeauthWatch.clear()@@ -1683,6 +1773,7 @@ class ScanForegroundService : Service() {locatingHandler.removeCallbacks(locatingCheck)com.rfsentinel.app.esp.EspBoards.stop(this)com.rfsentinel.app.usb.UsbWifi.stop(this)+ com.rfsentinel.app.usb.UsbBluetooth.stop(this)com.rfsentinel.app.sdr.SdrRadio.stop(this)// Its hooks point into this service: cleared, so a stopped scan isn't kept in memory by them.com.rfsentinel.app.sdr.SdrRadio.onAircraft = null@@ -1695,6 +1786,7 @@ class ScanForegroundService : Service() {// External hardware is gone with the scan: its "heard by" marks (External filter, badges) go too.com.rfsentinel.app.esp.HeardBy.esp.clear()com.rfsentinel.app.esp.HeardBy.usb.clear()+ com.rfsentinel.app.esp.HeardBy.usbBt.clear()com.rfsentinel.app.usb.ProbeIntel.clear()com.rfsentinel.app.data.ProbeLog.flush(this)nanRemoteId?.stop()@@ -1711,9 +1803,8 @@ class ScanForegroundService : Service() {cellMonitor?.close()com.rfsentinel.app.ui.ThreatBubble.hide(this)com.rfsentinel.app.ui.FloatingMap.hide(this)- // Take the final history and trace synchronously, so a scan restarted right- // away (new session, new trace) can't clear or reuse them; write them after.- val history = takeHistory()+ // The final history (taken above) and trace are taken synchronously, so a scan restarted right+ // away (new session, new trace) can't clear or reuse them; written after.val trip = TripRecorder.detach() // stopping the scanner ends the trace recording tooval app = application as RFSentinelAppapp.appScope.launch {diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 4cba17f..f225c6f 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -70,6 +70,15 @@ class SettingsActivity : AppCompatActivity() {private var stopObservingPrefetch: (() -> Unit)? = nullprivate var stopObservingDeflock: (() -> Unit)? = nullprivate val categorySwitches = mutableMapOf<Category, SwitchMaterial>()+ /** What follows each category switch (its alert chips, its own controls): one listener calls them all. */+ private val switchFollowers = HashMap<SwitchMaterial, MutableList<(Boolean) -> Unit>>()++ private fun SwitchMaterial.onToggle(f: (Boolean) -> Unit) {+ val list = switchFollowers.getOrPut(this) {+ mutableListOf<(Boolean) -> Unit>().also { l -> setOnCheckedChangeListener { _, on -> l.toList().forEach { it(on) } } }+ }+ list += f+ }private var airTagSwitch: SwitchMaterial? = nullprivate var wazeKeyInput: android.widget.EditText? = nullprivate var aircraftStatusText: android.widget.TextView? = null@@ -327,6 +336,9 @@ class SettingsActivity : AppCompatActivity() {val s = com.rfsentinel.app.esp.EspBoards.statusbinding.espStatusText.text = s.ifBlank { "ESP32 board on USB: not connected" }binding.usbWifiText.text = com.rfsentinel.app.usb.UsbWifi.status.ifBlank { "USB WiFi adapter: not connected" }+ binding.usbBtText.text = com.rfsentinel.app.usb.UsbBluetooth.status.ifBlank {+ if (Prefs.usbBluetooth(this)) "USB Bluetooth adapter: not connected" else "USB Bluetooth adapter: off"+ }binding.sdrStatusText.text = com.rfsentinel.app.sdr.SdrRadio.status.ifBlank { "RTL-SDR / HackRF: not connected" }val board = Prefs.ouiSpyBoard(this)binding.ouiSpyText.text = if (board == null) "OUI-SPY over Bluetooth: not paired"@@ -467,7 +479,8 @@ class SettingsActivity : AppCompatActivity() {"Two-way radio needs an RTL-SDR dongle or a HackRF on USB.\n\n" +"Police aircraft and Waze reports are online sources, off by default. Aircraft: every minute, a position " +"rounded to about 1 km goes to the community ADS-B feeds adsb.fi / adsb.lol; matched against a list of " +- "about 1,400 US and Canadian law-enforcement aircraft, plus unlisted aircraft circling low overhead. With an RTL-SDR " ++ "about 1,400 US and Canadian law-enforcement aircraft, plus unlisted aircraft circling low overhead. Only a strong match " ++ "within 5 km alerts; the rest are listed and logged. With an RTL-SDR " +"set up as an ADS-B receiver, aircraft are also heard directly, and the online feeds can be turned off. " +"Waze: crowd reports (police, and any other kind you tick), at your own risk. Either through your own OpenWeb Ninja key " +"(Waze never sees you), or Waze direct: no key, free, but an anonymous Waze account on this phone sends Waze (Google) your " +@@ -767,6 +780,60 @@ class SettingsActivity : AppCompatActivity() {}}+ /**+ * A What to detect row: the label with its ⓘ ([info]) right after the text, then the switch and its ▾ ([fold]).+ * A row with no ▾ keeps the slot empty, so every switch in the list lines up.+ */+ private fun detectRow(sw: SwitchMaterial, info: String? = null, title: String? = null, fold: View? = null): View {+ val slot = fold ?: foldIcon().apply { visibility = View.INVISIBLE; importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO }+ if (info == null) return android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ gravity = android.view.Gravity.CENTER_VERTICAL+ addView(sw, android.widget.LinearLayout.LayoutParams(0, -2, 1f))+ addView(slot)+ }+ // The label leaves the switch so the ⓘ can sit right after its text; tapping the label still flips the switch.+ val name = sw.text.toString()+ val label = android.widget.TextView(this).apply {+ text = name+ setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, sw.textSize)+ setTextColor(sw.textColors)+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO+ setOnClickListener { sw.toggle() }+ }+ sw.text = null+ sw.contentDescription = name+ val icon = infoIcon(info) { title ?: name }+ return object : android.widget.LinearLayout(this) {+ override fun onMeasure(widthSpec: Int, heightSpec: Int) {+ // A long label wraps before the ⓘ, switch and ▾, instead of pushing them off the row.+ val free = MeasureSpec.getSize(widthSpec) - paddingLeft - paddingRight+ var rest = 0+ for (v in listOf(icon, sw, slot)) { measureChild(v, widthSpec, heightSpec); rest += v.measuredWidth }+ label.maxWidth = (free - rest).coerceAtLeast(0)+ super.onMeasure(widthSpec, heightSpec)+ }+ }.apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ gravity = android.view.Gravity.CENTER_VERTICAL+ addView(label)+ addView(icon)+ addView(View(this@SettingsActivity), android.widget.LinearLayout.LayoutParams(0, 0, 1f))+ addView(sw)+ addView(slot)+ }+ }++ /** The ▾ that opens a category's alert chips, styled like an ⓘ. */+ private fun foldIcon() = android.widget.TextView(this).apply {+ val dp = resources.displayMetrics.density+ text = "▾"; textSize = 18f; alpha = 0.7f+ gravity = android.view.Gravity.CENTER+ minWidth = (36 * dp).toInt()+ setPadding((6 * dp).toInt(), (8 * dp).toInt(), (6 * dp).toInt(), (8 * dp).toInt())+ setBackgroundResource(android.util.TypedValue().also { theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, it, true) }.resourceId)+ }+/** Puts an ⓘ at the end of [view]'s row, where it already sits. */private fun info(view: View, text: String, title: String? = null) {val parent = view.parent as? android.view.ViewGroup ?: return@@ -844,7 +911,7 @@ class SettingsActivity : AppCompatActivity() {withUnit(binding.followMinutesInput, "min")withUnit(binding.followMetersInput, "m")info(binding.mapProviderLabel, "OpenFreeMap: free and open, OpenStreetMap data.\n\nMapbox: Mapbox's Standard map with 3D buildings and day / night light.\n\nThe floating mini map and the Android Auto map always use OpenStreetMap maps.")- info(binding.mapAutoRecenterSwitch, "While you drive, the map goes back to your position a few seconds after you stop touching it.")+ info(binding.mapAutoRecenterSwitch, "While you drive, the map goes back to your position once you've left it alone for the time set under it (Re-center after).")info(binding.mapSpeedometerSwitch, "Your speed and the posted limit in a corner of the map; your speed turns red over the limit.")info(binding.mapSpeedLimitLiveSwitch, "Shows the posted limit with no destination too, by asking the route server (Valhalla, OpenStreetMap data) about the road you're on. Your position is sent to it.")info(binding.autoCamerasSwitch, "Fetches the known cameras (OpenStreetMap) for the area the map shows, as you move it.")@@ -859,6 +926,10 @@ class SettingsActivity : AppCompatActivity() {info(binding.ouiSpyPhoneBleSwitch, "Off: while the OUI-SPY board is connected and live, the phone's own Bluetooth scan " +"pauses and the board does the Bluetooth scanning (it hears farther, and faster). It comes back on its own if the " +"board drops out. Turn on Relay everything too, or only the board's engine matches come in.")+ info(binding.usbBtSwitch, "Uses the Bluetooth part of a USB adapter as a second Bluetooth radio, next to the phone's own: " ++ "a Bluetooth dongle, or a combo adapter with WiFi and Bluetooth (MT7921AU, Realtek). It only listens for " ++ "advertisements, never connects. On a combo adapter WiFi and Bluetooth share the antennas. Off: only the phone's " ++ "Bluetooth scans.")info(binding.rtl5gSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS. Experimental.")info(binding.usbLightSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS: the light blinks with received traffic.")info(binding.pinpointSwitch, "Works out where a flagged device is from many readings as you move (GPS runs precise every second while one is in range).")@@ -971,6 +1042,7 @@ class SettingsActivity : AppCompatActivity() {searchHidden.forEach { if (it.getTag(R.id.search_hidden) == true) { it.setTag(R.id.search_hidden, null); it.visibility = View.VISIBLE } }searchHidden.clear()val q = raw.trim().lowercase()+ folds.values.forEach { it.searching(q.isNotEmpty()) }if (q.isEmpty()) {sectionUi.forEach { it.row.visibility = View.VISIBLE; it.divider?.visibility = View.VISIBLE; it.restore() }return@@ -1443,6 +1515,44 @@ class SettingsActivity : AppCompatActivity() {"to mute until you turn the sound back on.", "Snooze length"), at + 1)}+ /** Map > Re-center after, under Auto-recenter: how long after your last touch the map goes back to you. */+ private var recenterDelay: android.widget.Spinner? = null++ private fun setupRecenterDelay() {+ // Under the Auto-recenter row (with its ⓘ).+ val switchRow = binding.mapAutoRecenterSwitch.parent as? android.view.ViewGroup ?: return+ val section = switchRow.parent as? android.view.ViewGroup ?: return+ val choices = Prefs.RECENTER_CHOICES+ val row = android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ gravity = android.view.Gravity.CENTER_VERTICAL+ minimumHeight = (48 * resources.displayMetrics.density).toInt()+ }+ row.addView(android.widget.TextView(this).apply {+ text = "Re-center after"+ setTextAppearance(android.R.style.TextAppearance_Material_Body1)+ }, android.widget.LinearLayout.LayoutParams(0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1f))+ recenterDelay = androidx.appcompat.widget.AppCompatSpinner(this).apply {+ adapter = android.widget.ArrayAdapter(this@SettingsActivity, android.R.layout.simple_spinner_item,+ choices.map { if (it < 60) "$it s" else "${it / 60} min" }).also {+ it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)+ }+ setSelection(choices.indexOf(Prefs.mapRecenterSec(this@SettingsActivity)).coerceAtLeast(0))+ isEnabled = binding.mapAutoRecenterSwitch.isChecked+ contentDescription = "Re-center after"+ onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {+ override fun onItemSelected(parent: android.widget.AdapterView<*>?, view: View?, position: Int, id: Long) {+ Prefs.setMapRecenterSec(this@SettingsActivity, choices[position])+ }+ override fun onNothingSelected(parent: android.widget.AdapterView<*>?) {}+ }+ }+ row.addView(recenterDelay)+ section.addView(infoRow(row, "After you pan or zoom the map while driving, it goes back to following you once you " ++ "haven't touched it for this long. Turn Auto-recenter off to leave it where you put it.", "Re-center after"),+ section.indexOfChild(switchRow) + 1)+ }+/** Settings > Map: what the map shows (moved here from the map's menu). Saved as you switch. */private fun setupMapSection() {setupMapProvider()@@ -1455,7 +1565,7 @@ class SettingsActivity : AppCompatActivity() {binding.mapKnownCamerasSwitch.isChecked = Prefs.showKnownAlpr(this)binding.mapKnownCamerasSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowKnownAlpr(this, on) }binding.mapAutoRecenterSwitch.isChecked = Prefs.mapAutoRecenter(this)- binding.mapAutoRecenterSwitch.setOnCheckedChangeListener { _, on -> Prefs.setMapAutoRecenter(this, on) }+ binding.mapAutoRecenterSwitch.setOnCheckedChangeListener { _, on -> Prefs.setMapAutoRecenter(this, on); recenterDelay?.isEnabled = on }binding.mapSpeedometerSwitch.isChecked = Prefs.mapSpeedometer(this)binding.mapSpeedLimitLiveSwitch.isChecked = Prefs.mapSpeedLimitLive(this)binding.mapSpeedLimitLiveSwitch.isEnabled = binding.mapSpeedometerSwitch.isChecked@@ -1669,6 +1779,65 @@ class SettingsActivity : AppCompatActivity() {text.text = wifiLabel(slider.value.toInt())}+ /**+ * Under a category's switch: a chip per way it alerts you (the same chips as a watchlist entry's), on unless you+ * turn it off. Opened by the category's ▾ ([fold]); saved at once.+ */+ private fun addCategoryAlertChips(c: Category, sw: SwitchMaterial, fold: android.widget.TextView) {+ val dp = resources.displayMetrics.density+ val box = android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.VERTICAL+ setPadding((24 * dp).toInt(), 0, 0, (4 * dp).toInt())+ }+ box.addView(android.widget.TextView(this).apply {+ text = "Alerts you with"+ setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.text_caption))+ setTextColor(com.google.android.material.color.MaterialColors.getColor(this, android.R.attr.textColorSecondary))+ })+ val chips = com.google.android.material.chip.ChipGroup(this).apply {+ chipSpacingHorizontal = (6 * dp).toInt(); chipSpacingVertical = 0+ }+ var off = Prefs.categoryAlertsOff(this, c)+ com.rfsentinel.app.data.AlertKind.entries.forEach { kind ->+ chips.addView(com.rfsentinel.app.ui.FitChip(this).apply {+ text = kind.label; isCheckable = true+ com.rfsentinel.app.ui.ChipStyle.apply(this)+ isChecked = kind !in off+ contentDescription = "${kind.label} alerts for ${sw.contentDescription ?: sw.text}"+ setOnClickListener {+ off = if (isChecked) off - kind else off + kind+ Prefs.setCategoryAlertsOff(this@SettingsActivity, c, off)+ }+ })+ }+ box.addView(chips)+ binding.categoryContainer.addView(box)+ folds[sw] = Fold(sw, fold).also { it.add(box) }+ }++ private val folds = HashMap<SwitchMaterial, Fold>()++ /** A category's ▾ and what it opens: its alert chips, then its own settings (aircraft, Waze). */+ private inner class Fold(val sw: SwitchMaterial, val arrow: android.widget.TextView) {+ private var open = false+ private val panels = mutableListOf<View>()+ init {+ arrow.setOnClickListener { open = !open; show() }+ // Turning on a category that has its own settings opens them.+ sw.onToggle { on -> if (on && panels.size > 1) open = true; show() }+ }+ fun add(panel: View) { panels += panel; show() }+ /** Search only looks at what's shown: while searching, a category's own settings show, folded or not (not its chips). */+ fun searching(on: Boolean) { show(); if (on) panels.drop(1).forEach { it.shownIf(sw.isChecked) } }+ private fun show() {+ panels.forEach { it.shownIf(open && sw.isChecked) }+ arrow.text = if (open) "▴" else "▾"+ // Off: nothing to open, but the slot stays so the switches line up.+ arrow.visibility = if (sw.isChecked) View.VISIBLE else View.INVISIBLE+ arrow.contentDescription = "Options for ${sw.contentDescription ?: sw.text}, ${if (open) "expanded" else "collapsed"}"+ }+ }+/** Aircraft search radius (10-50 km) and the feed status, under the aircraft switch. */private fun addAircraftControls(sw: SwitchMaterial) {val dp = resources.displayMetrics.density@@ -1676,7 +1845,7 @@ class SettingsActivity : AppCompatActivity() {orientation = android.widget.LinearLayout.VERTICALsetPadding((24 * dp).toInt(), 0, 0, (6 * dp).toInt())}- box.addView(infoRow(SwitchMaterial(this).apply {+ box.addView(detectRow(SwitchMaterial(this).apply {text = "Online aircraft feeds"; isChecked = Prefs.aircraftOnline(this@SettingsActivity)setOnCheckedChangeListener { _, v -> Prefs.setAircraftOnline(this@SettingsActivity, v) }}, "Asks adsb.fi / adsb.lol every minute for aircraft near a position rounded to about 1 km. Turn off to use only " +@@ -1700,9 +1869,8 @@ class SettingsActivity : AppCompatActivity() {aircraftStatusText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }box.addView(aircraftStatusText)showNote(aircraftStatusText, com.rfsentinel.app.online.OnlineWatch.aircraftStatus)- box.shownIf(sw.isChecked)binding.categoryContainer.addView(box)- sw.setOnCheckedChangeListener { _, on -> box.shownIf(on) }+ folds[sw]?.add(box)}/**@@ -1909,9 +2077,9 @@ class SettingsActivity : AppCompatActivity() {text = "Waze status"setOnClickListener { com.rfsentinel.app.ui.WazeUi.openStatus(this@SettingsActivity) }})- box.shownIf(sw.isChecked)binding.categoryContainer.addView(box)- sw.setOnCheckedChangeListener { _, on ->+ folds[sw]?.add(box)+ sw.onToggle { on ->if (on && !Prefs.wazeReady(this)) {sw.isChecked = falseval direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT@@ -1925,9 +2093,7 @@ class SettingsActivity : AppCompatActivity() {}.setNegativeButton("Cancel", null).show()- return@setOnCheckedChangeListener}- box.shownIf(on)}}@@ -2138,17 +2304,20 @@ class SettingsActivity : AppCompatActivity() {isChecked = Prefs.categoryEnabled(this@SettingsActivity, c)}val details = listOfNotNull(more, if (c == Category.POLICE_REPORT) WAZE_WARNING_SHORT else null).joinToString("\n\n")- binding.categoryContainer.addView(if (details.isEmpty()) sw else infoRow(sw, details, short))+ val fold = foldIcon()+ binding.categoryContainer.addView(detectRow(sw, details.ifEmpty { null }, short, fold))categorySwitches[c] = sw+ addCategoryAlertChips(c, sw, fold)if (c == Category.TRACKER) {airTagSwitch = SwitchMaterial(this).apply {text = "Exclude Apple AirTags"isChecked = Prefs.excludeAirTags(this@SettingsActivity)- setPadding((24 * resources.displayMetrics.density).toInt(), 0, 0, 0)isEnabled = sw.isChecked}- sw.setOnCheckedChangeListener { _, on -> airTagSwitch?.isEnabled = on }- binding.categoryContainer.addView(airTagSwitch)+ sw.onToggle { on -> airTagSwitch?.isEnabled = on }+ binding.categoryContainer.addView(detectRow(airTagSwitch!!).apply {+ setPadding((24 * resources.displayMetrics.density).toInt(), 0, 0, 0)+ })}if (c == Category.AIRCRAFT) addAircraftControls(sw)if (c == Category.POLICE_REPORT) addWazeControls(sw)@@ -2253,6 +2422,7 @@ class SettingsActivity : AppCompatActivity() {binding.usbWifiLogButton.setOnClickListener { exportUsbWifiLog() }// FOSS build: an adapter waiting for its chip firmware asks to download it.binding.usbWifiText.setOnClickListener { com.rfsentinel.app.usb.FirmwarePrompt.show(this) { updateEspStatus() } }+ binding.usbBtText.setOnClickListener { com.rfsentinel.app.usb.FirmwarePrompt.show(this) { updateEspStatus() } }if (intent.getBooleanExtra(com.rfsentinel.app.usb.FirmwarePrompt.EXTRA, false)) {intent.removeExtra(com.rfsentinel.app.usb.FirmwarePrompt.EXTRA)com.rfsentinel.app.usb.FirmwarePrompt.show(this) { updateEspStatus() }@@ -2289,6 +2459,7 @@ class SettingsActivity : AppCompatActivity() {setupLiveExport()setupWigleAccount()addDetails()+ setupRecenterDelay()binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)binding.hideTrustedSwitch.setOnCheckedChangeListener { _, on -> Prefs.setHideWhitelisted(this, on) }binding.usbLightSwitch.isChecked = Prefs.usbAdapterLight(this)@@ -2296,6 +2467,12 @@ class SettingsActivity : AppCompatActivity() {Prefs.setUsbAdapterLight(this, on)com.rfsentinel.app.usb.Rtl8821auMonitor.lightEnabled = on // live, also while scanning}+ binding.usbBtSwitch.isChecked = Prefs.usbBluetooth(this)+ binding.usbBtSwitch.setOnCheckedChangeListener { _, on ->+ Prefs.setUsbBluetooth(this, on)+ com.rfsentinel.app.usb.UsbBluetooth.settingChanged(this) // starts or stops it live while scanning+ updateEspStatus()+ }binding.rtl5gSwitch.isChecked = Prefs.rtl8821au5g(this)binding.rtl5gSwitch.setOnCheckedChangeListener { _, on -> Prefs.setRtl8821au5g(this, on) }binding.autoUpdateSwitch.isChecked = Prefs.autoUpdateCheck(this)@@ -2364,6 +2541,7 @@ class SettingsActivity : AppCompatActivity() {confirm("Forget device history?", "New/returning status, detect counts and the cell towers remembered for the fake-cell checks start over. Favorites are kept.") {lifecycleScope.launch {AppDatabase.getInstance(this@SettingsActivity).knownDeviceDao().clearNonFavorites()+ AppDatabase.getInstance(this@SettingsActivity).deviceDetailsDao().pruneOrphans()com.rfsentinel.app.service.CellMonitor.forget(this@SettingsActivity)com.rfsentinel.app.service.CellTowerStore.forget(this@SettingsActivity)Toast.makeText(this@SettingsActivity, "Device history cleared", Toast.LENGTH_SHORT).show()diff --git a/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.ktindex 05fcc85..1bbdb8e 100644--- a/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt@@ -27,6 +27,8 @@ import kotlinx.coroutines.launch* Antenna check for the USB WiFi adapter (after Wardrive Go's): pick a nearby access point as* the reference, the adapter holds its channel, and its frames are compared per antenna (chain 0* vs chain 1, with Zero and Identify) and between captures with antenna A and antenna B.+ * With a USB Bluetooth adapter, the reference is a nearby Bluetooth LE device and the swap test+ * compares the antennas (one signal per advertisement, so no Zero / Identify).* Signal only, not SWR. Scanning goes back to hopping when the screen closes.*/class AntennaCheckActivity : AppCompatActivity() {@@ -48,6 +50,8 @@ class AntennaCheckActivity : AppCompatActivity() {private var auto = true/** When Auto started listening (the screen opened, or the reference was dropped). */private var autoSince = 0L+ /** Checking the USB Bluetooth adapter's antennas instead of the USB WiFi adapter's. */+ private var bt = falseprivate val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {init { setHasStableIds(true) } // rows stay put across refreshes, so a tap isn't lost to a rebind@@ -58,7 +62,7 @@ class AntennaCheckActivity : AppCompatActivity() {override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {val ap = aps[position]ItemDetectionBinding.bind(holder.itemView).apply {- labelText.text = ap.ssid ?: "Hidden network"+ labelText.text = ap.ssid ?: if (bt) "Unnamed device" else "Hidden network"macText.text = ap.bssidmetaText.text = "${AntennaCheck.channelName(ap.channel)} · ${ap.rssi} dBm"}@@ -80,6 +84,14 @@ class AntennaCheckActivity : AppCompatActivity() {binding.identifyButton.setOnClickListener { identifyNow() }binding.captureA.setOnClickListener { capture(a = true) }binding.captureB.setOnClickListener { capture(a = false) }+ binding.radioGroup.check(R.id.radioWifi)+ binding.radioGroup.addOnButtonCheckedListener { _, id, checked ->+ if (!checked || (id == R.id.radioBt) == bt) return@addOnButtonCheckedListener+ bt = id == R.id.radioBt+ AntennaCheck.useBluetooth(bt)+ binding.modePick.text = if (bt) "Pick device" else "Pick AP"+ pick(null)+ }binding.modeGroup.check(R.id.modeAuto)binding.modeGroup.addOnButtonCheckedListener { _, id, checked ->if (!checked) return@addOnButtonCheckedListener@@ -99,6 +111,7 @@ class AntennaCheckActivity : AppCompatActivity() {override fun onStart() {super.onStart()AntennaCheck.open()+ AntennaCheck.useBluetooth(bt)if (ref == null) autoSince = System.currentTimeMillis()ref?.let { AntennaCheck.lock(it.bssid, it.channel); lockedAt = System.currentTimeMillis() }}@@ -150,8 +163,9 @@ class AntennaCheckActivity : AppCompatActivity() {private fun showCaptures() {val a = capA; val b = capB+ val unit = if (bt) "adverts" else "frames"fun line(name: String, s: AntennaCheck.Stats?) = if (s == null) "$name: not captured" else- "$name: %.1f dBm, %d frames".format(s.rssi, s.frames) ++ "$name: %.1f dBm, %d $unit".format(s.rssi, s.frames) +if (s.a != null && s.b != null) " · chain 0 %.1f, chain 1 %.1f".format(s.a, s.b) else ""val out = mutableListOf(line("A", a), line("B", b))if (a?.rssi != null && b?.rssi != null) {@@ -186,6 +200,13 @@ class AntennaCheckActivity : AppCompatActivity() {private fun feedDemo() {val now = System.currentTimeMillis()+ if (bt) {+ listOf("02:00:00:00:00:11" to "Demo speaker", "02:00:00:00:00:12" to null).forEachIndexed { i, (m, n) ->+ AntennaCheck.heardBt(m, n, -55 - 10 * i, now)+ }+ repeat(3) { AntennaCheck.demoSample(-58 - (0..3).random(), null, null, now) }+ return+ }val single = intent.getBooleanExtra("single", false)listOf(Triple("02:00:00:00:00:01", "Demo network", 36), Triple("02:00:00:00:00:02", null, 6),Triple("02:00:00:00:00:03", "A much longer demo network name", 5975)).forEachIndexed { i, (m, n, ch) ->@@ -201,13 +222,20 @@ class AntennaCheckActivity : AppCompatActivity() {@SuppressLint("NotifyDataSetChanged", "SetTextI18n")private fun refresh() {val now = System.currentTimeMillis()- val live = demo || ScanForegroundService.isRunning && UsbWifi.status.contains("live")+ val running = ScanForegroundService.isRunning+ val wifiLive = demo || running && UsbWifi.status.contains("live")+ val btLive = demo || running && com.rfsentinel.app.usb.UsbBluetooth.runningChip != null+ // Only one adapter live: the check is on that one; both: the WiFi / Bluetooth buttons choose.+ if (bt && !btLive && wifiLive) binding.radioGroup.check(R.id.radioWifi)+ if (!bt && !wifiLive && btLive) binding.radioGroup.check(R.id.radioBt)+ binding.radioGroup.visibility = if (wifiLive && btLive) View.VISIBLE else View.GONE+ val live = if (bt) btLive else wifiLiveif (!live) {binding.pickPanel.visibility = View.GONEbinding.checkPanel.visibility = View.GONEbinding.emptyText.visibility = View.VISIBLE- binding.emptyText.text = "Start a scan with a USB WiFi adapter plugged in.\n" +- "The check tests the adapter's antennas, not the phone's own WiFi."+ binding.emptyText.text = "Start a scan with a USB WiFi or Bluetooth adapter plugged in.\n" ++ "The check tests the adapter's antennas, not the phone's own."return}binding.emptyText.visibility = View.GONE@@ -222,32 +250,55 @@ class AntennaCheckActivity : AppCompatActivity() {}if (auto) {binding.apList.visibility = View.GONE- AntennaCheck.strongest(fresh, now, autoSince)?.let { pick(it); return }- val left = ((autoSince + 12_000 - now) / 1000).coerceAtLeast(0)- binding.pickHint.text = if (left > 0) "Finding the strongest access point… $left s\nThe adapter visits every channel first."- else "No access point heard yet: keep the adapter near a WiFi network."+ val settle = if (bt) 5_000L else 12_000L+ AntennaCheck.strongest(fresh, now, autoSince, settle, if (bt) 3_000L else 8_000L)?.let { pick(it); return }+ val left = ((autoSince + settle - now) / 1000).coerceAtLeast(0)+ binding.pickHint.text = when {+ bt && left > 0 -> "Finding the strongest Bluetooth device… $left s"+ bt -> "No Bluetooth device heard yet: keep the adapter near a speaker, TV or other Bluetooth device."+ left > 0 -> "Finding the strongest access point… $left s\nThe adapter visits every channel first."+ else -> "No access point heard yet: keep the adapter near a WiFi network."+ }return}binding.apList.visibility = View.VISIBLE- binding.pickHint.text = if (aps.isEmpty()) "Listening for access points… the adapter visits every channel, which can take 15 s."- else "Tap a strong access point that stays put to use as the reference:"+ binding.pickHint.text = when {+ bt && aps.isEmpty() -> "Listening for Bluetooth devices…"+ bt -> "Tap a strong device that stays put (a speaker, TV or beacon) to use as the reference:"+ aps.isEmpty() -> "Listening for access points… the adapter visits every channel, which can take 15 s."+ else -> "Tap a strong access point that stays put to use as the reference:"+ }return}binding.pickPanel.visibility = View.GONEbinding.checkPanel.visibility = View.VISIBLEval s = AntennaCheck.stats(now - 5_000, now)- val holding = AntennaCheck.holding == r.channel- binding.adapterName.text = if (demo) "Demo adapter" else UsbWifi.runningChip ?: "USB WiFi adapter"+ val holding = bt || AntennaCheck.holding == r.channel+ binding.adapterName.text = when {+ demo -> "Demo adapter"+ bt -> com.rfsentinel.app.usb.UsbBluetooth.runningChip?.let { "$it Bluetooth" } ?: "USB Bluetooth adapter"+ else -> UsbWifi.runningChip ?: "USB WiFi adapter"+ }binding.channelChip.text = AntennaCheck.channelName(r.channel)- binding.refTitle.text = (if (auto) "Auto · " else "") + "Reference: ${r.ssid ?: "Hidden network"}"+ binding.refTitle.text = (if (auto) "Auto · " else "") + "Reference: ${r.ssid ?: if (bt) "Unnamed device" else "Hidden network"}"val stuck = !holding && now - lockedAt > 8_000val hold = when {+ bt -> "all advertising channels"holding -> "channel held"stuck -> "can't hold this channel"else -> "switching to its channel…"}binding.refSub.text = "${AntennaCheck.channelName(r.channel)} · $hold\n" +- "${s.frames} frames in the last 5 s" + (s.rssi?.let { " · %.1f dBm".format(it) } ?: "")+ "${s.frames} ${if (bt) "adverts" else "frames"} in the last 5 s" + (s.rssi?.let { " · %.1f dBm".format(it) } ?: "")+ // Bluetooth: one signal per advertisement, so only the swap test applies.+ val chainVis = if (bt) View.GONE else View.VISIBLE+ binding.chainButtons.visibility = chainVis+ binding.identifyText.visibility = chainVis+ binding.zeroHelp.visibility = chainVis+ binding.aboutText.text = if (bt) "This compares how strongly each antenna hears the reference Bluetooth device. " ++ "It doesn't measure SWR or impedance. On a combo adapter WiFi and Bluetooth share the antennas."+ else "This compares how strongly each antenna hears the reference access point. It doesn't measure SWR or " ++ "impedance. While this screen is open the adapter stays on the reference's channel."val recent = AntennaCheck.stats(now - 15_000, now)val dual = recent.both >= AntennaCheck.MIN_BOTH@@ -265,8 +316,14 @@ class AntennaCheckActivity : AppCompatActivity() {binding.chainVerdict.text = "No frames from the reference in the last 5 s."} else {binding.meter.setSingle(s.rssi, history)- binding.chainVerdict.text = if (s.frames >= 5) "This adapter reports one signal for these frames, not one per antenna: use the swap test below."- else "Waiting for frames from the reference…"+ binding.chainVerdict.text = when {+ bt && s.frames >= 5 -> "A Bluetooth adapter reports one signal per advertisement, not one per antenna: use the swap test below."+ bt && now - lockedAt > 10_000 && AntennaCheck.stats(now - 10_000, now).frames == 0 ->+ "Nothing from the reference in 10 s: it may have changed its address. Change the reference."+ bt -> "Waiting for advertisements from the reference…"+ s.frames >= 5 -> "This adapter reports one signal for these frames, not one per antenna: use the swap test below."+ else -> "Waiting for frames from the reference…"+ }}if (stuck) binding.chainVerdict.text = "This adapter can't stay on that channel: change the reference."diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.ktindex 1e40552..8fab560 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt@@ -29,6 +29,8 @@ data class DeviceRow(/** Heard by an ESP32 board (blue badge) and/or the phone's own radios (green badge). */val heardByEsp: Boolean = false,val heardByUsb: Boolean = false,+ /** Heard by a USB Bluetooth adapter. */+ val heardByUsbBt: Boolean = false,val heardByPhone: Boolean = false,/** The linked Sentinel that heard it (Sentinel Link), or null. */val heardByPeer: String? = null,@@ -38,7 +40,10 @@ data class DeviceRow(/** Added to [rssi] for the bars only: cell signals run about 10 dB lower than WiFi and Bluetooth. */val barBoost: Int = 0,/** A group's header ("Trackers · 3", Group by in the ⋮ menu): [title] only, not a device. */- val header: Boolean = false+ val header: Boolean = false,+ /** A flagged device: its row has the mute button ([com.rfsentinel.app.data.AlertMutes]). */+ val canMute: Boolean = false,+ val muted: Boolean = false) {companion object {/** Keyed by the group ([key]), not its label: the count changing must not swap the row (it flickered). */@@ -53,7 +58,7 @@ private const val PEER_BADGE = 0xFF00838F.toInt()/** The meta line, followed by small coloured "ESP32" / "INTERNAL" / "VIA <Sentinel>" badges. */private fun metaWithBadges(row: DeviceRow): CharSequence {- if (!row.heardByEsp && !row.heardByUsb && !row.heardByPhone && row.heardByPeer == null) return row.meta+ if (!row.heardByEsp && !row.heardByUsb && !row.heardByUsbBt && !row.heardByPhone && row.heardByPeer == null) return row.metaval sb = android.text.SpannableStringBuilder(row.meta)fun badge(label: String, color: Int) {sb.append(" ")@@ -66,6 +71,7 @@ private fun metaWithBadges(row: DeviceRow): CharSequence {}if (row.heardByEsp) badge("ESP32", ESP_BADGE)if (row.heardByUsb) badge("USB WIFI", USB_BADGE)+ if (row.heardByUsbBt) badge("USB BT", USB_BADGE)if (row.heardByPhone) badge("INTERNAL", PHONE_BADGE)row.heardByPeer?.let { badge("VIA " + it.uppercase(), PEER_BADGE) }return sb@@ -73,7 +79,9 @@ private fun metaWithBadges(row: DeviceRow): CharSequence {class DeviceAdapter(private val onClick: (DeviceRow) -> Unit,- private val onLongPress: (DeviceRow) -> Unit+ private val onLongPress: (DeviceRow) -> Unit,+ /** The mute button on a flagged row; [forever] on a long press. Null: no mute buttons. */+ private val onMute: ((row: DeviceRow, forever: Boolean) -> Unit)? = null) : ListAdapter<DeviceRow, RecyclerView.ViewHolder>(Diff) {/** Visual style: signal bars and a confidence bar on each row (Settings > Appearance, or the list's own choice). */@@ -159,6 +167,17 @@ class DeviceAdapter(b.signalBars.set(row.rssi + row.barBoost)b.signalText.text = "${row.rssi}"}+ val mute = onMute?.takeIf { row.canMute }+ b.muteButton.visibility = if (mute != null) View.VISIBLE else View.GONE+ if (mute != null) {+ // Muted: in the highlight colour; tap again to unmute.+ b.muteButton.imageTintList = android.content.res.ColorStateList.valueOf(+ if (row.muted) ChipStyle.accent(b.root.context).first else ChipStyle.onSurface(b.root.context))+ b.muteButton.alpha = if (row.muted) 1f else 0.6f+ b.muteButton.contentDescription = if (row.muted) "Unmute this device's alerts" else "Mute this device's alerts"+ b.muteButton.setOnClickListener { mute(row, false) }+ b.muteButton.setOnLongClickListener { mute(row, true); true }+ }holder.setHighlight(row.highlight, row.flashing)holder.itemView.setOnClickListener { onClick(row) }holder.itemView.setOnLongClickListener { onLongPress(row); true }diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.ktindex f9d840a..2938bb4 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt@@ -22,9 +22,6 @@ import com.rfsentinel.app.data.Favoritesimport com.rfsentinel.app.data.KnownDeviceEntityimport com.rfsentinel.app.data.WhitelistCacheimport com.rfsentinel.app.databinding.ActivityDeviceDetailBinding-import com.rfsentinel.app.detect.AdStructure-import com.rfsentinel.app.detect.Advert-import com.rfsentinel.app.detect.Bytesimport com.rfsentinel.app.detect.DeviceIntelimport com.rfsentinel.app.detect.Tierimport com.rfsentinel.app.detect.VendorDb@@ -66,6 +63,12 @@ class DeviceDetailActivity : AppCompatActivity() {/** The saved record's type as this version names it. */private val knownType get() = known?.let { DeviceIntel.savedType(it.deviceType, it.vendor, it.mac) }private var pastMatches: List<DetectionEntity> = emptyList()+ /** The newest saved match of each kind, as hits: what the page shows while the device isn't heard. */+ private var pastHits: List<com.rfsentinel.app.detect.Hit> = emptyList()+ /** Its page as it was when last heard: what the page shows while the device isn't heard. */+ private var saved: com.rfsentinel.app.data.LastHeard.Saved? = null+ /** The saved page, while the device isn't heard here now. */+ private fun savedNow(s: DeviceRegistry.Snapshot?) = if (s == null) saved else nullprivate val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)private val timeFmt = DateFormat.getTimeInstance(DateFormat.MEDIUM)@@ -124,6 +127,11 @@ class DeviceDetailActivity : AppCompatActivity() {val db = AppDatabase.getInstance(this@DeviceDetailActivity)known = db.knownDeviceDao().get(mac)pastMatches = db.detectionDao().forMac(mac)+ saved = db.deviceDetailsDao().get(mac)?.let { com.rfsentinel.app.data.LastHeard.fromJson(it.json) }+ pastHits = pastMatches.distinctBy { it.label }.take(5).map { m ->+ com.rfsentinel.app.detect.Hit(com.rfsentinel.app.detect.Category.parse(m.category) ?: com.rfsentinel.app.detect.Category.CUSTOM,+ m.label, m.confidence, m.evidence, "")+ }sectionsKey = ""refresh()}@@ -166,6 +174,9 @@ class DeviceDetailActivity : AppCompatActivity() {val now = System.currentTimeMillis()val whitelisted = WhitelistCache.contains(mac)val best = s?.best+ val last = savedNow(s)+ // Not heard now: its strongest match as last heard, else from the match history, like the list showed it.+ val pastBest = last?.best ?: pastHits.maxByOrNull { it.confidence }// Headerif (whitelisted) {@@ -176,10 +187,15 @@ class DeviceDetailActivity : AppCompatActivity() {binding.tagText.visibility = View.VISIBLEbinding.tagText.text = "${best.category.shortTag} · ${best.tier.label} ${best.confidence}%"binding.tagText.setBackgroundColor(ThemeManager.ink(this, if (best.tier == Tier.WEAK) 0xFFB26A00.toInt() else best.category.colorArgb))+ } else if (s == null && pastBest != null) {+ val h = pastBest+ binding.tagText.visibility = View.VISIBLE+ binding.tagText.text = "${h.category.shortTag} · ${h.tier.label} ${h.confidence}%"+ binding.tagText.setBackgroundColor(ThemeManager.ink(this, if (h.tier == Tier.WEAK) 0xFFB26A00.toInt() else h.category.colorArgb))} else {binding.tagText.visibility = View.GONE}- val heardAs = best?.label ?: s?.name ?: known?.name ?: s?.deviceType ?: knownType ?: "Device"+ val heardAs = best?.label ?: s?.name ?: pastBest?.label ?: known?.name ?: s?.deviceType ?: knownType ?: "Device"val alias = DeviceNames.of(mac)// Your own name in place of what it's heard as; that stays on the line below.binding.titleText.text = alias ?: heardAs@@ -190,7 +206,8 @@ class DeviceDetailActivity : AppCompatActivity() {binding.noteText.text = note?.let { "\uD83D\uDCDD $it" }binding.presenceText.text = when {liveMac != mac && live != null -> "In range under its new address $liveMac (it changed its address) · heard ${ago(now - live.lastSeen)}"- s == null -> "Not in range right now" + (known?.let { " · last heard ${dateFmt.format(Date(it.lastSeen))}" } ?: "")+ s == null -> "Not in range right now" + (known?.let { " · last heard ${dateFmt.format(Date(it.lastSeen))}" } ?: "") ++ (last?.takeIf { it.following }?.let { "\n⚠ Was moving with you" } ?: "")s.following -> "⚠ Has been moving with you"else -> "In range · heard ${ago(now - s.lastSeen)} · ${s.sightings} packets received"}@@ -199,7 +216,7 @@ class DeviceDetailActivity : AppCompatActivity() {val visual = this.visualbinding.visualTop.visibility = if (visual) View.VISIBLE else View.GONEbinding.rssiText.visibility = if (visual) View.GONE else View.VISIBLE- val ringHit = best?.takeIf { !whitelisted }+ val ringHit = (best ?: last?.best)?.takeIf { !whitelisted }binding.ring.visibility = if (ringHit != null) View.VISIBLE else View.GONEif (ringHit != null) binding.ring.set(ringHit.confidence,ThemeManager.ink(this, if (ringHit.tier == Tier.WEAK) 0xFFB26A00.toInt() else ringHit.category.colorArgb),@@ -222,8 +239,12 @@ class DeviceDetailActivity : AppCompatActivity() {} else {binding.rssiText.text = "--"binding.gauge.set(null, null, 0)- binding.rssiDetail.text = "Not currently heard"- binding.graph.setSamples(emptyList())+ // As last heard: its last reading, best and the signal graph then.+ binding.rssiDetail.text = "Not currently heard" + (last?.let {+ "\nLast ${it.rssi} dBm · ${ProximityUtil.band(it.rssi)}\n" ++ "${DeviceIntel.formatDistance(it.distanceM)} (rough) · best ${it.bestRssi} dBm"+ } ?: "")+ binding.graph.setSamples(last?.samples.orEmpty())binding.locateButton.isEnabled = falsestopLocate()}@@ -256,167 +277,27 @@ class DeviceDetailActivity : AppCompatActivity() {}}- private fun buildSections(s: DeviceRegistry.Snapshot?): List<Pair<String, List<Pair<String, String>>>> {- val out = mutableListOf<Pair<String, List<Pair<String, String>>>>()- val a = s?.advert-- // Why flagged- if (s != null) {- out += "Why it's flagged" to if (s.hits.isEmpty()) {- listOf("Result" to "Not flagged - no watchlist entry or equipment signature matched.")- } else {- s.hits.flatMap { h ->- listOf(- "● ${h.label}" to "${h.category.title} · ${h.tier.label} (${h.confidence}%)",- " Evidence" to h.evidence,- " Source" to h.source- )- }- }- }-- // Identity- val id = mutableListOf<Pair<String, String>>()- (s?.deviceType ?: knownType)?.let { id += "Device type" to it }- // The category the list files it under (a device no longer heard: from its saved type and name).- (s?.let { DeviceFilter.seen(it) } ?: knownType?.let {- DeviceFilter.Seen(mac, it, known?.name, emptyList(), emptySet(), false, vendor = VendorDb.macVendor(mac))- })?.let { id += "Category" to DeviceOrder.categoryLabel(it) }- (s?.name ?: known?.name)?.let { id += (if (a?.isWifi == true) "Network name (SSID)" else "Advertised name") to it }- VendorDb.macVendor(mac)?.let { id += "Address registrant (IEEE)" to it }- a?.manufacturerData?.keys?.forEach { cid ->- id += "Bluetooth company" to (VendorDb.company(cid) ?: "Unknown") + String.format(" (0x%04X)", cid)- }- if (s != null) {- id += "Address type" to s.addressType.label- id += "Trackability" to s.addressType.trackability(known?.firstSeen, known?.lastSeen, known?.sessions ?: 0,- com.rfsentinel.app.service.DeviceRegistry.linkedFrom(mac) != null)- id += "Radio" to s.sources.joinToString(" + ") { if (it == Advert.Source.BLE) "Bluetooth LE" else "WiFi" }- }- a?.connectable?.let { id += "Connectable" to if (it) "Yes (accepts connections)" else "No (broadcast only)" }- a?.phy?.let { id += "PHY" to it }- a?.txPower?.let { id += "Advertised TX power" to "$it dBm" }- s?.facts?.forEach { id += it }- DeviceNames.lookalike(mac, DeviceRegistry.fingerprintOf(DeviceRegistry.currentAddress(mac)))?.let {- id += "Looks like" to "Your \"$it\": its adverts look the same, so it's that device under a new address, or one of the same model"- }- DeviceRegistry.companions(DeviceRegistry.currentAddress(mac)).takeIf { it.isNotEmpty() }?.let { c ->- id += "Moved together with" to c.joinToString("\n") { (m, label) -> (DeviceNames.of(m) ?: label) + " · " + m }- }- s?.hits?.firstOrNull { it.category == com.rfsentinel.app.detect.Category.TRACKER }- ?.takeIf { !com.rfsentinel.app.detect.SignatureEngine.reportsOwnerState(it) }?.let {- DeviceRegistry.ownerPhone(DeviceRegistry.currentAddress(mac))?.let { phone ->- id += "With its owner" to "Moved with $phone at every place: most likely that phone owner's tag, so it doesn't alert as following you"- }- }- // Heard by a USB WiFi adapter / Marauder board: its WPS block, fingerprint, network requests.- com.rfsentinel.app.usb.ProbeIntel.of(mac)?.let { r ->- if (r.hidden) id += "Hidden network" to (s?.name?.let { "Its name, \"$it\", was revealed by a device joining or asking for it" }- ?: "It hides its name - shown once a device joins or asks for it (USB WiFi adapter)")- r.wps?.deviceName?.let { id += "Device name (WPS)" to it }- r.wps?.product?.let { id += "Maker / model (WPS)" to it }- r.fingerprint?.let { fp ->- id += "Probe fingerprint" to fp + if (OuiWatchlist.isFingerprintWatched(fp)) " · on your watchlist" else- " (same for every device of this model / OS - Watchlist can watch it)"- }- r.skeleton?.let { sk ->- id += "Probe shape" to "%08x".format(sk) + (com.rfsentinel.app.detect.SignatureEngine.probeShapeNote(sk)?.let { " · $it" } ?: "") +- if (OuiWatchlist.isFingerprintWatched(com.rfsentinel.app.usb.ProbeIntel.shapeKey(sk))) " · on your watchlist" else ""- }- if (r.probed.isNotEmpty()) id += "Networks it asked for" to r.probed.reversed().joinToString(", ")- }- a?.wifi?.probeRun?.let { run ->- id += "Wildcard probes" to run.describe() +- if (run.nonStop) " · non-stop, like a mains-powered fixed device" else ""- }- if (id.isNotEmpty()) out += "Identity" to id-- // Drone Remote ID- s?.remoteId?.let { r ->- val rows = mutableListOf<Pair<String, String>>()- r.uasId?.let { rows += "UAS ID" to it }- r.idType?.let { rows += "ID type" to it }- r.uaType?.let { rows += "Aircraft type" to it }- r.status?.let { rows += "Status" to it }- if (r.hasPosition) rows += "Drone position" to String.format(Locale.US, "%.6f, %.6f", r.latitude, r.longitude)- r.altitudeGeoM?.let { rows += "Altitude (WGS84)" to String.format(Locale.US, "%.0f m", it) }- r.heightM?.let { rows += "Height above takeoff/ground" to String.format(Locale.US, "%.0f m", it) }- r.speedMs?.let { rows += "Ground speed" to String.format(Locale.US, "%.1f m/s (%s)", it, com.rfsentinel.app.util.Units.speed(it)) }- r.verticalSpeedMs?.let { rows += "Vertical speed" to String.format(Locale.US, "%.1f m/s", it) }- r.directionDeg?.let { rows += "Heading" to "$it°" }- if (r.hasOperatorPosition) rows += "Operator position" to String.format(Locale.US, "%.6f, %.6f", r.operatorLatitude, r.operatorLongitude)- r.operatorId?.let { rows += "Operator ID" to it }- r.selfIdDescription?.let { rows += "Description" to it }- out += "Drone Remote ID (ASTM F3411)" to rows- }-- // Session & history- val hist = mutableListOf<Pair<String, String>>()- if (s != null) {- hist += "First heard this session" to timeFmt.format(Date(s.firstSeen))- }- known?.let {- hist += "First ever seen" to dateFmt.format(Date(it.firstSeen))- hist += "Last seen (saved)" to dateFmt.format(Date(it.lastSeen))- hist += "Scanning sessions seen in" to "${it.sessions}"- hist += "Detect count" to "${it.detectCount} (at most one per minute)"- } ?: run { hist += "History" to "First time this address has been heard" }- if (pastMatches.isNotEmpty()) {- hist += "Logged matches" to "${pastMatches.size}" + (if (pastMatches.size >= 200) "+" else "")- pastMatches.take(5).forEach { m ->- hist += dateFmt.format(Date(m.timestamp)) to "${m.label} · ${m.rssi} dBm" +- (if (m.latitude != null) String.format(Locale.US, " · %.5f, %.5f", m.latitude, m.longitude) else "")+ private fun buildSections(s: DeviceRegistry.Snapshot?): List<DeviceSection> {+ val last = savedNow(s) ?: return DeviceSections.build(this, mac, s, known, pastMatches, pastHits)+ // Not heard now: its page as last heard, with the saved record and match history as they are now.+ return last.sections.map { (title, rows) ->+ when (title) {+ DeviceSections.FLAGGED -> DeviceSections.WAS_FLAGGED to+ if (last.hits.isEmpty() && pastHits.isNotEmpty()) DeviceSections.pastMatchRows(pastMatches, pastHits) else rows+ DeviceSections.HISTORY -> title to listOf(+ "Last heard" to dateFmt.format(Date(last.firstSeen)) + " - " + timeFmt.format(Date(last.at)) ++ " · ${last.sightings} packets received"+ ) + DeviceSections.savedRows(known, pastMatches) + rows+ else -> title to rows}}- if (s != null && s.path.size >= 2) {- val first = s.path.first()- val moved = s.path.maxOf { DeviceRegistry.metersBetween(first.lat, first.lon, it.lat, it.lon) }- hist += "Travelled with you" to String.format(Locale.US, "%.0f m while in range", moved)- }- s?.broadcast?.let { b ->- hist += "Position (its own GPS, over V2X)" to String.format(Locale.US, "%.6f, %.6f", b.lat, b.lon)- } ?: s?.located?.let { e ->- hist += "Pinpointed position" to String.format(Locale.US, "%.6f, %.6f · ", e.lat, e.lon) +- com.rfsentinel.app.detect.Locator.describe(e)- } ?: s?.takeIf { it.best != null && !it.following && com.rfsentinel.app.util.Prefs.pinpointFlagged(this) }?.let {- hist += "Pinpointing" to "Not yet: pass it from more than one side (around the block) and it is placed on the map " +- "with the circle it is very likely in"- }- out += "History" to hist-- // Raw advertisement- if (a != null) {- val raw = mutableListOf<Pair<String, String>>()- a.manufacturerData.forEach { (cid, data) ->- raw += String.format("Manufacturer 0x%04X", cid) to Bytes.hex(data)- }- a.serviceUuids.forEach { u ->- val short = Advert.shortOf(u)- raw += "Service UUID" to (if (short != null) String.format("0x%04X", short) + (VendorDb.uuid16(short)?.let { " - $it" } ?: "") else u.toString())- }- a.serviceData.forEach { (u, data) ->- val short = Advert.shortOf(u)- val label = if (short != null) String.format("0x%04X", short) + (VendorDb.uuid16(short)?.let { " $it" } ?: "") else u.toString()- raw += "Service data $label" to Bytes.hex(data)- }- AdStructure.parse(a.rawBytes).forEach { ad ->- raw += String.format("AD 0x%02X %s", ad.type, ad.typeName) to Bytes.hex(ad.data).ifEmpty { "(empty)" }- }- a.wifi?.let { w ->- raw += "Capabilities" to w.capabilities.ifEmpty { "(none)" }- raw += "Information elements" to "${w.infoElements.size}" +- if (w.infoElements.isNotEmpty()) " (IDs " + w.infoElements.map { it.first }.distinct().joinToString() + ")" else ""- }- if (raw.isNotEmpty()) out += "Raw advertisement" to raw- }- return out}- private fun renderSections(sections: List<Pair<String, List<Pair<String, String>>>>) {+ private fun renderSections(sections: List<DeviceSection>) {val container = binding.sectionscontainer.removeAllViews()val dp = resources.displayMetrics.density- val hits = DeviceRegistry.get(mac)?.hits.orEmpty()+ val hits = DeviceRegistry.get(mac)?.hits ?: saved?.hits.orEmpty()for ((title, rows) in sections) {container.addView(TextView(this).apply {text = title@@ -424,7 +305,7 @@ class DeviceDetailActivity : AppCompatActivity() {setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)setPadding(0, (18 * dp).toInt(), 0, (4 * dp).toInt())})- if (visual && title == "Why it's flagged" && hits.isNotEmpty()) {+ if (visual && (title == DeviceSections.FLAGGED || title == DeviceSections.WAS_FLAGGED) && hits.isNotEmpty()) {hits.forEach { container.addView(hitCard(it)) }continue}@@ -441,7 +322,7 @@ class DeviceDetailActivity : AppCompatActivity() {text = vsetTextIsSelectable(true)setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)- if (title == "Raw advertisement") typeface = Typeface.MONOSPACE+ if (title == DeviceSections.RAW) typeface = Typeface.MONOSPACE})})}@@ -507,7 +388,14 @@ class DeviceDetailActivity : AppCompatActivity() {}private fun addDroneButtons(container: LinearLayout) {- val r = DeviceRegistry.get(mac)?.remoteId ?: return+ val r = DeviceRegistry.get(mac)?.remoteId+ if (r == null) {+ // Not heard now: where it and its operator were when last heard.+ val last = saved ?: return+ last.drone?.let { (lat, lon) -> container.addView(mapButton("Drone on map", lat, lon, "Drone ${last.uasId ?: ""}")) }+ last.operator?.let { (lat, lon) -> container.addView(mapButton("Operator / takeoff on map", lat, lon, "Drone operator")) }+ return+ }if (r.hasPosition) container.addView(mapButton("Drone on map", r.latitude!!, r.longitude!!, "Drone ${r.uasId ?: ""}"))if (r.hasOperatorPosition) container.addView(mapButton("Operator / takeoff on map", r.operatorLatitude!!, r.operatorLongitude!!, "Drone operator"))}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.ktindex 38de2a0..7516079 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt@@ -40,6 +40,8 @@ enum class DeviceFilter(val label: String, val liveOnly: Boolean = false) {AUDIO("Audio"),CAMERAS("Cameras"),ROUTERS("Routers"),+ /** Business access points and account sign-in (enterprise) WiFi: offices, shops, schools, hotels. */+ ACCESS_POINTS("Access points"),HOTSPOTS("Hotspots"),TVS("TVs & consoles"),SMART_HOME("Smart home"),@@ -89,7 +91,8 @@ enum class DeviceFilter(val label: String, val liveOnly: Boolean = false) {DRONES -> s.hits.any { it.category == Category.DRONE } || s.remoteId || s.type.startsWith("Drone")NEW -> s.isNewCELLS, WAZE, RADIO, AIRCRAFT -> false- EXTERNAL -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac)+ EXTERNAL -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac) ||+ com.rfsentinel.app.esp.HeardBy.usbBt.recent(s.mac)SENTINELS -> com.rfsentinel.app.esp.HeardBy.peer.recent(s.mac)FAVORITES -> Favorites.contains(s.mac)BLE -> Advert.Source.BLE in s.sources@@ -102,6 +105,7 @@ enum class DeviceFilter(val label: String, val liveOnly: Boolean = false) {s.hits.none { it.category == Category.AUDIO_SENSOR }CAMERAS -> s.anyType(CAMERA_TYPE) || s.hits.any { it.category in CAMERA_CATEGORIES }ROUTERS -> s.types.any { DeviceIntel.isRouter(it) } && !s.anyType(VEHICLE_TYPE)+ ACCESS_POINTS -> s.anyType(ACCESS_POINT_TYPE)HOTSPOTS -> s.anyType(HOTSPOT_TYPE)TVS -> s.anyType(TV_TYPE)SMART_HOME -> s.anyType(SMART_HOME_TYPE) && !s.anyType(VEHICLE_TYPE)@@ -116,7 +120,7 @@ enum class DeviceFilter(val label: String, val liveOnly: Boolean = false) {@Volatile var excludeAirTags = false/** The device-kind filters (from the device's type), after the main ones. */- val KINDS = listOf(VEHICLES, PHONES, COMPUTERS, AUDIO, CAMERAS, ROUTERS, HOTSPOTS, TVS, SMART_HOME, APPLE)+ val KINDS = listOf(VEHICLES, PHONES, COMPUTERS, AUDIO, CAMERAS, ROUTERS, ACCESS_POINTS, HOTSPOTS, TVS, SMART_HOME, APPLE)// Each kind from the types DeviceIntel gives (its own names, the Bluetooth appearance names and// older versions' names, so saved snapshots and traces sort the same way).@@ -128,7 +132,8 @@ enum class DeviceFilter(val label: String, val liveOnly: Boolean = false) {private val CAMERA_TYPE = kind("^(dashcam|action camera|security camera|camera)|body cam|\\bcam(era)?\\b")/** Detection categories that are cameras (police, home security, action / hidden, recording glasses). */private val CAMERA_CATEGORIES = setOf(Category.BODY_CAM, Category.ALPR, Category.NETWORK_CAMERA, Category.OTHER_CAMERA, Category.GLASSES)- // Business access points and account sign-in WiFi stay off both: they're neither.+ // Business access points and account sign-in WiFi are neither routers nor hotspots: they have their own kind.+ private val ACCESS_POINT_TYPE = kind("^business (access point|wifi)")private val HOTSPOT_TYPE = kind("^(public wifi hotspot|mobile hotspot box|phone hotspot|train wifi|open wifi)")private val TV_TYPE = kind("^(smart tv|tv / streaming|game console|game controller|vr headset|apple tv)|television|set-top|media player|^gaming|gamepad|joystick")private val SMART_HOME_TYPE = kind("smart-home|smart home|^iot|smart plug|bthome|^sensor|environmental sensor|light|" +diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceOrder.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceOrder.ktindex 3483d86..0d71c9c 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceOrder.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceOrder.kt@@ -51,7 +51,7 @@ object DeviceOrder {/** Category groups, in the filter chips' spirit: what matters most first. */private val CATEGORY_ORDER = listOf(DeviceFilter.TRACKERS, DeviceFilter.DRONES, DeviceFilter.CAMERAS, DeviceFilter.VEHICLES, DeviceFilter.PHONES,- DeviceFilter.COMPUTERS, DeviceFilter.AUDIO, DeviceFilter.ROUTERS, DeviceFilter.HOTSPOTS, DeviceFilter.TVS,+ DeviceFilter.COMPUTERS, DeviceFilter.AUDIO, DeviceFilter.ROUTERS, DeviceFilter.ACCESS_POINTS, DeviceFilter.HOTSPOTS, DeviceFilter.TVS,DeviceFilter.SMART_HOME, DeviceFilter.APPLE)/** The group of flagged devices, first when grouped. */diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.ktnew file mode 100644index 0000000..493029a--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt@@ -0,0 +1,234 @@+package com.rfsentinel.app.ui++import android.content.Context+import com.rfsentinel.app.data.DetectionEntity+import com.rfsentinel.app.data.DeviceNames+import com.rfsentinel.app.data.KnownDeviceEntity+import com.rfsentinel.app.detect.AdStructure+import com.rfsentinel.app.detect.Advert+import com.rfsentinel.app.detect.Bytes+import com.rfsentinel.app.detect.DeviceIntel+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.detect.VendorDb+import com.rfsentinel.app.oui.OuiWatchlist+import com.rfsentinel.app.service.DeviceRegistry+import java.text.DateFormat+import java.util.Date+import java.util.Locale++/** One section of a device's page: its title and its rows. */+typealias DeviceSection = Pair<String, List<Pair<String, String>>>++/**+ * The sections of a device's page (why it's flagged, identity, drone Remote ID, history, raw advertisement).+ * Shared by the page and by the scanner, which saves them while the device is heard ([com.rfsentinel.app.data.LastHeard]),+ * so a device no longer in range shows the same details as when it was.+ */+object DeviceSections {++ const val FLAGGED = "Why it's flagged"+ const val WAS_FLAGGED = "Why it was flagged"+ const val HISTORY = "History"+ const val RAW = "Raw advertisement"++ private fun dateFmt() = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)++ /**+ * Every section for [mac]: [s] is the device as heard now (null when it isn't), [known] its saved record,+ * [pastMatches] / [pastHits] its match history. [saving]: the History section keeps only what this sighting adds+ * (the saved record and match history are read again when it's shown).+ */+ fun build(+ context: Context, mac: String, s: DeviceRegistry.Snapshot?, known: KnownDeviceEntity?,+ pastMatches: List<DetectionEntity>, pastHits: List<Hit>, saving: Boolean = false+ ): List<DeviceSection> {+ val out = mutableListOf<DeviceSection>()+ val a = s?.advert+ val dateFmt = dateFmt()+ val knownType = known?.let { DeviceIntel.savedType(it.deviceType, it.vendor, it.mac) }++ // Why flagged+ if (s == null && pastHits.isNotEmpty()) {+ out += WAS_FLAGGED to pastMatchRows(pastMatches, pastHits)+ } else if (s != null) {+ out += FLAGGED to if (s.hits.isEmpty()) {+ listOf("Result" to "Not flagged - no watchlist entry or equipment signature matched.")+ } else {+ s.hits.flatMap { h ->+ listOf(+ "● ${h.label}" to "${h.category.title} · ${h.tier.label} (${h.confidence}%)",+ " Evidence" to h.evidence,+ " Source" to h.source+ )+ }+ }+ }++ // Identity+ val id = mutableListOf<Pair<String, String>>()+ (s?.deviceType ?: knownType)?.let { id += "Device type" to it }+ // The category the list files it under (a device no longer heard: from its saved type and name).+ (s?.let { DeviceFilter.seen(it) } ?: knownType?.let {+ DeviceFilter.Seen(mac, it, known?.name, pastHits, emptySet(), pastHits.isNotEmpty(), vendor = VendorDb.macVendor(mac))+ })?.let { id += "Category" to DeviceOrder.categoryLabel(it) }+ (s?.name ?: known?.name)?.let { id += (if (a?.isWifi == true) "Network name (SSID)" else "Advertised name") to it }+ VendorDb.macVendor(mac)?.let { id += "Address registrant (IEEE)" to it }+ a?.manufacturerData?.keys?.forEach { cid ->+ id += "Bluetooth company" to (VendorDb.company(cid) ?: "Unknown") + String.format(" (0x%04X)", cid)+ }+ if (s == null) pastMatches.firstOrNull { it.source == "BLE" || it.source == "WIFI" }?.let { m ->+ // The radio side as saved with its last match.+ id += "Radio" to (if (m.source == "BLE") "Bluetooth LE" else "WiFi") + (m.radio?.let { " · $it" } ?: "")+ }+ if (s != null) {+ id += "Address type" to s.addressType.label+ id += "Trackability" to s.addressType.trackability(known?.firstSeen, known?.lastSeen, known?.sessions ?: 0,+ DeviceRegistry.linkedFrom(mac) != null)+ id += "Radio" to s.sources.joinToString(" + ") { if (it == Advert.Source.BLE) "Bluetooth LE" else "WiFi" }+ }+ a?.connectable?.let { id += "Connectable" to if (it) "Yes (accepts connections)" else "No (broadcast only)" }+ a?.phy?.let { id += "PHY" to it }+ a?.txPower?.let { id += "Advertised TX power" to "$it dBm" }+ s?.facts?.forEach { id += it }+ DeviceNames.lookalike(mac, DeviceRegistry.fingerprintOf(DeviceRegistry.currentAddress(mac)))?.let {+ id += "Looks like" to "Your \"$it\": its adverts look the same, so it's that device under a new address, or one of the same model"+ }+ DeviceRegistry.companions(DeviceRegistry.currentAddress(mac)).takeIf { it.isNotEmpty() }?.let { c ->+ id += "Moved together with" to c.joinToString("\n") { (m, label) -> (DeviceNames.of(m) ?: label) + " · " + m }+ }+ s?.hits?.firstOrNull { it.category == com.rfsentinel.app.detect.Category.TRACKER }+ ?.takeIf { !com.rfsentinel.app.detect.SignatureEngine.reportsOwnerState(it) }?.let {+ DeviceRegistry.ownerPhone(DeviceRegistry.currentAddress(mac))?.let { phone ->+ id += "With its owner" to "Moved with $phone at every place: most likely that phone owner's tag, so it doesn't alert as following you"+ }+ }+ // Heard by a USB WiFi adapter / Marauder board: its WPS block, fingerprint, network requests.+ com.rfsentinel.app.usb.ProbeIntel.of(mac)?.let { r ->+ if (r.hidden) id += "Hidden network" to (s?.name?.let { "Its name, \"$it\", was revealed by a device joining or asking for it" }+ ?: "It hides its name - shown once a device joins or asks for it (USB WiFi adapter)")+ r.wps?.deviceName?.let { id += "Device name (WPS)" to it }+ r.wps?.product?.let { id += "Maker / model (WPS)" to it }+ r.fingerprint?.let { fp ->+ id += "Probe fingerprint" to fp + if (OuiWatchlist.isFingerprintWatched(fp)) " · on your watchlist" else+ " (same for every device of this model / OS - Watchlist can watch it)"+ }+ r.skeleton?.let { sk ->+ id += "Probe shape" to "%08x".format(sk) + (com.rfsentinel.app.detect.SignatureEngine.probeShapeNote(sk)?.let { " · $it" } ?: "") ++ if (OuiWatchlist.isFingerprintWatched(com.rfsentinel.app.usb.ProbeIntel.shapeKey(sk))) " · on your watchlist" else ""+ }+ if (r.probed.isNotEmpty()) id += "Networks it asked for" to r.probed.reversed().joinToString(", ")+ }+ a?.wifi?.probeRun?.let { run ->+ id += "Wildcard probes" to run.describe() ++ if (run.nonStop) " · non-stop, like a mains-powered fixed device" else ""+ }+ if (id.isNotEmpty()) out += "Identity" to id++ // Drone Remote ID+ s?.remoteId?.let { r ->+ val rows = mutableListOf<Pair<String, String>>()+ r.uasId?.let { rows += "UAS ID" to it }+ r.idType?.let { rows += "ID type" to it }+ r.uaType?.let { rows += "Aircraft type" to it }+ r.status?.let { rows += "Status" to it }+ if (r.hasPosition) rows += "Drone position" to String.format(Locale.US, "%.6f, %.6f", r.latitude, r.longitude)+ r.altitudeGeoM?.let { rows += "Altitude (WGS84)" to String.format(Locale.US, "%.0f m", it) }+ r.heightM?.let { rows += "Height above takeoff/ground" to String.format(Locale.US, "%.0f m", it) }+ r.speedMs?.let { rows += "Ground speed" to String.format(Locale.US, "%.1f m/s (%s)", it, com.rfsentinel.app.util.Units.speed(it)) }+ r.verticalSpeedMs?.let { rows += "Vertical speed" to String.format(Locale.US, "%.1f m/s", it) }+ r.directionDeg?.let { rows += "Heading" to "$it°" }+ if (r.hasOperatorPosition) rows += "Operator position" to String.format(Locale.US, "%.6f, %.6f", r.operatorLatitude, r.operatorLongitude)+ r.operatorId?.let { rows += "Operator ID" to it }+ r.selfIdDescription?.let { rows += "Description" to it }+ out += "Drone Remote ID (ASTM F3411)" to rows+ }++ // Session & history+ out += HISTORY to if (saving) heardRows(context, s) else {+ val hist = mutableListOf<Pair<String, String>>()+ if (s != null) hist += "First heard this session" to DateFormat.getTimeInstance(DateFormat.MEDIUM).format(Date(s.firstSeen))+ hist += savedRows(known, pastMatches)+ hist += heardRows(context, s)+ hist+ }++ // Raw advertisement+ if (a != null) {+ val raw = mutableListOf<Pair<String, String>>()+ a.manufacturerData.forEach { (cid, data) ->+ raw += String.format("Manufacturer 0x%04X", cid) to Bytes.hex(data)+ }+ a.serviceUuids.forEach { u ->+ val short = Advert.shortOf(u)+ raw += "Service UUID" to (if (short != null) String.format("0x%04X", short) + (VendorDb.uuid16(short)?.let { " - $it" } ?: "") else u.toString())+ }+ a.serviceData.forEach { (u, data) ->+ val short = Advert.shortOf(u)+ val label = if (short != null) String.format("0x%04X", short) + (VendorDb.uuid16(short)?.let { " $it" } ?: "") else u.toString()+ raw += "Service data $label" to Bytes.hex(data)+ }+ AdStructure.parse(a.rawBytes).forEach { ad ->+ raw += String.format("AD 0x%02X %s", ad.type, ad.typeName) to Bytes.hex(ad.data).ifEmpty { "(empty)" }+ }+ a.wifi?.let { w ->+ raw += "Capabilities" to w.capabilities.ifEmpty { "(none)" }+ raw += "Information elements" to "${w.infoElements.size}" ++ if (w.infoElements.isNotEmpty()) " (IDs " + w.infoElements.map { it.first }.distinct().joinToString() + ")" else ""+ }+ if (raw.isNotEmpty()) out += RAW to raw+ }+ return out+ }++ /** What it matched when it was heard (the newest match of each kind), from the match history. */+ fun pastMatchRows(pastMatches: List<DetectionEntity>, pastHits: List<Hit>): List<Pair<String, String>> {+ val dateFmt = dateFmt()+ return pastMatches.distinctBy { it.label }.take(pastHits.size).zip(pastHits).flatMap { (m, h) ->+ listOfNotNull(+ "● ${h.label}" to "${h.category.title} · ${h.tier.label} (${h.confidence}%)",+ h.evidence.takeIf { it.isNotBlank() }?.let { " Evidence" to it },+ " Last matched" to dateFmt.format(Date(m.timestamp))+ )+ }+ }++ /** The saved record and match history. */+ fun savedRows(known: KnownDeviceEntity?, pastMatches: List<DetectionEntity>): List<Pair<String, String>> {+ val dateFmt = dateFmt()+ val hist = mutableListOf<Pair<String, String>>()+ known?.let {+ hist += "First ever seen" to dateFmt.format(Date(it.firstSeen))+ hist += "Last seen (saved)" to dateFmt.format(Date(it.lastSeen))+ hist += "Scanning sessions seen in" to "${it.sessions}"+ hist += "Detect count" to "${it.detectCount} (at most one per minute)"+ } ?: run { hist += "History" to "First time this address has been heard" }+ if (pastMatches.isNotEmpty()) {+ hist += "Logged matches" to "${pastMatches.size}" + (if (pastMatches.size >= 200) "+" else "")+ pastMatches.take(5).forEach { m ->+ hist += dateFmt.format(Date(m.timestamp)) to "${m.label} · ${m.rssi} dBm" ++ (if (m.latitude != null) String.format(Locale.US, " · %.5f, %.5f", m.latitude, m.longitude) else "")+ }+ }+ return hist+ }++ /** What this sighting adds: how far it came along, where it was placed. */+ private fun heardRows(context: Context, s: DeviceRegistry.Snapshot?): List<Pair<String, String>> {+ val hist = mutableListOf<Pair<String, String>>()+ if (s != null && s.path.size >= 2) {+ val first = s.path.first()+ val moved = s.path.maxOf { DeviceRegistry.metersBetween(first.lat, first.lon, it.lat, it.lon) }+ hist += "Travelled with you" to String.format(Locale.US, "%.0f m while in range", moved)+ }+ s?.broadcast?.let { b ->+ hist += "Position (its own GPS, over V2X)" to String.format(Locale.US, "%.6f, %.6f", b.lat, b.lon)+ } ?: s?.located?.let { e ->+ hist += "Pinpointed position" to String.format(Locale.US, "%.6f, %.6f · ", e.lat, e.lon) ++ com.rfsentinel.app.detect.Locator.describe(e)+ } ?: s?.takeIf { it.best != null && !it.following && com.rfsentinel.app.util.Prefs.pinpointFlagged(context) }?.let {+ hist += "Pinpointing" to "Not yet: pass it from more than one side (around the block) and it is placed on the map " ++ "with the circle it is very likely in"+ }+ return hist+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.ktindex 8e08fb1..2685457 100644--- a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt@@ -14,9 +14,7 @@ import android.os.Buildimport android.os.Handlerimport android.os.Looperimport android.provider.Settings-import android.view.ContextThemeWrapperimport android.view.Gravity-import android.view.LayoutInflaterimport android.view.MotionEventimport android.view.Viewimport android.view.ViewOutlineProvider@@ -25,8 +23,6 @@ import android.widget.FrameLayoutimport android.widget.TextViewimport android.widget.Toastimport androidx.core.content.edit-import com.rfsentinel.app.R-import com.rfsentinel.app.databinding.ViewLiveReadBindingimport com.rfsentinel.app.service.ScanForegroundServiceimport com.rfsentinel.app.util.Prefsimport org.maplibre.android.camera.CameraPosition@@ -89,10 +85,10 @@ object FloatingMap {/** The map window's place and size, which the live read card follows. */private var mapLp: WindowManager.LayoutParams? = null/** The live read card (Locate or pinpointing): a small window of its own just under the map. */- private var live: ViewLiveReadBinding? = null- private var liveLp: WindowManager.LayoutParams? = null- private var liveCard: LiveReadCard? = null- private var stopLive: (() -> Unit)? = null+ private var live: LiveReadOverlay? = null++ /** True while the mini map is on screen (the threat bubble then leaves the live read card to it). */+ val showing get() = root != nullfun canShow(context: Context) = Settings.canDrawOverlays(context)@@ -142,8 +138,7 @@ object FloatingMap {private fun removeNow(context: Context) {val r = root ?: return- stopLive?.invoke(); stopLive = null- removeLive(context)+ live?.stop(); live = nullmapLp = nullrunCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(r) }view?.let { v -> runCatching { v.onPause(); v.onStop(); v.onDestroy() } }@@ -157,47 +152,16 @@ object FloatingMap {private fun overlayType() = if (Build.VERSION.SDK_INT >= 26) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAYelse @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE- /** Shows, updates or (null) removes the live read card under the map. */- private fun showLive(context: Context, r: LiveRead.Read?) {- if (r == null || root == null) { removeLive(context); return }- if (live == null) {- val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager- val b = ViewLiveReadBinding.inflate(LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_RFSentinel)))- // A little smaller than on the full map: it sits beside another app.- b.liveTitle.textSize = 14f; b.liveDetail.textSize = 12f- b.root.elevation = 6f * context.resources.displayMetrics.density- val lp = WindowManager.LayoutParams(- WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, overlayType(),- WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT- ).apply { gravity = Gravity.TOP or Gravity.END }- if (runCatching { wm.addView(b.root, lp) }.isFailure) return- live = b; liveLp = lp; liveCard = LiveReadCard(b)- // Placed again once its height is known (above the map when there is no room below).- b.root.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->- if (bottom - top != oldBottom - oldTop) placeLive(context)- }- }- liveCard?.show(r)- placeLive(context)- }-/** The card just under the map, its right edge on the map's, at least as wide as the map; above it near the bottom. */- private fun placeLive(context: Context) {- val b = live ?: return; val lp = liveLp ?: return; val m = mapLp ?: return+ private fun placeLive(context: Context, lp: WindowManager.LayoutParams, h: Int) {+ val m = mapLp ?: returnval dm = context.resources.displayMetricsval gap = dp(context, 6f)+ lp.gravity = Gravity.TOP or Gravity.ENDlp.width = maxOf(m.width, dp(context, 240f)).coerceAtMost(dm.widthPixels - dp(context, 16f))// Gravity END: x is from the right edge; kept on screen when the map is near the left.lp.x = m.x.coerceIn(0, (dm.widthPixels - lp.width).coerceAtLeast(0))- val h = b.root.height.takeIf { it > 0 } ?: dp(context, 84f)lp.y = if (m.y + m.height + gap + h <= dm.heightPixels) m.y + m.height + gap else (m.y - gap - h).coerceAtLeast(0)- runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).updateViewLayout(b.root, lp) }- }-- private fun removeLive(context: Context) {- val b = live ?: return- runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(b.root) }- live = null; liveLp = null; liveCard = null}@SuppressLint("ClickableViewAccessibility", "SetTextI18n")@@ -312,7 +276,7 @@ object FloatingMap {val dx = e.rawX - downX; val dy = e.rawY - downYif (abs(dx) > 8 * d || abs(dy) > 8 * d) moved = true// Gravity END: x grows to the left.- if (moved) { lp.x = startX - dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(frame, lp) }; placeLive(context) }+ if (moved) { lp.x = startX - dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(frame, lp) }; live?.replace() }}MotionEvent.ACTION_UP -> {if (pinched) prefs.edit { putFloat("zoom", zoom.toFloat()) }@@ -349,7 +313,7 @@ object FloatingMap {// Out (left / down) grows it, in (right / up) shrinks it; it stays square.val grow = maxOf(resizeDownX - e.rawX, e.rawY - resizeDownY)val n = (startSize + grow).toInt().coerceIn(minSize, maxSize)- if (n != lp.width) { lp.width = n; lp.height = n; runCatching { wm.updateViewLayout(frame, lp) }; placeLive(context) }+ if (n != lp.width) { lp.width = n; lp.height = n; runCatching { wm.updateViewLayout(frame, lp) }; live?.replace() }}MotionEvent.ACTION_UP -> prefs.edit { putInt("size", lp.width) }}@@ -361,7 +325,7 @@ object FloatingMap {m.onStart(); m.onResume()root = frame; view = m; badge = count; waiting = wait; mapLp = lpScanForegroundService.mapShown(context)- stopLive = LiveRead.addListener { showLive(context, it) }+ live = LiveReadOverlay(context) { lp, h -> placeLive(context, lp, h) }.also { it.start() }frame}.getOrNull()}diff --git a/app/src/main/java/com/rfsentinel/app/ui/GpsDot.kt b/app/src/main/java/com/rfsentinel/app/ui/GpsDot.ktindex 74bb74a..b067f71 100644--- a/app/src/main/java/com/rfsentinel/app/ui/GpsDot.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/GpsDot.kt@@ -7,13 +7,13 @@ import android.text.style.ForegroundColorSpanimport com.rfsentinel.app.service.ScanForegroundService/**- * The GPS dot on the main screen's status: red without a position (or one older than [STALE_MS]),+ * The GPS dot on the main screen's status: red without a position (or one older than the scan's+ * [ScanForegroundService.gpsStaleMs]: 10 s while it asks for frequent fixes, longer on balanced),* yellow while it's rougher than [GOOD_M], green from [GOOD_M] down, with the accuracy beside it.*/object GpsDot {const val GOOD_M = 20f- const val STALE_MS = 10_000Lenum class Level(val color: Int, val words: String) {NONE(0xFFB3261E.toInt(), "no position"),@@ -21,8 +21,8 @@ object GpsDot {GOOD(0xFF2E7D32.toInt(), "good")}- fun level(at: Long, accuracyM: Float?, now: Long): Level = when {- accuracyM == null || now - at > STALE_MS -> Level.NONE+ fun level(at: Long, accuracyM: Float?, now: Long, staleMs: Long = 10_000L): Level = when {+ accuracyM == null || now - at > staleMs -> Level.NONEaccuracyM > GOOD_M -> Level.ROUGHelse -> Level.GOOD}@@ -31,7 +31,7 @@ object GpsDot {fun text(context: Context, demo: Boolean = false): CharSequence {val now = System.currentTimeMillis()val acc = if (demo) 5f else ScanForegroundService.gpsAccuracyM- val lv = if (demo) Level.GOOD else level(ScanForegroundService.gpsAt, acc, now)+ val lv = if (demo) Level.GOOD else level(ScanForegroundService.gpsAt, acc, now, ScanForegroundService.gpsStaleMs)val b = SpannableStringBuilder("●")b.setSpan(ForegroundColorSpan(ThemeManager.ink(context, lv.color)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)b.append(if (lv == Level.NONE) " GPS - no position" else " GPS ${acc!!.toInt()} m")diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.ktindex 1d60a77..4deab40 100644--- a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt@@ -2,12 +2,18 @@ package com.rfsentinel.app.uiimport android.content.Contextimport android.content.res.ColorStateList+import android.graphics.PixelFormatimport android.media.AudioManagerimport android.media.ToneGenerator+import android.os.Buildimport android.os.Handlerimport android.os.Looper+import android.view.ContextThemeWrapper+import android.view.LayoutInflaterimport android.view.View+import android.view.WindowManagerimport android.widget.Toast+import com.rfsentinel.app.Rimport com.rfsentinel.app.data.DeviceNamesimport com.rfsentinel.app.databinding.ViewLiveReadBindingimport com.rfsentinel.app.detect.DeviceIntel@@ -210,3 +216,63 @@ internal class LiveReadCard(private val b: ViewLiveReadBinding) {b.root.visibility = View.VISIBLE}}++/**+ * The live read card in a small window of its own over other apps (under the floating map, beside the threat+ * bubble), shown while there is a read. [place] sets the window's gravity, x, y and width for a card [height]+ * tall; call [replace] when what it sits by moves. [wanted]: false while another overlay shows the card.+ */+internal class LiveReadOverlay(+ private val context: Context,+ private val wanted: () -> Boolean = { true },+ private val place: (lp: WindowManager.LayoutParams, height: Int) -> Unit+) {+ private var b: ViewLiveReadBinding? = null+ private var lp: WindowManager.LayoutParams? = null+ private var card: LiveReadCard? = null+ private var stopListening: (() -> Unit)? = null+ private val wm get() = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager++ fun start() { if (stopListening == null) stopListening = LiveRead.addListener { show(it) } }++ fun stop() {+ stopListening?.invoke(); stopListening = null+ remove()+ }++ fun replace() {+ val b = b ?: return; val lp = lp ?: return+ place(lp, b.root.height.takeIf { it > 0 } ?: (84 * context.resources.displayMetrics.density).toInt())+ runCatching { wm.updateViewLayout(b.root, lp) }+ }++ private fun show(r: LiveRead.Read?) {+ if (r == null || !wanted()) { remove(); return }+ if (b == null) {+ val nb = ViewLiveReadBinding.inflate(LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_RFSentinel)))+ // A little smaller than on the full map: it sits beside another app.+ nb.liveTitle.textSize = 14f; nb.liveDetail.textSize = 12f+ nb.root.elevation = 6f * context.resources.displayMetrics.density+ val type = if (Build.VERSION.SDK_INT >= 26) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY+ else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE+ val nlp = WindowManager.LayoutParams(+ WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, type,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT+ )+ if (runCatching { wm.addView(nb.root, nlp) }.isFailure) return+ b = nb; lp = nlp; card = LiveReadCard(nb)+ // Placed again once its height is known (it may go above what it sits by when there's no room below).+ nb.root.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->+ if (bottom - top != oldBottom - oldTop) replace()+ }+ }+ card?.show(r)+ replace()+ }++ private fun remove() {+ val v = b ?: return+ runCatching { wm.removeView(v.root) }+ b = null; lp = null; card = null+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.ktindex a3821c0..ac4e3e9 100644--- a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt@@ -39,7 +39,7 @@ object LiveWindow {val phoneMs = if (wifi) wifiMs else bleMs// Heard by an ESP32 board, a USB adapter or a linked Sentinel: its own time, or the longer one when the// phone hears it too.- val external = HeardBy.esp.recent(s.mac, now) || HeardBy.usb.recent(s.mac, now) || HeardBy.peer.recent(s.mac, now)+ val external = HeardBy.esp.recent(s.mac, now) || HeardBy.usb.recent(s.mac, now) || HeardBy.usbBt.recent(s.mac, now) || HeardBy.peer.recent(s.mac, now)val ms = when {!external -> phoneMsHeardBy.phone.recent(s.mac, now) -> maxOf(phoneMs, externalMs)diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex 197facf..3a44d52 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -116,7 +116,7 @@ class MapFragment : Fragment() {else -> base - (kmh - 30f) / 80f * 1.6}- /** After panning or zooming the map, it goes back to following you once this long has passed without a touch. */+ /** The shortest re-center delay: after panning or zooming, the map follows you again once this long (Settings > Map: longer) has passed without a touch. */const val RECENTER_AFTER_MS = 10_000L/**@@ -163,6 +163,10 @@ class MapFragment : Fragment() {private var centeredOnce = false/** The trace whose recording banner was hidden with its X. */private var recBannerHiddenFor: Long? = null+ /** The camera / CCTV download lines were hidden with the banner's X: they stay hidden until the map opens again. */+ private var downloadsHidden = false+ /** A camera / CCTV download line is on the banner now (its X hides those first). */+ private var downloadShown = false/** The live map opened on a world view because nothing was known about where you are: zoom in with the first fix. */private var startedOnWorld = false/** The map keeps your position centred until you pan it yourself. */@@ -284,7 +288,7 @@ class MapFragment : Fragment() {if (tripId == null) {nav = MapNav(act, binding, viewLifecycleOwner.lifecycleScope, embedded, { alive }, { rf }, { lastFix ?: knownFix() }, navHost).also { it.setup() }- // Alerts pop up over the full screen map (the small pane on the main screen has the list under it).+ // Alerts pop up over the full screen map only, never the main screen's split-view pane.if (!embedded) {val cards = AlertCardController(act, binding, { lastFix ?: knownFix() }) { lat, lon ->navHost.navLookAtRoute()@@ -295,9 +299,11 @@ class MapFragment : Fragment() {// One that came in just before this screen opened (tapping its notification, say) is still shown.AlertCards.latest?.takeIf { System.currentTimeMillis() - it.atMs < 6_000L }?.let { cards.show(it) }}- // Locate or pinpointing: the followed device's live signal, on the full map and the main screen's pane.- val live = LiveReadCard(binding.liveRead)- stopLiveRead = LiveRead.addListener { live.show(it) }+ // Locate or pinpointing: the followed device's live signal, on the full screen map only (not the split-view pane).+ if (!embedded) {+ val live = LiveReadCard(binding.liveRead)+ stopLiveRead = LiveRead.addListener { live.show(it) }+ }} else {binding.searchButton.visibility = View.GONE}@@ -330,7 +336,11 @@ class MapFragment : Fragment() {binding.recordButton.visibility = View.GONE}if (embedded) compactControls()- binding.statusDismiss.setOnClickListener { recBannerHiddenFor = TripRecorder.activeTripId; renderLive() }+ binding.statusDismiss.setOnClickListener {+ // A download line goes first; the recording banner with the next tap.+ if (downloadShown) downloadsHidden = true else recBannerHiddenFor = TripRecorder.activeTripId+ renderLive()+ }}/** The main screen's filter chip, for the embedded map. */@@ -975,7 +985,7 @@ class MapFragment : Fragment() {lastFix = fixgpsFix = fixif (shouldRecenter(Prefs.mapAutoRecenter(act), following, tripId == null, Navigator.active, if (fix.hasSpeed()) fix.speed else 0f,- nav?.cardShown == true, android.os.SystemClock.elapsedRealtime() - touchedAt)) setFollow(true, quiet = true)+ nav?.cardShown == true, android.os.SystemClock.elapsedRealtime() - touchedAt, Prefs.mapRecenterSec(act) * 1000L)) setFollow(true, quiet = true)if (tripId == null && !Navigator.active && Prefs.mapSpeedometer(act) && Prefs.mapSpeedLimitLive(act) && fix.hasSpeed())com.rfsentinel.app.nav.SpeedLimits.Live.onFix(fix.latitude, fix.longitude, fix.speed)updateGauge()@@ -1366,10 +1376,16 @@ class MapFragment : Fragment() {val positioned = devices.count { it.place != null }// Hidden with its X: stays hidden for this trace, comes back with the next one.val showRec = recording && TripRecorder.activeTripId != recBannerHiddenFor- val status = when {+ val download = when {+ downloadsHidden -> nullbulkStatus() != null -> bulkStatus() // a camera download's progress winsSystem.currentTimeMillis() - com.rfsentinel.app.alpr.AlprStore.lastAutoFailureAt < CAMERA_FAIL_SHOWN_MS ->"Couldn't download the cameras for this area (map server busy or offline) - retrying"+ else -> null+ }+ val cctv = rf?.cctvLine?.takeUnless { downloadsHidden }+ val status = when {+ download != null -> downloadNavigator.active && !showRec -> null // the guidance banner is the status// In the small pane the place card needs the room: the scan status is on the main screen above it anyway.embedded && nav?.cardShown == true && !showRec -> null@@ -1386,10 +1402,11 @@ class MapFragment : Fragment() {embedded -> nullelse -> "Scanning · ${drawn.size} on map" + if (filter != DeviceFilter.ALL) " (${filter.label} only)" else ""}- val text = listOfNotNull(status, rf?.cctvLine).joinToString("\n")+ val text = listOfNotNull(status, cctv).joinToString("\n")binding.statusText.text = textbinding.statusText.visibility = if (text.isEmpty() || (immersive && !Navigator.active)) View.GONE else View.VISIBLE- val dismissable = showRec && binding.statusText.visibility == View.VISIBLE && bulkStatus() == null+ downloadShown = download != null || cctv != null+ val dismissable = (showRec || downloadShown) && binding.statusText.visibility == View.VISIBLEbinding.statusDismiss.visibility = if (dismissable) View.VISIBLE else View.GONEbinding.statusText.setPaddingRelative(binding.statusText.paddingStart, binding.statusText.paddingTop,((if (dismissable) 40 else 12) * resources.displayMetrics.density).toInt(), binding.statusText.paddingBottom)diff --git a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.ktindex fef0bcf..9a1dde3 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt@@ -1,5 +1,6 @@package com.rfsentinel.app.ui+import android.content.Intentimport android.graphics.Typefaceimport android.os.Buildimport android.os.Bundle@@ -37,6 +38,11 @@ import kotlinx.coroutines.launch*/class SentinelLinkActivity : AppCompatActivity() {+ companion object {+ /** Opened from the "Pair your Meshtastic node" notification: pair now. */+ const val EXTRA_PAIR = "pair_mesh_node"+ }+private lateinit var status: TextViewprivate lateinit var share: SwitchMaterialprivate lateinit var list: LinearLayout@@ -167,7 +173,11 @@ class SentinelLinkActivity : AppCompatActivity() {setPadding(0, pad(8), 0, pad(8))}meshNodeText = TextView(this).apply { textSize = 14f }- meshStatus = TextView(this).apply { textSize = 14f; setPadding(0, pad(4), 0, 0) }+ meshStatus = TextView(this).apply {+ textSize = 14f; setPadding(0, pad(4), 0, 0)+ // "not paired - tap here to pair"+ setOnClickListener { LinkStore.meshNode(this@SentinelLinkActivity)?.let { pairMeshNode(it) } }+ }val choose = button("Choose a node") { chooseNode() }val intervalLabel = TextView(this).apply { textSize = 14f; setPadding(0, pad(12), 0, 0) }fun showInterval(s: Int) { intervalLabel.text = "Send a packet every $s s - watchlist matches sooner" }@@ -248,11 +258,10 @@ class SentinelLinkActivity : AppCompatActivity() {LinkStore.setMeshNode(this, address, names[i].substringBefore(" · "))LinkStore.setMeshOn(this, true)meshSwitch.isChecked = true- MeshNode.pair(this, address)+ pairMeshNode(address)ScanForegroundService.refreshLink(this)dialog.dismiss()refresh()- Toast.makeText(this, "If Android asks for a PIN: it's on the node's screen, or 123456", Toast.LENGTH_LONG).show()}dialog.setOnDismissListener { stop?.invoke(); stop = null }stop = MeshNode.find(this) { name, address, rssi ->@@ -265,6 +274,27 @@ class SentinelLinkActivity : AppCompatActivity() {dialog.show()}+ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ }++ override fun onResume() {+ super.onResume()+ // From the "Pair your Meshtastic node" notification: asked here, in front, Android shows its PIN dialog.+ if (intent.getBooleanExtra(EXTRA_PAIR, false)) {+ intent.removeExtra(EXTRA_PAIR)+ LinkStore.meshNode(this)?.let { pairMeshNode(it) }+ }+ }++ /** Asks Android to pair with the node, from this screen so its PIN dialog shows (not a notification). */+ private fun pairMeshNode(address: String) {+ com.rfsentinel.app.util.NotificationHelper.cancelMeshPairing(this)+ if (MeshNode.pair(this, address))+ Toast.makeText(this, "Android asks for a PIN: it's on the node's screen, or 123456", Toast.LENGTH_LONG).show()+ }+override fun onDestroy() {if (pairDialog?.isShowing == true) PhoneLink.cancelPairing()pairDialog = nulldiff --git a/app/src/main/java/com/rfsentinel/app/ui/ThreatBubble.kt b/app/src/main/java/com/rfsentinel/app/ui/ThreatBubble.ktindex fc33cc9..123a30f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/ThreatBubble.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/ThreatBubble.kt@@ -33,7 +33,8 @@ import kotlin.math.min* or something following you, with the number of flagged devices. Tap to open* the app, drag to move. Needs the "Display over other apps" permission; hidden* while RF Sentinel itself is on screen. Each new alert also shows a small card- * next to the bubble for a few seconds saying what was detected.+ * next to the bubble for a few seconds saying what was detected, and Locate or+ * pinpointing shows the live read card under it (unless the floating map shows it).*/object ThreatBubble {@@ -45,6 +46,8 @@ object ThreatBubble {private var popupView: TextView? = nullprivate val hidePopup = Runnable { popupView?.let { removePopupNow(it.context) } }private const val POPUP_MS = 6_000L+ /** The live read card (Locate or pinpointing) under the bubble. */+ private var live: LiveReadOverlay? = nullfun canShow(context: Context) = Settings.canDrawOverlays(context)@@ -121,6 +124,7 @@ object ThreatBubble {private fun removeNow(context: Context) {removePopupNow(context)+ live?.stop(); live = nullval v = view ?: returnrunCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(v) }view = null; params = null@@ -151,7 +155,7 @@ object ThreatBubble {MotionEvent.ACTION_MOVE -> {val dx = e.rawX - downX; val dy = e.rawY - downYif (!moved && (abs(dx) > 8 * d || abs(dy) > 8 * d)) { moved = true; removePopupNow(context) }- if (moved) { lp.x = startX + dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(v, lp) } }+ if (moved) { lp.x = startX + dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(v, lp) }; live?.replace() }}MotionEvent.ACTION_UP -> {if (moved) prefs.edit { putInt("x", lp.x); putInt("y", lp.y) }@@ -161,7 +165,21 @@ object ThreatBubble {}true}- return runCatching { wm.addView(v, lp); view = v; params = lp; v }.getOrNull()+ return runCatching { wm.addView(v, lp); view = v; params = lp; v }.getOrNull()?.also {+ live = LiveReadOverlay(context, wanted = { !FloatingMap.showing }) { clp, h -> placeLive(context, clp, h) }.also { it.start() }+ }+ }++ /** The live read card just under the bubble, its left edge on the bubble's (kept on screen); above it near the bottom. */+ private fun placeLive(context: Context, clp: WindowManager.LayoutParams, h: Int) {+ val b = params ?: return+ val dm = context.resources.displayMetrics+ val d = dm.density+ val gap = (6 * d).toInt()+ clp.gravity = Gravity.TOP or Gravity.START+ clp.width = (260 * d).toInt().coerceAtMost(dm.widthPixels - (16 * d).toInt())+ clp.x = b.x.coerceIn(0, (dm.widthPixels - clp.width).coerceAtLeast(0))+ clp.y = if (b.y + b.height + gap + h <= dm.heightPixels) b.y + b.height + gap else (b.y - gap - h).coerceAtLeast(0)}/** The drawn bubble: coloured disc, white ring, count or check mark. */diff --git a/app/src/main/java/com/rfsentinel/app/usb/AntennaCheck.kt b/app/src/main/java/com/rfsentinel/app/usb/AntennaCheck.ktindex d669c9b..146b180 100644--- a/app/src/main/java/com/rfsentinel/app/usb/AntennaCheck.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/AntennaCheck.kt@@ -4,6 +4,9 @@ package com.rfsentinel.app.usb* Antenna check for the USB WiFi adapter, after Wardrive Go's (RocketGod): pick a nearby access* point as the reference, the adapter stops hopping and holds its channel, and every frame the* reference sends is kept with its signal per antenna (chain) where the adapter reports one.+ * In [bluetooth] mode the same is done with the USB Bluetooth adapter: the reference is a nearby+ * Bluetooth LE device and each of its advertisements gives one signal (HCI reports no per-antenna+ * value), so only the swap test applies; the WiFi adapter keeps hopping meanwhile.* That compares antennas by how strongly they hear the same transmitter; it isn't an SWR or* impedance measurement. Only the open screen uses it, and nothing here is logged or stored.*@@ -11,7 +14,7 @@ package com.rfsentinel.app.usb*/object AntennaCheck {- /** An access point the adapter heard while the check is open. */+ /** An access point (or, in [bluetooth] mode, a Bluetooth LE device) the adapter heard while the check is open. */class Ap(val bssid: String, val ssid: String?, val channel: Int, val rssi: Int, val lastSeen: Long)/** One frame from the reference: its signal, and per antenna when the adapter reports both. */@@ -31,7 +34,12 @@ object AntennaCheck {/** The channel the driver is holding for the check (set by the driver once it's tuned). */@Volatile var holding = 0+ /** Checking the USB Bluetooth adapter instead of the USB WiFi adapter. */+ @Volatile var bluetooth = false+ private set+@Volatile private var target: ByteArray? = null+ @Volatile private var btTarget: String? = nullprivate val aps = LinkedHashMap<String, Ap>()private val samples = ArrayDeque<Sample>()@@ -47,8 +55,17 @@ object AntennaCheck {synchronized(this) { aps.clear() }}+ /** Switches the check between the USB WiFi and the USB Bluetooth adapter: everything heard so far is dropped. */+ fun useBluetooth(on: Boolean) {+ if (on == bluetooth) return+ unlock()+ bluetooth = on+ synchronized(this) { aps.clear() }+ }+fun lock(bssid: String, channel: Int) {synchronized(this) { samples.clear() }+ if (bluetooth) { btTarget = bssid; return } // nothing to tune: Bluetooth adverts come on all three advertising channelstarget = macBytes(bssid)holding = 0lockChannel = channel@@ -56,6 +73,7 @@ object AntennaCheck {fun unlock() {target = null+ btTarget = nulllockChannel = 0holding = 0synchronized(this) { samples.clear() }@@ -67,7 +85,7 @@ object AntennaCheck {// ---- from the drivers (RX thread, via MonitorFrames) ----internal fun heardAp(bssid: String, ssid: String?, channel: Int, rssi: Int?, now: Long) {- if (channel == 0) return+ if (channel == 0 || bluetooth) returnsynchronized(this) {val old = aps[bssid]aps[bssid] = Ap(bssid, ssid ?: old?.ssid, channel,@@ -88,9 +106,25 @@ object AntennaCheck {}}+ // ---- from the USB Bluetooth adapter (scan pipeline) ----++ /** An advertisement the USB Bluetooth adapter heard: listed as a possible reference, kept when it's the reference's. */+ fun heardBt(mac: String, name: String?, rssi: Int, now: Long) {+ if (!listening || !bluetooth) return+ synchronized(this) {+ val old = aps[mac]+ aps[mac] = Ap(mac, name ?: old?.ssid, 0, rssi, now)+ if (aps.size > 500) aps.remove(aps.keys.first())+ if (mac == btTarget) {+ samples.addLast(Sample(now, rssi, null, null))+ while (samples.size > MAX_SAMPLES || (samples.isNotEmpty() && now - samples.first().at > KEEP_MS)) samples.removeFirst()+ }+ }+ }+/** Debug builds' demo: a made-up frame from the reference, for checking the screen without an adapter. */internal fun demoSample(rssi: Int, a: Int?, b: Int?, now: Long) {- if (target == null) return+ if (target == null && btTarget == null) returnsynchronized(this) { samples.addLast(Sample(now, rssi, a, b)); while (samples.size > MAX_SAMPLES) samples.removeFirst() }}@@ -193,6 +227,7 @@ object AntennaCheck {/** "5 GHz ch 36" for a channel in [MonitorFrames]' numbering. */fun channelName(ch: Int): String = when {+ ch == 0 -> "Bluetooth LE"ch >= 5955 -> "6 GHz ch ${(ch - 5950) / 5}"ch > 14 -> "5 GHz ch $ch"else -> "2.4 GHz ch $ch"diff --git a/app/src/main/java/com/rfsentinel/app/usb/BtMediatek.kt b/app/src/main/java/com/rfsentinel/app/usb/BtMediatek.ktnew file mode 100644index 0000000..2f9cf52--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/BtMediatek.kt@@ -0,0 +1,181 @@+package com.rfsentinel.app.usb++/*+ * Bluetooth bring-up of MediaTek MT7921AU (MT7961) combo adapters: the btmtk_usb_setup path of+ * the Linux driver (drivers/bluetooth/btmtk.c, GPL-2.0; Copyright (c) 2021 MediaTek Inc.), step+ * by step in the same order: read the chip ID, firmware version and flavour, download the+ * BT_RAM_CODE patch sections with WMT PATCH_DWNLD commands (each answered on a polled control+ * IN request, btmtk_usb_hci_wmt_sync), set the endpoint reset option, then turn the Bluetooth+ * function on with WMT FUNC_CTRL. If the download fails, the Bluetooth subsystem is reset the+ * way btmtk_usb_subsys_reset does and the setup runs once more (Linux also resets the USB port,+ * which Android apps can't). The ISO data interface (LE audio) isn't claimed: nothing here uses it.+ */++import android.content.Context+import java.io.IOException++internal object BtMediatek {++ private const val WMT_PATCH_DWNLD = 0x1+ private const val WMT_FUNC_CTRL = 0x6+ private const val PKT_START = 1; private const val PKT_CONTINUE = 2; private const val PKT_END = 3+ private enum class Patch { UNDONE, PROGRESS, DONE }++ private const val EP_RST_OPT = 0x74011890; private const val EP_RST_IN_OUT_OPT = 0x00010001+ private const val BT_MISC = 0x70002510; private const val BT_RST_DONE = 0x100+ private const val BT_SUBSYS_RST = 0x70002610; private const val BT_WDT_STATUS = 0x740003A0+ private const val UDMA_INT_STA_BT = 0x74000024; private const val UDMA_INT_STA_BT1 = 0x74000308++ private const val HEADER = 32; private const val GLOBAL_DESC = 64; private const val SEC_MAP = 64+ private const val SEC_MAP_COMMON = 12; private const val SEC_MAP_NEED_SEND = 52++ /** What [identify] read: the chip and its firmware file. */+ class Chip(val devId: Int, val fwVersion: Int, val flavor: Int) {+ val name get() = if (devId == 0x7961) "MT7921AU" else "MT%04X".format(devId and 0xffff)+ /** btmtk_fw_get_filename for the chips with a USB form; null for one this app doesn't drive. */+ val firmware: String? get() = when (devId) {+ 0x7961 -> if (flavor != 0) null else "BT_RAM_CODE_MT7961_1_%x_hdr.bin".format((fwVersion and 0xff) + 1)+ else -> null+ }+ }++ // ---- registers (btmtk_usb_reg_read, btmtk_usb_uhw_reg_read / _write) ----++ private fun regRead(h: HciUsb, reg: Int): Int {+ val b = h.ctlIn(0xC0, 0x63, reg ushr 16, reg and 0xffff, 4) ?: throw IOException("register %08x not readable".format(reg))+ if (b.size < 4) throw IOException("register %08x: short read".format(reg))+ return HciUsb.le32(b, 0)+ }++ private fun uhwWrite(h: HciUsb, reg: Int, v: Int) {+ val d = byteArrayOf(v.toByte(), (v shr 8).toByte(), (v shr 16).toByte(), (v shr 24).toByte())+ if (!h.ctlOut(0x5E, 0x02, reg ushr 16, reg and 0xffff, d)) throw IOException("uhw register %08x not written".format(reg))+ }++ private fun uhwRead(h: HciUsb, reg: Int): Int {+ val b = h.ctlIn(0xDE, 0x01, reg ushr 16, reg and 0xffff, 4) ?: throw IOException("uhw register %08x not readable".format(reg))+ if (b.size < 4) throw IOException("uhw register %08x: short read".format(reg))+ return HciUsb.le32(b, 0)+ }++ /** The first part of btmtk_usb_setup: chip ID, firmware version and flavour. */+ fun identify(h: HciUsb): Chip {+ var devId = regRead(h, 0x80000008L.toInt())+ var fwVersion = 0; var flavor = 0+ if (devId == 0 || devId != 0x7663) {+ devId = regRead(h, 0x70010200)+ fwVersion = regRead(h, 0x80021004L.toInt())+ flavor = (regRead(h, 0x70010020) and 0x80) shr 7+ }+ return Chip(devId, fwVersion, flavor)+ }++ /**+ * btmtk_usb_hci_wmt_sync: the WMT command goes out as HCI vendor command 0xFC6F, its event+ * comes back on control IN request 1 (wValue 48), asked again every 500 us while it returns nothing.+ * Returns the event's WMT flag byte and, for FUNC_CTRL, its status word.+ */+ private fun wmt(h: HciUsb, op: Int, flag: Int, data: ByteArray): Pair<Int, Int?> {+ val dlen = data.size+ if (5 + dlen > 255) throw IOException("WMT command too long")+ h.send(0xFC6F, byteArrayOf(1, op.toByte(), (dlen + 1).toByte(), ((dlen + 1) shr 8).toByte(), flag.toByte()) + data)+ val deadline = System.currentTimeMillis() + h.cmdTimeoutMs+ while (System.currentTimeMillis() < deadline) {+ val e = h.ctlIn(0xC0, 0x01, 48, 0, 64)+ if (e == null) { if (h.unplugged) throw IOException("adapter unplugged"); continue }+ if (e.isEmpty()) { Thread.sleep(0, 500_000); continue }+ // hci_event_hdr (2) + wmt_hdr: dir, op, dlen (2), flag+ if (e.size < 7) throw IOException("WMT event too short (${e.size} bytes)")+ if (e[3].toInt() and 0xff != op) throw IOException("WMT answer for op ${e[3].toInt() and 0xff}, expected $op")+ val status = if (op == WMT_FUNC_CTRL && e.size >= 9) ((e[7].toInt() and 0xff) shl 8) or (e[8].toInt() and 0xff) else null+ return (e[6].toInt() and 0xff) to status+ }+ throw IOException("WMT command $op timed out")+ }++ private fun patchStatus(flag: Int) = when (flag) { 2 -> Patch.DONE; 1 -> Patch.PROGRESS; else -> Patch.UNDONE }++ /** btmtk_setup_firmware_79xx. */+ private fun download(h: HciUsb, fw: ByteArray, tag: String) {+ if (fw.size < HEADER + GLOBAL_DESC) throw IOException("firmware too small")+ val sections = HciUsb.le32(fw, HEADER + 12)+ if (sections <= 0 || fw.size < HEADER + GLOBAL_DESC + SEC_MAP * sections) throw IOException("firmware section table damaged")+ UsbWifi.log("$tag: firmware built ${String(fw, 0, 14, Charsets.US_ASCII).trimEnd('\u0000')}, $sections sections")+ for (i in 0 until sections) {+ val map = HEADER + GLOBAL_DESC + SEC_MAP * i+ val offset = HciUsb.le32(fw, map + 4)+ var size = HciUsb.le32(fw, map + 16) // bin_info_spec.dlsize+ if (size <= 0) continue+ if (offset < 0 || offset.toLong() + size > fw.size) throw IOException("firmware section $i out of bounds")+ var retry = 20+ var go = false+ while (retry > 0) {+ val cmd = byteArrayOf(0) + fw.copyOfRange(map + SEC_MAP_COMMON, map + SEC_MAP_COMMON + SEC_MAP_NEED_SEND)+ when (patchStatus(wmt(h, WMT_PATCH_DWNLD, 0, cmd).first)) {+ Patch.UNDONE -> { go = true; break }+ Patch.PROGRESS -> { Thread.sleep(100); retry-- }+ Patch.DONE -> break+ }+ }+ if (retry == 0) throw IOException("firmware section $i: chip stayed busy")+ if (!go) { UsbWifi.log("$tag: section $i already loaded"); continue }+ var at = offset+ var first = true+ while (size > 0) {+ val len = minOf(250, size)+ val flag = when { first -> PKT_START; size - len <= 0 -> PKT_END; else -> PKT_CONTINUE }+ first = false+ if (patchStatus(wmt(h, WMT_PATCH_DWNLD, flag, fw.copyOfRange(at, at + len)).first) == Patch.PROGRESS)+ throw IOException("firmware section $i: unexpected busy answer")+ size -= len; at += len+ }+ UsbWifi.log("$tag: section $i loaded (${HciUsb.le32(fw, map + 16) / 1024} KB)")+ }+ Thread.sleep(110) // firmware activation+ }++ /** btmtk_usb_subsys_reset, MT7921 branch. */+ private fun subsysReset(h: HciUsb) {+ uhwWrite(h, EP_RST_OPT, EP_RST_IN_OUT_OPT)+ uhwRead(h, BT_WDT_STATUS)+ uhwWrite(h, BT_SUBSYS_RST, 1)+ uhwWrite(h, UDMA_INT_STA_BT, 0xFF); uhwRead(h, UDMA_INT_STA_BT)+ uhwWrite(h, UDMA_INT_STA_BT1, 0xFF); uhwRead(h, UDMA_INT_STA_BT1)+ Thread.sleep(20) // MT7921 needs 20 ms between the reset toggles+ uhwWrite(h, BT_SUBSYS_RST, 0); uhwRead(h, BT_SUBSYS_RST)+ val until = System.currentTimeMillis() + 1_000+ while (uhwRead(h, BT_MISC) and BT_RST_DONE == 0) {+ if (System.currentTimeMillis() > until) { UsbWifi.log("BT MT7921AU: subsystem reset timed out"); break }+ Thread.sleep(20)+ }+ if (regRead(h, 0x70010200) == 0) throw IOException("chip ID unreadable after reset")+ }++ /**+ * The rest of btmtk_usb_setup for the 79xx chips: firmware, endpoint reset option, Bluetooth on.+ * Null when it runs, else what failed.+ */+ fun setup(ctx: Context, h: HciUsb, chip: Chip, tag: String): String? {+ val name = chip.firmware ?: return "${chip.name} Bluetooth isn't supported yet"+ val fw = Firmware.read(ctx, name)+ UsbWifi.log("$tag: chip %04x, firmware version %02x, flavour %d: %s".format(chip.devId and 0xffff, chip.fwVersion and 0xff, chip.flavor, name))+ try {+ download(h, fw, tag)+ } catch (e: IOException) {+ if (h.unplugged) throw e+ // Linux: retry once after a reset (btmtk_reset_sync).+ UsbWifi.log("$tag: firmware download failed (${e.message}) - resetting the Bluetooth subsystem and trying again")+ subsysReset(h)+ download(h, fw, tag)+ }+ uhwWrite(h, EP_RST_OPT, EP_RST_IN_OUT_OPT)+ val (flag, status) = wmt(h, WMT_FUNC_CTRL, 0, byteArrayOf(1))+ UsbWifi.log("$tag: Bluetooth function on (flag %d, status %s)".format(flag, status?.let { "0x%03x".format(it) } ?: "none"))+ return null+ }++ /** btmtk_usb_shutdown: Bluetooth function off. */+ fun shutdown(h: HciUsb) {+ runCatching { wmt(h, WMT_FUNC_CTRL, 0, byteArrayOf(0)) }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/BtRealtek.kt b/app/src/main/java/com/rfsentinel/app/usb/BtRealtek.ktnew file mode 100644index 0000000..ff61505--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/BtRealtek.kt@@ -0,0 +1,195 @@+package com.rfsentinel.app.usb++/*+ * Bluetooth bring-up of Realtek USB controllers (RTL8761B dongles, RTL8821AU / RTL8822BU combo+ * adapters and their relatives): btrtl_setup_realtek of the Linux driver (drivers/bluetooth/btrtl.c,+ * GPL-2.0; Copyright (C) 2015 Endless Mobile, Inc.), in the same order: read the chip's subversion+ * (vendor register read 0xFC61), its local version, pick the chip from the same table, read the+ * ROM version (0xFC6D) and the security key ID, pick the patch for that ROM out of the "Realtech"+ * epatch file, append the config file and send it in 252-byte fragments (0xFC20). Only the v1+ * epatch format is handled: chips whose firmware is the newer "RTBTCore" format (RTL8822CU,+ * RTL8852 / 8851 family) are named and left alone.+ */++import android.content.Context+import java.io.IOException++internal object BtRealtek {++ private const val LMP_8723A = 0x1200; private const val LMP_8723B = 0x8723; private const val LMP_8821A = 0x8821+ private const val LMP_8761A = 0x8761; private const val LMP_8822B = 0x8822; private const val LMP_8852A = 0x8852+ private const val LMP_8851B = 0x8851; private const val LMP_8922A = 0x8922+ private const val FRAG = 252++ /** ic_id_table, USB rows: subversion, HCI revision, HCI version (0 = any), firmware, config, config required. */+ class Ic(val lmpSubver: Int, val hciRev: Int, val hciVer: Int, val name: String, val fw: String?, val cfg: String?, val cfgNeeded: Boolean)++ // fw / cfg: this app's file names (assets/usbwifi, or Firmware's download), null when not handled here.+ private val TABLE = listOf(+ Ic(LMP_8723A, 0xb, 0x6, "RTL8723AU", null, null, false),+ Ic(LMP_8723B, 0xb, 0x6, "RTL8723BU", "bt_rtl8723b_fw.bin", null, false),+ Ic(LMP_8723B, 0xd, 0x8, "RTL8723DU", null, null, true),+ Ic(LMP_8821A, 0xa, 0x6, "RTL8821AU", "bt_rtl8821a_fw.bin", null, false),+ Ic(LMP_8821A, 0xc, 0x8, "RTL8821CU", "bt_rtl8821c_fw.bin", "bt_rtl8821c_config.bin", false),+ Ic(LMP_8761A, 0xa, 0x6, "RTL8761AU", "bt_rtl8761a_fw.bin", null, false),+ Ic(LMP_8761A, 0xb, 0xa, "RTL8761BU", "bt_rtl8761bu_fw.bin", "bt_rtl8761bu_config.bin", false),+ Ic(LMP_8761A, 0x0e, 0, "RTL8761CU", "bt_rtl8761cu_fw.bin", "bt_rtl8761cu_config.bin", false),+ Ic(LMP_8822B, 0xc, 0xa, "RTL8822CU", null, null, false),+ Ic(LMP_8822B, 0xb, 0x7, "RTL8822BU", "bt_rtl8822b_fw.bin", "bt_rtl8822b_config.bin", true),+ Ic(LMP_8852A, 0xa, 0xb, "RTL8852AU", null, null, false),+ Ic(LMP_8852A, 0xb, 0xb, "RTL8852BU", null, null, false),+ Ic(LMP_8852A, 0xc, 0xc, "RTL8852CU", null, null, false),+ Ic(LMP_8851B, 0xb, 0xc, "RTL8851BU", null, null, false),+ Ic(LMP_8922A, 0xa, 0xc, "RTL8922AU", null, null, false),+ Ic(LMP_8852A, 0x87, 0xc, "RTL8852BTU", null, null, false)+ )++ /** btrtl_match_ic for the USB bus. */+ internal fun match(lmpSubver: Int, hciRev: Int, hciVer: Int): Ic? =+ TABLE.firstOrNull { it.lmpSubver == lmpSubver && it.hciRev == hciRev && (it.hciVer == hciVer || it.hciVer == 0) }++ /** What [identify] found: the chip (null: not in the table) and its ROM version. */+ class Found(val ic: Ic?, val romVersion: Int, val keyId: Int, val lmpSubver: Int, val hciRev: Int, val hciVer: Int) {+ val name get() = ic?.name ?: "Realtek %04x".format(lmpSubver)+ /** The files to load; empty when no upload is needed or this chip isn't handled. */+ val files get() = listOfNotNull(ic?.fw, ic?.cfg?.takeIf { keyId == 0 })+ }++ /** btrtl_vendor_read_reg16: 0xFC61 answers status + 2 bytes. */+ private fun reg16(h: HciUsb, cmd: ByteArray): Int {+ val r = h.cmd(0xFC61, cmd)+ if (r.size != 3 || r[0].toInt() != 0) throw IOException("vendor register read failed")+ return HciUsb.le16(r, 1)+ }++ private val CHIP_SUBVER = byteArrayOf(0x10, 0x38, 0x04, 0x28, 0x80.toByte())+ private val CHIP_REV = byteArrayOf(0x10, 0x3A, 0x04, 0x28, 0x80.toByte())+ private val SEC_PROJ = byteArrayOf(0x10, 0xA4.toByte(), 0xAD.toByte(), 0x00, 0xB0.toByte())++ /** btrtl_initialize, up to the firmware file names. */+ fun identify(h: HciUsb, tag: String): Found {+ var dropped = false+ while (true) {+ var lmpSubver = reg16(h, CHIP_SUBVER)+ var hciRev: Int; var hciVer: Int+ var ic: Ic? = null+ var e8822 = false+ if (lmpSubver == LMP_8822B) {+ hciRev = reg16(h, CHIP_REV)+ if (hciRev == 0x000e) { hciVer = 0x0c; e8822 = true } // RTL8822E: not handled here+ else hciVer = 0+ } else { hciRev = 0; hciVer = 0 }+ if (!e8822) {+ val v = h.cmd(0x1001) // HCI_OP_READ_LOCAL_VERSION+ if (v.size != 9) throw IOException("local version answer has the wrong length")+ hciVer = v[1].toInt() and 0xff+ hciRev = HciUsb.le16(v, 2)+ lmpSubver = HciUsb.le16(v, 7)+ ic = match(lmpSubver, hciRev, hciVer)+ }+ UsbWifi.log("$tag: examining hci_ver=%02x hci_rev=%04x lmp_subver=%04x".format(hciVer, hciRev, lmpSubver))+ // Not in the table: the controller may be running a stock firmware; ask it to drop it (0xFC66) and look again, once.+ if (ic == null && !dropped) {+ dropped = true+ h.send(0xFC66)+ Thread.sleep(200)+ continue+ }+ if (ic == null) return Found(null, 0, 0, lmpSubver, hciRev, hciVer)+ var rom = 0+ if (ic.lmpSubver != LMP_8723A) { // has_rom_version on every USB chip but the 8723A+ val r = h.cmd(0xFC6D)+ if (r.size != 2) throw IOException("ROM version answer has the wrong length")+ rom = r[1].toInt() and 0xff+ UsbWifi.log("$tag: rom_version status=%x version=%x".format(r[0].toInt() and 0xff, rom))+ }+ val keyId = reg16(h, SEC_PROJ) and 0xff+ UsbWifi.log("$tag: key id $keyId")+ return Found(ic, rom, keyId, lmpSubver, hciRev, hciVer)+ }+ }++ /** project_id_to_lmp_subver. */+ private val PROJECTS = mapOf(0 to LMP_8723A, 1 to LMP_8723B, 2 to LMP_8821A, 3 to LMP_8761A, 7 to 0x8703, 8 to LMP_8822B,+ 9 to LMP_8723B, 10 to LMP_8821A, 13 to LMP_8822B, 14 to LMP_8761A, 18 to LMP_8852A, 20 to LMP_8852A, 25 to LMP_8852A,+ 36 to LMP_8851B, 44 to LMP_8922A, 47 to LMP_8852A, 51 to LMP_8761A)++ /** rtlbt_parse_firmware for the v1 "Realtech" epatch: the patch for [romVersion], with the file's version at its end. */+ internal fun parse(fw: ByteArray, lmpSubver: Int, romVersion: Int): ByteArray {+ val ext = byteArrayOf(0x51, 0x04, 0xfd.toByte(), 0x77)+ val sig = String(fw, 0, minOf(8, fw.size), Charsets.US_ASCII)+ if (sig == "RTBTCore") throw IOException("this chip's firmware is the newer RTBTCore format, not supported yet")+ if (sig != "Realtech") throw IOException("bad epatch signature")+ val headerLen = 14 // signature 8, fw_version 4, num_patches 2+ if (fw.size < headerLen + ext.size + 3) throw IOException("firmware too small")+ var p = fw.size - ext.size+ if (!fw.copyOfRange(p, fw.size).contentEquals(ext)) throw IOException("extension signature mismatch")+ // Walk the instructions backwards from the end to the one naming the project.+ var project = -1+ while (p >= headerLen + 3) {+ val opcode = fw[--p].toInt() and 0xff+ val length = fw[--p].toInt() and 0xff+ val data = fw[--p].toInt() and 0xff+ if (opcode == 0xff) break+ if (length == 0) throw IOException("firmware instruction with length 0")+ if (opcode == 0 && length == 1) { project = data; break }+ p -= length+ }+ if (project < 0) throw IOException("firmware has no version instruction")+ val forLmp = PROJECTS[project] ?: throw IOException("unknown firmware project $project")+ if (forLmp != lmpSubver) throw IOException("firmware is for %x but this is a %x".format(forLmp, lmpSubver))+ val patches = HciUsb.le16(fw, 12)+ if (fw.size < headerLen + ext.size + 3 + 8 * patches) throw IOException("firmware patch table truncated")+ val ids = headerLen+ val lengths = ids + 2 * patches+ val offsets = lengths + 2 * patches+ var length = 0; var offset = 0+ for (i in 0 until patches) {+ if (HciUsb.le16(fw, ids + 2 * i) == romVersion + 1) {+ length = HciUsb.le16(fw, lengths + 2 * i)+ offset = HciUsb.le32(fw, offsets + 4 * i)+ break+ }+ }+ if (offset == 0) throw IOException("no patch for ROM version $romVersion")+ if (length < 4 || offset < 0 || offset > fw.size || length > fw.size - offset) throw IOException("patch out of bounds")+ val out = ByteArray(length)+ fw.copyInto(out, 0, offset, offset + length - 4)+ fw.copyInto(out, length - 4, 8, 12) // the file's fw_version+ return out+ }++ /** rtl_download_firmware: 252-byte fragments, index 0..0x7f then from 1 again, the last one with bit 7 set. */+ private fun send(h: HciUsb, data: ByteArray, tag: String) {+ val frags = data.size / FRAG + 1+ var j = 0+ var at = 0+ for (i in 0 until frags) {+ var index = j+++ if (index == 0x7f) j = 1+ var len = FRAG+ if (i == frags - 1) { index = index or 0x80; len = data.size % FRAG }+ val cmd = ByteArray(1 + len)+ cmd[0] = index.toByte()+ data.copyInto(cmd, 1, at, at + len)+ val r = h.cmd(0xFC20, cmd)+ if (r.size != 2) throw IOException("download answer has the wrong length")+ at += FRAG+ }+ val v = h.cmd(0x1001)+ if (v.size == 9) UsbWifi.log("$tag: fw version 0x%04x%04x".format(HciUsb.le16(v, 2), HciUsb.le16(v, 7)))+ }++ /** btrtl_download_firmware (8723B-style chips). Null when it runs, else what failed. */+ fun setup(ctx: Context, h: HciUsb, f: Found, tag: String): String? {+ val ic = f.ic ?: run { UsbWifi.log("$tag: unknown chip, assuming no firmware upload needed"); return null }+ val fwName = ic.fw ?: return "${ic.name} Bluetooth isn't supported yet"+ val patch = parse(Firmware.read(ctx, fwName), ic.lmpSubver, f.romVersion)+ val cfg = ic.cfg?.takeIf { f.keyId == 0 }?.let { runCatching { Firmware.read(ctx, it) }.getOrNull() }+ if (ic.cfgNeeded && cfg == null) return "${ic.name}: its config file is missing"+ val all = if (cfg != null) patch + cfg else patch+ UsbWifi.log("$tag: cfg_sz ${cfg?.size ?: 0}, total sz ${all.size}")+ send(h, all, tag)+ return null+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/Firmware.kt b/app/src/main/java/com/rfsentinel/app/usb/Firmware.ktindex 64c6124..0b0d83f 100644--- a/app/src/main/java/com/rfsentinel/app/usb/Firmware.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/Firmware.kt@@ -8,7 +8,7 @@ import java.net.URLimport java.security.MessageDigest/**- * The USB WiFi chips' own firmware. The full build carries it in assets/usbwifi. The FOSS build leaves out the+ * The USB WiFi and Bluetooth chips' own firmware. The full build carries it in assets/usbwifi. The FOSS build leaves out the* firmware that isn't free software (Ralink, MediaTek and Realtek binaries) and, with your OK, downloads those exact* files once from linux-firmware on kernel.org, pinned to one commit and checked against their SHA-256, into the* app's own storage. The free ath9k_htc firmware and the Realtek register tables (GPL-2.0) ship in both builds.@@ -35,8 +35,36 @@ object Firmware {private val RTL8822B = Blob("rtl8822b_fw.bin", "rtw88/rtw8822b_fw.bin","a72da690597bfa99d8eb6fc2ab090d18d8ad92ac2befd35db1c9e3662d8d8418", 161240, "LICENCE.rtlwifi_firmware.txt")+ /** USB Bluetooth controllers' firmware ([BtMediatek], [BtRealtek]): Realtek's renamed bt_*, as two chips share a name with WiFi files. */+ private val BLUETOOTH = listOf(+ Blob("BT_RAM_CODE_MT7961_1_2_hdr.bin", "mediatek/BT_RAM_CODE_MT7961_1_2_hdr.bin",+ "7a440a0f7404c73a2f03d8cc0475ac9f7fdc931b494dce37705e7d578153dbae", 533870, "LICENCE.mediatek"),+ Blob("bt_rtl8723b_fw.bin", "rtl_bt/rtl8723b_fw.bin",+ "c9c8a9f6ebd90b7449a7e4d38ee39952dc7cc47d6c1d054e42cfbb5e4d818853", 45048, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8761a_fw.bin", "rtl_bt/rtl8761a_fw.bin",+ "581e5e81f5b51a29f475f8a276be95ad3210b3e3065987541c508e7f7a83a462", 74488, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8761bu_fw.bin", "rtl_bt/rtl8761bu_fw.bin",+ "1d7a9597349ad89344fa16c1913d3e39e9a12e966e417ca16871bc79bbe59edb", 44484, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8761bu_config.bin", "rtl_bt/rtl8761bu_config.bin",+ "6c28a3f07c6a30ed208c4b64862a23f02b7d93543ea980edd24df16bab45095f", 6, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8761cu_fw.bin", "rtl_bt/rtl8761cu_fw.bin",+ "525bfa5ab9a3ed74b788f9ac494467c522a436c1bc5290ebcb05c7f920533c09", 10296, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8761cu_config.bin", "rtl_bt/rtl8761cu_config.bin",+ "3142c2732470e4edcdb68edf58cc505b581e38d56b3ec09c64eddcb1d5099507", 11, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8821a_fw.bin", "rtl_bt/rtl8821a_fw.bin",+ "3ed5077f8f02ff2b06be257691dc72061efac976cd2dc174057833624c820b9d", 37420, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8821c_fw.bin", "rtl_bt/rtl8821c_fw.bin",+ "dfe7ef772d078ec09490c02190a32fcd40b3eaf3b040049d8930eb80e6d5743c", 54636, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8821c_config.bin", "rtl_bt/rtl8821c_config.bin",+ "292717b0610ce920f66b734c299d349ea59a4c4400044078d8fc65625f17e382", 10, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8822b_fw.bin", "rtl_bt/rtl8822b_fw.bin",+ "eecef2c3b2ff03c3a41292a93a25eca6f4ec38eb4a7491a3651b530be89a04fc", 51176, "LICENCE.rtlwifi_firmware.txt"),+ Blob("bt_rtl8822b_config.bin", "rtl_bt/rtl8822b_config.bin",+ "ea082136d5285655372e3805cd50d961bd7d42085c6fc1058a115a7e844df9c1", 14, "LICENCE.rtlwifi_firmware.txt")+ )+/** Every file the FOSS build may download. */- val ALL = listOf(RT2870, MT7662_PATCH, MT7662, MT7961_PATCH, MT7961_RAM, RTL8822B)+ val ALL = listOf(RT2870, MT7662_PATCH, MT7662, MT7961_PATCH, MT7961_RAM, RTL8822B) + BLUETOOTH/** The non-free files a driver needs (none for the drivers that load no firmware or only free files). */fun needed(driver: UsbWifi.Driver): List<Blob> = when (driver) {@@ -59,6 +87,10 @@ object Firmware {fun missing(context: Context, driver: UsbWifi.Driver): List<Blob> =needed(driver).filter { !inAssets(context, it.name) && !File(dir(context), it.name).isFile }+ /** Of the files named [names] (a USB Bluetooth controller's), those neither in this APK nor downloaded yet. */+ fun missingFiles(context: Context, names: List<String>): List<Blob> =+ ALL.filter { it.name in names && !inAssets(context, it.name) && !File(dir(context), it.name).isFile }+/** A file from assets/usbwifi, or one downloaded earlier (checked again before use). */fun read(context: Context, name: String): ByteArray {runCatching { return context.assets.open("usbwifi/$name").use { it.readBytes() } }diff --git a/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt b/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.ktindex b1add82..f712787 100644--- a/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt@@ -16,8 +16,8 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContext/**- * FOSS build: asks before downloading a USB WiFi chip's non-free firmware ([Firmware]). A notification when the- * adapter is plugged in; tapping it (or the adapter line in Settings) opens Settings with the question.+ * FOSS build: asks before downloading a USB WiFi or Bluetooth chip's non-free firmware ([Firmware]). A notification+ * when the adapter is plugged in; tapping it (or the adapter line in Settings) opens Settings with the question.*/object FirmwarePrompt {@@ -25,7 +25,8 @@ object FirmwarePrompt {private const val CHANNEL = "usb_firmware"private const val NOTIFICATION_ID = 4130- fun notify(context: Context, chip: UsbWifi.Chip) {+ /** [chip]: what the adapter is called ("MT7921AU", "RTL8761BU Bluetooth"). */+ fun notify(context: Context, chip: String) {val nm = context.getSystemService(NotificationManager::class.java) ?: returnnm.createNotificationChannel(NotificationChannel(CHANNEL, "USB adapter firmware", NotificationManager.IMPORTANCE_DEFAULT))val open = PendingIntent.getActivity(context, NOTIFICATION_ID,@@ -35,7 +36,7 @@ object FirmwarePrompt {runCatching {nm.notify(NOTIFICATION_ID, NotificationCompat.Builder(context, CHANNEL).setSmallIcon(R.drawable.ic_tile_scan)- .setContentTitle("${chip.name} adapter needs its firmware")+ .setContentTitle("$chip adapter needs its firmware").setContentText("Tap to download it once from kernel.org").setContentIntent(open).setAutoCancel(true)@@ -47,10 +48,28 @@ object FirmwarePrompt {context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)}+ /** What waits for firmware: its name, the files still missing, and how to start it once they're here. */+ private class Waiting(val name: String, val blobs: List<Firmware.Blob>, val retry: (Context) -> Unit)++ /** The WiFi adapter first, else the Bluetooth one; null when neither waits (or its files just arrived: started). */+ private fun waiting(context: Context): Waiting? {+ UsbWifi.firmwareNeeded?.let { chip ->+ val blobs = Firmware.missing(context, chip.driver)+ if (blobs.isNotEmpty()) return Waiting(chip.name, blobs, UsbWifi::retry)+ UsbWifi.retry(context)+ }+ UsbBluetooth.firmwareNeeded?.let { (chip, files) ->+ val blobs = Firmware.missingFiles(context, files)+ if (blobs.isNotEmpty()) return Waiting("$chip Bluetooth", blobs, UsbBluetooth::retry)+ UsbBluetooth.retry(context)+ }+ return null+ }+/** The question, for the adapter waiting for its firmware; false when none is waiting. */fun show(activity: AppCompatActivity, onDone: () -> Unit = {}): Boolean {- val chip = UsbWifi.firmwareNeeded ?: return false- val blobs = Firmware.missing(activity, chip.driver).ifEmpty { UsbWifi.retry(activity); return false }+ val chip = waiting(activity) ?: return false+ val blobs = chip.blobsval kb = blobs.sumOf { it.size } / 1024val files = blobs.joinToString("\n") { "• ${it.name}" }MaterialAlertDialogBuilder(activity)@@ -71,7 +90,7 @@ object FirmwarePrompt {return true}- private fun download(activity: AppCompatActivity, chip: UsbWifi.Chip, blobs: List<Firmware.Blob>, onDone: () -> Unit) {+ private fun download(activity: AppCompatActivity, chip: Waiting, blobs: List<Firmware.Blob>, onDone: () -> Unit) {val app = activity.applicationContextToast.makeText(activity, "Downloading the ${chip.name} firmware…", Toast.LENGTH_SHORT).show()activity.lifecycleScope.launch {@@ -79,7 +98,7 @@ object FirmwarePrompt {if (error == null) {UsbWifi.log("Firmware for ${chip.name} downloaded and checked")cancel(app)- UsbWifi.retry(app)+ chip.retry(app)Toast.makeText(app, "Firmware ready: starting the ${chip.name} adapter", Toast.LENGTH_SHORT).show()} else {UsbWifi.log("Firmware download failed: ${UsbWifi.describe(error)}")diff --git a/app/src/main/java/com/rfsentinel/app/usb/HciUsb.kt b/app/src/main/java/com/rfsentinel/app/usb/HciUsb.ktnew file mode 100644index 0000000..8c68c25--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/HciUsb.kt@@ -0,0 +1,158 @@+package com.rfsentinel.app.usb++/*+ * The Bluetooth HCI transport of a USB Bluetooth controller, as the Linux btusb driver+ * (drivers/bluetooth/btusb.c, GPL-2.0) runs it: commands go out as class control requests on+ * endpoint 0 (alloc_ctrl_urb: bRequestType USB_TYPE_CLASS, bRequest 0, wValue 0, wIndex 0),+ * events come in on interface 0's interrupt IN endpoint one max-packet at a time and are put+ * back together by their length byte (btusb_recv_intr). The interrupt endpoint is read from the+ * moment the interface is open, as btusb_open does, so nothing the controller says is lost.+ * Only the command and event channels are used: no ACL or SCO data, nothing is ever connected to.+ */++import android.hardware.usb.UsbDeviceConnection+import android.hardware.usb.UsbEndpoint+import java.io.IOException+import java.util.concurrent.LinkedBlockingQueue+import java.util.concurrent.TimeUnit++internal class HciUsb(private val conn: UsbDeviceConnection, private val evtIn: UsbEndpoint, private val tag: String) {++ /** HCI_INIT_TIMEOUT. */+ val cmdTimeoutMs = 10_000L++ /** Complete events other than advertising reports, for the command waiting on them. */+ private val events = LinkedBlockingQueue<ByteArray>(256)+ /** LE Meta events carrying advertising reports (subevents 0x02 and 0x0D), straight from the reader thread. */+ @Volatile var onAdvertising: ((ByteArray) -> Unit)? = null+ @Volatile private var stop = false+ private var reader: Thread? = null+ /** Consecutive failed control transfers: about 25 in a row means the adapter is gone. */+ @Volatile var ctlErrors = 0; private set+ @Volatile var eventsIn = 0L; private set+ /** The event endpoint fails at once, over and over: the adapter is gone or taken. */+ @Volatile private var readDead = false++ fun startReader() {+ stop = false+ reader = Thread({ readLoop() }, "usb-bt-events").also { it.isDaemon = true; it.start() }+ }++ fun close() {+ stop = true+ reader?.let { runCatching { it.join(1_000) } }+ reader = null+ }++ /** btusb_recv_intr: one event = 2-byte header (code, length) + that many bytes; a chunk can hold several. */+ private fun readLoop() {+ val size = evtIn.maxPacketSize.coerceIn(16, 1024)+ val chunk = ByteArray(size)+ var evt: java.io.ByteArrayOutputStream? = null+ var expect = 0+ var fastFails = 0+ while (!stop) {+ val t0 = System.nanoTime()+ val n = conn.bulkTransfer(evtIn, chunk, size, 200)+ if (n <= 0) {+ // A timeout takes the full 200 ms; an error comes back at once, so pause instead of spinning on it.+ if (System.nanoTime() - t0 < 50_000_000L) {+ if (++fastFails >= 100) { readDead = true; UsbWifi.log("$tag: event endpoint keeps failing - adapter gone"); return }+ Thread.sleep(50)+ } else fastFails = 0+ continue+ }+ fastFails = 0+ var off = 0+ var count = n+ while (count > 0) {+ if (evt == null) { evt = java.io.ByteArrayOutputStream(260); expect = 2 }+ val len = minOf(expect, count)+ evt.write(chunk, off, len)+ off += len; count -= len; expect -= len+ if (evt.size() == 2 && expect == 0) expect = chunk[off - 1].toInt() and 0xff // the header is complete: its length+ if (expect == 0) {+ // Each chunk should hold whole events: a leftover too short for a header is a controller bug.+ if (count in 1 until 2) { UsbWifi.log("$tag: unexpected $count-byte continuation dropped"); count = 0 }+ deliver(evt.toByteArray())+ evt = null+ }+ }+ }+ }++ private fun deliver(e: ByteArray) {+ eventsIn+++ if (e.size >= 3 && e[0].toInt() == 0x3E && (e[2].toInt() == 0x02 || e[2].toInt() == 0x0D)) {+ onAdvertising?.invoke(e)+ return+ }+ if (e.size >= 2 && e[0].toInt() == 0x10) UsbWifi.log("$tag: controller reported a hardware error (code ${e.getOrNull(2)?.toInt()?.and(0xff)})")+ if (!events.offer(e)) { events.poll(); events.offer(e) }+ }++ /** Sends a command without waiting for its answer (__hci_cmd_send). */+ fun send(opcode: Int, params: ByteArray = ByteArray(0)) {+ require(params.size <= 255)+ val pkt = ByteArray(3 + params.size)+ pkt[0] = opcode.toByte(); pkt[1] = (opcode shr 8).toByte(); pkt[2] = params.size.toByte()+ params.copyInto(pkt, 3)+ val r = conn.controlTransfer(0x20, 0x00, 0, 0, pkt, pkt.size, 1_000)+ if (r < 0) { ctlErrors++; throw IOException("command %04x not accepted by the adapter".format(opcode)) }+ ctlErrors = 0+ }++ /**+ * Sends a command and waits for its Command Complete (__hci_cmd_sync): returns its return+ * parameters (status first for most commands). A Command Status with an error fails it.+ */+ fun cmd(opcode: Int, params: ByteArray = ByteArray(0), timeoutMs: Long = cmdTimeoutMs): ByteArray {+ send(opcode, params)+ val deadline = System.currentTimeMillis() + timeoutMs+ while (!stop) {+ val left = deadline - System.currentTimeMillis()+ if (left <= 0) break+ val e = events.poll(left, TimeUnit.MILLISECONDS) ?: break+ val code = e[0].toInt() and 0xff+ if (code == 0x0E && e.size >= 5 && op(e, 3) == opcode) return e.copyOfRange(5, e.size)+ if (code == 0x0F && e.size >= 6 && op(e, 4) == opcode) {+ val status = e[2].toInt() and 0xff+ if (status != 0) throw IOException("command %04x refused (status 0x%02x)".format(opcode, status))+ }+ }+ throw IOException("no answer to command %04x".format(opcode))+ }++ /** cmd, then its status byte must be 0. */+ fun cmdOk(opcode: Int, params: ByteArray = ByteArray(0)): ByteArray {+ val r = cmd(opcode, params)+ if (r.isEmpty() || r[0].toInt() != 0) throw IOException("command %04x failed (status 0x%02x)".format(opcode, r.firstOrNull()?.toInt()?.and(0xff) ?: -1))+ return r+ }++ /** Vendor control-IN request on endpoint 0; null when it failed. Counts consecutive failures. */+ fun ctlIn(type: Int, request: Int, value: Int, index: Int, length: Int, timeoutMs: Int = 1_000): ByteArray? {+ val buf = ByteArray(length)+ val n = conn.controlTransfer(type, request, value, index, buf, length, timeoutMs)+ if (n < 0) { ctlErrors++; return null }+ ctlErrors = 0+ return buf.copyOf(n)+ }++ fun ctlOut(type: Int, request: Int, value: Int, index: Int, data: ByteArray): Boolean {+ val n = conn.controlTransfer(type, request, value, index, data, data.size, 1_000)+ if (n < 0) { ctlErrors++; return false }+ ctlErrors = 0+ return true+ }++ val unplugged get() = ctlErrors >= 25 || readDead++ companion object {+ fun op(b: ByteArray, at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8)+ fun le16(b: ByteArray, at: Int) = op(b, at)+ fun le32(b: ByteArray, at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8) or+ ((b[at + 2].toInt() and 0xff) shl 16) or ((b[at + 3].toInt() and 0xff) shl 24)+ fun u16(v: Int) = byteArrayOf(v.toByte(), (v shr 8).toByte())+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.mdindex 0ed1ba1..8997bd5 100644--- a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md+++ b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md@@ -13,6 +13,7 @@ These drivers run USB WiFi adapters in receive-only monitor mode from userspace.- `Ar9271Monitor.kt` and `Ar9271Tables.kt` drive Atheros AR9271 adapters (e.g. ALFA AWUS036NHA) - experimental - with the open ath9k_htc firmware in `assets/usbwifi/htc_9271-1.4.0.fw`.- `BulkRx.kt` is the USB receive loop of the RTL8187, RT3070, RTL8814AU, MT7612U and AR9271 drivers.- The FREE-WiLi 2 (an ESP32-C5 WiFi board with a USB console) is read by `esp/EspReader.kt` / `esp/EspReports.kt` (FreeWiliReports), ported from Wardrive Go.+- `UsbBluetooth.kt`, `HciUsb.kt`, `BtMediatek.kt` and `BtRealtek.kt` use the Bluetooth part of a USB adapter (a Bluetooth dongle, or the Bluetooth side of an MT7921AU or Realtek combo adapter) as a second LE scanner, receive only: standard HCI over USB, with MediaTek's and Realtek's firmware set-up.- `MonitorFrames.kt` turns the received 802.11 frames into access points and client devices for all of them.- `AntennaCheck.kt` (and the Antenna check screen) compares the adapter's antennas on a reference access point: per-chain signal with Zero and Identify, and an A / B swap test, after the antenna check in Wardrive Go (written anew here, no code copied).@@ -33,6 +34,11 @@ These drivers run USB WiFi adapters in receive-only monitor mode from userspace.| MT7921AU userspace USB driver (WFSYS reset, USB / WFDMA setup, ROM patch and firmware download, MCU command framing, efuse calibration push, monitor filters and sniffer mode, channel switching, RX descriptor parsing) | [mt76-usb-macos](https://github.com/Network-Weather/mt76-usb-macos) by Network Weather (Copyright (c) 2026 Primatech Paper Co LLC d/b/a Network Weather), a transcription of the MT7921 path of the Linux mt76 driver ([openwrt/mt76](https://github.com/openwrt/mt76): Copyright (C) 2020-2023 MediaTek Inc., (C) 2018 Lorenzo Bianconi, (C) 2016 Felix Fietkau) | BSD-3-Clause-Clear || MT7921AU ROM patch `WIFI_MT7961_patch_mcu_1_2_hdr.bin` and firmware `WIFI_RAM_CODE_MT7961_1.bin` (unmodified, from linux-firmware commit e981caea6ed3) | MediaTek Inc. | Redistributable binary, see `assets/usbwifi/LICENCE.mediatek` || AR9271 firmware `htc_9271-1.4.0.fw` (unmodified, from linux-firmware; Wardrive Go ships a build that differs in 10 bytes) | [open-ath9k-htc-firmware](https://github.com/qca/open-ath9k-htc-firmware), Qualcomm Atheros and others | Free software, see `assets/usbwifi/LICENCE.open-ath9k-htc-firmware` |+| USB Bluetooth HCI transport (class control commands, interrupt-endpoint event reassembly) | Linux `btusb` driver (`drivers/bluetooth/btusb.c`: Marcel Holtmann and others) | GPL-2.0 |+| MT7921AU Bluetooth set-up (chip ID, WMT patch download, subsystem reset, function on / off) | Linux `btmtk` driver (`drivers/bluetooth/btmtk.c`, Copyright (c) 2021 MediaTek Inc.) | GPL-2.0 |+| Realtek Bluetooth set-up (chip identification, v1 epatch parsing, firmware / config download) | Linux `btrtl` driver (`drivers/bluetooth/btrtl.c`, Copyright (C) 2015 Endless Mobile, Inc.; Realtek Semiconductor Corp.) | GPL-2.0 |+| MT7921AU Bluetooth firmware `BT_RAM_CODE_MT7961_1_2_hdr.bin` (unmodified, from linux-firmware) | MediaTek Inc. | Redistributable binary, see `assets/usbwifi/LICENCE.mediatek` |+| Realtek Bluetooth firmware and config files `bt_rtl*.bin` (unmodified, from linux-firmware `rtl_bt/`) | Realtek Semiconductor Corp. | Redistributable binary, see `assets/usbwifi/LICENCE.rtlwifi_firmware.txt` || RTL-SDR driver (`sdr/RtlSdr.kt`: RTL2832U baseband, R820T / R828D tuner, RTL-SDR Blog V4 band switching) | [librtlsdr](https://github.com/osmocom/rtl-sdr) (osmocom: Steve Markgraf, Dimitri Stolnikov and others; R82xx code by Mauro Carvalho Chehab and Steve Markgraf; Blog V4 support by RTL-SDR Blog) | GPL-2.0-or-later || Integration into RF Sentinel; removal of handshake / PMKID capture (8821AU, RT3070) and of every transmit, beamforming and calibration-for-TX path (8822BU, RTL8187); RT3070 fixes checked against the kernel (eFuse addressing, EEPROM reads, DMA / frame-length setup, receive gain, external LNA, EEPROM BBP overrides); MT7612U: bad-checksum frames dropped, auto-responder off, kernel ROM-patch rule; AR9271: signal relative to the noise floor, FCS removed, packets spanning transfers reassembled, WMI answers matched, running firmware reused; MT7921AU: Android USB host API instead of IOKit, no port reset, commands while receiving answered on the shared endpoint without blocking, bad-checksum frames dropped, failed register reads never written back, every transmit path (injection, TX descriptors) left out | RF Sentinel (CIS-C0) | GPL-3.0 |@@ -46,11 +52,11 @@ RF Sentinel is distributed under the GNU GPL v3.0 (see `LICENSE`). The registervalues and firmware are hardware configuration data from Realtek's driver; creditand thanks to Realtek, the aircrack-ng rtl8812au maintainers, RocketGod forWardrive Go, OpenIPC for devourer, Network Weather for mt76-usb-macos, MediaTek and-the mt76 authors, the Linux rtl8187 and rt2x00 authors, and Kismet. The Ralink and MediaTek firmware is redistributed under its own licences+the mt76 authors, the Linux btusb / btmtk / btrtl authors, the Linux rtl8187 and rt2x00 authors, and Kismet. The Ralink and MediaTek firmware is redistributed under its own licences(binary only, unmodified, no reverse engineering), reproduced in`assets/usbwifi/LICENCE.ralink-firmware.txt` and`assets/usbwifi/LICENCE.ralink_a_mediatek_company_firmware` and-`assets/usbwifi/LICENCE.mediatek` (MT7961: redistributed for use with MediaTek+`assets/usbwifi/LICENCE.mediatek` and `assets/usbwifi/LICENCE.rtlwifi_firmware.txt` (Realtek WiFi and Bluetooth firmware) (MT7961: redistributed for use with MediaTekchipsets, as separate files not covered by this app's GPL); the ath9k_htc firmwareis free software (`assets/usbwifi/LICENCE.open-ath9k-htc-firmware`, sources athttps://github.com/qca/open-ath9k-htc-firmware).diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.ktnew file mode 100644index 0000000..d096e2b--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbBluetooth.kt@@ -0,0 +1,366 @@+package com.rfsentinel.app.usb++/*+ * Bluetooth LE scanning with a USB Bluetooth controller: a plain dongle, or the Bluetooth half of+ * a combo WiFi + Bluetooth adapter (MT7921AU, RTL8821AU, RTL8822BU...), driven from userspace over+ * Android's USB host API, alongside the phone's own Bluetooth. The controller is brought up the way+ * the Linux btusb driver does it (vendor setup first: [BtMediatek], [BtRealtek]; then the HCI core's+ * reset), then scans passively - it never sends a scan request, never connects, never advertises.+ * Extended scanning on LE 1M and LE Coded (long range) when the controller has them, legacy+ * scanning otherwise. Settings › External hardware turns it off.+ */++import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.hardware.usb.UsbConstants+import android.hardware.usb.UsbDevice+import android.hardware.usb.UsbInterface+import android.hardware.usb.UsbManager+import androidx.core.content.ContextCompat+import java.io.IOException+import java.util.concurrent.atomic.AtomicLong++object UsbBluetooth {++ /** One advertising report, as the controller gave it. [addr] is in HCI order (least significant byte first). */+ class Report(val addr: ByteArray, val addrType: Int, val rssi: Int, val data: ByteArray, val connectable: Boolean,+ val phy: String?) {+ /** "AA:BB:CC:DD:EE:FF". */+ val mac get() = (5 downTo 0).joinToString(":") { "%02X".format(addr[it].toInt() and 0xff) }+ }++ /** Which bring-up a controller needs. */+ internal enum class Vendor { MEDIATEK, REALTEK, INTEL, GENERIC }++ private const val ACTION_PERMISSION = "com.rfsentinel.app.USB_BT_PERMISSION"+ private const val MANUFACTURER_REALTEK = 0x005D+ private const val MANUFACTURER_MEDIATEK = 0x0046++ /** Vendors whose controllers sit on a vendor-class (ff/01/01) interface (btusb_table). */+ private val VENDOR_CLASS_IDS = setOf(0x05ac, 0x105b, 0x0bb4, 0x0489, 0x04ca, 0x0a5c, 0x0b05, 0x050d, 0x13d3, 0x413c, 0x0930)++ /**+ * Standard controllers that need no firmware from the app (btusb runs them as they are), named by their+ * Bluetooth SIG company ID: CSR8510 dongles and their clones, Broadcom / Cypress BCM20702 and the like.+ */+ private val GENERIC_MAKERS = mapOf(0x000A to "CSR", 0x000F to "Broadcom", 0x0131 to "Cypress", 0x001D to "Qualcomm",+ 0x0030 to "ST", 0x000D to "Texas Instruments")++ @Volatile var status: String = ""+ private set+ /** The live controller's name (e.g. "MT7921AU", "CSR"), null while none is scanning. */+ @Volatile var runningChip: String? = null+ private set+ /** The controller waiting for its firmware (FOSS build): its name and file names; null when none. */+ @Volatile var firmwareNeeded: Pair<String, List<String>>? = null+ private set+ /** Advertising reports heard, for the adverts-per-second counter. */+ val reportCount = AtomicLong()++ private var receiver: BroadcastReceiver? = null+ private var sink: ((List<Report>) -> Unit)? = null+ private var appContext: Context? = null+ private var thread: Thread? = null+ @Volatile private var runningDevice: String? = null+ /** The running session's stop flag: each session has its own, so a quick stop and start can't revive the old one. */+ @Volatile private var halt = java.util.concurrent.atomic.AtomicBoolean(true)+ private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }++ /** The Bluetooth interface of [d] (btusb_table): class e0/01/01, or ff/01/01 for the vendors listed. */+ internal fun btInterface(d: UsbDevice): UsbInterface? = (0 until d.interfaceCount).map { d.getInterface(it) }.firstOrNull { i ->+ (i.interfaceClass == 0xe0 && i.interfaceSubclass == 0x01 && i.interfaceProtocol == 0x01) ||+ (i.interfaceClass == 0xff && i.interfaceSubclass == 0x01 && i.interfaceProtocol == 0x01 && d.vendorId in VENDOR_CLASS_IDS)+ }?.takeIf { i -> (0 until i.endpointCount).any { i.getEndpoint(it).let { e -> e.type == UsbConstants.USB_ENDPOINT_XFER_INT && e.direction == UsbConstants.USB_DIR_IN } } }++ /** Known from the USB ID alone: MediaTek (its chip ID registers are read before any HCI command), Realtek, Intel. */+ internal fun vendorOf(vendorId: Int, productId: Int): Vendor? = when {+ vendorId == 0x0e8d -> Vendor.MEDIATEK+ UsbWifi.chipOf(vendorId, productId)?.driver == UsbWifi.Driver.MT7921U -> Vendor.MEDIATEK+ vendorId == 0x0bda -> Vendor.REALTEK+ vendorId == 0x8087 -> Vendor.INTEL+ else -> null+ }++ @Synchronized+ fun start(context: Context, sightings: (List<Report>) -> Unit) {+ val app = context.applicationContext+ appContext = app+ sink = sightings+ if (receiver == null) {+ val r = object : BroadcastReceiver() {+ override fun onReceive(c: Context, intent: Intent) {+ when (intent.action) {+ UsbManager.ACTION_USB_DEVICE_ATTACHED -> {+ connect(app, ask = false)+ main.postDelayed({ if (receiver != null) connect(app) }, UsbAttachActivity.ATTACH_GRACE_MS)+ }+ // A combo adapter's access is asked for by the WiFi side: its answer starts this side too.+ ACTION_PERMISSION, UsbWifi.ACTION_PERMISSION, UsbAttachActivity.ACTION_READY -> connect(app)+ UsbManager.ACTION_USB_DEVICE_DETACHED -> {+ val d = deviceOf(intent)+ if (d != null && d.deviceName == runningDevice) stopAdapter("")+ else if (d != null && firmwareNeeded != null && btInterface(d) != null) { firmwareNeeded = null; status = "" }+ }+ }+ }+ }+ val filter = IntentFilter().apply {+ addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)+ addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)+ addAction(ACTION_PERMISSION)+ addAction(UsbWifi.ACTION_PERMISSION)+ addAction(UsbAttachActivity.ACTION_READY)+ }+ ContextCompat.registerReceiver(app, r, filter, ContextCompat.RECEIVER_NOT_EXPORTED)+ receiver = r+ }+ connect(app)+ }++ @Synchronized+ fun stop(context: Context) {+ receiver?.let { runCatching { context.applicationContext.unregisterReceiver(it) } }+ receiver = null+ stopAdapter("")+ sink = null+ }++ /** Tries again (firmware just downloaded, or the setting turned back on). */+ fun retry(context: Context) { if (receiver != null) connect(context.applicationContext) }++ /** Settings › External hardware: the switch was flipped while scanning. */+ fun settingChanged(context: Context) {+ if (com.rfsentinel.app.util.Prefs.usbBluetooth(context)) retry(context)+ else { stopAdapter(""); firmwareNeeded = null }+ }++ private fun deviceOf(intent: Intent): UsbDevice? =+ if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)+ else @Suppress("DEPRECATION") intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)++ @Synchronized+ private fun connect(context: Context, ask: Boolean = true) {+ if (runningDevice != null) return+ if (!com.rfsentinel.app.util.Prefs.usbBluetooth(context)) { status = ""; return }+ val mgr = context.getSystemService(UsbManager::class.java) ?: return+ val 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 }+ 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 }+ 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)+ status = "USB Bluetooth found - allow USB access on the prompt"+ runCatching { mgr.requestPermission(d, pi) }+ return+ }+ runningDevice = d.deviceName+ val mine = java.util.concurrent.atomic.AtomicBoolean(false).also { halt = it }+ val previous = thread+ status = "USB Bluetooth · starting…"+ thread = Thread({+ try {+ // A quick stop and start: the last session lets go of the adapter first.+ previous?.join(3_000)+ if (previous?.isAlive == true) status = "USB Bluetooth: the last session is still stopping - unplug and replug the adapter"+ else run(context, mgr, d, mine)+ } catch (e: Exception) {+ UsbWifi.log("BT: stopped - ${UsbWifi.describe(e)}")+ if (!mine.get()) status = "USB Bluetooth: error · ${e.message}"+ }+ synchronized(this) { if (halt === mine) runningDevice = null }+ }, "usb-bt").also { it.start() }+ }++ @Synchronized+ private fun stopAdapter(newStatus: String) {+ halt.set(true)+ runningDevice = null+ status = newStatus+ com.rfsentinel.app.esp.HeardBy.usbBt.clear()+ }++ // ---- bring-up and scanning ----++ private fun run(ctx: Context, mgr: UsbManager, d: UsbDevice, halt: java.util.concurrent.atomic.AtomicBoolean) {+ val intf = btInterface(d) ?: return+ val evtIn = (0 until intf.endpointCount).map { intf.getEndpoint(it) }+ .first { it.type == UsbConstants.USB_ENDPOINT_XFER_INT && it.direction == UsbConstants.USB_DIR_IN }+ val conn = mgr.openDevice(d) ?: run { status = "USB Bluetooth: couldn't open the adapter"; return }+ var h: HciUsb? = null+ var vendor: Vendor? = null+ var ext = false+ try {+ val id = "%04x:%04x".format(d.vendorId, d.productId)+ UsbWifi.log("=== USB Bluetooth bring-up ($id, interface ${intf.id}) - RF Sentinel ${com.rfsentinel.app.BuildConfig.VERSION_NAME} ===")+ BulkRx.claim("BT", conn, intf) { halt.get() }+ val hci = HciUsb(conn, evtIn, "BT").also { h = it }+ hci.startReader() // btusb_open: the interrupt endpoint is read from here on+ vendor = vendorOf(d.vendorId, d.productId)+ var name = "USB Bluetooth"+ if (vendor == null) {+ // Not known from its USB ID: the controller's own manufacturer ID decides.+ val v = hci.cmd(0x1001)+ val maker = if (v.size >= 9) HciUsb.le16(v, 5) else -1+ vendor = when (maker) { MANUFACTURER_REALTEK -> Vendor.REALTEK; MANUFACTURER_MEDIATEK -> Vendor.MEDIATEK; else -> Vendor.GENERIC }+ if (vendor == Vendor.GENERIC) name = GENERIC_MAKERS[maker] ?: "generic"+ UsbWifi.log("BT: manufacturer 0x%04x (%s)".format(maker, vendor.name.lowercase()))+ }+ when (vendor) {+ Vendor.INTEL -> { status = "USB Bluetooth (Intel) isn't supported: it needs Intel's own firmware loader"; return }+ Vendor.MEDIATEK -> {+ val chip = BtMediatek.identify(hci)+ name = chip.name+ if (!firmwareReady(ctx, name, listOfNotNull(chip.firmware))) return+ status = "USB Bluetooth ($name) · loading firmware…"+ BtMediatek.setup(ctx, hci, chip, "BT $name")?.let { status = "USB Bluetooth: $it"; return }+ }+ Vendor.REALTEK -> {+ val found = BtRealtek.identify(hci, "BT RTL")+ name = found.name+ if (!firmwareReady(ctx, name, found.files)) return+ status = "USB Bluetooth ($name) · loading firmware…"+ BtRealtek.setup(ctx, hci, found, "BT $name")?.let { status = "USB Bluetooth: $it"; return }+ }+ Vendor.GENERIC -> {}+ }+ if (halt.get()) return+ status = "USB Bluetooth ($name) · starting scan…"+ ext = startScan(hci, name)+ status = "USB Bluetooth ($name) · live · " + if (ext) "LE 1M + Coded" else "LE"+ runningChip = name+ hci.onAdvertising = { e -> parse(e).takeIf { it.isNotEmpty() }?.let { reportCount.addAndGet(it.size.toLong()); sink?.invoke(it) } }+ var lastLog = System.currentTimeMillis()+ var lastCount = reportCount.get()+ while (!halt.get()) {+ Thread.sleep(500)+ if (hci.unplugged) throw IOException("the adapter stopped answering")+ val now = System.currentTimeMillis()+ if (now - lastLog >= 60_000) {+ val c = reportCount.get()+ UsbWifi.log("BT: ${c - lastCount} advertising reports in the last minute, ${hci.eventsIn} events in all")+ lastLog = now; lastCount = c+ }+ }+ } finally {+ runningChip = null+ h?.let { hci ->+ hci.onAdvertising = null+ if (!hci.unplugged && halt.get()) {+ // hci_dev_close: scanning off, then the vendor shutdown (MediaTek: Bluetooth function off).+ runCatching { if (ext) hci.cmd(0x2042, byteArrayOf(0, 0, 0, 0, 0, 0)) else hci.cmd(0x200C, byteArrayOf(0, 0)) }+ if (vendor == Vendor.MEDIATEK) BtMediatek.shutdown(hci)+ }+ hci.close()+ }+ runCatching { conn.releaseInterface(intf) }+ runCatching { conn.close() }+ }+ }++ /** False (and the firmware question raised) when a file isn't in this build or downloaded yet. */+ private fun firmwareReady(ctx: Context, chip: String, files: List<String>): Boolean {+ val missing = Firmware.missingFiles(ctx, files)+ if (missing.isEmpty()) { firmwareNeeded = null; return true }+ if (firmwareNeeded?.first != chip) {+ UsbWifi.log("BT: $chip needs firmware that isn't downloaded yet: ${missing.joinToString { it.name }}")+ FirmwarePrompt.notify(ctx, "$chip Bluetooth")+ }+ firmwareNeeded = chip to files+ status = "USB Bluetooth ($chip) needs its chip firmware: tap the notification, or this line in Settings, to download it"+ return false+ }++ /**+ * The HCI core's init, the part an LE scanner needs (hci_init1..4 of the Linux core), then a+ * passive scan with duplicates kept. True when it's an extended scan (1M, plus Coded when the controller has it).+ */+ private fun startScan(h: HciUsb, name: String): Boolean {+ h.cmdOk(0x0C03) // Reset+ val features = h.cmdOk(0x1003) // Read Local Supported Features+ if (features.size < 9 || features[1 + 4].toInt() and 0x40 == 0) throw IOException("$name has no Bluetooth LE")+ h.cmdOk(0x1001).let { v -> UsbWifi.log("BT: $name HCI version %d, revision %04x, LMP subversion %04x".format(v[1].toInt() and 0xff, HciUsb.le16(v, 2), HciUsb.le16(v, 7))) }+ // Event mask: hardware error (bit 15) and LE meta (bit 61); command complete / status always come.+ h.cmdOk(0x0C01, byteArrayOf(0, 0x80.toByte(), 0, 0, 0, 0, 0, 0x20))+ val le = h.cmdOk(0x2003) // LE Read Local Supported Features+ val extAdv = le.size >= 3 && le[1 + 1].toInt() and 0x10 != 0 // bit 12+ val coded = le.size >= 3 && le[1 + 1].toInt() and 0x08 != 0 // bit 11+ // LE event mask: advertising report (bit 1), extended advertising report (bit 12).+ h.cmdOk(0x2001, byteArrayOf(0x02, if (extAdv) 0x10 else 0, 0, 0, 0, 0, 0, 0))+ val interval = HciUsb.u16(0x0060); val window = HciUsb.u16(0x0030)+ return if (extAdv) {+ // Set Extended Scan Parameters: public own address, accept all, then per PHY: passive, interval, window.+ val phys = if (coded) 0x05 else 0x01+ val per = byteArrayOf(0) + interval + window+ h.cmdOk(0x2041, byteArrayOf(0, 0, phys.toByte()) + per + (if (coded) per else ByteArray(0)))+ h.cmdOk(0x2042, byteArrayOf(1, 0, 0, 0, 0, 0)) // enable, duplicates kept, no duration, no period+ UsbWifi.log("BT: $name extended passive scan on LE 1M" + if (coded) " + LE Coded" else "")+ true+ } else {+ // Legacy: passive, the same interval, the full window.+ h.cmdOk(0x200B, byteArrayOf(0) + interval + interval + byteArrayOf(0, 0))+ h.cmdOk(0x200C, byteArrayOf(1, 0))+ UsbWifi.log("BT: $name legacy passive scan")+ false+ }+ }++ private val partial = HashMap<String, ByteArray>()++ /** LE Advertising Report (0x02) and LE Extended Advertising Report (0x0D) events into reports. */+ internal fun parse(e: ByteArray): List<Report> {+ if (e.size < 4) return emptyList()+ val out = ArrayList<Report>()+ val sub = e[2].toInt() and 0xff+ var n = e[3].toInt() and 0xff+ var p = 4+ if (sub == 0x02) {+ while (n-- > 0 && p + 9 <= e.size) {+ val type = e[p].toInt() and 0xff+ val addrType = e[p + 1].toInt() and 0xff+ val addr = e.copyOfRange(p + 2, p + 8)+ val len = e[p + 8].toInt() and 0xff+ if (p + 9 + len + 1 > e.size) break+ val data = e.copyOfRange(p + 9, p + 9 + len)+ val rssi = e[p + 9 + len].toInt()+ p += 10 + len+ // ADV_IND and ADV_DIRECT_IND are connectable; scan responses don't come in a passive scan.+ out += Report(addr, addrType, rssi, data, type == 0x00 || type == 0x01, "LE 1M (legacy)")+ }+ } else if (sub == 0x0D) {+ while (n-- > 0 && p + 24 <= e.size) {+ val type = HciUsb.le16(e, p)+ val addrType = e[p + 2].toInt() and 0xff+ val addr = e.copyOfRange(p + 3, p + 9)+ val primary = e[p + 9].toInt() and 0xff+ val secondary = e[p + 10].toInt() and 0xff+ val rssi = e[p + 13].toInt()+ val len = e[p + 23].toInt() and 0xff+ if (p + 24 + len > e.size) break+ var data = e.copyOfRange(p + 24, p + 24 + len)+ p += 24 + len+ if (addrType == 0xff) continue // anonymous: no address to show+ // Data status (bits 5-6): 1 = more to come in the next report, 2 = truncated.+ val key = addr.joinToString("") { "%02x".format(it) } + addrType+ val status = (type shr 5) and 0x3+ partial.remove(key)?.let { data = it + data }+ if (status == 1) { if (data.size < 1650) partial[key] = data; continue }+ if (partial.size > 64) partial.clear()+ val legacy = type and 0x10 != 0+ val phy = when {+ primary == 3 -> "LE Coded (long range)"+ legacy -> "LE 1M (legacy)"+ secondary == 2 -> "LE 1M / 2M (extended)"+ else -> "LE 1M (extended)"+ }+ out += Report(addr, addrType, rssi, data, type and 0x01 != 0, phy)+ }+ }+ return out+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.ktindex dcb2cd8..86f30c7 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt@@ -48,7 +48,7 @@ data class MonitorSighting(object UsbWifi {private const val TAG = "UsbWifi"- private const val ACTION_PERMISSION = "com.rfsentinel.app.USB_WIFI_PERMISSION"+ internal const val ACTION_PERMISSION = "com.rfsentinel.app.USB_WIFI_PERMISSION"/** Driver families. */enum class Driver { RTL88XXAU, RTL8812AU, RTL88X2BU, RTL8187, RT3070, RTL8814AU, MT7612U, MT7921U, AR9271 }@@ -346,7 +346,7 @@ object UsbWifi {if (missing.isNotEmpty()) {if (firmwareNeeded != chip) {log("${chip.name} needs firmware that isn't downloaded yet: ${missing.joinToString { it.name }}")- FirmwarePrompt.notify(context, chip)+ FirmwarePrompt.notify(context, chip.name)}firmwareNeeded = chipstatus = "USB WiFi (${chip.name}) needs its chip firmware: tap the notification, or this line in Settings, to download it"@@ -358,8 +358,12 @@ object UsbWifi {status = "USB WiFi (${chip.name}) · starting…"log("Starting ${chip.name} (${"%04x:%04x".format(d.vendorId, d.productId)}) - RF Sentinel ${com.rfsentinel.app.BuildConfig.VERSION_NAME}, " +"${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}, Android ${android.os.Build.VERSION.RELEASE}")+ val previous = threadthread = Thread({runCatching {+ // A quick stop and start: each driver refuses to start while its last session is still stopping.+ previous?.join(3_000)+ if (previous?.isAlive == true) { status = "USB WiFi (${chip.name}): the last session is still stopping - unplug and replug the adapter"; return@runCatching }val onStatus: (String) -> Unit = { s -> status = s }val onFrames: (List<MonitorSighting>) -> Unit = { list -> onSightings?.invoke(list) }when (chip.driver) {@@ -395,7 +399,6 @@ object UsbWifi {Ar9271Monitor.abort()runningDevice = nullrunningChip = null- thread = nullstatus = newStatuscom.rfsentinel.app.esp.HeardBy.usb.clear() // unplugged or stopped: nothing is "heard by USB" any more}diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.ktindex 829959f..388c835 100644--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt@@ -1,5 +1,6 @@package com.rfsentinel.app.util+import com.rfsentinel.app.data.AlertKindimport android.content.Contextimport android.media.AudioAttributesimport android.media.AudioFocusRequest@@ -55,12 +56,13 @@ object AlertPlayer {private val main = Handler(Looper.getMainLooper())private var focusRequest: AudioFocusRequest? = null- fun play(context: Context, tier: Tier, spoken: String?, following: Boolean = false) {+ /** [off]: the ways this device's watchlist entry says not to alert ([AlertKind]). */+ fun play(context: Context, tier: Tier, spoken: String?, following: Boolean = false, off: Set<AlertKind> = emptySet()) {val inCar = CarState.connectedval muted = Prefs.alertsSilenced(context)- val willSpeak = !muted && spoken != null && (Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))+ val willSpeak = !muted && spoken != null && AlertKind.VOICE !in off && (Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))var beepMs = 0- if (!muted && Prefs.soundEnabled(context) && (inCar || ringerAllowsSound(context))) {+ if (!muted && AlertKind.SOUND !in off && Prefs.soundEnabled(context) && (inCar || ringerAllowsSound(context))) {// Speech holds its own audio focus for exactly as long as it talks; this covers the beeps.val detector = Prefs.detectorSound(context)duckOthers(context, if (detector) 4_500L else 2_500L)@@ -82,7 +84,7 @@ object AlertPlayer {} else Beeper.play(attrs, Beeper.pattern(beeps, following))alertSoundUntil = System.currentTimeMillis() + beepMs}- if (Prefs.vibrateEnabled(context)) {+ if (AlertKind.VIBRATE !in off && Prefs.vibrateEnabled(context)) {val pattern = when {following -> longArrayOf(0, 600, 150, 150, 150, 600)tier == Tier.STRONG -> longArrayOf(0, 220, 120, 220, 120, 220)diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.ktindex dc70883..6f164be 100644--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt@@ -85,6 +85,36 @@ object NotificationHelper {runCatching { nm.notify(DOWNLOAD_NOTIFICATION_ID, b.build()) } // no-op without the notification permission}+ private const val MESH_PAIR_NOTIFICATION_ID = 3++ /** The Meshtastic node isn't paired: tapping opens Sentinel Link, which asks Android to pair (its PIN dialog). */+ fun showMeshPairing(context: Context) {+ val nm = context.getSystemService(NotificationManager::class.java) ?: return+ val open = PendingIntent.getActivity(+ context, MESH_PAIR_NOTIFICATION_ID,+ Intent(context, com.rfsentinel.app.ui.SentinelLinkActivity::class.java)+ .putExtra(com.rfsentinel.app.ui.SentinelLinkActivity.EXTRA_PAIR, true)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ val text = "Tap to pair. Android then asks for the PIN: it's on the node's screen, or 123456."+ val n = NotificationCompat.Builder(context, CHANNEL_ALERTS)+ .setSmallIcon(R.drawable.ic_tile_scan)+ .setContentTitle("Pair your Meshtastic node")+ .setContentText(text)+ .setStyle(NotificationCompat.BigTextStyle().bigText(text))+ .setContentIntent(open)+ .setAutoCancel(true)+ .setOnlyAlertOnce(true)+ .setSilent(true)+ .build()+ runCatching { nm.notify(MESH_PAIR_NOTIFICATION_ID, n) } // no-op without the notification permission+ }++ fun cancelMeshPairing(context: Context) {+ context.getSystemService(NotificationManager::class.java)?.cancel(MESH_PAIR_NOTIFICATION_ID)+ }+/** Clears a progress notification left behind when the app was killed mid-download. */fun clearStaleCameraDownload(context: Context) {val nm = context.getSystemService(NotificationManager::class.java) ?: return@@ -150,9 +180,12 @@ object NotificationHelper {/** Where the thing is (a camera); else where you were. */lat: Double? = null, lon: Double? = null,/** An internet alert's key ("air:..." aircraft, "waze:..." report): tapping opens the map on it ([lat] / [lon] where it was). */- online: String? = null+ online: String? = null,+ /** False: only logged (its category's banner is turned off). */+ banner: Boolean = true) {- recordAlert(context, key, null, hit, null, false, lat, lon)+ recordAlert(context, key, null, hit, null, false, lat, lon, card = banner)+ if (!banner) returnval discreet = Prefs.discreetMode(context)com.rfsentinel.app.ui.ThreatBubble.popup(context, if (discreet) "New alert" else hit.label,if (discreet) null else hit.category.shortTag, hit.category.colorArgb)@@ -200,7 +233,7 @@ object NotificationHelper {*/private fun recordAlert(context: Context, key: String, mac: String?, hit: Hit, rssi: Int?, following: Boolean,- lat: Double?, lon: Double?+ lat: Double?, lon: Double?, card: Boolean = true) {runCatching {val tag = Prefs.gpsTaggingEnabled(context)@@ -211,7 +244,7 @@ object NotificationHelper {)}// The full screen map shows it as a card (nothing is stored there: it is gone when the card is).- runCatching {+ if (card) runCatching {com.rfsentinel.app.ui.AlertCards.publish(com.rfsentinel.app.ui.AlertCards.Card(key, mac, hit.label, hit.evidence, hit.category, hit.confidence, following, rssi, lat, lon, System.currentTimeMillis()))}@@ -251,10 +284,12 @@ object NotificationHelper {).joinToString(" · ")/** [via]: the linked Sentinel that heard it (Sentinel Link); [rssi] is then that phone's. */- fun sendAlert(context: Context, mac: String, hit: Hit, rssi: Int, following: Boolean = false, via: String? = null) {+ /** [banner] false: the alert is only logged (its watchlist entry turned the banner off). */+ fun sendAlert(context: Context, mac: String, hit: Hit, rssi: Int, following: Boolean = false, via: String? = null, banner: Boolean = true) {// A drone with a Remote ID position is logged where it is; anything else where you were.val rid = com.rfsentinel.app.service.DeviceRegistry.get(mac)?.remoteId?.takeIf { it.hasPosition }- recordAlert(context, mac, mac, hit, rssi, following, rid?.latitude, rid?.longitude)+ recordAlert(context, mac, mac, hit, rssi, following, rid?.latitude, rid?.longitude, card = banner)+ if (!banner) returnval discreet = Prefs.discreetMode(context)com.rfsentinel.app.ui.ThreatBubble.popup(context,if (discreet) "New alert" else if (following) "Following you: ${hit.label}" else hit.label,diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 3167e3a..47430e1 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -46,6 +46,15 @@ object Prefs {fun setCategoryEnabled(context: Context, category: Category, value: Boolean) =setBool(context, "cat_" + category.name, value)+ /** The ways a category doesn't alert you (Settings › What to detect): banner, sound, voice, vibration, radar beep. */+ fun categoryAlertsOff(context: Context, category: Category): Set<com.rfsentinel.app.data.AlertKind> =+ com.rfsentinel.app.data.AlertKind.parse(sp(context).getString("cat_alerts_off_" + category.name, null))++ fun setCategoryAlertsOff(context: Context, category: Category, off: Set<com.rfsentinel.app.data.AlertKind>) = sp(context).edit {+ val key = "cat_alerts_off_" + category.name+ com.rfsentinel.app.data.AlertKind.format(off)?.let { putString(key, it) } ?: remove(key)+ }+// ---- Alerts ---------------------------------------------------------------fun soundEnabled(context: Context): Boolean = bool(context, "sound_enabled", true)@@ -568,6 +577,9 @@ object Prefs {/** The USB adapter's own light (only adapters whose light the app can drive: RTL8811AU / 8821AU): on by default. */fun usbAdapterLight(context: Context): Boolean = bool(context, "usb_adapter_light", true)fun setUsbAdapterLight(context: Context, value: Boolean) = setBool(context, "usb_adapter_light", value)+ /** 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)fun setRtl8821au5g(context: Context, value: Boolean) = setBool(context, "rtl8821au_5g", value)/** Hide trusted (whitelisted) devices from the live list and radar (off by default). */@@ -648,6 +660,10 @@ object Prefs {/** The live map goes back to following you a few seconds after you stop touching it while you drive (as Google Maps does). */fun mapAutoRecenter(context: Context): Boolean = bool(context, "map_auto_recenter", true)fun setMapAutoRecenter(context: Context, value: Boolean) = setBool(context, "map_auto_recenter", value)+ /** How long after your last touch the map goes back to you, in seconds (one of [RECENTER_CHOICES]). */+ fun mapRecenterSec(context: Context): Int = int(context, "map_recenter_sec", 30).let { if (it in RECENTER_CHOICES) it else 30 }+ fun setMapRecenterSec(context: Context, sec: Int) = setInt(context, "map_recenter_sec", sec)+ val RECENTER_CHOICES = listOf(10, 30, 60, 120)/** The speedometer in the corner of the live map: your speed, and the posted limit while it is known. */fun mapSpeedometer(context: Context): Boolean = bool(context, "map_speedometer", true)diff --git a/app/src/main/res/layout/activity_antenna_check.xml b/app/src/main/res/layout/activity_antenna_check.xmlindex f2f7556..1cef471 100644--- a/app/src/main/res/layout/activity_antenna_check.xml+++ b/app/src/main/res/layout/activity_antenna_check.xml@@ -11,6 +11,33 @@android:layout_height="match_parent"android:orientation="vertical">+ <!-- Which adapter: shown when both a USB WiFi and a USB Bluetooth adapter are live. -->+ <com.google.android.material.button.MaterialButtonToggleGroup+ android:id="@+id/radioGroup"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginBottom="8dp"+ android:visibility="gone"+ app:singleSelection="true"+ app:selectionRequired="true">++ <com.google.android.material.button.MaterialButton+ android:id="@+id/radioWifi"+ style="?attr/materialButtonOutlinedStyle"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:text="USB WiFi" />++ <com.google.android.material.button.MaterialButton+ android:id="@+id/radioBt"+ style="?attr/materialButtonOutlinedStyle"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:text="USB Bluetooth" />+ </com.google.android.material.button.MaterialButtonToggleGroup>+<com.google.android.material.button.MaterialButtonToggleGroupandroid:id="@+id/modeGroup"android:layout_width="match_parent"@@ -229,6 +256,7 @@android:textSize="@dimen/text_body" /><TextView+ android:id="@+id/zeroHelp"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="16dp"@@ -245,6 +273,7 @@android:text="Swap test: capture with antenna A, swap to antenna B, capture again. Each capture averages the last 5 s; keep the phone still." /><TextView+ android:id="@+id/aboutText"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="8dp"diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex c0e4cc0..30801ae 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -698,6 +698,17 @@style="@style/SettingsLabel"android:paddingTop="6dp" />+ <TextView+ android:id="@+id/usbBtText"+ style="@style/SettingsLabel"+ android:paddingTop="6dp" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/usbBtSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Scan Bluetooth with a USB adapter" />+<Buttonandroid:id="@+id/usbWifiLogButton"style="@style/Widget.MaterialComponents.Button.TextButton"diff --git a/app/src/main/res/layout/item_device.xml b/app/src/main/res/layout/item_device.xmlindex d2b70fd..2348afd 100644--- a/app/src/main/res/layout/item_device.xml+++ b/app/src/main/res/layout/item_device.xml@@ -87,6 +87,18 @@android:textColor="?android:attr/textColorSecondary"android:textSize="@dimen/text_caption" /></LinearLayout>++ <!-- Flagged rows: mute this device's alerts (tap 30 min, hold until unmuted) -->+ <ImageButton+ android:id="@+id/muteButton"+ android:layout_width="48dp"+ android:layout_height="48dp"+ android:layout_marginStart="4dp"+ android:layout_marginEnd="-8dp"+ android:background="?attr/selectableItemBackgroundBorderless"+ android:contentDescription="Mute this device's alerts"+ android:src="@drawable/ic_car_volume_off"+ android:visibility="gone" /></LinearLayout><Viewdiff --git a/app/src/main/res/layout/item_oui_entry.xml b/app/src/main/res/layout/item_oui_entry.xmlindex fcbd5c0..2240395 100644--- a/app/src/main/res/layout/item_oui_entry.xml+++ b/app/src/main/res/layout/item_oui_entry.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"@@ -31,6 +32,25 @@android:layout_height="wrap_content"android:textSize="@dimen/text_caption"android:textColor="?android:attr/textColorSecondary" />++ <!-- Your entries: the ways it alerts you (each can be turned off) -->+ <TextView+ android:id="@+id/alertsLabel"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="6dp"+ android:text="Alerts you with"+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary"+ android:visibility="gone" />++ <com.google.android.material.chip.ChipGroup+ android:id="@+id/alertChips"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone"+ app:chipSpacingHorizontal="6dp"+ app:chipSpacingVertical="0dp" /></LinearLayout><Buttondiff --git a/app/src/main/res/xml/usb_device_filter.xml b/app/src/main/res/xml/usb_device_filter.xmlindex c74c324..cc7770a 100644--- a/app/src/main/res/xml/usb_device_filter.xml+++ b/app/src/main/res/xml/usb_device_filter.xml@@ -202,4 +202,6 @@<usb-device vendor-id="2364" product-id="8282" /><!-- Espressif native USB (ESP32-S2, S3, C3, C5, C6...): every product --><usb-device vendor-id="12346" />+ <!-- Any standard USB Bluetooth controller (class e0 / 01 / 01) -->+ <usb-device class="224" subclass="1" protocol="1" /></resources>diff --git a/app/src/test/java/com/rfsentinel/app/detect/IdentifyMoreTest.kt b/app/src/test/java/com/rfsentinel/app/detect/IdentifyMoreTest.ktindex dfcb388..8af2c84 100644--- a/app/src/test/java/com/rfsentinel/app/detect/IdentifyMoreTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/IdentifyMoreTest.kt@@ -246,8 +246,9 @@ class IdentifyMoreTest {assertEquals(listOf(DeviceFilter.ROUTERS), kinds("Home router (internet provider's) - Sagemcom"))assertEquals(listOf(DeviceFilter.HOTSPOTS), kinds("Open WiFi (public or guest)"))assertEquals(listOf(DeviceFilter.HOTSPOTS), kinds("Public WiFi hotspot (Passpoint)"))- assertEquals(emptyList<DeviceFilter>(), kinds("Business access point - Ruckus"))- assertEquals(emptyList<DeviceFilter>(), kinds("Business WiFi (account sign-in)"))+ assertEquals(listOf(DeviceFilter.ACCESS_POINTS), kinds("Business access point - Ruckus"))+ assertEquals(listOf(DeviceFilter.ACCESS_POINTS), kinds("Business WiFi (account sign-in)"))+ assertEquals(listOf(DeviceFilter.ACCESS_POINTS), kinds("Business access point - Aruba (hidden network)"))}@Testdiff --git a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.ktindex 8b1f0fd..ba8d758 100644--- a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt+++ b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt@@ -47,9 +47,10 @@ class OnlineSourcesTest {val base = PoliceAircraft.parseFeed(feed)[0]val orbit = PoliceAircraft.LoiterTracker()var circling = false- for (i in 0..12) { // a full turn every 4 minutes, 1 fix a minute, staying put- val p = base.copy(trackDeg = (i * 90.0) % 360, lat = 10.10 + 0.002 * (i % 2), lon = -20.10)- circling = orbit.update(p, i * 60_000L)+ for (i in 0..24) { // a full turn every 4 minutes, a fix every 30 s, about 1 km around one spot+ val a = Math.toRadians(i * 45.0)+ val p = base.copy(trackDeg = (i * 45.0 + 90) % 360, lat = 10.10 + 0.009 * kotlin.math.cos(a), lon = -20.10 + 0.009 * kotlin.math.sin(a))+ circling = orbit.update(p, i * 30_000L)}assertTrue(circling)val straight = PoliceAircraft.LoiterTracker()@@ -58,6 +59,24 @@ class OnlineSourcesTest {assertFalse(flagged)}+ @Test+ fun straightFlightWithAJumpyHeadingIsNotCircling() {+ val base = PoliceAircraft.parseFeed(feed)[0].copy(speedKt = 60.0)+ val t = PoliceAircraft.LoiterTracker()+ var flagged = false+ // Slow and straight, but the reported heading keeps stepping round (a bad heading source).+ for (i in 0..24) flagged = flagged || t.update(base.copy(trackDeg = (i * 100.0) % 360, lat = 10.10 + 0.0008 * i), i * 30_000L)+ assertFalse(flagged)+ // On the ground: taxiing turns don't count.+ val ground = PoliceAircraft.LoiterTracker()+ for (i in 0..24) {+ val a = Math.toRadians(i * 45.0)+ flagged = flagged || ground.update(base.copy(altitudeFt = 0, trackDeg = (i * 45.0 + 90) % 360,+ lat = 10.10 + 0.009 * kotlin.math.cos(a), lon = -20.10 + 0.009 * kotlin.math.sin(a)), i * 30_000L)+ }+ assertFalse(flagged)+ }+@Testfun wazeParsingAndScore() {val json = """{"data":{"alerts":[diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.ktindex 5a8e6cc..142deb7 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 != "Snooze length" })+ assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().count { it.contentDescription !in setOf("Snooze length", "Re-center after") })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/UsbBluetoothParseTest.kt b/app/src/test/java/com/rfsentinel/app/usb/UsbBluetoothParseTest.ktnew file mode 100644index 0000000..5e1daf3--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/UsbBluetoothParseTest.kt@@ -0,0 +1,79 @@+package com.rfsentinel.app.usb++import com.rfsentinel.app.service.AdvertFactory+import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.IOException++/** USB Bluetooth: advertising events, the Realtek epatch, and a report turned into an advert. */+class UsbBluetoothParseTest {++ private fun bytes(vararg b: Int) = ByteArray(b.size) { b[it].toByte() }++ // Name "RFS" and maker 0x1234 data 01 02.+ private val ad = bytes(4, 0x09, 'R'.code, 'F'.code, 'S'.code, 5, 0xFF, 0x34, 0x12, 0x01, 0x02)++ @Test+ fun legacyReport() {+ val e = bytes(0x3E, 0, 0x02, 1, 0x00, 0x00, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, ad.size) + ad + bytes(0xC4)+ val r = UsbBluetooth.parse(e).single()+ assertEquals("11:22:33:44:55:66", r.mac)+ assertEquals(-60, r.rssi)+ assertTrue(r.connectable)+ assertEquals("LE 1M (legacy)", r.phy)+ assertArrayEquals(ad, r.data)+ }++ @Test+ fun extendedCodedReport() {+ val e = bytes(0x3E, 0, 0x0D, 1,+ 0x00, 0x00, // event type: not connectable, data complete+ 0x01, // random address+ 0x06, 0x05, 0x04, 0x03, 0x02, 0xC1,+ 0x03, 0x00, 0xFF, 0x7F, 0xB0, // Coded primary, no secondary, SID, TX, RSSI -80+ 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, // interval, direct address+ ad.size) + ad+ val r = UsbBluetooth.parse(e).single()+ assertEquals("C1:02:03:04:05:06", r.mac)+ assertEquals(-80, r.rssi)+ assertFalse(r.connectable)+ assertEquals("LE Coded (long range)", r.phy)+ }++ @Test+ fun truncatedEventIsDropped() {+ val e = bytes(0x3E, 0, 0x02, 1, 0x00, 0x00, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 30, 1, 2)+ assertTrue(UsbBluetooth.parse(e).isEmpty())+ }++ @Test+ fun reportToAdvert() {+ val r = UsbBluetooth.Report(bytes(0x66, 0x55, 0x44, 0x33, 0x22, 0x11), 0, -60, ad, true, "LE 1M (legacy)")+ val a = AdvertFactory.fromHci(r, now = 1L)+ assertEquals("11:22:33:44:55:66", a.mac)+ assertEquals("RFS", a.name)+ assertArrayEquals(bytes(0x01, 0x02), a.manufacturerData[0x1234])+ }++ /** A one-patch v1 epatch for project 1 (RTL8723B), ROM version 1, with its 6-byte patch at offset 22. */+ private val epatch = "Realtech".toByteArray() ++ bytes(0x01, 0x02, 0x03, 0x04, 0x01, 0x00, // fw_version, one patch+ 0x02, 0x00, 0x06, 0x00, 22, 0, 0, 0, // chip id (ROM + 1), length, offset+ 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, // the patch+ 0x01, 0x01, 0x00, // project 1 (read backwards: opcode 0, length 1)+ 0x51, 0x04, 0xFD, 0x77)++ @Test+ fun realtekPatchGetsTheFileVersion() {+ assertArrayEquals(bytes(0xAA, 0xBB, 0x01, 0x02, 0x03, 0x04), BtRealtek.parse(epatch, 0x8723, 1))+ }++ @Test(expected = IOException::class)+ fun realtekWrongChipRefused() { BtRealtek.parse(epatch, 0x8821, 1) }++ @Test(expected = IOException::class)+ fun realtekNoPatchForRom() { BtRealtek.parse(epatch, 0x8723, 5) }+}diff --git a/docs/qa.html b/docs/qa.htmlindex 0a3aa66..f5303ff 100644--- a/docs/qa.html+++ b/docs/qa.html@@ -24,7 +24,7 @@<link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin><link rel="stylesheet" href="assets/style.css">-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it, or whitelist a WiFi network by its name (Menu > Whitelist > Network names) when it is on many vehicles, like a bus fleet's routers."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Why does the scan find 0 devices?", "acceptedAnswer": {"@type": "Answer", "text": "Location is probably off. Android gives apps no Bluetooth or WiFi scan results while the phone's Location is off, even with every permission granted. Turn it on in the quick settings; RF Sentinel's main screen says so and opens the setting when you tap the warning. Also check that it has location and \"Nearby devices\"."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not on Google Play. The signed APK is published on GitHub Releases for every version, and Obtainium can install it and keep it updated from there. An F-Droid listing has been submitted and is waiting for review. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). For a build with only free software, take the one ending in -foss.apk instead. Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any ARM phone with Bluetooth LE, 64-bit or 32-bit: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "The map closes the app (or the app closes when I open the map). What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "This happened on some older phones (seen on Android 9) whose graphics chip has no Vulkan: earlier builds drew the map with Vulkan only, so opening the map closed the app, and it did it again at every launch until the app's data was cleared. Version 2.20 picks Vulkan only where the phone has it and OpenGL everywhere else. If the app closes while the map starts for any other reason, it now tries the map again with OpenGL at the next launch, and after a second failure it takes the map off the main screen and tells you, so the rest of the app opens (add it back with the Map view button). On an earlier build, clearing the app's data (Android Settings → Apps → RF Sentinel → Storage) opens the app again, but the map will close it again. If it still happens, Settings → Lists, tools & about → Export crash log and send it: it helps to know the phone model and Android version."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute (snooze) and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to snooze alerts (30 minutes unless you change it under Alerts). Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "With the board on, open Settings → Pair OUI-SPY board : the app looks for the board's Bluetooth service for a few seconds (scanning needn't be running) and lists OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one). If no board is found: the board stops advertising while another app is connected to it, so force-stop the OUI-SPY app (Android App info → Force stop , not just swiping it away) and unplug the board for a few seconds. Use the App-Controlled (node) firmware, which shows up as OUI-SPY-xxxx , and check that Bluetooth is on and Nearby devices is allowed."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → External hardware → Export USB adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works on 2.4, 5 and 6 GHz (tested on an ALFA), with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Can two phones running RF Sentinel share what they detect?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with Sentinel Link . Linked phones show the same devices on their list, radar and map, whichever phone heard them first, including what any phone's ESP32 board, USB WiFi adapter or RTL-SDR picks up. A device another phone heard is marked VIA with that phone's name, its alerts say \"via NAME\", and the Sentinels filter chip shows only those. On both phones: Settings → Sentinel Link → Open Sentinel Link, and give each phone a name. Keep them close. Tap Link up a Sentinel on one and Join a Sentinel on the other; allow \"Nearby devices\" if asked. Both show a 6-digit code. Same code: tap Confirm on both. Different code: Cancel. Linked phones then share while they scan, whenever they are in Bluetooth range, and find each other again by themselves. A third phone joins the same way, from any phone of the group. The link is encrypted with a key agreed through the 6-digit code; the phones' Bluetooth adverts only carry a changing tag that means nothing without the group's key; nothing goes through the internet."}}, {"@type": "Question", "name": "Can Sentinels far apart share through Meshtastic?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, through Meshtastic LoRa nodes, one paired with each phone over Bluetooth. This part is not yet tested on real hardware : it follows Meshtastic's phone API and passes its tests, but hasn't been tried with a real node. Reports are welcome on Discord or GitHub. Hardware: a LoRa board with the official Meshtastic firmware, e.g. Heltec V3, LilyGO T-Beam, or a Seeed XIAO ESP32S3 with its Wio-SX1262 LoRa board (a plain ESP32 has no LoRa radio). Set its LoRa region once in the Meshtastic app. Set up: link the phones with Sentinel Link first, disconnect the Meshtastic app from the node, then in Sentinel Link → Meshtastic node turn on \"Use a Meshtastic node\" and pick it. If Android asks for a PIN, it's on the node's screen, or 123456. Start a scan: the status goes to \"Meshtastic node · connected\". Channel: RF Sentinel adds a private channel named RFSentinel to a free slot of the node, with a key made from the group's key, so only your group reads it. Packets are also encrypted and signed with the group's key. What goes out: LoRa is slow, so each packet carries the phone's position once and a few devices: watchlist matches first (within about 20 s, then every minute), then flagged devices, then everything else, one packet every minute by default (15 s to 5 min). Whitelisted devices are never sent."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off. Sentinel Link, when you set it up, sends encrypted messages to your own linked phones and Meshtastic node only.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, navigation (on the phone or in Android Auto), Photon and Nominatim for place search and Valhalla for routes. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol, unless you turn the online feeds off and use only an RTL-SDR's own ADS-B receiver) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it, or whitelist a WiFi network by its name (Menu > Whitelist > Network names) when it is on many vehicles, like a bus fleet's routers."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Why does the scan find 0 devices?", "acceptedAnswer": {"@type": "Answer", "text": "Location is probably off. Android gives apps no Bluetooth or WiFi scan results while the phone's Location is off, even with every permission granted. Turn it on in the quick settings; RF Sentinel's main screen says so and opens the setting when you tap the warning. Also check that it has location and \"Nearby devices\"."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not on Google Play. The signed APK is published on GitHub Releases for every version, and Obtainium can install it and keep it updated from there. An F-Droid listing has been submitted and is waiting for review. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). For a build with only free software, take the one ending in -foss.apk instead. Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any ARM phone with Bluetooth LE, 64-bit or 32-bit: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "The map closes the app (or the app closes when I open the map). What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "This happened on some older phones (seen on Android 9) whose graphics chip has no Vulkan: earlier builds drew the map with Vulkan only, so opening the map closed the app, and it did it again at every launch until the app's data was cleared. Version 2.20 picks Vulkan only where the phone has it and OpenGL everywhere else. If the app closes while the map starts for any other reason, it now tries the map again with OpenGL at the next launch, and after a second failure it takes the map off the main screen and tells you, so the rest of the app opens (add it back with the Map view button). On an earlier build, clearing the app's data (Android Settings → Apps → RF Sentinel → Storage) opens the app again, but the map will close it again. If it still happens, Settings → Lists, tools & about → Export crash log and send it: it helps to know the phone model and Android version."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute (snooze) and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to snooze alerts (30 minutes unless you change it under Alerts). Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "With the board on, open Settings → Pair OUI-SPY board : the app looks for the board's Bluetooth service for a few seconds (scanning needn't be running) and lists OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one). If no board is found: the board stops advertising while another app is connected to it, so force-stop the OUI-SPY app (Android App info → Force stop , not just swiping it away) and unplug the board for a few seconds. Use the App-Controlled (node) firmware, which shows up as OUI-SPY-xxxx , and check that Bluetooth is on and Nearby devices is allowed."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → External hardware → Export USB adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works on 2.4, 5 and 6 GHz (tested on an ALFA), with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet. Supported chips and the adapters that use them. The Bluetooth part of a combo adapter, or a plain USB Bluetooth dongle, works as a second Bluetooth LE scanner next to the phone's own, listening only (Settings → External hardware → Scan Bluetooth with a USB adapter). Chip WiFi in RF Sentinel Bluetooth Status Adapters with this chip Realtek RTL8811AU / RTL8821AU 2.4 GHz (5 GHz experimental, opt-in) 8821AU: Bluetooth 4.0 used (opt-out), not yet tested; 8811AU none Supported ALFA AWUS036ACS Realtek RTL8812AU 2.4 + 5 GHz None Experimental, not yet tested on a real adapter ALFA AWUS036ACH, TP-Link Archer T4U / T4UH, Netgear A6200v2, Linksys WUSB6300, Buffalo WI-U3-866D, Tenda U12, ASUS, D-Link, Edimax, TRENDnet, Belkin, ZyXEL, EnGenius, Planex, I-O DATA Realtek RTL8812BU / RTL8822BU 2.4 + 5 GHz 8822BU: Bluetooth used (opt-out), not yet tested; 8812BU none Supported, tested on a Wise Tiger 8812BU TP-Link Archer T3U / T4U v3, ASUS USB-AC53 / AC55 / AC58, Edimax EW-7822U*, Netgear A6150, Linksys WUSB6400M / WUSB3600 v2, Wise Tiger AC1200, D-Link, TRENDnet, Buffalo Realtek RTL8814AU 2.4 + 5 GHz None Supported, not yet tested on hardware ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000, Edimax, ELECOM, D-Link, TRENDnet MediaTek MT7612U / MT7632U 2.4 + 5 GHz Not used Supported, tested on an ALFA AWUS036ACM ALFA AWUS036ACM, ASUS USB-AC54 / AC55 / N53 B1, Netgear A6210 / WNDA3100v3, Aukey USB-AC1200, Xbox One wireless adapter, TP-Link, Edimax, ELECOM MediaTek MT7921AU (WiFi 6E) 2.4 + 5 + 6 GHz Bluetooth 5.2 used (opt-out, LE Coded long range), not yet tested Supported, tested on an ALFA AWUS036AXML / AXM ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH Realtek RTL8187L / RTL8187B 2.4 GHz None Supported, tested on an ALFA AWUS036H ALFA AWUS036H, Netgear WG111v2 / v3, ASUS, HP, Belkin Ralink RT3070 2.4 GHz None Supported, tested on an ALFA AWUS036NEH ALFA AWUS036NH / AWUS036NEH, Edimax Atheros AR9271 2.4 GHz None Experimental ALFA AWUS036NHA, TP-Link TL-WN722N v1, Netgear WNA1100, D-Link DWA-126 RTL8811CU / 8821CU / 8812CU, RT5370 / 5372, RT3071 / 3072, MT7610U, AR7010 Not yet Not used Detected and named, not supported yet Bluetooth chip In RF Sentinel Dongles with this chip Generic USB Bluetooth (any standard controller, class e0) Used, no firmware needed CSR8510 A10 dongles and clones (TP-Link UB400, Avantree DG40S, many no-name \"Bluetooth 4.0\" dongles), Broadcom / Cypress BCM20702 (ASUS USB-BT400, Plugable USB-BT4LE, Kinivo BTD-400, IOGEAR GBU521) Realtek RTL8761B / RTL8761C Used, Realtek firmware TP-Link UB500, ASUS USB-BT500, UGREEN CM390 / CM591, Maxuni and other \"Bluetooth 5.0 / 5.1 / 5.3\" dongles Realtek RTL8723BU / 8821CU combo Used, Realtek firmware Edimax EW-7611ULB, many WiFi + Bluetooth nano adapters Intel, RTL8822CU / 8852, Qualcomm with firmware Not yet Intel AX200 / AX210 USB kits, newer RTL8852-based dongles"}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Can two phones running RF Sentinel share what they detect?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with Sentinel Link . Linked phones show the same devices on their list, radar and map, whichever phone heard them first, including what any phone's ESP32 board, USB WiFi adapter or RTL-SDR picks up. A device another phone heard is marked VIA with that phone's name, its alerts say \"via NAME\", and the Sentinels filter chip shows only those. On both phones: Settings → Sentinel Link → Open Sentinel Link, and give each phone a name. Keep them close. Tap Link up a Sentinel on one and Join a Sentinel on the other; allow \"Nearby devices\" if asked. Both show a 6-digit code. Same code: tap Confirm on both. Different code: Cancel. Linked phones then share while they scan, whenever they are in Bluetooth range, and find each other again by themselves. A third phone joins the same way, from any phone of the group. The link is encrypted with a key agreed through the 6-digit code; the phones' Bluetooth adverts only carry a changing tag that means nothing without the group's key; nothing goes through the internet."}}, {"@type": "Question", "name": "Can Sentinels far apart share through Meshtastic?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, through Meshtastic LoRa nodes, one paired with each phone over Bluetooth. This part is not yet tested on real hardware : it follows Meshtastic's phone API and passes its tests, but hasn't been tried with a real node. Reports are welcome on Discord or GitHub. Hardware: a LoRa board with the official Meshtastic firmware, e.g. Heltec V3, LilyGO T-Beam, or a Seeed XIAO ESP32S3 with its Wio-SX1262 LoRa board (a plain ESP32 has no LoRa radio). Set its LoRa region once in the Meshtastic app. Set up: link the phones with Sentinel Link first, disconnect the Meshtastic app from the node, then in Sentinel Link → Meshtastic node turn on \"Use a Meshtastic node\" and pick it. If Android asks for a PIN, it's on the node's screen, or 123456. Start a scan: the status goes to \"Meshtastic node · connected\". Channel: RF Sentinel adds a private channel named RFSentinel to a free slot of the node, with a key made from the group's key, so only your group reads it. Packets are also encrypted and signed with the group's key. What goes out: LoRa is slow, so each packet carries the phone's position once and a few devices: watchlist matches first (within about 20 s, then every minute), then flagged devices, then everything else, one packet every minute by default (15 s to 5 min). Whitelisted devices are never sent."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off. Sentinel Link, when you set it up, sends encrypted messages to your own linked phones and Meshtastic node only.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to map services: the map (vector tiles, styles and fonts from OpenFreeMap, built on OpenStreetMap data, or from Mapbox if you choose it in Settings, with its usage statistics switched off), the roads of your area while the Waze option to alert only for reports on your road is on, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files and, navigation (on the phone or in Android Auto), Photon and Nominatim for place search and Valhalla for routes. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol, unless you turn the online feeds off and use only an RTL-SDR's own ADS-B receiver) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -677,6 +677,29 @@<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?</summary><div><p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → External hardware → Export USB adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works on 2.4, 5 and 6 GHz (tested on an ALFA), with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Supported chips and the adapters that use them. The Bluetooth part of a combo adapter, or a plain USB Bluetooth dongle, works as a second Bluetooth LE scanner next to the phone's own, listening only (Settings → External hardware → Scan Bluetooth with a USB adapter).</p>+<div class="table-wrap"><table>+<thead><tr><th>Chip</th><th>WiFi in RF Sentinel</th><th>Bluetooth</th><th>Status</th><th>Adapters with this chip</th></tr></thead>+<tbody>+<tr><td>Realtek RTL8811AU / RTL8821AU</td><td>2.4 GHz (5 GHz experimental, opt-in)</td><td>8821AU: Bluetooth 4.0 used (opt-out), not yet tested; 8811AU none</td><td>Supported</td><td>ALFA AWUS036ACS</td></tr>+<tr><td>Realtek RTL8812AU</td><td>2.4 + 5 GHz</td><td>None</td><td>Experimental, not yet tested on a real adapter</td><td>ALFA AWUS036ACH, TP-Link Archer T4U / T4UH, Netgear A6200v2, Linksys WUSB6300, Buffalo WI-U3-866D, Tenda U12, ASUS, D-Link, Edimax, TRENDnet, Belkin, ZyXEL, EnGenius, Planex, I-O DATA</td></tr>+<tr><td>Realtek RTL8812BU / RTL8822BU</td><td>2.4 + 5 GHz</td><td>8822BU: Bluetooth used (opt-out), not yet tested; 8812BU none</td><td>Supported, tested on a Wise Tiger 8812BU</td><td>TP-Link Archer T3U / T4U v3, ASUS USB-AC53 / AC55 / AC58, Edimax EW-7822U*, Netgear A6150, Linksys WUSB6400M / WUSB3600 v2, Wise Tiger AC1200, D-Link, TRENDnet, Buffalo</td></tr>+<tr><td>Realtek RTL8814AU</td><td>2.4 + 5 GHz</td><td>None</td><td>Supported, not yet tested on hardware</td><td>ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000, Edimax, ELECOM, D-Link, TRENDnet</td></tr>+<tr><td>MediaTek MT7612U / MT7632U</td><td>2.4 + 5 GHz</td><td>Not used</td><td>Supported, tested on an ALFA AWUS036ACM</td><td>ALFA AWUS036ACM, ASUS USB-AC54 / AC55 / N53 B1, Netgear A6210 / WNDA3100v3, Aukey USB-AC1200, Xbox One wireless adapter, TP-Link, Edimax, ELECOM</td></tr>+<tr><td>MediaTek MT7921AU (WiFi 6E)</td><td>2.4 + 5 + 6 GHz</td><td>Bluetooth 5.2 used (opt-out, LE Coded long range), not yet tested</td><td>Supported, tested on an ALFA AWUS036AXML / AXM</td><td>ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH</td></tr>+<tr><td>Realtek RTL8187L / RTL8187B</td><td>2.4 GHz</td><td>None</td><td>Supported, tested on an ALFA AWUS036H</td><td>ALFA AWUS036H, Netgear WG111v2 / v3, ASUS, HP, Belkin</td></tr>+<tr><td>Ralink RT3070</td><td>2.4 GHz</td><td>None</td><td>Supported, tested on an ALFA AWUS036NEH</td><td>ALFA AWUS036NH / AWUS036NEH, Edimax</td></tr>+<tr><td>Atheros AR9271</td><td>2.4 GHz</td><td>None</td><td>Experimental</td><td>ALFA AWUS036NHA, TP-Link TL-WN722N v1, Netgear WNA1100, D-Link DWA-126</td></tr>+<tr><td>RTL8811CU / 8821CU / 8812CU, RT5370 / 5372, RT3071 / 3072, MT7610U, AR7010</td><td>Not yet</td><td>Not used</td><td>Detected and named, not supported yet</td><td></td></tr>+</tbody></table></div>+<div class="table-wrap"><table>+<thead><tr><th>Bluetooth chip</th><th>In RF Sentinel</th><th>Dongles with this chip</th></tr></thead>+<tbody>+<tr><td>Generic USB Bluetooth (any standard controller, class e0)</td><td>Used, no firmware needed</td><td>CSR8510 A10 dongles and clones (TP-Link UB400, Avantree DG40S, many no-name "Bluetooth 4.0" dongles), Broadcom / Cypress BCM20702 (ASUS USB-BT400, Plugable USB-BT4LE, Kinivo BTD-400, IOGEAR GBU521)</td></tr>+<tr><td>Realtek RTL8761B / RTL8761C</td><td>Used, Realtek firmware</td><td>TP-Link UB500, ASUS USB-BT500, UGREEN CM390 / CM591, Maxuni and other "Bluetooth 5.0 / 5.1 / 5.3" dongles</td></tr>+<tr><td>Realtek RTL8723BU / 8821CU combo</td><td>Used, Realtek firmware</td><td>Edimax EW-7611ULB, many WiFi + Bluetooth nano adapters</td></tr>+<tr><td>Intel, RTL8822CU / 8852, Qualcomm with firmware</td><td>Not yet</td><td>Intel AX200 / AX210 USB kits, newer RTL8852-based dongles</td></tr>+</tbody></table></div></div></details>diff --git a/docs/sitemap.xml b/docs/sitemap.xmlindex 5ea7582..4374a08 100644--- a/docs/sitemap.xml+++ b/docs/sitemap.xml@@ -10,7 +10,7 @@<url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-26</lastmod><priority>1.0</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-28</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/police-detector.html</loc><lastmod>2026-10-18</lastmod><priority>0.8</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-22</lastmod><priority>0.9</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-28</lastmod><priority>0.9</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/smart-glasses-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/sophia-alternative.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-26</lastmod><priority>0.8</priority></url>diff --git a/fastlane/metadata/android/en-US/changelogs/63.txt b/fastlane/metadata/android/en-US/changelogs/63.txtnew file mode 100644index 0000000..d4d61a7--- /dev/null+++ b/fastlane/metadata/android/en-US/changelogs/63.txt@@ -0,0 +1,5 @@+• USB Bluetooth: the Bluetooth part of an MT7921AU, RTL8821AU or RTL8822BU combo adapter, or a USB Bluetooth dongle, scans as a second Bluetooth LE receiver, listening only.+• Choose per category how it alerts you: banner, sound, voice, vibration, radar beep (Settings › What to detect, under ▾).+• A device opened from history shows everything its page showed when last heard.+• Alert cards show only on the full-screen map.+• USB adapter restart fixes.diff --git a/site/pages/qa.html b/site/pages/qa.htmlindex 27b05c5..a8df789 100644--- a/site/pages/qa.html+++ b/site/pages/qa.html@@ -637,6 +637,29 @@<summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036AXML, AWUS036H or AWUS036NHA with Android?</summary><div><p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → External hardware → Export USB adapter log makes a text file to send. Since 2.19, the WiFi 6E MT7921AU (ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000, TP-Link TXE50UH) works on 2.4, 5 and 6 GHz (tested on an ALFA), with a driver ported from mt76-usb-macos (BSD-3-Clause-Clear). RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Supported chips and the adapters that use them. The Bluetooth part of a combo adapter, or a plain USB Bluetooth dongle, works as a second Bluetooth LE scanner next to the phone's own, listening only (Settings → External hardware → Scan Bluetooth with a USB adapter).</p>+<div class="table-wrap"><table>+<thead><tr><th>Chip</th><th>WiFi in RF Sentinel</th><th>Bluetooth</th><th>Status</th><th>Adapters with this chip</th></tr></thead>+<tbody>+<tr><td>Realtek RTL8811AU / RTL8821AU</td><td>2.4 GHz (5 GHz experimental, opt-in)</td><td>8821AU: Bluetooth 4.0 used (opt-out), not yet tested; 8811AU none</td><td>Supported</td><td>ALFA AWUS036ACS</td></tr>+<tr><td>Realtek RTL8812AU</td><td>2.4 + 5 GHz</td><td>None</td><td>Experimental, not yet tested on a real adapter</td><td>ALFA AWUS036ACH, TP-Link Archer T4U / T4UH, Netgear A6200v2, Linksys WUSB6300, Buffalo WI-U3-866D, Tenda U12, ASUS, D-Link, Edimax, TRENDnet, Belkin, ZyXEL, EnGenius, Planex, I-O DATA</td></tr>+<tr><td>Realtek RTL8812BU / RTL8822BU</td><td>2.4 + 5 GHz</td><td>8822BU: Bluetooth used (opt-out), not yet tested; 8812BU none</td><td>Supported, tested on a Wise Tiger 8812BU</td><td>TP-Link Archer T3U / T4U v3, ASUS USB-AC53 / AC55 / AC58, Edimax EW-7822U*, Netgear A6150, Linksys WUSB6400M / WUSB3600 v2, Wise Tiger AC1200, D-Link, TRENDnet, Buffalo</td></tr>+<tr><td>Realtek RTL8814AU</td><td>2.4 + 5 GHz</td><td>None</td><td>Supported, not yet tested on hardware</td><td>ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000, Edimax, ELECOM, D-Link, TRENDnet</td></tr>+<tr><td>MediaTek MT7612U / MT7632U</td><td>2.4 + 5 GHz</td><td>Not used</td><td>Supported, tested on an ALFA AWUS036ACM</td><td>ALFA AWUS036ACM, ASUS USB-AC54 / AC55 / N53 B1, Netgear A6210 / WNDA3100v3, Aukey USB-AC1200, Xbox One wireless adapter, TP-Link, Edimax, ELECOM</td></tr>+<tr><td>MediaTek MT7921AU (WiFi 6E)</td><td>2.4 + 5 + 6 GHz</td><td>Bluetooth 5.2 used (opt-out, LE Coded long range), not yet tested</td><td>Supported, tested on an ALFA AWUS036AXML / AXM</td><td>ALFA AWUS036AXML / AXM, Comfast CF-952AX, Netgear A8000 / A7500, TP-Link TXE50UH</td></tr>+<tr><td>Realtek RTL8187L / RTL8187B</td><td>2.4 GHz</td><td>None</td><td>Supported, tested on an ALFA AWUS036H</td><td>ALFA AWUS036H, Netgear WG111v2 / v3, ASUS, HP, Belkin</td></tr>+<tr><td>Ralink RT3070</td><td>2.4 GHz</td><td>None</td><td>Supported, tested on an ALFA AWUS036NEH</td><td>ALFA AWUS036NH / AWUS036NEH, Edimax</td></tr>+<tr><td>Atheros AR9271</td><td>2.4 GHz</td><td>None</td><td>Experimental</td><td>ALFA AWUS036NHA, TP-Link TL-WN722N v1, Netgear WNA1100, D-Link DWA-126</td></tr>+<tr><td>RTL8811CU / 8821CU / 8812CU, RT5370 / 5372, RT3071 / 3072, MT7610U, AR7010</td><td>Not yet</td><td>Not used</td><td>Detected and named, not supported yet</td><td></td></tr>+</tbody></table></div>+<div class="table-wrap"><table>+<thead><tr><th>Bluetooth chip</th><th>In RF Sentinel</th><th>Dongles with this chip</th></tr></thead>+<tbody>+<tr><td>Generic USB Bluetooth (any standard controller, class e0)</td><td>Used, no firmware needed</td><td>CSR8510 A10 dongles and clones (TP-Link UB400, Avantree DG40S, many no-name "Bluetooth 4.0" dongles), Broadcom / Cypress BCM20702 (ASUS USB-BT400, Plugable USB-BT4LE, Kinivo BTD-400, IOGEAR GBU521)</td></tr>+<tr><td>Realtek RTL8761B / RTL8761C</td><td>Used, Realtek firmware</td><td>TP-Link UB500, ASUS USB-BT500, UGREEN CM390 / CM591, Maxuni and other "Bluetooth 5.0 / 5.1 / 5.3" dongles</td></tr>+<tr><td>Realtek RTL8723BU / 8821CU combo</td><td>Used, Realtek firmware</td><td>Edimax EW-7611ULB, many WiFi + Bluetooth nano adapters</td></tr>+<tr><td>Intel, RTL8822CU / 8852, Qualcomm with firmware</td><td>Not yet</td><td>Intel AX200 / AX210 USB kits, newer RTL8852-based dongles</td></tr>+</tbody></table></div></div></details>