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
Scan watchdog, cell towers, WiFi channel and spectrum analyzers, anchored map points, police-vehicle vendors, screen-off BLE filters
CIS-C0c241343da8da
diff --git a/README.md b/README.mdindex 5c6007f..00c3c33 100644--- a/README.md+++ b/README.md@@ -125,7 +125,8 @@ Every match shows its evidence, its source and a confidence tier: **weak** (< 50- Notification, Quick Settings tile and home-screen widget**Map & history**-- OpenStreetMap map with your GPS trace and every device placed where its signal peaked, the same filter chips as the list, self-centering+- OpenStreetMap map with your GPS trace and every device pinned exactly where its signal peaked (tap a spot to list everything heard there), the same filter chips as the list, self-centering+- Optional **cell tower layer**: every tower seen while scanning, at the spot where its signal was strongest- **Record traces** of your route and the devices along it, with the screen off- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)@@ -139,6 +140,8 @@ Every match shows its evidence, its source and a confidence tier: **weak** (< 50**Interface**- Live list and radar view, filter chips with live counts (flagged, trackers, drones, new, ESP32, favorites, Bluetooth, WiFi), search+- **Tools** (menu ⋮): **Cell towers** (serving and neighbour cells with network, IDs, channel and signal, plus every tower seen while scanning), **WiFi channels** and **WiFi spectrum** analyzers for 2.4 / 5 / 6 GHz+- **Scan watchdog:** a scanner that goes silent is restarted on its own- Device details: evidence, identity, decoded data, signal graph, **Locate** mode, history, raw advertisement- Setup wizard (theme, region, alerts, camera radius, screen, permissions)- 13 themes, including the **DedSec** (Watch Dogs 2) and **fsociety** (Mr. Robot) fan themes@@ -219,8 +222,11 @@ the raw advertisement.- The **map** shows your position, the trace being recorded, and every deviceheard around you, placed where your phone was when its signal was strongest.- That's an approximation, not a fix. Devices heard from the same spot fan out- when you zoom in.+ That's an approximation, not a fix. Each dot stays pinned to its spot as you+ pan and zoom; tap a spot where several devices were heard to pick one from a list.+- **Cell towers** (map menu ⋮ → *Show cell towers*): towers seen while scanning,+ at the spot where your phone heard them strongest - an estimate, not the+ tower's real position (looking that up online would reveal where you are).- **Known cameras** (map menu ⋮): *Download nearby cameras* fetches plate readerswithin your radius (10-200 km, 100 by default); *Download Flock* fetches everyplate reader mapped in the US and Canada (~18 MB, refreshed weekly on WiFi).diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 931b9d2..835d273 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -68,6 +68,8 @@<activity android:name=".whitelist.WhitelistActivity" android:exported="false" /><activity android:name=".ouilist.OuiListActivity" android:exported="false" /><activity android:name=".ui.DetectionLogActivity" android:exported="false" />+ <activity android:name=".ui.CellTowersActivity" android:exported="false" />+ <activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" /><activityandroid:name=".ui.SetupActivity"android:exported="false" />diff --git a/app/src/main/assets/oui_presets/canada.json b/app/src/main/assets/oui_presets/canada.jsonindex e0ffe02..9cfb5b0 100644--- a/app/src/main/assets/oui_presets/canada.json+++ b/app/src/main/assets/oui_presets/canada.json@@ -214,5 +214,53 @@"confidence": "candidate","score": 35,"category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:A0:D5",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "28:A3:31",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "50:13:9D",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "64:CE:6E",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "84:DB:2F",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "CC:93:4A",+ "label": "Sierra Wireless AirLink vehicle gateway (police / EMS / fleet)",+ "source": "IEEE MA-L (Sierra Wireless, ULC); AirLink routers are sold by Canadian police-vehicle integrators and installed with carrier vehicle modems. Weak: also on buses, utility trucks and kiosks",+ "confidence": "candidate",+ "score": 40,+ "category": "PUBLIC_SAFETY"}]diff --git a/app/src/main/assets/oui_presets/global.json b/app/src/main/assets/oui_presets/global.jsonindex 3f46c47..2894d5f 100644--- a/app/src/main/assets/oui_presets/global.json+++ b/app/src/main/assets/oui_presets/global.json@@ -1686,5 +1686,285 @@"confidence": "candidate","score": 40,"category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:05:12",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:07:4D",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Corp.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:15:70",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:23:68",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:A0:F8",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "40:83:DE",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "48:8E:B7",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "60:95:32",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "74:93:A4",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Corp.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "78:B8:D6",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "84:24:8D",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "88:BC:AC",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "90:75:DE",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "94:FB:29",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "C4:7D:CC",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "C8:1C:FE",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "FC:59:7A",+ "label": "Zebra Technologies (mobile printers, incl. in-car e-ticket printers)",+ "source": "IEEE MA-L (Zebra Technologies Inc.); public police procurement records list Zebra mobile printers for electronic tickets in patrol cars. Weak: Zebra scanners, handhelds and label printers are everywhere in stores and warehouses",+ "confidence": "candidate",+ "score": 25,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:1B:A9",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:80:77",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "30:05:5C",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "3C:2A:F4",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother Industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "94:DD:F8",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother Industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "B0:7C:8E",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother Industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "B4:22:00",+ "label": "Brother Industries (RuggedJet / PocketJet in-car printers)",+ "source": "IEEE MA-L (Brother Industries, LTD.); Brother mobile printers are sold for in-car reports and tickets. Very weak: Brother home and office printers use the same blocks",+ "confidence": "candidate",+ "score": 20,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:11:6E",+ "label": "Peplink vehicle cellular router (police / EMS / fleet)",+ "source": "IEEE MA-L (Peplink International Ltd.); Peplink mobile routers are sold for public-safety vehicles. Weak: also on buses, boats and RVs",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "10:56:CA",+ "label": "Peplink vehicle cellular router (police / EMS / fleet)",+ "source": "IEEE MA-L (Peplink International Ltd.); Peplink mobile routers are sold for public-safety vehicles. Weak: also on buses, boats and RVs",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "6C:A3:D3",+ "label": "Peplink vehicle cellular router (police / EMS / fleet)",+ "source": "IEEE MA-L (Peplink International Ltd.); Peplink mobile routers are sold for public-safety vehicles. Weak: also on buses, boats and RVs",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "D4:13:F8",+ "label": "Peplink vehicle cellular router (police / EMS / fleet)",+ "source": "IEEE MA-L (Peplink International Ltd.); Peplink mobile routers are sold for public-safety vehicles. Weak: also on buses, boats and RVs",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:15:FF",+ "label": "Inseego (Novatel) vehicle radio / MiFi (reported in public-safety vehicles)",+ "source": "IEEE MA-L (Inseego Wireless, Inc); Inseego vehicle routers are sold for public-safety fleets. Weak: same blocks as consumer MiFi hotspots",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "18:EE:86",+ "label": "Inseego (Novatel) vehicle radio / MiFi (reported in public-safety vehicles)",+ "source": "IEEE MA-L (Inseego Wireless, Inc); Inseego vehicle routers are sold for public-safety fleets. Weak: same blocks as consumer MiFi hotspots",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "78:0C:71",+ "label": "Inseego (Novatel) vehicle radio / MiFi (reported in public-safety vehicles)",+ "source": "IEEE MA-L (Inseego Wireless, Inc); Inseego vehicle routers are sold for public-safety fleets. Weak: same blocks as consumer MiFi hotspots",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "E0:86:14",+ "label": "Inseego (Novatel) vehicle radio / MiFi (reported in public-safety vehicles)",+ "source": "IEEE MA-L (Inseego Wireless, Inc); Inseego vehicle routers are sold for public-safety fleets. Weak: same blocks as consumer MiFi hotspots",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "4C:36:4E",+ "label": "Panasonic Connect (Toughbook rugged laptops / tablets used in patrol cars)",+ "source": "IEEE MA-L (Panasonic Connect Co., Ltd.); Toughbooks are common in-car computers. Weak: the same company makes projectors, cameras and business gear, and a laptop is usually a WiFi client a phone can't see",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "B8:20:8E",+ "label": "Panasonic Connect (Toughbook rugged laptops / tablets used in patrol cars)",+ "source": "IEEE MA-L (Panasonic Connect Co., Ltd.); Toughbooks are common in-car computers. Weak: the same company makes projectors, cameras and business gear, and a laptop is usually a WiFi client a phone can't see",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "BC:3E:0B",+ "label": "Panasonic Connect (Toughbook rugged laptops / tablets used in patrol cars)",+ "source": "IEEE MA-L (Panasonic Connect Co., Ltd.); Toughbooks are common in-car computers. Weak: the same company makes projectors, cameras and business gear, and a laptop is usually a WiFi client a phone can't see",+ "confidence": "candidate",+ "score": 30,+ "category": "PUBLIC_SAFETY"}]diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 7e4add9..05ffdb1 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -237,6 +237,10 @@ class MainActivity : AppCompatActivity() {(com.rfsentinel.app.service.CellMonitor.lastAnomaly?.takeIf { System.currentTimeMillis() - it.first < 15 * 60_000L }?.let { " · ⚠ ${it.second.title}" } ?: "") ++ (ScanForegroundService.lastWatchdogRestart+ ?.takeIf { System.currentTimeMillis() - it.first < 10 * 60_000L }+ ?.let { " · ${it.second} scan restarted " ++ java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(it.first)) } ?: "") +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()}@@ -451,6 +455,12 @@ class MainActivity : AppCompatActivity() {R.id.action_traces -> { startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java)); true }R.id.action_history -> { startActivity(Intent(this, com.rfsentinel.app.ui.HistoryActivity::class.java)); true }R.id.action_about -> { AboutDialog.show(this); true }+ R.id.action_cell_towers -> { startActivity(Intent(this, com.rfsentinel.app.ui.CellTowersActivity::class.java)); true }+ R.id.action_wifi_channels -> { startActivity(Intent(this, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java)); true }+ R.id.action_wifi_spectrum -> {+ startActivity(Intent(this, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java)+ .putExtra(com.rfsentinel.app.ui.WifiAnalyzerActivity.EXTRA_SPECTRUM, true)); true+ }R.id.action_mute -> {val muted = !Prefs.alertsMuted(this)Prefs.setAlertsMuted(this, muted)diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.ktindex ef412dc..7bf01ce 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt@@ -53,6 +53,9 @@ object AlprStore {private val busy = java.util.concurrent.atomic.AtomicBoolean(false)@Volatile private var lastFailedArea: CameraArea? = null+ /** When the last automatic download failed (0 = the last one worked), for the map's status line. */+ @Volatile var lastAutoFailureAt = 0L+ private setval isBusy: Boolean get() = busy.get()private fun file(context: Context) = File(context.filesDir, FILE)@@ -85,12 +88,14 @@ object AlprStore {val (s, w, n, e) = CameraArea.expand(south, west, north, east, MAX_SPAN_DEG)return try {download(context, s, w, n, e)+ lastAutoFailureAt = 0Ltrue} catch (ex: kotlinx.coroutines.CancellationException) {throw ex // the screen closed: not a failure, try again next time} catch (ex: Exception) {android.util.Log.w("AlprStore", "Automatic camera download failed: ${ex.message}")lastFailedArea = CameraArea(s, w, n, e, System.currentTimeMillis())+ lastAutoFailureAt = System.currentTimeMillis()false} finally {busy.set(false)diff --git a/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt b/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.ktindex d24e984..6ca371a 100644--- a/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt@@ -37,7 +37,13 @@ class CellAnalyzer(private val knownAreas: MutableMap<String, Int> = LinkedHashM/** LAC (2G/3G) or TAC (4G/5G). */val area: Int?,val cellId: Long?,- val dbm: Int?+ val dbm: Int?,+ /** Radio channel: ARFCN (2G), UARFCN (3G), EARFCN (4G) or NR-ARFCN (5G). */+ val channel: Int? = null,+ /** Physical cell ID (4G/5G PCI, 3G PSC, 2G BSIC): what neighbour cells report instead of an ID. */+ val pci: Int? = null,+ /** Network name the cell broadcasts, when Android reports it. */+ val operator: String? = null) {val key get() = "${rat.name} ${mcc ?: "?"}-${mnc ?: "?"} ${area ?: "?"}/${cellId ?: "?"}"/** The cell's identity without its area: a cloned cell keeps this and changes the area. */diff --git a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.ktindex a5a71cc..23b7749 100644--- a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt@@ -38,11 +38,22 @@ object PatrolCluster {private const val MIN_CORRELATION = 0.6private const val MIN_SPREAD_DB = 2.0+ private const val ROLE_SCREENING = "impairment-screening device"+ private const val ROLE_INTERFACE = "vehicle interface module"+ /**+ * Roles from makers whose products are mostly civilian (remote starters, medical and+ * gas-detection gear): they add to a group but can't make one on their own, so an office or a+ * driveway full of them never reads as a police vehicle.+ */+ private val SUPPORT_ROLES = setOf(ROLE_SCREENING, ROLE_INTERFACE)+private val ROLE_BY_VENDOR = listOf(Regex("axon|taser", RegexOption.IGNORE_CASE) to "Axon / TASER gear",Regex("motorola solutions|harris corp|l3harris", RegexOption.IGNORE_CASE) to "two-way radio",- Regex("cradlepoint|sierra wireless", RegexOption.IGNORE_CASE) to "vehicle cellular router",+ Regex("cradlepoint|sierra wireless|peplink|inseego", RegexOption.IGNORE_CASE) to "vehicle cellular router",Regex("zebra|ruggedjet|pocketjet", RegexOption.IGNORE_CASE) to "mobile printer",+ Regex("dräger|draeger", RegexOption.IGNORE_CASE) to ROLE_SCREENING,+ Regex("fortin vehicle|fortin electronic", RegexOption.IGNORE_CASE) to ROLE_INTERFACE,Regex("cyberkar", RegexOption.IGNORE_CASE) to "in-car computer / console",Regex("getac", RegexOption.IGNORE_CASE) to "rugged laptop / body cam",Regex("genetec", RegexOption.IGNORE_CASE) to "plate reader",@@ -93,7 +104,7 @@ object PatrolCluster {}return live.indices.groupBy { find(it) }.values.map { idx -> Group(idx.map { live[it] }, idx.map { live[it].role }.toSet(), idx.any { it in correlatedPairs }) }- .filter { it.roles.size >= 2 }+ .filter { it.roles.size >= 2 && (it.roles - SUPPORT_ROLES).isNotEmpty() }}/** The cluster hit for [mac], if it belongs to a group. */diff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.ktindex 81415ba..88b6c9b 100644--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt@@ -34,6 +34,9 @@ object SignatureEngine {private const val CID_VUZIX = 0x060C // Vuzix Corporationprivate const val CID_META = 0x01AB // Meta Platforms, Inc.private const val CID_META_TECH = 0x058E // Meta Platforms Technologies (shared with Quest)+ private const val CID_ZEBRA = 0x01F1 // Zebra Technologies Corporation+ private const val CID_BROTHER = 0x0755 // Brother Industries, Ltd+ private const val CID_DRAEGER = 0x04BC // Draegerwerk AG & Co. KGaA// --- 16-bit service UUIDs ------------------------------------------------private val AXON_UUIDS = mapOf(0xFC81 to "Axon Enterprise", 0xFE6B to "TASER International", 0xFE6C to "TASER International")@@ -46,6 +49,8 @@ object SignatureEngine {private const val UUID_SPECTACLES = 0xFE45 // Snapchat Incprivate val META_UUIDS = setOf(0xFEB7, 0xFEB8) // Meta Platforms, Inc.private val ZEBRA_UUIDS = setOf(0xFE79, 0xFD66) // Zebra Technologies (FE79 = Link-OS printer BLE service)+ private val FORTIN_UUIDS = setOf(0xFDE1, 0xFDCA) // Fortin Electronic Systems (vehicle interface modules)+ private const val UUID_DRAEGER = 0xFCDA // Draeger/** HeyCyan smart-glasses SDK service; must match all 16 bytes (Apple ANCS differs by 2 bytes). */private val HEYCYAN = UUID.fromString("7905fff0-b5ce-4e99-a40f-4b1e122d00d0")@@ -151,6 +156,29 @@ object SignatureEngine {}}+ if (CID_ZEBRA in a.manufacturerData && ZEBRA_UUIDS.none { it in allShorts }) {+ hits += Hit(Category.PUBLIC_SAFETY, "Zebra device (mobile printer or handheld)", 25,+ "Zebra Technologies company ID 0x01F1 - mobile printers (incl. e-ticket printers) but also " ++ "store scanners and handhelds", SIG)+ }+ if (CID_BROTHER in a.manufacturerData) {+ hits += Hit(Category.PUBLIC_SAFETY, "Brother printer", 20,+ "Brother Industries company ID 0x0755 - RuggedJet / PocketJet in-car printers, but mostly " ++ "home and office printers", SIG)+ }++ // ---- Vehicle and impairment-testing gear ----------------------------+ if (FORTIN_UUIDS.any { it in allShorts }) {+ hits += Hit(Category.PUBLIC_SAFETY, "Fortin vehicle interface module", 20,+ "Fortin Electronic Systems service UUID 0xFDE1/0xFDCA - interface modules used when upfitting " ++ "police vehicles, but also remote starters in many ordinary cars", SIG)+ }+ if (CID_DRAEGER in a.manufacturerData || UUID_DRAEGER in allShorts) {+ hits += Hit(Category.PUBLIC_SAFETY, "Dräger device (breath / drug screening or medical)", 35,+ "Draegerwerk company ID 0x04BC or service UUID 0xFCDA - Dräger makes the roadside breath " ++ "(Alcotest) and drug (DrugTest) screening devices police use, and hospital and gas-detection gear", SIG)+ }+// ---- Flock Safety ALPR + Raven --------------------------------------val xuntong = CID_XUNTONG in a.manufacturerDatawhen {diff --git a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.ktindex 053feec..e8b471f 100644--- a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt+++ b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt@@ -124,12 +124,14 @@ class BleScanEngine(for (cid in intArrayOf(0x034D, 0x04EC, 0x09C8, 0x0D53, 0x03C2, 0x060C, 0x01AB)) {out += ScanFilter.Builder().setManufacturerData(cid, ByteArray(0)).build()}- // Apple Find My "separated from owner" frame: type 0x12, length 0x19.- out += ScanFilter.Builder()- .setManufacturerData(0x004C, byteArrayOf(0x12, 0x19), byteArrayOf(0xFF.toByte(), 0xFF.toByte()))- .build()- // Service data: Remote ID, Find Hub / Eddystone, SmartTag, Tile.- for (short in intArrayOf(0xFFFA, 0xFEAA, 0xFD5A, 0xFEED)) {+ // The makers behind most Bluetooth traffic, so ordinary devices (and trackers following+ // you) stay visible with the screen off, when Android suspends the unfiltered scan:+ // Apple (any frame, incl. Find My), Samsung, Google, Microsoft, Garmin, Bose, Sony, Xiaomi.+ for (cid in intArrayOf(0x004C, 0x0075, 0x00E0, 0x0006, 0x0087, 0x009E, 0x012D, 0x038F)) {+ out += ScanFilter.Builder().setManufacturerData(cid, ByteArray(0)).build()+ }+ // Service data: Remote ID, Find Hub / Eddystone, SmartTag, Tile, Google Fast Pair.+ for (short in intArrayOf(0xFFFA, 0xFEAA, 0xFD5A, 0xFEED, 0xFE2C)) {out += ScanFilter.Builder().setServiceData(ParcelUuid(Advert.uuid16(short)), ByteArray(0)).build()}// Advertised services: Axon/TASER, Flock Raven GPS, Motorola Solutions, Zebra printers,@@ -137,7 +139,7 @@ class BleScanEngine(for (short in intArrayOf(0xFC81, 0xFE6B, 0xFE6C, 0x3100, 0xFD8E, 0xFE04, 0xFE79, 0xFD66, 0xFE45, 0xFEB7, 0xFEB8)) {out += ScanFilter.Builder().setServiceUuid(ParcelUuid(Advert.uuid16(short))).build()}- // Controllers offload a limited number of filters; keep the total around 30.+ // Controllers offload a limited number of filters; keep the total around 40.watchedMacs.take(8).forEach { mac ->runCatching { out += ScanFilter.Builder().setDeviceAddress(mac).build() }}diff --git a/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt b/app/src/main/java/com/rfsentinel/app/service/CellMonitor.ktindex 240fea6..7152270 100644--- a/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt+++ b/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt@@ -43,6 +43,18 @@ class CellMonitor(private val context: Context) {while (fixes.size > 12) fixes.removeFirst()}+ @Synchronized+ private fun lastFix(): Location? = fixes.lastOrNull()++ /** The cells the phone sees right now, without any analysis (the cell towers screen). */+ suspend fun read(): List<CellAnalyzer.Cell> {+ val tm = tm ?: return emptyList()+ return fetch(tm)?.mapNotNull(::toCell).orEmpty()+ }++ /** Frees the reader thread of a monitor used only through [read]. */+ fun release() = executor.shutdown()+/** True / false when GPS knows whether you've been still for ~2 minutes; null otherwise. */@Synchronizedprivate fun stationary(now: Long): Boolean? {@@ -62,6 +74,7 @@ class CellMonitor(private val context: Context) {val cells = infos.mapNotNull(::toCell)if (cells.isEmpty()) return emptyList()val now = System.currentTimeMillis()+ CellTowerStore.record(context, cells, lastFix(), now)// A call (or one that just ended): networks without 4G calling drop to 2G/3G for it.// The audio mode tells without the phone-state permission.if (audio?.mode == android.media.AudioManager.MODE_IN_CALL) lastCallAt = now@@ -120,13 +133,16 @@ class CellMonitor(private val context: Context) {val reg = info.isRegisteredreturn when (info) {is CellInfoLte -> info.cellIdentity.let {- CellAnalyzer.Cell(CellAnalyzer.Rat.LTE, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.tac.orNull(), it.ci.orNull()?.toLong(), info.cellSignalStrength.dbm)+ CellAnalyzer.Cell(CellAnalyzer.Rat.LTE, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.tac.orNull(), it.ci.orNull()?.toLong(),+ info.cellSignalStrength.dbm, it.earfcn.orNull(), it.pci.orNull(), opName(it))}is CellInfoGsm -> info.cellIdentity.let {- CellAnalyzer.Cell(CellAnalyzer.Rat.GSM, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.lac.orNull(), it.cid.orNull()?.toLong(), info.cellSignalStrength.dbm)+ CellAnalyzer.Cell(CellAnalyzer.Rat.GSM, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.lac.orNull(), it.cid.orNull()?.toLong(),+ info.cellSignalStrength.dbm, it.arfcn.orNull(), it.bsic.orNull(), opName(it))}is CellInfoWcdma -> info.cellIdentity.let {- CellAnalyzer.Cell(CellAnalyzer.Rat.WCDMA, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.lac.orNull(), it.cid.orNull()?.toLong(), info.cellSignalStrength.dbm)+ CellAnalyzer.Cell(CellAnalyzer.Rat.WCDMA, reg, mcc(it.mccCompat()), mnc(it.mncCompat()), it.lac.orNull(), it.cid.orNull()?.toLong(),+ info.cellSignalStrength.dbm, it.uarfcn.orNull(), it.psc.orNull(), opName(it))}is CellInfoCdma -> CellAnalyzer.Cell(CellAnalyzer.Rat.CDMA, reg, null, null,info.cellIdentity.networkId.orNull(), info.cellIdentity.basestationId.orNull()?.toLong(), info.cellSignalStrength.dbm)@@ -138,14 +154,22 @@ class CellMonitor(private val context: Context) {private fun newer(info: CellInfo, reg: Boolean): CellAnalyzer.Cell? = when (info) {is CellInfoNr -> (info.cellIdentity as CellIdentityNr).let {CellAnalyzer.Cell(CellAnalyzer.Rat.NR, reg, it.mccString, it.mncString, it.tac.orNull(),- it.nci.takeIf { n -> n != CellInfo.UNAVAILABLE_LONG && n >= 0 }, info.cellSignalStrength.dbm)+ it.nci.takeIf { n -> n != CellInfo.UNAVAILABLE_LONG && n >= 0 }, info.cellSignalStrength.dbm,+ it.nrarfcn.orNull(), it.pci.orNull(), opName(it))}is CellInfoTdscdma -> info.cellIdentity.let {- CellAnalyzer.Cell(CellAnalyzer.Rat.TDSCDMA, reg, it.mccString, it.mncString, it.lac.orNull(), it.cid.orNull()?.toLong(), info.cellSignalStrength.dbm)+ CellAnalyzer.Cell(CellAnalyzer.Rat.TDSCDMA, reg, it.mccString, it.mncString, it.lac.orNull(), it.cid.orNull()?.toLong(),+ info.cellSignalStrength.dbm, it.uarfcn.orNull(), it.cpid.orNull(), opName(it))}else -> null}+ /** The network name the cell broadcasts (API 28+). */+ private fun opName(id: Any): String? =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) (id as? android.telephony.CellIdentity)+ ?.let { (it.operatorAlphaLong ?: it.operatorAlphaShort)?.toString()?.takeIf { s -> s.isNotBlank() } }+ else null+// Operator codes: the String getters are API 28+; older phones only have the int ones.private fun mcc(v: String?) = v?.takeIf { it.isNotBlank() }private fun mnc(v: String?) = v?.takeIf { it.isNotBlank() }@@ -171,6 +195,7 @@ class CellMonitor(private val context: Context) {fun close() {saveKnownAreas()+ CellTowerStore.save(context)executor.shutdown()}diff --git a/app/src/main/java/com/rfsentinel/app/service/CellTowerStore.kt b/app/src/main/java/com/rfsentinel/app/service/CellTowerStore.ktnew file mode 100644index 0000000..932a391--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/service/CellTowerStore.kt@@ -0,0 +1,123 @@+package com.rfsentinel.app.service++import android.content.Context+import android.location.Location+import com.google.gson.Gson+import com.google.gson.reflect.TypeToken+import com.rfsentinel.app.detect.CellAnalyzer+import java.io.File++/**+ * Every cell tower the phone has seen while scanning, kept on the phone only.+ * A tower's position is *estimated*: where your phone was when its signal was+ * strongest. Real tower positions would need an online database, which would+ * reveal where you are, so none is used.+ */+object CellTowerStore {++ data class Tower(+ val key: String,+ val rat: String,+ val mcc: String?,+ val mnc: String?,+ val area: Int?,+ val cellId: Long,+ var channel: Int?,+ var pci: Int?,+ var operator: String?,+ val firstSeen: Long,+ var lastSeen: Long,+ var timesSeen: Int,+ var servedYou: Boolean,+ var bestDbm: Int?,+ var bestLat: Double?,+ var bestLon: Double?+ ) {+ val ratLabel get() = runCatching { CellAnalyzer.Rat.valueOf(rat).label }.getOrDefault(rat)+ }++ private const val FILE = "cell_towers.json"+ private const val MAX_TOWERS = 3000+ private const val SAVE_EVERY = 20+ /** A fix older or coarser than this doesn't place a tower. */+ private const val MAX_FIX_AGE_MS = 60_000L+ private const val MAX_FIX_ACCURACY_M = 100f++ private val gson = Gson()+ private val listType = object : TypeToken<List<Tower>>() {}.type+ private val towers = LinkedHashMap<String, Tower>()+ private var loaded = false+ private var records = 0++ /** The cells of the latest snapshot (serving and neighbours), and when it was taken. */+ @Volatile var current: List<CellAnalyzer.Cell> = emptyList()+ private set+ @Volatile var currentAt = 0L+ private set++ @Synchronized+ fun all(context: Context): List<Tower> {+ ensureLoaded(context)+ return towers.values.map { it.copy() }+ }++ /** Adds one snapshot. Cells without an ID (most neighbours) are only shown live. */+ @Synchronized+ fun record(context: Context, cells: List<CellAnalyzer.Cell>, fix: Location?, now: Long = System.currentTimeMillis()) {+ current = cells+ currentAt = now+ ensureLoaded(context)+ val place = fix?.takeIf {+ now - it.time <= MAX_FIX_AGE_MS && (!it.hasAccuracy() || it.accuracy <= MAX_FIX_ACCURACY_M)+ }+ for (c in cells) {+ val id = c.cellId ?: continue+ val t = towers.getOrPut(c.key) {+ Tower(c.key, c.rat.name, c.mcc, c.mnc, c.area, id, c.channel, c.pci, c.operator,+ now, now, 0, false, null, null, null)+ }+ t.lastSeen = now+ t.timesSeen+++ if (c.registered) t.servedYou = true+ c.channel?.let { t.channel = it }+ c.pci?.let { t.pci = it }+ c.operator?.let { t.operator = it }+ val dbm = c.dbm?.takeIf { it in -150..-20 }+ if (dbm != null && (t.bestDbm == null || dbm > t.bestDbm!!)) {+ t.bestDbm = dbm+ if (place != null) { t.bestLat = place.latitude; t.bestLon = place.longitude }+ } else if (place != null && t.bestLat == null) {+ t.bestLat = place.latitude; t.bestLon = place.longitude+ }+ }+ if (towers.size > MAX_TOWERS) {+ towers.values.sortedBy { it.lastSeen }.take(towers.size - MAX_TOWERS).forEach { towers.remove(it.key) }+ }+ if (++records % SAVE_EVERY == 0) save(context)+ }++ @Synchronized+ fun save(context: Context) {+ if (!loaded) return+ runCatching { File(context.filesDir, FILE).writeText(gson.toJson(towers.values.toList())) }+ }++ /** Erased with "Forget device history": the list says where you have been. */+ @Synchronized+ fun forget(context: Context) {+ towers.clear()+ current = emptyList()+ loaded = true+ runCatching { File(context.filesDir, FILE).delete() }+ }++ private fun ensureLoaded(context: Context) {+ if (loaded) return+ loaded = true+ runCatching {+ File(context.filesDir, FILE).takeIf { it.exists() }?.readText()+ ?.let { gson.fromJson<List<Tower>>(it, listType) }+ ?.forEach { towers[it.key] = it }+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 98b5120..f31c193 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -71,6 +71,10 @@ class ScanForegroundService : Service() {/** Android downgrades an unfiltered BLE scan to opportunistic after ~30 min; restart before. */private const val BLE_RESTART_INTERVAL_MS = 25 * 60 * 1000L+ /** Watchdog: a scanner silent this long is restarted. */+ private const val BLE_SILENCE_MS = 2 * 60_000L+ private const val WIFI_SILENCE_MS = 3 * 60_000L+ private const val MAX_SILENCE_MS = 16 * 60_000L/** At most one logged row per device per this interval (BLE repeats many times a second). */private const val LOG_THROTTLE_MS = 30_000L@@ -117,6 +121,11 @@ class ScanForegroundService : Service() {@androidx.annotation.VisibleForTestingfun setLastFixForTest(l: Location?) { lastFix = l }+ /** Last watchdog restart (time, which scanner), for the status line. */+ @Volatile+ var lastWatchdogRestart: Pair<Long, String>? = null+ private set+/** True while an instance is alive in this process. Source of truth for the UI. */@Volatilevar isRunning = false@@ -193,8 +202,16 @@ class ScanForegroundService : Service() {pipelineThread = HandlerThread("rf-pipeline").apply { start() }pipeline = Handler(pipelineThread.looper)- bleEngine = BleScanEngine(this) { r -> pipeline.post { AdvertFactory.fromBle(r)?.let(::processPhone) } }+ bleEngine = BleScanEngine(this) { r ->+ val t = System.currentTimeMillis()+ lastBleResultAt = t+ bleWatchdogRestartAt?.let { onRecovered("Bluetooth", it, t); bleWatchdogRestartAt = null; bleSilenceMs = BLE_SILENCE_MS }+ pipeline.post { AdvertFactory.fromBle(r)?.let(::processPhone) }+ }wifiEngine = WifiScanEngine(this) { results ->+ val t = System.currentTimeMillis()+ lastWifiResultAt = t+ wifiWatchdogRestartAt?.let { onRecovered("WiFi", it, t); wifiWatchdogRestartAt = null; wifiSilenceMs = WIFI_SILENCE_MS }pipeline.post { results.forEach { r -> AdvertFactory.fromWifi(r)?.let(::processPhone) } }}@@ -298,6 +315,7 @@ class ScanForegroundService : Service() {// ---- Scanning -----------------------------------------------------------private fun startBle() {+ bleStartedAt = System.currentTimeMillis()val watched = OuiWatchlist.allEntries().filter { it.isCustom && it.prefix.length == 17 }.map { it.prefix }bleEngine.start(Prefs.bleScanMode(this), watched)bleRestartJob?.cancel()@@ -306,6 +324,7 @@ class ScanForegroundService : Service() {delay(BLE_RESTART_INTERVAL_MS)bleEngine.stop()delay(1_000)+ bleStartedAt = System.currentTimeMillis()bleEngine.start(Prefs.bleScanMode(this@ScanForegroundService), watched)}}@@ -317,6 +336,7 @@ class ScanForegroundService : Service() {}private fun startWifiPolling() {+ wifiStartedAt = System.currentTimeMillis()wifiEngine.start()wifiPollJob?.cancel()wifiPollJob = serviceScope.launch {@@ -669,10 +689,66 @@ class ScanForegroundService : Service() {}// Forget classification cache for devices that left.classified.keys.retainAll(devices.map { it.mac }.toSet())+ watchdog()}}}+ // ---- Watchdog ----------------------------------------------------------------++ @Volatile private var lastBleResultAt = 0L+ @Volatile private var lastWifiResultAt = 0L+ @Volatile private var bleStartedAt = 0L+ @Volatile private var wifiStartedAt = 0L+ /** Set when the watchdog restarted a scanner; cleared by its next result. */+ @Volatile private var bleWatchdogRestartAt: Long? = null+ @Volatile private var wifiWatchdogRestartAt: Long? = null+ /** Silence allowed before a restart; doubles after each restart that brought nothing back. */+ @Volatile private var bleSilenceMs = BLE_SILENCE_MS+ @Volatile private var wifiSilenceMs = WIFI_SILENCE_MS++ /** Results came back after a restart: the scanner really was stuck, so say so. */+ private fun onRecovered(which: String, restartAt: Long, now: Long) {+ if (now - restartAt <= 90_000L) {+ Log.i(TAG, "Watchdog: $which scan recovered after restart")+ lastWatchdogRestart = restartAt to which+ }+ }++ /**+ * A scanner that goes silent is restarted. Android (or a phone maker's battery+ * manager) can stop delivering results without reporting an error - the scan+ * looks alive but nothing arrives until it's restarted. Nearly every place has+ * some Bluetooth or WiFi around, so minutes of silence mean a stuck scanner.+ * Skipped with the screen off: Android pauses unfiltered BLE scans then by design.+ */+ private fun watchdog() {+ val now = System.currentTimeMillis()+ val interactive = (getSystemService(POWER_SERVICE) as PowerManager).isInteractive+ val adapterOn = runCatching {+ (getSystemService(BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager).adapter?.isEnabled == true+ }.getOrDefault(false)+ if (interactive && adapterOn && Prefs.bleEnabled(this) &&+ now - maxOf(lastBleResultAt, bleStartedAt) > bleSilenceMs+ ) {+ Log.w(TAG, "Watchdog: no Bluetooth results for ${(now - maxOf(lastBleResultAt, bleStartedAt)) / 1000} s - restarting the scan")+ // A quiet area isn't a stuck scanner: back off while restarts bring nothing.+ if (bleWatchdogRestartAt != null) bleSilenceMs = (bleSilenceMs * 2).coerceAtMost(MAX_SILENCE_MS)+ bleWatchdogRestartAt = now+ android.os.Handler(Looper.getMainLooper()).post { bleEngine.stop(); startBle() }+ }+ val wifiOn = runCatching { (applicationContext.getSystemService(WIFI_SERVICE) as android.net.wifi.WifiManager).isScanAlwaysAvailable ||+ (applicationContext.getSystemService(WIFI_SERVICE) as android.net.wifi.WifiManager).isWifiEnabled }.getOrDefault(false)+ if (wifiOn && Prefs.wifiEnabled(this) &&+ now - maxOf(lastWifiResultAt, wifiStartedAt) > maxOf(wifiSilenceMs, 4 * Prefs.scanIntervalMs(this))+ ) {+ Log.w(TAG, "Watchdog: no WiFi results - restarting the WiFi scan")+ if (wifiWatchdogRestartAt != null) wifiSilenceMs = (wifiSilenceMs * 2).coerceAtMost(MAX_SILENCE_MS)+ wifiWatchdogRestartAt = now+ android.os.Handler(Looper.getMainLooper()).post { wifiEngine.stop(); startWifiPolling() }+ }+ }+/*** Fake-cell-tower check every 15 s: reads the cells the phone already sees* (passive, no extra permission beyond location). Probable signs alert like adiff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex ace639b..7ff632b 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -466,6 +466,7 @@ class SettingsActivity : AppCompatActivity() {lifecycleScope.launch {AppDatabase.getInstance(this@SettingsActivity).knownDeviceDao().clearNonFavorites()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/CellTowersActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.ktnew file mode 100644index 0000000..1c6d18c--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt@@ -0,0 +1,200 @@+package com.rfsentinel.app.ui++import android.content.Intent+import android.graphics.Typeface+import android.os.Bundle+import android.view.LayoutInflater+import android.view.View+import android.view.ViewGroup+import android.widget.TextView+import androidx.appcompat.app.AlertDialog+import androidx.appcompat.app.AppCompatActivity+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.lifecycleScope+import androidx.lifecycle.repeatOnLifecycle+import androidx.recyclerview.widget.LinearLayoutManager+import androidx.recyclerview.widget.RecyclerView+import com.rfsentinel.app.databinding.ActivityLogBinding+import com.rfsentinel.app.databinding.ItemDetectionBinding+import com.rfsentinel.app.detect.CellAnalyzer+import com.rfsentinel.app.service.CellMonitor+import com.rfsentinel.app.service.CellTowerStore+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.util.Permissions+import com.rfsentinel.app.util.applySystemBarInsets+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import java.text.DateFormat+import java.util.Date++/**+ * The cell towers around you (serving cell and neighbours, live) and every tower+ * seen while scanning, with radio type, network, IDs, channel and signal.+ * Read passively from what the modem already reports; nothing is transmitted.+ */+class CellTowersActivity : AppCompatActivity() {++ private lateinit var binding: ActivityLogBinding+ private val fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)+ private var reader: CellMonitor? = null++ private sealed interface Row {+ data class Header(val text: String) : Row+ data class Live(val cell: CellAnalyzer.Cell) : Row+ data class Seen(val tower: CellTowerStore.Tower) : Row+ }++ private var rows: List<Row> = emptyList()++ private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {+ override fun getItemCount() = rows.size+ override fun getItemViewType(position: Int) = if (rows[position] is Row.Header) 0 else 1++ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {+ val v = if (viewType == 0) TextView(parent.context).apply {+ setTypeface(typeface, Typeface.BOLD)+ textSize = 15f+ setPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())+ } else ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root+ return object : RecyclerView.ViewHolder(v) {}+ }++ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {+ when (val r = rows[position]) {+ is Row.Header -> (holder.itemView as TextView).text = r.text+ is Row.Live -> bindLive(ItemDetectionBinding.bind(holder.itemView), r.cell)+ is Row.Seen -> bindSeen(ItemDetectionBinding.bind(holder.itemView), r.tower)+ }+ }+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ binding = ActivityLogBinding.inflate(layoutInflater)+ setContentView(binding.root)+ binding.root.applySystemBarInsets()+ title = "Cell towers"+ supportActionBar?.setDisplayHomeAsUpEnabled(true)+ binding.recyclerView.layoutManager = LinearLayoutManager(this)+ binding.recyclerView.adapter = adapter++ lifecycleScope.launch {+ repeatOnLifecycle(Lifecycle.State.STARTED) {+ while (true) {+ refresh()+ delay(REFRESH_MS)+ }+ }+ }+ }++ override fun onDestroy() {+ reader?.release()+ super.onDestroy()+ }++ override fun onSupportNavigateUp(): Boolean { finish(); return true }++ private suspend fun refresh() {+ if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {+ show(emptyList(), "Cell information needs the location permission.\nStart a scan once to grant it.")+ return+ }+ // While scanning, the scanner's own snapshot (every 15 s); otherwise read here.+ val fresh = System.currentTimeMillis() - CellTowerStore.currentAt < 30_000L+ val live = if (ScanForegroundService.isRunning && fresh) CellTowerStore.current+ else (reader ?: CellMonitor(this).also { reader = it }).read()+ val seen = CellTowerStore.all(this).sortedByDescending { it.lastSeen }++ val out = ArrayList<Row>()+ out += Row.Header("Now · ${live.size} ${if (live.size == 1) "cell" else "cells"}")+ live.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })+ .forEach { out += Row.Live(it) }+ out += Row.Header("Seen while scanning · ${seen.size}")+ seen.forEach { out += Row.Seen(it) }+ val empty = if (live.isEmpty() && seen.isEmpty())+ "No cell information.\nIs the SIM active and airplane mode off? While scanning, towers are recorded " ++ "when the Fake cell tower category is on (Settings)."+ else null+ show(out, empty)+ }++ @android.annotation.SuppressLint("NotifyDataSetChanged") // a few dozen rows, rebuilt every 5 s+ private fun show(list: List<Row>, emptyText: String?) {+ rows = list+ adapter.notifyDataSetChanged()+ binding.emptyText.text = emptyText.orEmpty()+ binding.emptyText.visibility = if (emptyText != null) View.VISIBLE else View.GONE+ }++ private fun network(mcc: String?, mnc: String?, operator: String?) =+ listOfNotNull(operator, if (mcc != null || mnc != null) "${mcc ?: "?"}-${mnc ?: "?"}" else null).joinToString(" · ")++ private fun ids(rat: CellAnalyzer.Rat?, area: Int?, cellId: Long?, pci: Int?, channel: Int?): String {+ val areaName = if (rat == CellAnalyzer.Rat.LTE || rat == CellAnalyzer.Rat.NR) "TAC" else "LAC"+ val chName = when (rat) {+ CellAnalyzer.Rat.LTE -> "EARFCN"; CellAnalyzer.Rat.NR -> "NR-ARFCN"+ CellAnalyzer.Rat.WCDMA, CellAnalyzer.Rat.TDSCDMA -> "UARFCN"; else -> "ARFCN"+ }+ val pciName = when (rat) {+ CellAnalyzer.Rat.GSM -> "BSIC"; CellAnalyzer.Rat.WCDMA -> "PSC"; CellAnalyzer.Rat.TDSCDMA -> "CPID"; else -> "PCI"+ }+ return listOfNotNull(+ area?.let { "$areaName $it" }, cellId?.let { "Cell $it" },+ pci?.let { "$pciName $it" }, channel?.let { "$chName $it" }+ ).joinToString(" · ").ifEmpty { "No IDs reported" }+ }++ private fun bindLive(b: ItemDetectionBinding, c: CellAnalyzer.Cell) {+ b.labelText.text = c.rat.label + (if (c.registered) " · serving" else " · neighbour")+ b.labelText.setTextColor(if (c.registered) ThemeManager.ink(this, 0xFF0B7A3E.toInt()) else b.macText.currentTextColor)+ b.macText.text = ids(c.rat, c.area, c.cellId, c.pci, c.channel)+ b.metaText.text = listOfNotNull(network(c.mcc, c.mnc, c.operator).ifEmpty { null }, c.dbm?.let { "$it dBm" })+ .joinToString(" · ")+ b.root.setOnClickListener(null)+ }++ private fun bindSeen(b: ItemDetectionBinding, t: CellTowerStore.Tower) {+ val rat = runCatching { CellAnalyzer.Rat.valueOf(t.rat) }.getOrNull()+ b.labelText.text = t.ratLabel + (if (t.servedYou) " · served you" else "")+ b.labelText.setTextColor(b.macText.currentTextColor)+ b.macText.text = ids(rat, t.area, t.cellId, t.pci, t.channel)+ b.metaText.text = listOfNotNull(+ network(t.mcc, t.mnc, t.operator).ifEmpty { null },+ t.bestDbm?.let { "best $it dBm" },+ "seen ${t.timesSeen}×, last ${fmt.format(Date(t.lastSeen))}",+ if (t.bestLat != null) "on map" else null+ ).joinToString(" · ")+ b.root.setOnClickListener { details(t) }+ }++ private fun details(t: CellTowerStore.Tower) {+ val rat = runCatching { CellAnalyzer.Rat.valueOf(t.rat) }.getOrNull()+ val text = buildString {+ append(network(t.mcc, t.mnc, t.operator).ifEmpty { "Unknown network" }).append('\n')+ append(ids(rat, t.area, t.cellId, t.pci, t.channel)).append("\n\n")+ append("First seen ${fmt.format(Date(t.firstSeen))}\nLast seen ${fmt.format(Date(t.lastSeen))}\n")+ append("Seen ${t.timesSeen} times").append(if (t.servedYou) ", served your phone" else ", as a neighbour only").append('\n')+ t.bestDbm?.let { append("Strongest signal: $it dBm\n") }+ append("\nThe map position is where your phone was when this tower's signal was strongest - ")+ append("an estimate, usually within a few hundred metres to a few km of the real tower.")+ }+ AlertDialog.Builder(this)+ .setTitle(t.ratLabel)+ .setMessage(text)+ .apply {+ if (t.bestLat != null) setPositiveButton("Show on map") { _, _ ->+ startActivity(Intent(this@CellTowersActivity, MapActivity::class.java)+ .putExtra(MapActivity.EXTRA_CENTER_LAT, t.bestLat!!)+ .putExtra(MapActivity.EXTRA_CENTER_LON, t.bestLon!!)+ .putExtra(MapActivity.EXTRA_SHOW_TOWERS, true))+ }+ }+ .setNegativeButton("Close", null)+ .show()+ }++ companion object {+ private const val REFRESH_MS = 5_000L+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex 65f97a7..02affa2 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -61,6 +61,13 @@ class MapActivity : AppCompatActivity() {companion object {const val EXTRA_TRIP_ID = "trip_id"+ /** Open the map centred here (e.g. a cell tower), without following your position. */+ const val EXTRA_CENTER_LAT = "center_lat"+ const val EXTRA_CENTER_LON = "center_lon"+ /** Turn the cell tower layer on. */+ const val EXTRA_SHOW_TOWERS = "show_towers"+ /** A failed camera download stays in the status line this long (the retry runs after a minute). */+ private const val CAMERA_FAIL_SHOWN_MS = 90_000Lprivate const val TRACE_COLOR = 0xFFE0622D.toInt()private const val PAST_TRACE_COLOR = 0xFF1F5FBF.toInt()private const val DRONE_COLOR = 0xFF1F5FBF.toInt()@@ -83,12 +90,19 @@ class MapActivity : AppCompatActivity() {private var following = falseprivate val trace = Polyline()- private val pins = FolderOverlay()+ private val pins by lazy { PointsOverlay<Pin>(resources.displayMetrics.density) { showPins(it) } }/** Live drones from Remote ID: aircraft, operator and the line between them. */private val drones = FolderOverlay()/** Plate-reader cameras mapped in OpenStreetMap (downloaded on request). */- private val knownAlpr = FolderOverlay()+ private val knownAlpr by lazy {+ PointsOverlay<com.rfsentinel.app.alpr.KnownCamera>(resources.displayMetrics.density) { showKnownCamera(it.first()) }+ }private var knownAlprDrawnFor: BoundingBox? = null+ /** Cell towers seen while scanning, at their estimated (strongest-signal) spot. */+ private val towers by lazy {+ PointsOverlay<com.rfsentinel.app.service.CellTowerStore.Tower>(resources.displayMetrics.density) { showTower(it.first()) }+ }+ private val towerIcon by lazy { MapIcons.towerIcon(resources.displayMetrics.density) }private lateinit var myLocation: MyLocationNewOverlayprivate val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)@@ -111,6 +125,7 @@ class MapActivity : AppCompatActivity() {insets}+ if (intent.getBooleanExtra(EXTRA_SHOW_TOWERS, false)) com.rfsentinel.app.util.Prefs.setShowCellTowers(this, true)setupMap()binding.map.post { drawKnownAlpr() }// Every device heard around you by default (same colours as the list and radar).@@ -157,6 +172,7 @@ class MapActivity : AppCompatActivity() {strokeWidth = 7f * resources.displayMetrics.density / 2}map.overlays.add(knownAlpr)+ map.overlays.add(towers)map.overlays.add(trace)map.overlays.add(pins)map.overlays.add(drones)@@ -169,16 +185,18 @@ class MapActivity : AppCompatActivity() {}override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also {drawKnownAlprSoon()- // The fan-out of stacked dots depends on the zoom.- map.removeCallbacks(respreadPins)- map.postDelayed(respreadPins, 150)}})myLocation = MyLocationNewOverlay(GpsMyLocationProvider(this), map)if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {myLocation.enableMyLocation()- if (tripId == null) {+ if (intent.hasExtra(EXTRA_CENTER_LAT)) {+ // Opened on a place (a cell tower): look there instead of following you.+ map.controller.setZoom(15.0)+ map.controller.setCenter(GeoPoint(intent.getDoubleExtra(EXTRA_CENTER_LAT, 0.0), intent.getDoubleExtra(EXTRA_CENTER_LON, 0.0)))+ centeredOnce = true+ } else if (tripId == null) {// Live map: keep your position centred from the first fix until you pan away.setFollow(true)myLocation.runOnFirstFix {@@ -201,6 +219,7 @@ class MapActivity : AppCompatActivity() {}// Precise GPS while the map is on screen, so devices land where they were heard.if (tripId == null) ScanForegroundService.mapShown(this)+ drawTowers()}override fun onPause() {@@ -321,6 +340,8 @@ class MapActivity : AppCompatActivity() {val positioned = devices.count { it.bestPosition != null }binding.statusText.text = when {bulkStatus() != null -> bulkStatus() // a camera download's progress wins+ System.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"!ScanForegroundService.isRunning -> "Not scanning - start scanning, then Record trace to save your route"recording -> {val mins = (System.currentTimeMillis() - TripRecorder.startedAt) / 60000@@ -436,44 +457,14 @@ class MapActivity : AppCompatActivity() {// ---- Drawing ----------------------------------------------------------------------- private var lastPins: List<Pin> = emptyList()- private val respreadPins = Runnable { drawPins(lastPins); binding.map.invalidate() }-- /** Metres per screen pixel at the map's current zoom, near [lat]. */- private fun metersPerPx(lat: Double, lon: Double): Double {- val proj = binding.map.projection- val a = proj.toPixels(GeoPoint(lat, lon), null)- val b = proj.toPixels(GeoPoint(lat + 0.001, lon), null)- val px = kotlin.math.abs(b.y - a.y).toDouble()- return if (px > 0) 111.32 / px else 0.0- }-+ /**+ * Each device sits exactly where it was heard best. Devices heard from the same+ * spot overlap; tapping there lists them all.+ */private fun drawPins(list: List<Pin>) {- lastPins = list- pins.items.clear()- val dp = resources.displayMetrics.density- // Ordinary devices first so flagged ones end up on top.- val sorted = list.sortedBy { it.flagged }- // Devices heard from the same spot share coordinates: fan them out so each can be tapped.- val center = binding.map.mapCenter- val real = sorted.map { it.lat to it.lon }- val shown = if (binding.map.zoomLevelDouble < PinSpread.MIN_ZOOM) real- else PinSpread.spread(real, metersPerPx(center.latitude, center.longitude), 30.0 * dp)- sorted.forEachIndexed { i, p ->- val size = ((if (p.flagged) 24 else 16) * dp).toInt()- val dot = GradientDrawable().apply {- shape = GradientDrawable.OVAL- setColor(p.color)- setStroke((2 * dp).toInt(), Color.WHITE)- setSize(size, size)- }- pins.add(Marker(binding.map).apply {- position = GeoPoint(shown[i].first, shown[i].second)- icon = dot- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = p.label- setOnMarkerClickListener { _, _ -> showPin(p); true }- })+ // Ordinary devices first so flagged ones are drawn on top.+ pins.points = list.sortedBy { it.flagged }.map { p ->+ PointsOverlay.Point(p.lat, p.lon, p, color = p.color, sizeDp = if (p.flagged) 24f else 16f)}}@@ -601,30 +592,21 @@ class MapActivity : AppCompatActivity() {/** Draws the cameras in (and just around) the visible area; skipped when zoomed far out. */private fun drawKnownAlpr() {val map = binding.map- knownAlpr.items.clear()map.removeCallbacks(autoDownloadCameras)map.postDelayed(autoDownloadCameras, 1_200)if (!com.rfsentinel.app.util.Prefs.showKnownAlpr(this) || map.zoomLevelDouble < 9.0) {- map.invalidate(); return+ knownAlpr.points = emptyList(); map.invalidate(); return}val box = map.boundingBox.increaseByScale(1.5f)val inView = com.rfsentinel.app.alpr.AlprStore.cameras.filter {it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast}.take(1500)val dp = resources.displayMetrics.density- val icons = com.rfsentinel.app.alpr.KnownCamera.Kind.entries.associateWith {- android.graphics.drawable.BitmapDrawable(resources, cameraIcon(dp, it))- }- for (cam in inView) {- knownAlpr.add(Marker(map).apply {- position = GeoPoint(cam.lat, cam.lon)- this.icon = icons.getValue(cam.type)- // Cameras whose alerts you turned off stay on the map, faded.- if (com.rfsentinel.app.alpr.IgnoredCameras.contains(this@MapActivity, cam.osmId)) alpha = 0.35f- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = cam.label- setOnMarkerClickListener { _, _ -> showKnownCamera(cam); true }- })+ val icons = com.rfsentinel.app.alpr.KnownCamera.Kind.entries.associateWith { cameraIcon(dp, it) }+ knownAlpr.points = inView.map { cam ->+ // Cameras whose alerts you turned off stay on the map, faded.+ val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(this@MapActivity, cam.osmId)+ PointsOverlay.Point(cam.lat, cam.lon, cam, icon = icons.getValue(cam.type), alpha = if (ignored) 90 else 255)}knownAlprDrawnFor = boxmap.invalidate()@@ -664,6 +646,38 @@ class MapActivity : AppCompatActivity() {.show()}+ private fun drawTowers() {+ towers.points = if (tripId != null || !com.rfsentinel.app.util.Prefs.showCellTowers(this)) emptyList()+ else com.rfsentinel.app.service.CellTowerStore.all(this).filter { it.bestLat != null }.map {+ PointsOverlay.Point(it.bestLat!!, it.bestLon!!, it, icon = towerIcon)+ }+ binding.map.invalidate()+ }++ private fun showTower(t: com.rfsentinel.app.service.CellTowerStore.Tower) {+ val net = listOfNotNull(t.operator, "${t.mcc ?: "?"}-${t.mnc ?: "?"}").joinToString(" · ")+ AlertDialog.Builder(this)+ .setTitle(t.ratLabel)+ .setMessage("$net\nArea ${t.area ?: "?"} · Cell ${t.cellId}" ++ (t.bestDbm?.let { "\nStrongest signal $it dBm" } ?: "") ++ "\nSeen ${t.timesSeen}×, last ${dateFmt.format(java.util.Date(t.lastSeen))}" ++ "\n\nPlaced where your phone heard it strongest: an estimate, not the tower's exact position.")+ .setPositiveButton("All towers") { _, _ -> startActivity(Intent(this, CellTowersActivity::class.java)) }+ .setNegativeButton("Close", null)+ .show()+ }++ /** One device, or a list to pick from when several were heard at the same spot. */+ private fun showPins(list: List<Pin>) {+ if (list.size == 1) { showPin(list[0]); return }+ val sorted = list.sortedByDescending { it.flagged }+ AlertDialog.Builder(this)+ .setTitle("${list.size} devices here")+ .setItems(sorted.map { (if (it.flagged) "⚠ " else "") + it.label }.toTypedArray()) { _, i -> showPin(sorted[i]) }+ .setNegativeButton("Close", null)+ .show()+ }+private fun showPin(p: Pin) {AlertDialog.Builder(this).setTitle(p.label)@@ -771,6 +785,9 @@ class MapActivity : AppCompatActivity() {isCheckable = true; isChecked = com.rfsentinel.app.util.Prefs.showKnownAlpr(this@MapActivity)}menu.add(0, 7, 3, "Delete downloaded cameras")+ menu.add(0, 9, 4, "Show cell towers").apply {+ isCheckable = true; isChecked = com.rfsentinel.app.util.Prefs.showCellTowers(this@MapActivity)+ }}return true}@@ -797,6 +814,12 @@ class MapActivity : AppCompatActivity() {Toast.makeText(this, "Downloaded cameras deleted", Toast.LENGTH_SHORT).show(); true}8 -> { downloadAllPlateCameras(); true }+ 9 -> {+ val show = !com.rfsentinel.app.util.Prefs.showCellTowers(this)+ com.rfsentinel.app.util.Prefs.setShowCellTowers(this, show)+ item.isChecked = show+ drawTowers(); true+ }android.R.id.home -> { finish(); true }else -> super.onOptionsItemSelected(item)}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.ktindex 210f628..a3392d9 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt@@ -45,6 +45,24 @@ object MapIcons {return bmp}+ /** A cell tower: a mast with two radio waves on a dark disc. */+ fun towerIcon(dp: Float): Bitmap {+ val s = (20 * dp).toInt()+ val bmp = Bitmap.createBitmap(s, s, Bitmap.Config.ARGB_8888)+ val c = Canvas(bmp)+ val p = Paint(Paint.ANTI_ALIAS_FLAG)+ val r = s / 2f+ p.color = 0xFF5E35B1.toInt(); c.drawCircle(r, r, r - 1 * dp, p)+ p.style = Paint.Style.STROKE; p.strokeWidth = 1.5f * dp; p.color = Color.WHITE+ c.drawCircle(r, r, r - 1 * dp, p)+ p.strokeCap = Paint.Cap.ROUND+ c.drawLine(r, r - 1 * dp, r - 3.5f * dp, r + 6 * dp, p)+ c.drawLine(r, r - 1 * dp, r + 3.5f * dp, r + 6 * dp, p)+ c.drawArc(RectF(r - 4 * dp, r - 6 * dp, r + 4 * dp, r + 2 * dp), 200f, 140f, false, p)+ c.drawArc(RectF(r - 6.5f * dp, r - 8.5f * dp, r + 6.5f * dp, r + 4.5f * dp), 205f, 130f, false, p)+ return bmp+ }+/** A round device dot with a white ring. */fun dot(dp: Float, color: Int, sizeDp: Int, ringDp: Float = 2f) = GradientDrawable().apply {shape = GradientDrawable.OVALdiff --git a/app/src/main/java/com/rfsentinel/app/ui/PinSpread.kt b/app/src/main/java/com/rfsentinel/app/ui/PinSpread.ktdeleted file mode 100644index c4fdd91..0000000--- a/app/src/main/java/com/rfsentinel/app/ui/PinSpread.kt+++ /dev/null@@ -1,64 +0,0 @@-package com.rfsentinel.app.ui--import kotlin.math.PI-import kotlin.math.cos-import kotlin.math.sin--/**- * Devices are placed where the phone heard them loudest, so everything heard- * from one spot shares the same coordinates and the dots stack on top of each- * other. This fans dots that would overlap on screen out into rings around- * their shared spot, so each one can be tapped. Pure (unit-tested).- */-object PinSpread {-- /** Dots further apart than this in reality are never regrouped. */- const val MAX_GROUP_M = 30.0- /** Below this zoom the map shows dots where they are, overlapping or not. */- const val MIN_ZOOM = 15.0-- /**- * Returns a display position for every input position (same order).- * [metersPerPx] is the map's current scale and [spacingPx] the on-screen gap- * wanted between dot centres.- */- fun spread(- points: List<Pair<Double, Double>>, metersPerPx: Double, spacingPx: Double,- maxGroupM: Double = MAX_GROUP_M- ): List<Pair<Double, Double>> {- if (points.size < 2 || metersPerPx <= 0.0) return points- val spacingM = spacingPx * metersPerPx- // Only dots heard from (nearly) the same spot are fanned out - never ones that just look close when zoomed out.- val joinM = minOf(spacingM, maxGroupM)- // Greedy grouping: a dot joins the first group whose centre is close enough.- val groups = ArrayList<MutableList<Int>>()- for (i in points.indices) {- val g = groups.firstOrNull { metersBetween(points[it.first()], points[i]) < joinM }- if (g != null) g += i else groups += mutableListOf(i)- }- val out = points.toMutableList()- for (g in groups) {- if (g.size < 2) continue- val (lat0, lon0) = points[g.first()]- val mPerDegLat = 111_320.0- val mPerDegLon = 111_320.0 * cos(Math.toRadians(lat0)).coerceAtLeast(0.01)- // The first dot keeps the spot; the rest go on rings of 6, 12, 18... one spacing apart.- var ring = 1- var slot = 0- for (k in 1 until g.size) {- val perRing = 6 * ring- val angle = 2 * PI * slot / perRing - PI / 2- val r = spacingM * ring- out[g[k]] = (lat0 + r * sin(-angle) / mPerDegLat) to (lon0 + r * cos(angle) / mPerDegLon)- if (++slot == perRing) { ring++; slot = 0 }- }- }- return out- }-- private fun metersBetween(a: Pair<Double, Double>, b: Pair<Double, Double>): Double {- val dLat = (b.first - a.first) * 111_320.0- val dLon = (b.second - a.second) * 111_320.0 * cos(Math.toRadians(a.first))- return kotlin.math.sqrt(dLat * dLat + dLon * dLon)- }-}diff --git a/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.kt b/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.ktnew file mode 100644index 0000000..4dc85f1--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/PointsOverlay.kt@@ -0,0 +1,84 @@+package com.rfsentinel.app.ui++import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paint+import android.view.MotionEvent+import org.osmdroid.util.GeoPoint+import org.osmdroid.views.MapView+import org.osmdroid.views.overlay.Overlay++/**+ * Draws many points straight onto the map canvas, each centred exactly on its+ * coordinate and re-projected on every frame, so points stay pinned to the map+ * while it pans, zooms or rotates (no per-point Marker objects lagging behind,+ * no fanning out). Idea from Wardrive Go's markers overlay (GPL-3.0), written+ * for RF Sentinel's point styles.+ *+ * A tap reports every point under the finger, nearest first, so points heard from+ * the same spot can be picked from a list instead of being spread apart.+ */+class PointsOverlay<T>(+ private val density: Float,+ private val onTap: (List<T>) -> Unit+) : Overlay() {++ /** One point: a filled dot with a ring, or an [icon] bitmap centred on the coordinate. */+ class Point<T>(+ val lat: Double,+ val lon: Double,+ val payload: T,+ val color: Int = 0,+ val sizeDp: Float = 16f,+ val ringColor: Int = 0xFFFFFFFF.toInt(),+ val icon: Bitmap? = null,+ val alpha: Int = 255+ )++ @Volatile var points: List<Point<T>> = emptyList()++ private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }+ private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }+ private val bitmapPaint = Paint(Paint.FILTER_BITMAP_FLAG)+ private val px = android.graphics.Point()+ private val tapRadius = 22f * density++ override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) {+ if (shadow) return+ val proj = mapView.projection+ val margin = 40 * density+ val w = mapView.width; val h = mapView.height+ for (p in points) {+ proj.toPixels(GeoPoint(p.lat, p.lon), px)+ // Rotation and scaling are applied to the canvas by osmdroid; cull generously.+ val x = px.x.toFloat(); val y = px.y.toFloat()+ if (x < -w - margin || y < -h - margin || x > 2 * w + margin || y > 2 * h + margin) continue+ val icon = p.icon+ if (icon != null) {+ bitmapPaint.alpha = p.alpha+ canvas.drawBitmap(icon, x - icon.width / 2f, y - icon.height / 2f, bitmapPaint)+ } else {+ val r = p.sizeDp * density / 2+ ring.color = p.ringColor; ring.alpha = p.alpha+ canvas.drawCircle(x, y, r, ring)+ fill.color = p.color; fill.alpha = p.alpha+ canvas.drawCircle(x, y, r - 2 * density, fill)+ }+ }+ }++ override fun onSingleTapConfirmed(e: MotionEvent, mapView: MapView): Boolean {+ val proj = mapView.projection+ val hits = ArrayList<Pair<Float, T>>()+ for (p in points) {+ proj.toPixels(GeoPoint(p.lat, p.lon), px)+ val r = maxOf(tapRadius, (p.icon?.width ?: 0) / 2f, p.sizeDp * density / 2)+ val dx = e.x - px.x; val dy = e.y - px.y+ val d2 = dx * dx + dy * dy+ if (d2 <= r * r) hits += d2 to p.payload+ }+ if (hits.isEmpty()) return false+ onTap(hits.sortedBy { it.first }.map { it.second })+ return true+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.ktnew file mode 100644index 0000000..1da70ff--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt@@ -0,0 +1,192 @@+package com.rfsentinel.app.ui++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.net.wifi.ScanResult+import android.net.wifi.WifiManager+import android.os.Build+import android.os.Bundle+import android.os.SystemClock+import android.view.LayoutInflater+import android.view.Menu+import android.view.MenuItem+import android.view.ViewGroup+import android.widget.Toast+import androidx.appcompat.app.AppCompatActivity+import androidx.core.content.ContextCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.lifecycleScope+import androidx.lifecycle.repeatOnLifecycle+import androidx.recyclerview.widget.LinearLayoutManager+import androidx.recyclerview.widget.RecyclerView+import com.google.android.material.chip.Chip+import com.rfsentinel.app.databinding.ActivityWifiAnalyzerBinding+import com.rfsentinel.app.databinding.ItemDetectionBinding+import com.rfsentinel.app.ui.WifiChartView.Ap+import com.rfsentinel.app.ui.WifiChartView.Band+import com.rfsentinel.app.util.applySystemBarInsets+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * WiFi channel and spectrum analyzer for 2.4, 5 and 6 GHz, from the phone's own+ * WiFi scans (receive-only: scanning listens for access point beacons).+ * Android limits apps to about four scans per two minutes, so the chart refreshes+ * whenever any app's scan delivers new results.+ */+class WifiAnalyzerActivity : AppCompatActivity() {++ private lateinit var binding: ActivityWifiAnalyzerBinding+ private val wifi by lazy { applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager }+ private var aps: List<Ap> = emptyList()+ private val bandChips = HashMap<Band, Chip>()++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(c: Context?, i: Intent?) = reload()+ }++ private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {+ var items: List<Ap> = emptyList()+ override fun getItemCount() = items.size+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =+ object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}+ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {+ val ap = items[position]+ val b = ItemDetectionBinding.bind(holder.itemView)+ b.labelText.text = ap.ssid+ b.macText.text = "${ap.bssid} · ch ${WifiChartView.channelOf(ap.freq)} · ${ap.widthMhz} MHz"+ b.metaText.text = "${ap.rssi} dBm · ${ap.freq} MHz" ++ if (ap.centerFreq > 0 && ap.centerFreq != ap.freq) " · centre ${ap.centerFreq} MHz" else ""+ }+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ binding = ActivityWifiAnalyzerBinding.inflate(layoutInflater)+ setContentView(binding.root)+ binding.root.applySystemBarInsets()+ title = "WiFi channels"+ supportActionBar?.setDisplayHomeAsUpEnabled(true)++ val spectrum = intent.getBooleanExtra(EXTRA_SPECTRUM, false)+ binding.modeGroup.check(if (spectrum) binding.modeSpectrum.id else binding.modeChannels.id)+ binding.chart.mode = if (spectrum) WifiChartView.Mode.SPECTRUM else WifiChartView.Mode.CHANNELS+ if (spectrum) title = "WiFi spectrum"+ binding.modeGroup.addOnButtonCheckedListener { _, id, checked ->+ if (!checked) return@addOnButtonCheckedListener+ val s = id == binding.modeSpectrum.id+ binding.chart.mode = if (s) WifiChartView.Mode.SPECTRUM else WifiChartView.Mode.CHANNELS+ title = if (s) "WiFi spectrum" else "WiFi channels"+ }+ for (band in Band.entries) {+ val chip = Chip(this).apply {+ text = band.label+ isCheckable = true+ id = android.view.View.generateViewId()+ setOnClickListener { selectBand(band) }+ }+ bandChips[band] = chip+ binding.bandGroup.addView(chip)+ }+ bandChips.getValue(Band.B24).isChecked = true++ binding.recyclerView.layoutManager = LinearLayoutManager(this)+ binding.recyclerView.adapter = adapter++ lifecycleScope.launch {+ repeatOnLifecycle(Lifecycle.State.STARTED) {+ while (true) { reload(); delay(5_000) }+ }+ }+ }++ override fun onStart() {+ super.onStart()+ ContextCompat.registerReceiver(this, receiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION),+ ContextCompat.RECEIVER_NOT_EXPORTED)+ requestScan(quiet = true)+ }++ override fun onStop() {+ runCatching { unregisterReceiver(receiver) }+ super.onStop()+ }++ override fun onCreateOptionsMenu(menu: Menu): Boolean {+ menu.add(0, 1, 0, "Scan now").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)+ return true+ }++ override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {+ 1 -> { requestScan(quiet = false); true }+ android.R.id.home -> { finish(); true }+ else -> super.onOptionsItemSelected(item)+ }++ private fun requestScan(quiet: Boolean) {+ @Suppress("DEPRECATION") // no replacement API+ val ok = runCatching { wifi.startScan() }.getOrDefault(false)+ if (!quiet && !ok) {+ Toast.makeText(this, "Android limits WiFi scans to about 4 per 2 minutes - showing the latest results", Toast.LENGTH_LONG).show()+ }+ }++ private fun selectBand(band: Band) {+ bandChips.forEach { (b, c) -> c.isChecked = b == band }+ binding.chart.band = band+ render()+ }++ @android.annotation.SuppressLint("MissingPermission") // checked just below+ private fun reload() {+ if (!com.rfsentinel.app.util.Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {+ binding.summaryText.text = "WiFi scan results need the location permission. Start a scan once to grant it."+ return+ }+ val nowUs = SystemClock.elapsedRealtime() * 1000+ aps = runCatching { wifi.scanResults }.getOrNull().orEmpty()+ .filter { nowUs - it.timestamp <= MAX_AGE_US }+ .map { r ->+ @Suppress("DEPRECATION")+ val ssid = r.SSID?.removeSurrounding("\"")?.takeIf { it.isNotEmpty() && it != "<unknown ssid>" } ?: "(hidden)"+ Ap(ssid, r.BSSID ?: "?", r.frequency, centerOf(r), widthOf(r), r.level)+ }+ render()+ }++ @android.annotation.SuppressLint("NotifyDataSetChanged") // a list of a few dozen networks+ private fun render() {+ binding.chart.setAps(aps)+ val counts = aps.groupBy { WifiChartView.bandOf(it.freq) }+ bandChips.forEach { (b, c) -> c.text = "${b.label} ${counts[b]?.size ?: 0}" }+ val inBand = aps.filter { WifiChartView.bandOf(it.freq) == binding.chart.band }.sortedByDescending { it.rssi }+ val busiest = inBand.groupBy { WifiChartView.channelOf(it.freq) }.maxByOrNull { it.value.size }+ binding.summaryText.text = when {+ aps.isEmpty() -> "No WiFi scan results yet. Is WiFi (or WiFi scanning) on, and location allowed?"+ inBand.isEmpty() -> "Nothing on ${binding.chart.band.label} right now."+ else -> "${inBand.size} networks on ${binding.chart.band.label}" ++ (busiest?.let { " · busiest channel ${it.key} (${it.value.size})" } ?: "") ++ " · strongest ${inBand.first().rssi} dBm"+ }+ adapter.items = inBand+ adapter.notifyDataSetChanged()+ }++ private fun widthOf(r: ScanResult): Int = when (r.channelWidth) {+ ScanResult.CHANNEL_WIDTH_40MHZ -> 40+ ScanResult.CHANNEL_WIDTH_80MHZ -> 80+ ScanResult.CHANNEL_WIDTH_160MHZ, ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ -> 160+ else -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && r.channelWidth == ScanResult.CHANNEL_WIDTH_320MHZ) 320 else 20+ }++ /** The middle of the occupied block (for 40 MHz+ the primary channel sits off-centre). */+ private fun centerOf(r: ScanResult): Int = if (widthOf(r) > 20 && r.centerFreq0 > 0) r.centerFreq0 else r.frequency++ companion object {+ const val EXTRA_SPECTRUM = "spectrum"+ /** Cached results older than this are left out (ScanResult.timestamp is µs since boot). */+ private const val MAX_AGE_US = 3 * 60_000_000L+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/WifiChartView.kt b/app/src/main/java/com/rfsentinel/app/ui/WifiChartView.ktnew file mode 100644index 0000000..b0fae13--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/WifiChartView.kt@@ -0,0 +1,164 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.Path+import android.util.AttributeSet+import android.view.View+import com.google.android.material.color.MaterialColors+import com.rfsentinel.app.R++/**+ * WiFi channel views for one band, from ordinary scan results:+ * - [Mode.CHANNELS]: networks per channel (bar) and the strongest signal on it;+ * - [Mode.SPECTRUM]: each network as a curve across the channels it occupies+ * (centre frequency and width), so overlapping networks are visible.+ */+class WifiChartView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {++ enum class Mode { CHANNELS, SPECTRUM }+ enum class Band(val label: String) { B24("2.4 GHz"), B5("5 GHz"), B6("6 GHz") }++ /** One access point as the chart needs it. */+ data class Ap(val ssid: String, val bssid: String, val freq: Int, val centerFreq: Int, val widthMhz: Int, val rssi: Int)++ var mode = Mode.CHANNELS+ set(v) { field = v; invalidate() }+ var band = Band.B24+ set(v) { field = v; invalidate() }+ private var aps: List<Ap> = emptyList()++ fun setAps(list: List<Ap>) { aps = list; invalidate() }++ private val d = resources.displayMetrics.density+ private val textColor = MaterialColors.getColor(context, android.R.attr.textColorSecondary, 0xFF888888.toInt())+ private val accent = MaterialColors.getColor(context, R.attr.rfTraceColor, 0xFFE0622D.toInt())+ private val grid = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = (textColor and 0x00FFFFFF) or 0x33000000; strokeWidth = d }+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = textColor; textSize = 10 * d }+ private val bar = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = accent }+ private val curveFill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }+ private val curveLine = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.8f * d }+ private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply { textSize = 10 * d; textAlign = Paint.Align.CENTER }++ private val palette = intArrayOf(+ 0xFFE0622D.toInt(), 0xFF1F8FBF.toInt(), 0xFF2E9E5B.toInt(), 0xFF8E44AD.toInt(), 0xFFD4A017.toInt(),+ 0xFFC2185B.toInt(), 0xFF00897B.toInt(), 0xFF5D6D7E.toInt(), 0xFF6D4C41.toInt(), 0xFF3949AB.toInt()+ )++ /** Channels drawn on the x axis for the band, with their centre frequency. */+ private fun axis(): List<Pair<Int, Int>> = when (band) {+ Band.B24 -> (1..13).map { it to 2407 + 5 * it }+ Band.B5 -> listOf(36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 149, 153, 157, 161, 165, 169, 173, 177)+ .map { it to 5000 + 5 * it }+ Band.B6 -> (1..233 step 4).map { it to 5950 + 5 * it }+ }++ override fun onDraw(canvas: Canvas) {+ super.onDraw(canvas)+ val inBand = aps.filter { bandOf(it.freq) == band }+ val left = 30 * d; val right = width - 6 * d; val top = 14 * d; val bottom = height - 20 * d+ val chans = axis()+ val fLo = chans.first().second - if (band == Band.B24) 12 else 15+ val fHi = chans.last().second + if (band == Band.B24) 12 else 15+ fun xOf(f: Double) = (left + (f - fLo) / (fHi - fLo) * (right - left)).toFloat()+ fun yOf(rssi: Int) = bottom - (rssi.coerceIn(-100, -20) + 100) / 80f * (bottom - top)++ // dBm grid+ text.textAlign = Paint.Align.RIGHT+ for (db in -90..-30 step 20) {+ val y = yOf(db)+ canvas.drawLine(left, y, right, y, grid)+ canvas.drawText("$db", left - 3 * d, y + 3 * d, text)+ }+ // channel labels (thinned so they never collide)+ text.textAlign = Paint.Align.CENTER+ val minGap = 22 * d+ var lastX = -1e9f+ for ((ch, f) in chans) {+ val x = xOf(f.toDouble())+ if (x - lastX < minGap) continue+ canvas.drawText("$ch", x, height - 6 * d, text)+ lastX = x+ }+ if (inBand.isEmpty()) {+ text.textAlign = Paint.Align.CENTER+ canvas.drawText("No ${band.label} networks heard", (left + right) / 2, (top + bottom) / 2, text)+ return+ }+ when (mode) {+ Mode.CHANNELS -> drawChannels(canvas, inBand, chans, ::xOf, ::yOf, bottom)+ Mode.SPECTRUM -> drawSpectrum(canvas, inBand, ::xOf, ::yOf, bottom)+ }+ }++ private fun drawChannels(+ canvas: Canvas, list: List<Ap>, chans: List<Pair<Int, Int>>,+ xOf: (Double) -> Float, yOf: (Int) -> Float, bottom: Float+ ) {+ val byCh = list.groupBy { channelOf(it.freq) }+ val maxCount = byCh.values.maxOf { it.size }.coerceAtLeast(1)+ val slot = if (chans.size > 1) xOf(chans[1].second.toDouble()) - xOf(chans[0].second.toDouble()) else 20 * d+ val w = (slot * 0.7f).coerceIn(4 * d, 18 * d)+ label.color = textColor+ for ((ch, aps) in byCh) {+ val x = xOf(freqOf(ch, band).toDouble())+ val strongest = aps.maxOf { it.rssi }+ // Bar height = strongest signal; the count is printed on top.+ val y = yOf(strongest)+ bar.alpha = (110 + 145 * aps.size / maxCount).coerceAtMost(255)+ canvas.drawRoundRect(x - w / 2, y, x + w / 2, bottom, 2 * d, 2 * d, bar)+ canvas.drawText("${aps.size}", x, y - 3 * d, label)+ }+ }++ private fun drawSpectrum(canvas: Canvas, list: List<Ap>, xOf: (Double) -> Float, yOf: (Int) -> Float, bottom: Float) {+ val sorted = list.sortedBy { it.rssi } // strongest drawn last, on top+ for ((i, ap) in sorted.withIndex()) {+ val color = palette[(ap.bssid.hashCode() and 0x7FFFFFFF) % palette.size]+ val c = (if (ap.centerFreq > 0) ap.centerFreq else ap.freq).toDouble()+ val half = ap.widthMhz / 2.0+ val x0 = xOf(c - half); val x1 = xOf(c + half)+ val ramp = (x1 - x0) * 0.18f+ val y = yOf(ap.rssi)+ val path = Path().apply {+ moveTo(x0, bottom)+ cubicTo(x0 + ramp * 0.6f, bottom, x0 + ramp * 0.4f, y, x0 + ramp, y)+ lineTo(x1 - ramp, y)+ cubicTo(x1 - ramp * 0.4f, y, x1 - ramp * 0.6f, bottom, x1, bottom)+ }+ curveFill.color = (color and 0x00FFFFFF) or 0x2E000000+ canvas.drawPath(path, curveFill)+ curveLine.color = color+ canvas.drawPath(path, curveLine)+ // Label the strongest few so the chart stays readable.+ if (i >= sorted.size - 8) {+ label.color = color+ canvas.drawText(ap.ssid.take(16), (x0 + x1) / 2, y - 3 * d, label)+ }+ }+ }++ companion object {+ fun bandOf(freq: Int): Band? = when {+ freq in 2400..2500 -> Band.B24+ freq in 4900..5899 -> Band.B5+ freq >= 5925 -> Band.B6+ else -> null+ }++ fun channelOf(freq: Int): Int = when {+ freq == 2484 -> 14+ freq in 2400..2500 -> (freq - 2407) / 5+ freq in 4900..5899 -> (freq - 5000) / 5+ freq >= 5925 -> (freq - 5950) / 5+ else -> 0+ }++ fun freqOf(ch: Int, band: Band): Int = when (band) {+ Band.B24 -> if (ch == 14) 2484 else 2407 + 5 * ch+ Band.B5 -> 5000 + 5 * ch+ Band.B6 -> 5950 + 5 * ch+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex a1c3434..937f40d 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -145,6 +145,8 @@ object Prefs {fun setDeflockUpdated(context: Context, time: Long) = sp(context).edit { putLong("deflock_updated", time) }fun ouiSpyRelayAll(context: Context): Boolean = bool(context, "ouispy_relay_all", true)fun setOuiSpyRelayAll(context: Context, value: Boolean) = setBool(context, "ouispy_relay_all", value)+ fun showCellTowers(context: Context): Boolean = bool(context, "show_cell_towers", false)+ fun setShowCellTowers(context: Context, value: Boolean) = setBool(context, "show_cell_towers", value)fun showKnownAlpr(context: Context): Boolean = bool(context, "show_known_alpr", true)fun setShowKnownAlpr(context: Context, value: Boolean) = setBool(context, "show_known_alpr", value)diff --git a/app/src/main/res/layout/activity_wifi_analyzer.xml b/app/src/main/res/layout/activity_wifi_analyzer.xmlnew file mode 100644index 0000000..02c026b--- /dev/null+++ b/app/src/main/res/layout/activity_wifi_analyzer.xml@@ -0,0 +1,60 @@+<?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="match_parent"+ android:orientation="vertical"+ android:padding="16dp">++ <com.google.android.material.button.MaterialButtonToggleGroup+ android:id="@+id/modeGroup"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ app:singleSelection="true"+ app:selectionRequired="true">++ <com.google.android.material.button.MaterialButton+ android:id="@+id/modeChannels"+ style="?attr/materialButtonOutlinedStyle"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:text="Channels" />++ <com.google.android.material.button.MaterialButton+ android:id="@+id/modeSpectrum"+ style="?attr/materialButtonOutlinedStyle"+ android:layout_width="0dp"+ android:layout_height="wrap_content"+ android:layout_weight="1"+ android:text="Spectrum" />+ </com.google.android.material.button.MaterialButtonToggleGroup>++ <com.google.android.material.chip.ChipGroup+ android:id="@+id/bandGroup"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ app:singleSelection="true"+ app:selectionRequired="true" />++ <com.rfsentinel.app.ui.WifiChartView+ android:id="@+id/chart"+ android:layout_width="match_parent"+ android:layout_height="240dp"+ android:layout_marginTop="8dp" />++ <TextView+ android:id="@+id/summaryText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:textSize="13sp" />++ <androidx.recyclerview.widget.RecyclerView+ android:id="@+id/recyclerView"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_marginTop="8dp"+ android:layout_weight="1" />+</LinearLayout>diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xmlindex fe9a9b5..7fae3fb 100644--- a/app/src/main/res/menu/menu_main.xml+++ b/app/src/main/res/menu/menu_main.xml@@ -15,6 +15,13 @@<item android:id="@+id/action_match_log" android:title="Match history" app:showAsAction="never" /><item android:id="@+id/action_traces" android:title="Recorded traces" app:showAsAction="never" /><item android:id="@+id/action_history" android:title="History map & timeline" app:showAsAction="never" />+ <item android:id="@+id/action_tools" android:title="Tools" app:showAsAction="never">+ <menu>+ <item android:id="@+id/action_cell_towers" android:title="Cell towers" />+ <item android:id="@+id/action_wifi_channels" android:title="WiFi channels" />+ <item android:id="@+id/action_wifi_spectrum" android:title="WiFi spectrum" />+ </menu>+ </item><item android:id="@+id/action_oui_list" android:title="Watchlist & rules" app:showAsAction="never" /><item android:id="@+id/action_whitelist" android:title="Whitelist (trusted devices)" app:showAsAction="never" /><item android:id="@+id/action_settings" android:title="Settings" app:showAsAction="never" />diff --git a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.ktindex d6aed87..0a8dd1b 100644--- a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt@@ -56,6 +56,23 @@ class DetectionTest {assertEquals(Category.BODY_CAM, best(ble(uuids = listOf(Advert.uuid16(0xFC81))))?.category)}+ @Test+ fun printerVehicleAndScreeningMakersAreWeakClues() {+ val zebra = best(ble(mfg = mapOf(0x01F1 to bytes(1))))+ assertEquals(Category.PUBLIC_SAFETY, zebra?.category)+ assertEquals(25, zebra?.confidence)+ // The Zebra printer UUID rule takes over when both are present.+ assertEquals(30, best(ble(mfg = mapOf(0x01F1 to bytes(1)), uuids = listOf(Advert.uuid16(0xFE79))))?.confidence)+ assertEquals(20, best(ble(mfg = mapOf(0x0755 to bytes(1))))?.confidence)+ assertEquals("Fortin vehicle interface module", best(ble(uuids = listOf(Advert.uuid16(0xFDE1))))?.label)+ assertEquals(35, best(ble(mfg = mapOf(0x04BC to bytes(1))))?.confidence)+ assertEquals(35, best(ble(uuids = listOf(Advert.uuid16(0xFCDA))))?.confidence)+ // All stay under the default alert threshold (50).+ listOf(0x01F1, 0x0755, 0x04BC).forEach { cid ->+ assertTrue(best(ble(mfg = mapOf(cid to bytes(1))))!!.confidence < 50)+ }+ }+@Testfun motorolaIsWeak() {val hit = best(ble(mfg = mapOf(0x04EC to bytes(0))))diff --git a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.ktindex 85df314..3141598 100644--- a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt@@ -119,6 +119,28 @@ class IdentificationTest {assertEquals(PatrolCluster.Motion.OneFlat, PatrolCluster.motion(wave(0), parked, now))}+ @Test+ fun newVehicleRolesAndSupportOnlyGroups() {+ assertEquals("vehicle cellular router", PatrolCluster.roleOf(emptyList(), "Peplink International Ltd.", null))+ assertEquals("vehicle cellular router", PatrolCluster.roleOf(emptyList(), "Inseego Wireless, Inc", null))+ assertEquals("vehicle interface module",+ PatrolCluster.roleOf(listOf(hit(Category.PUBLIC_SAFETY, "Fortin vehicle interface module", 20)), null, null))+ // Fortinet firewalls are not Fortin modules.+ assertNull(PatrolCluster.roleOf(emptyList(), "Fortinet, Inc.", null))+ assertNull(PatrolCluster.roleOf(emptyList(), "Brother industries, LTD.", null))++ val now = 60_000L+ // A remote starter and a Dräger device moving together: civilian makers alone never make a vehicle.+ val supportOnly = listOf(+ PatrolCluster.Member("AA:00:00:00:00:01", "vehicle interface module", 0, now, wave(0)),+ PatrolCluster.Member("AA:00:00:00:00:02", "impairment-screening device", 0, now, wave(0, offset = -80))+ )+ assertTrue(PatrolCluster.groups(supportOnly, now).isEmpty())+ // ...but they add to a group with a core role.+ val withRadio = supportOnly + PatrolCluster.Member("AA:00:00:00:00:03", "two-way radio", 0, now, wave(0, offset = -75))+ assertEquals(3, PatrolCluster.groups(withRadio, now).single().roles.size)+ }+@Testfun consumerBrandsHaveNoPatrolRole() {assertNull(PatrolCluster.roleOf(emptyList(), "JVCKENWOOD Corporation", "KENWOOD CAR"))diff --git a/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.kt b/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.ktdeleted file mode 100644index 2eb095c..0000000--- a/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.kt+++ /dev/null@@ -1,39 +0,0 @@-package com.rfsentinel.app.ui--import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test-import kotlin.math.cos-import kotlin.math.sqrt--class PinSpreadTest {-- private fun px(a: Pair<Double, Double>, b: Pair<Double, Double>, mPerPx: Double): Double {- val dLat = (b.first - a.first) * 111_320.0- val dLon = (b.second - a.second) * 111_320.0 * cos(Math.toRadians(a.first))- return sqrt(dLat * dLat + dLon * dLon) / mPerPx- }-- @Test- fun stackedDotsAllBecomeSeparate() {- val spot = 39.0 to -98.0- val out = PinSpread.spread(List(16) { spot }, metersPerPx = 0.3, spacingPx = 24.0)- assertEquals(spot, out[0]) // the first keeps the real spot- for (i in out.indices) for (j in i + 1 until out.size) {- assertTrue("dots $i and $j overlap", px(out[i], out[j], 0.3) >= 23.0)- }- }-- @Test- fun farApartDotsStayPut() {- val pts = listOf(39.0 to -98.0, 39.01 to -98.0, 39.0 to -98.01)- assertEquals(pts, PinSpread.spread(pts, metersPerPx = 0.3, spacingPx = 24.0))- }-- @Test- fun zoomedOutNeighboursAreNotDraggedAround() {- // ~100 m apart: at 20 m/px they'd overlap on screen, but they're different spots.- val pts = listOf(39.0 to -98.0, 39.0009 to -98.0)- assertEquals(pts, PinSpread.spread(pts, metersPerPx = 20.0, spacingPx = 24.0))- }-}diff --git a/tools/gen_assets.py b/tools/gen_assets.pyindex 2eee514..1334625 100644--- a/tools/gen_assets.py+++ b/tools/gen_assets.py@@ -117,6 +117,13 @@ CODE_PREFIXES = {# Canada preset (2026-09 research)'8C1F64DF0': 'Cyberkar', '00BF15': 'Genetec', '0CBF15': 'Genetec', '0050C2BE7': 'Genetec','003044': 'CradlePoint', '00E01C': 'CradlePoint',+ # Police-vehicle vendor sweep (2026-10)+ '000512': 'Zebra', '00074D': 'Zebra', '001570': 'Zebra', '002368': 'Zebra', '00A0F8': 'Zebra', '4083DE': 'Zebra', '488EB7': 'Zebra', '609532': 'Zebra', '7493A4': 'Zebra', '78B8D6': 'Zebra', '84248D': 'Zebra', '88BCAC': 'Zebra', '9075DE': 'Zebra', '94FB29': 'Zebra', 'C47DCC': 'Zebra', 'C81CFE': 'Zebra', 'FC597A': 'Zebra',+ '001BA9': 'Brother', '008077': 'Brother', '30055C': 'Brother', '3C2AF4': 'Brother', '94DDF8': 'Brother', 'B07C8E': 'Brother', 'B42200': 'Brother',+ '00116E': 'Peplink', '1056CA': 'Peplink', '6CA3D3': 'Peplink', 'D413F8': 'Peplink',+ '0015FF': 'Inseego', '18EE86': 'Inseego', '780C71': 'Inseego', 'E08614': 'Inseego',+ '4C364E': 'Panasonic', 'B8208E': 'Panasonic', 'BC3E0B': 'Panasonic',+ '00A0D5': 'Sierra', '28A331': 'Sierra', '50139D': 'Sierra', '64CE6E': 'Sierra', '84DB2F': 'Sierra', 'CC934A': 'Sierra',}bad = 0for p, expect in CODE_PREFIXES.items():