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
Release 2.17.0: list / radar / map in any combination, the full map on the main screen, 3D driving view, RTL-SDR settings and names, live export, crash log
CIS-C0d85424827364
diff --git a/README.md b/README.mdindex cec51d3..4a1239d 100644--- a/README.md+++ b/README.md@@ -148,13 +148,13 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer**Hardware**- ESP32 boards over USB OTG (OUI-Spy, GhostESP, Marauder incl. dual-band ESP32-C5 boards, or through a Flipper Zero) or Bluetooth (OUI-SPY App-Controlled) add their detections and extend range-- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically+- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically- **Requested networks:** the WiFi names nearby devices ask for (probe requests), from a USB adapter or a Marauder board, in an optional list; **watch** a name to get an alert whenever any device asks for it- **More from every frame:** WPS maker / model / device name, a **probe fingerprint** that survives MAC randomization (watchable: "every device of this type"), and the real name of **hidden networks** when a device joins them**Interface**- Live list and radar view, filter chips with live counts (flagged, trackers, drones, favorites, new, Bluetooth, WiFi, cells, Waze, external hardware), search; Waze reports in range show nearest first with their exact distance and direction from you (ahead / behind / left / right while driving), and flash at the top once they reach your alert threshold; pull the list down (or use the menu) to check Waze right now, and the Waze status screen shows what is sent and when-- **Tools** (button next to the map button): **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+- **Tools** (wrench button next to the List / Radar / Map toggle): **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- **Cell towers in the live list:** the serving cell and its neighbours appear under *All*, after the devices- **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@@ -212,9 +212,13 @@ Details: [How it works](https://cis-c0.github.io/RFSentinel/how-it-works.html) a**INTERNAL** badge means the phone heard it; a blue **ESP32** badge means aconnected board reported it. Flagged devices sort first and flash in theircategory colour.-- **List / Radar / Map:** the toggle switches list and radar; **Map** sits right- next to it. On the radar, closer to the centre means a stronger signal; the- angle is not a direction (a phone can't measure one).+- **List / Radar / Map:** turn on one view to fill the screen, or two or all+ three to see them together (stacked, side by side in landscape), with a handle+ between each to resize. The Map view is the full map with every button; its+ ⛶ button opens it on its own screen. On the radar, closer to the centre means+ a stronger signal; the angle is not a direction (a phone can't measure one).+- **Scrolled to the top**, the list stays there as alerts arrive; scrolled down,+ a *New alert* pill takes you up.- **Filters and search:** All, Flagged, Trackers, Drones, Favorites, New,Bluetooth, WiFi, Cells, External (heard by an ESP32 board or a USB WiFiadapter). Search matches name, address, vendor and type.@@ -246,7 +250,11 @@ the raw advertisement.heard around you, placed where your phone was when its signal was strongest.That's an approximation, not a fix. Each dot stays pinned to its spot as youpan and zoom; tap a spot where several devices were heard to pick one from a list.-- **Cell towers** (map ⚙ → Settings → *Map* → *Show cell towers*): towers seen while scanning,+- **North up / heading up / 3D:** the compass button steps through north up,+ heading up (turns with your direction of travel while moving), and a **3D driving+ view** - tilted in perspective with your position low on the screen, like a car+ navigation app. The sun / moon button switches the map between light and dark.+- **Cell towers** (Settings → *Map* → *Show cell towers*): towers seen while scanning,at the spot where your phone heard them strongest - an estimate, not thetower's real position (looking that up online would reveal where you are).- **Known cameras** (Settings → *Known cameras*): *Download cameras around me* fetches plate readers@@ -266,10 +274,13 @@ the raw advertisement.- **Record trace** saves your route and every device heard along it, with thescreen off, and can start with each scan.- **Screen:** *always on*, *on while charging* (default) or *normal*.+- **Crash log:** if the app ever closes unexpectedly, what went wrong is saved on the+ phone (never sent automatically); it offers to send it next time, or Settings →+ *Lists, tools & about* → *Export crash log*.### Export-Menu → **Export all devices...** or **Export...**:+Menu → **Export...** (or Settings → Data → Export all devices):| Export | Formats ||---|---|@@ -411,7 +422,7 @@ go through RF Sentinel's own rules like everything else, with a purple| Chip | Example adapters | Status ||---|---|---|-| Realtek RTL8811AU / RTL8821AU (`0bda:0811`) | ALFA AWUS036ACS | Supported (2.4 GHz) |+| Realtek RTL8811AU / RTL8821AU (`0bda:0811`) | ALFA AWUS036ACS | Supported (2.4 GHz; 5 GHz experimental, opt-in) || Realtek RTL8812BU / RTL8822BU (`0bda:b812`, `0bda:b82c` and ~35 other IDs) | TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, Wise Tiger AC1200 | Supported (2.4 + 5 GHz), tested on a Wise Tiger 8812BU || Realtek RTL8814AU (`0bda:8813` and 13 other IDs) | ALFA AWUS1900, TP-Link Archer T9UH, ASUS USB-AC68, Netgear A7000 | Supported (2.4 + 5 GHz), not yet tested on hardware || MediaTek MT7612U / MT7632U (`0e8d:7612` and 16 other IDs) | ALFA AWUS036ACM, ASUS USB-AC55, Netgear A6210 | Supported (2.4 + 5 GHz), not yet tested on hardware |@@ -452,6 +463,22 @@ counts, and only as a weak sign. Consumer walkie-talkies (FRS / GMRS, MURS),marine, railroad, weather and paging channels are skipped. The dongle's log is inthe exported USB adapter log.+Hits show in the **main list** (the *Radio* filter, or under *All*): frequency,+its name when known, signal above the noise, and whether it's **getting closer or+moving away**. The dongle's status shows on the main screen next to the other+hardware. **Settings → RTL-SDR radio**:++- **Sensitivity** (how far above the noise a burst must be), the **built-in bands**+ on / off, **your own bands**, **ranges never to report** (e.g. a business band)+ and **frequencies to watch** (reported whenever they're active), one per line in MHz.+- **Say the frequency** (and its name) instead of "Radio transmitting nearby", and+ a **closer / moving away** call-out when the signal changes by the set number of dB.+- **Frequency names**: import a CSV (RadioReference's export, CHIRP, or any file with+ a frequency and a name column), and / or let **RadioReference** name the FCC+ licences near you (US; your own RadioReference Premium login and developer key,+ stored encrypted; your position rounded to ~1 km is sent, at most once a day per+ area). A hit takes the closest name within the set ± kHz.+**Requested networks** (Menu → *Requested networks*): phones and laptops ask byname for networks they joined before. With an adapter or a Marauder boardplugged in, RF Sentinel can keep these names (off by default: they're otherdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex efc5954..f08ee6e 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -7,8 +7,8 @@ plugins {}// Bump both for every release. versionName ends up in the APK file name.-val appVersionCode = 40-val appVersionName = "2.16.0"+val appVersionCode = 41+val appVersionName = "2.17.0"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex dfa493a..b959b7b 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -21,11 +21,9 @@ import com.rfsentinel.app.detect.Advertimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.detect.DeviceIntelimport com.rfsentinel.app.detect.Tier-import com.rfsentinel.app.ouilist.OuiListActivityimport com.rfsentinel.app.service.DeviceRegistryimport com.rfsentinel.app.service.ScanForegroundServiceimport com.rfsentinel.app.settings.SettingsActivity-import com.rfsentinel.app.ui.AboutDialogimport com.rfsentinel.app.ui.DetectionLogActivityimport com.rfsentinel.app.ui.DeviceActionsimport com.rfsentinel.app.ui.DeviceAdapter@@ -36,7 +34,6 @@ import com.rfsentinel.app.util.Permissionsimport com.rfsentinel.app.util.Prefsimport com.rfsentinel.app.util.ProximityUtilimport com.rfsentinel.app.util.applySystemBarInsets-import com.rfsentinel.app.whitelist.WhitelistActivityimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch@@ -46,6 +43,9 @@ class MainActivity : AppCompatActivity() {/** Row id prefix of the live cell tower rows (not devices). */private const val CELL_ROW = "cell:"private const val WAZE_ROW = "waze:"+ private const val RADIO_ROW = "radio:"+ /** A radio row flashes while its transmitter was heard this recently. */+ private const val RADIO_LIVE_MS = 15_000Lprivate const val BLUETOOTH_TAG_COLOR = 0xFF1565C0.toInt()private const val WIFI_TAG_COLOR = 0xFF00838F.toInt()private const val REFRESH_MS = 1_000L@@ -55,6 +55,7 @@ class MainActivity : AppCompatActivity() {private lateinit var binding: ActivityMainBindingprivate lateinit var adapter: DeviceAdapter+ private lateinit var panes: com.rfsentinel.app.ui.MainPanesprivate var filter = com.rfsentinel.app.ui.DeviceFilter.ALLprivate val filterChips = HashMap<com.rfsentinel.app.ui.DeviceFilter, com.google.android.material.chip.Chip>()private var query = ""@@ -84,6 +85,7 @@ class MainActivity : AppCompatActivity() {adapter = DeviceAdapter(onClick = {if (it.mac.startsWith(CELL_ROW)) startActivity(Intent(this, com.rfsentinel.app.ui.CellTowersActivity::class.java))+ else if (it.mac.startsWith(RADIO_ROW)) startActivity(Intent(this, com.rfsentinel.app.ui.DetectionLogActivity::class.java))else if (it.mac.startsWith(WAZE_ROW)) {com.rfsentinel.app.online.WazePolice.latest.firstOrNull { w -> WAZE_ROW + w.report.id == it.mac }?.let { w ->startActivity(Intent(this, com.rfsentinel.app.ui.MapActivity::class.java)@@ -93,10 +95,19 @@ class MainActivity : AppCompatActivity() {}else DeviceActions.openDetails(this, it.mac)},- onLongPress = { if (!it.mac.startsWith(CELL_ROW) && !it.mac.startsWith(WAZE_ROW)) DeviceActions.showQuickActions(this, it.mac) }+ onLongPress = { if (!it.mac.startsWith(CELL_ROW) && !it.mac.startsWith(WAZE_ROW) && !it.mac.startsWith(RADIO_ROW)) DeviceActions.showQuickActions(this, it.mac) })binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapter+ binding.newAlertPill.setOnClickListener {+ binding.recyclerView.smoothScrollToPosition(0)+ showNewAlertPill(false)+ }+ binding.recyclerView.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {+ override fun onScrolled(rv: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) {+ if (!rv.canScrollVertically(-1)) showNewAlertPill(false)+ }+ })binding.wazeSwipe.setColorSchemeColors(com.rfsentinel.app.ui.ChipStyle.accent(this).first)binding.wazeSwipe.setOnRefreshListener {if (com.rfsentinel.app.ui.WazeUi.checkNow(this)) {@@ -108,16 +119,21 @@ class MainActivity : AppCompatActivity() {// crossfade would make the whole list flicker and fight the match flash.(binding.recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = falsebinding.radarView.onBlipClick = { DeviceActions.openDetails(this, it) }+ panes = com.rfsentinel.app.ui.MainPanes(this, binding)+ binding.startStopButton.addOnLayoutChangeListener { _, l, _, r, _, ol, _, or, _ -> if (r - l != or - ol) fitStartButton() }binding.startStopButton.setOnClickListener {if (ScanForegroundService.isRunning) stopScanning() else requestPermissionsAndStart()}styleViewToggle()- binding.viewToggle.check(if (Prefs.radarView(this)) R.id.viewRadarButton else R.id.viewListButton)- binding.viewToggle.addOnButtonCheckedListener { _, id, checked ->- if (!checked) return@addOnButtonCheckedListener- Prefs.setRadarView(this, id == R.id.viewRadarButton)+ // Any mix of list, radar and live map: one fills the screen, more share it.+ for ((pane, id) in paneButtons) if (pane in panes.panes) binding.viewToggle.check(id)+ binding.viewToggle.addOnButtonCheckedListener { group, _, _ ->+ val chosen = paneButtons.filter { it.second in group.checkedButtonIds }.map { it.first }.toSet()+ if (chosen.isEmpty() || chosen == panes.panes) return@addOnButtonCheckedListener+ panes.setPanes(chosen)applyViewMode()+ render()}binding.toolsButton.setOnClickListener { v ->androidx.appcompat.widget.PopupMenu(this, v).apply {@@ -137,25 +153,15 @@ class MainActivity : AppCompatActivity() {}}.show()}- binding.mapButton.setOnClickListener {- startActivity(Intent(this, com.rfsentinel.app.ui.MapActivity::class.java))- }- // The disclaimer line at the bottom steps aside once the list is scrolled.- binding.recyclerView.addOnScrollListener(object : androidx.recyclerview.widget.RecyclerView.OnScrollListener() {- override fun onScrolled(rv: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) {- val atTop = !rv.canScrollVertically(-1)- if (dy > 8 && !atTop) binding.disclaimerText.visibility = View.GONE- else if (atTop) binding.disclaimerText.visibility = View.VISIBLE- }- })setupFilterChips()+ panes.setFilter(filter)// Debug builds only: made-up devices for screenshots (see DemoData).if (BuildConfig.DEBUG && intent.getBooleanExtra("demo", false)) {demoMode = true// So the Android Auto screens show the demo as a running scan too.ScanForegroundService.isRunning = true- intent.getStringExtra("view")?.let { Prefs.setRadarView(this, it == "radar") }+ intent.getStringExtra("view")?.split(',')?.toSet()?.let { Prefs.setViewPanes(this, it) }val demoLat = intent.getFloatExtra("lat", Float.NaN)val demoLon = intent.getFloatExtra("lon", Float.NaN)if (!demoLat.isNaN() && !demoLon.isNaN()) {@@ -183,6 +189,7 @@ class MainActivity : AppCompatActivity() {// Only on a real fresh start - a theme change recreates this screen too.if (savedInstanceState == null && !Prefs.onboardingDone(this)) showOnboarding()else if (savedInstanceState == null) com.rfsentinel.app.util.UpdateChecker.checkOnStartup(this)+ if (savedInstanceState == null) com.rfsentinel.app.util.CrashLog.offerAfterCrash(this)}override fun onResume() {@@ -190,6 +197,7 @@ class MainActivity : AppCompatActivity() {updateStatus()}+/** Styled themes: their own title, animated wordmark and the user's banner image. */private fun applyThemeHeader() {val theme = com.rfsentinel.app.ui.ThemeManager.current(this)@@ -219,13 +227,18 @@ class MainActivity : AppCompatActivity() {}}+ private val paneButtons get() = listOf("list" to R.id.viewListButton, "radar" to R.id.viewRadarButton, "map" to R.id.viewMapButton)+private fun applyViewMode() {- val radar = Prefs.radarView(this)- binding.radarView.visibility = if (radar) View.VISIBLE else View.GONE- binding.recyclerView.visibility = if (radar) View.GONE else View.VISIBLE- binding.wazeSwipe.visibility = if (radar) View.GONE else View.VISIBLE- binding.disclaimerText.visibility =- if (radar || !binding.recyclerView.canScrollVertically(-1)) View.VISIBLE else View.GONE+ panes.apply()+ // The "nothing heard" note sits over the list, or over the radar when there is no list.+ val home = if (!panes.listShown && panes.radarShown) binding.radarPane else binding.listFrame+ if (binding.emptyText.parent !== home) {+ (binding.emptyText.parent as? android.view.ViewGroup)?.removeView(binding.emptyText)+ home.addView(binding.emptyText, android.widget.FrameLayout.LayoutParams(+ android.widget.FrameLayout.LayoutParams.MATCH_PARENT, android.widget.FrameLayout.LayoutParams.WRAP_CONTENT,+ android.view.Gravity.CENTER))+ }}/** Filter chips from [com.rfsentinel.app.ui.DeviceFilter] (same rules as the map), counts filled in by render(). */@@ -235,6 +248,8 @@ class MainActivity : AppCompatActivity() {id = View.generateViewId()text = f.labelisCheckable = true+ // No invisible 48 dp touch frame around each chip: the row is 16 dp shorter.+ setEnsureMinTouchTargetSize(false)com.rfsentinel.app.ui.ChipStyle.apply(this)}filterChips[f] = chip@@ -243,6 +258,7 @@ class MainActivity : AppCompatActivity() {}binding.filterChips.setOnCheckedStateChangeListener { _, ids ->filter = filterChips.entries.firstOrNull { it.value.id == ids.firstOrNull() }?.key ?: return@setOnCheckedStateChangeListener+ panes.setFilter(filter)render()}}@@ -253,13 +269,11 @@ class MainActivity : AppCompatActivity() {val text = com.rfsentinel.app.ui.ChipStyle.onSurface(this)val checked = intArrayOf(android.R.attr.state_checked)val none = intArrayOf()- for (b in listOf(binding.viewListButton, binding.viewRadarButton)) {+ for (b in listOf(binding.viewListButton, binding.viewRadarButton, binding.viewMapButton)) {b.backgroundTintList = android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(accent, 0x00000000))b.iconTint = android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(onAccent, text))b.strokeColor = android.content.res.ColorStateList.valueOf(accent)}- binding.mapButton.iconTint = android.content.res.ColorStateList.valueOf(accent)- binding.mapButton.strokeColor = android.content.res.ColorStateList.valueOf(accent)binding.toolsButton.iconTint = android.content.res.ColorStateList.valueOf(accent)binding.toolsButton.strokeColor = android.content.res.ColorStateList.valueOf(accent)}@@ -273,9 +287,8 @@ class MainActivity : AppCompatActivity() {// Start: theme highlight with a play icon; Stop: red with a stop icon.val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)val red = com.rfsentinel.app.ui.ThemeManager.ink(this, 0xFFB3261E.toInt())- binding.startStopButton.text = if (running) "Stop" else "Start"binding.startStopButton.contentDescription = if (running) "Stop scanning" else "Start scanning"- binding.startStopButton.setIconResource(if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play)+ fitStartButton()binding.startStopButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (running) red else accent)val fg = if (running) 0xFFFFFFFF.toInt() else onAccentbinding.startStopButton.setTextColor(fg)@@ -295,7 +308,75 @@ class MainActivity : AppCompatActivity() {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() +- com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty()+ com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() ++ com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() ++ com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }+ ?.let { "\n$it" }.orEmpty()+ }+ }++ /**+ * Start / Stop with its icon when both fit; with large text the icon goes first, then the+ * word (the colour and the icon still tell them apart), so the label is never cut off.+ */+ private var startIconPadding = -1++ private fun fitStartButton() {+ val b = binding.startStopButton+ val running = shownRunning == true+ val label = if (running) "Stop" else "Start"+ val icon = if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play+ if (b.width == 0) { b.text = label; b.setIconResource(icon); return }+ val room = b.width - b.paddingStart - b.paddingEnd+ val drawn = b.transformationMethod?.getTransformation(label, b)?.toString() ?: label+ val textW = b.paint.measureText(drawn) + 2 * resources.displayMetrics.density+ if (startIconPadding < 0) startIconPadding = b.iconPadding+ val iconW = (b.iconSize.takeIf { it > 0 } ?: (24 * resources.displayMetrics.density).toInt()) + startIconPadding+ when {+ textW + iconW <= room -> { b.text = label; b.setIconResource(icon); b.iconPadding = startIconPadding }+ textW <= room -> { b.text = label; b.icon = null }+ else -> { b.text = ""; b.setIconResource(icon); b.iconPadding = 0 }+ }+ }++ /** Alerts (flagged rows) already shown, so a new one above the screen can be pointed out. */+ private var seenAlerts: Set<String> = emptySet()++ /**+ * At the top of the list, the list stays at the top: a new alert inserted above appears in+ * view instead of just off screen. Scrolled down, the rows you are reading stay put, and a+ * "New alert" pill shows instead; tap it (or scroll up) to see it.+ */+ private fun submitRows(rows: List<DeviceRow>) {+ val rv = binding.recyclerView+ val atTop = !rv.canScrollVertically(-1)+ val alerts = rows.filter { it.highlight != null || it.flashing }.map { it.mac }.toSet()+ val fresh = alerts - seenAlerts+ seenAlerts = alerts+ adapter.submitList(rows) {+ if (atTop) {+ rv.scrollToPosition(0)+ showNewAlertPill(false)+ } else if (fresh.isNotEmpty()) {+ val first = (rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()+ if (rows.withIndex().any { (i, r) -> r.mac in fresh && i < first }) showNewAlertPill(true)+ }+ }+ }++ private fun showNewAlertPill(show: Boolean) {+ val pill = binding.newAlertPill+ if (show == (pill.visibility == View.VISIBLE)) return+ if (show) {+ val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)+ pill.background = android.graphics.drawable.GradientDrawable().apply {+ cornerRadius = 18 * resources.displayMetrics.density; setColor(accent)+ }+ pill.setTextColor(onAccent)+ pill.alpha = 0f; pill.visibility = View.VISIBLE+ pill.animate().alpha(1f).setDuration(150).start()+ } else {+ pill.animate().alpha(0f).setDuration(150).withEndAction { pill.visibility = View.GONE }.start()}}@@ -334,11 +415,13 @@ class MainActivity : AppCompatActivity() {// Ordinary devices leave the list and radar soon after they're out of range (LiveWindow).val bleMs = Prefs.liveBleSec(this) * 1000Lval wifiMs = Prefs.liveWifiSec(this) * 1000L+ // Settings > Scanning: trusted (whitelisted) devices can be left out of the list and radar.+ val hideTrusted = Prefs.hideWhitelisted(this)val all = DeviceRegistry.snapshot(now).filter {- com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs)+ com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs) && !(hideTrusted && WhitelistCache.contains(it.mac))}val threshold = Prefs.alertThreshold(this)- binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && binding.radarView.visibility != View.VISIBLE+ binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && panes.listShowndeviceCount = all.size// The banner and radar alert only for flagged devices still in range.val flagged = all.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }@@ -351,6 +434,7 @@ class MainActivity : AppCompatActivity() {val n = when (f) {com.rfsentinel.app.ui.DeviceFilter.CELLS -> liveCellCount(now)com.rfsentinel.app.ui.DeviceFilter.WAZE -> currentWaze(now).size+ com.rfsentinel.app.ui.DeviceFilter.RADIO -> if (ScanForegroundService.isRunning) com.rfsentinel.app.sdr.RadioLog.current(now).size else 0else -> all.count { f.matches(it) }}val label = if (f == com.rfsentinel.app.ui.DeviceFilter.ALL || n > 0) "${f.label} $n" else f.label@@ -365,7 +449,9 @@ class MainActivity : AppCompatActivity() {.thenBy { it.firstSeen })- if (binding.radarView.visibility == View.VISIBLE) {+ // The map and radar frames take the top alert's colour.+ panes.update(flagged.maxByOrNull { it.best?.confidence ?: 0 }?.let { colorFor(it) })+ if (panes.radarShown) {binding.radarView.setBlips(visible.take(200).map { s ->val alert = com.rfsentinel.app.ui.LiveWindow.alerting(s, now)RadarView.Blip(@@ -375,20 +461,26 @@ class MainActivity : AppCompatActivity() {if (alert) s.best?.label else null)})- } else {+ }+ if (panes.listShown) {val cells = cellRows(now)val waze = wazeRows(now, threshold)- // Waze reports that meet the alert threshold flash at the very top; the rest follow the devices.+ val radio = radioRows(now, threshold)+ // Waze reports and radios on the air that meet the alert threshold flash at the very top;+ // the rest follow the devices.val (urgent, quiet) = waze.partition { it.flashing }- adapter.submitList(urgent + visible.map { toRow(it, now, threshold) } + cells + quiet)- shownCells = cells.size + waze.size+ val (radioLive, radioOld) = radio.partition { it.flashing }+ submitRows(radioLive + urgent + visible.map { toRow(it, now, threshold) } + radioOld + cells + quiet)+ shownCells = cells.size + waze.size + radio.size}- binding.emptyText.visibility = if (visible.isEmpty() && (binding.radarView.visibility == View.VISIBLE || shownCells == 0)) View.VISIBLE else View.GONE+ binding.emptyText.visibility = if (visible.isEmpty() && (!panes.listShown || shownCells == 0)) View.VISIBLE else View.GONEbinding.emptyText.text = when {all.isEmpty() && !ScanForegroundService.isRunning -> "Not scanning.\nTap Start scanning to begin."all.isEmpty() -> "Listening... no devices heard yet."filter == com.rfsentinel.app.ui.DeviceFilter.WAZE ->"No Waze reports in range.\nTurn on Waze police reports in Settings and keep scanning."+ filter == com.rfsentinel.app.ui.DeviceFilter.RADIO ->+ "No radio transmissions heard in the last 5 minutes.\nNeeds an RTL-SDR on USB and the Police radio category on in Settings."filter == com.rfsentinel.app.ui.DeviceFilter.CELLS ->"No cell towers yet - they're read every 15 s while scanning\n(needs the Fake cell tower category on in Settings)."else -> "No devices match this filter."@@ -457,6 +549,41 @@ class MainActivity : AppCompatActivity() {}}+ /**+ * RTL-SDR transmissions of the last few minutes (the radio log), under the All and Radio+ * filters: frequency, its name when known, signal and closer / farther trend. One on the air+ * right now at or above the alert threshold is tinted, flashes and is pinned to the top.+ */+ private fun radioRows(now: Long, threshold: Int): List<DeviceRow> {+ if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.RADIO) ||+ !ScanForegroundService.isRunning) return emptyList()+ val color = com.rfsentinel.app.ui.ThemeManager.ink(this, Category.RADIO.colorArgb)+ return com.rfsentinel.app.sdr.RadioLog.current(now)+ .filter { r -> query.isBlank() || listOfNotNull(r.mhz, r.name, r.bandLabel).any { it.contains(query.trim(), ignoreCase = true) } }+ .map { r ->+ val live = now - r.lastSeen <= RADIO_LIVE_MS+ val urgent = live && r.confidence >= threshold+ val ago = (now - r.lastSeen) / 1000+ val trend = when (r.trend) {+ com.rfsentinel.app.sdr.RadioLog.Trend.CLOSER -> "getting closer ↑"+ com.rfsentinel.app.sdr.RadioLog.Trend.FARTHER -> "moving away ↓"+ else -> null+ }+ DeviceRow(+ mac = RADIO_ROW + r.freqHz,+ title = "Radio ${r.mhz} MHz" + (r.name?.let { " · $it" } ?: ""),+ subtitle = listOfNotNull("${r.snrDb} dB above the noise (peak ${r.peakSnrDb})", trend, r.bandLabel).joinToString(" · "),+ meta = (if (ago < 3) "On the air now" else "Last heard ${ago}s ago") ++ " · first ${java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(r.firstSeen))}",+ tag = "RADIO · ${r.confidence}%",+ tagColor = color,+ highlight = if (urgent) color else null,+ flashing = urgent,+ bold = live+ )+ }+ }+private fun cellRows(now: Long): List<DeviceRow> {if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.CELLS) ||!ScanForegroundService.isRunning) return emptyList()@@ -651,14 +778,9 @@ class MainActivity : AppCompatActivity() {R.id.action_match_log -> { startActivity(Intent(this, DetectionLogActivity::class.java)); true }R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)); true }R.id.action_probes -> { startActivity(Intent(this, com.rfsentinel.app.probes.ProbeListActivity::class.java)); true }- R.id.action_whitelist -> { startActivity(Intent(this, WhitelistActivity::class.java)); true }- R.id.action_oui_list -> { startActivity(Intent(this, OuiListActivity::class.java)); true }R.id.action_export -> { Exporter.showExportMenu(this); true }- R.id.action_export_all -> { Exporter.showExportAll(this); true }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_check_update -> { com.rfsentinel.app.util.UpdateChecker.check(this); true }R.id.action_mute -> {val muted = !Prefs.alertsMuted(this)Prefs.setAlertsMuted(this, muted)diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.ktindex 7f65360..d315f6f 100644--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt@@ -25,6 +25,7 @@ class RFSentinelApp : Application() {override fun onCreate() {super.onCreate()+ com.rfsentinel.app.util.CrashLog.install(this)com.rfsentinel.app.ui.DeviceFilter.excludeAirTags = com.rfsentinel.app.util.Prefs.excludeAirTags(this)com.rfsentinel.app.ui.ThemeManager.install(this)com.rfsentinel.app.ui.ScreenAwake.install(this)diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.ktindex c725013..84d8178 100644--- a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt@@ -63,7 +63,7 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)companion object {/** The filters offered in the car (cell towers have their own screen). */- val CAR_FILTERS = DeviceFilter.entries.filter { it != DeviceFilter.CELLS && it != DeviceFilter.WAZE }+ val CAR_FILTERS = DeviceFilter.entries.filter { it != DeviceFilter.CELLS && it != DeviceFilter.WAZE && it != DeviceFilter.RADIO }fun titleOf(f: DeviceFilter) = when (f) {DeviceFilter.ALL -> "All nearby"diff --git a/app/src/main/java/com/rfsentinel/app/sdr/FreqNames.kt b/app/src/main/java/com/rfsentinel/app/sdr/FreqNames.ktnew file mode 100644index 0000000..f7832c2--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/FreqNames.kt@@ -0,0 +1,132 @@+package com.rfsentinel.app.sdr++import android.content.Context+import com.google.gson.Gson+import com.google.gson.reflect.TypeToken+import java.io.File++/**+ * Names for RTL-SDR hits: who is licensed or known to use a frequency. Two sources:+ * - a frequency list the user imports (CSV: RadioReference's export, CHIRP, or any file+ * with a frequency column and a name column), kept on the phone;+ * - FCC licences near you from RadioReference ([RadioReference]), cached per area.+ * A hit within ± the tolerance set in Settings takes the closest name.+ */+object FreqNames {++ data class Name(val hz: Long, val name: String, val source: String)++ private const val FILE = "freq_names.json"+ private val gson = Gson()+ private val type = object : TypeToken<List<Name>>() {}.type++ @Volatile private var imported: List<Name> = emptyList()+ @Volatile private var loaded = false+ /** RadioReference results for the area around you (replaced when you move on). */+ @Volatile var nearby: List<Name> = emptyList()++ val importedCount: Int get() = imported.size++ @Synchronized+ fun load(context: Context) {+ if (loaded) return+ imported = runCatching {+ File(context.filesDir, FILE).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<Name>>(it, type) }+ }.getOrNull().orEmpty()+ loaded = true+ }++ /** The closest name within [tolHz] of [hz]: the imported list first, then RadioReference. */+ fun lookup(hz: Long, tolHz: Long): Name? =+ closest(imported, hz, tolHz) ?: closest(nearby, hz, tolHz)++ internal fun closest(list: List<Name>, hz: Long, tolHz: Long): Name? =+ list.filter { kotlin.math.abs(it.hz - hz) <= tolHz }.minByOrNull { kotlin.math.abs(it.hz - hz) }++ /** Replaces the imported list; returns how many frequencies were read. */+ @Synchronized+ fun importCsv(context: Context, text: String, source: String): Int {+ val names = parseCsv(text, source)+ imported = names+ loaded = true+ runCatching { File(context.filesDir, FILE).writeText(gson.toJson(names)) }+ return names.size+ }++ @Synchronized+ fun clearImported(context: Context) {+ imported = emptyList()+ File(context.filesDir, FILE).delete()+ }++ /** A frequency list file, at most [max] bytes (a big RadioReference export is well under 1 MB). */+ fun readLimited(input: java.io.InputStream, max: Int = 8_000_000): String {+ val out = java.io.ByteArrayOutputStream()+ val buf = ByteArray(64 * 1024)+ while (out.size() < max) {+ val n = input.read(buf, 0, minOf(buf.size, max - out.size()))+ if (n < 0) break+ out.write(buf, 0, n)+ }+ return String(out.toByteArray(), Charsets.UTF_8)+ }++ // ---- CSV (pure; unit-tested) ----++ /** One CSV line into fields (quotes and doubled quotes handled). */+ internal fun fields(line: String): List<String> {+ val out = ArrayList<String>(); val sb = StringBuilder(); var q = false; var i = 0+ while (i < line.length) {+ val c = line[i]+ when {+ q && c == '"' && i + 1 < line.length && line[i + 1] == '"' -> { sb.append('"'); i++ }+ c == '"' -> q = !q+ !q && (c == ',' || c == ';' || c == '\t') -> { out += sb.toString().trim(); sb.clear() }+ else -> sb.append(c)+ }+ i+++ }+ out += sb.toString().trim()+ return out+ }++ private fun mhz(s: String): Long? {+ val v = s.replace(Regex("(?i)\\s*mhz"), "").replace(',', '.').toDoubleOrNull() ?: return null+ // Some exports give Hz or kHz.+ val m = when { v > 1_000_000 -> v / 1e6; v > 30_000 -> v / 1e3; else -> v }+ return if (m in 25.0..1800.0) (m * 1_000_000).toLong() else null+ }++ /**+ * Reads a frequency list. With a header row, the frequency is the "Frequency Output" /+ * "Frequency" / "Freq" column and the name is built from "Alpha Tag", "Description",+ * "Name", "Agency/Category", "FCC Callsign" or "Comment"; without one, the first column+ * that holds a frequency and the first text column.+ */+ fun parseCsv(text: String, source: String): List<Name> {+ val rows = text.lines().filter { it.isNotBlank() }.map { fields(it) }+ if (rows.isEmpty()) return emptyList()+ val head = rows.first().map { it.lowercase() }+ fun col(vararg keys: String) = keys.firstNotNullOfOrNull { k -> head.indexOfFirst { it == k }.takeIf { it >= 0 } }+ ?: keys.firstNotNullOfOrNull { k -> head.indexOfFirst { it.contains(k) }.takeIf { it >= 0 } }+ val freqCol = col("frequency output", "frequency", "freq", "output", "rx frequency")+ val hasHeader = freqCol != null && rows.first().getOrNull(freqCol)?.let { mhz(it) } == null+ val names = if (hasHeader) {+ val nameCols = listOfNotNull(col("description"), col("alpha tag", "alpha"), col("name"),+ col("agency/category", "agency", "category"), col("fcc callsign", "callsign"), col("comment")).distinct()+ rows.drop(1).mapNotNull { r ->+ val hz = r.getOrNull(freqCol!!)?.let { mhz(it) } ?: return@mapNotNull null+ val parts = nameCols.mapNotNull { r.getOrNull(it)?.takeIf { s -> s.isNotBlank() } }.distinct()+ Name(hz, parts.take(2).joinToString(" · ").ifEmpty { "%.4f MHz".format(java.util.Locale.US, hz / 1e6) }, source)+ }+ } else rows.mapNotNull { r ->+ val fi = r.indexOfFirst { mhz(it) != null }.takeIf { it >= 0 } ?: return@mapNotNull null+ val hz = mhz(r[fi])!!+ val name = r.filterIndexed { i, s -> i != fi && s.isNotBlank() && s.replace(',', '.').toDoubleOrNull() == null }.firstOrNull()+ Name(hz, name ?: "%.4f MHz".format(java.util.Locale.US, hz / 1e6), source)+ }+ // Names are shown in the list and spoken: keep them short.+ return names.map { if (it.name.length > 80) it.copy(name = it.name.take(80)) else it }+ .distinctBy { it.hz to it.name }.take(20_000)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioLog.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioLog.ktnew file mode 100644index 0000000..10d0b01--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioLog.kt@@ -0,0 +1,76 @@+package com.rfsentinel.app.sdr++/**+ * The RTL-SDR transmissions heard recently, one entry per frequency, for the main list: last+ * signal strength, strongest, and whether the transmitter is getting closer or farther. A+ * trend is called when the signal moved by at least the step set in Settings (in dB) since the+ * last call - signal strength only, so it's a rough guide (antenna, terrain and power all count).+ */+object RadioLog {++ enum class Trend { NEW, CLOSER, FARTHER, STEADY }++ data class Entry(+ val freqHz: Long,+ val bandLabel: String,+ val kind: RadioWatch.Kind,+ val firstSeen: Long,+ val lastSeen: Long,+ val snrDb: Int,+ val peakSnrDb: Int,+ val confidence: Int,+ /** From the imported frequency list or RadioReference, when one matched. */+ val name: String?,+ val trend: Trend,+ /** The signal when the trend was last called: the next call compares to it. */+ val refSnrDb: Int+ ) {+ val mhz: String get() = "%.4f".format(java.util.Locale.US, freqHz / 1e6)+ }++ /** A gap this long starts a new episode (a fresh "new", no trend from last time). */+ private const val EPISODE_GAP_MS = 90_000L+ /** Entries leave the list this long after they were last heard. */+ const val KEEP_MS = 5 * 60_000L++ private val entries = LinkedHashMap<Long, Entry>()++ /** Records a reading; returns CLOSER / FARTHER when that should be called out, else null. */+ @Synchronized+ fun observe(e: RadioWatch.Event, name: String?, stepDb: Int, now: Long): Trend? {+ val prev = entries[e.freqHz]+ if (prev == null || now - prev.lastSeen > EPISODE_GAP_MS) {+ entries[e.freqHz] = Entry(e.freqHz, e.band.label, e.band.kind, now, now, e.snrDb, e.snrDb, e.confidence,+ name, Trend.NEW, e.snrDb)+ prune(now)+ return null+ }+ val delta = e.snrDb - prev.refSnrDb+ val trend = when {+ stepDb > 0 && delta >= stepDb -> Trend.CLOSER+ stepDb > 0 && delta <= -stepDb -> Trend.FARTHER+ else -> null+ }+ entries[e.freqHz] = prev.copy(+ lastSeen = now, snrDb = e.snrDb, peakSnrDb = maxOf(prev.peakSnrDb, e.snrDb),+ confidence = maxOf(prev.confidence, e.confidence), name = name ?: prev.name,+ trend = trend ?: (if (prev.trend == Trend.NEW) Trend.STEADY else prev.trend),+ refSnrDb = if (trend != null) e.snrDb else prev.refSnrDb+ )+ return trend+ }++ /** Heard within [KEEP_MS], most recent first. */+ @Synchronized+ fun current(now: Long = System.currentTimeMillis()): List<Entry> {+ prune(now)+ return entries.values.sortedByDescending { it.lastSeen }+ }++ @Synchronized+ fun clear() = entries.clear()++ private fun prune(now: Long) {+ entries.values.removeAll { now - it.lastSeen > KEEP_MS }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioReference.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioReference.ktnew file mode 100644index 0000000..9c2153d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioReference.kt@@ -0,0 +1,158 @@+package com.rfsentinel.app.sdr++import android.content.Context+import com.rfsentinel.app.util.Prefs+import com.rfsentinel.app.util.SecureStore+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.net.HttpURLConnection+import java.net.URL++/**+ * Names RTL-SDR hits from RadioReference.com's database (Settings > RTL-SDR radio, off by+ * default): the FCC licences within a few km of you (fccGetProxCallsigns), then each licence's+ * frequencies (fccGetCallsign), so a hit within ± the tolerance gets the licensee's name.+ * Needs the user's own RadioReference Premium login and a RadioReference developer key (both+ * stored encrypted on the phone). What's sent: the login and your position rounded to ~1 km,+ * only when you're somewhere not looked up in the last day. FCC licences cover the US.+ */+object RadioReference {++ const val USER_KEY = "radioreference_user"+ const val PASS_KEY = "radioreference_password"+ const val APPKEY_KEY = "radioreference_appkey"++ private const val ENDPOINT = "https://api.radioreference.com/soap2/index.php"+ private const val NS = "http://api.radioreference.com/soap2"+ /** RadioReference asks to keep proximity searches under ~3 miles. */+ private const val RANGE_KM = 4.5+ private const val MAX_CALLSIGNS = 25+ private const val REFRESH_MS = 24 * 3600_000L++ @Volatile var status: String = ""; private set+ @Volatile private var lastArea: Pair<Double, Double>? = null+ @Volatile private var lastAreaAt = 0L+ @Volatile private var busy = false++ data class Auth(val user: String, val password: String, val appKey: String)++ fun auth(context: Context): Auth? {+ val u = SecureStore.get(context, USER_KEY)?.takeIf { it.isNotBlank() } ?: return null+ val p = SecureStore.get(context, PASS_KEY)?.takeIf { it.isNotBlank() } ?: return null+ val k = SecureStore.get(context, APPKEY_KEY)?.takeIf { it.isNotBlank() } ?: return null+ return Auth(u, p, k)+ }++ fun ready(context: Context) = Prefs.radioReferenceOn(context) && auth(context) != null++ /** ~1 km grid, so the exact position never leaves the phone. */+ fun snap(lat: Double, lon: Double) = Math.round(lat * 100) / 100.0 to Math.round(lon * 100) / 100.0++ /**+ * Looks up the licences around [lat] / [lon] unless that ~1 km area was done in the last day;+ * fills [FreqNames.nearby]. Safe to call on every hit.+ */+ suspend fun refreshAround(context: Context, lat: Double, lon: Double) {+ if (!ready(context) || busy) return+ val area = snap(lat, lon)+ if (area == lastArea && System.currentTimeMillis() - lastAreaAt < REFRESH_MS) return+ val a = auth(context) ?: return+ busy = true+ try {+ withContext(Dispatchers.IO) {+ status = "RadioReference: looking up licences near you…"+ val calls = proxCallsigns(a, area.first, area.second)+ val names = ArrayList<FreqNames.Name>()+ for (c in calls.take(MAX_CALLSIGNS)) {+ runCatching { callsignFreqs(a, c.callsign) }.getOrNull()?.forEach { hz ->+ names += FreqNames.Name(hz, "${c.licensee.take(60)} (${c.callsign}, %.1f km)".format(java.util.Locale.US, c.km), "RadioReference")+ }+ }+ FreqNames.nearby = names+ lastArea = area; lastAreaAt = System.currentTimeMillis()+ status = "RadioReference: ${calls.size} licences, ${names.size} frequencies near you"+ }+ } catch (e: Exception) {+ status = "RadioReference: " + (e.message ?: "lookup failed")+ } finally {+ busy = false+ }+ }++ /** Settings "Test login": one small query; returns a human answer. */+ suspend fun test(context: Context): String = withContext(Dispatchers.IO) {+ val a = auth(context) ?: return@withContext "Enter the username, password and developer key first"+ // Any position checks the login; 0,0 sends nothing about where you are.+ runCatching { proxCallsigns(a, 0.0, 0.0); "Login works" }.getOrElse { it.message ?: "Failed" }+ }++ data class Callsign(val callsign: String, val licensee: String, val km: Double)++ private fun proxCallsigns(a: Auth, lat: Double, lon: Double): List<Callsign> {+ val xml = call("fccGetProxCallsigns",+ "<lat xsi:type=\"xsd:decimal\">$lat</lat><lon xsi:type=\"xsd:decimal\">$lon</lon>" ++ "<range xsi:type=\"xsd:decimal\">$RANGE_KM</range><unit xsi:type=\"xsd:string\">k</unit>", a)+ return parseProx(xml)+ }++ private fun callsignFreqs(a: Auth, callsign: String): List<Long> =+ parseFrequencies(call("fccGetCallsign", "<callsign xsi:type=\"xsd:string\">${esc(callsign)}</callsign>", a))++ private fun esc(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """)++ /** One SOAP (rpc / encoded) call; throws with RadioReference's own message on a fault. */+ private fun call(op: String, params: String, a: Auth): String {+ val body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ++ "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"$NS\" " ++ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " ++ "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" ++ "<SOAP-ENV:Body><ns1:$op>$params<authInfo xsi:type=\"ns1:authInfo\">" ++ "<username xsi:type=\"xsd:string\">${esc(a.user)}</username><password xsi:type=\"xsd:string\">${esc(a.password)}</password>" ++ "<appKey xsi:type=\"xsd:string\">${esc(a.appKey)}</appKey><version xsi:type=\"xsd:string\">latest</version>" ++ "<style xsi:type=\"xsd:string\">rpc</style></authInfo></ns1:$op></SOAP-ENV:Body></SOAP-ENV:Envelope>"+ val conn = (URL(ENDPOINT).openConnection() as HttpURLConnection).apply {+ requestMethod = "POST"; doOutput = true; connectTimeout = 15_000; readTimeout = 30_000+ setRequestProperty("Content-Type", "text/xml; charset=utf-8")+ setRequestProperty("SOAPAction", "\"$NS#$op\"")+ }+ try {+ conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }+ val stream = if (conn.responseCode in 200..299) conn.inputStream else conn.errorStream ?: conn.inputStream+ val text = stream.use { String(it.readBytes(), Charsets.UTF_8) }+ fault(text)?.let { throw java.io.IOException(it) }+ return text+ } finally {+ conn.disconnect()+ }+ }++ // ---- response parsing (pure; unit-tested) ----++ /** The faultstring of a SOAP fault, or null. */+ fun fault(xml: String): String? {+ if (!xml.contains("Fault")) return null+ return Regex("<faultstring[^>]*>(.*?)</faultstring>", RegexOption.DOT_MATCHES_ALL).find(xml)?.groupValues?.get(1)?.trim()+ }++ /** The child elements' text of each <item> in the response (the answers are flat). */+ private fun items(xml: String): List<Map<String, String>> =+ Regex("<item\\b[^>]*>(.*?)</item>", RegexOption.DOT_MATCHES_ALL).findAll(xml).map { item ->+ Regex("<([A-Za-z0-9_]+)\\b[^>]*>([^<]*)</\\1>").findAll(item.groupValues[1])+ .associate { it.groupValues[1] to unescape(it.groupValues[2].trim()) }+ }.toList()++ private fun unescape(s: String) = s.replace("<", "<").replace(">", ">").replace(""", "\"")+ .replace("'", "'").replace("&", "&")++ fun parseProx(xml: String): List<Callsign> = items(xml).mapNotNull { m ->+ val cs = m["callsign"]?.takeIf { it.isNotBlank() } ?: return@mapNotNull null+ val dist = m["distance"]?.toDoubleOrNull() ?: 0.0+ Callsign(cs, m["licensee"]?.takeIf { it.isNotBlank() } ?: cs, dist)+ }.sortedBy { it.km }++ /** The frequencies (MHz → Hz) of an fccGetCallsign answer. */+ fun parseFrequencies(xml: String): List<Long> =+ Regex("<frequency[^>]*>([0-9.]+)</frequency>").findAll(xml)+ .mapNotNull { it.groupValues[1].toDoubleOrNull()?.let { mhz -> (mhz * 1_000_000).toLong() } }+ .filter { it in 25_000_000L..1_800_000_000L }.distinct().toList()+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.ktnew file mode 100644index 0000000..42d17c6--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt@@ -0,0 +1,68 @@+package com.rfsentinel.app.sdr++import android.content.Context+import com.rfsentinel.app.util.Prefs++/**+ * Settings > RTL-SDR radio, turned into a [RadioWatch.Config]: which built-in bands to sweep,+ * the user's own bands, excluded ranges and watched frequencies (typed one per line, in MHz),+ * and the sensitivity. Parsing is pure and unit-tested.+ */+object RadioSettings {++ /** Built-in bands, by Settings key. */+ val BUILT_IN = listOf(+ "700" to RadioWatch.BANDS[0], "800" to RadioWatch.BANDS[1],+ "vhf" to RadioWatch.BANDS[2], "uhf" to RadioWatch.BANDS[3]+ )++ /** The RTL-SDR tunes about 24 - 1766 MHz; more than this much custom spectrum makes a sweep crawl. */+ private const val MIN_HZ = 24_000_000L+ private const val MAX_HZ = 1_766_000_000L+ private const val MAX_CUSTOM_SPAN_HZ = 120_000_000L+ private const val MAX_TARGETS = 50++ fun config(context: Context): RadioWatch.Config {+ val off = Prefs.radioBandsOff(context)+ return RadioWatch.Config(+ bands = BUILT_IN.filter { it.first !in off }.map { it.second } + customBands(Prefs.radioCustomBands(context)),+ excluded = ranges(Prefs.radioExcluded(context)).map { it.first },+ targets = targets(Prefs.radioTargets(context)),+ minSnrDb = Prefs.radioMinSnr(context)+ )+ }++ private val RANGE = Regex("""^\s*(\d{2,4}(?:[.,]\d+)?)\s*(?:-|–|to)\s*(\d{2,4}(?:[.,]\d+)?)\s*(?:mhz)?\s*(.*)$""", RegexOption.IGNORE_CASE)+ private val FREQ = Regex("""^\s*(\d{2,4}(?:[.,]\d+)?)\s*(?:mhz)?\s*[,;:\-]?\s*(.*)$""", RegexOption.IGNORE_CASE)++ private fun mhzToHz(s: String): Long? = s.replace(',', '.').toDoubleOrNull()?.let { (it * 1_000_000).toLong() }++ /** "462-469 business band" lines → (range, label); lines that don't parse are skipped. */+ fun ranges(text: String): List<Pair<LongRange, String>> = text.lines().mapNotNull { line ->+ val m = RANGE.find(line) ?: return@mapNotNull null+ val a = mhzToHz(m.groupValues[1]) ?: return@mapNotNull null+ val b = mhzToHz(m.groupValues[2]) ?: return@mapNotNull null+ val lo = minOf(a, b).coerceAtLeast(MIN_HZ); val hi = maxOf(a, b).coerceAtMost(MAX_HZ)+ if (hi <= lo) null else (lo..hi) to m.groupValues[3].trim()+ }++ /** The user's bands, swept like the shared land-mobile bands; capped so a sweep stays quick. */+ fun customBands(text: String): List<RadioWatch.Band> {+ var span = 0L+ return ranges(text).mapNotNull { (r, label) ->+ val len = r.last - r.first+ if (span + len > MAX_CUSTOM_SPAN_HZ) return@mapNotNull null+ span += len+ RadioWatch.Band(label.ifEmpty { "Custom band %.3f-%.3f MHz".format(java.util.Locale.US, r.first / 1e6, r.last / 1e6) },+ r.first, r.last, RadioWatch.Kind.CUSTOM)+ }+ }++ /** "154.4300 County fire dispatch" lines → watched frequencies. */+ fun targets(text: String): List<RadioWatch.Target> = text.lines().mapNotNull { line ->+ if (RANGE.containsMatchIn(line)) return@mapNotNull null+ val m = FREQ.find(line) ?: return@mapNotNull null+ val hz = mhzToHz(m.groupValues[1])?.takeIf { it in MIN_HZ..MAX_HZ } ?: return@mapNotNull null+ RadioWatch.Target(hz, m.groupValues[2].trim().ifEmpty { "%.4f MHz".format(java.util.Locale.US, hz / 1e6) })+ }.distinctBy { it.freqHz }.take(MAX_TARGETS)+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.ktindex aff7ba7..dfe14fd 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt@@ -21,15 +21,34 @@ import kotlin.math.sin*/class RadioWatch {- enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED }+ enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED, CUSTOM, TARGET }data class Band(val label: String, val startHz: Long, val endHz: Long, val kind: Kind)- /** A strong transmission on a normally quiet channel. */- data class Event(val freqHz: Long, val snrDb: Int, val band: Band, val confidence: Int) {+ /** A frequency the user asked to watch (Settings > RTL-SDR radio): reported whenever it's active. */+ data class Target(val freqHz: Long, val label: String)++ /** What to watch and how sensitive (Settings > RTL-SDR radio); read at the start of every sweep. */+ data class Config(+ val bands: List<Band> = BANDS,+ /** The user's own excluded ranges (e.g. a business band), on top of the built-in ones. */+ val excluded: List<LongRange> = emptyList(),+ val targets: List<Target> = emptyList(),+ /** A transmission counts from this many dB above the noise (lower = more sensitive). */+ val minSnrDb: Int = DEFAULT_MIN_SNR+ )++ /**+ * A strong transmission on a normally quiet channel. [repeat]: the same channel again within+ * [REPEAT_MS] - not a new alert, but it keeps the live list and the closer / farther trend current.+ */+ data class Event(val freqHz: Long, val snrDb: Int, val band: Band, val confidence: Int,+ val target: Target? = null, val repeat: Boolean = false) {val mhz: String get() = "%.4f".format(java.util.Locale.US, freqHz / 1e6)}+ @Volatile var config = Config()+private class Channel {var visits = 0/** The last 32 visits, 1 = energy on the channel. */@@ -61,12 +80,13 @@ class RadioWatch {val floor = median(FloatArray(2 * usableBins) { psdDb[(n / 2 - usableBins + it).coerceIn(0, n - 1)] })val half = maxOf(1, (CHANNEL_HALF_HZ / binHz).roundToInt())val found = ArrayList<Event>()- for (band in BANDS) {+ val cfg = config+ for (band in cfg.bands) {var f = ((maxOf(band.startHz, centerHz - USABLE_HZ.toLong()) + STEP_HZ - 1) / STEP_HZ) * STEP_HZval last = minOf(band.endHz, centerHz + USABLE_HZ.toLong())while (f <= last) {val off = f - centerHz- if (kotlin.math.abs(off) > DC_GUARD_HZ && !excluded(f)) {+ if (kotlin.math.abs(off) > DC_GUARD_HZ && !excluded(f, cfg)) {val mid = n / 2 + (off / binHz).roundToInt()var p = -200ffor (k in mid - half..mid + half) if (k in 0 until n && psdDb[k] > p) p = psdDb[k]@@ -75,29 +95,46 @@ class RadioWatch {val active = snr >= ACTIVE_DBch.recent = (ch.recent shl 1) or (if (active) 1L else 0L)ch.visits++- if (active) eventFor(f, snr, band, ch, now)?.let { found += it }+ if (active) eventFor(f, snr, band, ch, now, cfg.minSnrDb)?.let { found += it }}f += STEP_HZ}}- // A strong signal spills into the channels next to it: keep the strongest of a cluster.- val kept = found.sortedByDescending { it.snrDb }.fold(ArrayList<Event>()) { acc, e ->- if (acc.none { kotlin.math.abs(it.freqHz - e.freqHz) <= SPLATTER_HZ }) acc += e- acc+ // Watched frequencies: any burst counts (no learning, no busy filter - the user asked for them).+ for (t in cfg.targets) {+ val off = t.freqHz - centerHz+ if (kotlin.math.abs(off) > USABLE_HZ || kotlin.math.abs(off) <= DC_GUARD_HZ) continue+ val mid = n / 2 + (off / binHz).roundToInt()+ var p = -200f+ for (k in mid - half..mid + half) if (k in 0 until n && psdDb[k] > p) p = psdDb[k]+ val snr = (p - floor).roundToInt()+ val st = targetState.getOrPut(t.freqHz) { Channel() }+ if (snr < maxOf(ACTIVE_DB, cfg.minSnrDb - 10)) continue+ found += Event(t.freqHz, snr, Band(t.label, t.freqHz, t.freqHz, Kind.TARGET), TARGET_CONFIDENCE, t,+ repeat = now - st.lastEvent < REPEAT_MS)}- for (e in kept) channels[e.freqHz]?.lastEvent = now+ // A strong signal spills into the channels next to it: keep the strongest of a cluster+ // (a watched frequency wins a tie).+ val kept = found.sortedWith(compareByDescending<Event> { it.snrDb }.thenByDescending { it.target != null })+ .fold(ArrayList<Event>()) { acc, e ->+ if (acc.none { kotlin.math.abs(it.freqHz - e.freqHz) <= SPLATTER_HZ }) acc += e+ acc+ }+ for (e in kept) if (!e.repeat) (if (e.target != null) targetState else channels)[e.freqHz]?.lastEvent = nowreturn kept}- private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long): Event? {+ private val targetState = HashMap<Long, Channel>()++ /** [min]: the sensitivity setting; at the default (30 dB) the thresholds are the original ones. */+ private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long, min: Int = DEFAULT_MIN_SNR): Event? {if (sweeps < LEARN_SWEEPS) return null // still learning what's always thereif (ch.visits >= MIN_VISITS_BUSY && ch.busyRatio() >= BUSY_RATIO) return null // tower / control channel / pager- if (now - ch.lastEvent < REPEAT_MS) return nullval confidence = when (band.kind) {- Kind.PUBLIC_SAFETY_MOBILE -> when { snr >= 40 -> 75; snr >= 30 -> 60; else -> return null }- Kind.SHARED -> when { snr >= 45 -> 55; snr >= 35 -> 35; else -> return null }+ Kind.PUBLIC_SAFETY_MOBILE -> when { snr >= min + 10 -> 75; snr >= min -> 60; else -> return null }+ else -> when { snr >= min + 15 -> 55; snr >= min + 5 -> 35; else -> return null }}- return Event(f, snr, band, confidence)+ return Event(f, snr, band, confidence, repeat = now - ch.lastEvent < REPEAT_MS)}companion object {@@ -112,6 +149,9 @@ class RadioWatch {private const val MIN_VISITS_BUSY = 6private const val LEARN_SWEEPS = 6 // = MIN_VISITS_BUSY: no alert before always-on channels are knownprivate const val REPEAT_MS = 120_000L+ /** Default sensitivity: 30 dB above the noise (the original public-safety threshold). */+ const val DEFAULT_MIN_SNR = 30+ private const val TARGET_CONFIDENCE = 70/** North American (FCC) public-safety land-mobile bands. */val BANDS = listOf(@@ -132,12 +172,22 @@ class RadioWatch {) + listOf(152_007_500L, 152_240_000L, 152_480_000L, 157_740_000L, 158_100_000L, 158_700_000L) // paging.map { it - 6_250L..it + 6_250L }- fun excluded(hz: Long) = EXCLUDED.any { hz in it }+ fun excluded(hz: Long, cfg: Config = Config()) = EXCLUDED.any { hz in it } || cfg.excluded.any { hz in it }- /** Tuning plan: chunk centres covering every band with the usable middle of the spectrum. */- fun plan(): List<Long> = BANDS.flatMap { b ->+ /**+ * Tuning plan: chunk centres covering every band with the usable middle of the spectrum,+ * plus a chunk for each watched frequency outside them.+ */+ fun plan(cfg: Config = Config()): List<Long> {val step = (2 * USABLE_HZ).toLong()- generateSequence(b.startHz + step / 2) { it + step }.takeWhile { it - step / 2 < b.endHz }.toList()+ val chunks = cfg.bands.flatMap { b ->+ generateSequence(b.startHz + step / 2) { it + step }.takeWhile { it - step / 2 < b.endHz }.toList()+ }.toMutableList()+ for (t in cfg.targets) {+ // Inside a chunk's usable middle but clear of its centre (DC): nothing to add.+ if (chunks.none { kotlin.math.abs(t.freqHz - it) in (DC_GUARD_HZ + 1)..USABLE_HZ.toLong() }) chunks += t.freqHz + step / 4+ }+ return chunks}private fun median(a: FloatArray): Float { a.sort(); return if (a.isEmpty()) 0f else a[a.size / 2] }diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex 6baa2f8..50660bf 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -26,6 +26,8 @@ object SdrRadio {private const val SETTLE_READS = 2 // samples after a retune are discarded@Volatile var status: String = ""; private set+ /** What to watch (Settings > RTL-SDR radio); picked up at the next sweep. */+ @Volatile var config = RadioWatch.Config()private var receiver: BroadcastReceiver? = nullprivate var onEvent: ((RadioWatch.Event) -> Unit)? = null@Volatile private var runningDevice: String? = null@@ -108,15 +110,22 @@ object SdrRadio {sdr.setSampleRate(SAMPLE_RATE)sdr.setGain(GAIN_TENTHS_DB)sdr.resetBuffer()- val plan = RadioWatch.plan()+ var cfg = config+ var plan = RadioWatch.plan(cfg)val watch = RadioWatch()- UsbWifi.log("RTL-SDR: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " +- RadioWatch.BANDS.joinToString { "%.1f-%.1f MHz".format(it.startHz / 1e6, it.endHz / 1e6) } + ", USB errors ${sdr.ctlErrors}")+ watch.config = cfg+ fun logPlan() = UsbWifi.log("RTL-SDR: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " ++ cfg.bands.joinToString { "%.1f-%.1f MHz".format(it.startHz / 1e6, it.endHz / 1e6) } ++ (if (cfg.targets.isNotEmpty()) ", ${cfg.targets.size} watched frequencies" else "") ++ ", reporting from ${cfg.minSnrDb} dB, USB errors ${sdr.ctlErrors}")+ logPlan()val buf = ByteArray(XFER)val iq = ByteArray(XFER * READS_PER_CHUNK)var lastLog = 0L; var sweepStart = System.currentTimeMillis(); var sweepMs = 0Lvar events = 0; var unlocked = 0; var readErrors = 0while (!stop) {+ // Settings changed: the new bands / targets / sensitivity from this sweep on.+ if (config != cfg) { cfg = config; plan = RadioWatch.plan(cfg); watch.config = cfg; logPlan() }for (center in plan) {if (stop) breakif (!sdr.tune(center)) { unlocked++; continue }@@ -130,8 +139,10 @@ object SdrRadio {if (got < 2 * 1024) continueval psd = RadioWatch.powerSpectrum(iq, got / 2)for (e in watch.analyze(center, psd, sdr.sampleRate, System.currentTimeMillis())) {- events++- UsbWifi.log("RTL-SDR: transmission ${e.mhz} MHz, ${e.snrDb} dB above the noise (${e.band.label})")+ if (!e.repeat) {+ events+++ UsbWifi.log("RTL-SDR: transmission ${e.mhz} MHz, ${e.snrDb} dB above the noise (${e.band.label})")+ }onEvent?.invoke(e)}}@@ -139,7 +150,7 @@ object SdrRadio {val now = System.currentTimeMillis()sweepMs = now - sweepStart; sweepStart = nowstatus = if (watch.sweeps < 6) "RTL-SDR · learning the radio bands here…"- else "RTL-SDR · watching police radio bands · $events transmissions nearby so far"+ else "RTL-SDR · live · sweep ${sweepMs / 100 / 10.0} s · $events transmissions nearby so far"if (now - lastLog > (if (watch.sweeps < 20) 10_000 else 60_000)) {lastLog = nowUsbWifi.log("RTL-SDR: sweep ${watch.sweeps} in $sweepMs ms, ${watch.learnedChannels} channels, ${watch.busyChannels} always busy, " +diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 6600f00..bb3bd03 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -280,7 +280,12 @@ class ScanForegroundService : Service() {// A USB WiFi adapter in monitor mode (e.g. AWUS036ACS): access points and client devices.com.rfsentinel.app.usb.UsbWifi.start(this) { list -> pipeline.post { list.forEach(::processUsbWifi) } }// An RTL-SDR dongle: strong two-way radio transmissions nearby (signal strength only).- if (Prefs.categoryEnabled(this, Category.RADIO)) com.rfsentinel.app.sdr.SdrRadio.start(this) { e -> pipeline.post { onRadio(e) } }+ if (Prefs.categoryEnabled(this, Category.RADIO)) {+ // Settings > RTL-SDR radio: bands, excluded ranges, watched frequencies, sensitivity (re-read on every refresh).+ com.rfsentinel.app.sdr.SdrRadio.config = com.rfsentinel.app.sdr.RadioSettings.config(this)+ com.rfsentinel.app.sdr.FreqNames.load(this)+ com.rfsentinel.app.sdr.SdrRadio.start(this) { e -> pipeline.post { onRadio(e) } }+ }else com.rfsentinel.app.sdr.SdrRadio.stop(this)// An OUI-SPY board paired over Bluetooth (App-Controlled firmware).Prefs.ouiSpyBoard(this)?.let { addr ->@@ -776,6 +781,12 @@ class ScanForegroundService : Service() {StatusWidget.updateAll(this@ScanForegroundService, devices.size, flagged)runCatching { TripRecorder.flush(this@ScanForegroundService) }.onFailure { Log.w(TAG, "Trace flush failed", it) }+ // Settings > Data > Live export: files another mapping app can read (every 30 s).+ runCatching {+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ com.rfsentinel.app.util.LiveExport.maybeWrite(this@ScanForegroundService, DeviceRegistry.sessionStart, lastLocation ?: lastFix)+ }+ }.onFailure { Log.w(TAG, "Live export failed", it) }if (System.currentTimeMillis() - lastHistoryFlush >= HISTORY_FLUSH_MS) {runCatching { flushHistory() }.onFailure { Log.w(TAG, "History flush failed", it) }}@@ -901,12 +912,31 @@ class ScanForegroundService : Service() {private fun onRadio(e: com.rfsentinel.app.sdr.RadioWatch.Event) {if (!Prefs.categoryEnabled(this, Category.RADIO)) returnval now = System.currentTimeMillis()+ // Who uses this frequency: a watched frequency's own label, the imported list, or RadioReference.+ val named = com.rfsentinel.app.sdr.FreqNames.lookup(e.freqHz, Prefs.radioMatchKhz(this) * 1000L)+ val name = e.target?.label ?: named?.name+ if (named == null && com.rfsentinel.app.sdr.RadioReference.ready(this)) (lastLocation ?: lastFix)?.let { l ->+ serviceScope.launch { com.rfsentinel.app.sdr.RadioReference.refreshAround(this@ScanForegroundService, l.latitude, l.longitude) }+ }+ val threshold = Prefs.alertThreshold(this)+ val trend = com.rfsentinel.app.sdr.RadioLog.observe(e, name, Prefs.radioTrendDb(this), now)+ if (trend != null && e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {+ AlertPlayer.callout(this, "Radio ${spokenMhz(e.freqHz)} " ++ if (trend == com.rfsentinel.app.sdr.RadioLog.Trend.CLOSER) "getting closer" else "moving away")+ }+ if (e.repeat) return // same channel within 2 minutes: list and trend only, no new log entry or alertval near = when { e.snrDb >= 40 -> "very close"; e.snrDb >= 30 -> "close" else -> "nearby" }val detail = "A radio transmitted on ${e.mhz} MHz (${e.band.label}), ${e.snrDb} dB above the noise - $near. " +- if (e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.PUBLIC_SAFETY_MOBILE)- "Public-safety radios (police, fire, EMS) transmit on this band; not proof of who it is."- else "Police use this band, but so do businesses, schools and transit; a weak sign on its own."- val hit = Hit(Category.RADIO, "Two-way radio transmitting nearby", e.confidence, detail, "RTL-SDR signal strength (no decoding)")+ (named?.let { "Matches ${"%.4f".format(java.util.Locale.US, it.hz / 1e6)} MHz: ${it.name} (${it.source}). " } ?: "") ++ when (e.band.kind) {+ com.rfsentinel.app.sdr.RadioWatch.Kind.PUBLIC_SAFETY_MOBILE ->+ "Public-safety radios (police, fire, EMS) transmit on this band; not proof of who it is."+ com.rfsentinel.app.sdr.RadioWatch.Kind.TARGET -> "One of the frequencies you watch (Settings > RTL-SDR radio)."+ com.rfsentinel.app.sdr.RadioWatch.Kind.CUSTOM -> "A band you added in Settings > RTL-SDR radio."+ else -> "Police use this band, but so do businesses, schools and transit; a weak sign on its own."+ }+ val label = name?.let { "Radio transmitting: $it" } ?: "Two-way radio transmitting nearby"+ val hit = Hit(Category.RADIO, label, e.confidence, detail, "RTL-SDR signal strength (no decoding)")val loc = lastLocationval tag = Prefs.gpsTaggingEnabled(this)serviceScope.launch {@@ -919,12 +949,19 @@ class ScanForegroundService : Service() {))}- if (e.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {+ if (e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)- AlertPlayer.play(this, hit.tier, "Radio transmitting nearby")+ // Spoken: the frequency (and its name) when that's on, else the short phrase.+ val spoken = if (Prefs.radioSpeakFreq(this)) "Radio ${spokenMhz(e.freqHz)}" + (name?.let { ", $it" } ?: "")+ else "Radio transmitting nearby"+ AlertPlayer.play(this, hit.tier, spoken)}}+ /** "154.43" for 154.430 MHz: three decimals, trailing zeros dropped, read well by the voice. */+ private fun spokenMhz(hz: Long): String =+ "%.3f".format(java.util.Locale.US, hz / 1e6).trimEnd('0').trimEnd('.')+/** Police aircraft (ADS-B) and Waze reports: internet sources, both off by default. */private val onlineWatch by lazy {com.rfsentinel.app.online.OnlineWatch(this, serviceScope, { lastLocation ?: lastFix },diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex a1862f2..6c48c9c 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -290,6 +290,14 @@ class SettingsActivity : AppCompatActivity() {/** A foldable settings section: its header, its content and what the ⓘ button explains. */private class Section(val key: String, val header: android.widget.TextView, val body: View, val info: String)+ /** A folded section on screen, for the search: its header row, divider, body and fold state. */+ private class SectionUi(+ val title: String, val info: String, val row: View, val divider: View?, val body: View,+ val restore: () -> Unit, val expand: () -> Unit+ )++ private val sectionUi = mutableListOf<SectionUi>()+private fun sections() = listOf(Section("general", binding.headerGeneral, binding.sectionGeneral,"Setup wizard: walks through the permissions and main choices again.\n\n" +@@ -305,6 +313,7 @@ class SettingsActivity : AppCompatActivity() {"is turned off in Developer options; then down to 5 s works, at some battery cost.\n\n" +"Background scanning: lets the scan keep running with the screen off.\n\n" +"Remove from the list: how long an ordinary device stays in the list and radar once it stops being heard (default 30 s Bluetooth, 60 s WiFi). Flagged devices follow these too; favourite and following devices stay 3 minutes. " ++ "Hide trusted devices: whitelisted devices are left out of the list and radar (they stay in the history). " +"Both can go down to 5 s (WiFi only when Developer options are on and the WiFi interval is under 30 s)."),Section("autostart", binding.headerAutoStart, binding.sectionAutoStart,"When the phone starts: begins scanning after a reboot.\n\n" +@@ -393,18 +402,43 @@ class SettingsActivity : AppCompatActivity() {"• USB WiFi adapters in monitor mode: longer range, and they hear devices connected to networks. " +"RTL8811AU / 8821AU (ALFA AWUS036ACS), RTL8812BU / 8822BU, RTL8814AU (AWUS1900), MT7612U (AWUS036ACM), " +"RTL8187 (AWUS036H), RT3070 (AWUS036NH / NEH), AR9271 (AWUS036NHA, experimental).\n\n" ++ "AWUS036ACS 5 GHz (experimental, off by default): the RTL8811AU / 8821AU also hops 5 GHz channels 36-48 and " ++ "149-165. Untested on every unit: if it misbehaves, turn it off and send the adapter log. Applies when the adapter is plugged in.\n\n" +"• RTL-SDR dongle: notices two-way radios transmitting nearby (signal strength only, nothing is decoded).\n\n" +"OUI-SPY over Bluetooth needs its App-Controlled firmware. Relay mode passes on every network and device it hears " +"so RF Sentinel's own lists check them (the board also sends standard Wi-Fi scan probes).\n\n" +"Adapter not working? Export its log and send it to the developer."),+ Section("radio", binding.headerRadio, binding.sectionRadio,+ "An RTL-SDR dongle on USB notices two-way radios transmitting nearby, from signal strength only - nothing is " ++ "decoded or recorded. Needs the Police radio category on (What to detect).\n\n" ++ "Sensitivity: how far above the noise a burst must be to count. Lower hears farther radios, and more false alarms.\n\n" ++ "Bands: the built-in North American public-safety bands, your own bands (one per line, \"380-400 TETRA\"), " ++ "ranges never to report (\"462-469 business band\"), and frequencies to watch (\"154.4300 County fire\"), " ++ "which are reported whenever they're active.\n\n" ++ "Hits show in the main list (Radio filter). Closer / moving away: called out when the signal changes by the set " ++ "amount - a rough guide only.\n\n" ++ "Frequency names: import a CSV (RadioReference's export, CHIRP, or any file with a frequency and a name column), " ++ "or let RadioReference name the FCC licences near you (US): needs your own RadioReference Premium login and a " ++ "RadioReference developer key; your position rounded to ~1 km is sent to RadioReference, at most once a day per area.\n\n" ++ "Changes apply from the next sweep while scanning."),Section("location", binding.headerLocation, binding.sectionLocation,"Traces: records your route while scanning, to view on the map.\n\n" +"Saving the GPS position with matches is privacy-sensitive: the log then shows where you were. It also lets the map remember where it last looked, so it can open there before the GPS answers."),Section("data", binding.headerData, binding.sectionData,"Everything stays on this phone. History older than the set number of days is deleted (0 keeps it forever).\n\n" ++ "Live export (off by default): while scanning, rewrites three files every 30 s in the folder you choose - " ++ "rfsentinel_live_matches.csv, rfsentinel_live_matches.kml and rfsentinel_live.geojson (devices on the map and " ++ "your position) - so another mapping app can show them close to live. Anything that can read that folder can read them.\n\n" +"Forget device history: new / returning status, detect counts and the cell towers remembered for the " +"fake-cell checks start over. Favorites are kept.\n\n" +- "Changes on this screen are saved automatically.")+ "Changes on this screen are saved automatically."),+ Section("more", binding.headerMore, binding.sectionMore,+ "Watchlist & rules: the vendor prefixes and rules that flag a device; add your own.\n\n" ++ "Whitelist: devices you trust, never flagged.\n\n" ++ "Check for updates: asks GitHub for a newer version now.\n\n" ++ "About & sources: version, licence, where the signatures come from, and the app's limits.\n\n" ++ "Crash log: if RF Sentinel ever closes unexpectedly, what went wrong is saved on this phone (never sent " ++ "automatically). Export it to send to the developer; the app also offers this the next time it opens."))/** Folds each section under a tappable header (remembered) with an ⓘ button for the details. */@@ -443,8 +477,9 @@ class SettingsActivity : AppCompatActivity() {}parent.addView(row, at, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT))- if (i > 0) parent.addView(View(this).apply { setBackgroundColor(divider) }, at,- android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, maxOf(1, dp.toInt())))+ val dividerView = if (i == 0) null else View(this).apply { setBackgroundColor(divider) }+ dividerView?.let { parent.addView(it, at,+ android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, maxOf(1, dp.toInt()))) }s.body.setPadding(0, 0, 0, (10 * dp).toInt())val requested = intent.getStringExtra(EXTRA_SECTION) == s.keyif (requested) ui.edit().putBoolean(s.key, true).apply()@@ -462,6 +497,293 @@ class SettingsActivity : AppCompatActivity() {ui.edit().putBoolean(s.key, open).apply()show()}+ sectionUi += SectionUi(title, s.info, row, dividerView, s.body, restore = { show() }, expand = {+ s.body.visibility = View.VISIBLE+ s.header.text = "▾ $title"+ })+ }+ }++ // ---- Search ----------------------------------------------------------------------------++ /** Views tinted as search matches, with the background they had before. */+ private val highlighted = mutableListOf<Pair<View, android.graphics.drawable.Drawable?>>()+ private lateinit var searchInput: android.widget.EditText++ /** The search field pinned above the scrolling settings (with a clear button). */+ private fun searchBar(): View {+ val dp = resources.displayMetrics.density+ searchInput = android.widget.EditText(this).apply {+ hint = "Search settings"+ isSingleLine = true+ inputType = android.text.InputType.TYPE_CLASS_TEXT+ imeOptions = android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH+ setCompoundDrawablesRelativeWithIntrinsicBounds(android.R.drawable.ic_menu_search, 0, 0, 0)+ compoundDrawablePadding = (6 * dp).toInt()+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO+ }+ val clear = android.widget.TextView(this).apply {+ text = "✕"+ textSize = 18f+ setPadding((12 * dp).toInt(), (8 * dp).toInt(), (12 * dp).toInt(), (8 * dp).toInt())+ contentDescription = "Clear search"+ visibility = View.GONE+ setOnClickListener { searchInput.setText("") }+ }+ // Back only puts the keyboard away (the search stays); the keyboard's search key does too.+ searchInput.setOnEditorActionListener { v, actionId, _ ->+ if (actionId != android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) return@setOnEditorActionListener false+ getSystemService(android.view.inputmethod.InputMethodManager::class.java)?.hideSoftInputFromWindow(v.windowToken, 0)+ true+ }+ searchInput.addTextChangedListener(object : android.text.TextWatcher {+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}+ override fun afterTextChanged(s: android.text.Editable?) {+ val q = s?.toString().orEmpty()+ clear.visibility = if (q.isEmpty()) View.GONE else View.VISIBLE+ filterSettings(q)+ }+ })+ return android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ gravity = android.view.Gravity.CENTER_VERTICAL+ setPadding((16 * dp).toInt(), (4 * dp).toInt(), (4 * dp).toInt(), 0)+ addView(searchInput, android.widget.LinearLayout.LayoutParams(0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1f))+ addView(clear)+ }+ }++ /**+ * Shows only the sections with a setting (or ⓘ text) matching [raw], unfolded, tints the+ * matching settings and scrolls to the first one. Empty: everything back as it was.+ */+ private fun filterSettings(raw: String) {+ highlighted.forEach { (v, bg) -> v.background = bg }+ highlighted.clear()+ val q = raw.trim().lowercase()+ if (q.isEmpty()) {+ sectionUi.forEach { it.row.visibility = View.VISIBLE; it.divider?.visibility = View.VISIBLE; it.restore() }+ return+ }+ val tint = androidx.core.graphics.ColorUtils.setAlphaComponent(+ com.google.android.material.color.MaterialColors.getColor(binding.root, androidx.appcompat.R.attr.colorPrimary), 0x40)+ var first: View? = null+ for (s in sectionUi) {+ val hits = mutableListOf<View>()+ collectMatches(s.body, q, hits)+ val show = hits.isNotEmpty() || s.title.lowercase().contains(q) || s.info.lowercase().contains(q)+ s.row.visibility = if (show) View.VISIBLE else View.GONE+ s.divider?.visibility = s.row.visibility+ if (!show) { s.body.visibility = View.GONE; continue }+ s.expand()+ for (v in hits) {+ highlighted += v to v.background+ v.background = android.graphics.drawable.ColorDrawable(tint)+ }+ if (first == null) first = hits.firstOrNull() ?: s.row+ }+ val target = first ?: return+ binding.root.post {+ if (isFinishing) return@post+ val content = binding.root.getChildAt(0) as? android.view.ViewGroup ?: return@post+ val r = android.graphics.Rect()+ target.getDrawingRect(r)+ runCatching { content.offsetDescendantRectToMyCoords(target, r) }.onSuccess {+ binding.root.scrollTo(0, maxOf(0, r.top - (24 * resources.displayMetrics.density).toInt()))+ }+ }+ }++ /** Visible settings under [v] whose label, text or hint contains [q]. */+ private fun collectMatches(v: View, q: String, out: MutableList<View>) {+ if (v is android.view.ViewGroup) {+ for (i in 0 until v.childCount) {+ val c = v.getChildAt(i)+ if (c.visibility == View.VISIBLE) collectMatches(c, q, out)+ }+ } else if (v is android.widget.TextView) {+ val text = v.text?.toString().orEmpty().lowercase()+ val hint = v.hint?.toString().orEmpty().lowercase()+ if (text.contains(q) || hint.contains(q)) out += v+ }+ }++ // ---- RTL-SDR radio -------------------------------------------------------------------++ private val freqListPicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->+ if (uri == null) return@registerForActivityResult+ lifecycleScope.launch {+ val n = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ runCatching {+ val text = contentResolver.openInputStream(uri)?.use { com.rfsentinel.app.sdr.FreqNames.readLimited(it) }.orEmpty()+ com.rfsentinel.app.sdr.FreqNames.importCsv(this@SettingsActivity, text, "your list")+ }.getOrDefault(-1)+ }+ Toast.makeText(this@SettingsActivity,+ if (n > 0) "$n frequencies imported" else "No frequencies found in that file (needs a frequency column in MHz)",+ Toast.LENGTH_LONG).show()+ updateFreqListText()+ }+ }++ private var freqListText: android.widget.TextView? = null++ private fun updateFreqListText() {+ val n = com.rfsentinel.app.sdr.FreqNames.importedCount+ freqListText?.text = if (n == 0) "No frequency list imported" else "$n named frequencies imported"+ }++ /** Settings > RTL-SDR radio, built in code; everything is saved as you change it. */+ private fun setupRadioSection() {+ val box = binding.sectionRadio+ val dp = resources.displayMetrics.density+ fun label(t: String, small: Boolean = false) = android.widget.TextView(this).apply {+ text = t; textSize = if (small) 12f else 14f+ if (small) alpha = 0.75f+ setPadding(0, (if (small) 0 else 10 * dp).toInt(), 0, (2 * dp).toInt())+ }.also { box.addView(it) }+ fun slider(from: Int, to: Int, value: Int, text: (Int) -> String, save: (Int) -> Unit) {+ val l = label(text(value))+ box.addView(com.google.android.material.slider.Slider(this).apply {+ valueFrom = from.toFloat(); valueTo = to.toFloat(); stepSize = 1f+ this.value = value.coerceIn(from, to).toFloat()+ contentDescription = text(value)+ addOnChangeListener { _, v, fromUser -> if (fromUser) { save(v.toInt()); l.text = text(v.toInt()) } }+ })+ }+ fun lines(title: String, hint: String, value: String, save: (String) -> Unit) {+ label(title)+ box.addView(android.widget.EditText(this).apply {+ setText(value); this.hint = hint+ minLines = 2; maxLines = 8; gravity = android.view.Gravity.TOP+ inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO+ addTextChangedListener(object : android.text.TextWatcher {+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}+ override fun afterTextChanged(s: android.text.Editable?) { save(s?.toString().orEmpty()) }+ })+ })+ }+ fun switch(t: String, on: Boolean, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {+ text = t; isChecked = on+ setOnCheckedChangeListener { _, v -> save(v) }+ }.also { box.addView(it) }++ slider(15, 50, Prefs.radioMinSnr(this), { "Sensitivity: report a radio from $it dB above the noise (lower = hears farther, more false alarms)" }) {+ Prefs.setRadioMinSnr(this, it)+ }+ label("Bands to sweep")+ val off = Prefs.radioBandsOff(this).toMutableSet()+ for ((key, band) in com.rfsentinel.app.sdr.RadioSettings.BUILT_IN) {+ box.addView(android.widget.CheckBox(this).apply {+ text = "%s (%.1f-%.1f MHz)".format(java.util.Locale.US, band.label, band.startHz / 1e6, band.endHz / 1e6)+ isChecked = key !in off+ setOnCheckedChangeListener { _, on ->+ if (on) off -= key else off += key+ Prefs.setRadioBandsOff(this@SettingsActivity, off.toSet())+ }+ })+ }+ lines("Your own bands (one per line, in MHz)", "380-400 TETRA\n220-222", Prefs.radioCustomBands(this)) { Prefs.setRadioCustomBands(this, it) }+ lines("Never report these ranges", "462-469 business band\n151.8-152.0", Prefs.radioExcluded(this)) { Prefs.setRadioExcluded(this, it) }+ lines("Watch these frequencies (always reported when active)", "154.4300 County fire dispatch\n460.125", Prefs.radioTargets(this)) { Prefs.setRadioTargets(this, it) }+ switch("Say the frequency (and its name) instead of \"Radio transmitting nearby\"", Prefs.radioSpeakFreq(this)) { Prefs.setRadioSpeakFreq(this, it) }+ slider(0, 20, Prefs.radioTrendDb(this), { if (it == 0) "Closer / moving away: off" else "Say \"getting closer\" / \"moving away\" when the signal changes by $it dB" }) {+ Prefs.setRadioTrendDb(this, it)+ }+ slider(1, 50, Prefs.radioMatchKhz(this), { "A hit takes a frequency's name within ± $it kHz" }) { Prefs.setRadioMatchKhz(this, it) }++ label("Frequency names")+ freqListText = label("", small = true)+ com.rfsentinel.app.sdr.FreqNames.load(this)+ updateFreqListText()+ box.addView(android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ addView(com.google.android.material.button.MaterialButton(this@SettingsActivity, null,+ android.R.attr.borderlessButtonStyle).apply {+ text = "Import CSV"+ setOnClickListener { freqListPicker.launch(arrayOf("text/*", "application/csv", "application/vnd.ms-excel", "*/*")) }+ })+ addView(com.google.android.material.button.MaterialButton(this@SettingsActivity, null,+ android.R.attr.borderlessButtonStyle).apply {+ text = "Clear list"+ setOnClickListener { com.rfsentinel.app.sdr.FreqNames.clearImported(this@SettingsActivity); updateFreqListText() }+ })+ })++ val rrSwitch = switch("Name hits from RadioReference (your own Premium login)", Prefs.radioReferenceOn(this)) {+ Prefs.setRadioReferenceOn(this, it)+ }+ fun secret(title: String, key: String, password: Boolean) {+ box.addView(android.widget.EditText(this).apply {+ hint = title+ setText(com.rfsentinel.app.util.SecureStore.get(this@SettingsActivity, key).orEmpty())+ isSingleLine = true+ inputType = android.text.InputType.TYPE_CLASS_TEXT or+ (if (password) android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD else android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO+ setOnFocusChangeListener { v, has ->+ if (!has) com.rfsentinel.app.util.SecureStore.put(this@SettingsActivity, key, (v as android.widget.EditText).text.toString().trim())+ }+ secretFields += this to key+ })+ }+ secret("RadioReference username (not your email)", com.rfsentinel.app.sdr.RadioReference.USER_KEY, false)+ secret("RadioReference password", com.rfsentinel.app.sdr.RadioReference.PASS_KEY, true)+ secret("RadioReference developer key", com.rfsentinel.app.sdr.RadioReference.APPKEY_KEY, true)+ val rrStatus = label(com.rfsentinel.app.sdr.RadioReference.status.ifEmpty { "Stored encrypted on this phone." }, small = true)+ box.addView(com.google.android.material.button.MaterialButton(this, null, android.R.attr.borderlessButtonStyle).apply {+ text = "Test login"+ setOnClickListener {+ saveSecrets()+ rrStatus.text = "Checking…"+ lifecycleScope.launch { rrStatus.text = com.rfsentinel.app.sdr.RadioReference.test(this@SettingsActivity) }+ }+ })+ rrSwitch.isChecked = Prefs.radioReferenceOn(this)+ }++ /** The RadioReference fields, saved (encrypted) when they lose focus and when leaving Settings. */+ private val secretFields = mutableListOf<Pair<android.widget.EditText, String>>()++ private fun saveSecrets() {+ for ((field, key) in secretFields) com.rfsentinel.app.util.SecureStore.put(this, key, field.text.toString().trim())+ }++ // ---- Live export (Settings > Data) ---------------------------------------------------++ private val liveExportFolder = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocumentTree()) { uri ->+ if (uri == null) { if (Prefs.liveExportTree(this) == null) binding.liveExportSwitch.isChecked = false; return@registerForActivityResult }+ runCatching {+ contentResolver.takePersistableUriPermission(uri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ }+ Prefs.setLiveExportTree(this, uri.toString())+ com.rfsentinel.app.util.LiveExport.reset()+ updateLiveExportText()+ }++ private fun setupLiveExport() {+ binding.liveExportSwitch.isChecked = Prefs.liveExport(this)+ binding.liveExportSwitch.setOnCheckedChangeListener { _, on ->+ Prefs.setLiveExport(this, on)+ if (on && Prefs.liveExportTree(this) == null) liveExportFolder.launch(null)+ updateLiveExportText()+ }+ binding.liveExportFolderButton.setOnClickListener { liveExportFolder.launch(null) }+ updateLiveExportText()+ }++ private fun updateLiveExportText() {+ val tree = Prefs.liveExportTree(this)?.let { android.net.Uri.parse(it) }+ val folder = tree?.let { runCatching { android.provider.DocumentsContract.getTreeDocumentId(it).substringAfter(':') }.getOrNull() }+ binding.liveExportText.text = when {+ !Prefs.liveExport(this) -> "Off"+ tree == null -> "Choose a folder"+ else -> "Folder: ${folder?.ifEmpty { "storage root" } ?: tree}" ++ com.rfsentinel.app.util.LiveExport.status.takeIf { it.isNotEmpty() }?.let { "\n$it" }.orEmpty()}}@@ -880,8 +1202,17 @@ class SettingsActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivitySettingsBinding.inflate(layoutInflater)- setContentView(binding.root)- binding.root.applySystemBarInsets()+ // The search field stays pinned above the scrolling settings.+ val page = android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.VERTICAL+ // The page holds focus, so opening Settings doesn't pop the keyboard up.+ isFocusableInTouchMode = true+ addView(searchBar())+ addView(binding.root, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))+ }+ setContentView(page)+ page.applySystemBarInsets()+ page.requestFocus()title = "Settings"supportActionBar?.setDisplayHomeAsUpEnabled(true)@@ -1101,6 +1432,12 @@ class SettingsActivity : AppCompatActivity() {binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)setupMapSection()+ setupRadioSection()+ setupLiveExport()+ binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)+ binding.hideTrustedSwitch.setOnCheckedChangeListener { _, on -> Prefs.setHideWhitelisted(this, on) }+ binding.rtl5gSwitch.isChecked = Prefs.rtl8821au5g(this)+ binding.rtl5gSwitch.setOnCheckedChangeListener { _, on -> Prefs.setRtl8821au5g(this, on) }binding.autoUpdateSwitch.isChecked = Prefs.autoUpdateCheck(this)fun showRadius(km: Int) {binding.cameraRadiusText.text = "Download radius: $km km"@@ -1147,6 +1484,16 @@ class SettingsActivity : AppCompatActivity() {// Databinding.retentionInput.setText(Prefs.retentionDays(this).toString())binding.exportAllButton.setOnClickListener { com.rfsentinel.app.util.Exporter.showExportMenu(this) }+ // Lists, tools & about (moved here from the main screen's menu).+ binding.openWatchlistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ouilist.OuiListActivity::class.java)) }+ binding.openWhitelistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.whitelist.WhitelistActivity::class.java)) }+ binding.checkUpdateButton.setOnClickListener { com.rfsentinel.app.util.UpdateChecker.check(this) }+ binding.aboutButton.setOnClickListener { com.rfsentinel.app.ui.AboutDialog.show(this) }+ binding.exportCrashLogButton.setOnClickListener { com.rfsentinel.app.util.CrashLog.share(this) }+ binding.clearCrashLogButton.setOnClickListener {+ com.rfsentinel.app.util.CrashLog.clear(this)+ Toast.makeText(this, "Crash log cleared", Toast.LENGTH_SHORT).show()+ }binding.forgetHistoryButton.setOnClickListener {confirm("Forget device history?", "New/returning status, detect counts and the cell towers remembered for the fake-cell checks start over. Favorites are kept.") {lifecycleScope.launch {@@ -1240,6 +1587,7 @@ class SettingsActivity : AppCompatActivity() {/** Settings save themselves: whenever this screen is left (back, home, another screen). */override fun onPause() {+ saveSecrets()// Leaving Settings ends any sound preview (not an intro played by a starting scan).com.rfsentinel.app.util.AlertPlayer.stopPreview(stopIntro = introTesting)if (introTesting) { introTesting = false; binding.testIntroButton.text = "Test intro" }diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.ktindex 367003b..0713f6b 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt@@ -19,6 +19,8 @@ enum class DeviceFilter(val label: String) {WIFI("WiFi"),/** Cell towers: not devices, listed from the cell snapshot (list only, not the map). */CELLS("Cells"),+ /** RTL-SDR radio hits: not devices, listed from the radio log (list only). */+ RADIO("Radio"),/** Waze reports: not devices, drawn on the map from the Waze poll (map only). */WAZE("Waze"),/** Heard by external hardware: an ESP32 board (USB or OUI-SPY over Bluetooth) or a USB WiFi adapter. */@@ -31,7 +33,7 @@ enum class DeviceFilter(val label: String) {s.deviceType.contains("tracker", true) || s.deviceType.contains("Find My", true))DRONES -> s.hits.any { it.category == Category.DRONE } || s.remoteId != nullNEW -> s.isNew- CELLS, WAZE -> false+ CELLS, WAZE, RADIO -> falseEXTERNAL -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac)FAVORITES -> Favorites.contains(s.mac)BLE -> Advert.Source.BLE in s.sourcesdiff --git a/app/src/main/java/com/rfsentinel/app/ui/MainPanes.kt b/app/src/main/java/com/rfsentinel/app/ui/MainPanes.ktnew file mode 100644index 0000000..51d937e--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MainPanes.kt@@ -0,0 +1,182 @@+package com.rfsentinel.app.ui++import android.annotation.SuppressLint+import android.content.res.Configuration+import android.graphics.Outline+import android.graphics.drawable.GradientDrawable+import android.view.MotionEvent+import android.view.View+import android.view.ViewOutlineProvider+import android.widget.FrameLayout+import android.widget.LinearLayout+import androidx.appcompat.app.AppCompatActivity+import com.rfsentinel.app.databinding.ActivityMainBinding+import com.rfsentinel.app.util.Prefs++/**+ * The main screen's views - live map, radar, list - in any mix: one fills the screen, two or+ * three stack (side by side in landscape) with a handle between each pair to share the space.+ * The Map view is the full map ([MapFragment]: every layer, button and menu), following the+ * main screen's filter chip. The mix and the sizes are remembered.+ */+class MainPanes(private val activity: AppCompatActivity, private val b: ActivityMainBinding) {++ private val density = activity.resources.displayMetrics.density+ private val mapBorder = GradientDrawable()+ private val radarBorder = GradientDrawable()++ var panes: Set<String> = Prefs.viewPanes(activity)+ private set++ val mapShown get() = "map" in panes+ val radarShown get() = "radar" in panes+ val listShown get() = "list" in panes++ private companion object { const val MAP_TAG = "main_map" }++ init {+ val radius = 16f * density+ for ((pane, border) in listOf(b.mapPane to mapBorder, b.radarPane to radarBorder)) {+ pane.outlineProvider = object : ViewOutlineProvider() {+ override fun getOutline(view: View, outline: Outline) = outline.setRoundRect(0, 0, view.width, view.height, radius)+ }+ border.cornerRadius = radius+ pane.foreground = border+ }+ b.mapPane.clipToOutline = true+ for (grip in listOf(b.gripA, b.gripB)) {+ grip.background = GradientDrawable().apply {+ cornerRadius = 3 * density+ setColor((ChipStyle.onSurface(activity) and 0x00FFFFFF) or 0x66000000)+ }+ grip.alpha = 0.7f+ }+ setupHandle(b.handleA, b.gripA) { pairA() }+ setupHandle(b.handleB, b.gripB) { "radar" to "list" }+ }++ fun setPanes(value: Set<String>) {+ Prefs.setViewPanes(activity, value)+ panes = Prefs.viewPanes(activity)+ apply()+ }++ /** Lays the chosen views out; call again after a rotation or a change of mix. */+ fun apply() {+ val landscape = activity.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE+ b.contentArea.orientation = if (landscape) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL+ val several = panes.size > 1+ b.mapPane.visibility = if (mapShown) View.VISIBLE else View.GONE+ b.radarPane.visibility = if (radarShown) View.VISIBLE else View.GONE+ b.listFrame.visibility = if (listShown) View.VISIBLE else View.GONE+ b.handleA.visibility = if (mapShown && (radarShown || listShown)) View.VISIBLE else View.GONE+ b.handleB.visibility = if (radarShown && listShown) View.VISIBLE else View.GONE+ // Framed when they share the screen; the radar alone fills it as before.+ val (accent, _) = ChipStyle.accent(activity)+ mapBorder.setStroke((2 * density).toInt(), accent)+ radarBorder.setStroke(if (several) (2 * density).toInt() else 0, accent)+ b.radarPane.clipToOutline = several+ val handle = (20 * density).toInt()+ for ((h, grip) in listOf(b.handleA to b.gripA, b.handleB to b.gripB)) {+ h.layoutParams = (h.layoutParams as LinearLayout.LayoutParams).apply {+ width = if (landscape) handle else LinearLayout.LayoutParams.MATCH_PARENT+ height = if (landscape) LinearLayout.LayoutParams.MATCH_PARENT else handle+ weight = 0f+ }+ grip.layoutParams = (grip.layoutParams as FrameLayout.LayoutParams).apply {+ width = ((if (landscape) 5 else 40) * density).toInt()+ height = ((if (landscape) 40 else 5) * density).toInt()+ }+ }+ for (p in Prefs.PANES) {+ viewOf(p).layoutParams = (viewOf(p).layoutParams as LinearLayout.LayoutParams).apply {+ weight = Prefs.paneWeight(activity, p)+ if (landscape) { width = 0; height = LinearLayout.LayoutParams.MATCH_PARENT }+ else { width = LinearLayout.LayoutParams.MATCH_PARENT; height = 0 }+ topMargin = if (!landscape && p != "list" && p == Prefs.PANES.firstOrNull { it in panes }) (6 * density).toInt() else 0+ }+ }+ b.contentArea.requestLayout()+ applyMap()+ }++ private fun viewOf(pane: String): View = when (pane) {+ "map" -> b.mapPane+ "radar" -> b.radarPane+ else -> b.listFrame+ }++ /** The first handle sits after the map: it joins the map to whatever comes next. */+ private fun pairA(): Pair<String, String> = "map" to (if (radarShown) "radar" else "list")++ /** The full map (every layer, button and menu of the map screen), in the Map view. */+ private fun applyMap() {+ val fm = activity.supportFragmentManager+ val current = fm.findFragmentByTag(MAP_TAG) as? MapFragment+ if (mapShown && current == null) {+ fm.beginTransaction()+ .replace(b.previewMapHolder.id, MapFragment.create(android.os.Bundle().apply { putBoolean(MapFragment.ARG_EMBEDDED, true) }), MAP_TAG)+ .runOnCommit { mapFragment()?.setFilter(filter) }+ .commitAllowingStateLoss()+ } else if (!mapShown && current != null) {+ // Hidden: the map goes away entirely, so its GPS and downloads stop with it.+ fm.beginTransaction().remove(current).commitAllowingStateLoss()+ }+ }++ private fun mapFragment() = activity.supportFragmentManager.findFragmentByTag(MAP_TAG) as? MapFragment++ private var filter = DeviceFilter.ALL++ /** The main screen's filter chip also picks what the map shows. */+ fun setFilter(f: DeviceFilter) {+ filter = f+ mapFragment()?.setFilter(f)+ }++ /** A handle shares the space of the two views either side of it (each keeps at least 15 %). */+ @SuppressLint("ClickableViewAccessibility")+ private fun setupHandle(handle: View, grip: View, pair: () -> Pair<String, String>) {+ var first = 0f; var second = 0f+ handle.setOnTouchListener { _, e ->+ val (p, q) = pair()+ val before = viewOf(p); val after = viewOf(q)+ val landscape = b.contentArea.orientation == LinearLayout.HORIZONTAL+ when (e.actionMasked) {+ MotionEvent.ACTION_DOWN -> grip.alpha = 1f+ MotionEvent.ACTION_MOVE -> {+ val start = IntArray(2).also { before.getLocationOnScreen(it) }+ val end = IntArray(2).also { after.getLocationOnScreen(it) }+ val from = if (landscape) start[0] else start[1]+ val to = if (landscape) end[0] + after.width else end[1] + after.height+ if (to > from) {+ val pos = (if (landscape) e.rawX else e.rawY) - from+ val f = (pos / (to - from)).coerceIn(0.15f, 0.85f)+ val total = Prefs.paneWeight(activity, p).let { if (first + second > 0) first + second else it + Prefs.paneWeight(activity, q) }+ first = total * f; second = total * (1 - f)+ (before.layoutParams as LinearLayout.LayoutParams).weight = first+ (after.layoutParams as LinearLayout.LayoutParams).weight = second+ b.contentArea.requestLayout()+ }+ }+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {+ grip.alpha = 0.7f+ if (first + second > 0) {+ Prefs.setPaneWeight(activity, p, first)+ Prefs.setPaneWeight(activity, q, second)+ }+ first = 0f; second = 0f+ }+ }+ true+ }+ }++ /** Once a second from the main screen: the frames take the colour of the strongest alert in range. */+ fun update(alertColor: Int?) {+ val accent = ChipStyle.accent(activity).first+ val width = ((if (alertColor != null) 3 else 2) * density).toInt()+ mapBorder.setStroke(width, alertColor ?: accent)+ if (panes.size > 1) radarBorder.setStroke(width, alertColor ?: accent)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex 1ef5607..5fb2710 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -1,1151 +1,40 @@package com.rfsentinel.app.ui-import android.content.Intent-import android.graphics.Color-import android.graphics.drawable.GradientDrawableimport android.os.Bundle-import android.view.Menuimport android.view.MenuItem-import android.view.View-import android.widget.EditText-import android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity-import androidx.core.view.ViewCompat-import androidx.core.view.WindowInsetsCompat-import androidx.core.view.updatePadding-import androidx.lifecycle.Lifecycle-import androidx.lifecycle.lifecycleScope-import androidx.lifecycle.repeatOnLifecycle-import com.rfsentinel.app.BuildConfig-import com.rfsentinel.app.data.AppDatabase-import com.rfsentinel.app.data.TripDeviceEntity-import com.rfsentinel.app.data.TripEntity-import com.rfsentinel.app.data.WhitelistCache-import com.rfsentinel.app.databinding.ActivityMapBinding-import com.rfsentinel.app.detect.Category-import com.rfsentinel.app.detect.Tier-import com.rfsentinel.app.service.DeviceRegistry-import com.rfsentinel.app.service.ScanForegroundService-import com.rfsentinel.app.service.TripRecorder-import com.rfsentinel.app.util.Exporter-import com.rfsentinel.app.util.Permissions-import kotlinx.coroutines.delay-import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch-import org.osmdroid.config.Configuration-import org.osmdroid.tileprovider.tilesource.TileSourceFactory-import org.osmdroid.util.BoundingBox-import org.osmdroid.util.GeoPoint-import org.osmdroid.views.CustomZoomButtonsController-import org.osmdroid.views.overlay.CopyrightOverlay-import org.osmdroid.views.overlay.FolderOverlay-import org.osmdroid.views.overlay.Marker-import org.osmdroid.views.overlay.Polyline-import org.osmdroid.views.overlay.ScaleBarOverlay-import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider-import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay-import java.io.File-import java.text.DateFormat-import java.util.Date-import java.util.Locale/**- * OpenStreetMap view of a scan. Live mode shows your position, the trace being- * recorded and nearby devices; trip mode shows a saved trace. Devices are drawn- * where YOUR phone was when their signal was strongest - an approximation.- *- * Network use: map tiles only (OpenStreetMap), cached in the app's cache dir.+ * The map full screen: a saved trace (Traces), a place to look at (a cell tower, a Waze report),+ * or the live map from a notification or the floating map. The map itself is [MapFragment],+ * the same one the main screen's Map view shows.*/class MapActivity : AppCompatActivity() {companion object {- const val EXTRA_TRIP_ID = "trip_id"+ const val HEADING_MIN_SPEED_MS = MapFragment.HEADING_MIN_SPEED_MS+ const val EXTRA_TRIP_ID = MapFragment.EXTRA_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"+ const val EXTRA_CENTER_LAT = MapFragment.EXTRA_CENTER_LAT+ const val EXTRA_CENTER_LON = MapFragment.EXTRA_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_000L- private const val TRACE_COLOR = 0xFFE0622D.toInt()- private const val PAST_TRACE_COLOR = 0xFF1F5FBF.toInt()- private const val DRONE_COLOR = 0xFF1F5FBF.toInt()+ const val EXTRA_SHOW_TOWERS = MapFragment.EXTRA_SHOW_TOWERS}- /** One device to draw, from the live registry or a saved trip. */- private data class Pin(- val mac: String, val lat: Double, val lon: Double, val label: String, val flagged: Boolean,- val color: Int, val details: String- )-- private lateinit var binding: ActivityMapBinding- private var tripId: Long? = null- private var trip: TripEntity? = null- /** Which devices the map shows (live: every filter; a saved trace: all or flagged). */- private var filter = DeviceFilter.ALL- private val filterChips = HashMap<DeviceFilter, com.google.android.material.chip.Chip>()- private var centeredOnce = false- /** The live map opened on a world view because nothing was known about where you are: zoom in with the first fix. */- private var startedOnWorld = false- /** The map keeps your position centred until you pan it yourself. */- private var following = false-- private val trace = Polyline()- 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()- /** Aircraft from the ADS-B feeds (Settings > What to detect > Police / government aircraft). */- private val aircraft = FolderOverlay()- /** Waze reports (Settings > What to detect > Waze): shown on the All and Waze chips. */- private val wazeLayer = FolderOverlay()- private var planeZoomStep = -1- /** Plate-reader cameras mapped in OpenStreetMap (downloaded on request). */- private val knownAlpr by lazy {- PointsOverlay<com.rfsentinel.app.alpr.KnownCamera>(resources.displayMetrics.density) { showKnownCamera(it.first()) }- }- private var knownAlprDrawnFor: BoundingBox? = null- /** CCTV cameras mapped in OpenStreetMap (map menu, off by default): icons over their view cones. */- private val cctv by lazy {- PointsOverlay<com.rfsentinel.app.alpr.CctvCamera>(resources.displayMetrics.density) { showCctv(it.first()) }- }- private val cctvCones by lazy { CctvConeOverlay(resources.displayMetrics.density) }- /** 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: MyLocationNewOverlay- private val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)-override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)- // osmdroid: identify ourselves to the tile server (OSM tile policy) and keep- // the tile cache inside the app's private cache.- MapIcons.configureOsm(this)- binding = ActivityMapBinding.inflate(layoutInflater)- setContentView(binding.root)supportActionBar?.setDisplayHomeAsUpEnabled(true)- tripId = intent.getLongExtra(EXTRA_TRIP_ID, -1).takeIf { it > 0 }- title = if (tripId == null) "Scan map" else "Recorded trace"-- // Edge-to-edge: keep the controls above the navigation bar.- ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->- val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())- binding.controls.updatePadding(bottom = bars.bottom + (6 * resources.displayMetrics.density).toInt())- binding.statusBox.translationY = bars.top.toFloat()- 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).- setupFilterChips()- styleFollowButton()- // Outlined "Traces" in the theme highlight (the stock dark teal was unreadable on dark themes).- ChipStyle.accent(this).first.let { accent ->- binding.tracesButton.setTextColor(accent)- binding.tracesButton.strokeColor = android.content.res.ColorStateList.valueOf(accent)- }- binding.centerButton.setOnClickListener {- if (tripId == null) setFollow(true) else centerOnMe()- }- binding.tracesButton.setOnClickListener { startActivity(Intent(this, TripsActivity::class.java)) }-- if (tripId == null) {- observeBulk()- binding.recordButton.setOnClickListener { toggleRecording() }- lifecycleScope.launch {- repeatOnLifecycle(Lifecycle.State.STARTED) {- // A new or cleared Waze report is drawn at once, not at the next 3 s tick.- val stopWaze = com.rfsentinel.app.online.WazePolice.addListener { runOnUiThread { if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) renderLive() } }- try {- while (isActive) {- renderLive()- delay(3_000)- }- } finally {- stopWaze()- }- }- }- } else {- binding.recordButton.visibility = View.GONE- loadTrip()- }- }-- private fun setupMap() {- val map = binding.map- map.setTileSource(TileSourceFactory.MAPNIK)- map.setMultiTouchControls(true)- map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT)- // Open where you are, not on (0, 0): the live map used to sit on open sea until the first GPS fix.- val liveHere = tripId == null && !intent.hasExtra(EXTRA_CENTER_LAT)- val knownFix = if (liveHere) knownFix() else null- val start = if (liveHere) MapStart.pick(- listOf(knownFix?.let { MapStart.Fix(it.latitude, it.longitude, it.time) }),- com.rfsentinel.app.util.Prefs.lastMapCenter(this), com.rfsentinel.app.util.Prefs.mapZoom(this), System.currentTimeMillis()- ) else null- map.controller.setZoom(start?.zoom ?: if (liveHere) MapStart.WORLD_ZOOM else MapStart.DEFAULT_ZOOM)- startedOnWorld = liveHere && start == null- if (start != null) {- map.controller.setCenter(GeoPoint(start.lat, start.lon))- if (start.fresh) centeredOnce = true // already where you are: the first GPS fix need not move the map- }- map.minZoomLevel = 3.0- map.maxZoomLevel = 20.0-- trace.outlinePaint.apply {- color = if (tripId == null) TRACE_COLOR else PAST_TRACE_COLOR- strokeWidth = 7f * resources.displayMetrics.density / 2- }- map.overlays.add(cctvCones)- map.overlays.add(cctv)- map.overlays.add(knownAlpr)- map.overlays.add(towers)- map.overlays.add(trace)- map.overlays.add(pins)- map.overlays.add(drones)- map.overlays.add(wazeLayer)- map.overlays.add(aircraft)- // Redraw the camera layer for the visible area after panning / zooming.- map.addMapListener(object : org.osmdroid.events.MapListener {- override fun onScroll(event: org.osmdroid.events.ScrollEvent?) = false.also {- drawKnownAlprSoon()- // osmdroid stops following when you drag the map: show that on the button.- if (following && !myLocation.isFollowLocationEnabled) setFollow(false)- }- override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also {- drawKnownAlprSoon()- // Plane icons grow as you zoom in (and shrink as you zoom out).- val step = kotlin.math.round(binding.map.zoomLevelDouble * 2).toInt()- if (step != planeZoomStep) { planeZoomStep = step; drawAircraft() }- }- })-- myLocation = MyLocationNewOverlay(GpsMyLocationProvider(this), map)- if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {- myLocation.enableMyLocation()- 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, quiet = true)- myLocation.runOnFirstFix {- runOnUiThread {- if (!centeredOnce) {- centeredOnce = true- if (following) {- if (startedOnWorld) { startedOnWorld = false; binding.map.controller.setZoom(MapStart.DEFAULT_ZOOM) }- centerOnMe()- }- }- }- }- // A current position puts the arrow on the map straight away instead of after the first GPS update.- if (start?.fresh == true) knownFix?.let { myLocation.onLocationChanged(it, null) }- }- }- map.overlays.add(myLocation)- map.overlays.add(ScaleBarOverlay(map).apply { setAlignBottom(false); setScaleBarOffset(20, 180) })- map.overlays.add(CopyrightOverlay(this)) // "© OpenStreetMap contributors" (required attribution)- }-- override fun onResume() {- super.onResume()- binding.map.onResume()- // The location overlay's GPS runs only while the map is on screen.- if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {- myLocation.enableMyLocation()- if (following) myLocation.enableFollowLocation()- }- // Precise GPS while the map is on screen, so devices land where they were heard.- if (tripId == null) ScanForegroundService.mapShown(this)- // Back from Settings > Map: show what's switched on now (and nothing that was switched off).- drawTowers()- drawKnownAlpr()- if (com.rfsentinel.app.util.Prefs.showCctv(this)) lifecycleScope.launch {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.rfsentinel.app.alpr.CctvStore.load(this@MapActivity) }- drawCctv()- maybeDownloadCctv()- } else drawCctv()- }-- override fun onPause() {- saveView()- if (tripId == null) ScanForegroundService.mapHidden(this)- myLocation.disableMyLocation()- binding.map.onPause()- super.onPause()- }-- override fun onDestroy() {- stopObservingBulk?.invoke()- com.rfsentinel.app.alpr.CctvStore.onChanged = null- myLocation.disableMyLocation()- binding.map.removeCallbacks(autoDownloadCameras)- binding.map.removeCallbacks(redrawKnownAlpr)- // These two were left pending: one firing after onDetach() below touches detached overlays and crashes.- binding.map.removeCallbacks(redrawCctv)- binding.map.removeCallbacks(downloadCctv)- binding.map.onDetach()- super.onDestroy()- }-- private fun setupFilterChips() {- val options = if (tripId == null) DeviceFilter.entries else listOf(DeviceFilter.ALL, DeviceFilter.FLAGGED)- filter = DeviceFilter.parse(com.rfsentinel.app.util.Prefs.mapFilter(this)).takeIf { it in options } ?: DeviceFilter.ALL- val group = binding.mapFilterChips- for (f in options) {- val chip = com.google.android.material.chip.Chip(this, null, com.google.android.material.R.attr.chipStyle).apply {- id = View.generateViewId()- text = f.label- isCheckable = true- isCheckedIconVisible = false- ChipStyle.apply(this, overMap = true)- }- filterChips[f] = chip- group.addView(chip)- if (f == filter) chip.isChecked = true- }- group.setOnCheckedStateChangeListener { _, ids ->- val picked = filterChips.entries.firstOrNull { it.value.id == ids.firstOrNull() }?.key ?: return@setOnCheckedStateChangeListener- filter = picked- com.rfsentinel.app.util.Prefs.setMapFilter(this, picked.name)- if (tripId != null) loadTrip() else renderLive()- drawTowers()- }- }-- /** Chip labels with how many devices each filter would show ("Trackers 2"). */- private fun updateFilterCounts(devices: List<DeviceRegistry.Snapshot>) {- val placed = devices.filter { it.bestPosition != null }- for ((f, chip) in filterChips) {- val n = when (f) {- DeviceFilter.CELLS -> towerCount- DeviceFilter.WAZE -> currentWaze().size- else -> placed.count { f.matches(it) }- }- chip.text = if (f == DeviceFilter.ALL || n > 0) "${f.label} $n" else f.label- }- }-- /** Turns following on (re-centres now and keeps you centred) or off (after you pan). */- private fun setFollow(on: Boolean, quiet: Boolean = false) {- following = on- if (on) {- myLocation.enableFollowLocation()- centerOnMe(quiet)- } else {- myLocation.disableFollowLocation()- }- styleFollowButton()- }-- /** Filled with the theme highlight while following, plain otherwise. */- private fun styleFollowButton() {- val on = following- val (accent, onAccent) = ChipStyle.accent(this)- val plain = 0xFFFFFFFF.toInt()- binding.centerButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (on) accent else plain)- binding.centerButton.imageTintList = android.content.res.ColorStateList.valueOf(if (on) onAccent else 0xFF0B5C63.toInt())- binding.centerButton.contentDescription = if (on) "Following your position" else "Follow my position"- }-- private fun centerOnMe(quiet: Boolean = false) {- val fix = myLocation.myLocation- ?: TripRecorder.livePoints().lastOrNull()?.let { GeoPoint(it.lat, it.lon) }- if (fix != null) goTo(fix)- else if (!quiet) Toast.makeText(this, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()- }-- /** Glides to a nearby place; jumps when it is far (an old position, or the first fix after a long trip). */- private fun goTo(p: GeoPoint) {- val map = binding.map- val here = map.mapCenter- val far = !map.isLayoutOccurred ||- DeviceRegistry.metersBetween(here.latitude, here.longitude, p.latitude, p.longitude) > 3_000- if (far) map.controller.setCenter(p) else map.controller.animateTo(p)- }-- /** The best position known before this screen's own GPS answers: the running scan's fix, else the system's last known. */- private fun knownFix(): android.location.Location? =- listOfNotNull(ScanForegroundService.lastFix, systemLastKnown()).maxByOrNull { it.time }-- @android.annotation.SuppressLint("MissingPermission")- private fun systemLastKnown(): android.location.Location? {- if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION) &&- !Permissions.granted(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null- val manager = getSystemService(LOCATION_SERVICE) as? android.location.LocationManager ?: return null- return runCatching {- manager.getProviders(true).mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time }- }.getOrNull()- }-- /** Remembers where the live map is looking, so it can open there next time. */- private fun saveView() {- if (tripId != null || intent.hasExtra(EXTRA_CENTER_LAT)) return- val c = binding.map.mapCenter- if (kotlin.math.abs(c.latitude) < 1e-4 && kotlin.math.abs(c.longitude) < 1e-4) return // it never looked anywhere- com.rfsentinel.app.util.Prefs.saveMapView(this, c.latitude, c.longitude, binding.map.zoomLevelDouble)- }-- // ---- Live mode ------------------------------------------------------------------ private fun renderLive() {- val recording = TripRecorder.isRecording- binding.recordButton.text = if (recording) "Stop recording" else "Record trace"- val (accent, onAccent) = ChipStyle.accent(this)- binding.recordButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (recording) 0xFFB3261E.toInt() else accent)- val recordFg = if (recording) 0xFFFFFFFF.toInt() else onAccent- binding.recordButton.setTextColor(recordFg)- binding.recordButton.iconTint = android.content.res.ColorStateList.valueOf(recordFg)-- // Only the trace being recorded right now; a stopped one is under Traces.- trace.setPoints(if (recording) TripRecorder.livePoints().map { GeoPoint(it.lat, it.lon) } else emptyList())-- // Includes devices from a scan that just stopped: the registry drops them after 3 minutes.- val devices = DeviceRegistry.snapshot()- val drawn = devices.mapNotNull { s ->- val pos = s.bestPosition ?: return@mapNotNull null- val flagged = DeviceColors.isFlagged(s)- if (!filter.matches(s)) return@mapNotNull null- val best = s.best- Pin(- s.mac, pos.lat, pos.lon,- best?.label ?: s.name ?: s.deviceType,- flagged,- DeviceColors.forDevice(this, s),- buildString {- append(s.mac)- s.vendor?.let { append("\n").append(it) }- if (best != null) append("\n${best.category.title} · ${best.tier.label} ${best.confidence}%\n${best.evidence}")- append("\nStrongest signal here: ${s.bestRssi} dBm")- }- )- }- drawPins(drawn)- updateFilterCounts(devices)- drawDrones(devices.filter { it.remoteId?.hasPosition == true })- drawAircraft()- drawWaze()-- 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- String.format(- Locale.US, "● Recording %d:%02d · %.2f km · %s (%d flagged)",- mins / 60, mins % 60, TripRecorder.distanceM / 1000, devicesLabel(TripRecorder.deviceCount()), TripRecorder.flaggedCount()- )- }- positioned == 0 -> "Scanning · waiting for GPS to place devices"- else -> "Scanning · ${drawn.size} on map" + if (filter != DeviceFilter.ALL) " (${filter.label} only)" else ""- } + (cctvLine?.let { "\n$it" } ?: "")- binding.statusText.background.mutate().setTint(if (recording) 0xFFB3261E.toInt() else 0xCC0B5C63.toInt())- binding.map.invalidate()- }-- private fun toggleRecording() {- if (TripRecorder.isRecording) {- lifecycleScope.launch {- val id = TripRecorder.activeTripId- TripRecorder.stop(this@MapActivity)- refreshServiceLocation()- val saved = id?.let { AppDatabase.getInstance(this@MapActivity).tripDao().get(it) }- if (saved != null) {- AlertDialog.Builder(this@MapActivity)- .setTitle("Trace saved")- .setMessage(String.format(Locale.US, "%s\n%.2f km · %s (%d flagged)",- saved.name, saved.distanceM / 1000, devicesLabel(saved.deviceCount), saved.flaggedCount))- .setPositiveButton("View") { _, _ -> openTrip(saved.id) }- .setNeutralButton("Export") { _, _ -> Exporter.showTripExport(this@MapActivity, saved.id) }- .setNegativeButton("Close", null)- .show()- } else {- Toast.makeText(this@MapActivity, "Nothing recorded (no GPS fix)", Toast.LENGTH_LONG).show()- }- renderLive()- }- return- }- if (Permissions.missingRequired(this).isNotEmpty()) {- Toast.makeText(this, "Grant location and nearby-devices first (Start scanning on the main screen)", Toast.LENGTH_LONG).show()- return- }- lifecycleScope.launch {- if (!ScanForegroundService.isRunning) {- runCatching { ScanForegroundService.start(this@MapActivity) }- delay(600)- }- TripRecorder.start(this@MapActivity)- refreshServiceLocation()- Toast.makeText(this@MapActivity, "Recording your trace - keeps going with the screen off", Toast.LENGTH_SHORT).show()- renderLive()- }- }-- /** Tells the running service to switch location updates to trace mode (or back). */- private fun refreshServiceLocation() {- // Only a running scanner needs refreshing; sending it otherwise would start scanning.- if (!ScanForegroundService.isRunning) return- runCatching {- startService(Intent(this, ScanForegroundService::class.java).setAction(ScanForegroundService.ACTION_REFRESH_LOCATION))- }- }-- private fun openTrip(id: Long) {- startActivity(Intent(this, MapActivity::class.java).putExtra(EXTRA_TRIP_ID, id))- }-- // ---- Trip mode -------------------------------------------------------------------- private fun loadTrip() {- val id = tripId ?: return- lifecycleScope.launch {- val dao = AppDatabase.getInstance(this@MapActivity).tripDao()- val t = dao.get(id) ?: run { finish(); return@launch }- trip = t- val points = dao.points(id).map { GeoPoint(it.lat, it.lon) }- val devices = dao.devices(id)- trace.setPoints(points)- drawPins(devices.filter { it.lat != null && (it.flagged || filter == DeviceFilter.ALL) }.map { it.toPin() })- val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000- binding.statusText.text = String.format(- Locale.US, "%s\n%s · %d:%02d · %.2f km · %s (%d flagged)",- t.name, dateFmt.format(Date(t.startTime)), mins / 60, mins % 60, t.distanceM / 1000,- devicesLabel(t.deviceCount), t.flaggedCount- )- binding.statusText.background.mutate().setTint(0xCC1F5FBF.toInt())- val all = points + devices.filter { it.lat != null }.map { GeoPoint(it.lat!!, it.lon!!) }- if (all.isNotEmpty()) {- binding.map.post {- if (all.size == 1) binding.map.controller.setCenter(all[0])- else binding.map.zoomToBoundingBox(BoundingBox.fromGeoPoints(all).increaseByScale(1.3f), false)- }- }- binding.map.invalidate()- }- }-- private fun TripDeviceEntity.toPin(): Pin {- val cat = Category.parse(category)- return Pin(- mac, lat!!, lon!!, label, flagged,- DeviceColors.forMatch(this@MapActivity, if (flagged) cat else null, confidence),- buildString {- append(mac)- vendor?.let { append("\n").append(it) }- if (cat != null) append("\n${cat.title} · ${Tier.of(confidence).label} $confidence%")- evidence?.let { append("\n").append(it) }- probedList.takeIf { it.isNotEmpty() }?.let { append("\nAsked for networks: ").append(it.joinToString(", ")) }- append("\nStrongest signal here: $bestRssi dBm")- append("\nHeard ${dateFmt.format(Date(firstSeen))}")- }- )- }-- // ---- Drawing ------------------------------------------------------------------------ /**- * 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>) {- // 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)- }- }-- /**- * Drones place themselves: Remote ID broadcasts the aircraft's own GPS fix- * (and usually the operator's / take-off point), so these markers are real- * positions, unlike RSSI-based device pins.- */- private fun drawDrones(list: List<DeviceRegistry.Snapshot>) {- drones.items.clear()- val dp = resources.displayMetrics.density- for (s in list) {- val r = s.remoteId ?: continue- val aircraft = GeoPoint(r.latitude!!, r.longitude!!)- val details = droneDetails(s, r)- if (r.hasOperatorPosition) {- val operator = GeoPoint(r.operatorLatitude!!, r.operatorLongitude!!)- drones.add(Polyline().apply {- setPoints(listOf(operator, aircraft))- outlinePaint.apply {- color = DRONE_COLOR- strokeWidth = 2.5f * dp- pathEffect = android.graphics.DashPathEffect(floatArrayOf(10 * dp, 6 * dp), 0f)- }- })- drones.add(Marker(binding.map).apply {- position = operator- icon = GradientDrawable().apply {- shape = GradientDrawable.RECTANGLE- setColor(0xFFF5E100.toInt())- setStroke((2 * dp).toInt(), DRONE_COLOR)- setSize((14 * dp).toInt(), (14 * dp).toInt())- }- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = "Drone operator / take-off point"- setOnMarkerClickListener { _, _ -> showDrone(s, "Operator of this drone (or its take-off point)\n\n$details"); true }- })- }- drones.add(Marker(binding.map).apply {- position = aircraft- icon = android.graphics.drawable.BitmapDrawable(resources, droneArrow(dp))- rotation = -(r.directionDeg ?: 0).toFloat() // osmdroid rotates counter-clockwise- isFlat = true- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = "Drone"- setOnMarkerClickListener { _, _ -> showDrone(s, details); true }- })- }- }-- /** The Waze reports from the checker, which clears them when it stops. */- private fun currentWaze(): List<com.rfsentinel.app.online.WazePolice.Shown> = com.rfsentinel.app.online.WazePolice.latest-- /**- * Waze reports as coloured dots (blue police, red accident, orange hazard, brown closure,- * purple jam) with a white outline. Tap one for what it is, how far, how old, how many confirmed.- */- private fun drawWaze() {- wazeLayer.items.clear()- val show = tripId == null && (filter == DeviceFilter.ALL || filter == DeviceFilter.WAZE)- if (show) {- val dp = resources.displayMetrics.density- for (w in currentWaze()) {- wazeLayer.add(Marker(binding.map).apply {- position = GeoPoint(w.report.lat, w.report.lon)- icon = GradientDrawable().apply {- shape = GradientDrawable.OVAL- setColor(w.report.type.color)- setStroke((2 * dp).toInt(), android.graphics.Color.WHITE)- setSize((20 * dp).toInt(), (20 * dp).toInt())- }- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- title = w.hit.label- setOnMarkerClickListener { _, _ -> showWaze(w); true }- })- }- }- binding.map.invalidate()- }-- private fun showWaze(w: com.rfsentinel.app.online.WazePolice.Shown) {- AlertDialog.Builder(this)- .setTitle(w.hit.label)- .setMessage("${w.hit.tier.label} ${w.hit.confidence}%\n${com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend)}\n${w.hit.evidence}")- .setNegativeButton("Close", null)- .show()- }-- /**- * Aircraft from the latest ADS-B poll: police / government / circling ones in bold- * purple with their agency and altitude, every other aircraft small and grey, each- * pointing along its track. Tap one for its details.- */- private fun drawAircraft() {- aircraft.items.clear()- binding.map.invalidate()- val list = com.rfsentinel.app.online.PoliceAircraft.latest- if (list.isEmpty() || System.currentTimeMillis() - com.rfsentinel.app.online.PoliceAircraft.latestAt > 3 * 60_000L) return- val dp = resources.displayMetrics.density- // Sized to the zoom: 0.5x at a city-wide view (zoom 10), 1x at zoom 13, 2.2x at street level (17+).- val scale = (0.5 + (binding.map.zoomLevelDouble - 10.0) * (1.7 / 7.0)).coerceIn(0.5, 2.2).toFloat()- val icons = HashMap<Boolean, android.graphics.drawable.BitmapDrawable>()- // Ordinary traffic first, so flagged aircraft are drawn on top.- for ((p, hit) in list.sortedBy { it.hit != null }) {- val flagged = hit != null- val at = GeoPoint(p.lat, p.lon)- aircraft.add(Marker(binding.map).apply {- position = at- icon = icons.getOrPut(flagged) { android.graphics.drawable.BitmapDrawable(resources, MapIcons.planeIcon(dp, flagged, scale)) }- rotation = -(p.trackDeg ?: 0.0).toFloat() // osmdroid rotates counter-clockwise- isFlat = true- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)- setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }- })- if (flagged) {- val label = listOfNotNull(- hit!!.label.substringAfter(": ", hit.label).take(28),- p.altitudeFt?.takeIf { it > 0 }?.let { "$it ft" }- ).joinToString(" · ")- aircraft.add(Marker(binding.map).apply {- position = at- icon = android.graphics.drawable.BitmapDrawable(resources, aircraftLabel(dp, label))- setAnchor(Marker.ANCHOR_CENTER, -0.9f) // just below the plane, never rotated- setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }- })- }- }- }-- private fun aircraftLabel(dp: Float, text: String): android.graphics.Bitmap {- val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {- textSize = 11 * dp- color = android.graphics.Color.WHITE- typeface = android.graphics.Typeface.DEFAULT_BOLD- }- val pad = 4 * dp- val w = (p.measureText(text) + 2 * pad).toInt()- val h = (p.textSize + 2 * pad).toInt()- val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)- val c = android.graphics.Canvas(bmp)- val bg = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = MapIcons.POLICE_AIRCRAFT_COLOR }- c.drawRoundRect(android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat()), 4 * dp, 4 * dp, bg)- c.drawText(text, pad, h - pad - p.descent() / 2, p)- return bmp- }-- private fun showAircraft(p: com.rfsentinel.app.online.PoliceAircraft.Plane, hit: com.rfsentinel.app.detect.Hit?) {- val me = myLocation.myLocation- val text = buildString {- hit?.let { append(it.evidence).append("\n\n") }- p.registration?.let { append("Registration: $it\n") }- p.callsign?.let { append("Callsign: $it\n") }- p.type?.let { append("Type: $it\n") }- p.owner?.let { append("Owner / operator: $it\n") }- p.altitudeFt?.let { append(if (it <= 0) "On the ground\n" else "Altitude: $it ft\n") }- p.speedKt?.let { append(String.format(Locale.US, "Speed: %.0f kt (%.0f km/h)\n", it, it * 1.852)) }- p.trackDeg?.let { append(String.format(Locale.US, "Heading: %.0f°\n", it)) }- me?.let { append(String.format(Locale.US, "Distance: %.1f km\n",- DeviceRegistry.metersBetween(it.latitude, it.longitude, p.lat, p.lon) / 1000)) }- append("ICAO address: ${p.hex.uppercase()}\nSource: community ADS-B (adsb.fi / adsb.lol)")- }- AlertDialog.Builder(this)- .setTitle(hit?.label ?: (p.registration ?: p.callsign ?: "Aircraft"))- .setMessage(text)- .setPositiveButton("OK", null)- .show()- }-- private fun droneDetails(s: DeviceRegistry.Snapshot, r: com.rfsentinel.app.detect.RemoteId.Info) = buildString {- r.uasId?.let { append("ID: $it\n") }- r.uaType?.let { append("Type: $it\n") }- r.status?.let { append("Status: $it\n") }- r.heightM?.let { append(String.format(Locale.US, "Height: %.0f m\n", it)) }- r.altitudeGeoM?.let { append(String.format(Locale.US, "Altitude (GPS): %.0f m\n", it)) }- r.speedMs?.let { append(String.format(Locale.US, "Speed: %.0f km/h\n", it * 3.6)) }- r.directionDeg?.let { append("Heading: $it°\n") }- r.operatorId?.let { append("Operator ID: $it\n") }- r.selfIdDescription?.let { append("Description: $it\n") }- append("Radio: ${s.mac} · ${s.rssi} dBm")- }-- private fun showDrone(s: DeviceRegistry.Snapshot, text: String) {- AlertDialog.Builder(this)- .setTitle("Drone (Remote ID)")- .setMessage(text + "\n\nPositions are broadcast by the drone itself (ASTM F3411 Remote ID).")- .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(this, s.mac) }- .setNegativeButton("Close", null)- .show()- }-- /** A blue arrow pointing north; the marker rotation turns it to the drone's heading. */- private fun droneArrow(dp: Float): android.graphics.Bitmap {- val size = (30 * dp).toInt()- val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)- val c = android.graphics.Canvas(bmp)- val path = android.graphics.Path().apply {- moveTo(size / 2f, 2 * dp); lineTo(size - 5 * dp, size - 4 * dp)- lineTo(size / 2f, size * 0.68f); lineTo(5 * dp, size - 4 * dp); close()- }- val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)- c.drawPath(path, paint.apply { color = DRONE_COLOR; style = android.graphics.Paint.Style.FILL })- c.drawPath(path, paint.apply { color = Color.WHITE; style = android.graphics.Paint.Style.STROKE; strokeWidth = 2 * dp })- return bmp- }-- // ---- Known plate, speed and red-light cameras (OpenStreetMap) ---------------------------------------------- private val redrawKnownAlpr = Runnable { drawKnownAlpr() }-- private fun drawKnownAlprSoon() {- binding.map.removeCallbacks(redrawKnownAlpr)- binding.map.postDelayed(redrawKnownAlpr, 250)- binding.map.removeCallbacks(redrawCctv)- binding.map.postDelayed(redrawCctv, 250)- }-- // ---- CCTV cameras (OpenStreetMap) ----------------------------------------------------------------- private val redrawCctv = Runnable { drawCctv() }- private fun drawCctvSoon() {- binding.map.removeCallbacks(redrawCctv)- binding.map.postDelayed(redrawCctv, 300)- }- private val downloadCctv = Runnable { maybeDownloadCctv() }-- /** Below this zoom the layer is hidden (cities hold thousands of cameras); view cones from [cctvConeZoom]. */- private val cctvMinZoom = 12.0- private val cctvConeZoom = 15.0-- /** What the CCTV layer is doing, added to the status line (null while the layer is off). */- @Volatile private var cctvLine: String? = null-- private fun setCctvLine(text: String?) {- if (text == cctvLine) return- cctvLine = text- if (tripId == null) renderLive()- }-- private fun drawCctv() {- com.rfsentinel.app.alpr.CctvStore.onChanged = { if (!isFinishing && !isDestroyed) drawCctvSoon() }- val map = binding.map- val on = com.rfsentinel.app.util.Prefs.showCctv(this) && tripId == null- if (!on || map.zoomLevelDouble < cctvMinZoom) {- if (cctv.points.isNotEmpty() || cctvCones.cameras.isNotEmpty()) {- cctv.points = emptyList(); cctvCones.cameras = emptyList(); map.invalidate()- }- setCctvLine(if (!on) null else com.rfsentinel.app.alpr.CctvStore.progress?.let { "CCTV: downloading around you, $it" }- ?: "CCTV: zoom in to see the cameras")- return- }- map.removeCallbacks(downloadCctv)- map.postDelayed(downloadCctv, 1_200)- val private = com.rfsentinel.app.util.Prefs.cctvPrivate(this)- val box = map.boundingBox.increaseByScale(1.5f)- val center = map.mapCenter- val inView = com.rfsentinel.app.alpr.CctvStore.cameras.filter {- (private || !it.isPrivate) && it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast- }.let { all ->- // Zoomed out over a city: the ones nearest the centre of the screen.- if (all.size <= 3000) all- else all.sortedBy { (it.lat - center.latitude).let { d -> d * d } + (it.lon - center.longitude).let { d -> d * d } }.take(3000)- }- val dp = resources.displayMetrics.density- val publicIcon = MapIcons.cctvIcon(dp, false); val privateIcon = MapIcons.cctvIcon(dp, true)- cctvCones.cameras = if (map.zoomLevelDouble >= cctvConeZoom) inView else emptyList()- cctv.points = inView.map { PointsOverlay.Point(it.lat, it.lon, it, icon = if (it.isPrivate) privateIcon else publicIcon) }- map.invalidate()- val store = com.rfsentinel.app.alpr.CctvStore- val view = map.boundingBox- val hiddenPrivate = if (private) 0 else store.cameras.count {- it.isPrivate && it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast- }- val shown = inView.count { it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast }- setCctvLine(when {- store.progress != null -> "CCTV: downloading around you, ${store.progress}"- store.isBusy -> "CCTV: downloading..."- System.currentTimeMillis() - store.lastFailureAt < 60_000 -> "CCTV: map server busy - retrying"- store.missingAreas > 0 && shown > 0 -> "CCTV: $shown in view - ${store.missingAreas} area(s) around you still missing (servers busy), retried next time"- shown == 0 && store.needsDownload(view.latSouth, view.lonWest, view.latNorth, view.lonEast) -> "CCTV: downloading..."- shown == 0 && hiddenPrivate > 0 -> "CCTV: only private ones here ($hiddenPrivate) - Settings > Known cameras > Include private"- shown == 0 -> "CCTV: none mapped here"- else -> "CCTV: $shown in view" + if (hiddenPrivate > 0) " (+$hiddenPrivate private hidden)" else ""- })- }-- /**- * Fetches the CCTV cameras within the download radius around you (once, in the- * background), and the area on screen when you look somewhere outside it.- */- private fun maybeDownloadCctv() {- val map = binding.map- if (!com.rfsentinel.app.util.Prefs.showCctv(this) || tripId != null) return- val store = com.rfsentinel.app.alpr.CctvStore- if (map.isAnimating || store.isBusy) { map.postDelayed(downloadCctv, 2_000); return }- val here = myLocation.myLocation ?: ScanForegroundService.lastFix?.let { GeoPoint(it.latitude, it.longitude) }- if (here != null) {- val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(this).toDouble()- store.ensureAround(this, here.latitude, here.longitude, radius)- if (store.isBusy) return- }- if (map.zoomLevelDouble < cctvMinZoom) return- val box = map.boundingBox- lifecycleScope.launch {- com.rfsentinel.app.alpr.CctvStore.autoDownload(this@MapActivity, box.latSouth, box.lonWest, box.latNorth, box.lonEast)- // Redraw either way: new cameras, or the status line (none mapped / server busy).- drawCctv()- // After a failure, try again once the back-off has passed.- if (System.currentTimeMillis() - com.rfsentinel.app.alpr.CctvStore.lastFailureAt < 60_000)- binding.map.postDelayed(downloadCctv, 61_000)- }- }-- private fun showCctv(c: com.rfsentinel.app.alpr.CctvCamera) {- val text = buildString {- append(when (c.zone) {- "public" -> "Watches a public space (street, square, station...).\n"- "outdoor" -> "A private camera that watches outside (an entrance, a car park...).\n"- "indoor" -> "Inside a building or shop.\n"- else -> "Whether it watches public space isn't mapped.\n"- })- c.area?.let { append("Watches: $it\n") }- c.operator?.let { append("Operator: $it\n") }- c.mount?.let { append("Mounted on: $it\n") }- c.height?.let { append("Height: ${"%.0f".format(it)} m\n") }- c.direction?.let { append("Faces: $it°" + (c.angle?.let { a -> ", $a° wide" } ?: "") + "\n") }- append("OSM: ${c.osmId}\n\n")- append("Mapped by OpenStreetMap volunteers. Most of these cameras are wired and give off no Bluetooth or WiFi " +- "signal, so the scan can't detect them - this layer shows the ones that have been mapped. " +- "The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")- }- AlertDialog.Builder(this)- .setTitle(com.rfsentinel.app.alpr.Cctv.title(c))- .setMessage(text)- .setPositiveButton("Close", null)- .setNeutralButton("Open in OpenStreetMap") { _, _ ->- runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${c.osmId}"))) }- }- .show()- }-- private val autoDownloadCameras = Runnable { maybeAutoDownloadCameras() }-- /**- * Fetches the cameras for the area on screen when it isn't cached yet, so- * they're always on the map without a manual download. Runs once the map- * has stopped moving for a moment.- */- private fun maybeAutoDownloadCameras() {- val prefs = com.rfsentinel.app.util.Prefs- if (!prefs.autoCameras(this) || !prefs.showKnownAlpr(this) || tripId != null) return- // Still gliding to your position (or another target): wait until it stops.- if (binding.map.isAnimating) { binding.map.postDelayed(autoDownloadCameras, 1_000); return }- val box = binding.map.boundingBox- val span = com.rfsentinel.app.alpr.AlprStore.MAX_SPAN_DEG- if (box.latNorth - box.latSouth > span || box.lonEast - box.lonWest > span) return- // The map starts at 0°,0° until it's moved to your position: don't fetch the ocean.- if (kotlin.math.abs(box.centerLatitude) < 0.5 && kotlin.math.abs(box.centerLongitude) < 0.5) return- // Another download (e.g. the car screen's) is running: look again shortly.- if (com.rfsentinel.app.alpr.AlprStore.isBusy) { binding.map.postDelayed(autoDownloadCameras, 3_000); return }- lifecycleScope.launch {- val changed = com.rfsentinel.app.alpr.AlprStore.autoDownload(- this@MapActivity, box.latSouth, box.lonWest, box.latNorth, box.lonEast- )- // Redrawing also re-checks the area now on screen, in case the map moved meanwhile.- if (changed) { drawKnownAlpr(); refreshServiceLocation() }- }- }-- /** Draws the cameras in (and just around) the visible area; skipped when zoomed far out. */- private fun drawKnownAlpr() {- val map = binding.map- map.removeCallbacks(autoDownloadCameras)- map.postDelayed(autoDownloadCameras, 1_200)- if (!com.rfsentinel.app.util.Prefs.showKnownAlpr(this) || map.zoomLevelDouble < 9.0) {- 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 { 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 = box- map.invalidate()- }-- private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = MapIcons.cameraIcon(dp, kind)-- private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {- val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(this, cam.osmId)- val text = buildString {- if (ignored) append("Alerts for this camera are off.\n\n")- append(when (cam.type) {- com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "A license-plate reader mapped in OpenStreetMap.\n\n"- com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "A speed camera mapped in OpenStreetMap.\n\n"- com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "A red-light camera mapped in OpenStreetMap.\n\n"- })- cam.brand?.let { append("Maker: $it\n") }- cam.operator?.let { append("Operator: $it\n") }- cam.direction?.let { append("Faces: $it°\n") }- append("OSM: ${cam.osmId}\n\n")- append("These cameras send their data over cellular or wire and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning. Mobile speed cameras move and are rarely mapped.\n\nMap data © OpenStreetMap contributors (ODbL).")- }- AlertDialog.Builder(this)- .setTitle(cam.label)- .setMessage(text)- // Kept until turned back on here (or cleared in Settings).- .setPositiveButton(if (ignored) "Alert again" else "Ignore alerts") { _, _ ->- com.rfsentinel.app.alpr.IgnoredCameras.set(this, cam.osmId, !ignored)- Toast.makeText(this, if (ignored) "You'll be warned about this camera again"- else "No more alerts for this camera (tap it again to undo)", Toast.LENGTH_SHORT).show()- drawKnownAlpr()- }- .setNegativeButton("Close", null)- .setNeutralButton("Open in OpenStreetMap") { _, _ ->- runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }- }- .show()- }-- /** Towers with a map position (the Cells chip's count), refreshed with the layer. */- private var towerCount = 0-- private fun drawTowers() {- towerCount = com.rfsentinel.app.service.CellTowerStore.all(this).count { it.bestLat != null }- // The Cells chip shows the towers (only them); All adds them when the map menu's switch is on;- // every other chip hides them.- val show = filter == DeviceFilter.CELLS ||- (filter == DeviceFilter.ALL && com.rfsentinel.app.util.Prefs.showCellTowers(this))- towers.points = if (tripId != null || !show) 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)- .setMessage(p.details + "\n\nPosition = where your phone was when this device's signal was strongest (approximate).")- .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(this, p.mac) }- .setNegativeButton("Close", null)- .show()- }-- private var stopObservingBulk: (() -> Unit)? = null-- /** Status text while a DeFlock download runs, or null when none does. */- private fun bulkStatus(): String? = when (val s = com.rfsentinel.app.alpr.DeflockBulk.state) {- is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading ->- "Downloading plate cameras · ${s.detail.ifEmpty { "${s.done}/${s.total} regions" }} · ${s.found} found"- is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras ->- "${s.cameras} plate cameras on the map · checking OpenStreetMap for more (up to 45 s)..."- else -> null- }-- /** Follows every DeFlock download (from here, Settings or the weekly refresh) with the progress bar. */- private fun observeBulk() {- stopObservingBulk = com.rfsentinel.app.alpr.DeflockBulk.observe { s ->- if (isFinishing || isDestroyed) return@observe- val bar = binding.downloadProgress- when (s) {- is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading -> {- if (bar.isIndeterminate) { bar.visibility = View.INVISIBLE; bar.isIndeterminate = false }- bar.visibility = View.VISIBLE- bar.setProgressCompat((s.fraction * 100).toInt(), true)- }- is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras -> {- // DeFlock's cameras are saved: show them now; the bar keeps moving for the extras.- com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, true)- drawKnownAlpr(); refreshServiceLocation()- bar.visibility = View.INVISIBLE; bar.isIndeterminate = true; bar.visibility = View.VISIBLE- }- is com.rfsentinel.app.alpr.DeflockBulk.State.Done -> {- bar.visibility = View.GONE- drawKnownAlpr(); refreshServiceLocation()- }- is com.rfsentinel.app.alpr.DeflockBulk.State.Failed -> {- bar.visibility = View.GONE- }- com.rfsentinel.app.alpr.DeflockBulk.State.Idle -> bar.visibility = View.GONE- }- bulkStatus()?.let { binding.statusText.text = it }+ val host = androidx.fragment.app.FragmentContainerView(this).apply { id = com.rfsentinel.app.R.id.mapHost }+ setContentView(host)+ if (savedInstanceState == null) {+ supportFragmentManager.beginTransaction()+ .replace(com.rfsentinel.app.R.id.mapHost, MapFragment.create(intent.extras ?: Bundle()))+ .commit()}}- // ---- Menu (trip mode) ----------------------------------------------------------------- override fun onCreateOptionsMenu(menu: Menu): Boolean {- if (tripId != null) {- menu.add(0, 1, 0, "Export trace...")- menu.add(0, 2, 1, "Rename")- menu.add(0, 3, 2, "Delete")- } else {- menu.add(0, 13, 1, "Check Waze now")- menu.add(0, 14, 2, "Waze status")- // The map's options live in Settings > Map.- menu.add(0, 12, 0, "Map settings").apply {- setIcon(com.rfsentinel.app.R.drawable.ic_settings)- setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)- }- }- return true- }-override fun onOptionsItemSelected(item: MenuItem): Boolean {- val id = tripId- return when (item.itemId) {- 1 -> { id?.let { Exporter.showTripExport(this, it) }; true }- 2 -> { id?.let { rename(it) }; true }- 3 -> { id?.let { confirmDelete(it) }; true }- 12 -> {- startActivity(Intent(this, com.rfsentinel.app.settings.SettingsActivity::class.java)- .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION,- com.rfsentinel.app.settings.SettingsActivity.SECTION_MAP))- true- }- 13 -> { WazeUi.checkNow(this); true }- 14 -> { WazeUi.openStatus(this); true }- android.R.id.home -> { finish(); true }- else -> super.onOptionsItemSelected(item)- }- }-- private fun rename(id: Long) {- val input = EditText(this).apply { setText(trip?.name ?: ""); setSelection(text.length) }- AlertDialog.Builder(this)- .setTitle("Rename trace")- .setView(input)- .setPositiveButton("Save") { _, _ ->- lifecycleScope.launch {- AppDatabase.getInstance(this@MapActivity).tripDao().rename(id, input.text.toString().trim().ifEmpty { "Trace" })- loadTrip()- }- }- .setNegativeButton("Cancel", null)- .show()- }-- private fun confirmDelete(id: Long) {- AlertDialog.Builder(this)- .setTitle("Delete this trace?")- .setMessage("The route and its device list are deleted from this phone.")- .setPositiveButton("Delete") { _, _ ->- lifecycleScope.launch {- AppDatabase.getInstance(this@MapActivity).tripDao().delete(id)- finish()- }- }- .setNegativeButton("Cancel", null)- .show()+ if (item.itemId == android.R.id.home) { finish(); return true }+ return super.onOptionsItemSelected(item)}}--/** "1 device" / "3 devices". */-internal fun devicesLabel(n: Int) = if (n == 1) "1 device" else "$n devices"diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktnew file mode 100644index 0000000..acfaa11--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -0,0 +1,1643 @@+package com.rfsentinel.app.ui++import android.content.Intent+import android.graphics.Color+import android.graphics.drawable.GradientDrawable+import android.os.Bundle+import android.view.LayoutInflater+import android.view.Menu+import android.view.MenuInflater+import android.view.MenuItem+import android.view.MotionEvent+import android.view.View+import android.view.ViewGroup+import android.widget.EditText+import android.widget.Toast+import androidx.appcompat.app.AlertDialog+import androidx.core.view.MenuProvider+import androidx.core.view.ViewCompat+import androidx.core.view.WindowInsetsCompat+import androidx.core.view.updatePadding+import androidx.fragment.app.Fragment+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.lifecycleScope+import androidx.lifecycle.repeatOnLifecycle+import com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.data.TripDeviceEntity+import com.rfsentinel.app.data.TripEntity+import com.rfsentinel.app.databinding.ActivityMapBinding+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.Tier+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.service.TripRecorder+import com.rfsentinel.app.util.Exporter+import com.rfsentinel.app.util.Permissions+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import org.osmdroid.tileprovider.tilesource.TileSourceFactory+import org.osmdroid.util.BoundingBox+import org.osmdroid.util.GeoPoint+import org.osmdroid.views.CustomZoomButtonsController+import org.osmdroid.views.overlay.CopyrightOverlay+import org.osmdroid.views.overlay.FolderOverlay+import org.osmdroid.views.overlay.Marker+import org.osmdroid.views.overlay.Polyline+import org.osmdroid.views.overlay.ScaleBarOverlay+import org.osmdroid.views.overlay.TilesOverlay+import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider+import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay+import java.text.DateFormat+import java.util.Date+import java.util.Locale++/**+ * OpenStreetMap view of a scan. Live mode shows your position, the trace being+ * recorded and nearby devices; trip mode shows a saved trace. Devices are drawn+ * where YOUR phone was when their signal was strongest - an approximation.+ *+ * Shown full screen by [MapActivity] (a saved trace, a place to look at, a notification) and+ * embedded in the main screen's Map view, where the main screen's filter chips drive it and+ * its menu items are in the main screen's menu.+ *+ * Network use: map tiles only (OpenStreetMap), cached in the app's cache dir.+ */+class MapFragment : Fragment() {++ companion object {+ /** Heading up turns the map only above this speed (~5 km/h): stopped, GPS bearing is noise. */+ const val HEADING_MIN_SPEED_MS = 1.4f+ 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"+ /** Inside the main screen (its chips drive the filter; the menu is a button on the map). */+ const val ARG_EMBEDDED = "embedded"+ /** 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_000L+ private const val TRACE_COLOR = 0xFFE0622D.toInt()+ private const val PAST_TRACE_COLOR = 0xFF1F5FBF.toInt()+ private const val DRONE_COLOR = 0xFF1F5FBF.toInt()+ private const val GPS_MOVING_MS = 1_000L+ private const val GPS_PARKED_MS = 5_000L+ /**+ * 3D view: the tilt, and the camera distance in map-area heights (proportional, so the+ * perspective looks the same in a small pane and full screen; the size is worked out in tiltFit).+ */+ /** Upper limit for the tilted view's height, in map-area heights. */+ private const val TILT_MAX_HEIGHT = 6f+ private const val TILT_DEGREES = 50f+ private const val TILT_CAMERA = 14.3f++ fun create(args: Bundle) = MapFragment().apply { arguments = args }+ }++ /** One device to draw, from the live registry or a saved trip. */+ private data class Pin(+ val mac: String, val lat: Double, val lon: Double, val label: String, val flagged: Boolean,+ val color: Int, val details: String+ )++ private var _binding: ActivityMapBinding? = null+ private val binding get() = _binding!!+ private val act get() = requireActivity() as androidx.appcompat.app.AppCompatActivity+ private val args get() = arguments ?: Bundle.EMPTY+ private val embedded get() = args.getBoolean(ARG_EMBEDDED, false)+ /**+ * Still on screen: delayed redraws / downloads and GPS callbacks can arrive after the map was+ * closed or the main screen's Map view turned off, and must then do nothing.+ */+ private val alive get() = _binding != null && isAdded && activity != null+ private var tripId: Long? = null+ private var trip: TripEntity? = null+ /** Which devices the map shows (live: every filter; a saved trace: all or flagged). */+ private var filter = DeviceFilter.ALL+ private val filterChips = HashMap<DeviceFilter, com.google.android.material.chip.Chip>()+ private var centeredOnce = false+ /** The live map opened on a world view because nothing was known about where you are: zoom in with the first fix. */+ private var startedOnWorld = false+ /** The map keeps your position centred until you pan it yourself. */+ private var following = false++ private val trace = Polyline()+ 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()+ /** Aircraft from the ADS-B feeds (Settings > What to detect > Police / government aircraft). */+ private val aircraft = FolderOverlay()+ /** Waze reports (Settings > What to detect > Waze): shown on the All and Waze chips. */+ private val wazeLayer = FolderOverlay()+ private var planeZoomStep = -1+ /** Plate-reader cameras mapped in OpenStreetMap (downloaded on request). */+ private val knownAlpr by lazy {+ PointsOverlay<com.rfsentinel.app.alpr.KnownCamera>(resources.displayMetrics.density) { showKnownCamera(it.first()) }+ }+ private var knownAlprDrawnFor: BoundingBox? = null+ /** CCTV cameras mapped in OpenStreetMap (Settings > Known cameras, off by default): icons over their view cones. */+ private val cctv by lazy {+ PointsOverlay<com.rfsentinel.app.alpr.CctvCamera>(resources.displayMetrics.density) { showCctv(it.first()) }+ }+ private val cctvCones by lazy { CctvConeOverlay(resources.displayMetrics.density) }+ /** 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: MyLocationNewOverlay+ private val scaleBar by lazy { ScaleBarOverlay(binding.map).apply { setAlignBottom(false); setScaleBarOffset(20, 180) } }++ private fun placeScaleBar() {+ val b = _binding ?: return+ val gap = (8 * resources.displayMetrics.density).toInt()+ val box = b.statusBox+ val y = if (box.height > 0) box.bottom + box.translationY.toInt() + gap else box.top + box.translationY.toInt()+ scaleBar.setScaleBarOffset(20, y.coerceAtLeast(gap))+ // The 3D view's map credit takes the scale bar's place.+ b.osmCredit.translationY = y.coerceAtLeast(gap).toFloat()+ b.map.invalidate()+ }+ private val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)++ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {+ // osmdroid: identify ourselves to the tile server (OSM tile policy) and keep+ // the tile cache inside the app's private cache.+ MapIcons.configureOsm(requireContext())+ _binding = ActivityMapBinding.inflate(inflater, container, false)+ return binding.root+ }++ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {+ tripId = args.getLong(EXTRA_TRIP_ID, -1).takeIf { it > 0 }+ if (!embedded) act.title = if (tripId == null) "Scan map" else "Recorded trace"++ // Full screen, edge-to-edge: keep the controls above the navigation bar.+ if (!embedded) ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->+ val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())+ binding.controls.updatePadding(bottom = bars.bottom + (6 * resources.displayMetrics.density).toInt())+ binding.statusBox.translationY = bars.top.toFloat()+ insets+ }++ if (args.getBoolean(EXTRA_SHOW_TOWERS, false)) com.rfsentinel.app.util.Prefs.setShowCellTowers(act, true)+ setupMap()+ binding.map.post { if (_binding != null) drawKnownAlpr() }+ // Every device heard around you by default (same colours as the list and radar).+ setupFilterChips()+ styleFollowButton()+ // Outlined "Traces" in the theme highlight (the stock dark teal was unreadable on dark themes).+ ChipStyle.accent(act).first.let { accent ->+ binding.tracesButton.setTextColor(accent)+ binding.tracesButton.strokeColor = android.content.res.ColorStateList.valueOf(accent)+ }+ binding.centerButton.setOnClickListener {+ if (tripId == null) setFollow(true) else centerOnMe()+ }+ binding.tracesButton.setOnClickListener { startActivity(Intent(act, TripsActivity::class.java)) }+ setupThemeButton()+ setupMenu()++ if (tripId == null) {+ observeBulk()+ binding.recordButton.setOnClickListener { toggleRecording() }+ viewLifecycleOwner.lifecycleScope.launch {+ viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {+ // A new or cleared Waze report is drawn at once, not at the next 3 s tick.+ val stopWaze = com.rfsentinel.app.online.WazePolice.addListener {+ activity?.runOnUiThread { if (alive && viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) renderLive() }+ }+ try {+ while (isActive) {+ renderLive()+ delay(3_000)+ }+ } finally {+ stopWaze()+ }+ }+ }+ } else {+ binding.recordButton.visibility = View.GONE+ loadTrip()+ }+ if (embedded) compactControls()+ }++ /** The main screen's filter chip, for the embedded map. */+ fun setFilter(f: DeviceFilter) {+ if (f == filter || _binding == null) { filter = f; return }+ filter = f+ if (tripId != null) loadTrip() else renderLive()+ drawTowers()+ }++ // ---- Light / dark map -----------------------------------------------------------------------------++ private fun darkTiles(): Boolean = com.rfsentinel.app.util.Prefs.mapDark(act)+ ?: ((resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==+ android.content.res.Configuration.UI_MODE_NIGHT_YES)++ /** Dark map = the OpenStreetMap tiles with their colours inverted (as in dark mode before). */+ private fun applyTiles() {+ binding.map.overlayManager.tilesOverlay.setColorFilter(if (darkTiles()) TilesOverlay.INVERT_COLORS else null)+ styleThemeButton()+ binding.map.invalidate()+ }++ private fun setupThemeButton() {+ binding.themeButton.setOnClickListener {+ val dark = !darkTiles()+ com.rfsentinel.app.util.Prefs.setMapDark(act, dark)+ applyTiles()+ Toast.makeText(act, if (dark) "Dark map" else "Light map", Toast.LENGTH_SHORT).show()+ }+ applyTiles()+ }++ private fun styleThemeButton() {+ val dark = darkTiles()+ binding.themeButton.setImageResource(if (dark) com.rfsentinel.app.R.drawable.ic_light_mode else com.rfsentinel.app.R.drawable.ic_dark_mode)+ binding.themeButton.backgroundTintList = android.content.res.ColorStateList.valueOf(0xFFFFFFFF.toInt())+ binding.themeButton.imageTintList = android.content.res.ColorStateList.valueOf(0xFF0B5C63.toInt())+ binding.themeButton.contentDescription = if (dark) "Dark map (tap for light)" else "Light map (tap for dark)"+ }++ // ---- Embedded in the main screen ------------------------------------------------------------------++ /**+ * Inside the main screen the map shares the space, so Record / Traces become small+ * round buttons on the map instead of a bar under it; everything else is the same.+ */+ private fun compactControls() {+ binding.controls.visibility = View.GONE+ binding.compactControls.visibility = View.VISIBLE+ val (accent, onAccent) = ChipStyle.accent(act)+ binding.tracesFab.backgroundTintList = android.content.res.ColorStateList.valueOf(0xFFFFFFFF.toInt())+ binding.tracesFab.imageTintList = android.content.res.ColorStateList.valueOf(0xFF0B5C63.toInt())+ binding.tracesFab.setOnClickListener { startActivity(Intent(act, TripsActivity::class.java)) }+ binding.recordFab.setOnClickListener { toggleRecording() }+ // The map on its own screen, as before (Record trace / Traces bar, its own filter chips).+ binding.fullscreenButton.visibility = View.VISIBLE+ binding.fullscreenButton.backgroundTintList = android.content.res.ColorStateList.valueOf(0xFFFFFFFF.toInt())+ binding.fullscreenButton.imageTintList = android.content.res.ColorStateList.valueOf(0xFF0B5C63.toInt())+ binding.fullscreenButton.setOnClickListener { startActivity(Intent(act, MapActivity::class.java)) }+ // A short pane has no room for four buttons stacked on the right: light / dark and full+ // screen join Record and Traces along the bottom; the compass and follow stay on the right.+ val gap = (8 * resources.displayMetrics.density).toInt()+ for (v in listOf(binding.themeButton, binding.fullscreenButton)) {+ (v.parent as? ViewGroup)?.removeView(v)+ binding.compactControls.addView(v, android.widget.LinearLayout.LayoutParams(+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = gap })+ }+ binding.recordFab.backgroundTintList = android.content.res.ColorStateList.valueOf(accent)+ binding.recordFab.imageTintList = android.content.res.ColorStateList.valueOf(onAccent)+ binding.statusText.textSize = 12f+ }++ private fun setupMap() {+ val map = binding.map+ map.setTileSource(TileSourceFactory.MAPNIK)+ map.setMultiTouchControls(true)+ // Pinch to zoom; no + / - buttons.+ map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)+ // Open where you are, not on (0, 0): the live map used to sit on open sea until the first GPS fix.+ val liveHere = tripId == null && !args.containsKey(EXTRA_CENTER_LAT)+ val knownFix = if (liveHere) knownFix() else null+ val start = if (liveHere) MapStart.pick(+ listOf(knownFix?.let { MapStart.Fix(it.latitude, it.longitude, it.time) }),+ com.rfsentinel.app.util.Prefs.lastMapCenter(act), com.rfsentinel.app.util.Prefs.mapZoom(act), System.currentTimeMillis()+ ) else null+ map.controller.setZoom(start?.zoom ?: if (liveHere) MapStart.WORLD_ZOOM else MapStart.DEFAULT_ZOOM)+ startedOnWorld = liveHere && start == null+ if (start != null) {+ map.controller.setCenter(GeoPoint(start.lat, start.lon))+ if (start.fresh) centeredOnce = true // already where you are: the first GPS fix need not move the map+ }+ map.minZoomLevel = 3.0+ map.maxZoomLevel = 20.0++ trace.outlinePaint.apply {+ color = if (tripId == null) TRACE_COLOR else PAST_TRACE_COLOR+ strokeWidth = 7f * resources.displayMetrics.density / 2+ }+ map.overlays.add(cctvCones)+ map.overlays.add(cctv)+ map.overlays.add(knownAlpr)+ map.overlays.add(towers)+ map.overlays.add(trace)+ map.overlays.add(pins)+ map.overlays.add(drones)+ map.overlays.add(wazeLayer)+ map.overlays.add(aircraft)+ // Redraw the camera layer for the visible area after panning / zooming.+ map.addMapListener(object : org.osmdroid.events.MapListener {+ override fun onScroll(event: org.osmdroid.events.ScrollEvent?) = false.also {+ drawKnownAlprSoon()+ // osmdroid stops following when you drag the map: show that on the button.+ if (following && !myLocation.isFollowLocationEnabled) setFollow(false)+ }+ override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also {+ drawKnownAlprSoon()+ // Plane icons grow as you zoom in (and shrink as you zoom out).+ val step = kotlin.math.round(binding.map.zoomLevelDouble * 2).toInt()+ if (step != planeZoomStep) { planeZoomStep = step; drawAircraft() }+ }+ })++ myLocation = object : MyLocationNewOverlay(gps, map) {+ override fun onLocationChanged(location: android.location.Location?, source: org.osmdroid.views.overlay.mylocation.IMyLocationProvider?) {+ super.onLocationChanged(arrowFix(location), source)+ if (location != null) activity?.runOnUiThread { if (alive) { turnToHeading(location); adaptGpsRate(location); autoZoomFor(location) } }+ }+ init { defaultPerson = mPersonBitmap; defaultArrow = mDirectionArrowBitmap }+ }+ if (Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) {+ myLocation.enableMyLocation()+ if (args.containsKey(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(args.getDouble(EXTRA_CENTER_LAT), args.getDouble(EXTRA_CENTER_LON)))+ centeredOnce = true+ } else if (tripId == null) {+ // Live map: keep your position centred from the first fix until you pan away.+ setFollow(true, quiet = true)+ myLocation.runOnFirstFix {+ activity?.runOnUiThread {+ if (alive && !centeredOnce) {+ centeredOnce = true+ if (following) {+ if (startedOnWorld) { startedOnWorld = false; binding.map.controller.setZoom(MapStart.DEFAULT_ZOOM) }+ centerOnMe()+ }+ }+ }+ }+ // A current position puts the arrow on the map straight away instead of after the first GPS update.+ if (start?.fresh == true) knownFix?.let { myLocation.onLocationChanged(it, null) }+ }+ }+ // Under the device dots, drones, Waze reports and aircraft (above the trace and the camera layers), so it never hides what was detected.+ map.overlays.add(map.overlays.indexOf(pins).coerceAtLeast(0), myLocation)+ setupOrientationButton()+ map.overlays.add(scaleBar)+ setup3dPinch(map)+ // The scale sits just under the status banner, or at the very top when there is none.+ binding.statusBox.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeScaleBar() }+ map.overlays.add(CopyrightOverlay(act)) // "© OpenStreetMap contributors" (required attribution)+ binding.root.addOnLayoutChangeListener { _, l, t, r, btm, ol, ot, or, ob ->+ if (r - l != or - ol || btm - t != ob - ot) binding.root.post { apply3d() }+ }+ }++ // ---- Battery: the map's own GPS ---------------------------------------------------------------------++ /**+ * The position arrow's GPS: a fix a second (2 m) while moving - smooth enough for driving -+ * and every 5 s (10 m) after a minute parked, instead of osmdroid's default of every fix.+ * Runs only while the map is on screen (off with the screen, the app in the background,+ * or the main screen's Map view turned off).+ */+ private val gps by lazy {+ GpsMyLocationProvider(act).apply { locationUpdateMinTime = GPS_MOVING_MS; locationUpdateMinDistance = 2f }+ }+ private var gpsParked = false+ private var stillSince = 0L++ private fun adaptGpsRate(fix: android.location.Location) {+ val now = android.os.SystemClock.elapsedRealtime()+ val moving = fix.hasSpeed() && fix.speed >= 1.0f+ if (moving) stillSince = 0L else if (stillSince == 0L) stillSince = now+ val parked = !moving && stillSince != 0L && now - stillSince > 60_000L+ if (parked == gpsParked) return+ gpsParked = parked+ gps.locationUpdateMinTime = if (parked) GPS_PARKED_MS else GPS_MOVING_MS+ gps.locationUpdateMinDistance = if (parked) 10f else 2f+ // Re-register with the new rate; the arrow stays where it is meanwhile.+ if (myLocation.isMyLocationEnabled) { gps.stopLocationProvider(); gps.startLocationProvider(myLocation) }+ }++ // ---- 3D driving view ---------------------------------------------------------------------------------++ private fun is3d() = tripId == null && com.rfsentinel.app.util.Prefs.map3d(act) && com.rfsentinel.app.util.Prefs.mapHeadingUp(act)++ /**+ * Like a car navigation app: heading up, the map tilted back in perspective so you see further+ * down the road, and your position low on the screen. The map view is made larger than the+ * screen and tilted (osmdroid has no 3D of its own); taps still land on the right dot.+ */+ private var pinching = false+ private var pinchSpan = 0f+ private var pinchZoom = 0.0++ /**+ * 3D pinch zoom. The map view is tilted, so Android hands it finger positions on the tilted+ * plane: near the top a tiny finger move is a long way on the map, and osmdroid's pinch zoom+ * jumps. In 3D the pinch is measured on the screen instead and zooms around your position+ * (like a car navigation app); one-finger drags and taps still go to the map.+ */+ /** The distance between two fingers on the screen itself (not on the tilted map). */+ @androidx.annotation.RequiresApi(29)+ private fun span(e: MotionEvent): Float {+ if (e.pointerCount < 2) return 0f+ val dx = e.getRawX(0) - e.getRawX(1); val dy = e.getRawY(0) - e.getRawY(1)+ return kotlin.math.hypot(dx, dy)+ }++ @android.annotation.SuppressLint("ClickableViewAccessibility")+ private fun setup3dPinch(map: org.osmdroid.views.MapView) {+ map.setOnTouchListener { v, e ->+ if (rewriting) return@setOnTouchListener false+ if (android.os.Build.VERSION.SDK_INT < 29 || !is3d()) { pinching = false; return@setOnTouchListener false }+ when (e.actionMasked) {+ MotionEvent.ACTION_POINTER_DOWN -> if (!pinching && e.pointerCount == 2) {+ // Take the gesture over: the map forgets the drag it had started.+ MotionEvent.obtain(e).apply { action = MotionEvent.ACTION_CANCEL }.also { v.dispatchTouchEvent(it); it.recycle() }+ pinching = true+ pinchSpan = span(e)+ pinchZoom = map.zoomLevelDouble+ }+ MotionEvent.ACTION_MOVE -> if (pinching) {+ val now = span(e)+ if (now > 10f && pinchSpan > 10f) {+ val z = (pinchZoom + kotlin.math.ln((now / pinchSpan).toDouble()) / kotlin.math.ln(2.0))+ .coerceIn(map.minZoomLevel, map.maxZoomLevel)+ map.controller.setZoom(z)+ autoZoom = false // your zoom now, until the follow button+ }+ }+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> if (pinching) {+ pinching = false+ drawKnownAlprSoon()+ return@setOnTouchListener true+ }+ }+ if (pinching) return@setOnTouchListener true+ // One finger (tap, drag, long-press): hand the map the point really under the finger.+ if (e.pointerCount == 1) {+ val at = screenToMap(map, e.rawX, e.rawY) ?: return@setOnTouchListener false+ val fixed = MotionEvent.obtain(e).apply { setLocation(at[0], at[1]) }+ rewriting = true+ try { v.dispatchTouchEvent(fixed) } finally { rewriting = false; fixed.recycle() }+ return@setOnTouchListener true+ }+ false+ }+ }++ private var rewriting = false++ /**+ * Where a point of the screen falls on the tilted map view: the view's own 3D matrix,+ * inverted. (Android's own conversion of touches through a tilted view is off, so taps+ * missed the icons drawn under the finger.)+ */+ private fun screenToMap(map: org.osmdroid.views.MapView, rawX: Float, rawY: Float): FloatArray? {+ val parent = map.parent as? View ?: return null+ val inverse = android.graphics.Matrix()+ if (!map.matrix.invert(inverse)) return null+ val origin = IntArray(2).also { parent.getLocationOnScreen(it) }+ val pts = floatArrayOf(rawX - origin[0] - map.left, rawY - origin[1] - map.top)+ inverse.mapPoints(pts)+ return pts+ }++ /**+ * The tilted map view's size for a [w] x [h] map area, and the centre offset that puts your+ * position a quarter of the way up: asks the view's own 3D matrix (with the tilt and camera+ * already set) where its points land, so nothing depends on screen size or density.+ * Returns width, height, centre offset (px).+ */+ private fun tiltFit(m: org.osmdroid.views.MapView, w: Int, h: Int): IntArray {+ val pt = FloatArray(2)+ // Pivot on the bottom-centre; x measured from the centre line.+ fun project(height: Float, x: Float, y: Float): FloatArray {+ m.pivotX = 0f; m.pivotY = height+ pt[0] = x; pt[1] = y+ m.matrix.mapPoints(pt)+ return pt+ }+ // Where the top edge lands on screen (from the map area's top) for a view this tall.+ fun topOnScreen(height: Float) = (h - height) + project(height, 0f, 0f)[1]+ // Smallest height whose top edge reaches the top (the edge only rises as the view grows).+ var lo = h.toFloat(); var hi = h * TILT_MAX_HEIGHT+ if (topOnScreen(hi) <= 0f) repeat(24) { val mid = (lo + hi) / 2; if (topOnScreen(mid) <= 0f) hi = mid else lo = mid }+ val height = hi + h * 0.01f+ // How much the far edge shrinks: the view must be this much wider than the area.+ val shrink = project(height, 1000f, 0f)[0] / 1000f+ val width = (w / shrink.coerceIn(0.2f, 1f)) * 1.02f+ // Your position: the point of the view that lands 3/4 of the way down the map area.+ val target = h * 0.75f+ var a = 0f; var bb = height+ repeat(24) { val mid = (a + bb) / 2; if ((h - height) + project(height, 0f, mid)[1] < target) a = mid else bb = mid }+ return intArrayOf(width.toInt(), height.toInt(), (a - height / 2f).toInt())+ }++ // ---- 3D: navigation zoom and arrow -------------------------------------------------------------++ /**+ * What the position arrow is drawn from. Heading up / 3D: below walking-to-crawling speed the+ * GPS direction is noise, and the map (rightly) stops turning - so the arrow drops it too and+ * stays pointing up, the way you were last going, instead of swinging sideways. Moving, the+ * arrow follows the GPS course, which is also what turns the map: it points straight up the road.+ */+ private fun arrowFix(fix: android.location.Location?): android.location.Location? {+ if (fix == null || !fix.hasBearing() || !alive || tripId != null || !com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) return fix+ if (fix.hasSpeed() && fix.speed >= HEADING_MIN_SPEED_MS) return fix+ return android.location.Location(fix).apply {+ @Suppress("DEPRECATION") removeBearing()+ }+ }++ /** Street-level zoom from your speed while following you in 3D; off once you pinch, back with the follow button. */+ private var autoZoom = true+ private var smoothKmh = -1f+ private var defaultPerson: android.graphics.Bitmap? = null+ private var defaultArrow: android.graphics.Bitmap? = null+ private val navArrow by lazy { navArrowIcon(resources.displayMetrics.density) }++ /** In 3D the zoom levels are shifted (screen-density tiles): the flat map's level minus this. */+ private fun tileShift() = kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0)++ /**+ * Like a car navigation app: close street level in town, gradually wider on faster roads+ * (flat-map zoom 18 up to 30 km/h, down to 16 from 110 km/h), eased in so it doesn't pump.+ */+ private fun autoZoomFor(fix: android.location.Location, now: Boolean = false) {+ val m = _binding?.map ?: return+ if (!is3d() || !autoZoom || !following || pinching) return+ val kmh = if (fix.hasSpeed()) fix.speed * 3.6f else 0f+ smoothKmh = if (smoothKmh < 0f || now) kmh else smoothKmh * 0.7f + kmh * 0.3f+ val flat = when {+ smoothKmh <= 30f -> 18.0+ smoothKmh >= 110f -> 16.0+ else -> 18.0 - (smoothKmh - 30f) / 80f * 2.0+ }+ val target = (flat - tileShift()).coerceIn(m.minZoomLevel, m.maxZoomLevel)+ if (kotlin.math.abs(target - m.zoomLevelDouble) < 0.15) return+ if (now) m.controller.setZoom(target)+ else if (!m.isAnimating) m.controller.zoomTo(target, 900L)+ }++ /** Heading up and 3D: a blue navigation arrow for your position (pointing the way you go); north up: osmdroid's own icons. */+ private fun styleMyLocation(on: Boolean) {+ if (!::myLocation.isInitialized) return+ if (on) {+ myLocation.setDirectionIcon(navArrow); myLocation.setPersonIcon(navArrow)+ myLocation.setDirectionAnchor(0.5f, 0.5f); myLocation.setPersonAnchor(0.5f, 0.5f)+ } else {+ defaultArrow?.let { myLocation.setDirectionIcon(it); myLocation.setDirectionAnchor(0.5f, 0.5f) }+ // osmdroid's person is anchored near its feet.+ defaultPerson?.let { myLocation.setPersonIcon(it); myLocation.setPersonAnchor(0.5f, 0.8125f) }+ }+ }++ private fun navArrowIcon(dp: Float): android.graphics.Bitmap {+ val size = (46 * dp).toInt()+ val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+ val c = android.graphics.Canvas(bmp)+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+ val r = size / 2f+ // Soft white disc behind, like the navigation apps' puck.+ c.drawCircle(r, r, r - 1 * dp, paint.apply { color = 0xE6FFFFFF.toInt(); style = android.graphics.Paint.Style.FILL; setShadowLayer(3 * dp, 0f, 1 * dp, 0x55000000) })+ paint.clearShadowLayer()+ val path = android.graphics.Path().apply {+ moveTo(r, 7 * dp); lineTo(size - 11 * dp, size - 10 * dp)+ lineTo(r, size - 16 * dp); lineTo(11 * dp, size - 10 * dp); close()+ }+ c.drawPath(path, paint.apply { color = 0xFF1A73E8.toInt(); style = android.graphics.Paint.Style.FILL })+ c.drawPath(path, paint.apply { color = 0xFFFFFFFF.toInt(); style = android.graphics.Paint.Style.STROKE; strokeWidth = 1.5f * dp; strokeJoin = android.graphics.Paint.Join.ROUND })+ return bmp+ }++ private fun apply3d() {+ val b = _binding ?: return+ val w = b.root.width; val h = b.root.height+ if (w == 0 || h == 0) return+ val m = b.map+ val on = is3d()+ // The tilted view is several screens' worth of map: drawn with screen-density tiles it needs+ // ~7x fewer of them (smooth zooming, readable street names). The zoom level is shifted so+ // switching in or out of 3D keeps the same scale.+ if (m.isTilesScaledToDpi != on) {+ val shift = kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0)+ val zoom = m.zoomLevelDouble + if (on) -shift else shift+ m.isTilesScaledToDpi = on+ m.controller.setZoom(zoom.coerceIn(m.minZoomLevel, m.maxZoomLevel))+ }+ m.cameraDistance = TILT_CAMERA * h+ m.rotationX = if (on) TILT_DEGREES else 0f+ val lp = m.layoutParams as android.widget.FrameLayout.LayoutParams+ var mw = w; var mh = h; var offsetY = 0+ if (on) {+ // Exact size, from the tilt itself: just tall enough that the far edge reaches the top of+ // the map area, just wide enough there to cover its width (no black corners at any size).+ val fit = tiltFit(m, w, h)+ mw = fit[0]; mh = fit[1]; offsetY = fit[2]+ }+ val wantW = if (on) mw else android.widget.FrameLayout.LayoutParams.MATCH_PARENT+ val wantH = if (on) mh else android.widget.FrameLayout.LayoutParams.MATCH_PARENT+ if (lp.width != wantW || lp.height != wantH) {+ lp.width = wantW; lp.height = wantH+ lp.gravity = if (on) android.view.Gravity.BOTTOM or android.view.Gravity.CENTER_HORIZONTAL else android.view.Gravity.NO_GRAVITY+ m.layoutParams = lp+ }+ m.pivotX = mw / 2f+ m.pivotY = mh.toFloat()+ m.setMapCenterOffset(0, offsetY)+ scaleBar.isEnabled = !on+ b.osmCredit.visibility = if (on) View.VISIBLE else View.GONE+ // The navigation arrow whenever the map turns with you (heading up and 3D).+ styleMyLocation(tripId == null && com.rfsentinel.app.util.Prefs.mapHeadingUp(act))+ if (on) lastFixForHeading?.let { autoZoomFor(it, now = true) }+ m.invalidate()+ }++ override fun onResume() {+ super.onResume()+ binding.map.onResume()+ applyTiles()+ // The location overlay's GPS runs only while the map is on screen.+ if (Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) {+ myLocation.enableMyLocation()+ if (following) myLocation.enableFollowLocation()+ }+ // Precise GPS while the map is on screen, so devices land where they were heard.+ if (tripId == null) ScanForegroundService.mapShown(act)+ // Back from Settings > Map: show what's switched on now (and nothing that was switched off).+ drawTowers()+ drawKnownAlpr()+ if (com.rfsentinel.app.util.Prefs.showCctv(act)) viewLifecycleOwner.lifecycleScope.launch {+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.rfsentinel.app.alpr.CctvStore.load(act) }+ drawCctv()+ maybeDownloadCctv()+ } else drawCctv()+ }++ override fun onPause() {+ saveView()+ if (tripId == null) ScanForegroundService.mapHidden(act)+ myLocation.disableMyLocation()+ binding.map.onPause()+ super.onPause()+ }++ override fun onDestroyView() {+ stopObservingBulk?.invoke()+ com.rfsentinel.app.alpr.CctvStore.onChanged = null+ myLocation.disableMyLocation()+ binding.map.removeCallbacks(autoDownloadCameras)+ binding.map.removeCallbacks(redrawKnownAlpr)+ // These two were left pending: one firing after onDetach() below touches detached overlays and crashes.+ binding.map.removeCallbacks(redrawCctv)+ binding.map.removeCallbacks(downloadCctv)+ binding.map.onDetach()+ _binding = null+ super.onDestroyView()+ }++ private fun setupFilterChips() {+ if (embedded) {+ binding.mapFilterScroll.visibility = View.GONE+ filter = DeviceFilter.ALL+ return+ }+ val options = if (tripId == null) DeviceFilter.entries.filter { it != DeviceFilter.RADIO } else listOf(DeviceFilter.ALL, DeviceFilter.FLAGGED)+ filter = DeviceFilter.parse(com.rfsentinel.app.util.Prefs.mapFilter(act)).takeIf { it in options } ?: DeviceFilter.ALL+ val group = binding.mapFilterChips+ for (f in options) {+ val chip = com.google.android.material.chip.Chip(act, null, com.google.android.material.R.attr.chipStyle).apply {+ id = View.generateViewId()+ text = f.label+ isCheckable = true+ isCheckedIconVisible = false+ ChipStyle.apply(this, overMap = true)+ }+ filterChips[f] = chip+ group.addView(chip)+ if (f == filter) chip.isChecked = true+ }+ group.setOnCheckedStateChangeListener { _, ids ->+ val picked = filterChips.entries.firstOrNull { it.value.id == ids.firstOrNull() }?.key ?: return@setOnCheckedStateChangeListener+ filter = picked+ com.rfsentinel.app.util.Prefs.setMapFilter(act, picked.name)+ if (tripId != null) loadTrip() else renderLive()+ drawTowers()+ }+ }++ /** Chip labels with how many devices each filter would show ("Trackers 2"). */+ private fun updateFilterCounts(devices: List<DeviceRegistry.Snapshot>) {+ val placed = devices.filter { it.bestPosition != null }+ for ((f, chip) in filterChips) {+ val n = when (f) {+ DeviceFilter.CELLS -> towerCount+ DeviceFilter.WAZE -> currentWaze().size+ else -> placed.count { f.matches(it) }+ }+ chip.text = if (f == DeviceFilter.ALL || n > 0) "${f.label} $n" else f.label+ }+ }++ // ---- North up / heading up ------------------------------------------------------------------++ /** The map button: north up (fixed) or heading up (turns with your direction of travel). */+ private fun setupOrientationButton() {+ val btn = binding.orientationButton+ if (tripId != null) { btn.visibility = View.GONE; return }+ btn.setOnClickListener {+ // North up -> heading up -> 3D driving view -> north up.+ val prefs = com.rfsentinel.app.util.Prefs+ val heading = prefs.mapHeadingUp(act); val tilt = prefs.map3d(act)+ when {+ !heading -> { prefs.setMapHeadingUp(act, true); prefs.setMap3d(act, false) }+ !tilt -> prefs.setMap3d(act, true)+ else -> { prefs.setMapHeadingUp(act, false); prefs.setMap3d(act, false) }+ }+ if (prefs.mapHeadingUp(act)) {+ lastFixForHeading?.let { turnToHeading(it, force = true) }+ // 3D only makes sense around you: follow again.+ if (prefs.map3d(act)) setFollow(true, quiet = true)+ Toast.makeText(act, if (prefs.map3d(act)) "3D driving view" else "Map turns with your direction of travel", Toast.LENGTH_SHORT).show()+ } else {+ binding.map.mapOrientation = 0f+ Toast.makeText(act, "Map fixed with north up", Toast.LENGTH_SHORT).show()+ }+ apply3d()+ styleOrientationButton()+ }+ styleOrientationButton()+ if (!com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) binding.map.mapOrientation = 0f+ }++ private fun styleOrientationButton() {+ val heading = com.rfsentinel.app.util.Prefs.mapHeadingUp(act)+ val tilt = is3d()+ val (accent, onAccent) = ChipStyle.accent(act)+ binding.orientationButton.setImageResource(when {+ tilt -> com.rfsentinel.app.R.drawable.ic_view_3d+ heading -> com.rfsentinel.app.R.drawable.ic_heading_up+ else -> com.rfsentinel.app.R.drawable.ic_north_up+ })+ binding.orientationButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (heading) accent else 0xFFFFFFFF.toInt())+ binding.orientationButton.imageTintList = android.content.res.ColorStateList.valueOf(if (heading) onAccent else 0xFF0B5C63.toInt())+ binding.orientationButton.contentDescription = when {+ tilt -> "Map: 3D driving view (tap for north up)"+ heading -> "Map: heading up (tap for the 3D driving view)"+ else -> "Map: north up (tap to turn with your direction)"+ }+ }++ private var lastFixForHeading: android.location.Location? = null++ /**+ * Heading up: the direction of travel points to the top of the screen. Only from the GPS+ * course while moving (above ~5 km/h) - stopped, the bearing is noise, so the map keeps its angle.+ */+ private fun turnToHeading(fix: android.location.Location, force: Boolean = false) {+ lastFixForHeading = fix+ if (tripId != null || !com.rfsentinel.app.util.Prefs.mapHeadingUp(act)) return+ if (!fix.hasBearing() || (!force && (!fix.hasSpeed() || fix.speed < HEADING_MIN_SPEED_MS))) return+ val target = -fix.bearing+ // Small wobbles at speed aren't worth a redraw.+ val diff = ((target - binding.map.mapOrientation + 540f) % 360f) - 180f+ if (!force && kotlin.math.abs(diff) < 3f) return+ binding.map.mapOrientation = (target + 360f) % 360f+ }++ /** Turns following on (re-centres now and keeps you centred) or off (after you pan). */+ private fun setFollow(on: Boolean, quiet: Boolean = false) {+ following = on+ if (on) {+ myLocation.enableFollowLocation()+ centerOnMe(quiet)+ autoZoom = true+ lastFixForHeading?.let { autoZoomFor(it, now = true) }+ } else {+ myLocation.disableFollowLocation()+ }+ styleFollowButton()+ }++ /** Filled with the theme highlight while following, plain otherwise. */+ private fun styleFollowButton() {+ val on = following+ val (accent, onAccent) = ChipStyle.accent(act)+ val plain = 0xFFFFFFFF.toInt()+ binding.centerButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (on) accent else plain)+ binding.centerButton.imageTintList = android.content.res.ColorStateList.valueOf(if (on) onAccent else 0xFF0B5C63.toInt())+ binding.centerButton.contentDescription = if (on) "Following your position" else "Follow my position"+ }++ private fun centerOnMe(quiet: Boolean = false) {+ val fix = myLocation.myLocation+ ?: TripRecorder.livePoints().lastOrNull()?.let { GeoPoint(it.lat, it.lon) }+ if (fix != null) goTo(fix)+ else if (!quiet) Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()+ }++ /** Glides to a nearby place; jumps when it is far (an old position, or the first fix after a long trip). */+ private fun goTo(p: GeoPoint) {+ val map = binding.map+ val here = map.mapCenter+ val far = !map.isLayoutOccurred ||+ DeviceRegistry.metersBetween(here.latitude, here.longitude, p.latitude, p.longitude) > 3_000+ if (far) map.controller.setCenter(p) else map.controller.animateTo(p)+ }++ /** The best position known before this screen's own GPS answers: the running scan's fix, else the system's last known. */+ private fun knownFix(): android.location.Location? =+ listOfNotNull(ScanForegroundService.lastFix, systemLastKnown()).maxByOrNull { it.time }++ @android.annotation.SuppressLint("MissingPermission")+ private fun systemLastKnown(): android.location.Location? {+ if (!Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION) &&+ !Permissions.granted(act, android.Manifest.permission.ACCESS_COARSE_LOCATION)) return null+ val manager = act.getSystemService(android.content.Context.LOCATION_SERVICE) as? android.location.LocationManager ?: return null+ return runCatching {+ manager.getProviders(true).mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time }+ }.getOrNull()+ }++ /** Remembers where the live map is looking, so it can open there next time. */+ private fun saveView() {+ if (tripId != null || args.containsKey(EXTRA_CENTER_LAT)) return+ val c = binding.map.mapCenter+ if (kotlin.math.abs(c.latitude) < 1e-4 && kotlin.math.abs(c.longitude) < 1e-4) return // it never looked anywhere+ // In 3D the zoom level is shifted (bigger tiles, see apply3d): save the flat map's equivalent.+ val shift = if (binding.map.isTilesScaledToDpi) kotlin.math.ln(resources.displayMetrics.density.toDouble()) / kotlin.math.ln(2.0) else 0.0+ com.rfsentinel.app.util.Prefs.saveMapView(act, c.latitude, c.longitude, binding.map.zoomLevelDouble + shift)+ }++ // ---- Live mode ----------------------------------------------------------------++ private fun renderLive() {+ val recording = TripRecorder.isRecording+ binding.recordButton.text = if (recording) "Stop recording" else "Record trace"+ val (accent, onAccent) = ChipStyle.accent(act)+ binding.recordButton.backgroundTintList = android.content.res.ColorStateList.valueOf(if (recording) 0xFFB3261E.toInt() else accent)+ val recordFg = if (recording) 0xFFFFFFFF.toInt() else onAccent+ binding.recordButton.setTextColor(recordFg)+ binding.recordButton.iconTint = android.content.res.ColorStateList.valueOf(recordFg)+ // Embedded: the round record button, red with a stop square while recording.+ binding.recordFab.backgroundTintList = android.content.res.ColorStateList.valueOf(if (recording) 0xFFB3261E.toInt() else accent)+ binding.recordFab.imageTintList = android.content.res.ColorStateList.valueOf(recordFg)+ binding.recordFab.setImageResource(if (recording) com.rfsentinel.app.R.drawable.ic_car_stop else com.rfsentinel.app.R.drawable.ic_record)+ binding.recordFab.contentDescription = if (recording) "Stop recording" else "Record trace"++ // Only the trace being recorded right now; a stopped one is under Traces.+ trace.setPoints(if (recording) TripRecorder.livePoints().map { GeoPoint(it.lat, it.lon) } else emptyList())++ // Includes devices from a scan that just stopped: the registry drops them after 3 minutes.+ val devices = DeviceRegistry.snapshot()+ val drawn = devices.mapNotNull { s ->+ val pos = s.bestPosition ?: return@mapNotNull null+ val flagged = DeviceColors.isFlagged(s)+ if (!filter.matches(s) || filter == DeviceFilter.RADIO) return@mapNotNull null+ val best = s.best+ Pin(+ s.mac, pos.lat, pos.lon,+ best?.label ?: s.name ?: s.deviceType,+ flagged,+ DeviceColors.forDevice(act, s),+ buildString {+ append(s.mac)+ s.vendor?.let { append("\n").append(it) }+ if (best != null) append("\n${best.category.title} · ${best.tier.label} ${best.confidence}%\n${best.evidence}")+ append("\nStrongest signal here: ${s.bestRssi} dBm")+ }+ )+ }+ drawPins(drawn)+ updateFilterCounts(devices)+ drawDrones(devices.filter { it.remoteId?.hasPosition == true })+ drawAircraft()+ drawWaze()++ val positioned = devices.count { it.bestPosition != null }+ val status = 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+ String.format(+ Locale.US, "● Recording %d:%02d · %.2f km · %s (%d flagged)",+ mins / 60, mins % 60, TripRecorder.distanceM / 1000, devicesLabel(TripRecorder.deviceCount()), TripRecorder.flaggedCount()+ )+ }+ positioned == 0 -> "Scanning · waiting for GPS to place devices"+ // On the main screen the device count is already in the status line above the map.+ embedded -> null+ else -> "Scanning · ${drawn.size} on map" + if (filter != DeviceFilter.ALL) " (${filter.label} only)" else ""+ }+ val text = listOfNotNull(status, cctvLine).joinToString("\n")+ binding.statusText.text = text+ binding.statusText.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE+ binding.statusText.background.mutate().setTint(if (recording) 0xFFB3261E.toInt() else 0xCC0B5C63.toInt())+ binding.map.invalidate()+ }++ private fun toggleRecording() {+ if (TripRecorder.isRecording) {+ viewLifecycleOwner.lifecycleScope.launch {+ val id = TripRecorder.activeTripId+ TripRecorder.stop(act)+ refreshServiceLocation()+ val saved = id?.let { AppDatabase.getInstance(act).tripDao().get(it) }+ if (saved != null) {+ AlertDialog.Builder(act)+ .setTitle("Trace saved")+ .setMessage(String.format(Locale.US, "%s\n%.2f km · %s (%d flagged)",+ saved.name, saved.distanceM / 1000, devicesLabel(saved.deviceCount), saved.flaggedCount))+ .setPositiveButton("View") { _, _ -> openTrip(saved.id) }+ .setNeutralButton("Export") { _, _ -> Exporter.showTripExport(act, saved.id) }+ .setNegativeButton("Close", null)+ .show()+ } else {+ Toast.makeText(act, "Nothing recorded (no GPS fix)", Toast.LENGTH_LONG).show()+ }+ renderLive()+ }+ return+ }+ if (Permissions.missingRequired(act).isNotEmpty()) {+ Toast.makeText(act, "Grant location and nearby-devices first (Start scanning on the main screen)", Toast.LENGTH_LONG).show()+ return+ }+ viewLifecycleOwner.lifecycleScope.launch {+ if (!ScanForegroundService.isRunning) {+ runCatching { ScanForegroundService.start(act) }+ delay(600)+ }+ TripRecorder.start(act)+ refreshServiceLocation()+ Toast.makeText(act, "Recording your trace - keeps going with the screen off", Toast.LENGTH_SHORT).show()+ renderLive()+ }+ }++ /** Tells the running service to switch location updates to trace mode (or back). */+ private fun refreshServiceLocation() {+ // Only a running scanner needs refreshing; sending it otherwise would start scanning.+ if (!ScanForegroundService.isRunning) return+ runCatching {+ act.startService(Intent(act, ScanForegroundService::class.java).setAction(ScanForegroundService.ACTION_REFRESH_LOCATION))+ }+ }++ private fun openTrip(id: Long) {+ startActivity(Intent(act, MapActivity::class.java).putExtra(EXTRA_TRIP_ID, id))+ }++ // ---- Trip mode ------------------------------------------------------------------++ private fun loadTrip() {+ val id = tripId ?: return+ viewLifecycleOwner.lifecycleScope.launch {+ val dao = AppDatabase.getInstance(act).tripDao()+ val t = dao.get(id) ?: run { act.finish(); return@launch }+ trip = t+ val points = dao.points(id).map { GeoPoint(it.lat, it.lon) }+ val devices = dao.devices(id)+ trace.setPoints(points)+ drawPins(devices.filter { it.lat != null && (it.flagged || filter == DeviceFilter.ALL) }.map { it.toPin() })+ val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000+ binding.statusText.text = String.format(+ Locale.US, "%s\n%s · %d:%02d · %.2f km · %s (%d flagged)",+ t.name, dateFmt.format(Date(t.startTime)), mins / 60, mins % 60, t.distanceM / 1000,+ devicesLabel(t.deviceCount), t.flaggedCount+ )+ binding.statusText.background.mutate().setTint(0xCC1F5FBF.toInt())+ val all = points + devices.filter { it.lat != null }.map { GeoPoint(it.lat!!, it.lon!!) }+ if (all.isNotEmpty()) {+ binding.map.post {+ if (all.size == 1) binding.map.controller.setCenter(all[0])+ else binding.map.zoomToBoundingBox(BoundingBox.fromGeoPoints(all).increaseByScale(1.3f), false)+ }+ }+ binding.map.invalidate()+ }+ }++ private fun TripDeviceEntity.toPin(): Pin {+ val cat = Category.parse(category)+ return Pin(+ mac, lat!!, lon!!, label, flagged,+ DeviceColors.forMatch(act, if (flagged) cat else null, confidence),+ buildString {+ append(mac)+ vendor?.let { append("\n").append(it) }+ if (cat != null) append("\n${cat.title} · ${Tier.of(confidence).label} $confidence%")+ evidence?.let { append("\n").append(it) }+ probedList.takeIf { it.isNotEmpty() }?.let { append("\nAsked for networks: ").append(it.joinToString(", ")) }+ append("\nStrongest signal here: $bestRssi dBm")+ append("\nHeard ${dateFmt.format(Date(firstSeen))}")+ }+ )+ }++ // ---- Drawing ----------------------------------------------------------------------++ /**+ * 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>) {+ // 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)+ }+ }++ /**+ * Drones place themselves: Remote ID broadcasts the aircraft's own GPS fix+ * (and usually the operator's / take-off point), so these markers are real+ * positions, unlike RSSI-based device pins.+ */+ private fun drawDrones(list: List<DeviceRegistry.Snapshot>) {+ drones.items.clear()+ val dp = resources.displayMetrics.density+ for (s in list) {+ val r = s.remoteId ?: continue+ val aircraft = GeoPoint(r.latitude!!, r.longitude!!)+ val details = droneDetails(s, r)+ if (r.hasOperatorPosition) {+ val operator = GeoPoint(r.operatorLatitude!!, r.operatorLongitude!!)+ drones.add(Polyline().apply {+ setPoints(listOf(operator, aircraft))+ outlinePaint.apply {+ color = DRONE_COLOR+ strokeWidth = 2.5f * dp+ pathEffect = android.graphics.DashPathEffect(floatArrayOf(10 * dp, 6 * dp), 0f)+ }+ })+ drones.add(Marker(binding.map).apply {+ position = operator+ icon = GradientDrawable().apply {+ shape = GradientDrawable.RECTANGLE+ setColor(0xFFF5E100.toInt())+ setStroke((2 * dp).toInt(), DRONE_COLOR)+ setSize((14 * dp).toInt(), (14 * dp).toInt())+ }+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ title = "Drone operator / take-off point"+ setOnMarkerClickListener { _, _ -> showDrone(s, "Operator of this drone (or its take-off point)\n\n$details"); true }+ })+ }+ drones.add(Marker(binding.map).apply {+ position = aircraft+ icon = android.graphics.drawable.BitmapDrawable(resources, droneArrow(dp))+ rotation = -(r.directionDeg ?: 0).toFloat() // osmdroid rotates counter-clockwise+ isFlat = true+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ title = "Drone"+ setOnMarkerClickListener { _, _ -> showDrone(s, details); true }+ })+ }+ }++ /** The Waze reports from the checker, which clears them when it stops. */+ private fun currentWaze(): List<com.rfsentinel.app.online.WazePolice.Shown> = com.rfsentinel.app.online.WazePolice.latest++ /**+ * Waze reports as coloured dots (blue police, red accident, orange hazard, brown closure,+ * purple jam) with a white outline. Tap one for what it is, how far, how old, how many confirmed.+ */+ private fun drawWaze() {+ wazeLayer.items.clear()+ val show = tripId == null && (filter == DeviceFilter.ALL || filter == DeviceFilter.WAZE)+ if (show) {+ val dp = resources.displayMetrics.density+ for (w in currentWaze()) {+ wazeLayer.add(Marker(binding.map).apply {+ position = GeoPoint(w.report.lat, w.report.lon)+ icon = GradientDrawable().apply {+ shape = GradientDrawable.OVAL+ setColor(w.report.type.color)+ setStroke((2 * dp).toInt(), android.graphics.Color.WHITE)+ setSize((20 * dp).toInt(), (20 * dp).toInt())+ }+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ title = w.hit.label+ setOnMarkerClickListener { _, _ -> showWaze(w); true }+ })+ }+ }+ binding.map.invalidate()+ }++ private fun showWaze(w: com.rfsentinel.app.online.WazePolice.Shown) {+ AlertDialog.Builder(act)+ .setTitle(w.hit.label)+ .setMessage("${w.hit.tier.label} ${w.hit.confidence}%\n${com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend)}\n${w.hit.evidence}")+ .setNegativeButton("Close", null)+ .show()+ }++ /**+ * Aircraft from the latest ADS-B poll: police / government / circling ones in bold+ * purple with their agency and altitude, every other aircraft small and grey, each+ * pointing along its track. Tap one for its details.+ */+ private fun drawAircraft() {+ aircraft.items.clear()+ binding.map.invalidate()+ val list = com.rfsentinel.app.online.PoliceAircraft.latest+ if (list.isEmpty() || System.currentTimeMillis() - com.rfsentinel.app.online.PoliceAircraft.latestAt > 3 * 60_000L) return+ val dp = resources.displayMetrics.density+ // Sized to the zoom: 0.5x at a city-wide view (zoom 10), 1x at zoom 13, 2.2x at street level (17+).+ val scale = (0.5 + (binding.map.zoomLevelDouble - 10.0) * (1.7 / 7.0)).coerceIn(0.5, 2.2).toFloat()+ val icons = HashMap<Boolean, android.graphics.drawable.BitmapDrawable>()+ // Ordinary traffic first, so flagged aircraft are drawn on top.+ for ((p, hit) in list.sortedBy { it.hit != null }) {+ val flagged = hit != null+ val at = GeoPoint(p.lat, p.lon)+ aircraft.add(Marker(binding.map).apply {+ position = at+ icon = icons.getOrPut(flagged) { android.graphics.drawable.BitmapDrawable(resources, MapIcons.planeIcon(dp, flagged, scale)) }+ rotation = -(p.trackDeg ?: 0.0).toFloat() // osmdroid rotates counter-clockwise+ isFlat = true+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)+ setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }+ })+ if (flagged) {+ val label = listOfNotNull(+ hit!!.label.substringAfter(": ", hit.label).take(28),+ p.altitudeFt?.takeIf { it > 0 }?.let { "$it ft" }+ ).joinToString(" · ")+ aircraft.add(Marker(binding.map).apply {+ position = at+ icon = android.graphics.drawable.BitmapDrawable(resources, aircraftLabel(dp, label))+ setAnchor(Marker.ANCHOR_CENTER, -0.9f) // just below the plane, never rotated+ setOnMarkerClickListener { _, _ -> showAircraft(p, hit); true }+ })+ }+ }+ }++ private fun aircraftLabel(dp: Float, text: String): android.graphics.Bitmap {+ val p = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {+ textSize = 11 * dp+ color = android.graphics.Color.WHITE+ typeface = android.graphics.Typeface.DEFAULT_BOLD+ }+ val pad = 4 * dp+ val w = (p.measureText(text) + 2 * pad).toInt()+ val h = (p.textSize + 2 * pad).toInt()+ val bmp = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)+ val c = android.graphics.Canvas(bmp)+ val bg = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply { color = MapIcons.POLICE_AIRCRAFT_COLOR }+ c.drawRoundRect(android.graphics.RectF(0f, 0f, w.toFloat(), h.toFloat()), 4 * dp, 4 * dp, bg)+ c.drawText(text, pad, h - pad - p.descent() / 2, p)+ return bmp+ }++ private fun showAircraft(p: com.rfsentinel.app.online.PoliceAircraft.Plane, hit: com.rfsentinel.app.detect.Hit?) {+ val me = myLocation.myLocation+ val text = buildString {+ hit?.let { append(it.evidence).append("\n\n") }+ p.registration?.let { append("Registration: $it\n") }+ p.callsign?.let { append("Callsign: $it\n") }+ p.type?.let { append("Type: $it\n") }+ p.owner?.let { append("Owner / operator: $it\n") }+ p.altitudeFt?.let { append(if (it <= 0) "On the ground\n" else "Altitude: $it ft\n") }+ p.speedKt?.let { append(String.format(Locale.US, "Speed: %.0f kt (%.0f km/h)\n", it, it * 1.852)) }+ p.trackDeg?.let { append(String.format(Locale.US, "Heading: %.0f°\n", it)) }+ me?.let { append(String.format(Locale.US, "Distance: %.1f km\n",+ DeviceRegistry.metersBetween(it.latitude, it.longitude, p.lat, p.lon) / 1000)) }+ append("ICAO address: ${p.hex.uppercase()}\nSource: community ADS-B (adsb.fi / adsb.lol)")+ }+ AlertDialog.Builder(act)+ .setTitle(hit?.label ?: (p.registration ?: p.callsign ?: "Aircraft"))+ .setMessage(text)+ .setPositiveButton("OK", null)+ .show()+ }++ private fun droneDetails(s: DeviceRegistry.Snapshot, r: com.rfsentinel.app.detect.RemoteId.Info) = buildString {+ r.uasId?.let { append("ID: $it\n") }+ r.uaType?.let { append("Type: $it\n") }+ r.status?.let { append("Status: $it\n") }+ r.heightM?.let { append(String.format(Locale.US, "Height: %.0f m\n", it)) }+ r.altitudeGeoM?.let { append(String.format(Locale.US, "Altitude (GPS): %.0f m\n", it)) }+ r.speedMs?.let { append(String.format(Locale.US, "Speed: %.0f km/h\n", it * 3.6)) }+ r.directionDeg?.let { append("Heading: $it°\n") }+ r.operatorId?.let { append("Operator ID: $it\n") }+ r.selfIdDescription?.let { append("Description: $it\n") }+ append("Radio: ${s.mac} · ${s.rssi} dBm")+ }++ private fun showDrone(s: DeviceRegistry.Snapshot, text: String) {+ AlertDialog.Builder(act)+ .setTitle("Drone (Remote ID)")+ .setMessage(text + "\n\nPositions are broadcast by the drone itself (ASTM F3411 Remote ID).")+ .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(act, s.mac) }+ .setNegativeButton("Close", null)+ .show()+ }++ /** A blue arrow pointing north; the marker rotation turns it to the drone's heading. */+ private fun droneArrow(dp: Float): android.graphics.Bitmap {+ val size = (30 * dp).toInt()+ val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+ val c = android.graphics.Canvas(bmp)+ val path = android.graphics.Path().apply {+ moveTo(size / 2f, 2 * dp); lineTo(size - 5 * dp, size - 4 * dp)+ lineTo(size / 2f, size * 0.68f); lineTo(5 * dp, size - 4 * dp); close()+ }+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+ c.drawPath(path, paint.apply { color = DRONE_COLOR; style = android.graphics.Paint.Style.FILL })+ c.drawPath(path, paint.apply { color = Color.WHITE; style = android.graphics.Paint.Style.STROKE; strokeWidth = 2 * dp })+ return bmp+ }++ // ---- Known plate, speed and red-light cameras (OpenStreetMap) --------------------------------------------++ private val redrawKnownAlpr = Runnable { if (alive) drawKnownAlpr() }++ private fun drawKnownAlprSoon() {+ binding.map.removeCallbacks(redrawKnownAlpr)+ binding.map.postDelayed(redrawKnownAlpr, 250)+ binding.map.removeCallbacks(redrawCctv)+ binding.map.postDelayed(redrawCctv, 250)+ }++ // ---- CCTV cameras (OpenStreetMap) ---------------------------------------------------------------++ private val redrawCctv = Runnable { if (alive) drawCctv() }+ private fun drawCctvSoon() {+ binding.map.removeCallbacks(redrawCctv)+ binding.map.postDelayed(redrawCctv, 300)+ }+ private val downloadCctv = Runnable { if (alive) maybeDownloadCctv() }++ /** Below this zoom the layer is hidden (cities hold thousands of cameras); view cones from [cctvConeZoom]. */+ private val cctvMinZoom = 12.0+ private val cctvConeZoom = 15.0++ /** What the CCTV layer is doing, added to the status line (null while the layer is off). */+ @Volatile private var cctvLine: String? = null++ private fun setCctvLine(text: String?) {+ if (text == cctvLine) return+ cctvLine = text+ if (tripId == null) renderLive()+ }++ private fun drawCctv() {+ com.rfsentinel.app.alpr.CctvStore.onChanged = { if (alive) drawCctvSoon() }+ val map = binding.map+ val on = com.rfsentinel.app.util.Prefs.showCctv(act) && tripId == null+ if (!on || map.zoomLevelDouble < cctvMinZoom) {+ if (cctv.points.isNotEmpty() || cctvCones.cameras.isNotEmpty()) {+ cctv.points = emptyList(); cctvCones.cameras = emptyList(); map.invalidate()+ }+ setCctvLine(if (!on) null else com.rfsentinel.app.alpr.CctvStore.progress?.let { "CCTV: downloading around you, $it" }+ ?: "CCTV: zoom in to see the cameras")+ return+ }+ map.removeCallbacks(downloadCctv)+ map.postDelayed(downloadCctv, 1_200)+ val private = com.rfsentinel.app.util.Prefs.cctvPrivate(act)+ val box = map.boundingBox.increaseByScale(1.5f)+ val center = map.mapCenter+ val inView = com.rfsentinel.app.alpr.CctvStore.cameras.filter {+ (private || !it.isPrivate) && it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast+ }.let { all ->+ // Zoomed out over a city: the ones nearest the centre of the screen.+ if (all.size <= 3000) all+ else all.sortedBy { (it.lat - center.latitude).let { d -> d * d } + (it.lon - center.longitude).let { d -> d * d } }.take(3000)+ }+ val dp = resources.displayMetrics.density+ val publicIcon = MapIcons.cctvIcon(dp, false); val privateIcon = MapIcons.cctvIcon(dp, true)+ cctvCones.cameras = if (map.zoomLevelDouble >= cctvConeZoom) inView else emptyList()+ cctv.points = inView.map { PointsOverlay.Point(it.lat, it.lon, it, icon = if (it.isPrivate) privateIcon else publicIcon) }+ map.invalidate()+ val store = com.rfsentinel.app.alpr.CctvStore+ val view = map.boundingBox+ val hiddenPrivate = if (private) 0 else store.cameras.count {+ it.isPrivate && it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast+ }+ val shown = inView.count { it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast }+ setCctvLine(when {+ store.progress != null -> "CCTV: downloading around you, ${store.progress}"+ store.isBusy -> "CCTV: downloading..."+ System.currentTimeMillis() - store.lastFailureAt < 60_000 -> "CCTV: map server busy - retrying"+ store.missingAreas > 0 && shown > 0 -> "CCTV: $shown in view - ${store.missingAreas} area(s) around you still missing (servers busy), retried next time"+ shown == 0 && store.needsDownload(view.latSouth, view.lonWest, view.latNorth, view.lonEast) -> "CCTV: downloading..."+ shown == 0 && hiddenPrivate > 0 -> "CCTV: only private ones here ($hiddenPrivate) - Settings > Known cameras > Include private"+ shown == 0 -> "CCTV: none mapped here"+ else -> "CCTV: $shown in view" + if (hiddenPrivate > 0) " (+$hiddenPrivate private hidden)" else ""+ })+ }++ /**+ * Fetches the CCTV cameras within the download radius around you (once, in the+ * background), and the area on screen when you look somewhere outside it.+ */+ private fun maybeDownloadCctv() {+ val map = binding.map+ if (!com.rfsentinel.app.util.Prefs.showCctv(act) || tripId != null) return+ val store = com.rfsentinel.app.alpr.CctvStore+ if (map.isAnimating || store.isBusy) { map.postDelayed(downloadCctv, 2_000); return }+ val here = myLocation.myLocation ?: ScanForegroundService.lastFix?.let { GeoPoint(it.latitude, it.longitude) }+ if (here != null) {+ val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(act).toDouble()+ store.ensureAround(act, here.latitude, here.longitude, radius)+ if (store.isBusy) return+ }+ if (map.zoomLevelDouble < cctvMinZoom) return+ val box = map.boundingBox+ viewLifecycleOwner.lifecycleScope.launch {+ com.rfsentinel.app.alpr.CctvStore.autoDownload(act, box.latSouth, box.lonWest, box.latNorth, box.lonEast)+ // Redraw either way: new cameras, or the status line (none mapped / server busy).+ drawCctv()+ // After a failure, try again once the back-off has passed.+ if (System.currentTimeMillis() - com.rfsentinel.app.alpr.CctvStore.lastFailureAt < 60_000)+ binding.map.postDelayed(downloadCctv, 61_000)+ }+ }++ private fun showCctv(c: com.rfsentinel.app.alpr.CctvCamera) {+ val text = buildString {+ append(when (c.zone) {+ "public" -> "Watches a public space (street, square, station...).\n"+ "outdoor" -> "A private camera that watches outside (an entrance, a car park...).\n"+ "indoor" -> "Inside a building or shop.\n"+ else -> "Whether it watches public space isn't mapped.\n"+ })+ c.area?.let { append("Watches: $it\n") }+ c.operator?.let { append("Operator: $it\n") }+ c.mount?.let { append("Mounted on: $it\n") }+ c.height?.let { append("Height: ${"%.0f".format(it)} m\n") }+ c.direction?.let { append("Faces: $it°" + (c.angle?.let { a -> ", $a° wide" } ?: "") + "\n") }+ append("OSM: ${c.osmId}\n\n")+ append("Mapped by OpenStreetMap volunteers. Most of these cameras are wired and give off no Bluetooth or WiFi " ++ "signal, so the scan can't detect them - this layer shows the ones that have been mapped. " ++ "The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")+ }+ AlertDialog.Builder(act)+ .setTitle(com.rfsentinel.app.alpr.Cctv.title(c))+ .setMessage(text)+ .setPositiveButton("Close", null)+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->+ runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${c.osmId}"))) }+ }+ .show()+ }++ private val autoDownloadCameras = Runnable { if (alive) maybeAutoDownloadCameras() }++ /**+ * Fetches the cameras for the area on screen when it isn't cached yet, so+ * they're always on the map without a manual download. Runs once the map+ * has stopped moving for a moment.+ */+ private fun maybeAutoDownloadCameras() {+ val prefs = com.rfsentinel.app.util.Prefs+ if (!prefs.autoCameras(act) || !prefs.showKnownAlpr(act) || tripId != null) return+ // Still gliding to your position (or another target): wait until it stops.+ if (binding.map.isAnimating) { binding.map.postDelayed(autoDownloadCameras, 1_000); return }+ val box = binding.map.boundingBox+ val span = com.rfsentinel.app.alpr.AlprStore.MAX_SPAN_DEG+ if (box.latNorth - box.latSouth > span || box.lonEast - box.lonWest > span) return+ // The map starts at 0°,0° until it's moved to your position: don't fetch the ocean.+ if (kotlin.math.abs(box.centerLatitude) < 0.5 && kotlin.math.abs(box.centerLongitude) < 0.5) return+ // Another download (e.g. the car screen's) is running: look again shortly.+ if (com.rfsentinel.app.alpr.AlprStore.isBusy) { binding.map.postDelayed(autoDownloadCameras, 3_000); return }+ viewLifecycleOwner.lifecycleScope.launch {+ val changed = com.rfsentinel.app.alpr.AlprStore.autoDownload(+ act, box.latSouth, box.lonWest, box.latNorth, box.lonEast+ )+ // Redrawing also re-checks the area now on screen, in case the map moved meanwhile.+ if (changed) { drawKnownAlpr(); refreshServiceLocation() }+ }+ }++ /** Draws the cameras in (and just around) the visible area; skipped when zoomed far out. */+ private fun drawKnownAlpr() {+ val map = binding.map+ map.removeCallbacks(autoDownloadCameras)+ map.postDelayed(autoDownloadCameras, 1_200)+ if (!com.rfsentinel.app.util.Prefs.showKnownAlpr(act) || map.zoomLevelDouble < 9.0) {+ 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 { 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(act, cam.osmId)+ PointsOverlay.Point(cam.lat, cam.lon, cam, icon = icons.getValue(cam.type), alpha = if (ignored) 90 else 255)+ }+ knownAlprDrawnFor = box+ map.invalidate()+ }++ private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = MapIcons.cameraIcon(dp, kind)++ private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {+ val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(act, cam.osmId)+ val text = buildString {+ if (ignored) append("Alerts for this camera are off.\n\n")+ append(when (cam.type) {+ com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "A license-plate reader mapped in OpenStreetMap.\n\n"+ com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "A speed camera mapped in OpenStreetMap.\n\n"+ com.rfsentinel.app.alpr.KnownCamera.Kind.RED_LIGHT -> "A red-light camera mapped in OpenStreetMap.\n\n"+ })+ cam.brand?.let { append("Maker: $it\n") }+ cam.operator?.let { append("Operator: $it\n") }+ cam.direction?.let { append("Faces: $it°\n") }+ append("OSM: ${cam.osmId}\n\n")+ append("These cameras send their data over cellular or wire and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning. Mobile speed cameras move and are rarely mapped.\n\nMap data © OpenStreetMap contributors (ODbL).")+ }+ AlertDialog.Builder(act)+ .setTitle(cam.label)+ .setMessage(text)+ // Kept until turned back on here (or cleared in Settings).+ .setPositiveButton(if (ignored) "Alert again" else "Ignore alerts") { _, _ ->+ com.rfsentinel.app.alpr.IgnoredCameras.set(act, cam.osmId, !ignored)+ Toast.makeText(act, if (ignored) "You'll be warned about this camera again"+ else "No more alerts for this camera (tap it again to undo)", Toast.LENGTH_SHORT).show()+ drawKnownAlpr()+ }+ .setNegativeButton("Close", null)+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->+ runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }+ }+ .show()+ }++ /** Towers with a map position (the Cells chip's count), refreshed with the layer. */+ private var towerCount = 0++ private fun drawTowers() {+ towerCount = com.rfsentinel.app.service.CellTowerStore.all(act).count { it.bestLat != null }+ // The Cells chip shows the towers (only them); All adds them when the map menu's switch is on;+ // every other chip hides them.+ val show = filter == DeviceFilter.CELLS ||+ (filter == DeviceFilter.ALL && com.rfsentinel.app.util.Prefs.showCellTowers(act))+ towers.points = if (tripId != null || !show) emptyList()+ else com.rfsentinel.app.service.CellTowerStore.all(act).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(act)+ .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(act, 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(act)+ .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(act)+ .setTitle(p.label)+ .setMessage(p.details + "\n\nPosition = where your phone was when this device's signal was strongest (approximate).")+ .setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(act, p.mac) }+ .setNegativeButton("Close", null)+ .show()+ }++ private var stopObservingBulk: (() -> Unit)? = null++ /** Status text while a DeFlock download runs, or null when none does. */+ private fun bulkStatus(): String? = when (val s = com.rfsentinel.app.alpr.DeflockBulk.state) {+ is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading ->+ "Downloading plate cameras · ${s.detail.ifEmpty { "${s.done}/${s.total} regions" }} · ${s.found} found"+ is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras ->+ "${s.cameras} plate cameras on the map · checking OpenStreetMap for more (up to 45 s)..."+ else -> null+ }++ /** Follows every DeFlock download (from here, Settings or the weekly refresh) with the progress bar. */+ private fun observeBulk() {+ stopObservingBulk = com.rfsentinel.app.alpr.DeflockBulk.observe { s ->+ if (!alive) return@observe+ val bar = binding.downloadProgress+ when (s) {+ is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading -> {+ if (bar.isIndeterminate) { bar.visibility = View.INVISIBLE; bar.isIndeterminate = false }+ bar.visibility = View.VISIBLE+ bar.setProgressCompat((s.fraction * 100).toInt(), true)+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras -> {+ // DeFlock's cameras are saved: show them now; the bar keeps moving for the extras.+ com.rfsentinel.app.util.Prefs.setShowKnownAlpr(act, true)+ drawKnownAlpr(); refreshServiceLocation()+ bar.visibility = View.INVISIBLE; bar.isIndeterminate = true; bar.visibility = View.VISIBLE+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.Done -> {+ bar.visibility = View.GONE+ drawKnownAlpr(); refreshServiceLocation()+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.Failed -> {+ bar.visibility = View.GONE+ }+ com.rfsentinel.app.alpr.DeflockBulk.State.Idle -> bar.visibility = View.GONE+ }+ bulkStatus()?.let { binding.statusText.text = it; binding.statusText.visibility = View.VISIBLE }+ }+ }++ // ---- Menu ---------------------------------------------------------------------------++ /** Full screen: the action bar's menu. Embedded, the main screen's menu has the same items (Waze, Settings). */+ private fun setupMenu() {+ if (embedded) return+ act.addMenuProvider(object : MenuProvider {+ override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) = addMenuItems(menu)+ override fun onMenuItemSelected(menuItem: MenuItem) = onMenuItem(menuItem.itemId)+ }, viewLifecycleOwner, Lifecycle.State.RESUMED)+ }++ private fun addMenuItems(menu: Menu) {+ if (tripId != null) {+ menu.add(0, 1, 0, "Export trace...")+ menu.add(0, 2, 1, "Rename")+ menu.add(0, 3, 2, "Delete")+ } else {+ menu.add(0, 13, 1, "Check Waze now")+ menu.add(0, 14, 2, "Waze status")+ // The map's options live in Settings > Map.+ menu.add(0, 12, 0, "Map settings").apply {+ setIcon(com.rfsentinel.app.R.drawable.ic_settings)+ setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)+ }+ }+ }++ private fun onMenuItem(itemId: Int): Boolean {+ val id = tripId+ return when (itemId) {+ 1 -> { id?.let { Exporter.showTripExport(act, it) }; true }+ 2 -> { id?.let { rename(it) }; true }+ 3 -> { id?.let { confirmDelete(it) }; true }+ 12 -> {+ startActivity(Intent(act, com.rfsentinel.app.settings.SettingsActivity::class.java)+ .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION,+ com.rfsentinel.app.settings.SettingsActivity.SECTION_MAP))+ true+ }+ 13 -> { WazeUi.checkNow(act); true }+ 14 -> { WazeUi.openStatus(act); true }+ else -> false+ }+ }++ private fun rename(id: Long) {+ val input = EditText(act).apply { setText(trip?.name ?: ""); setSelection(text.length) }+ AlertDialog.Builder(act)+ .setTitle("Rename trace")+ .setView(input)+ .setPositiveButton("Save") { _, _ ->+ viewLifecycleOwner.lifecycleScope.launch {+ AppDatabase.getInstance(act).tripDao().rename(id, input.text.toString().trim().ifEmpty { "Trace" })+ loadTrip()+ }+ }+ .setNegativeButton("Cancel", null)+ .show()+ }++ private fun confirmDelete(id: Long) {+ AlertDialog.Builder(act)+ .setTitle("Delete this trace?")+ .setMessage("The route and its device list are deleted from this phone.")+ .setPositiveButton("Delete") { _, _ ->+ viewLifecycleOwner.lifecycleScope.launch {+ AppDatabase.getInstance(act).tripDao().delete(id)+ act.finish()+ }+ }+ .setNegativeButton("Cancel", null)+ .show()+ }+}++/** "1 device" / "3 devices". */+internal fun devicesLabel(n: Int) = if (n == 1) "1 device" else "$n devices"diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.ktindex 529b609..442ffd7 100644--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt@@ -84,7 +84,8 @@ class MonitorFrames {}// Probe request: a device looking for networks (e.g. a laptop or a Flock camera),// often by name - the networks it has joined before.- 4 -> if (captureClients) touch(a2, ap = false)?.let { s ->+ // (Bare scanner probes - a fresh random address each burst - are skipped: see isScannerProbe.)+ 4 -> if (captureClients && !isScannerProbe(b, d, end)) touch(a2, ap = false)?.let { s ->val ies = Ies.read(b, d + 24, end)ies.wps?.let { s.wps = it }ProbeIntel.fingerprint(b, d + 24, end)?.let { s.fingerprint = it }@@ -108,6 +109,22 @@ class MonitorFrames {}}+ /**+ * A bare broadcast probe as sent by ESP32 scanners (OUI-SPY's survey engine, GhostESP):+ * empty SSID and only the four 802.11b rates, nothing else, from a new random address+ * after every channel hop. Phones and laptops always add more elements. Counting them+ * would add a "new device" every second while such a board scans next to the adapter.+ */+ internal fun isScannerProbe(b: ByteArray, d: Int, end: Int): Boolean {+ val body = d + 24+ val rest = end - (body + 8)+ if (rest != 0 && rest != 4) return false // + FCS when the driver keeps it+ fun u8(i: Int) = b[i].toInt() and 0xff+ if ((u8(d + 10) and 0x02) == 0) return false // locally administered (random) source+ return u8(body) == 0 && u8(body + 1) == 0 && u8(body + 2) == 1 && u8(body + 3) == 4 &&+ u8(body + 4) == 0x82 && u8(body + 5) == 0x84 && u8(body + 6) == 0x8B && u8(body + 7) == 0x96+ }+private fun revealFromAssociation(b: ByteArray, from: Int, end: Int, bssid: String) {if (from >= end) returnval name = Ies.read(b, from, end).ssid?.takeIf { validSsid(it) } ?: returndiff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.ktindex 7d67c11..801b6e7 100644--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt@@ -27,7 +27,12 @@ object Rtl8821auMonitor {@Volatile private var stop = falseprivate val frames = MonitorFrames()- private val HOP = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)+ private val HOP_24 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)+ /** UNII-1 and UNII-3, like the RTL8814AU driver (where most 5 GHz networks are). */+ private val HOP_5 = intArrayOf(36, 40, 44, 48, 149, 153, 157, 161, 165)+ /** Settings > External hardware: also hop 5 GHz (experimental); read when the adapter starts. */+ @Volatile var scan5g = false+ private var HOP = HOP_24private const val DWELL_MS = 350Lprivate val FRESH_MS get() = (HOP.size * DWELL_MS * 9 / 5).coerceAtLeast(3000L)@@ -87,6 +92,8 @@ object Rtl8821auMonitor {w16(conn, Rtl8821auTables.REG_RXFLTMAP0, Rtl8821auTables.RXFLTMAP_ALL)w16(conn, Rtl8821auTables.REG_RXFLTMAP1, Rtl8821auTables.RXFLTMAP_ALL)w16(conn, Rtl8821auTables.REG_RXFLTMAP2, Rtl8821auTables.RXFLTMAP_ALL)+ HOP = if (scan5g) HOP_24 + HOP_5 else HOP_24+ if (scan5g) UsbWifi.log("RTL8821AU: 5 GHz hopping on (experimental): ${HOP.joinToString()}")channelTune(conn, HOP[0])UsbWifi.log("RTL8821AU: RCR=0x%08x BB(0x800)=0x%08x — monitor live ch ${HOP[0]}".format(r32(conn, Rtl8821auTables.REG_RCR), r32(conn, 0x800)))@@ -136,7 +143,7 @@ object Rtl8821auMonitor {}private fun channelTune(conn: UsbDeviceConnection, ch: Int) {- for (op in Rtl8821auTables.channelTune(ch)) {+ for (op in Rtl8821auTables.channelTune(ch, bandSwitch = scan5g)) {val kind = op[0]; val addr = op[1]; val mask = op[2]; val v = op[3]when (kind) {Rtl8821auTables.RF -> rfMask(conn, addr, mask, v)diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auTables.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auTables.ktindex addc4dc..69b8bc0 100644--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auTables.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auTables.kt@@ -727,7 +727,63 @@ object Rtl8821auTables {intArrayOf(0x18, 0x1712A))- fun channelTune(ch: Int): Array<IntArray> = arrayOf(+ /**+ * Tunes to [ch]: the 2.4 GHz table below (unchanged), or the 5 GHz one. With [bandSwitch]+ * the RTL8811AU's external antenna band switch is set too (one-antenna modules such as the+ * ALFA AWUS036ACS need it to hear 5 GHz); off, 2.4 GHz tuning is exactly as before.+ */+ fun channelTune(ch: Int, bandSwitch: Boolean = false): Array<IntArray> = when {+ ch > 14 -> extBandSwitch(5) + tune5g(ch)+ bandSwitch -> extBandSwitch(2) + tune24(ch)+ else -> tune24(ch)+ }++ /**+ * phydm_set_ext_band_switch_8821A: DPDT pins as WLAN-controlled outputs (MAC 0x4C bit 23 = 0,+ * bit 24 = 1), then 0xCB4[29:28] = 01 for 2.4 GHz, 10 for 5 GHz.+ */+ private fun extBandSwitch(ghz: Int): Array<IntArray> = arrayOf(+ intArrayOf(MAC8, 0x4E, 0x80, 0x0),+ intArrayOf(MAC8, 0x4F, 0x01, 0x1),+ intArrayOf(BB, 0xCB4, 0xF, 0x7),+ intArrayOf(BB, 0xCB4, 0xF0, 0x7),+ intArrayOf(BB, 0xCB4, 0x30000000, if (ghz == 5) 0x2 else 0x1)+ )++ /**+ * 5 GHz receive tuning, from the same Realtek driver: PHY_SwitchWirelessBand8812 (5G branch,+ * RTL8821: RFE pins, CCK check on, AGC table 1, CCK RX path off) and phy_SwChnl8812 (fc_area+ * and RF_MOD_AG by sub-band, channel number). The 20 MHz bandwidth writes are the 2.4 GHz ones.+ */+ private fun tune5g(ch: Int): Array<IntArray> {+ val fc = when { ch <= 48 -> 0x494; ch <= 80 -> 0x453; ch <= 116 -> 0x452; else -> 0x412 }+ val mod = when { ch <= 80 -> 0x101; ch <= 140 -> 0x301; else -> 0x501 }+ return arrayOf(+ intArrayOf(BB, 0x808, 0x30000000, 0x3),+ intArrayOf(BB, 0xCB0, 0xF000, 0x5),+ intArrayOf(BB, 0xCB0, 0xF0, 0x4),+ intArrayOf(BB, 0xCB4, 0x100000, 0x0),+ intArrayOf(BB, 0xCB4, 0x400000, 0x0),+ intArrayOf(BB, 0xCB0, 0x7, 0x7),+ intArrayOf(BB, 0xCB0, 0x700, 0x7),+ intArrayOf(MAC8, 0x454, 0x80, 0x1),+ intArrayOf(BB, 0xC1C, 0xF00, 0x1),+ intArrayOf(BB, 0x82C, 0x3, 0x1),+ intArrayOf(BB, 0x80C, 0xF0, 0x0),+ intArrayOf(BB, 0xA04, 0xF000000, 0xF),+ intArrayOf(BB, 0x860, 0x1FFE0000, fc),+ intArrayOf(RF, 0x18, 0x70300, mod),+ intArrayOf(RF, 0x18, 0xFF, ch),+ intArrayOf(MAC16, 0x668, 0x180, 0x0),+ intArrayOf(MAC8, 0x483, 0xFF, 0x0),+ intArrayOf(BB, 0x8AC, 0x3003C3, 0x300200),+ intArrayOf(BB, 0x8C4, 0x40000000, 0x0),+ intArrayOf(BB, 0x848, 0x3C00000, 0x8),+ intArrayOf(RF, 0x18, 0xC00, 0x3)+ )+ }++ private fun tune24(ch: Int): Array<IntArray> = arrayOf(intArrayOf(BB, 0x808, 0x30000000, 0x3),intArrayOf(BB, 0xCB0, 0xF000, 0x7),intArrayOf(BB, 0xCB0, 0xF0, 0x7),diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.ktindex ab13695..10334a6 100644--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt@@ -302,7 +302,10 @@ object UsbWifi {val onStatus: (String) -> Unit = { s -> status = s }val onFrames: (List<MonitorSighting>) -> Unit = { list -> onSightings?.invoke(list) }when (chip.driver) {- Driver.RTL88XXAU -> Rtl8821auMonitor.run(context, d, onStatus, onFrames)+ Driver.RTL88XXAU -> {+ Rtl8821auMonitor.scan5g = com.rfsentinel.app.util.Prefs.rtl8821au5g(context)+ Rtl8821auMonitor.run(context, d, onStatus, onFrames)+ }Driver.RTL88X2BU -> Rtl8822buMonitor.run(context, d, chip.name, onStatus, onFrames)Driver.RTL8187 -> Rtl8187Monitor.run(context, d, chip.name, onStatus, onFrames)Driver.RT3070 -> Rt3070Monitor.run(context, d, chip.name, onStatus, onFrames)diff --git a/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt b/app/src/main/java/com/rfsentinel/app/util/CrashLog.ktnew file mode 100644index 0000000..8e5f4dd--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt@@ -0,0 +1,91 @@+package com.rfsentinel.app.util++import android.content.Context+import android.content.Intent+import android.os.Build+import android.widget.Toast+import androidx.appcompat.app.AlertDialog+import androidx.appcompat.app.AppCompatActivity+import com.rfsentinel.app.BuildConfig+import java.io.File+import java.io.PrintWriter+import java.io.StringWriter+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++/**+ * Crashes written to a private file (never sent anywhere) so testers without adb can send them:+ * Settings > Lists, tools & about > Export crash log, or the prompt after the app closed+ * unexpectedly. Keeps the newest ~200 KB.+ */+object CrashLog {+ private const val FILE = "crash_log.txt"+ private const val MAX_BYTES = 200_000+ private const val PREFS = "crash_log"++ fun file(context: Context) = File(context.filesDir, FILE)++ fun install(context: Context) {+ val app = context.applicationContext+ val previous = Thread.getDefaultUncaughtExceptionHandler()+ Thread.setDefaultUncaughtExceptionHandler { thread, error ->+ runCatching { record(app, thread, error) }+ previous?.uncaughtException(thread, error)+ }+ }++ private fun record(context: Context, thread: Thread, error: Throwable) {+ val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()+ val entry = buildString {+ append("==== ").append(SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US).format(Date())).append(" ====\n")+ append("RF Sentinel ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})${if (BuildConfig.DEBUG) " debug" else ""}\n")+ append("${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})\n")+ append("Thread: ${thread.name}\n")+ append(trace).append("\n")+ }+ val f = file(context)+ val old = if (f.exists()) f.readText() else ""+ f.writeText((old + entry).takeLast(MAX_BYTES))+ // commit(): the process is about to die.+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("unseen", true).commit()+ }++ fun hasCrashes(context: Context) = file(context).let { it.exists() && it.length() > 0 }++ /** After a crash, once: offers to send the log. */+ fun offerAfterCrash(activity: AppCompatActivity) {+ val prefs = activity.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+ if (!prefs.getBoolean("unseen", false)) return+ prefs.edit().putBoolean("unseen", false).apply()+ if (!hasCrashes(activity)) return+ AlertDialog.Builder(activity)+ .setTitle("RF Sentinel closed unexpectedly")+ .setMessage("A crash log was saved on this phone (nothing is sent automatically). " ++ "Sending it to the developer helps fix it.\n\nLater: Settings > Lists, tools & about > Export crash log.")+ .setPositiveButton("Send log") { _, _ -> share(activity) }+ .setNegativeButton("Later", null)+ .show()+ }++ /** The crash log as a .txt file to send (email, messages, Drive...). */+ fun share(activity: AppCompatActivity) {+ if (!hasCrashes(activity)) {+ Toast.makeText(activity, "No crashes recorded", Toast.LENGTH_SHORT).show()+ return+ }+ val uri = runCatching {+ val dir = File(activity.cacheDir, "exports").apply { mkdirs() }+ val out = File(dir, "rfsentinel-crash-log-${Exporter.stamp()}.txt")+ file(activity).copyTo(out, overwrite = true)+ androidx.core.content.FileProvider.getUriForFile(activity, "${activity.packageName}.fileprovider", out)+ }.getOrNull()+ if (uri == null) { Toast.makeText(activity, "Couldn't create the log file", Toast.LENGTH_SHORT).show(); return }+ activity.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain")+ .putExtra(Intent.EXTRA_STREAM, uri)+ .putExtra(Intent.EXTRA_SUBJECT, "RF Sentinel crash log")+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION), "Export crash log"))+ }++ fun clear(context: Context) { file(context).delete() }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt b/app/src/main/java/com/rfsentinel/app/util/LiveExport.ktnew file mode 100644index 0000000..45ee029--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt@@ -0,0 +1,110 @@+package com.rfsentinel.app.util++import android.content.Context+import android.location.Location+import android.net.Uri+import android.provider.DocumentsContract+import com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.service.DeviceRegistry+import org.json.JSONArray+import org.json.JSONObject+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import java.util.TimeZone++/**+ * Settings > Data > Live export (off by default): while scanning, keeps three files up to date+ * (every 30 s) in a folder the user picks, outside the app's private storage, so another+ * mapping app can load them close to live:+ * - rfsentinel_live_matches.csv: every match of this scan (devices and radio hits);+ * - rfsentinel_live_matches.kml: the same matches that carry a position;+ * - rfsentinel_live.geojson: every device placed on the map now, plus your position.+ * The folder is reached through Android's storage-access framework (no storage permission).+ */+object LiveExport {++ const val CSV = "rfsentinel_live_matches.csv"+ const val KML = "rfsentinel_live_matches.kml"+ const val GEOJSON = "rfsentinel_live.geojson"+ private const val EVERY_MS = 30_000L++ @Volatile var status: String = ""; private set+ @Volatile private var lastWrite = 0L+ private val uris = HashMap<String, Uri>()++ /** Writes the files when the setting is on and 30 s have passed. Call from a background thread. */+ suspend fun maybeWrite(context: Context, sessionStart: Long, here: Location?) {+ if (!Prefs.liveExport(context)) return+ val now = System.currentTimeMillis()+ if (now - lastWrite < EVERY_MS) return+ lastWrite = now+ val tree = Prefs.liveExportTree(context)?.let(Uri::parse) ?: run { status = "Live export: choose a folder in Settings > Data"; return }+ try {+ val rows = AppDatabase.getInstance(context).detectionDao().since(sessionStart)+ write(context, tree, CSV, "text/csv", Exporter.csv(rows))+ write(context, tree, KML, "application/vnd.google-earth.kml+xml", Exporter.kml(rows))+ write(context, tree, GEOJSON, "application/geo+json", geoJson(DeviceRegistry.snapshot(now), here, now))+ status = "Live export: updated " + java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM).format(Date(now))+ } catch (e: Exception) {+ synchronized(uris) { uris.clear() }+ status = "Live export failed: ${e.message ?: e.javaClass.simpleName} (pick the folder again in Settings > Data)"+ }+ }++ /** Forget cached file handles (a new folder was picked). */+ fun reset() { synchronized(uris) { uris.clear() }; lastWrite = 0L; status = "" }++ private fun write(context: Context, tree: Uri, name: String, mime: String, text: String) {+ val uri = fileUri(context, tree, name, mime) ?: throw java.io.IOException("can't create $name")+ context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray(Charsets.UTF_8)) }+ ?: throw java.io.IOException("can't write $name")+ }++ /** The file [name] in the picked folder, created on first use. */+ private fun fileUri(context: Context, tree: Uri, name: String, mime: String): Uri? {+ synchronized(uris) { uris[name]?.let { return it } }+ val treeId = DocumentsContract.getTreeDocumentId(tree)+ val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, treeId)+ val found = context.contentResolver.query(children,+ arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c ->+ var id: String? = null+ while (c.moveToNext()) if (c.getString(1) == name) { id = c.getString(0); break }+ id+ }+ val uri = found?.let { DocumentsContract.buildDocumentUriUsingTree(tree, it) }+ ?: DocumentsContract.createDocument(context.contentResolver, DocumentsContract.buildDocumentUriUsingTree(tree, treeId), mime, name)+ if (uri != null) synchronized(uris) { uris[name] = uri }+ return uri+ }++ private val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }++ /** Devices at the spot they were heard strongest, plus "you are here" (pure; unit-tested). */+ fun geoJson(devices: List<DeviceRegistry.Snapshot>, here: Location?, now: Long): String {+ val features = JSONArray()+ for (s in devices) {+ val p = s.bestPosition ?: continue+ val best = s.best+ features.put(JSONObject()+ .put("type", "Feature")+ .put("geometry", JSONObject().put("type", "Point").put("coordinates", JSONArray().put(p.lon).put(p.lat)))+ .put("properties", JSONObject()+ .put("mac", s.mac)+ .put("name", s.name ?: JSONObject.NULL)+ .put("vendor", s.vendor ?: JSONObject.NULL)+ .put("type", s.deviceType)+ .put("flagged", best != null)+ .put("label", best?.label ?: JSONObject.NULL)+ .put("category", best?.category?.name ?: JSONObject.NULL)+ .put("confidence", best?.confidence ?: 0)+ .put("rssi", s.rssi)+ .put("last_seen", iso.format(Date(s.lastSeen)))))+ }+ if (here != null) features.put(JSONObject()+ .put("type", "Feature")+ .put("geometry", JSONObject().put("type", "Point").put("coordinates", JSONArray().put(here.longitude).put(here.latitude)))+ .put("properties", JSONObject().put("name", "You (RF Sentinel)").put("updated", iso.format(Date(now)))))+ return JSONObject().put("type", "FeatureCollection").put("features", features).toString()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex da8094c..0736e26 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -294,6 +294,10 @@ object Prefs {fun cctvPrivate(context: Context): Boolean = bool(context, "cctv_private", false)fun setCctvPrivate(context: Context, value: Boolean) = setBool(context, "cctv_private", value)+ /** Live map turned to the direction of travel instead of north up (map button; off = north up). */+ fun mapHeadingUp(context: Context): Boolean = bool(context, "map_heading_up", false)+ fun setMapHeadingUp(context: Context, value: Boolean) = setBool(context, "map_heading_up", 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)@@ -337,6 +341,56 @@ object Prefs {fun scanIntro(context: Context): Boolean = bool(context, "scan_intro", false)fun setScanIntro(context: Context, value: Boolean) = setBool(context, "scan_intro", value)+ // ---- RTL-SDR radio (Settings > RTL-SDR radio) ----++ private fun str(c: Context, key: String) = sp(c).getString(key, "").orEmpty()+ private fun setStr(c: Context, key: String, v: String) = sp(c).edit { putString(key, v) }++ /** Report a radio from this many dB above the noise (15-50; 30 = the original sensitivity). */+ fun radioMinSnr(context: Context): Int = int(context, "radio_min_snr", com.rfsentinel.app.sdr.RadioWatch.DEFAULT_MIN_SNR).coerceIn(15, 50)+ fun setRadioMinSnr(context: Context, v: Int) = setInt(context, "radio_min_snr", v.coerceIn(15, 50))+ /** Built-in bands switched off ("700", "800", "vhf", "uhf"). */+ fun radioBandsOff(context: Context): Set<String> = sp(context).getStringSet("radio_bands_off", emptySet()).orEmpty()+ fun setRadioBandsOff(context: Context, v: Set<String>) = sp(context).edit { putStringSet("radio_bands_off", v) }+ /** The user's own bands, one "start-end MHz label" per line. */+ fun radioCustomBands(context: Context) = str(context, "radio_custom_bands")+ fun setRadioCustomBands(context: Context, v: String) = setStr(context, "radio_custom_bands", v)+ /** Ranges never to report, one "start-end MHz" per line (e.g. a business band). */+ fun radioExcluded(context: Context) = str(context, "radio_excluded")+ fun setRadioExcluded(context: Context, v: String) = setStr(context, "radio_excluded", v)+ /** Frequencies to watch, one "MHz label" per line. */+ fun radioTargets(context: Context) = str(context, "radio_targets")+ fun setRadioTargets(context: Context, v: String) = setStr(context, "radio_targets", v)+ /** Say the frequency (and its name when known) instead of "Radio transmitting nearby". */+ fun radioSpeakFreq(context: Context): Boolean = bool(context, "radio_speak_freq", false)+ fun setRadioSpeakFreq(context: Context, v: Boolean) = setBool(context, "radio_speak_freq", v)+ /** Call out "closer" / "farther" after the signal moved this many dB (0 = off). */+ fun radioTrendDb(context: Context): Int = int(context, "radio_trend_db", 6).coerceIn(0, 20)+ fun setRadioTrendDb(context: Context, v: Int) = setInt(context, "radio_trend_db", v.coerceIn(0, 20))+ /** A hit matches a named frequency within ± this many kHz. */+ fun radioMatchKhz(context: Context): Int = int(context, "radio_match_khz", 7).coerceIn(1, 50)+ fun setRadioMatchKhz(context: Context, v: Int) = setInt(context, "radio_match_khz", v.coerceIn(1, 50))+ /** Name hits from RadioReference (needs the user's own Premium login and developer key; off by default). */+ fun radioReferenceOn(context: Context): Boolean = bool(context, "radio_reference_on", false)+ fun setRadioReferenceOn(context: Context, v: Boolean) = setBool(context, "radio_reference_on", v)++ // ---- Live export (Settings > Data) ----++ /** Keep a live copy of matches, devices and radio hits in a folder other apps can read (off by default). */+ fun liveExport(context: Context): Boolean = bool(context, "live_export", false)+ fun setLiveExport(context: Context, v: Boolean) = setBool(context, "live_export", v)+ /** The folder picked for it (a storage-access tree URI). */+ fun liveExportTree(context: Context): String? = sp(context).getString("live_export_tree", null)+ fun setLiveExportTree(context: Context, v: String?) = sp(context).edit { putString("live_export_tree", v) }++ /** ALFA AWUS036ACS / RTL8811AU-8821AU: also hop 5 GHz (experimental, off by default). */+ fun rtl8821au5g(context: Context): Boolean = bool(context, "rtl8821au_5g", false)+ fun setRtl8821au5g(context: Context, value: Boolean) = setBool(context, "rtl8821au_5g", value)++ /** Hide trusted (whitelisted) devices from the live list and radar (off by default). */+ fun hideWhitelisted(context: Context): Boolean = bool(context, "hide_whitelisted", false)+ fun setHideWhitelisted(context: Context, value: Boolean) = setBool(context, "hide_whitelisted", value)+fun threatBubble(context: Context): Boolean = bool(context, "threat_bubble", false)fun setThreatBubble(context: Context, value: Boolean) = setBool(context, "threat_bubble", value)@@ -360,4 +414,29 @@ object Prefs {fun radarView(context: Context): Boolean = bool(context, "radar_view", false)fun setRadarView(context: Context, value: Boolean) = setBool(context, "radar_view", value)++ /** The main screen's views, any mix of "map", "radar" and "list", shown in that order; older installs only knew list / radar. */+ fun viewPanes(context: Context): Set<String> =+ sp(context).getString("view_panes", null)?.split(',')?.filter { it in PANES }?.toSet()?.takeIf { it.isNotEmpty() }+ ?: if (radarView(context)) setOf("radar") else setOf("list")+ fun setViewPanes(context: Context, value: Set<String>) {+ val panes = PANES.filter { it in value }.ifEmpty { listOf("list") }+ sp(context).edit().putString("view_panes", panes.joinToString(",")).apply()+ setRadarView(context, panes == listOf("radar"))+ }+ val PANES = listOf("map", "radar", "list")++ /** Each view's share of the screen when several show together (dragging a handle moves it). */+ fun paneWeight(context: Context, pane: String): Float =+ sp(context).getFloat("pane_weight_$pane", if (pane == "list") 1.2f else 1f).coerceIn(0.1f, 10f)+ fun setPaneWeight(context: Context, pane: String, value: Float) = sp(context).edit().putFloat("pane_weight_$pane", value).apply()++ /** 3D driving view: heading up, tilted in perspective, your position low on screen (map button, third step). */+ fun map3d(context: Context): Boolean = bool(context, "map_3d", false)+ fun setMap3d(context: Context, value: Boolean) = setBool(context, "map_3d", value)++ /** Light or dark map tiles (the map's sun / moon button); null = follow the phone's dark mode. */+ fun mapDark(context: Context): Boolean? =+ if (sp(context).contains("map_dark")) sp(context).getBoolean("map_dark", false) else null+ fun setMapDark(context: Context, value: Boolean) = setBool(context, "map_dark", value)}diff --git a/app/src/main/res/drawable/ic_dark_mode.xml b/app/src/main/res/drawable/ic_dark_mode.xmlnew file mode 100644index 0000000..4c98190--- /dev/null+++ b/app/src/main/res/drawable/ic_dark_mode.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "dark_mode", Apache-2.0: switch the map to dark. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M12,3c-4.97,0 -9,4.03 -9,9s4.03,9 9,9 9,-4.03 9,-9c0,-0.46 -0.04,-0.92 -0.1,-1.36 -0.98,1.37 -2.58,2.26 -4.4,2.26 -2.98,0 -5.4,-2.42 -5.4,-5.4 0,-1.81 0.89,-3.42 2.26,-4.4C12.92,3.04 12.46,3 12,3z" />+</vector>diff --git a/app/src/main/res/drawable/ic_fullscreen.xml b/app/src/main/res/drawable/ic_fullscreen.xmlnew file mode 100644index 0000000..30eff83--- /dev/null+++ b/app/src/main/res/drawable/ic_fullscreen.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "fullscreen", Apache-2.0: open the map full screen. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M7,14L5,14v5h5v-2L7,17v-3zM5,10h2L7,7h3L10,5L5,5v5zM17,17h-3v2h5v-5h-2v3zM14,5v2h3v3h2L19,5h-5z" />+</vector>diff --git a/app/src/main/res/drawable/ic_heading_up.xml b/app/src/main/res/drawable/ic_heading_up.xmlnew file mode 100644index 0000000..fe38184--- /dev/null+++ b/app/src/main/res/drawable/ic_heading_up.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "navigation", Apache-2.0: map turned to the direction of travel. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M12,2L4.5,20.29l0.71,0.71L12,18l6.79,3 0.71,-0.71z" />+</vector>diff --git a/app/src/main/res/drawable/ic_light_mode.xml b/app/src/main/res/drawable/ic_light_mode.xmlnew file mode 100644index 0000000..25def03--- /dev/null+++ b/app/src/main/res/drawable/ic_light_mode.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "light_mode", Apache-2.0: switch the map to light. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M12,7c-2.76,0 -5,2.24 -5,5s2.24,5 5,5 5,-2.24 5,-5 -2.24,-5 -5,-5zM2,13h2c0.55,0 1,-0.45 1,-1s-0.45,-1 -1,-1L2,11c-0.55,0 -1,0.45 -1,1s0.45,1 1,1zM20,13h2c0.55,0 1,-0.45 1,-1s-0.45,-1 -1,-1h-2c-0.55,0 -1,0.45 -1,1s0.45,1 1,1zM11,2v2c0,0.55 0.45,1 1,1s1,-0.45 1,-1L13,2c0,-0.55 -0.45,-1 -1,-1s-1,0.45 -1,1zM11,20v2c0,0.55 0.45,1 1,1s1,-0.45 1,-1v-2c0,-0.55 -0.45,-1 -1,-1 -0.55,0 -1,0.45 -1,1zM5.99,4.58c-0.39,-0.39 -1.03,-0.39 -1.41,0 -0.39,0.39 -0.39,1.03 0,1.41l1.06,1.06c0.39,0.39 1.03,0.39 1.41,0s0.39,-1.03 0,-1.41L5.99,4.58zM18.36,16.95c-0.39,-0.39 -1.03,-0.39 -1.41,0 -0.39,0.39 -0.39,1.03 0,1.41l1.06,1.06c0.39,0.39 1.03,0.39 1.41,0 0.39,-0.39 0.39,-1.03 0,-1.41l-1.06,-1.06zM19.42,5.99c0.39,-0.39 0.39,-1.03 0,-1.41 -0.39,-0.39 -1.03,-0.39 -1.41,0l-1.06,1.06c-0.39,0.39 -0.39,1.03 0,1.41s1.03,0.39 1.41,0l1.06,-1.06zM7.05,18.36c0.39,-0.39 0.39,-1.03 0,-1.41 -0.39,-0.39 -1.03,-0.39 -1.41,0l-1.06,1.06c-0.39,0.39 -0.39,1.03 0,1.41s1.03,0.39 1.41,0l1.06,-1.06z" />+</vector>diff --git a/app/src/main/res/drawable/ic_north_up.xml b/app/src/main/res/drawable/ic_north_up.xmlnew file mode 100644index 0000000..d9480f5--- /dev/null+++ b/app/src/main/res/drawable/ic_north_up.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "explore" (compass), Apache-2.0: map fixed with north up. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M12,10.9c-0.61,0 -1.1,0.49 -1.1,1.1s0.49,1.1 1.1,1.1c0.61,0 1.1,-0.49 1.1,-1.1s-0.49,-1.1 -1.1,-1.1zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM14.19,14.19L6,18l3.81,-8.19L18,6l-3.81,8.19z" />+</vector>diff --git a/app/src/main/res/drawable/ic_view_3d.xml b/app/src/main/res/drawable/ic_view_3d.xmlnew file mode 100644index 0000000..b563a93--- /dev/null+++ b/app/src/main/res/drawable/ic_view_3d.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Design icon "view_in_ar", Apache-2.0: the 3D driving view. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFF"+ android:pathData="M18.25,7.6l-5.5,-3.18c-0.46,-0.27 -1.04,-0.27 -1.5,0L5.75,7.6C5.29,7.87 5,8.36 5,8.9v6.35c0,0.54 0.29,1.03 0.75,1.3l5.5,3.18c0.46,0.27 1.04,0.27 1.5,0l5.5,-3.18c0.46,-0.27 0.75,-0.76 0.75,-1.3V8.9C19,8.36 18.71,7.87 18.25,7.6zM7,14.96v-4.62l4,2.32v4.61L7,14.96zM12,10.93L8,8.61l4,-2.31l4,2.31L12,10.93zM13,17.27v-4.61l4,-2.32v4.62L13,17.27zM7,2H3.5C2.67,2 2,2.67 2,3.5V7h2V4h3V2zM17,2h3.5C21.33,2 22,2.67 22,3.5V7h-2V4h-3V2zM7,22H3.5C2.67,22 2,21.33 2,20.5V17h2v3h3V22zM17,22h3.5c0.83,0 1.5,-0.67 1.5,-1.5V17h-2v3h-3V22z" />+</vector>diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xmlindex 64f94ca..3d28fb5 100644--- a/app/src/main/res/layout/activity_main.xml+++ b/app/src/main/res/layout/activity_main.xml@@ -5,7 +5,7 @@android:layout_height="match_parent"android:orientation="vertical"android:paddingStart="16dp"- android:paddingTop="12dp"+ android:paddingTop="4dp"android:paddingEnd="16dp"android:paddingBottom="8dp">@@ -38,12 +38,12 @@android:id="@+id/threatBanner"android:layout_width="match_parent"android:layout_height="wrap_content"- android:layout_marginBottom="8dp"+ android:layout_marginBottom="4dp"android:background="@drawable/banner_bg"android:paddingStart="12dp"- android:paddingTop="8dp"+ android:paddingTop="6dp"android:paddingEnd="12dp"- android:paddingBottom="8dp"+ android:paddingBottom="6dp"android:textColor="#FFFFFF"android:textSize="14sp"android:textStyle="bold"@@ -53,7 +53,7 @@android:id="@+id/statusText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:paddingBottom="8dp"+ android:paddingBottom="4dp"android:text="Idle"android:textSize="15sp" />@@ -69,7 +69,9 @@android:layout_height="wrap_content"android:layout_marginEnd="8dp"android:layout_weight="1"- android:minHeight="52dp"+ android:minHeight="44dp"+ android:insetTop="0dp"+ android:insetBottom="0dp"android:maxLines="1"android:paddingStart="12dp"android:paddingEnd="12dp"@@ -78,13 +80,13 @@app:icon="@drawable/ic_car_play"app:iconGravity="textStart" />- <!-- List / radar: a two-way toggle reads clearer than one button naming the other view. -->+ <!-- List / radar / live map: pick one, or two or all three to see them together. --><com.google.android.material.button.MaterialButtonToggleGroupandroid:id="@+id/viewToggle"android:layout_width="wrap_content"android:layout_height="wrap_content"app:selectionRequired="true"- app:singleSelection="true">+ app:singleSelection="false"><com.google.android.material.button.MaterialButtonandroid:id="@+id/viewListButton"@@ -92,8 +94,13 @@android:layout_width="wrap_content"android:layout_height="wrap_content"android:contentDescription="List view"- android:minWidth="56dp"- android:minHeight="52dp"+ android:minWidth="48dp"+ android:minHeight="44dp"+ android:insetTop="0dp"+ android:insetBottom="0dp"+ android:paddingStart="0dp"+ android:paddingEnd="0dp"+ app:iconGravity="textStart"app:icon="@drawable/ic_car_list"app:iconPadding="0dp" />@@ -103,24 +110,32 @@android:layout_width="wrap_content"android:layout_height="wrap_content"android:contentDescription="Radar view"- android:minWidth="56dp"- android:minHeight="52dp"+ android:minWidth="48dp"+ android:minHeight="44dp"+ android:insetTop="0dp"+ android:insetBottom="0dp"+ android:paddingStart="0dp"+ android:paddingEnd="0dp"+ app:iconGravity="textStart"app:icon="@drawable/ic_radar"app:iconPadding="0dp" />- </com.google.android.material.button.MaterialButtonToggleGroup>- <!-- The map (traces, devices, known cameras), right beside the list / radar views. -->- <com.google.android.material.button.MaterialButton- android:id="@+id/mapButton"- style="@style/Widget.MaterialComponents.Button.OutlinedButton"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:layout_marginStart="8dp"- android:contentDescription="Open the map: your traces, devices and known cameras"- android:minWidth="56dp"- android:minHeight="52dp"- app:icon="@drawable/ic_map"- app:iconPadding="0dp" />+ <com.google.android.material.button.MaterialButton+ android:id="@+id/viewMapButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:contentDescription="Map view: the full map on the main screen"+ android:minWidth="48dp"+ android:minHeight="44dp"+ android:insetTop="0dp"+ android:insetBottom="0dp"+ android:paddingStart="0dp"+ android:paddingEnd="0dp"+ app:iconGravity="textStart"+ app:icon="@drawable/ic_map"+ app:iconPadding="0dp" />+ </com.google.android.material.button.MaterialButtonToggleGroup><!-- Tools: cell towers, WiFi channels and spectrum. --><com.google.android.material.button.MaterialButton@@ -130,8 +145,13 @@android:layout_height="wrap_content"android:layout_marginStart="8dp"android:contentDescription="Tools: cell towers, WiFi channels, WiFi spectrum and satellites"- android:minWidth="56dp"- android:minHeight="52dp"+ android:minWidth="48dp"+ android:minHeight="44dp"+ android:insetTop="0dp"+ android:insetBottom="0dp"+ android:paddingStart="0dp"+ android:paddingEnd="0dp"+ app:iconGravity="textStart"app:icon="@drawable/ic_tools"app:iconPadding="0dp" /></LinearLayout>@@ -140,7 +160,7 @@<HorizontalScrollViewandroid:layout_width="match_parent"android:layout_height="wrap_content"- android:layout_marginTop="4dp"+ android:layout_marginTop="6dp"android:scrollbars="none"><com.google.android.material.chip.ChipGroup@@ -152,51 +172,116 @@app:singleSelection="true" /></HorizontalScrollView>- <FrameLayout+ <!-- The chosen views, stacked (side by side in landscape): live map, radar, list. Handles between them resize. -->+ <LinearLayout+ android:id="@+id/contentArea"android:layout_width="match_parent"android:layout_height="0dp"- android:layout_weight="1">+ android:layout_weight="1"+ android:orientation="vertical">- <!-- Pull down to check Waze right now (only while Waze reports are on). -->- <androidx.swiperefreshlayout.widget.SwipeRefreshLayout- android:id="@+id/wazeSwipe"+ <FrameLayout+ android:id="@+id/mapPane"android:layout_width="match_parent"- android:layout_height="match_parent">+ android:layout_height="0dp"+ android:layout_weight="1"+ android:visibility="gone">- <androidx.recyclerview.widget.RecyclerView- android:id="@+id/recyclerView"+ <!-- The full map (MapFragment), added while the Map view is on. -->+ <FrameLayout+ android:id="@+id/previewMapHolder"android:layout_width="match_parent"- android:layout_height="match_parent"- android:clipToPadding="false"- android:paddingBottom="8dp" />- </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>+ android:layout_height="match_parent" />+ </FrameLayout>- <com.rfsentinel.app.ui.RadarView- android:id="@+id/radarView"+ <FrameLayout+ android:id="@+id/handleA"android:layout_width="match_parent"- android:layout_height="match_parent"- android:visibility="gone" />+ android:layout_height="20dp"+ android:contentDescription="Drag to resize"+ android:visibility="gone">++ <View+ android:id="@+id/gripA"+ android:layout_width="40dp"+ android:layout_height="5dp"+ android:layout_gravity="center" />+ </FrameLayout>- <TextView- android:id="@+id/emptyText"+ <FrameLayout+ android:id="@+id/radarPane"android:layout_width="match_parent"- android:layout_height="wrap_content"- android:layout_gravity="center"- android:gravity="center"- android:padding="24dp"- android:text="No devices heard yet.\nTap a device for full details.\nLong-press for quick actions (watchlist, whitelist, favorite)."- android:textColor="#888888" />+ android:layout_height="0dp"+ android:layout_weight="1"+ android:visibility="gone">- </FrameLayout>+ <com.rfsentinel.app.ui.RadarView+ android:id="@+id/radarView"+ android:layout_width="match_parent"+ android:layout_height="match_parent" />+ </FrameLayout>- <!-- Hidden while the list is scrolled down; back when it returns to the top. -->- <TextView- android:id="@+id/disclaimerText"- android:layout_width="match_parent"- android:layout_height="wrap_content"- android:paddingTop="6dp"- android:text="@string/disclaimer"- android:textColor="#888888"- android:textSize="10sp" />+ <FrameLayout+ android:id="@+id/handleB"+ android:layout_width="match_parent"+ android:layout_height="20dp"+ android:contentDescription="Drag to resize"+ android:visibility="gone">++ <View+ android:id="@+id/gripB"+ android:layout_width="40dp"+ android:layout_height="5dp"+ android:layout_gravity="center" />+ </FrameLayout>++ <FrameLayout+ android:id="@+id/listFrame"+ android:layout_width="match_parent"+ android:layout_height="0dp"+ android:layout_weight="1">++ <!-- Pull down to check Waze right now (only while Waze reports are on). -->+ <androidx.swiperefreshlayout.widget.SwipeRefreshLayout+ android:id="@+id/wazeSwipe"+ android:layout_width="match_parent"+ android:layout_height="match_parent">++ <androidx.recyclerview.widget.RecyclerView+ android:id="@+id/recyclerView"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:clipToPadding="false"+ android:paddingBottom="8dp" />+ </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>++ <TextView+ android:id="@+id/emptyText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:gravity="center"+ android:padding="24dp"+ android:text="No devices heard yet.\nTap a device for full details.\nLong-press for quick actions (watchlist, whitelist, favorite)."+ android:textColor="#888888" />++ <!-- Scrolled down when a new alert arrives above: tap to go up to it. -->+ <TextView+ android:id="@+id/newAlertPill"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="top|center_horizontal"+ android:layout_marginTop="6dp"+ android:elevation="4dp"+ android:paddingStart="14dp"+ android:paddingTop="6dp"+ android:paddingEnd="14dp"+ android:paddingBottom="6dp"+ android:text="▲ New alert"+ android:textSize="14sp"+ android:textStyle="bold"+ android:visibility="gone" />+ </FrameLayout>+ </LinearLayout></LinearLayout>diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xmlindex 147b053..81d5370 100644--- a/app/src/main/res/layout/activity_map.xml+++ b/app/src/main/res/layout/activity_map.xml@@ -10,6 +10,21 @@android:layout_width="match_parent"android:layout_height="match_parent" />+ <!-- 3D view: the map is tilted, so its own attribution can be off screen; this one stays. -->+ <TextView+ android:id="@+id/osmCredit"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="top|start"+ android:layout_marginStart="10dp"+ android:background="#99FFFFFF"+ android:paddingStart="4dp"+ android:paddingEnd="4dp"+ android:text="© OpenStreetMap contributors"+ android:textColor="#333333"+ android:textSize="10sp"+ android:visibility="gone" />+<!-- Status card, with the camera-download progress bar under it --><LinearLayoutandroid:id="@+id/statusBox"@@ -52,6 +67,45 @@android:layout_gravity="bottom"android:orientation="vertical">+ <!-- On the main screen: open the map full screen. -->+ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/fullscreenButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="end"+ android:layout_marginEnd="14dp"+ android:layout_marginBottom="8dp"+ android:contentDescription="Open the map full screen"+ android:src="@drawable/ic_fullscreen"+ android:visibility="gone"+ app:fabSize="mini"+ app:tint="#FFFFFF" />++ <!-- Light / dark map. -->+ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/themeButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="end"+ android:layout_marginEnd="14dp"+ android:layout_marginBottom="8dp"+ android:contentDescription="Light / dark map"+ android:src="@drawable/ic_dark_mode"+ app:fabSize="mini"+ app:tint="#FFFFFF" />++ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/orientationButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="end"+ android:layout_marginEnd="14dp"+ android:layout_marginBottom="8dp"+ android:contentDescription="Map: north up"+ android:src="@drawable/ic_north_up"+ app:fabSize="mini"+ app:tint="#FFFFFF" />+<com.google.android.material.floatingactionbutton.FloatingActionButtonandroid:id="@+id/centerButton"android:layout_width="wrap_content"@@ -113,4 +167,34 @@android:text="Traces" /></LinearLayout></LinearLayout>++ <!-- On the main screen: Record / Traces as round buttons on the map (the bar above is hidden). -->+ <LinearLayout+ android:id="@+id/compactControls"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="bottom|start"+ android:layout_marginStart="10dp"+ android:layout_marginBottom="8dp"+ android:orientation="horizontal"+ android:visibility="gone">++ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/recordFab"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginEnd="8dp"+ android:contentDescription="Record trace"+ android:src="@drawable/ic_record"+ app:fabSize="mini" />++ <com.google.android.material.floatingactionbutton.FloatingActionButton+ android:id="@+id/tracesFab"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:contentDescription="Traces"+ android:src="@drawable/ic_car_history"+ app:fabSize="mini" />++ </LinearLayout></FrameLayout>diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex 00c7d27..b68ce60 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -85,6 +85,12 @@<TextView android:id="@+id/headerScanning" style="@style/SettingsHeader" android:text="Scanning" /><LinearLayout android:id="@+id/sectionScanning" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">+ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/hideTrustedSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Hide trusted (whitelisted) devices from the list and radar" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/bleSwitch"android:layout_width="match_parent"@@ -607,8 +613,18 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:text="OUI-SPY: relay everything it hears" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/rtl5gSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="AWUS036ACS (RTL8811AU / 8821AU): also scan 5 GHz (experimental)" /></LinearLayout>+ <!-- ================= RTL-SDR radio (filled in by SettingsActivity.setupRadioSection) ================= -->+ <TextView android:id="@+id/headerRadio" style="@style/SettingsHeader" android:text="RTL-SDR radio" />+ <LinearLayout android:id="@+id/sectionRadio" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />+<!-- ================= Location & traces ================= --><TextView android:id="@+id/headerLocation" style="@style/SettingsHeader" android:text="Location & traces" /><LinearLayout android:id="@+id/sectionLocation" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">@@ -630,6 +646,25 @@<TextView android:id="@+id/headerData" style="@style/SettingsHeader" android:text="Data" /><LinearLayout android:id="@+id/sectionData" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">+ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/liveExportSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Live export for other mapping apps" />++ <Button+ android:id="@+id/liveExportFolderButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Choose folder" />++ <TextView+ android:id="@+id/liveExportText"+ style="@style/SettingsLabel"+ android:paddingTop="0dp"+ android:textSize="12sp" />+<TextView android:id="@+id/retentionLabel" style="@style/SettingsLabel" android:text="Keep history for (days, 0 = forever)" /><EditText@@ -663,5 +698,57 @@android:text="Clear match history" /></LinearLayout>+ <!-- ================= Lists, tools & about ================= -->+ <TextView android:id="@+id/headerMore" style="@style/SettingsHeader" android:text="Lists, tools & about" />+ <LinearLayout android:id="@+id/sectionMore" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">++ <Button+ android:id="@+id/openWatchlistButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="Watchlist & rules" />++ <Button+ android:id="@+id/openWhitelistButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="Whitelist (trusted devices)" />++ <Button+ android:id="@+id/checkUpdateButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="Check for updates" />++ <Button+ android:id="@+id/aboutButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="About & sources" />++ <Button+ android:id="@+id/exportCrashLogButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="Export crash log" />++ <Button+ android:id="@+id/clearCrashLogButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Clear crash log" />+ </LinearLayout>+</LinearLayout></ScrollView>diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xmlindex bf953c1..fabb0c3 100644--- a/app/src/main/res/menu/menu_main.xml+++ b/app/src/main/res/menu/menu_main.xml@@ -12,17 +12,17 @@android:icon="@drawable/ic_car_volume"android:title="Mute alerts"app:showAsAction="ifRoom" />+ <item+ android:id="@+id/action_settings"+ android:icon="@drawable/ic_settings"+ android:title="Settings"+ app:showAsAction="always" /><item android:id="@+id/action_waze_now" android:title="Check Waze now" app:showAsAction="never" /><item android:id="@+id/action_waze_status" android:title="Waze status" app:showAsAction="never" /><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_oui_list" android:title="Watchlist & rules" app:showAsAction="never" /><item android:id="@+id/action_probes" android:title="Requested networks" 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" />- <item android:id="@+id/action_export_all" android:title="Export all devices..." app:showAsAction="never" />+<item android:id="@+id/action_export" android:title="Export (history, matches, everything)..." app:showAsAction="never" />- <item android:id="@+id/action_check_update" android:title="Check for updates" app:showAsAction="never" />- <item android:id="@+id/action_about" android:title="About & sources" app:showAsAction="never" /></menu>diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xmlnew file mode 100644index 0000000..a47f60f--- /dev/null+++ b/app/src/main/res/values/ids.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <item name="mapHost" type="id" />+</resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 2c6fa04..9b2fb2b 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -3,6 +3,5 @@<string name="tile_label">RF Sentinel</string><string name="tile_scanning">Scanning</string><string name="tile_idle">Idle</string>- <string name="disclaimer">Passive, receive-only scanning. A match means a device with a watchlisted vendor prefix is advertising nearby - not proof of any specific equipment. Check local laws before use.</string><string name="widget_description">Scanner status with a start / stop button</string></resources>diff --git a/app/src/test/java/com/rfsentinel/app/sdr/RadioFeaturesTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/RadioFeaturesTest.ktnew file mode 100644index 0000000..d8f1fdf--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/sdr/RadioFeaturesTest.kt@@ -0,0 +1,76 @@+package com.rfsentinel.app.sdr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++class RadioFeaturesTest {++ @Test+ fun settingsLinesParse() {+ val r = RadioSettings.ranges("462-469 business band\nnonsense\n151,8 - 152.0\n")+ assertEquals(2, r.size)+ assertEquals(462_000_000L..469_000_000L, r[0].first)+ assertEquals("business band", r[0].second)+ val t = RadioSettings.targets("154.4300 County fire\n460.125\n462-469 not a target\n")+ assertEquals(listOf(154_430_000L, 460_125_000L), t.map { it.freqHz })+ assertEquals("County fire", t[0].label)+ val bands = RadioSettings.customBands("380-400 TETRA\n100-300 too much on top")+ assertEquals(1, bands.size) // the second would exceed the custom-span cap+ assertEquals(RadioWatch.Kind.CUSTOM, bands[0].kind)+ }++ @Test+ fun trendIsCalledOnTheSetStep() {+ RadioLog.clear()+ val band = RadioWatch.BANDS[1]+ fun ev(snr: Int) = RadioWatch.Event(807_312_500L, snr, band, 60)+ assertNull(RadioLog.observe(ev(30), null, 6, 0)) // new+ assertNull(RadioLog.observe(ev(33), null, 6, 1_000)) // +3: not yet+ assertEquals(RadioLog.Trend.CLOSER, RadioLog.observe(ev(37), "Fire", 6, 2_000))+ assertEquals(RadioLog.Trend.FARTHER, RadioLog.observe(ev(30), null, 6, 3_000))+ val e = RadioLog.current(3_000).single()+ assertEquals("Fire", e.name)+ assertEquals(37, e.peakSnrDb)+ // A long gap starts over.+ assertNull(RadioLog.observe(ev(45), null, 6, 200_000))+ assertEquals(RadioLog.Trend.NEW, RadioLog.current(200_000).single().trend)+ }++ @Test+ fun frequencyListsFromRadioReferenceChirpAndPlainFiles() {+ val rr = "Frequency Output,Frequency Input,FCC Callsign,Agency/Category,Description,Alpha Tag,PL Tone,Mode,Class Station Code,Tag\n" ++ "154.43000,,KQB123,County Fire,Fire Dispatch,FD DISP,CSQ,FM,BM,Fire Dispatch\n" ++ "\"155.47500\",,,State Police,\"Car-to-car, statewide\",SP C2C,,FM,M,Law Tac\n"+ val a = FreqNames.parseCsv(rr, "rr")+ assertEquals(2, a.size)+ assertEquals(154_430_000L, a[0].hz)+ assertEquals("Fire Dispatch · FD DISP", a[0].name)+ assertEquals("Car-to-car, statewide · SP C2C", a[1].name)+ val chirp = "Location,Name,Frequency,Duplex,Offset\n0,PD MAIN,460.125000,,0.000000\n"+ assertEquals("PD MAIN", FreqNames.parseCsv(chirp, "c").single().name)+ val plain = "453.2500,Public works\n"+ assertEquals(453_250_000L, FreqNames.parseCsv(plain, "p").single().hz)+ val near = FreqNames.closest(a, 154_436_000L, 7_000)+ assertEquals("Fire Dispatch · FD DISP", near!!.name)+ assertNull(FreqNames.closest(a, 154_450_000L, 7_000))+ }++ @Test+ fun radioReferenceAnswersParse() {+ val prox = """<SOAP-ENV:Body><ns1:fccGetProxCallsignsResponse><return xsi:type="SOAP-ENC:Array">+ <item xsi:type="tns:proxCallsignResult"><callsign xsi:type="xsd:string">WQAB123</callsign><licensee xsi:type="xsd:string">CITY OF SAMPLE & CO</licensee><lat>10.5</lat><lon>-20.5</lon><distance xsi:type="xsd:decimal">1.25</distance></item>+ <item><callsign>KNXY456</callsign><licensee>COUNTY SHERIFF</licensee><distance>0.4</distance></item>+ </return></ns1:fccGetProxCallsignsResponse></SOAP-ENV:Body>"""+ val calls = RadioReference.parseProx(prox)+ assertEquals(listOf("KNXY456", "WQAB123"), calls.map { it.callsign })+ assertEquals("CITY OF SAMPLE & CO", calls[1].licensee)+ val details = """<frequencies><item><locationNumber>1</locationNumber><frequency xsi:type="xsd:decimal">155.475</frequency></item>+ <item><frequency>460.125</frequency></item><item><frequency>3.0</frequency></item></frequencies>"""+ assertEquals(listOf(155_475_000L, 460_125_000L), RadioReference.parseFrequencies(details))+ assertEquals("Invalid Username or Password.", RadioReference.fault(+ "<SOAP-ENV:Fault><faultcode>AUTH</faultcode><faultstring xsi:type=\"xsd:string\">Invalid Username or Password.</faultstring></SOAP-ENV:Fault>"))+ assertNull(RadioReference.fault(prox))+ assertEquals(10.5 to -20.5, RadioReference.snap(10.5012, -20.4987))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.ktindex 124a792..c7f8ae8 100644--- a/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt+++ b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt@@ -52,8 +52,10 @@ class RadioWatchTest {assertEquals(radio, ev[0].freqHz)assertEquals(75, ev[0].confidence)assertEquals(RadioWatch.Kind.PUBLIC_SAFETY_MOBILE, ev[0].band.kind)- // the same channel isn't reported again right away- assertTrue(w.analyze(center, psd(center, radio to 42), rate, t + 2_500).isEmpty())+ // the same channel isn't a new report right away - only a repeat, for the live list and trend+ val again = w.analyze(center, psd(center, radio to 42), rate, t + 2_500)+ assertTrue(again.all { it.repeat })+ assertEquals(radio, again.single().freqHz)}@Test@@ -108,4 +110,42 @@ class RadioWatchTest {val peak = p.indices.maxByOrNull { p[it] }!!assertEquals(n / 2 + (tone / binHz).roundToInt(), peak)}++ // ---- Settings > RTL-SDR radio ----++ @Test+ fun sensitivityMovesTheThresholds() {+ val w = RadioWatch()+ w.config = RadioWatch.Config(minSnrDb = 20)+ val t = learn(w, 8)+ // 25 dB: below the default 30, above a sensitivity of 20.+ val ev = w.analyze(center, psd(center, tower to 40, radio to 25), rate, t)+ assertEquals(60, ev.single().confidence)+ val dflt = RadioWatch()+ val t2 = learn(dflt, 8)+ assertTrue(dflt.analyze(center, psd(center, tower to 40, radio to 25), rate, t2).isEmpty())+ }++ @Test+ fun excludedRangesAndWatchedFrequencies() {+ val w = RadioWatch()+ w.config = RadioWatch.Config(+ excluded = listOf(807_300_000L..807_330_000L),+ targets = listOf(RadioWatch.Target(806_812_500L, "Dispatch"))+ )+ val t = learn(w, 8)+ val ev = w.analyze(center, psd(center, tower to 40, radio to 42, 806_812_500L to 20), rate, t)+ assertTrue(ev.none { it.freqHz == radio }) // excluded+ val target = ev.single { it.target != null }+ assertEquals("Dispatch", target.target!!.label)+ assertEquals(RadioWatch.Kind.TARGET, target.band.kind)+ }++ @Test+ fun watchedFrequenciesOutsideTheBandsGetTheirOwnChunk() {+ val cfg = RadioWatch.Config(targets = listOf(RadioWatch.Target(121_500_000L, "x")))+ val plan = RadioWatch.plan(cfg)+ assertEquals(RadioWatch.plan().size + 1, plan.size)+ assertTrue(plan.any { kotlin.math.abs(121_500_000L - it) in 20_000L..800_000L })+ }}diff --git a/app/src/test/java/com/rfsentinel/app/usb/Rtl8821au5gTest.kt b/app/src/test/java/com/rfsentinel/app/usb/Rtl8821au5gTest.ktnew file mode 100644index 0000000..8b6b968--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/Rtl8821au5gTest.kt@@ -0,0 +1,31 @@+package com.rfsentinel.app.usb++import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class Rtl8821au5gTest {++ @Test+ fun twoPointFourIsUnchangedUnlessTheBandSwitchIsAsked() {+ val plain = Rtl8821auTables.channelTune(6)+ // Without 5 GHz on, 2.4 GHz tuning is exactly the old table (no band-switch writes).+ assertTrue(plain.none { it[1] == 0x4E || it[1] == 0x4F })+ val switched = Rtl8821auTables.channelTune(6, bandSwitch = true)+ assertEquals(plain.size + 5, switched.size)+ assertArrayEquals(intArrayOf(Rtl8821auTables.BB, 0xCB4, 0x30000000, 0x1), switched[4])+ }++ @Test+ fun fiveGhzSetsTheBandSwitchSubBandAndChannel() {+ val t = Rtl8821auTables.channelTune(149)+ assertTrue(t.any { it.contentEquals(intArrayOf(Rtl8821auTables.BB, 0xCB4, 0x30000000, 0x2)) })+ assertTrue(t.any { it.contentEquals(intArrayOf(Rtl8821auTables.RF, 0x18, 0x70300, 0x501)) })+ assertTrue(t.any { it.contentEquals(intArrayOf(Rtl8821auTables.RF, 0x18, 0xFF, 149)) })+ assertTrue(t.any { it.contentEquals(intArrayOf(Rtl8821auTables.BB, 0x860, 0x1FFE0000, 0x412)) })+ val low = Rtl8821auTables.channelTune(36)+ assertTrue(low.any { it.contentEquals(intArrayOf(Rtl8821auTables.RF, 0x18, 0x70300, 0x101)) })+ assertTrue(low.any { it.contentEquals(intArrayOf(Rtl8821auTables.BB, 0x82C, 0x3, 0x1)) })+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/usb/ScannerProbeTest.kt b/app/src/test/java/com/rfsentinel/app/usb/ScannerProbeTest.ktnew file mode 100644index 0000000..214ad33--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/usb/ScannerProbeTest.kt@@ -0,0 +1,32 @@+package com.rfsentinel.app.usb++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/** ESP32 scanner bursts (OUI-SPY survey engine) don't count as new client devices. */+class ScannerProbeTest {++ private fun mac(s: String) = s.split(":").map { it.toInt(16).toByte() }.toByteArray()++ /** OUI-SPY's wildcard probe: broadcast, random source, empty SSID, rates 1 / 2 / 5.5 / 11. */+ private fun scannerProbe(src: String) = ByteArray(24).also {+ it[0] = 0x40; mac("ff:ff:ff:ff:ff:ff").copyInto(it, 4); mac(src).copyInto(it, 10); mac("ff:ff:ff:ff:ff:ff").copyInto(it, 16)+ } + byteArrayOf(0, 0, 1, 4, 0x82.toByte(), 0x84.toByte(), 0x8B.toByte(), 0x96.toByte())++ @Test+ fun randomScannerBurstsAreIgnoredButPhonesAreNot() {+ val t = MonitorFrames()+ repeat(20) { i ->+ val f = scannerProbe("%02x:11:22:33:44:%02x".format(0x02 or (i shl 2), i))+ t.frame(f, 0, f.size, 6, -50, i.toLong())+ val withFcs = f + byteArrayOf(1, 2, 3, 4)+ t.frame(withFcs, 0, withFcs.size, 6, -50, i.toLong())+ }+ assertEquals(0, t.drain(20, 5000).size)+ // A phone's probe: same start, plus more elements (extended rates, HT capabilities...).+ val phone = scannerProbe("3a:11:22:33:44:55") + byteArrayOf(0x32, 4, 0x0c, 0x12, 0x18, 0x24)+ t.frame(phone, 0, phone.size, 6, -50, 30)+ assertTrue(t.drain(30, 5000).any { it.mac.equals("3A:11:22:33:44:55", ignoreCase = true) })+ }+}diff --git a/docs/index.html b/docs/index.htmlindex 192e3e7..a24e709 100644--- a/docs/index.html+++ b/docs/index.html@@ -24,7 +24,7 @@<link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin><link rel="stylesheet" href="assets/style.css">-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.16.0", "dateModified": "2026-10-07", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.17.0", "dateModified": "2026-10-08", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -93,9 +93,9 @@<h2 id="features">Features</h2><div class="grid">- <div class="card"><h3>Live list & radar</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>+ <div class="card"><h3>Live list, radar & map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div><div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>+ <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>diff --git a/docs/install.html b/docs/install.htmlindex 6599e63..e4fd4ec 100644--- a/docs/install.html+++ b/docs/install.html@@ -42,7 +42,7 @@<div class="page-head"><p class="crumbs"><a href="./">rf_sentinel</a> / install</p><h1>Install</h1>- <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 10 MB.</p>+ <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 11 MB.</p><div class="cta"><a class="btn primary" href="https://github.com/CIS-C0/RFSentinel/releases/latest" data-apk><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 20h14v-2H5v2zM19 9h-4V3H9v6H5l7 7 7-7z"/></svg>Download APK <span data-version></span></a><a class="btn" href="https://github.com/CIS-C0/RFSentinel/releases/latest">All releases & changelog</a>@@ -59,7 +59,7 @@</ol><h2 id="update">Updating</h2>-<p>The app's menu (⋮) → <b>Check for updates</b> asks GitHub for the latest release and links its APK (only when you tap it). Install the newer APK over the existing one. History, watchlist and settings are kept. Every release is signed with the same key; Android refuses an update signed with a different one.</p>+<p>Settings → <b>Lists, tools & about</b> → <b>Check for updates</b> asks GitHub for the latest release and links its APK (only when you tap it). Install the newer APK over the existing one. History, watchlist and settings are kept. Every release is signed with the same key; Android refuses an update signed with a different one.</p><h2 id="auto">Android Auto</h2><p>In a real car, Android Auto only shows Car App Library apps like RF Sentinel when they're installed from a trusted store (Google Play or ONE store); its <b>Unknown sources</b> setting doesn't cover them. The GitHub APK's car screens run on Google's Desktop Head Unit emulator, and once that setting is on it gets a media-style RF Sentinel screen and alert messages in the car. More on <a href="android-auto.html#setup">Android Auto</a>.</p>diff --git a/docs/qa.html b/docs/qa.htmlindex b19ed95..065bab3 100644--- a/docs/qa.html+++ b/docs/qa.html@@ -24,7 +24,7 @@<link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin><link rel="stylesheet" href="assets/style.css">-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any phone with Bluetooth LE: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels: no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to OpenStreetMap services (map tiles, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files) and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script>+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "RF Sentinel", "item": "https://cis-c0.github.io/RFSentinel/"}, {"@type": "ListItem", "position": 2, "name": "Q&A", "item": "https://cis-c0.github.io/RFSentinel/qa.html"}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "How do I detect police with an Android phone?", "acceptedAnswer": {"@type": "Answer", "text": "Modern police gear is full of radios that broadcast on their own: body cameras advertise over Bluetooth LE so the officer's phone and holster sensors can find them, in-car routers run WiFi access points, radios and e-ticket printers pair over Bluetooth. Any phone can receive those broadcasts without connecting to anything. RF Sentinel runs a continuous BLE scan and periodic WiFi scans, and matches every packet against vendor company IDs, service UUIDs, payload tags, network names and IEEE MAC prefixes assigned to law-enforcement equipment makers (Axon/TASER, Motorola Solutions, Digital Ally, Getac, Zebra, Flock Safety and others). When two or more kinds of police-type gear rise and fall in signal together, it flags a possible police vehicle. Install the APK , tap Start scanning , grant location and Nearby devices. See the police detection guide ."}}, {"@type": "Question", "name": "Is there an app that detects police nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel is a free, open-source Android app that does this passively from Bluetooth LE and WiFi signals, with no root and no subscription. It detects the equipment , not people: a match means a device with a police-equipment signature is in range. Crowd-sourced apps (Waze) rely on users reporting; RF Sentinel relies only on what the hardware itself broadcasts, so it also works where nobody has reported anything."}}, {"@type": "Question", "name": "Can my phone detect a police body camera?", "acceptedAnswer": {"@type": "Answer", "text": "Often, yes. Body cameras use Bluetooth LE to pair with the officer's phone app, holster and light-bar triggers, and many advertise continuously. RF Sentinel matches: the BWCDEVICE ASCII tag in service data, manufacturer data or the raw advert, in either byte order (confidence 90, field-validated); TASER International company ID 0x034D and Axon / TASER service UUIDs 0xFC81 , 0xFE6B , 0xFE6C (60 each); Utility Inc. BodyWorn Remote names (80); IEEE MAC prefixes registered to Axon ( 00:25:DF ), Digital Ally, WatchGuard, Getac, Zepcam and others. Independent matches on the same device are fused, so an Axon camera with the company ID, UUID and prefix lands in the strong tier. Cameras that are switched off, or that only use WiFi to dock, are not visible."}}, {"@type": "Question", "name": "How do I detect Axon body cameras and TASERs?", "acceptedAnswer": {"@type": "Answer", "text": "Axon (formerly TASER International) gear is identifiable from the Bluetooth SIG company ID 0x034D , the 16-bit service UUIDs 0xFC81 (Axon Enterprise), 0xFE6B and 0xFE6C (TASER International), and the IEEE block 00:25:DF . Axon Signal Sidearm holster sensors and Signal units, which start body cameras when a gun is drawn or the light bar turns on, are Bluetooth LE too. RF Sentinel ships all of these rules on by default."}}, {"@type": "Question", "name": "Can it detect a police car or unmarked car?", "acceptedAnswer": {"@type": "Answer", "text": "Indirectly. A single Motorola radio, Zebra printer or Cradlepoint router proves nothing, because civilians use them too. RF Sentinel assigns each device a role (body camera, plate reader, two-way radio, vehicle cellular router, mobile printer, in-car computer, rugged laptop, police camera) and groups devices with at least two different roles when their RSSI moves together (Pearson r ≥ 0.6 over at least 8 aligned seconds), or when both are flat (parked) and appeared within 30 s of each other. The group is flagged \"Possible police vehicle\" at 24 + 12 × roles, +10 when the signals move together, capped at 88: two roles stay weak (48), three moving together reach 70. An unmarked car is detected the same way if its gear advertises; there is no \"unmarked car\" signal as such. Details: patrol-vehicle detection ."}}, {"@type": "Question", "name": "Can it detect police radios?", "acceptedAnswer": {"@type": "Answer", "text": "It flags radios that expose Bluetooth or WiFi: Motorola Solutions company ID 0x04EC and UUIDs 0xFD8E / 0xFE04 , plus IEEE prefixes of P25 / TETRA radio makers. Those are weak on their own (Motorola radios are also used by security guards, schools and construction crews) and become meaningful as part of a patrol-vehicle group. It does not receive the voice channels themselves. P25 and TETRA run on VHF, UHF and 700/800 MHz and are usually encrypted; a phone has no receiver for those bands. That would need a software-defined radio, and RF Sentinel never decodes or listens to radio traffic."}}, {"@type": "Question", "name": "Is RF Sentinel a radar detector? Does it detect police radar guns?", "acceptedAnswer": {"@type": "Answer", "text": "No. Police radar and lidar use X, K and Ka-band microwave or infrared laser, which a phone cannot receive. \"Police radar\" in RF Sentinel's list means the Bluetooth/WiFi signatures of radar makers' in-car units when they advertise. For fixed speed and red-light cameras, RF Sentinel uses the OpenStreetMap camera layer and warns about 30 seconds ahead."}}, {"@type": "Question", "name": "Can it detect e-ticket printers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with care. Zebra mobile printers advertise UUIDs 0xFE79 / 0xFD66 . With a factory-serial name ( ^[A-Z0-9]{2}[A-Z]{3}\\d{9}$ ), which fleets rarely rename, the score is 50; any other name stays at 30 because the same printers are everywhere in warehouses and retail. Next to a body camera or radio moving with it, it becomes part of a patrol-vehicle group."}}, {"@type": "Question", "name": "How will I be alerted?", "acceptedAnswer": {"@type": "Answer", "text": "Matches above your alert threshold (default 50, probable) play a sound and vibrate: one pulse for weak, two for probable, three for strong. Optional spoken announcements use the phone's own text-to-speech engine, in full (\"Axon body camera nearby\") or short (\"Body cam\", \"Police car\", \"Speed camera, 50\"). Optional radar-detector beeps keep ticking after an alert, faster as the flagged device gets closer, like a radar detector. There is a discreet mode, a floating threat bubble over other apps (green / orange / red with a count, plus a pop-up card naming each new detection), a notification, a Quick Settings tile, a home-screen widget, and heads-up alerts in Android Auto."}}, {"@type": "Question", "name": "Why did it flag a device that is not police?", "acceptedAnswer": {"@type": "Answer", "text": "A match is a signature, not an identification. 00:25:DF means \"registered to Axon Enterprise\", not \"a police officer\". Some identifiers are shared with consumer products: Motorola Solutions radios are used by private security, Zebra printers by shops, Meta's company ID by Quest headsets. That is why every rule has a confidence, weak matches are amber and silent by default, and the detail screen shows the exact evidence and source. Long-press a device to whitelist it."}}, {"@type": "Question", "name": "How do I detect Flock Safety cameras?", "acceptedAnswer": {"@type": "Answer", "text": "Two ways, combined in the app: Radio signatures. Flock units and their batteries broadcast identifiable signals: WiFi SSIDs starting with Flock- (88), BLE names FS Ext Battery (80), Penguin-<digits> or FS-<hex> (70, or 80 with company ID 0x09C8 ), and the XUNTONG company ID 0x09C8 alone (45, shared silicon). The known-camera map. Flock cameras mapped by volunteers in OpenStreetMap (via DeFlock ) are downloaded and kept offline. You are warned when one is within about 20 seconds of travel and getting closer, even for cameras that only use cellular and emit nothing a phone can hear. See the Flock / ALPR guide ."}}, {"@type": "Question", "name": "How do I detect license plate readers (ALPR) on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Most non-Flock plate readers (Genetec AutoVu, Motorola / Vigilant, Perceptics, Quercus, Tattile) are wired or on cellular modems and don't broadcast anything a phone can match. RF Sentinel flags them by IEEE prefix when they do expose WiFi or Bluetooth, and covers the rest with the OpenStreetMap layer: every element tagged surveillance:type=ALPR , with manufacturer, operator and direction where mapped. The Download Flock option fetches every mapped plate reader in the US and Canada (~18 MB, about 143,000 cameras, refreshed weekly on WiFi); Download nearby cameras fetches a 10-200 km radius."}}, {"@type": "Question", "name": "Can it detect Flock Raven gunshot / audio sensors?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Raven sensors advertise 128-bit service UUIDs whose short IDs fall in 0x3100 - 0x3500 , matched at confidence 80 (field capture via all-cameras-are-beacons)."}}, {"@type": "Question", "name": "Can it warn me about speed cameras and red-light cameras without Waze?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Fixed speed and red-light cameras mapped in OpenStreetMap are downloaded automatically for the area you look at and kept offline, refreshed weekly. Speed cameras warn about 30 seconds ahead, with the speed limit when it's mapped. No account, no reporting, no location sent anywhere except the area request to the Overpass API. Coverage depends on how well your area is mapped in OpenStreetMap, and mobile speed traps aren't covered."}}, {"@type": "Question", "name": "Can I silence one specific camera I pass every day?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Tap the camera on the map and choose Ignore alerts . It stays on the map, faded, and never alerts again. Alert again on the same camera, or Settings, turns it back on. Ignored cameras are kept permanently."}}, {"@type": "Question", "name": "Can I find hidden cameras with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Only cameras that use WiFi or Bluetooth. RF Sentinel has an optional (off by default) network-camera category: SSIDs starting with ARLO_VMB_ / NTGR_VMB_ (88) and IEEE blocks of Arlo, Blink, Ezviz, Uniview, Amcrest, Wyze, Swann, Night Owl, SkyBell and WUUK (65, WiFi only). Turn on the Network / home security camera category in Settings. Limits you should know: a camera that joins an existing WiFi network as a client is invisible to an Android WiFi scan (only access points are listed), and wired, SD-card-only or cellular cameras emit nothing usable. A lens-reflection or IR check finds those, not a radio app."}}, {"@type": "Question", "name": "Can it identify hidden WiFi networks?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Hidden networks still send beacons with information elements. RF Sentinel reads the WPS element (manufacturer, model name and number, device name, primary device type), the Cisco CCX AP name (IE 133), the BSSID's IEEE registrant and vendor IE owners, and links a hidden BSSID to the visible network on the same router (octets 2-5 equal, last octet within 16). Requires Android 11+ for the raw elements."}}, {"@type": "Question", "name": "How do I know if an AirTag is following me on Android?", "acceptedAnswer": {"@type": "Answer", "text": "An AirTag away from its owner switches to a \"separated\" Find My frame: Apple company ID 0x004C , type 0x12 , length 0x19 . RF Sentinel matches that frame (confidence 70), keeps tracking the tag through its address rotations, and raises a may be following you alert when it has been with you for at least 10 minutes while you moved at least 800 m (both adjustable: 2-240 minutes). Tap the device and use Locate : it beeps faster as the signal gets stronger. It reacts to the same frame Android's built-in unknown-tracker alerts use, but shows it live, with history and a signal graph, instead of after hours."}}, {"@type": "Question", "name": "Does it detect Tile, Samsung SmartTag and Google Find Hub trackers?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Google Find Hub tags via 0xFEAA service data frame 0x41 (separated; frame 0x40 means near the owner and is ignored), Samsung SmartTag via 0xFD5A and Tile via 0xFEED service data (55). All feed the same follow detection."}}, {"@type": "Question", "name": "Can it find a GPS tracker hidden on my car?", "acceptedAnswer": {"@type": "Answer", "text": "Only Bluetooth trackers (AirTag, SmartTag, Tile, Find Hub tags). LTE / GSM GPS trackers report over the cellular network and don't broadcast anything a phone can identify. For those, a physical inspection or a dedicated RF sweep is needed."}}, {"@type": "Question", "name": "My own AirTag keeps showing up. How do I ignore it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it and ignore it. The ignore follows the tag when its address changes: it is carried over through the advert fingerprint link, so you don't have to ignore it again after each rotation. To leave every Apple Find My tag out of the Trackers category, turn on Settings → Exclude Apple AirTags (also in Android Auto → More); Google Find Hub, SmartTag and Tile trackers still alert."}}, {"@type": "Question", "name": "How do I detect drones near me with my phone?", "acceptedAnswer": {"@type": "Answer", "text": "Drones sold since FAA / EU Remote ID rules must broadcast an ASTM F3411 Remote ID signal over Bluetooth (service data 0xFFFA , app code 0x0D ) or WiFi (vendor IE OUI FA:0B:BC , type 0x0D ). RF Sentinel decodes it (confidence 95), places the drone on the map with heading, altitude and speed, and raises a \"drone overhead\" alert when it is within 200 m horizontally (once per drone per 5 minutes). Drone makers' own IEEE blocks (DJI, Parrot, Skydio, Autel, Yuneec...) are also matched at 60. See the drone guide ."}}, {"@type": "Question", "name": "Can I see where the drone pilot is?", "acceptedAnswer": {"@type": "Answer", "text": "When the drone's Remote ID includes the System message, yes: Remote ID carries the operator (or take-off) position. The detail screen shows it, and you can open both the drone and operator positions in your maps app. Remote ID also carries the serial number and, where used, an operator ID."}}, {"@type": "Question", "name": "Does it detect police drones?", "acceptedAnswer": {"@type": "Answer", "text": "It detects any drone that broadcasts Remote ID, which includes most police drones (DJI, Skydio, Autel) under current rules. It can't tell who operates it unless the operator ID says so. Exempt or modified drones that don't broadcast Remote ID are not detected."}}, {"@type": "Question", "name": "How do I detect a Stingray or IMSI catcher on Android without root?", "acceptedAnswer": {"@type": "Answer", "text": "Without root, Android exposes the cells your phone sees (network codes, cell IDs, area codes, radio technology, signal) but not ciphering or signalling messages. RF Sentinel reads them every 15 s and looks for the signs a cell-site simulator leaves in that data: serving cell on a test / reserved MCC (001, 002, 999): 85; sudden switch from 4G/5G to 2G while strong LTE is still visible (the visible side of the 2G downgrade EFF's Rayhunter watches for): 70; a known cell number appearing in a different area (cloned identity), a reserved area code (0, 0xFFFE, 0xFFFF) or cell ID 0; a network country code that doesn't match the SIM while not roaming; the location area changing while GPS shows you standing still, a new cell with no neighbours. A sign must persist across two checks; 2G drops during calls and area codes flipping at coverage borders are ignored. Several signs together score max + 15, capped at 90. See the IMSI catcher guide ."}}, {"@type": "Question", "name": "How reliable is fake cell tower detection on a phone?", "acceptedAnswer": {"@type": "Answer", "text": "It is heuristic. Each sign has innocent explanations (network maintenance, rural 2G, carrier misconfiguration), and a well-configured simulator copying a real cell's identity shows few of them. Treat it as a warning to look closer, not proof. The strongest protection is turning off Allow 2G in your SIM settings (Android 12+), and on Android 15+ enabling Cellular security → Network notifications , which warns when a network asks for your SIM identity or turns off encryption. RF Sentinel's Settings links there."}}, {"@type": "Question", "name": "How does this compare with EFF's Rayhunter?", "acceptedAnswer": {"@type": "Answer", "text": "Rayhunter runs on a cheap mobile hotspot with root access to the modem's signalling (QMDL / diag), so it sees identity requests and ciphering changes directly. A normal Android app can't. RF Sentinel implements the parts of that analysis visible through Android's public cell APIs (2G downgrade, identity anomalies) and points to Android 15's own network notifications for the rest. For the strongest detection, use Rayhunter hardware alongside."}}, {"@type": "Question", "name": "How do I detect Ray-Ban Meta smart glasses nearby?", "acceptedAnswer": {"@type": "Answer", "text": "Ray-Ban Meta glasses advertise over Bluetooth LE. RF Sentinel matches Luxottica's company ID 0x0D53 (70), company ID 0x058E together with the META_RB_GLASS token (72), and Meta's corporate company ID 0x01AB / UUIDs 0xFEB7 / 0xFEB8 (45, because Quest headsets share them). Snap Spectacles ( 0x03C2 ), Vuzix ( 0x060C ) and HeyCyan-SDK glasses (full 128-bit UUID) are matched too. See the smart glasses guide ."}}, {"@type": "Question", "name": "Can it tell if the glasses are recording?", "acceptedAnswer": {"@type": "Answer", "text": "No. It tells you the glasses are near you and advertising. Recording state is not part of the advertisement."}}, {"@type": "Question", "name": "How can I get s0phia ops (SØPHIA) for free?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a paid product sold by its own developer, and this site doesn't distribute it or any copy of it. If what you want is the same kind of tool for free, RF Sentinel is a free, open-source (GPL-3.0) alternative: passive Bluetooth LE and WiFi scanning for police gear, plate-reader cameras, trackers and drones, installed as a signed APK, no account. Comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Is there a free alternative to SØPHIA / SophiaOps?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. RF Sentinel covers passive BLE and WiFi recon with a radar view, risk scoring and a timeline, and adds sourced police, ALPR, tracker, Remote ID and smart-glasses signatures, patrol-vehicle grouping, fake cell tower signs, an offline camera map and Android Auto. It costs nothing and the full source is on GitHub . RF Sentinel is independent and not affiliated with SØPHIA or DetecX."}}, {"@type": "Question", "name": "Do I need Termux to scan for police on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Not with RF Sentinel. It is a regular Android app using the public BLE scan and WiFi scan APIs, so there's no Termux, Termux:API, Python or shell setup."}}, {"@type": "Question", "name": "How is it different from RF Party, BLE Radar (MetaRadar) or Flock You?", "acceptedAnswer": {"@type": "Answer", "text": "RF Party (based on Alan Meekins' DEF CON 31 talk) and BLE Radar are general Bluetooth scanners: they list and track devices, with fewer police-specific rules. Flock You and OUI-Spy are ESP32 firmware focused on Flock and watchlist matching. RF Sentinel combines a sourced signature set (each rule cites the IEEE registry, Bluetooth SIG or published research), evidence fusion, patrol-vehicle grouping, WiFi and cell analysis, the OpenStreetMap camera layer and Android Auto in one Android app, and can ingest OUI-Spy and GhostESP boards. No code from those projects is included."}}, {"@type": "Question", "name": "Is there a Flock You app for Android? (Flock You alternative)", "acceptedAnswer": {"@type": "Answer", "text": "Yes: RF Sentinel detects Flock Safety cameras on an Android phone with no extra hardware, and can also read a Flock You / OUI-Spy ESP32 board. Details Flock You is open-source (MIT) ESP32 firmware focused on one target: Flock Safety cameras. It runs the radio in 2.4 GHz promiscuous mode, so it sees Flock cameras' WiFi probe requests and SoftAPs that a phone can't, plus Flock battery-pack BLE adverts, and beeps or feeds a dashboard. RF Sentinel is a phone app that covers Flock as one category among many (body cams, patrol gear, trackers, drones, glasses, fake cell towers) and adds the OpenStreetMap / DeFlock camera map for cellular-only cameras. They combine well: plug an ESP32 running OUI-Spy's Flock-You mode into the phone and RF Sentinel shows its Flock detections next to its own. See ESP32 boards ."}}, {"@type": "Question", "name": "Which Android app works with OUI-Spy? (OUI-Spy app for Android)", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel connects to OUI-Spy boards over USB OTG or Bluetooth and merges their detections with the phone's own. Setup OUI-Spy is ESP32 firmware for the XIAO ESP32-S3 with several modes (Detector, Flock-You, Foxhunter, Sky Spy), a buzzer and LED, and a web flasher. OUI-APEX (lukeswitz's fork) runs those engines from one firmware and pairs with its own cross-platform app. It isn't either/or: RF Sentinel reads OUI-Spy boards over USB, and OUI-SPY App-Controlled boards over Bluetooth, and merges their detections with the phone's own (blue ESP32 badge). The board gives range and radio modes a phone lacks; RF Sentinel adds its rule set, patrol-vehicle grouping, the camera map, alerts and Android Auto."}}, {"@type": "Question", "name": "Wardrive Go alternative: what's the difference with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Wardrive Go (GPL-3.0, Android) is a wardriving app: it maps WiFi, Bluetooth and cellular networks, uploads to WiGLE and WDGWars, supports USB monitor-mode WiFi adapters and has channel / spectrum analyzers, Android Auto and a Wear OS companion. It also flags Flock cameras and Axon body cams. RF Sentinel is built around detection and alerting rather than mapping for upload: sourced signatures with confidence tiers, evidence fusion, patrol-vehicle grouping, follower alerts, Remote ID decoding, fake-cell signs and warnings before mapped cameras. Use Wardrive Go to contribute to WiGLE; use RF Sentinel to be warned while you drive. Some of RF Sentinel's prefix data was cross-checked with Wardrive Go's lists."}}, {"@type": "Question", "name": "Fieldwatch alternative for detecting police and surveillance gear", "acceptedAnswer": {"@type": "Answer", "text": "Fieldwatch (MIT, Android) is a receive-only WiFi and Bluetooth LE observer with customizable views, a filtering engine, an extensible signature library and reports, fully offline. It's a general field-survey tool. RF Sentinel shares the receive-only, offline approach but is tuned for surveillance and police gear: alert tiers, patrol-vehicle grouping, tracker follow detection, drone and cell analysis, the camera map and Android Auto. Part of RF Sentinel's prefix data was cross-checked with Fieldwatch's list."}}, {"@type": "Question", "name": "SØPHIA vs RF Sentinel: what's the difference?", "acceptedAnswer": {"@type": "Answer", "text": "SØPHIA is a closed-source passive BLE and WiFi recon app for Android sold by DetecX. RF Sentinel does the same kind of passive WiFi and Bluetooth recon for free and open source, with police, ALPR, tracker, drone and fake-cell detection, a camera map and Android Auto. Full comparison: RF Sentinel vs SØPHIA ."}}, {"@type": "Question", "name": "Flock-You for Android alternative", "acceptedAnswer": {"@type": "Answer", "text": "Flock-You (Android) is a separate counter-surveillance app with broad multi-protocol ambitions (BLE, WiFi, cellular, GNSS, ultrasonic) and Flipper Zero integration. RF Sentinel stays with what a phone's radios can verify, cites a source for every rule, and connects to ESP32 boards instead of a Flipper. Part of RF Sentinel's prefix data was cross-checked with its list."}}, {"@type": "Question", "name": "Best app to detect surveillance over both Bluetooth and WiFi (instead of AirGuard, BLE Radar, WiFi analyzers)", "acceptedAnswer": {"@type": "Answer", "text": "Many good tools cover one radio or one job: Bluetooth only: AirGuard (AirTag / Find My tracker protection), BLE Radar (MetaRadar) (BLE environment monitoring and custom filters), nRF Connect (a developer's BLE scanner), RF Party (BLE from the DEF CON 31 talk). WiFi only: WiFi analyzer apps show access points and channels but don't identify police or surveillance gear. Cell only: EFF's Rayhunter (IMSI catcher detection on dedicated hardware). Mapping: WiGLE WiFi Wardriving and Wardrive Go map networks for upload. RF Sentinel puts Bluetooth LE, WiFi and cell analysis in one app, so evidence from different radios can add up (e.g. a router, a radio and a printer moving together = possible police vehicle). A single-radio tool can't make that connection."}}, {"@type": "Question", "name": "Is there an iPhone version?", "acceptedAnswer": {"@type": "Answer", "text": "No. iOS hides Bluetooth MAC addresses and most advertisement fields from apps, offers no WiFi scan API, and doesn't expose cell information, so most of RF Sentinel's detection can't run there. It is Android only."}}, {"@type": "Question", "name": "Is RF Sentinel free? Are there ads or in-app purchases?", "acceptedAnswer": {"@type": "Answer", "text": "Free, no ads, no in-app purchases, no subscription, no account. Licensed GPL-3.0."}}, {"@type": "Question", "name": "Is it on Google Play or F-Droid?", "acceptedAnswer": {"@type": "Answer", "text": "Not currently. The signed APK is published on GitHub Releases for every version. See the install guide ."}}, {"@type": "Question", "name": "How do I install the APK?", "acceptedAnswer": {"@type": "Answer", "text": "On the phone, open the latest release . Under Assets , tap the file ending in -release.apk (not \"Source code\"). Open the downloaded file from the notification or Files → Downloads. If Android blocks it, tap Settings , enable Allow from this source , go back and tap Install . Open RF Sentinel. The setup wizard covers theme, region, alerts, camera download radius and permissions."}}, {"@type": "Question", "name": "Is the APK safe?", "acceptedAnswer": {"@type": "Answer", "text": "The full source is public, every release is signed with the same release key (Android refuses an update signed with a different key), and you can build it yourself with ./gradlew assembleDebug . The app requests no contacts, storage, camera or microphone permissions. Play Protect may warn about any app installed outside Google Play; that warning is about the install source, not a scan result."}}, {"@type": "Question", "name": "How do I update?", "acceptedAnswer": {"@type": "Answer", "text": "Install the newer APK over the existing one. Settings, history and watchlist are kept."}}, {"@type": "Question", "name": "Which Android versions and phones are supported?", "acceptedAnswer": {"@type": "Answer", "text": "Android 8.0 (API 26) and newer, on any phone with Bluetooth LE: Pixel, Samsung, Motorola, OnePlus, Xiaomi and others. Hidden-network WiFi details need Android 11+. Bluetooth 5 extended advertising and LE Coded PHY (long range) are used automatically where the chip supports them."}}, {"@type": "Question", "name": "Does it need root?", "acceptedAnswer": {"@type": "Answer", "text": "No. Everything uses public Android APIs."}}, {"@type": "Question", "name": "Why does it ask for location?", "acceptedAnswer": {"@type": "Answer", "text": "Android ties Bluetooth and WiFi scan results to the location permission (up to Android 11 always, and still for WiFi scans and cell info). RF Sentinel also uses GPS for traces, follow detection and camera warnings. Nearby devices (Bluetooth scan) is required; notifications, Display over other apps (bubble) and Nearby devices → connect (only to list your paired car) are optional."}}, {"@type": "Question", "name": "Scanning stops on Samsung / Xiaomi / OnePlus. What do I do?", "acceptedAnswer": {"@type": "Answer", "text": "Some manufacturers kill background apps aggressively. Scanning runs as a foreground service with a notification, but you may still need to set RF Sentinel's battery usage to Unrestricted . Settings has a shortcut to Android's battery optimization screen."}}, {"@type": "Question", "name": "How does passive Bluetooth LE detection work?", "acceptedAnswer": {"@type": "Answer", "text": "BLE devices broadcast advertising packets on channels 37, 38 and 39 so other devices can find them. Each packet carries an address, flags and optional fields: device name, 16/128-bit service UUIDs, service data, manufacturer data with a Bluetooth SIG company ID, TX power. RF Sentinel receives these through Android's BluetoothLeScanner and matches every field against its rules. It never connects, so the device never knows it was seen."}}, {"@type": "Question", "name": "What is a MAC vendor prefix (OUI) and why does it matter?", "acceptedAnswer": {"@type": "Answer", "text": "The first 3 bytes of a public MAC address (MA-L), or 3.5 / 4.5 bytes for MA-M / MA-S blocks, are assigned by the IEEE to a company. If a device uses its public address, the prefix reveals the maker, e.g. 00:25:DF is Axon Enterprise. RF Sentinel ships the IEEE registry offline and regional watchlist presets (Global, Canada, US) of law-enforcement and surveillance makers, each prefix re-checked against its registrant. Devices using random private addresses defeat prefix matching, which is why payload signatures and fingerprint linking matter more."}}, {"@type": "Question", "name": "What do weak, probable and strong mean?", "acceptedAnswer": {"@type": "Answer", "text": "Tier Confidence Meaning Weak (verify) < 50 Identifier shared with many unrelated products. Amber, silent by default. Probable 50-79 Vendor-specific identifier. Alerts at the default threshold. Strong 80+ Payload tag, or a network name the vendor gives its own devices."}}, {"@type": "Question", "name": "What is evidence fusion?", "acceptedAnswer": {"@type": "Answer", "text": "When different rules of the same category match one device, the scores combine by noisy-OR, with each supporting hit discounted by half because rules often share evidence: 1 - (1 - top) × Π(1 - 0.5 × support) . Hits under 30 never corroborate, and fusion never exceeds 90. Example: watchlisted address 70 + Zebra serial name 50 → 78."}}, {"@type": "Question", "name": "Devices change their Bluetooth address. How does it keep track?", "acceptedAnswer": {"@type": "Answer", "text": "A structural advert fingerprint survives address rotation: names, service UUIDs, service-data and company-ID payload sizes, TX power and connectable flag. When a new private address appears with the same fingerprint as exactly one device that went silent 1.5-30 s earlier, it inherits that device's matches (at −5), follow history and ignore state. Apple-Continuity-only adverts (phones) are never linked, and two identical candidates means no link."}}, {"@type": "Question", "name": "Can I add my own devices or signatures?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The watchlist takes exact addresses, vendor prefixes (MA-L / MA-M / MA-S) and name or vendor rules, each with a label and score, plus the regional presets. It exports as JSON. Long-press any device to add it."}}, {"@type": "Question", "name": "I found an unidentified device. How do I report it?", "acceptedAnswer": {"@type": "Answer", "text": "Long-press it → Report unknown device . The report shows exactly what is shared before you send it: vendor prefix, name pattern with serial digits hidden, service and manufacturer IDs. No full address, serial, location or time. Paste it into a GitHub issue or share it on Discord . New signatures need a registry or published source; guesses aren't merged."}}, {"@type": "Question", "name": "How far away can it detect devices?", "acceptedAnswer": {"@type": "Answer", "text": "It depends on the transmitter's power, walls, bodies and your phone's antenna. Bluetooth LE from a body camera is typically heard at tens of metres in the open and much less through a vehicle or building; WiFi access points carry further. Phones with LE Coded PHY hear Bluetooth 5 long-range adverts further. An external ESP32 board with a better antenna extends range. Phone radios are weaker than dedicated hardware, so expect fewer catches than purpose-built scanners."}}, {"@type": "Question", "name": "Can it tell the distance or direction of a device?", "acceptedAnswer": {"@type": "Answer", "text": "Distance is estimated from RSSI and is often off by 2-3×. The radar view places stronger signals closer to the centre, but the angle is not a direction: a phone can't measure angle of arrival. To find a device, use Locate mode and walk: it beeps faster as the signal grows."}}, {"@type": "Question", "name": "Why does WiFi only update every 30 seconds?", "acceptedAnswer": {"@type": "Answer", "text": "Android throttles apps to about four WiFi scans per two minutes. The default 30-second interval stays within that limit. Bluetooth LE is continuous."}}, {"@type": "Question", "name": "Why doesn't it see WiFi phones, laptops or cameras connected to a network?", "acceptedAnswer": {"@type": "Answer", "text": "Android's WiFi scan only lists access points (beacons and probe responses). Client devices, such as an in-car laptop connected to the car's router, need monitor mode, which Android doesn't offer without root and a supported chip. An ESP32 board can partly fill that gap."}}, {"@type": "Question", "name": "Does it work with the screen off?", "acceptedAnswer": {"@type": "Answer", "text": "Partly. Android pauses app Bluetooth scanning while the screen is off, and on some phones (a Pixel in our tests) no Bluetooth results arrive at all until the screen is back on. WiFi, the fake-cell checks, known-camera warnings and ESP32 / USB hardware keep working. Keep the screen on for Bluetooth: the car-mount default \"keep screen on while charging\" does that while driving. Android Auto warns you when a scan starts with the phone screen off and shows \"Bluetooth limited\" on its home screen."}}, {"@type": "Question", "name": "How much battery does it use?", "acceptedAnswer": {"@type": "Answer", "text": "Continuous scanning costs battery. Settings → BLE scan mode offers Low latency (default, catches the most), Balanced and Low power , and the WiFi interval is adjustable. Auto-start in the car scans only while you drive."}}, {"@type": "Question", "name": "What can't it detect at all?", "acceptedAnswer": {"@type": "Answer", "text": "Anything that doesn't broadcast BLE or WiFi beacons: cellular-only devices (most non-Flock plate readers, LTE GPS trackers), wired cameras, radios' voice channels, radar and lidar, devices switched off or in a non-advertising state, and WiFi clients. Cameras in OpenStreetMap are covered by the map layer instead."}}, {"@type": "Question", "name": "Is there a police detector app for Android Auto?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel runs in Android Auto: threat headline, the next known camera on your way, recent alerts, Start/Stop and mute on the home screen, device lists with the phone's filters, cell towers, hardware status, a live OpenStreetMap map with devices, cameras and drones, OSM navigation with spoken turns, and alerts as heads-up cards through the car speakers with Mute 30 min and Ignore buttons. See Android Auto ."}}, {"@type": "Question", "name": "RF Sentinel doesn't show up in Android Auto. How do I fix it?", "acceptedAnswer": {"@type": "Answer", "text": "In a real car, Android Auto only shows apps built with Google's Car App Library, like RF Sentinel, when they were installed from a trusted store (Google Play or ONE store). Its Unknown sources developer setting covers media and messaging apps, not these ( Google's testing guide ), so the GitHub APK's car screens can't appear there; they run on Google's Desktop Head Unit emulator. It still works in the car through the app types that setting covers: in Android Auto settings tap Version ten times, open ⋮ → Developer settings , enable Unknown sources and reconnect. RF Sentinel then shows a media-style screen (threats, cameras, alerts, status, with Scan and Mute buttons), and each alert arrives as a message you can have read aloud; reply \"mute\" to silence alerts for 30 minutes. Tick it under Customize launcher if it's missing."}}, {"@type": "Question", "name": "Can I use it with Waze or Google Maps on screen?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The floating threat bubble (needs Display over other apps) sits over any app: green when clear, orange for probable, red for strong or a follower, with the count. Each new alert shows a small card beside it for a few seconds saying what was detected, its type and distance. Tap to open, drag to move. Spoken alerts briefly lower other audio."}}, {"@type": "Question", "name": "Can it start by itself when I get in the car?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Settings → Start scanning automatically in the car : pick your car's Bluetooth. Scanning starts when the phone connects to it or to Android Auto, and stops when you leave if the car started it."}}, {"@type": "Question", "name": "Can I use an ESP32 with RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Plug a board running OUI-Spy , GhostESP or ESP32 Marauder into the phone with a USB OTG cable while scanning, or pair an OUI-SPY board running the Bluetooth (App-Controlled) firmware wirelessly. Its detections merge into the list with a blue ESP32 badge. Native-USB boards (S2/S3/C3/C5/C6) and CP210x / CH340 bridges work. See ESP32 boards ."}}, {"@type": "Question", "name": "How do I pair an OUI-SPY board over Bluetooth?", "acceptedAnswer": {"@type": "Answer", "text": "Start scanning with the board on, then Settings → Pair OUI-SPY board and pick OUI-SPY-xxxx . Pair only there, not in Android's Bluetooth settings: the board keeps no pairing keys, so a phone-side bond breaks the link (the app tells you to tap Forget if it finds one)."}}, {"@type": "Question", "name": "Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet."}}, {"@type": "Question", "name": "How do I see the cell towers my Android phone is connected to?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel's Tools button → Cell towers lists the serving cell and its neighbours live (2G-5G, operator, MCC-MNC, area code, cell ID, PCI, channel, signal) and every tower seen while scanning. They also appear in the live list (Cells filter) and optionally on the map at the spot where the signal was strongest. An optional alert says when the serving tower changes. No online lookup is made, so nothing reveals where you are."}}, {"@type": "Question", "name": "Is there a WiFi channel and spectrum analyzer in RF Sentinel?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: Tools → WiFi channels (networks and strongest signal per channel) and WiFi spectrum (each network as a curve across its channel width) for 2.4, 5 and 6 GHz, from the phone's own scans."}}, {"@type": "Question", "name": "Does it work with Flipper Zero or a WiFi Pineapple?", "acceptedAnswer": {"@type": "Answer", "text": "A Flipper Zero with an ESP32 board running Marauder (for example the BFFB) works since 2.11.1: plug the Flipper into the phone and open GPIO → USB-UART Bridge . A WiFi Pineapple isn't supported. Other supported hardware: ESP32 boards running OUI-Spy, GhostESP or Marauder, and RTL8811AU / 8821AU or RTL8812BU / 8822BU USB WiFi adapters."}}, {"@type": "Question", "name": "Can I use ESP32 Marauder or an ESP32-C5 board for 5 GHz WiFi on Android?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, with RF Sentinel 2.11.1+. Plug a board running ESP32 Marauder into the phone with a USB OTG cable while scanning. RF Sentinel runs only its passive beacon and probe sniffers and adds the networks and client devices to the list. On ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) that includes 5 GHz. Keep Channel Hop on in Marauder's settings. See ESP32 boards ."}}, {"@type": "Question", "name": "Does RF Sentinel transmit or jam anything?", "acceptedAnswer": {"@type": "Answer", "text": "No. It never transmits, jams, spoofs or connects to the devices it detects. (The phone's own WiFi scan sends standard probe requests like any phone looking for networks, and an OUI-SPY board in relay mode does the same; that can be turned off.)"}}, {"@type": "Question", "name": "Can police or anyone tell I'm running it?", "acceptedAnswer": {"@type": "Answer", "text": "The app itself sends nothing to the devices it scans. Your phone, like every phone, may still advertise its own Bluetooth and probe for WiFi networks independently of RF Sentinel."}}, {"@type": "Question", "name": "What data does it collect?", "acceptedAnswer": {"@type": "Answer", "text": "None leaves the phone. No accounts, no analytics, no crash reporting. Detections are stored in a local database excluded from cloud backup. Network requests go only to OpenStreetMap services (map tiles, Overpass camera data from overpass-api.de or its mirrors, DeFlock's region files) and, in Android Auto navigation, Nominatim and OSRM. They see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to about 1 km is sent to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja API key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid, never your exact position), third-party services used at your own risk."}}, {"@type": "Question", "name": "Is it legal to detect police equipment?", "acceptedAnswer": {"@type": "Answer", "text": "RF Sentinel only receives signals that devices broadcast publicly by design, and it doesn't decode private communications. Passive reception of Bluetooth and WiFi advertisements is generally lawful, but rules differ by country and state, and some places restrict use in vehicles or of radar detectors. Check your local laws. This is not legal advice."}}, {"@type": "Question", "name": "What is it meant for?", "acceptedAnswer": {"@type": "Answer", "text": "Awareness, research and personal privacy: knowing which surveillance devices are around you, finding trackers, documenting plate-reader deployments. A detection says a device with a given signature is nearby; it isn't proof of who is present or what they're doing."}}, {"@type": "Question", "name": "Is there a Watch Dogs / DedSec or Mr. Robot theme?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. DedSec (Watch Dogs 2-inspired: black, white and electric blue, poster banner, sliced wordmark, a [email protected]:~$ terminal typing hacktivist lines) and fsociety (Mr. Robot-inspired: black and blood red, striped wordmark, a root@fsociety:~# terminal typing quotes from the show). Unofficial fan homages, not affiliated with Ubisoft or NBCUniversal. Eleven more themes include Night Drive (red-only HUD for night driving), Night Vision, Amber CRT, Synthwave, Tactical, Blueprint, Paper and Material You."}}, {"@type": "Question", "name": "Can I export detections?", "acceptedAnswer": {"@type": "Answer", "text": "Yes: current scan as CSV, JSON or KML; all devices ever seen as CSV or JSON; the match log as CSV, JSON, GPX or KML; GPS traces with their devices as GPX, KML, GeoJSON or CSV; the watchlist as JSON; or everything in one JSON file."}}, {"@type": "Question", "name": "Is it open source? Can I build it myself?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, GPL-3.0, 100% Kotlin. Requirements: Android Studio, or JDK 17+ with the Android SDK. git clone https://github.com/CIS-C0/RFSentinel cd RFSentinel ./gradlew assembleDebug tools/gen_assets.py regenerates the offline IEEE and Bluetooth SIG databases and fails if any prefix used in code stops matching its registrant."}}, {"@type": "Question", "name": "How can I help?", "acceptedAnswer": {"@type": "Answer", "text": "Report unknown devices with the in-app report, submit sourced signatures, map cameras in OpenStreetMap / DeFlock, file bugs on GitHub , join the Discord , and star the repo so others find it."}}]}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -660,7 +660,7 @@<details class="faq" id="usb-wifi-adapter"><summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?</summary><div>-<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels: no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p></div></details>diff --git a/docs/sitemap.xml b/docs/sitemap.xmlindex b804aaa..65d0e0e 100644--- a/docs/sitemap.xml+++ b/docs/sitemap.xml@@ -7,10 +7,10 @@<url><loc>https://cis-c0.github.io/RFSentinel/flock-camera-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/how-it-works.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/imsi-catcher-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-07</lastmod><priority>1.0</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/</loc><lastmod>2026-10-08</lastmod><priority>1.0</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/install.html</loc><lastmod>2026-10-08</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/police-detector.html</loc><lastmod>2026-10-07</lastmod><priority>0.8</priority></url>- <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-07</lastmod><priority>0.9</priority></url>+ <url><loc>https://cis-c0.github.io/RFSentinel/qa.html</loc><lastmod>2026-10-08</lastmod><priority>0.9</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/smart-glasses-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/sophia-alternative.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url><url><loc>https://cis-c0.github.io/RFSentinel/tracker-detector.html</loc><lastmod>2026-10-05</lastmod><priority>0.8</priority></url>diff --git a/site/pages/index.html b/site/pages/index.htmlindex e46ce06..5ea6d65 100644--- a/site/pages/index.html+++ b/site/pages/index.html@@ -53,9 +53,9 @@<h2 id="features">Features</h2><div class="grid">- <div class="card"><h3>Live list & radar</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>+ <div class="card"><h3>Live list, radar & map</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts. Show the list, the radar and the map one at a time or together, resizable.</p></div><div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div>+ <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. North up, heading up, or a 3D driving view that zooms with your speed; light or dark. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>diff --git a/site/pages/install.html b/site/pages/install.htmlindex 0daaa90..b2884a1 100644--- a/site/pages/install.html+++ b/site/pages/install.html@@ -2,7 +2,7 @@<div class="page-head"><p class="crumbs"><a href="./">rf_sentinel</a> / install</p><h1>Install</h1>- <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 10 MB.</p>+ <p class="lead">Android 8.0 or newer. One signed APK from GitHub Releases, about 11 MB.</p><div class="cta"><a class="btn primary" href="{{RELEASES}}" data-apk>{{DOWNLOAD_SVG}}Download APK <span data-version></span></a><a class="btn" href="{{RELEASES}}">All releases & changelog</a>@@ -19,7 +19,7 @@</ol><h2 id="update">Updating</h2>-<p>The app's menu (⋮) → <b>Check for updates</b> asks GitHub for the latest release and links its APK (only when you tap it). Install the newer APK over the existing one. History, watchlist and settings are kept. Every release is signed with the same key; Android refuses an update signed with a different one.</p>+<p>Settings → <b>Lists, tools & about</b> → <b>Check for updates</b> asks GitHub for the latest release and links its APK (only when you tap it). Install the newer APK over the existing one. History, watchlist and settings are kept. Every release is signed with the same key; Android refuses an update signed with a different one.</p><h2 id="auto">Android Auto</h2><p>In a real car, Android Auto only shows Car App Library apps like RF Sentinel when they're installed from a trusted store (Google Play or ONE store); its <b>Unknown sources</b> setting doesn't cover them. The GitHub APK's car screens run on Google's Desktop Head Unit emulator, and once that setting is on it gets a media-style RF Sentinel screen and alert messages in the car. More on <a href="android-auto.html#setup">Android Auto</a>.</p>diff --git a/site/pages/qa.html b/site/pages/qa.htmlindex a67d0ff..936f717 100644--- a/site/pages/qa.html+++ b/site/pages/qa.html@@ -620,7 +620,7 @@<details class="faq" id="usb-wifi-adapter"><summary>Can I use a USB WiFi adapter like the ALFA AWUS036ACS, AWUS1900, AWUS036ACM, AWUS036H or AWUS036NHA with Android?</summary><div>-<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels: no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p>+<p>Yes, with RF Sentinel 2.11+. Plug an RTL8811AU / RTL8821AU adapter (e.g. AWUS036ACS) into the phone with an OTG cable while scanning and allow USB access. RF Sentinel drives it directly over Android's USB host API (no root), in receive-only monitor mode on the 2.4 GHz channels (5 GHz too since 2.17, experimental: Settings → External hardware): no 30-second scan limit, longer range, and it hears client devices (laptops, phones, cameras on a network) that a phone's WiFi scan can't. The driver is ported from Wardrive Go (GPL-3.0). Since 2.12, RTL8812BU / RTL8822BU adapters (TP-Link Archer T3U, ASUS USB-AC53/AC55/AC58, Edimax EW-7822U*, generic AC1200 dongles) work too, on 2.4 and 5 GHz, with a driver ported from OpenIPC devourer (GPL-2.0); single-antenna dongles are handled automatically. With an adapter plugged in, RF Sentinel can also list the WiFi names nearby devices ask for (Menu → Requested networks) and alert when a watched name is asked for. Since 2.13, RTL8814AU (AWUS1900) and MT7612U (AWUS036ACM) adapters work on 2.4 and 5 GHz, RTL8187 (AWUS036H) and RT3070 (AWUS036NH / NEH) on 2.4 GHz, and AR9271 (AWUS036NHA) experimentally; if one misbehaves, Settings → Export USB WiFi adapter log makes a text file to send. RTL8812AU and RTL8811CU / 8821CU are recognised but not supported yet.</p></div></details>