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.16.0: Waze direct, event types, ranges, adaptive checks, call-outs, status screen; map opens on your area
CIS-C03916ebb69d6f
diff --git a/README.md b/README.mdindex b48e3cc..cec51d3 100644--- a/README.md+++ b/README.md@@ -93,7 +93,7 @@| **Camera glasses** | Ray-Ban / Oakley Meta, Snap Spectacles, Vuzix, HeyCyan-based glasses such as Nilox Smart AI Glasses | Company IDs `0x0D53`, `0x03C2`, `0x060C`, Meta UUIDs, the HeyCyan SDK UUID, name tokens || **Fake cell towers** | IMSI catchers / cell-site simulators | Test network codes, sudden 4G→2G, cloned or reserved cell identities, unexpected networks || **Police aircraft** *(online, off by default)* | Police, sheriff, state patrol, federal and RCMP / provincial police aircraft, and unlisted aircraft circling low overhead | Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries |-| **Waze police reports** *(online, off by default)* | Police reported by Waze users within 2 km | Your own OpenWeb Ninja API key; scored by distance and age; third-party service, at your own risk |+| **Waze reports** *(online, off by default)* | Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), each with its own level: sound and voice, notification only, or silent. Shows what Waze says it is (hiding, mobile speed camera...) | Two sources: your own OpenWeb Ninja API key, or *Waze direct* (opt-in: no key, free, sends Waze your IP address and a position rounded to a 1 km grid). You set the alert range (100 m to 10 km), the map range, and how often Waze is asked (15 s to 5 min direct, 2 to 10 min OpenWeb Ninja), slower when parked and faster on fast roads. Scored by distance, age and driver confirmations and re-scored every second as you move, so an alert fires the moment a report comes into range, not at the next check. Optional: only alert for reports ahead of you, and spoken call-outs at 1 km, 500 m and 200 m. Third-party service, at your own risk || **Card skimmers** | Bluetooth modules inside gas-pump and ATM skimmers | HC-05 / HC-06 / HC-03 / RN42 / BT04-A names, serial-port service || **Hacking tools** *(off by default)* | Flipper Zero, Pwnagotchi, WiFi Pineapple, ESP deauthers, evil twin WiFi networks, Bluetooth spam floods | Flipper UUIDs / company ID `0x0E29` / IEEE block, Pwnagotchi beacon JSON, default SSIDs, same network name from two makers with mismatched security, bursts of new pairing pop-ups || **Action & hidden cameras** *(off by default)* | GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO, Garmin VIRB, Ricoh THETA, Kodak PIXPRO, Sony action cams, Apeman, Campark...; WiFi spy cameras in setup mode (V380, LookCam Pro, TinyCam Pro, HDSmartIPC) | GoPro company ID `0x02F2` / UUIDs `0xFEA5` `0xFEA6`, Insta360 (Arashi Vision) `0x10D7` / `0xFC30`, IEEE blocks, names |@@ -136,7 +136,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer- Notification, Quick Settings tile and home-screen widget**Map & history**-- OpenStreetMap map with your GPS trace and every device pinned exactly where its signal peaked (tap a spot to list everything heard there), the same filter chips as the list, self-centering+- OpenStreetMap map with your GPS trace and every device pinned exactly where its signal peaked (tap a spot to list everything heard there), the same filter chips as the list (including Waze, which draws reports as coloured dots by type), self-centering- Optional **cell tower layer** (or the map's **Cells** chip): every tower seen while scanning, at the spot where its signal was strongest- **Record traces** of your route and the devices along it, with the screen off (with the network names each device asked for, when a USB adapter or Marauder board is plugged in)- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)@@ -153,7 +153,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer- **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, external hardware), search+- 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- **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@@ -517,9 +517,16 @@ Pick a theme in the setup wizard or under **Settings → Appearance**.Map data © OpenStreetMap contributors (ODbL).- **Two optional online sources, off by default:** *Police / governmentaircraft* sends a position rounded to about 1 km to the community ADS-B- feeds adsb.fi / adsb.lol every minute while scanning. *Police reported on- Waze* uses your own OpenWeb Ninja API key (stored encrypted on the phone)- and sends a box of about 4 km around you every 4 minutes. OpenWeb Ninja and+ feeds adsb.fi / adsb.lol every minute while scanning. *Waze reports* use+ either your own OpenWeb Ninja API key (stored encrypted on the phone; a box+ around you at the interval you pick, 4 minutes by default) or, if you choose+ it in Settings, *Waze direct*: an anonymous Waze account made on the phone+ (stored encrypted), presented to Waze as the Waze app, that sends Waze (a+ Google service) your IP address and your position rounded to a 1 km grid, so+ never closer than about 500 m, at the interval you pick (every minute by+ default). Direct's protocol layer is vendored from+ highway-radar-sabre-plus (MIT), see+ `app/src/main/java/com/rfsentinel/app/online/wazert/LICENSE`. OpenWeb Ninja andWaze are third-party services RF Sentinel isn't affiliated with and doesn'tendorse; using them is at your own risk and under their terms.- **Data leaves the phone only when you export or share it.**diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 8f311cb..efc5954 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -3,11 +3,12 @@ import java.util.Propertiesplugins {id("com.android.application")id("com.google.devtools.ksp")+ id("com.google.protobuf")}// Bump both for every release. versionName ends up in the APK file name.-val appVersionCode = 39-val appVersionName = "2.15.3"+val appVersionCode = 40+val appVersionName = "2.16.0"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.@@ -74,11 +75,21 @@ android {}}+// Generates WazeProto (the Waze direct backend's wire format) from src/main/proto/waze.proto.+protobuf {+ protoc { artifact = "com.google.protobuf:protoc:4.35.0" }+ generateProtoTasks {+ all().forEach { task -> task.builtins { maybeCreate("java").option("lite") } }+ }+}+dependencies {implementation("androidx.core:core-ktx:1.19.1")implementation("androidx.appcompat:appcompat:1.8.0")implementation("com.google.android.material:material:1.14.0")implementation("androidx.recyclerview:recyclerview:1.4.0")+ // Pull the list down to check Waze now.+ implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.2.0")implementation("androidx.lifecycle:lifecycle-service:2.11.0")implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.11.0")implementation("androidx.activity:activity-ktx:1.13.0")@@ -88,6 +99,8 @@ dependencies {ksp("androidx.room:room-compiler:2.8.5")implementation("com.google.code.gson:gson:2.14.0")+ // Waze direct backend: lite protobuf runtime for the app protocol.+ implementation("com.google.protobuf:protobuf-javalite:4.35.0")// OpenStreetMap map view (Apache-2.0, no API key). Tiles are the only network use.implementation("org.osmdroid:osmdroid-android:6.1.20")diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 2e1b979..5a52ebf 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -76,6 +76,7 @@<activity android:name=".ui.DetectionLogActivity" android:exported="false" /><activity android:name=".ui.CellTowersActivity" android:exported="false" /><activity android:name=".ui.GnssActivity" android:exported="false" />+ <activity android:name=".ui.WazeStatusActivity" android:exported="false" /><activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" /><activityandroid:name=".ui.SetupActivity"diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 1b1cf28..dfa493a 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -45,6 +45,7 @@ class MainActivity : AppCompatActivity() {companion object {/** 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 BLUETOOTH_TAG_COLOR = 0xFF1565C0.toInt()private const val WIFI_TAG_COLOR = 0xFF00838F.toInt()private const val REFRESH_MS = 1_000L@@ -83,12 +84,26 @@ 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(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)+ .putExtra(com.rfsentinel.app.ui.MapActivity.EXTRA_CENTER_LAT, w.report.lat)+ .putExtra(com.rfsentinel.app.ui.MapActivity.EXTRA_CENTER_LON, w.report.lon))+ }+ }else DeviceActions.openDetails(this, it.mac)},- onLongPress = { if (!it.mac.startsWith(CELL_ROW)) DeviceActions.showQuickActions(this, it.mac) }+ onLongPress = { if (!it.mac.startsWith(CELL_ROW) && !it.mac.startsWith(WAZE_ROW)) DeviceActions.showQuickActions(this, it.mac) })binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapter+ binding.wazeSwipe.setColorSchemeColors(com.rfsentinel.app.ui.ChipStyle.accent(this).first)+ binding.wazeSwipe.setOnRefreshListener {+ if (com.rfsentinel.app.ui.WazeUi.checkNow(this)) {+ refreshAskedAt = System.currentTimeMillis()+ binding.wazeSwipe.postDelayed({ binding.wazeSwipe.isRefreshing = false }, 12_000) // never spin for ever+ } else binding.wazeSwipe.isRefreshing = false+ }// Rows rebind every second (RSSI / "seen Xs ago"); the default change// crossfade would make the whole list flicker and fight the match flash.(binding.recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false@@ -208,6 +223,7 @@ class MainActivity : AppCompatActivity() {val radar = Prefs.radarView(this)binding.radarView.visibility = if (radar) View.VISIBLE else View.GONEbinding.recyclerView.visibility = if (radar) View.GONE else View.VISIBLE+ binding.wazeSwipe.visibility = if (radar) View.GONE else View.VISIBLEbinding.disclaimerText.visibility =if (radar || !binding.recyclerView.canScrollVertically(-1)) View.VISIBLE else View.GONE}@@ -292,9 +308,22 @@ class MainActivity : AppCompatActivity() {private fun observeDevices() {lifecycleScope.launch {repeatOnLifecycle(Lifecycle.State.STARTED) {- while (true) {- render()- delay(REFRESH_MS)+ // A new or cleared Waze report redraws the list at once, not at the next tick.+ val stopWaze = com.rfsentinel.app.online.WazePolice.addListener {+ runOnUiThread {+ if (!lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) return@runOnUiThread+ // The answer to a pull-down check ends the spinner.+ if (binding.wazeSwipe.isRefreshing && com.rfsentinel.app.online.WazePolice.latestAt >= refreshAskedAt) binding.wazeSwipe.isRefreshing = false+ render()+ }+ }+ try {+ while (true) {+ render()+ delay(REFRESH_MS)+ }+ } finally {+ stopWaze()}}}@@ -309,6 +338,7 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs)}val threshold = Prefs.alertThreshold(this)+ binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && binding.radarView.visibility != View.VISIBLEdeviceCount = 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) }@@ -318,7 +348,11 @@ class MainActivity : AppCompatActivity() {// Live counts on the chips ("Trackers 2"); empty filters stay unlabelled.for ((f, chip) in filterChips) {- val n = if (f == com.rfsentinel.app.ui.DeviceFilter.CELLS) liveCellCount(now) else all.count { f.matches(it) }+ val n = when (f) {+ com.rfsentinel.app.ui.DeviceFilter.CELLS -> liveCellCount(now)+ com.rfsentinel.app.ui.DeviceFilter.WAZE -> currentWaze(now).size+ else -> all.count { f.matches(it) }+ }val label = if (f == com.rfsentinel.app.ui.DeviceFilter.ALL || n > 0) "${f.label} $n" else f.labelif (chip.text != label) chip.text = label}@@ -343,13 +377,18 @@ class MainActivity : AppCompatActivity() {})} else {val cells = cellRows(now)- adapter.submitList(visible.map { toRow(it, now, threshold) } + cells)- shownCells = cells.size+ val waze = wazeRows(now, threshold)+ // Waze reports 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}binding.emptyText.visibility = if (visible.isEmpty() && (binding.radarView.visibility == View.VISIBLE || 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.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."@@ -375,6 +414,48 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.service.CellTowerStore.current.size else 0private var shownCells = 0+ /** When the list was last pulled down to check Waze. */+ private var refreshAskedAt = 0L++ /**+ * The Waze reports inside the alert range (Settings > Waze), kept live by the checker: distance, direction+ * and score follow you as you drive. The map still shows the wider view range.+ */+ private fun currentWaze(now: Long): List<com.rfsentinel.app.online.WazePolice.Shown> {+ if (!ScanForegroundService.isRunning) return emptyList()+ val alertM = Prefs.wazeAlertM(this).toDouble()+ return com.rfsentinel.app.online.WazePolice.latest.filter { it.distanceM <= alertM }+ }++ /**+ * The Waze reports in range, nearest first, under the All and Waze filters. One that reaches the alert+ * threshold (and is not silenced for its type, nor behind you when only reports ahead count) is tinted,+ * flashes, and is pinned to the top.+ */+ private fun wazeRows(now: Long, threshold: Int): List<DeviceRow> {+ if (filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.WAZE) return emptyList()+ val aheadOnly = Prefs.wazeAheadOnly(this)+ return currentWaze(now)+ .sortedBy { it.distanceM }+ .filter { query.isBlank() || it.hit.label.contains(query.trim(), ignoreCase = true) }+ .map { w ->+ val urgent = w.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&+ w.hit.confidence >= threshold && !(aheadOnly && w.where.isBehind)+ val ago = w.report.publishedMs?.let { "${((now - it) / 60_000).coerceAtLeast(0)} min ago" } ?: "just now"+ DeviceRow(+ mac = WAZE_ROW + w.report.id,+ title = w.hit.label,+ subtitle = com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend),+ meta = "Reported $ago" + listOfNotNull(w.report.street, w.report.city).joinToString(", ").takeIf { it.isNotEmpty() }?.let { " · $it" }.orEmpty() ++ (if (w.report.thumbsUp > 0) " · ${w.report.thumbsUp} confirmed" else ""),+ tag = "WAZE · ${w.hit.tier.label.lowercase()} ${w.hit.confidence}%",+ tagColor = w.report.type.color,+ highlight = if (urgent) w.report.type.color else null,+ flashing = urgent,+ bold = urgent+ )+ }+ }private fun cellRows(now: Long): List<DeviceRow> {if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.CELLS) ||@@ -530,6 +611,9 @@ class MainActivity : AppCompatActivity() {}override fun onPrepareOptionsMenu(menu: Menu): Boolean {+ val wazeOn = com.rfsentinel.app.ui.WazeUi.on(this)+ menu.findItem(R.id.action_waze_now)?.isVisible = wazeOn+ menu.findItem(R.id.action_waze_status)?.isVisible = wazeOnval muted = Prefs.alertsMuted(this)menu.findItem(R.id.action_mute)?.apply {setIcon(if (muted) R.drawable.ic_car_volume_off else R.drawable.ic_car_volume)@@ -562,6 +646,8 @@ class MainActivity : AppCompatActivity() {override fun onOptionsItemSelected(item: MenuItem): Boolean {return when (item.itemId) {+ R.id.action_waze_now -> { com.rfsentinel.app.ui.WazeUi.checkNow(this); true }+ R.id.action_waze_status -> { com.rfsentinel.app.ui.WazeUi.openStatus(this); true }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 }diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.ktindex a7b63de..7f65360 100644--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt@@ -59,6 +59,13 @@ class RFSentinelApp : Application() {}}}+ // Open the map's tile database off the main thread now, so the first map of the session does not wait for it.+ appScope.launch(Dispatchers.IO) {+ runCatching {+ com.rfsentinel.app.ui.MapIcons.configureOsm(this@RFSentinelApp)+ org.osmdroid.tileprovider.modules.SqlTileWriter().onDetach()+ }+ }appScope.launch(Dispatchers.IO) {runCatching { VendorDb.load { assets.open(it) } }.onFailure { Log.e("RFSentinelApp", "Vendor database failed to load", it) }diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.ktindex 4cde821..c725013 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 }+ val CAR_FILTERS = DeviceFilter.entries.filter { it != DeviceFilter.CELLS && it != DeviceFilter.WAZE }fun titleOf(f: DeviceFilter) = when (f) {DeviceFilter.ALL -> "All nearby"diff --git a/app/src/main/java/com/rfsentinel/app/detect/Category.kt b/app/src/main/java/com/rfsentinel/app/detect/Category.ktindex 7fa224e..fc0d55a 100644--- a/app/src/main/java/com/rfsentinel/app/detect/Category.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/Category.kt@@ -25,7 +25,7 @@ enum class Category(/** Online (ADS-B feeds): off by default, it sends a rounded position to adsb.fi / adsb.lol. */AIRCRAFT("Police / government aircraft overhead (online: adsb.fi, adsb.lol)", "AIRCRAFT", 0xFF5E35B1.toInt(), false),/** Online (the user's OpenWeb Ninja key): off by default, third-party service used at the user's own risk. */- POLICE_REPORT("Police reported on Waze (online: your OpenWeb Ninja key)", "WAZE", 0xFF1E88E5.toInt(), false),+ POLICE_REPORT("Waze reports (online: OpenWeb Ninja key or Waze direct)", "WAZE", 0xFF1E88E5.toInt(), false),/** Off by default: action cameras (GoPro, Insta360, DJI Osmo...) and WiFi spy cameras in setup mode. */OTHER_CAMERA("Action & hidden cameras (GoPro, Insta360, DJI Osmo, V380 / LookCam spy cams...)", "CAMERA+", 0xFF00897B.toInt(), false),/** Bluetooth serial modules built into gas-pump / ATM card skimmers (BLE names, receive-only). */diff --git a/app/src/main/java/com/rfsentinel/app/online/AmbientThreats.kt b/app/src/main/java/com/rfsentinel/app/online/AmbientThreats.ktindex d17fe31..666b1fd 100644--- a/app/src/main/java/com/rfsentinel/app/online/AmbientThreats.kt+++ b/app/src/main/java/com/rfsentinel/app/online/AmbientThreats.kt@@ -23,7 +23,8 @@ object AmbientThreats {@Volatile var waze: Pair<Long, Threat>? = nullprivate const val ONLINE_TTL_MS = 3 * 60_000L- private const val WAZE_TTL_MS = 6 * 60_000L+ /** How long a Waze report keeps the headline up: a little over two polls, never under 6 minutes (set by OnlineWatch). */+ @Volatile var wazeTtlMs = 6 * 60_000Lfun clear() {aircraft = null@@ -34,7 +35,7 @@ object AmbientThreats {fun top(context: Context, now: Long = System.currentTimeMillis()): Threat? = listOfNotNull(camera(context),aircraft?.takeIf { now - it.first < ONLINE_TTL_MS }?.second,- waze?.takeIf { now - it.first < WAZE_TTL_MS }?.second+ waze?.takeIf { now - it.first < wazeTtlMs }?.second).filter { it.score >= 40 }.maxByOrNull { it.score }private fun camera(context: Context): Threat? {diff --git a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.ktindex a1334af..3b1fad0 100644--- a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt@@ -6,7 +6,6 @@ import com.rfsentinel.app.BuildConfigimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.detect.Hitimport com.rfsentinel.app.util.Prefs-import com.rfsentinel.app.util.SecureStoreimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -17,27 +16,42 @@ import java.net.HttpURLConnectionimport java.net.URL/**- * The two internet sources, both off by default: police / government aircraft from- * community ADS-B feeds (every 60 s) and Waze police reports through the user's- * OpenWeb Ninja key (every 4 min). Each sends only a position rounded to ~1 km (ADS-B)- * or a ~4 km box (Waze). New sightings go to [onHit]; the strongest current one feeds- * the threat headline ([AmbientThreats]); [aircraftStatus] / [wazeStatus] say how each- * source is doing (shown in Settings).+ * The two internet sources, both off by default: police / government aircraft from community ADS-B+ * feeds (every 60 s), and Waze reports ([WazeWatch]: through the user's OpenWeb Ninja key or straight+ * from Waze, as often as Settings says). Aircraft send a position rounded to ~1 km. New sightings go to+ * [onAlert]; the strongest current one feeds the threat headline ([AmbientThreats]); [aircraftStatus] /+ * [wazeStatus] say how each source is doing (shown in Settings).*/class OnlineWatch(private val context: Context,private val scope: CoroutineScope,private val location: () -> Location?,- private val onHit: (hit: Hit, lat: Double, lon: Double, key: String) -> Unit+ onCallout: (String) -> Unit = {},+ private val onAlert: (Alert) -> Unit) {+ /** A new sighting for the service to log and, if it clears the alert threshold, to alert on. */+ data class Alert(+ val hit: Hit,+ val lat: Double,+ val lon: Double,+ val key: String,+ /** What to say aloud; null for the short word of the hit. */+ val spoken: String? = null,+ /** Sound and voice, a notification only, or nothing beyond the log. */+ val level: WazePolice.Level = WazePolice.Level.LOUD,+ /** False for a sighting already logged that only now clears the alert threshold. */+ val log: Boolean = true+ )++ /** An answer other than 200. */+ internal class HttpError(val code: Int) : Exception("HTTP $code")+private var aircraftJob: Job? = null- private var wazeJob: Job? = nullprivate val loiter = PoliceAircraft.LoiterTracker()private val lastAircraftHit = HashMap<String, Long>()- private val wazeSeen = HashMap<String, Long>()- private var wazeKey: String? = null+ private val waze = WazeWatch(context, scope, location, onAlert, onCallout)- /** Starts or stops each source to match Settings (call on every scan (re)start). */+ /** Starts or stops each source to match Settings (call on every scan (re)start and when Settings closes). */fun sync() {val wantAir = Prefs.categoryEnabled(context, Category.AIRCRAFT)if (wantAir && aircraftJob?.isActive != true) {@@ -48,22 +62,13 @@ class OnlineWatch(aircraftJob?.cancel(); aircraftJob = null; AmbientThreats.aircraft = null; aircraftStatus = ""PoliceAircraft.latest = emptyList()}- val wantWaze = Prefs.categoryEnabled(context, Category.POLICE_REPORT) && Prefs.wazeAccepted(context)- // A new or changed key is tried right away, not at the next 4-minute round.- val key = SecureStore.get(context, WAZE_KEY_NAME)- if (key != wazeKey) { wazeKey = key; wazeJob?.cancel(); wazeJob = null }- if (wantWaze && wazeJob?.isActive != true) {- wazeJob = scope.launch(Dispatchers.IO) {- while (isActive) { runCatching { pollWaze() }.onFailure { wazeStatus = "Error: ${it.message}" }; delay(WAZE_MS) }- }- } else if (!wantWaze) {- wazeJob?.cancel(); wazeJob = null; AmbientThreats.waze = null; wazeStatus = ""- }+ waze.sync()}fun stop() {- aircraftJob?.cancel(); wazeJob?.cancel()- aircraftJob = null; wazeJob = null+ aircraftJob?.cancel()+ aircraftJob = null+ waze.stop()AmbientThreats.clear()PoliceAircraft.latest = emptyList()}@@ -74,7 +79,7 @@ class OnlineWatch(var lastError: String? = nullval radiusKm = Prefs.aircraftRadiusKm(context)val json = PoliceAircraft.feedUrls(me.latitude, me.longitude, radiusKm).firstNotNullOfOrNull { url ->- runCatching { get(url, emptyMap()) }.onFailure { lastError = it.message }.getOrNull()+ runCatching { httpGet(url, emptyMap()) }.onFailure { lastError = it.message }.getOrNull()} ?: run { aircraftStatus = "ADS-B feeds unreachable" + (lastError?.let { " ($it)" } ?: ""); return }val planes = PoliceAircraft.parseFeed(json)val now = System.currentTimeMillis()@@ -91,7 +96,7 @@ class OnlineWatch(val last = lastAircraftHit[p.hex] ?: 0Lif (now - last >= AIRCRAFT_REPEAT_MS) {lastAircraftHit[p.hex] = now- onHit(hit, p.lat, p.lon, "air:" + p.hex)+ onAlert(Alert(hit, p.lat, p.lon, "air:" + p.hex))}}loiter.prune(now)@@ -104,60 +109,31 @@ class OnlineWatch((best?.let { " · ${it.label}" } ?: ", none police")}- private fun pollWaze() {- val key = SecureStore.get(context, WAZE_KEY_NAME)- if (key.isNullOrBlank()) { wazeStatus = "Add your OpenWeb Ninja API key"; return }- val me = location() ?: run { wazeStatus = "Waiting for a GPS fix"; return }- val json = try {- get(WazePolice.url(me.latitude, me.longitude), mapOf("x-api-key" to key))- } catch (e: HttpError) {- wazeStatus = when (e.code) {- 401, 403 -> "API key rejected (HTTP ${e.code})"- 429 -> "OpenWeb Ninja limit reached (HTTP 429)"- else -> "OpenWeb Ninja answered HTTP ${e.code}"- }- return- }- val now = System.currentTimeMillis()- val hits = WazePolice.parse(json).mapNotNull { r -> WazePolice.hit(r, me.latitude, me.longitude, now)?.let { r to it.first } }- for ((r, hit) in hits) {- if (r.id in wazeSeen) continue- wazeSeen[r.id] = now- onHit(hit, r.lat, r.lon, "waze:" + r.id)- }- wazeSeen.entries.removeAll { now - it.value > WazePolice.MAX_AGE_MS * 2 }- val best = hits.maxByOrNull { it.second.confidence }?.second- AmbientThreats.waze = best?.let { now to AmbientThreats.Threat(it.confidence, it.label, Category.POLICE_REPORT) }- wazeStatus = "Updated ${clock(now)}: ${hits.size} police report${if (hits.size == 1) "" else "s"} within 2 km"- }-- private class HttpError(val code: Int) : Exception("HTTP $code")-- private fun get(url: String, headers: Map<String, String>): String {- val c = (URL(url).openConnection() as HttpURLConnection).apply {- connectTimeout = 10_000- readTimeout = 20_000- setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")- setRequestProperty("Accept", "application/json")- headers.forEach { (k, v) -> setRequestProperty(k, v) }- }- try {- if (c.responseCode != 200) throw HttpError(c.responseCode)- return c.inputStream.bufferedReader().use { it.readText() }- } finally {- c.disconnect()- }- }-private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))companion object {const val WAZE_KEY_NAME = "openwebninja_api_key"private const val AIRCRAFT_MS = 60_000L- private const val WAZE_MS = 4 * 60_000Lprivate const val AIRCRAFT_REPEAT_MS = 20 * 60_000L@Volatile var aircraftStatus = ""@Volatile var wazeStatus = ""++ /** A plain GET returning the body as text; throws [HttpError] for any answer other than 200. */+ internal fun httpGet(url: String, headers: Map<String, String>): String {+ val c = (URL(url).openConnection() as HttpURLConnection).apply {+ connectTimeout = 10_000+ readTimeout = 20_000+ setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")+ setRequestProperty("Accept", "application/json")+ headers.forEach { (k, v) -> setRequestProperty(k, v) }+ }+ try {+ if (c.responseCode != 200) throw HttpError(c.responseCode)+ return c.inputStream.bufferedReader().use { it.readText() }+ } finally {+ c.disconnect()+ }+ }}}diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeMotion.kt b/app/src/main/java/com/rfsentinel/app/online/WazeMotion.ktnew file mode 100644index 0000000..f8b1273--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/WazeMotion.kt@@ -0,0 +1,123 @@+package com.rfsentinel.app.online++import com.rfsentinel.app.service.DeviceRegistry++/**+ * Tells whether the phone is parked, moving or on a fast road, from the position it is fed about+ * once a second. "Parked" means it has stayed within [parkedRadiusM] of one spot for [parkedAfterMs]+ * (GPS wander while standing still is smaller than that).+ */+class MotionTracker(+ private val parkedRadiusM: Double = 60.0,+ private val parkedAfterMs: Long = 90_000L,+ private val fastMps: Double = 22.0 // about 80 km/h+) {+ enum class State { PARKED, MOVING, FAST }++ private var anchorLat = 0.0+ private var anchorLon = 0.0+ private var anchorSince = -1L+ private var lastLat = 0.0+ private var lastLon = 0.0+ private var lastAt = -1L+ private var speedMps = 0.0++ /** [speed] is the fix's own speed in m/s when it has one; otherwise it is worked out from the last two positions. */+ fun update(lat: Double, lon: Double, speed: Float?, now: Long) {+ if (anchorSince < 0 || DeviceRegistry.metersBetween(anchorLat, anchorLon, lat, lon) > parkedRadiusM) {+ anchorLat = lat; anchorLon = lon; anchorSince = now+ }+ speedMps = when {+ speed != null && speed >= 0f -> speed.toDouble()+ lastAt >= 0 && now - lastAt >= 1_000 -> DeviceRegistry.metersBetween(lastLat, lastLon, lat, lon) / ((now - lastAt) / 1000.0)+ else -> speedMps+ }+ lastLat = lat; lastLon = lon; lastAt = now+ }++ /** Before the first position it acts as if driving, so nothing is slowed down on a guess. */+ fun state(now: Long): State = when {+ anchorSince < 0 -> State.MOVING+ now - anchorSince >= parkedAfterMs -> State.PARKED+ speedMps >= fastMps -> State.FAST+ else -> State.MOVING+ }+}++/** How often Waze is asked, and how that adapts to how the phone is moving. */+object WazeTiming {+ /** The seconds each backend's slider steps through. */+ val DIRECT_STEPS_S = intArrayOf(15, 30, 60, 90, 120, 300)+ /** OpenWeb Ninja bills every check, so it never goes faster than 2 minutes. */+ val NINJA_STEPS_S = intArrayOf(120, 180, 240, 300, 600)+ const val DIRECT_DEFAULT_S = 60+ const val NINJA_DEFAULT_S = 240++ fun steps(direct: Boolean) = if (direct) DIRECT_STEPS_S else NINJA_STEPS_S++ /** Fewest seconds between two checks when one is asked for by hand ("Check now"). */+ fun minGapS(direct: Boolean) = if (direct) 10 else 60++ /**+ * Whether a check is due: the very first one ([lastStart] 0), one whose interval has run out, or one+ * asked for by hand ([manual]) that is not too soon after the last.+ */+ fun checkDue(now: Long, lastStart: Long, everyS: Int, manual: Boolean, minGapS: Int): Boolean =+ lastStart == 0L || now - lastStart >= everyS * 1000L || (manual && now - lastStart >= minGapS * 1000L)++ /**+ * The seconds to wait before the next check. Parked: four times as long (never slower than the+ * slowest step). On a fast road: half as long, but only for Waze direct (free; OpenWeb Ninja+ * would bill twice as much). Otherwise the chosen interval.+ */+ fun effectiveS(baseS: Int, state: MotionTracker.State, direct: Boolean, adapt: Boolean): Int {+ if (!adapt) return baseS+ val steps = steps(direct)+ return when (state) {+ MotionTracker.State.PARKED -> minOf(baseS * 4, maxOf(steps.last(), baseS))+ MotionTracker.State.FAST -> if (direct) maxOf(baseS / 2, steps.first()) else baseS+ MotionTracker.State.MOVING -> baseS+ }+ }+}++/**+ * Whether each report is getting closer or further, from its distance over the last few seconds.+ * Needs about 4 s of history and a change of 15 m or more; anything less is "steady".+ */+class WazeTrend {+ enum class Trend { CLOSING, AWAY, STEADY }++ private class Sample(val at: Long, val distM: Double)++ private val history = HashMap<String, ArrayDeque<Sample>>()++ fun update(id: String, distM: Double, now: Long) {+ val h = history.getOrPut(id) { ArrayDeque() }+ h.addLast(Sample(now, distM))+ while (h.size > 1 && now - h.first().at > WINDOW_MS) h.removeFirst()+ }++ fun trend(id: String): Trend {+ val h = history[id] ?: return Trend.STEADY+ if (h.size < 2) return Trend.STEADY+ val first = h.first()+ val last = h.last()+ if (last.at - first.at < MIN_SPAN_MS) return Trend.STEADY+ val delta = last.distM - first.distM+ return when {+ delta <= -MIN_CHANGE_M -> Trend.CLOSING+ delta >= MIN_CHANGE_M -> Trend.AWAY+ else -> Trend.STEADY+ }+ }++ /** Forgets reports that are no longer around. */+ fun keepOnly(ids: Set<String>) { history.keys.retainAll(ids) }++ private companion object {+ const val WINDOW_MS = 10_000L+ const val MIN_SPAN_MS = 4_000L+ const val MIN_CHANGE_M = 15.0+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt b/app/src/main/java/com/rfsentinel/app/online/WazePolice.ktindex 3f1c3de..c373747 100644--- a/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt+++ b/app/src/main/java/com/rfsentinel/app/online/WazePolice.kt@@ -4,17 +4,50 @@ import com.google.gson.JsonObjectimport com.google.gson.JsonParserimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.online.wazert.WazeRtFetcherimport com.rfsentinel.app.service.DeviceRegistryimport java.time.Instant+import kotlin.math.abs/**- * Police reported by Waze users, read through OpenWeb Ninja's Waze API with the user's- * own API key (off by default; a third-party service RF Sentinel doesn't run or endorse).- * Scored by distance and age: a fresh report next to you is a probable sign, one a- * kilometre away or 40 minutes old only a weak one.+ * Reports from Waze users (police by default, other event types if the user enables them),+ * read either through OpenWeb Ninja's Waze API with the user's own API key, or (opt-in)+ * straight from Waze over the app's own protocol (see [WazeRtFetcher]). Off by default;+ * third-party services RF Sentinel doesn't run or endorse.+ * Scored by distance and age: a fresh report next to you is a probable sign, one far away+ * or 40 minutes old only a weak one.*/object WazePolice {+ /** What an alert of one event type does: all of it, a notification only, or nothing beyond the list and map. */+ enum class Level(val label: String) {+ LOUD("Sound and voice"),+ NOTIFY("Notification only"),+ LOG("Silent (list and map)")+ }++ /** The event kinds the user can pick under "What to alert on". Police is the default. */+ enum class Type(+ val label: String, val wire: List<String>, val color: Int, val baseScore: Double, val defaultLevel: Level+ ) {+ POLICE("Police", listOf("POLICE"), 0xFF1E88E5.toInt(), 90.0, Level.LOUD),+ ACCIDENT("Accidents", listOf("ACCIDENT"), 0xFFE53935.toInt(), 75.0, Level.LOUD),+ HAZARD("Hazards", listOf("HAZARD", "NEW_BAD_WEATHER"), 0xFFFB8C00.toInt(), 70.0, Level.NOTIFY),+ ROAD_CLOSED("Road closures", listOf("ROAD_CLOSED", "SYSTEM_ROAD_CLOSED", "TURN_CLOSED", "NEW_LANE_CLOSED"), 0xFF6D4C41.toInt(), 70.0, Level.NOTIFY),+ JAM("Traffic jams", listOf("JAM"), 0xFF8E24AA.toInt(), 65.0, Level.LOG);++ val singular: String get() = when (this) {+ POLICE -> "Police"; ACCIDENT -> "Accident"; HAZARD -> "Hazard"; ROAD_CLOSED -> "Road closure"; JAM -> "Traffic jam"+ }++ companion object {+ fun ofWire(w: String?): Type? = entries.firstOrNull { t -> t.wire.any { it.equals(w, ignoreCase = true) } }+ fun parse(names: Set<String>): Set<Type> = entries.filter { it.name in names }.toSet()+ /** The type a hit is about, from its label ("Accident reported on Waze (major)"). */+ fun ofHit(hit: Hit): Type? = entries.firstOrNull { hit.label.startsWith(it.singular) }+ }+ }+data class Report(val id: String,val lat: Double,@@ -23,30 +56,164 @@ object WazePolice {val street: String?,val city: String?,val thumbsUp: Int,- val reliability: Int?+ val reliability: Int?,+ val type: Type = Type.POLICE,+ /** Waze's own name for it, e.g. POLICE_HIDING; see [subtypeLabel]. */+ val subtype: String? = null)- /** Search box half-size: about 2 km around you. */+ /** Default search radius: about 2 km around you (Settings can change it). */const val RADIUS_M = 2_000.0/** Reports older than this are ignored. */const val MAX_AGE_MS = 45 * 60_000L- fun url(lat: Double, lon: Double): String {- val dLat = RADIUS_M / 111_000.0- val dLon = RADIUS_M / (111_000.0 * kotlin.math.max(0.01, kotlin.math.cos(Math.toRadians(lat))))+ // ---- where a report is, relative to you -------------------------------------------------++ enum class Side { AHEAD, BEHIND, LEFT, RIGHT }++ /**+ * [distanceM] and the [compass] point from you to the report; [side] and [relDeg] (-180..180,+ * 0 = straight ahead) are known only while you are driving, i.e. with a heading and some speed.+ */+ data class Where(val distanceM: Double, val compass: String, val side: Side?, val relDeg: Float?) {+ /** Clearly behind (more than 100 degrees off your heading); false when the heading is unknown. */+ val isBehind: Boolean get() = relDeg != null && abs(relDeg) > 100f+ }++ /** Works out [Where] from plain numbers; [heading] is null when the phone is not driving. */+ fun where(meLat: Double, meLon: Double, heading: Double?, lat: Double, lon: Double): Where {+ val d = DeviceRegistry.metersBetween(meLat, meLon, lat, lon)+ val p1 = Math.toRadians(meLat)+ val p2 = Math.toRadians(lat)+ val dl = Math.toRadians(lon - meLon)+ val y = Math.sin(dl) * Math.cos(p2)+ val x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl)+ val bearing = (Math.toDegrees(Math.atan2(y, x)) + 360.0) % 360.0+ val compass = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")[((bearing + 22.5) / 45.0).toInt() % 8]+ val rel = heading?.let { (((bearing - it + 540.0) % 360.0) - 180.0).toFloat() }+ val side = rel?.let {+ when {+ abs(it) <= 45f -> Side.AHEAD+ abs(it) >= 135f -> Side.BEHIND+ it > 0 -> Side.RIGHT+ else -> Side.LEFT+ }+ }+ return Where(d, compass, side, rel)+ }++ /** [where] from a fix: the heading counts only while the phone is moving (over about 5 km/h). */+ fun where(me: android.location.Location, lat: Double, lon: Double): Where =+ where(me.latitude, me.longitude, if (me.hasBearing() && me.hasSpeed() && me.speed > 1.5f) me.bearing.toDouble() else null, lat, lon)++ /** Exact distance: whole metres under 1 km, then km to 10 m. */+ fun preciseDistance(m: Double): String =+ if (m < 1000) "${m.toInt()} m" else String.format(java.util.Locale.US, "%.2f km", m / 1000)++ /** "412 m NE · ahead · closing in": distance, compass point, side while driving, and whether it is getting closer. */+ fun relativeText(w: Where, trend: WazeTrend.Trend = WazeTrend.Trend.STEADY): String {+ val side = when (w.side) {+ Side.AHEAD -> " · ahead"+ Side.BEHIND -> " · behind you"+ Side.RIGHT -> " · to your right"+ Side.LEFT -> " · to your left"+ null -> ""+ }+ val moving = when {+ trend == WazeTrend.Trend.CLOSING -> " · closing in"+ trend == WazeTrend.Trend.AWAY && w.side != Side.BEHIND -> " · moving away"+ else -> ""+ }+ return "${preciseDistance(w.distanceM)} ${w.compass}$side$moving"+ }++ /** Where a report is relative to a fix, as text (no trend). */+ fun relative(me: android.location.Location, lat: Double, lon: Double): String = relativeText(where(me, lat, lon))++ // ---- what the screens show --------------------------------------------------------------++ /** One report as the list and map show it: how it scored, where it is now, and whether it is getting closer. */+ data class Shown(+ val report: Report,+ val hit: Hit,+ val where: Where,+ val trend: WazeTrend.Trend = WazeTrend.Trend.STEADY,+ val level: Level = Level.LOUD+ ) {+ val distanceM: Double get() = where.distanceM+ }++ /** The current reports (every enabled type, inside the view range). */+ @Volatile var latest: List<Shown> = emptyList()+ private set+ /** When the last check answered. */+ @Volatile var latestAt = 0L+ private set++ private val listeners = java.util.concurrent.CopyOnWriteArrayList<() -> Unit>()++ /**+ * Calls [onChange] (on the polling thread) every time the list of reports changes in a way worth+ * redrawing at once, so a screen need not wait for its next tick. Returns a function that removes it.+ */+ fun addListener(onChange: () -> Unit): () -> Unit {+ listeners.add(onChange)+ return { listeners.remove(onChange) }+ }++ /** Replaces the current reports and tells every open screen. */+ fun publish(reports: List<Shown>, at: Long) {+ latest = reports+ latestAt = at+ for (l in listeners) runCatching { l() }+ }++ /** Refreshes distances and scores once a second without waking the listeners: the screens redraw on their own ticks. */+ fun updateQuiet(reports: List<Shown>) {+ latest = reports+ }++ // ---- the poller's state, for the "check now" button and the status screen ---------------++ /** True while the Waze checks are running (scanning, Waze on, not paused). */+ @Volatile var running = false+ /** When the last check began (0 = none yet). */+ @Volatile var lastCheckStartedAt = 0L+ /** Set by "Check now"; the poller runs a check as soon as it sees a newer value. */+ @Volatile var checkNowAt = 0L+ private set++ /**+ * Asks the poller to check right now. Returns null when asked, or how many seconds to wait:+ * manual checks are spaced out so Waze is not hammered and OpenWeb Ninja does not bill a burst.+ */+ fun requestCheckNow(minGapS: Int, now: Long = System.currentTimeMillis()): Int? {+ val since = now - lastCheckStartedAt+ if (lastCheckStartedAt != 0L && since < minGapS * 1000L) return ((minGapS * 1000L - since + 999) / 1000).toInt()+ checkNowAt = now+ return null+ }++ // ---- fetching ----------------------------------------------------------------------------++ fun url(lat: Double, lon: Double, radiusM: Double = RADIUS_M, types: Set<Type> = setOf(Type.POLICE)): String {+ val dLat = radiusM / 111_000.0+ val dLon = radiusM / (111_000.0 * kotlin.math.max(0.01, kotlin.math.cos(Math.toRadians(lat))))fun f(v: Double) = String.format(java.util.Locale.US, "%.4f", v)+ // OpenWeb Ninja filters alerts by these names; jams are a separate list there, so JAM is not sent.+ val names = types.filter { it != Type.JAM }.ifEmpty { listOf(Type.POLICE) }.joinToString(",") { it.name }return "https://api.openwebninja.com/waze/alerts-and-jams?bottom_left=${f(lat - dLat)},${f(lon - dLon)}" +- "&top_right=${f(lat + dLat)},${f(lon + dLon)}&alert_types=POLICE&max_alerts=50&max_jams=0"+ "&top_right=${f(lat + dLat)},${f(lon + dLon)}&alert_types=$names&max_alerts=200&max_jams=0"}- /** POLICE alerts from the API's JSON (re-filtered here in case the server ignores the type filter). */- internal fun parse(json: String): List<Report> {+ /** Alerts of the wanted types from the API's JSON (re-filtered here in case the server ignores the type filter). */+ internal fun parse(json: String, types: Set<Type> = setOf(Type.POLICE)): List<Report> {val root = JsonParser.parseString(json).asJsonObjectval data = root.getAsJsonObject("data") ?: return emptyList()val alerts = data.getAsJsonArray("alerts") ?: return emptyList()return alerts.mapNotNull { e ->val o = e.asJsonObject- if (!o.str("type").equals("POLICE", ignoreCase = true)) return@mapNotNull null+ val type = Type.ofWire(o.str("type"))?.takeIf { it in types } ?: return@mapNotNull nullReport(id = o.str("alert_id") ?: return@mapNotNull null,lat = o.num("latitude") ?: return@mapNotNull null,@@ -55,7 +222,9 @@ object WazePolice {street = o.str("street"),city = o.str("city"),thumbsUp = o.num("num_thumbs_up")?.toInt() ?: 0,- reliability = o.num("alert_reliability")?.toInt()+ reliability = o.num("alert_reliability")?.toInt(),+ type = type,+ subtype = o.str("subtype"))}}@@ -66,33 +235,109 @@ object WazePolice {private fun JsonObject.num(k: String): Double? =get(k)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isNumber }?.asDouble+ // ---- scoring -----------------------------------------------------------------------------++ /** Points lost between the base score (within 100 m) and the edge of the alert radius. */+ private const val EDGE_DROP = 20.0+ /** Most points a report loses as it ages over [MAX_AGE_MS]. */+ private const val MAX_DECAY = 8.0+/**- * 0-100: 70 within 100 m, falling to 40 at 2 km; minus up to 12 points as the report- * ages over 45 minutes; plus up to 6 for other drivers confirming it.+ * 0-100: the type's base score (90 for police) within 100 m, falling by 20 at the edge of the+ * alert radius; minus up to 8 points as the report ages over 45 minutes; plus up to 6 for other+ * drivers confirming it.*/- fun score(distanceM: Double, ageMs: Long, thumbsUp: Int): Int {+ fun score(distanceM: Double, ageMs: Long, thumbsUp: Int, radiusM: Double = RADIUS_M, base: Double = 90.0): Int {val byDistance = when {- distanceM <= 100 -> 70.0- distanceM >= RADIUS_M -> 40.0- else -> 70.0 - 30.0 * (distanceM - 100) / (RADIUS_M - 100)+ distanceM <= 100 -> base+ distanceM >= radiusM -> base - EDGE_DROP+ else -> base - EDGE_DROP * (distanceM - 100) / (radiusM - 100)}- val decay = 12.0 * (ageMs.coerceIn(0, MAX_AGE_MS).toDouble() / MAX_AGE_MS)+ val decay = MAX_DECAY * (ageMs.coerceIn(0, MAX_AGE_MS).toDouble() / MAX_AGE_MS)val trust = (thumbsUp * 2).coerceAtMost(6)return (byDistance - decay + trust).toInt().coerceIn(0, 100)}- fun hit(r: Report, lat: Double, lon: Double, now: Long): Pair<Hit, Double>? {+ /** A police alert from the direct (Waze app protocol) backend. Its thumbs-up count is the crowd-trust signal. */+ internal fun fromDirect(a: WazeRtFetcher.PoliceAlert) = Report(+ id = a.uuid, lat = a.lat, lon = a.lon,+ publishedMs = a.pubMillis.takeIf { it > 0 },+ street = a.street?.ifBlank { null }, city = a.city?.ifBlank { null },+ thumbsUp = a.thumbsUp, reliability = null,+ type = Type.ofWire(a.type) ?: Type.POLICE,+ subtype = a.subtype?.ifBlank { null }+ )++ // ---- readable names for Waze's subtypes --------------------------------------------------++ private val SUBTYPE_WORDS = mapOf(+ "POLICE_VISIBLE" to "visible",+ "POLICE_HIDING" to "hiding",+ "POLICE_WITH_MOBILE_CAMERA" to "mobile speed camera",+ "ACCIDENT_MINOR" to "minor",+ "ACCIDENT_MAJOR" to "major",+ "JAM_LIGHT_TRAFFIC" to "light",+ "JAM_MODERATE_TRAFFIC" to "moderate",+ "JAM_HEAVY_TRAFFIC" to "heavy",+ "JAM_STAND_STILL_TRAFFIC" to "standstill",+ "HAZARD_ON_ROAD" to "on the road",+ "HAZARD_ON_SHOULDER" to "on the shoulder",+ "HAZARD_WEATHER" to "weather",+ "HAZARD_ON_ROAD_OBJECT" to "object on the road",+ "HAZARD_ON_ROAD_POT_HOLE" to "pothole",+ "HAZARD_ON_ROAD_ROAD_KILL" to "animal on the road",+ "HAZARD_ON_ROAD_LANE_CLOSED" to "lane closed",+ "HAZARD_ON_ROAD_OIL" to "oil on the road",+ "HAZARD_ON_ROAD_ICE" to "ice on the road",+ "HAZARD_ON_ROAD_CONSTRUCTION" to "construction",+ "HAZARD_ON_ROAD_CAR_STOPPED" to "car stopped on the road",+ "HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT" to "traffic light fault",+ "HAZARD_ON_ROAD_EMERGENCY_VEHICLE" to "emergency vehicle",+ "HAZARD_ON_SHOULDER_CAR_STOPPED" to "car stopped on the shoulder",+ "HAZARD_ON_SHOULDER_ANIMALS" to "animals on the shoulder",+ "HAZARD_ON_SHOULDER_MISSING_SIGN" to "missing sign",+ "HAZARD_WEATHER_FOG" to "fog",+ "HAZARD_WEATHER_HAIL" to "hail",+ "HAZARD_WEATHER_HEAVY_RAIN" to "heavy rain",+ "HAZARD_WEATHER_HEAVY_SNOW" to "heavy snow",+ "HAZARD_WEATHER_FLOOD" to "flood",+ "HAZARD_WEATHER_FREEZING_RAIN" to "freezing rain",+ "ROAD_CLOSED_HAZARD" to "hazard",+ "ROAD_CLOSED_CONSTRUCTION" to "construction",+ "ROAD_CLOSED_EVENT" to "event"+ )++ private val TYPE_PREFIXES = listOf("POLICE_", "ACCIDENT_", "JAM_", "HAZARD_", "ROAD_CLOSED_", "LANE_CLOSURE_", "BAD_WEATHER_")++ /** "hiding", "mobile speed camera", "heavy"...; null when Waze gave no subtype. */+ fun subtypeLabel(subtype: String?): String? {+ val s = subtype?.trim()?.uppercase()?.ifEmpty { null } ?: return null+ if (s == "NO_SUBTYPE" || s.startsWith("__NOT_IN_USE")) return null+ SUBTYPE_WORDS[s]?.let { return it }+ val prefix = TYPE_PREFIXES.firstOrNull { s.startsWith(it) }+ return (if (prefix != null) s.removePrefix(prefix) else s).lowercase().replace('_', ' ').ifEmpty { null }+ }++ const val VIA_NINJA = "OpenWeb Ninja"+ const val VIA_DIRECT = "Waze direct"++ /**+ * [radiusM] is the alert radius: the score falls from its base by 20 across it. [maxM] is how+ * far away a report is still kept (the map's view range), so changing the view never changes a score.+ */+ fun hit(r: Report, lat: Double, lon: Double, now: Long, via: String = VIA_NINJA, radiusM: Double = RADIUS_M, maxM: Double = radiusM * 1.5): Pair<Hit, Double>? {val d = DeviceRegistry.metersBetween(lat, lon, r.lat, r.lon)- if (d > RADIUS_M * 1.5) return null+ if (d > maxM) return nullval age = r.publishedMs?.let { now - it } ?: 0Lif (age > MAX_AGE_MS) return nullval where = listOfNotNull(r.street, r.city).joinToString(", ").ifEmpty { "nearby" }val ago = r.publishedMs?.let { " ${(age / 60_000).coerceAtLeast(0)} min ago" } ?: ""val dist = if (d < 1000) "${(d / 10).toInt() * 10} m" else String.format(java.util.Locale.US, "%.1f km", d / 1000)- return Hit(Category.POLICE_REPORT, "Police reported on Waze", score(d, age, r.thumbsUp),+ val sub = subtypeLabel(r.subtype)?.let { " ($it)" } ?: ""+ return Hit(Category.POLICE_REPORT, "${r.type.singular} reported on Waze$sub", score(d, age, r.thumbsUp, radiusM, r.type.baseScore),"Reported$ago on $where, about $dist away" +(if (r.thumbsUp > 0) " (${r.thumbsUp} driver${if (r.thumbsUp == 1) "" else "s"} confirmed)" else "") +- ". Crowd report via OpenWeb Ninja - not verified.",- "Waze user reports via OpenWeb Ninja (third party)") to d+ ". Crowd report via $via - not verified.",+ "Waze user reports via $via (third party)") to d}}diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.ktnew file mode 100644index 0000000..e26c540--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt@@ -0,0 +1,319 @@+package com.rfsentinel.app.online++import android.content.Context+import android.location.Location+import android.os.SystemClock+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.online.wazert.WazeRtFetcher+import com.rfsentinel.app.util.Prefs+import com.rfsentinel.app.util.SecureStore+import com.rfsentinel.app.util.Spoken+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch++/** What the Waze status screen shows about the checks, kept by [WazeWatch]. */+object WazeStatus {+ @Volatile var direct = false+ /** The interval chosen in Settings, and what it is right now after adapting to how the phone moves. */+ @Volatile var baseS = 0+ @Volatile var everyS = 0+ @Volatile var motion = MotionTracker.State.MOVING+ @Volatile var nextCheckAt = 0L+ @Volatile var lastCheckAt = 0L+ @Volatile var lastCheckMs = 0L+ @Volatile var checks = 0+ /** From the last answer: reports on the map, and how many of them are inside the alert range. */+ @Volatile var onMap = 0+ @Volatile var inAlertRange = 0+}++/**+ * The Waze source. It asks Waze (or OpenWeb Ninja) for the reports around you at the interval set in+ * Settings, and then, every second, works out from your position right now how far each one is, whether+ * it is ahead of you and getting closer, and what to do about it: a new alert the moment one comes inside+ * the alert range (not only at the next check), and spoken call-outs as it gets closer.+ */+class WazeWatch(+ private val context: Context,+ private val scope: CoroutineScope,+ private val location: () -> Location?,+ private val onAlert: (OnlineWatch.Alert) -> Unit,+ private val onCallout: (String) -> Unit+) {+ private var job: Job? = null+ /** Bumped whenever the checks start or stop, so a cancelled loop that is still winding down cannot undo a newer one. */+ private val generation = java.util.concurrent.atomic.AtomicInteger()+ private var jobKey: String? = null+ private val motion = MotionTracker()+ private val trend = WazeTrend()+ /** First seen (and logged) reports, and those that have had an alert. */+ private val seen = HashMap<String, Long>()+ private val alerted = HashSet<String>()+ /** The smallest call-out distance already spoken for each report. */+ private val calledBand = HashMap<String, Int>()+ private var known: Map<String, WazePolice.Report> = emptyMap()+ private var via = WazePolice.VIA_DIRECT+ private var lastOkAt = 0L+ private var shownIds: Set<String> = emptySet()+ private var direct = false+ private var wazeDirect: WazeRtFetcher? = null+ private var wazeDirectRegion = ""++ /** Starts or stops the checks to match Settings (call on every scan (re)start and when Settings closes). */+ fun sync() {+ val want = Prefs.categoryEnabled(context, Category.POLICE_REPORT) && Prefs.wazeReady(context)+ val wantDirect = Prefs.wazeBackend(context) == Prefs.WAZE_DIRECT+ // A new or changed key, or a switch of backend, is tried right away, not at the next round.+ val key = if (wantDirect) "direct" else SecureStore.get(context, OnlineWatch.WAZE_KEY_NAME)+ if (key != jobKey) { jobKey = key; job?.cancel(); job = null }+ if (want && job?.isActive != true) {+ direct = wantDirect+ val gen = generation.incrementAndGet()+ job = scope.launch(Dispatchers.IO) { loop(gen) }+ } else if (!want) {+ job?.cancel(); job = null+ clear()+ }+ }++ fun stop() {+ job?.cancel(); job = null+ clear()+ }++ private fun clear() {+ generation.incrementAndGet()+ known = emptyMap()+ shownIds = emptySet()+ AmbientThreats.waze = null+ OnlineWatch.wazeStatus = ""+ WazePolice.running = false+ WazePolice.publish(emptyList(), 0L)+ }++ private suspend fun loop(gen: Int) {+ WazePolice.running = true+ var lastStart = 0L+ var handledNow = WazePolice.checkNowAt+ try {+ while (currentCoroutineContext().isActive) {+ val now = System.currentTimeMillis()+ location()?.let { motion.update(it.latitude, it.longitude, if (it.hasSpeed()) it.speed else null, now) }+ if (Prefs.wazePaused(context)) {+ if (known.isNotEmpty()) { known = emptyMap(); AmbientThreats.waze = null; WazePolice.publish(emptyList(), now) }+ OnlineWatch.wazeStatus = "Paused - open Waze status to resume"+ WazeStatus.nextCheckAt = 0L+ delay(1_000)+ continue+ }+ val every = effectiveS(now)+ WazeStatus.direct = direct+ val sinceStart = now - lastStart+ val manual = WazePolice.checkNowAt > handledNow+ if (manual) handledNow = WazePolice.checkNowAt+ val due = WazeTiming.checkDue(now, lastStart, every, manual, WazeTiming.minGapS(direct))+ if (due) {+ lastStart = now+ val began = SystemClock.elapsedRealtime()+ val asked = runCatching { if (direct) pollDirect() else pollNinja() }+ .onFailure { OnlineWatch.wazeStatus = "Error: ${it.message}" }.getOrDefault(true)+ if (asked) {+ WazePolice.lastCheckStartedAt = now+ WazeStatus.lastCheckAt = now+ WazeStatus.lastCheckMs = SystemClock.elapsedRealtime() - began+ WazeStatus.checks+++ } else {+ // No GPS fix or key yet: look again in a few seconds instead of waiting out the interval.+ lastStart = now - every * 1000L + RETRY_MS+ }+ }+ WazeStatus.nextCheckAt = lastStart + every * 1000L+ evaluate(System.currentTimeMillis(), publish = false)+ delay(1_000)+ }+ } finally {+ if (generation.get() == gen) WazePolice.running = false+ }+ }++ /** The seconds between checks right now: the chosen interval, adapted to whether the phone is parked or on a fast road. */+ private fun effectiveS(now: Long): Int {+ val base = Prefs.wazeIntervalS(context, direct)+ val state = motion.state(now)+ val every = WazeTiming.effectiveS(base, state, direct, Prefs.wazeAdaptive(context))+ WazeStatus.baseS = base+ WazeStatus.everyS = every+ WazeStatus.motion = state+ return every+ }++ // ---- the two ways of asking ---------------------------------------------------------------++ /** Returns false when nothing could be asked yet (no key or GPS fix), so the loop retries soon. */+ private fun pollNinja(): Boolean {+ val key = SecureStore.get(context, OnlineWatch.WAZE_KEY_NAME)+ if (key.isNullOrBlank()) { OnlineWatch.wazeStatus = "Add your OpenWeb Ninja API key"; return false }+ val me = location() ?: run { OnlineWatch.wazeStatus = "Waiting for a GPS fix"; return false }+ val types = WazePolice.Type.parse(Prefs.wazeTypes(context)).ifEmpty { setOf(WazePolice.Type.POLICE) }+ val reach = maxOf(Prefs.wazeViewKm(context) * 1000.0, Prefs.wazeAlertM(context).toDouble())+ val json = try {+ OnlineWatch.httpGet(WazePolice.url(me.latitude, me.longitude, reach, types), mapOf("x-api-key" to key))+ } catch (e: OnlineWatch.HttpError) {+ OnlineWatch.wazeStatus = when (e.code) {+ 401, 403 -> "API key rejected (HTTP ${e.code})"+ 429 -> "OpenWeb Ninja limit reached (HTTP 429)"+ else -> "OpenWeb Ninja answered HTTP ${e.code}"+ }+ return true+ }+ ingest(WazePolice.parse(json, types), WazePolice.VIA_NINJA, System.currentTimeMillis())+ return true+ }++ /** The Waze RT host region for a position: Americas, Israel, or the rest of the world. */+ private fun wazeRegion(lat: Double, lon: Double) = when {+ lon in -170.0..-30.0 -> "na"+ lat in 29.0..33.5 && lon in 34.0..36.0 -> "il"+ else -> "row"+ }++ private fun fetcherFor(region: String): WazeRtFetcher {+ if (wazeDirect == null || wazeDirectRegion != region) {+ wazeDirect = WazeRtFetcher(context, region); wazeDirectRegion = region+ }+ return wazeDirect!!+ }++ /** Direct backend: alerts of the chosen types straight from Waze over the app protocol. */+ private fun pollDirect(): Boolean {+ val me = location() ?: run { OnlineWatch.wazeStatus = "Waiting for a GPS fix"; return false }+ val types = WazePolice.Type.parse(Prefs.wazeTypes(context)).ifEmpty { setOf(WazePolice.Type.POLICE) }+ val reach = maxOf(Prefs.wazeViewKm(context) * 1000.0, Prefs.wazeAlertM(context).toDouble())+ val alerts = try {+ // A box wider than the view range, so reports ahead of you are already loaded.+ fetcherFor(wazeRegion(me.latitude, me.longitude))+ .fetchAlertsNear(me.latitude, me.longitude, reach * 1.2, types.flatMap { it.wire }.toSet())+ } catch (e: Exception) {+ OnlineWatch.wazeStatus = "Waze direct: ${e.message ?: e.javaClass.simpleName}"+ return true+ }+ ingest(alerts.map { WazePolice.fromDirect(it) }, WazePolice.VIA_DIRECT, System.currentTimeMillis())+ return true+ }++ // ---- what to do with the reports ----------------------------------------------------------++ /** A check answered: these are now the known reports. */+ @Synchronized+ internal fun ingest(reports: List<WazePolice.Report>, source: String, now: Long) {+ known = reports.associateBy { it.id }+ via = source+ lastOkAt = now+ evaluate(now, publish = true)+ }++ /**+ * Works out, from the position right now, which known reports are in view, how far and in which+ * direction each is, and which deserve an alert or a call-out. Run once a second, and after each check.+ * With [publish] false the screens are woken only when something they show has changed.+ */+ @Synchronized+ internal fun evaluate(now: Long, publish: Boolean) {+ // Failing checks for a long while: better to show nothing than reports that may be long gone.+ if (known.isNotEmpty() && now - lastOkAt > staleAfterMs(now)) known = emptyMap()+ val me = location() ?: return+ val alertM = Prefs.wazeAlertM(context).toDouble()+ val viewM = maxOf(Prefs.wazeViewKm(context) * 1000.0, alertM) // never narrower than the alert range+ val aheadOnly = Prefs.wazeAheadOnly(context)+ val approachOn = Prefs.wazeApproach(context)+ val threshold = Prefs.alertThreshold(context)+ val levels = WazePolice.Type.entries.associateWith { Prefs.wazeLevel(context, it) }++ val shown = ArrayList<WazePolice.Shown>(known.size)+ for (r in known.values) {+ val hit = WazePolice.hit(r, me.latitude, me.longitude, now, via, alertM, viewM)?.first ?: continue+ val w = WazePolice.where(me, r.lat, r.lon)+ trend.update(r.id, w.distanceM, now)+ shown += WazePolice.Shown(r, hit, w, trend.trend(r.id), levels.getValue(r.type))+ }+ trend.keepOnly(known.keys)++ // In the alert range, and (if asked) not behind you.+ fun counts(s: WazePolice.Shown) = s.distanceM <= alertM && !(aheadOnly && s.where.isBehind)++ var fired = false+ for (s in shown) {+ if (!counts(s)) continue+ val id = s.report.id+ val first = id !in seen+ if (first) seen[id] = now+ val eligible = s.hit.confidence >= threshold+ if (first || (eligible && id !in alerted)) {+ if (eligible) alerted += id+ fired = true+ calledBand.putIfAbsent(id, bandFor(s.distanceM))+ onAlert(OnlineWatch.Alert(+ s.hit, s.report.lat, s.report.lon, "waze:$id",+ Spoken.waze(context, s.report.type, s.distanceM, s.where.side), s.level, log = first+ ))+ } else if (approachOn && s.level == WazePolice.Level.LOUD && eligible &&+ s.trend == WazeTrend.Trend.CLOSING && s.where.side != WazePolice.Side.BEHIND+ ) {+ val band = bandFor(s.distanceM)+ if (band < (calledBand[id] ?: Int.MAX_VALUE)) {+ calledBand[id] = band+ onCallout(Spoken.wazePhrase(s.report.type, s.distanceM, s.where.side, short = true))+ }+ }+ }+ seen.entries.removeAll { now - it.value > WazePolice.MAX_AGE_MS * 2 }+ alerted.retainAll(seen.keys)+ calledBand.keys.retainAll(seen.keys)++ // The threat headline: the strongest report that counts and is allowed to be loud enough to matter.+ val headline = shown.filter { counts(it) && it.level != WazePolice.Level.LOG }.maxByOrNull { it.hit.confidence }+ AmbientThreats.waze = headline?.let { now to AmbientThreats.Threat(it.hit.confidence, it.hit.label, Category.POLICE_REPORT) }+ AmbientThreats.wazeTtlMs = 20_000L // refreshed every second while the checks run++ val ids = shown.mapTo(HashSet()) { it.report.id }+ val changed = ids != shownIds+ shownIds = ids+ if (publish) {+ val every = WazeTiming.effectiveS(Prefs.wazeIntervalS(context, via == WazePolice.VIA_DIRECT), motion.state(now), via == WazePolice.VIA_DIRECT, Prefs.wazeAdaptive(context))+ val inRange = shown.count { counts(it) }+ WazeStatus.onMap = shown.size+ WazeStatus.inAlertRange = inRange+ OnlineWatch.wazeStatus = "Updated ${clock(now)}: ${shown.size} on the map (within ${Prefs.formatRange(viewM.toInt())}), " ++ "$inRange in alert range (${Prefs.formatRange(alertM.toInt())}) · every ${Prefs.formatInterval(every)}" ++ (if (every != Prefs.wazeIntervalS(context, via == WazePolice.VIA_DIRECT)) " (adapted)" else "")+ WazePolice.publish(shown, now)+ } else if (changed || fired) {+ WazeStatus.onMap = shown.size+ WazeStatus.inAlertRange = shown.count { counts(it) }+ WazePolice.publish(shown, WazePolice.latestAt)+ } else {+ WazePolice.updateQuiet(shown)+ }+ }++ /** Reports are dropped when no check has answered for this long (a little over three intervals, never under 10 minutes). */+ private fun staleAfterMs(now: Long) = maxOf(10 * 60_000L, WazeTiming.effectiveS(+ Prefs.wazeIntervalS(context, direct), motion.state(now), direct, Prefs.wazeAdaptive(context)) * 3_500L)++ private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))++ private companion object {+ /** After a skipped check (no fix or key yet), look again this soon. */+ const val RETRY_MS = 5_000L+ /** The distances at which a report coming closer is called out again. */+ val APPROACH_BANDS_M = intArrayOf(200, 500, 1000)++ /** The smallest call-out distance a report is already inside (none: a very large number). */+ fun bandFor(distanceM: Double): Int = APPROACH_BANDS_M.firstOrNull { distanceM <= it } ?: Int.MAX_VALUE+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/AlertQueryResult.java b/app/src/main/java/com/rfsentinel/app/online/wazert/AlertQueryResult.javanew file mode 100644index 0000000..44d74e0--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/AlertQueryResult.java@@ -0,0 +1,26 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++import java.util.List;++/**+ * The result of one Waze RT area query: the alerts the server added (as+ * AddAlertAction elements) and the uuids it removed (as "RmAlert," old_command+ * lines).+ *+ * The RT /command endpoint is session-stateful, it only sends an alert once per+ * session, then a removal when it clears, so callers must MERGE these deltas into+ * a persistent cache rather than treat each result as a full snapshot. See+ * {@link WazeAlertCache}.+ */+final class AlertQueryResult {+ final List<WazeAlert> newAlerts;+ final List<String> removedIds;++ AlertQueryResult(List<WazeAlert> newAlerts, List<String> removedIds) {+ this.newAlerts = newAlerts;+ this.removedIds = removedIds;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/DeviceIdentity.java b/app/src/main/java/com/rfsentinel/app/online/wazert/DeviceIdentity.javanew file mode 100644index 0000000..85fb218--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/DeviceIdentity.java@@ -0,0 +1,51 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++import java.util.Random;+import java.util.UUID;++/**+ * A synthetic Android device fingerprint sent in ClientInfo when registering /+ * logging in to Waze: one of 8 fixed device profiles, matching what the Waze+ * client itself reports, with a fresh random installationId.+ */+final class DeviceIdentity {+ final String manufacturer;+ final String model;+ final String osVersion; // synthetic "<release>-SDK<api>" token, sent as ClientInfo.osVersion+ final int screenW;+ final int screenH;+ final String installationId;++ DeviceIdentity(String manufacturer, String model, String osVersion,+ int screenW, int screenH, String installationId) {+ this.manufacturer = manufacturer;+ this.model = model;+ this.osVersion = osVersion;+ this.screenW = screenW;+ this.screenH = screenH;+ this.installationId = installationId;+ }++ private static final DeviceIdentity[] POOL = {+ new DeviceIdentity("samsung", "SM-S928B", "16-SDK36", 1440, 3088, ""),+ new DeviceIdentity("samsung", "SM-A546B", "15-SDK35", 1080, 2340, ""),+ new DeviceIdentity("Google", "Pixel 9 Pro", "16-SDK36", 1280, 2856, ""),+ new DeviceIdentity("Google", "Pixel 8", "15-SDK35", 1080, 2400, ""),+ new DeviceIdentity("OnePlus", "CPH2451", "15-SDK35", 1240, 2772, ""),+ new DeviceIdentity("Xiaomi", "2201117TG", "14-SDK34", 1220, 2712, ""),+ new DeviceIdentity("motorola", "moto g84", "15-SDK35", 1080, 2400, ""),+ new DeviceIdentity("Nothing", "A065", "15-SDK35", 1080, 2412, ""),+ };++ private static final Random RNG = new Random();++ /** Pick a random profile and assign it a fresh installation UUID. */+ static DeviceIdentity random() {+ DeviceIdentity d = POOL[RNG.nextInt(POOL.length)];+ return new DeviceIdentity(d.manufacturer, d.model, d.osVersion,+ d.screenW, d.screenH, UUID.randomUUID().toString());+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/GeoBoxes.java b/app/src/main/java/com/rfsentinel/app/online/wazert/GeoBoxes.javanew file mode 100644index 0000000..67a6e28--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/GeoBoxes.java@@ -0,0 +1,50 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/**+ * Bounding-box geometry for Waze RT area queries (circle to box, shrink, and the+ * shrinking-box series).+ *+ * <p>A single MapDisplayed query over the full HR radius is thinned server-side by+ * viewport size, so minor/near-driver alerts (e.g. a car stopped on the shoulder)+ * get dropped. Querying a series of progressively smaller boxes around the driver+ * defeats that: the smaller the viewport the less the server thins it, so the inner+ * detail comes through. Each box is shrunk to 0.75 before querying, as the Waze+ * client does for its primary viewport.+ *+ * <p>Boxes are {@code [lonMin, latMin, lonMax, latMax]}.+ */+final class GeoBoxes {+ private GeoBoxes() {}++ /** A lon/lat box of half-width radiusM around the point. */+ static double[] circleToBox(double lon, double lat, double radiusM) {+ double dLat = radiusM / WazeConstants.M_PER_DEG_LAT;+ double dLon = radiusM / WazeConstants.mPerDegLon(lat);+ return new double[]{lon - dLon, lat - dLat, lon + dLon, lat + dLat};+ }++ /** Same center, half-extent scaled by {@code factor}. */+ static double[] shrink(double[] box, double factor) {+ double cx = (box[0] + box[2]) / 2.0;+ double cy = (box[1] + box[3]) / 2.0;+ double hx = ((box[2] - box[0]) / 2.0) * factor;+ double hy = ((box[3] - box[1]) / 2.0) * factor;+ return new double[]{cx - hx, cy - hy, cx + hx, cy + hy};+ }++ /**+ * The shrinking-box series: the full-radius box, then each+ * successive box halved, for {@code steps} zoom levels in all.+ */+ static double[][] shrinkingBoxes(double lon, double lat, double radiusM, int steps) {+ double[][] out = new double[steps][];+ out[0] = circleToBox(lon, lat, radiusM);+ for (int i = 1; i < steps; i++) {+ out[i] = shrink(out[i - 1], 0.5);+ }+ return out;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/LICENSE b/app/src/main/java/com/rfsentinel/app/online/wazert/LICENSEnew file mode 100644index 0000000..1fad15d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 highway-radar-sabre-plus contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlert.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlert.javanew file mode 100644index 0000000..2f19d9d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlert.java@@ -0,0 +1,38 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/**+ * A Waze alert decoded from a RealtimeAlert protobuf message (fetch-relevant+ * fields only).+ */+public final class WazeAlert {+ public final String uuid;+ public final long id;+ public final String type;+ public final String subtype;+ public final double lon;+ public final double lat;+ public final int magvar;+ public final long pubMillis;+ public final Integer nThumbsUp;+ public final String street;+ public final String city;++ public WazeAlert(String uuid, long id, String type, String subtype,+ double lon, double lat, int magvar, long pubMillis,+ Integer nThumbsUp, String street, String city) {+ this.uuid = uuid;+ this.id = id;+ this.type = type;+ this.subtype = subtype;+ this.lon = lon;+ this.lat = lat;+ this.magvar = magvar;+ this.pubMillis = pubMillis;+ this.nThumbsUp = nThumbsUp;+ this.street = street;+ this.city = city;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlertCache.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlertCache.javanew file mode 100644index 0000000..1ded7b8--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeAlertCache.java@@ -0,0 +1,87 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++import java.util.ArrayList;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * Persistent uuid-keyed alert cache with soft-delete, matching the caching+ * behavior of the original wzsabre plugin (merge, soft-delete, expiry, filter).+ *+ * <p>WHY this exists: the Waze RT {@code /command} endpoint is session-stateful.+ * It returns each alert as an {@code AddAlertAction} only ONCE per session, then a+ * {@code "RmAlert,<uuid>"} removal line when the alert clears. The previous source+ * replaced its cache with every response, so after the first query the cache went+ * near-empty and alerts vanished from Highway Radar mid-drive. This class instead+ * accumulates adds and soft-deletes removals (kept {@link #SOFT_DELETE_MS} before+ * purge), so the merged view stays complete.+ */+final class WazeAlertCache {+ /** wzsabre uses PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS (5 minutes). */+ static final long SOFT_DELETE_MS = 5 * 60_000L;++ private final Map<String, WazeAlert> alertCache = new LinkedHashMap<>();+ private final Map<String, Long> softDeleted = new LinkedHashMap<>();++ /** Apply one query's deltas: upsert adds, soft-delete removals still cached. */+ synchronized void submit(AlertQueryResult result) {+ for (WazeAlert a : result.newAlerts) {+ if (a.uuid != null && a.uuid.length() != 0) {+ alertCache.put(a.uuid, a);+ softDeleted.remove(a.uuid);+ }+ }+ long now = System.currentTimeMillis();+ for (String id : result.removedIds) {+ if (alertCache.containsKey(id) && !softDeleted.containsKey(id)) {+ softDeleted.put(id, now);+ }+ }+ }++ private void purgeExpiredSoftDeletes() {+ long now = System.currentTimeMillis();+ List<String> expired = new ArrayList<>();+ for (Map.Entry<String, Long> e : softDeleted.entrySet()) {+ if (now - e.getValue() >= SOFT_DELETE_MS) expired.add(e.getKey());+ }+ for (String id : expired) {+ alertCache.remove(id);+ softDeleted.remove(id);+ }+ }++ private boolean isSoftDeleteExpired(String uuid) {+ Long t = softDeleted.get(uuid);+ return t != null && System.currentTimeMillis() - t >= SOFT_DELETE_MS;+ }++ /**+ * Live view of the cache: purge expired soft-deletes, then return every cached+ * alert that is not currently soft-deleted.+ */+ synchronized List<WazeAlert> snapshot() {+ purgeExpiredSoftDeletes();+ List<WazeAlert> out = new ArrayList<>();+ for (WazeAlert a : alertCache.values()) {+ if (!(softDeleted.containsKey(a.uuid) && !isSoftDeleteExpired(a.uuid))) {+ out.add(a);+ }+ }+ return out;+ }++ synchronized void clear() {+ alertCache.clear();+ softDeleted.clear();+ }++ synchronized int size() {+ return alertCache.size();+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeConstants.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeConstants.javanew file mode 100644index 0000000..895744b--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeConstants.java@@ -0,0 +1,46 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/**+ * Constants and host resolution for the Waze mobile-app "RT" protocol.+ */+final class WazeConstants {+ static final int PROTOCOL_VERSION = 234;+ static final String APP_VERSION = "5.17.1.0";++ static final String PATH_LOGIN = "/rtserver/distrib/login";+ static final String PATH_STATIC = "/rtserver/distrib/static";+ static final String PATH_COMMAND = "/rtserver/distrib/command";++ static final String WAIT_TIMEOUT_LOGIN = "8500";+ static final String WAIT_TIMEOUT_COMMAND = "10500";++ static final long SESSION_IDLE_TIMEOUT_MS = 100_000L;+ static final long KEEPALIVE_INTERVAL_MS = 60_000L;+ static final int MAX_CONSECUTIVE_REJECTIONS = 10;+ static final int MAX_ACCOUNTS_PER_DAY = 10;+ static final int NUM_QUERY_SLOTS = 5;+ static final int TILE_NUM_ROWS = 18000;+ static final double M_PER_DEG_LAT = 110574.0;++ private WazeConstants() {}++ static double mPerDegLon(double lat) {+ return Math.cos(Math.toRadians(lat)) * 111320.0;+ }++ /** RT server host for a region ("na" covers all of California). */+ static String rtHost(String region) {+ if ("na".equals(region)) return "rt-xlb-am.waze.com";+ if ("il".equals(region)) return "rt-xlb-il.waze.com";+ return "rt-xlb-row.waze.com";+ }++ static String tileHost(String region) {+ if ("na".equals(region)) return "ctilesgcs-am.waze.com";+ if ("il".equals(region)) return "ctilesgcs-il.waze.com";+ return "ctilesgcs-row.waze.com";+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeCredentials.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeCredentials.javanew file mode 100644index 0000000..30f432d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeCredentials.java@@ -0,0 +1,18 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/**+ * Anonymous Waze account credentials, minted by the /rtserver/distrib/static+ * register endpoint. {@code community} is the username, {@code secret} the password.+ */+final class WazeCredentials {+ final String community;+ final String secret;++ WazeCredentials(String community, String secret) {+ this.community = community;+ this.secret = secret;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeExceptions.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeExceptions.javanew file mode 100644index 0000000..2eac73b--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeExceptions.java@@ -0,0 +1,24 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/** Waze RT-protocol error conditions. */+final class WazeExceptions {+ private WazeExceptions() {}++ /** The server rejected the account/session (HTTP 4xx, e.g. 403). The slot should be replaced. */+ static final class AccountRejectedException extends Exception {+ AccountRejectedException(String message) { super(message); }+ }++ /** The session is no longer valid ("relogin", "unknown userid", "secretkey missing"). Re-login. */+ static final class SessionExpiredException extends Exception {+ SessionExpiredException(String message) { super(message); }+ }++ /** A generic protocol/operation failure (HTTP 5xx, register failure, etc.). */+ static final class WazeOperationException extends Exception {+ WazeOperationException(String message) { super(message); }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeHttpClient.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeHttpClient.javanew file mode 100644index 0000000..7fb3a1d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeHttpClient.java@@ -0,0 +1,124 @@+package com.rfsentinel.app.online.wazert;++// Replaces the upstream OkHttp-based client of the same name from+// highway-radar-sabre-plus (MIT). Same contract on HttpURLConnection, so the+// app takes no OkHttp dependency. See LICENSE in this directory.++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.net.HttpURLConnection;+import java.net.URL;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * RF Sentinel replacement for the SABRE Plus OkHttp-based {@code WazeHttpClient}.+ * Same contract — binary/octet-stream POSTs, per-session cookies (login sets+ * {@code Waze-Session-Affinity}, every later command must carry it), three+ * attempts on transport failure — on {@link HttpURLConnection}, so the app takes+ * no OkHttp dependency. Only POST is kept; the tile-server GET is not part of the+ * alert fetch path.+ */+class WazeHttpClient {+ private static final int CONNECT_TIMEOUT_MS = 15_000;+ /** Must exceed the /command long-poll (x-waze-wait-timeout: 10500 ms). */+ private static final int READ_TIMEOUT_MS = 20_000;++ /** Session cookies by name. */+ private final Map<String, String> cookies = new LinkedHashMap<>();++ /** Drop all cookies (login clears them before re-authenticating). */+ void clearCookies() { synchronized (cookies) { cookies.clear(); } }++ static final class HttpResult {+ final int code;+ final byte[] body;+ HttpResult(int code, byte[] body) { this.code = code; this.body = body; }+ }++ HttpResult post(String url, byte[] body, Map<String, String> headers) throws IOException {+ IOException last = null;+ for (int attempt = 1; attempt <= 3; attempt++) {+ try {+ return postOnce(url, body, headers);+ } catch (IOException e) {+ last = e;+ if (attempt == 3) break; // no point sleeping after the final attempt+ try { Thread.sleep(400L * attempt); } catch (InterruptedException ie) {+ Thread.currentThread().interrupt();+ throw e;+ }+ }+ }+ throw last;+ }++ private HttpResult postOnce(String url, byte[] body, Map<String, String> headers) throws IOException {+ HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();+ try {+ c.setConnectTimeout(CONNECT_TIMEOUT_MS);+ c.setReadTimeout(READ_TIMEOUT_MS);+ c.setRequestMethod("POST");+ c.setDoOutput(true);+ c.setUseCaches(false);+ c.setFixedLengthStreamingMode(body.length);+ c.setRequestProperty("Content-Type", "binary/octet-stream");+ if (headers != null) {+ for (Map.Entry<String, String> e : headers.entrySet()) {+ if (e.getValue() != null) c.setRequestProperty(e.getKey(), e.getValue());+ }+ }+ String cookieHeader = cookieHeader();+ if (cookieHeader != null) c.setRequestProperty("Cookie", cookieHeader);+ try (OutputStream out = c.getOutputStream()) { out.write(body); }+ int code = c.getResponseCode();+ rememberCookies(c.getHeaderFields());+ InputStream in = code >= 400 ? c.getErrorStream() : c.getInputStream();+ byte[] bytes = in == null ? new byte[0] : readAll(in);+ return new HttpResult(code, bytes);+ } finally {+ c.disconnect();+ }+ }++ private String cookieHeader() {+ synchronized (cookies) {+ if (cookies.isEmpty()) return null;+ StringBuilder sb = new StringBuilder();+ for (Map.Entry<String, String> e : cookies.entrySet()) {+ if (sb.length() > 0) sb.append("; ");+ sb.append(e.getKey()).append('=').append(e.getValue());+ }+ return sb.toString();+ }+ }++ /** Keep the name=value pair of every Set-Cookie (attributes are irrelevant: one host, one path). */+ private void rememberCookies(Map<String, List<String>> responseHeaders) {+ if (responseHeaders == null) return;+ for (Map.Entry<String, List<String>> h : responseHeaders.entrySet()) {+ if (h.getKey() == null || !h.getKey().equalsIgnoreCase("Set-Cookie") || h.getValue() == null) continue;+ for (String raw : h.getValue()) {+ if (raw == null) continue;+ int semi = raw.indexOf(';');+ String pair = (semi >= 0 ? raw.substring(0, semi) : raw).trim();+ int eq = pair.indexOf('=');+ if (eq <= 0) continue;+ synchronized (cookies) { cookies.put(pair.substring(0, eq).trim(), pair.substring(eq + 1).trim()); }+ }+ }+ }++ private static byte[] readAll(InputStream in) throws IOException {+ try (InputStream s = in) {+ ByteArrayOutputStream bos = new ByteArrayOutputStream(8192);+ byte[] buf = new byte[8192];+ int n;+ while ((n = s.read(buf)) != -1) bos.write(buf, 0, n);+ return bos.toByteArray();+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtCodec.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtCodec.javanew file mode 100644index 0000000..93b71f2--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtCodec.java@@ -0,0 +1,238 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++import android.util.Base64;++import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.UUID;++/**+ * Encodes/decodes the Waze "RT" protocol wire format on top of the generated+ * {@link WazeProto} protobuf classes. (Named *Codec to avoid clashing with the+ * generated WazeProto outer class.)+ *+ * Body framing: each protobuf "line" is {@code "ProtoBase64," + base64(Batch{element})}+ * with NO_WRAP base64; multiple lines are joined with '\n'. Raw command lines+ * (SeeMe / Location / MapDisplayed) are sent as plain text, not protobuf-wrapped.+ */+final class WazeRtCodec {+ private WazeRtCodec() {}++ private static String protoBase64Line(WazeProto.Element element) {+ WazeProto.Batch batch = WazeProto.Batch.newBuilder().addElement(element).build();+ return "ProtoBase64," + Base64.encodeToString(batch.toByteArray(), Base64.NO_WRAP);+ }++ // Upstream's reportPayload() is deliberately absent: RF Sentinel is read-only.++ // ── Request line builders ────────────────────────────────────────────────++ static String buildClientInfoLine(DeviceIdentity device, double lon, double lat) {+ // Position is jittered by up to +/-500m before encoding (matches official).+ double lonOffset = ((Math.random() - 0.5) * 1000.0) / (Math.cos(Math.toRadians(lat)) * 111320.0);+ double latOffset = ((Math.random() - 0.5) * 1000.0) / 110574.0;++ WazeProto.Coordinate pos = WazeProto.Coordinate.newBuilder()+ .setLonTimes1000000((int) Math.round((lon + lonOffset) * 1_000_000.0))+ .setLatTimes1000000((int) Math.round((lat + latOffset) * 1_000_000.0))+ .build();++ WazeProto.Display display = WazeProto.Display.newBuilder()+ .setType(WazeProto.Display.Type.BUILT_IN)+ .setWidth(device.screenW)+ .setHeight(device.screenH)+ .build();++ WazeProto.ClientInfo ci = WazeProto.ClientInfo.newBuilder()+ .setProtocol(WazeConstants.PROTOCOL_VERSION)+ .setClientVersion(WazeConstants.APP_VERSION)+ .setLastPosition(pos)+ .setManufacturer(device.manufacturer)+ .setModel(device.model)+ .setOsVersion(device.osVersion)+ .setLocale("en")+ .setInstallationId(device.installationId)+ .setDeviceType(WazeProto.DeviceType.ANDROID_DEVICE)+ .setAppType(WazeProto.AppType.WAZE)+ .addDisplay(display)+ .setOsLanguageId("en")+ .setSessionUuid(UUID.randomUUID().toString())+ .setCurrentTimeMillis(System.currentTimeMillis())+ .setAppFlavor(WazeProto.AppFlavor.ALPHA)+ .build();++ return protoBase64Line(WazeProto.Element.newBuilder().setClientInfo(ci).build());+ }++ static String buildRegisterLine() {+ return protoBase64Line(WazeProto.Element.newBuilder()+ .setRegister(WazeProto.Register.getDefaultInstance()).build());+ }++ static String buildLoginLine(String community, String secret) {+ WazeProto.PasswordCredential cred = WazeProto.PasswordCredential.newBuilder()+ .setUsername(community)+ .setPassword(secret)+ .build();+ WazeProto.LoginRequest lr = WazeProto.LoginRequest.newBuilder()+ .setPasswordCredential(cred)+ .setReason(WazeProto.LoginRequest.LoginReason.NORMAL)+ .build();+ return protoBase64Line(WazeProto.Element.newBuilder().setLoginRequest(lr).build());+ }++ static String buildAdsLine() {+ return protoBase64Line(WazeProto.Element.newBuilder()+ .setReportAdsSetting(WazeProto.ReportAdsSettings.getDefaultInstance()).build());+ }++ /** uid request header = base64(UID{id=serverSessionId, secretKey=secretKey}). */+ static String buildUidHeader(WazeSessionInfo session) {+ WazeProto.UID uid = WazeProto.UID.newBuilder()+ .setId(session.serverSessionId)+ .setSecretKey(session.secretKey)+ .build();+ return Base64.encodeToString(uid.toByteArray(), Base64.NO_WRAP);+ }++ // ── Raw command-line builders (sent as-is as the /command body) ──────────++ private static String f6(double v) { return String.format(Locale.US, "%.6f", v); }++ /** bbox = [lonMin, latMin, lonMax, latMax]. */+ static String mapDisplayedCommand(double lonMin, double latMin, double lonMax, double latMax) {+ double midLon = (lonMin + lonMax) / 2.0;+ double midLat = (latMin + latMax) / 2.0;+ return "MapDisplayed,"+ + f6(lonMin) + "," + f6(latMax) + "," + f6(lonMax) + "," + f6(latMax) + ","+ + f6(lonMax) + "," + f6(latMin) + "," + f6(lonMin) + "," + f6(latMin) + ","+ + f6(midLon) + "," + f6(midLat) + ",67186,"+ + f6(lonMin) + "," + f6(latMax) + "," + f6(lonMax) + "," + f6(latMax) + ","+ + f6(lonMax) + "," + f6(latMin) + "," + f6(lonMin) + "," + f6(latMin);+ }++ /** Default SeeMe level (matches the handshake's original no-arg behavior). */+ static String seeMeCommand() { return seeMeCommand(1); }++ /** mode 1 = handshake SeeMe; mode 2 = the post-report SeeMe used to close+ * out the simulateDriving sequence. Wire form: "SeeMe," + level + ",2,T,T,T,1,-1,1,7". */+ static String seeMeCommand(int mode) {+ return "SeeMe," + mode + ",2,T,T,T,1,-1,1,7";+ }++ static String setMoodCommand(){ return "SetMood,1"; }+ static String locationCommand(double lon, double lat) {+ return "Location," + lon + "," + lat;+ }++ /**+ * "At" position update carrying the road-snap result: fromNode/toNode are the+ * tile-local directional node indices from a {@code SegmentMatch}, or -1/-1 when+ * no segment matched. lon/lat formatted identically to {@link #locationCommand}+ * (plain concatenation, not fixed-decimal), as the Waze client formats it.+ */+ static String atCommand(double lon, double lat, int heading, long fromNode, long toNode) {+ return "At," + lon + "," + lat + ",0," + heading + ",1," + fromNode + "," + toNode + ",T,0,-1,-1,0";+ }++ /** Handshake = SeeMe + SetMood + Location + MapDisplayed, newline-joined, one POST. */+ static String handshakePayload(double lon, double lat) {+ double[] b = circleToBox(lon, lat);+ return seeMeCommand() + "\n" + setMoodCommand() + "\n" + locationCommand(lon, lat)+ + "\n" + mapDisplayedCommand(b[0], b[1], b[2], b[3]);+ }++ /** Default ~0.018deg lon x 0.015deg lat box around a point (matches official). */+ static double[] circleToBox(double lon, double lat) {+ return new double[]{ lon - 0.018, lat - 0.015, lon + 0.018, lat + 0.015 };+ }++ // ── Response parsing ─────────────────────────────────────────────────────++ /**+ * Extracts removed-alert uuids from a batch. The RT server signals a cleared+ * alert with an {@code old_command} line of the form {@code "RmAlert,<uuid>"}+ * (NOT a RemoveAlertAction message; verified on the live feed). Strip the prefix+ * and trim to get the uuid.+ */+ static List<String> parseRemovedAlertIds(WazeProto.Batch batch) {+ List<String> out = new ArrayList<>();+ for (WazeProto.Element el : batch.getElementList()) {+ String oc = el.getOldCommand();+ if (oc == null) continue;+ oc = oc.trim();+ if (oc.startsWith("RmAlert,")) {+ out.add(oc.substring("RmAlert,".length()).trim());+ }+ }+ return out;+ }++ static List<WazeAlert> parseAlerts(WazeProto.Batch batch) {+ List<WazeAlert> out = new ArrayList<>();+ for (WazeProto.Element el : batch.getElementList()) {+ if (!el.hasAddAlertAction()) continue;+ WazeProto.AddAlertAction aaa = el.getAddAlertAction();+ if (!aaa.hasRealtimeAlert()) continue;+ WazeProto.RealtimeAlert ra = aaa.getRealtimeAlert();+ if (!ra.hasAlertInfo()) continue;+ WazeProto.AlertInfo info = ra.getAlertInfo();+ if (!info.hasPosition()) continue;+ WazeProto.Coordinate c = info.getPosition();++ // Longitude is an unsigned-32-bit micro-degree value; map to signed range.+ long lonRaw = ((long) c.getLonTimes1000000()) & 0xFFFFFFFFL;+ if (lonRaw >= 0x80000000L) lonRaw -= 0x100000000L;+ double lon = lonRaw / 1_000_000.0;+ double lat = c.getLatTimes1000000() / 1_000_000.0;++ String type = typeName(info.getType());+ String subtype = subTypeName(info.getSubType());+ int magvar = info.getAzymuth();++ long reportTime = 0L;+ Integer thumbs = null;+ String street = null, city = null;+ if (ra.hasAlertReportingInfo()) {+ WazeProto.AlertReportingInfo ri = ra.getAlertReportingInfo();+ reportTime = ri.getReportTime();+ if (ri.getThumbsUpCount() > 0) thumbs = ri.getThumbsUpCount();+ String s = ri.getAlertAddress().getStreet();+ String ci2 = ri.getAlertAddress().getCity();+ if (s != null && !s.isEmpty()) street = s;+ if (ci2 != null && !ci2.isEmpty()) city = ci2;+ }+ long pubMillis = reportTime > 0 ? reportTime * 1000L : System.currentTimeMillis();++ out.add(new WazeAlert(ra.getAlertUuid(), ra.getId(), type, subtype,+ lon, lat, magvar, pubMillis, thumbs, street, city));+ }+ return out;+ }++ /**+ * Type-enum → wire name, as the SABRE consumer expects it: the generated enum+ * constant name, except the unnamed types (UNKNOWN_TYPE and+ * the reserved __NOT_IN_USE__ values) collapse to "UNKNOWN".+ */+ private static String typeName(WazeProto.AlertType t) {+ String n = t.name();+ if (n.equals("UNKNOWN_TYPE") || n.startsWith("__NOT_IN_USE")) return "UNKNOWN";+ return n;+ }++ /**+ * Subtype-enum → wire name, as the SABRE consumer expects it:+ * the enum constant name, except NO_SUBTYPE and the reserved __NOT_IN_USE__+ * values map to "" so the caller falls back to the type name.+ */+ private static String subTypeName(WazeProto.AlertSubType s) {+ String n = s.name();+ if (n.equals("NO_SUBTYPE") || n.startsWith("__NOT_IN_USE")) return "";+ return n;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.javanew file mode 100644index 0000000..7c740c8--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java@@ -0,0 +1,415 @@+package com.rfsentinel.app.online.wazert;++import android.content.Context;+import android.content.SharedPreferences;+import android.os.SystemClock;+import android.util.Log;++import org.json.JSONObject;+import com.rfsentinel.app.util.SecureStore;++import java.util.ArrayList;+import java.util.List;++/**+ * RF Sentinel's driver for the vendored Waze RT protocol layer: owns the anonymous+ * account, the session lifecycle, the alert cache and the rate limits, and hands+ * back just the POLICE alerts near a point.+ *+ * <p>This class is RF Sentinel's own (the classes it drives are vendored from+ * highway-radar-sabre-plus — see LICENSE in this directory). It is a slimmed+ * equivalent of that project's WazeProtocolSource: no Highway Radar plumbing, no+ * reporting, no tile decoding, no keepalive thread.+ *+ * <p><b>What talking to Waze costs the user.</b> The RT protocol is the one the+ * Waze app itself speaks. Using it means registering an anonymous account with+ * Waze (username/password minted by Waze, stored encrypted on-device) and sending+ * a position with each query. That position is first rounded to a 1 km grid+ * ({@link #snapToGrid}), so Waze only ever learns which ~1 km cell the phone is in+ * (never closer than about 500 m), and every command (login, handshake, query+ * boxes) uses the rounded point, not the real one. That is a real disclosure, so the backend is opt-in and+ * the Settings screen says so plainly before the user turns it on.+ *+ * <p><b>Rate limits.</b> Waze caps anonymous registrations per device per day, so+ * a minted account is persisted and reused, registrations are counted against+ * {@link WazeConstants#MAX_ACCOUNTS_PER_DAY} in a rolling 24 h window, and a+ * rejected account backs off exponentially (30 s → 10 min) instead of spinning the+ * register→login loop. A generic failure (5xx, network flap) backs off 15 s.+ *+ * <p>Every public method is synchronized: a poll can overlap a Settings action+ * ("forget account") and both touch the session and the cache.+ */+public final class WazeRtFetcher {++ private static final String TAG = "WazeRtFetcher";+ private static final String PREFS = "rfsentinel_wazert";+ private static final String KEY_ACCOUNT = "wazert_account"; // SecureStore (encrypted)+ private static final String KEY_REG_COUNT = "reg_count"; // plain prefs (not secret)+ private static final String KEY_REG_WINDOW = "reg_window_start";++ /** Never sweep a box tighter than this: the user is moving, and a 2 km box+ * would leave nothing ahead of them by the next poll. Matches upstream. */+ private static final double MIN_QUERY_RADIUS_M = 8000.0;+ /** Progressively smaller boxes defeat the server's viewport-size thinning. */+ private static final int SHRINK_STEPS = 5;+ /** Waze is only told which grid cell of this size you are in. A grid, not random jitter: a phone+ * that stays put sends the same value every time, so many polls cannot be averaged back to it. */+ private static final double GRID_M = 1000.0;+ /** A cell centre is at most this far (diagonally) from the true position, so every query is widened by it. */+ private static final double SNAP_MARGIN_M = 750.0;+ /** The smallest query box is never narrower than this (before the 0.75 shrink): it must still hold the true position. */+ private static final double MIN_INNER_BOX_M = 1000.0;+ private static final long QUERY_BUDGET_MS = 10_000L;+ /** A brand-new account's first command often draws an in-band 504 "Retry";+ * it succeeds on the next attempt, so absorb it rather than lose a poll. */+ private static final int HANDSHAKE_ATTEMPTS = 3;++ private static final long BACKOFF_BASE_MS = 30_000L;+ private static final long BACKOFF_MAX_MS = 10 * 60_000L;+ private static final long GENERIC_FAIL_BACKOFF_MS = 15_000L;+ private static final long DAY_MS = 24 * 3600_000L;++ /** One Waze police report, reduced to what RF Sentinel scores. */+ public static final class PoliceAlert {+ public final String uuid;+ public final String subtype; // e.g. POLICE_WITH_MOBILE_CAMERA; "" when unspecified+ public final double lat;+ public final double lon;+ public final long pubMillis;+ public final int thumbsUp; // crowd corroboration; 0 when absent+ public final String type; // Waze alert type name, e.g. POLICE, ACCIDENT, HAZARD+ public final String street; // null when Waze gave none+ public final String city; // null when Waze gave none++ public PoliceAlert(String uuid, String subtype, double lat, double lon, long pubMillis, int thumbsUp, String type) {+ this(uuid, subtype, lat, lon, pubMillis, thumbsUp, type, null, null);+ }++ public PoliceAlert(String uuid, String subtype, double lat, double lon, long pubMillis, int thumbsUp, String type,+ String street, String city) {+ this.uuid = uuid;+ this.subtype = subtype;+ this.lat = lat;+ this.lon = lon;+ this.pubMillis = pubMillis;+ this.thumbsUp = thumbsUp;+ this.type = type;+ this.street = street;+ this.city = city;+ }+ }++ /** Bumped by {@link #forgetStoredAccount}: every running fetcher drops its session when it sees a new value. */+ private static final java.util.concurrent.atomic.AtomicInteger ACCOUNT_EPOCH = new java.util.concurrent.atomic.AtomicInteger();++ private final Context ctx;+ private final String region;+ private int seenEpoch = ACCOUNT_EPOCH.get();+ private final WazeAlertCache cache = new WazeAlertCache();++ private WazeSession session;+ private int consecutiveRejections = 0;+ private long backoffUntilMs = 0L;++ private final WazeHttpClient http;++ public WazeRtFetcher(Context context, String region) {+ this(context, region, new WazeHttpClient());+ }++ /** Test seam: the transport is supplied by the caller (a fake server). */+ WazeRtFetcher(Context context, String region, WazeHttpClient http) {+ this.ctx = context.getApplicationContext();+ this.region = region;+ this.http = http;+ }++ /**+ * Blocking: ensure a session, sweep the area, and return the cached POLICE+ * alerts. Throws on failure (the caller turns that into a status message);+ * the thrown message is safe to show, it never contains credentials.+ */+ public synchronized List<PoliceAlert> fetchAlertsNear(double lat, double lon, double radiusMeters, java.util.Set<String> types)+ throws Exception {+ Diagnostics.lastAttemptAt = System.currentTimeMillis();+ Diagnostics.host = WazeConstants.rtHost(region);+ try {+ List<PoliceAlert> out = fetchLocked(lat, lon, radiusMeters, types);+ Diagnostics.lastOkAt = System.currentTimeMillis();+ Diagnostics.lastError = "";+ Diagnostics.alertsInCache = cache.size();+ return out;+ } catch (Exception e) {+ Diagnostics.lastError = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();+ throw e;+ }+ }++ /** What the status screen shows: the last attempt, and the rounded position that went out with it. */+ public static final class Diagnostics {+ private Diagnostics() {}+ public static volatile long lastAttemptAt;+ public static volatile long lastOkAt;+ public static volatile String lastError = "";+ public static volatile String host = "";+ public static volatile double sentLat = Double.NaN;+ public static volatile double sentLon = Double.NaN;+ public static volatile int alertsInCache;+ }++ /** True once an anonymous account is stored (Settings > Waze status). */+ public static boolean hasStoredAccount(Context context) {+ String blob = SecureStore.INSTANCE.get(context.getApplicationContext(), KEY_ACCOUNT);+ return blob != null && !blob.isEmpty();+ }++ /** Anonymous accounts registered in the last 24 hours, and the most Waze allows per day. */+ public static int accountsMadeToday(Context context) {+ SharedPreferences p = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);+ long start = p.getLong(KEY_REG_WINDOW, 0L);+ if (start == 0L || System.currentTimeMillis() - start >= DAY_MS) return 0;+ return p.getInt(KEY_REG_COUNT, 0);+ }++ public static int dailyAccountLimit() { return WazeConstants.MAX_ACCOUNTS_PER_DAY; }++ private List<PoliceAlert> fetchLocked(double lat, double lon, double radiusMeters, java.util.Set<String> types)+ throws Exception {+ int epoch = ACCOUNT_EPOCH.get();+ if (epoch != seenEpoch) { // the account was forgotten in Settings: start over with a fresh one+ seenEpoch = epoch;+ session = null;+ cache.clear();+ consecutiveRejections = 0;+ backoffUntilMs = 0L;+ }+ long now = SystemClock.elapsedRealtime();+ if (now < backoffUntilMs) {+ throw new WazeExceptions.WazeOperationException(+ "backing off " + ((backoffUntilMs - now) / 1000) + "s after a rejected session");+ }+ try {+ double[] at = snapToGrid(lat, lon);+ Diagnostics.sentLat = at[0];+ Diagnostics.sentLon = at[1];+ queryArea(at[0], at[1], Math.max(radiusMeters + SNAP_MARGIN_M, MIN_QUERY_RADIUS_M));+ consecutiveRejections = 0;+ backoffUntilMs = 0L;+ return filter(cache.snapshot(), types);+ } catch (WazeExceptions.AccountRejectedException e) {+ // Waze disowned this account (they get purged). Drop it so the next+ // attempt mints a fresh one, and back off so a persistent rejection+ // cannot burn the daily registration cap in seconds.+ forgetAccount();+ session = null;+ consecutiveRejections++;+ setBackoff();+ throw e;+ } catch (WazeExceptions.SessionExpiredException e) {+ session = null; // credentials are still good, just re-login next poll+ throw e;+ } catch (Exception e) {+ if (backoffUntilMs <= SystemClock.elapsedRealtime()) {+ backoffUntilMs = SystemClock.elapsedRealtime() + GENERIC_FAIL_BACKOFF_MS;+ }+ throw e;+ }+ }++ /** Forget the session (not the account) so the next fetch logs in again. */+ public synchronized void reset() {+ session = null;+ cache.clear();+ }++ // ── privacy: what position Waze gets ─────────────────────────────────────++ /**+ * Rounds a position to the centre of its ~1 km grid cell: {@code [lat, lon]}. The cell is the+ * same for every point inside it, so Waze cannot tell where in the cell the phone is, and the+ * rounding error is at most about 500 m per axis.+ */+ static double[] snapToGrid(double lat, double lon) {+ double latStep = GRID_M / WazeConstants.M_PER_DEG_LAT;+ double snappedLat = Math.round(lat / latStep) * latStep;+ // Longitude degrees shrink towards the poles; use the cell row's own latitude so the whole row shares one step.+ double lonStep = GRID_M / Math.max(WazeConstants.mPerDegLon(snappedLat), 1000.0);+ double snappedLon = Math.round(lon / lonStep) * lonStep;+ return new double[]{snappedLat, snappedLon};+ }++ /** How many shrinking boxes to query: stop before one gets narrower than {@link #MIN_INNER_BOX_M}. */+ static int boxSteps(double radiusM) {+ int steps = 1;+ while (steps < SHRINK_STEPS && radiusM / (1L << steps) >= MIN_INNER_BOX_M) steps++;+ return steps;+ }++ /** Settings "forget account": wipes the stored account and makes every running fetcher drop its session too. */+ public static void forgetStoredAccount(Context context) {+ SecureStore.INSTANCE.put(context.getApplicationContext(), KEY_ACCOUNT, ""); // empty clears the entry+ ACCOUNT_EPOCH.incrementAndGet();+ }++ // ── session + query ──────────────────────────────────────────────────────++ private void queryArea(double lat, double lon, double radiusMeters) throws Exception {+ if (session == null) session = restoreOrCreateSession();+ boolean wasUnregistered = session.getCredentials() == null;+ if (wasUnregistered && !canRegisterToday()) {+ throw new WazeExceptions.WazeOperationException(+ "Waze's daily anonymous-account limit is reached — try again tomorrow");+ }++ long sessionBefore = session.currentServerSessionId();+ WazeProto.Batch handshake = prepareWithRetry(lat, lon);++ // Credentials exist now: persist immediately so a failure in the box loop+ // below cannot lose a freshly minted account and force a wasteful+ // re-register on the next poll.+ if (wasUnregistered) {+ noteRegistration();+ saveAccount(session.getCredentials(), session.getDevice());+ Log.i(TAG, "Registered a new anonymous Waze account");+ }++ // A new server session re-sends every active alert but sends no removal for+ // alerts that cleared while we were logged out, so a stale cache would show+ // ghosts. Defer the clear until the first box succeeds, so a failure right+ // after a re-login keeps serving the previous cache instead of blanking.+ boolean sessionChanged = session.currentServerSessionId() != sessionBefore;+ boolean cleared = false;++ double[][] boxes = GeoBoxes.shrinkingBoxes(lon, lat, radiusMeters, boxSteps(radiusMeters));+ long deadline = SystemClock.elapsedRealtime() + QUERY_BUDGET_MS;+ for (double[] box : boxes) {+ if (SystemClock.elapsedRealtime() >= deadline) break; // best-effort, like the official client+ WazeProto.Batch batch = session.queryBox(GeoBoxes.shrink(box, 0.75));+ if (sessionChanged && !cleared) {+ cache.clear();+ cleared = true;+ }+ if (handshake != null) {+ // The handshake's own MapDisplayed box is a real viewport query and the+ // server will not send those alerts again this session, so merge it.+ cache.submit(new AlertQueryResult(+ WazeRtCodec.parseAlerts(handshake), WazeRtCodec.parseRemovedAlertIds(handshake)));+ handshake = null;+ }+ cache.submit(new AlertQueryResult(+ WazeRtCodec.parseAlerts(batch), WazeRtCodec.parseRemovedAlertIds(batch)));+ }+ }++ private WazeProto.Batch prepareWithRetry(double lat, double lon) throws Exception {+ WazeExceptions.WazeOperationException last = null;+ for (int attempt = 1; attempt <= HANDSHAKE_ATTEMPTS; attempt++) {+ try {+ return session.prepareForArea(lat, lon);+ } catch (WazeExceptions.WazeOperationException e) {+ last = e;+ Log.w(TAG, "Waze handshake attempt " + attempt + " failed: " + e.getMessage());+ if (attempt == HANDSHAKE_ATTEMPTS) break;+ try {+ Thread.sleep(2000L * attempt);+ } catch (InterruptedException ie) {+ Thread.currentThread().interrupt();+ throw e;+ }+ }+ }+ throw last;+ }++ /** Only the alert types the user chose (police by default); the caller names them by Waze type. */+ private static List<PoliceAlert> filter(List<WazeAlert> all, java.util.Set<String> types) {+ List<PoliceAlert> out = new ArrayList<>();+ for (WazeAlert a : all) {+ if (a.type == null || !types.contains(a.type)) continue;+ if (a.uuid == null || a.uuid.isEmpty()) continue;+ out.add(new PoliceAlert(a.uuid, a.subtype == null ? "" : a.subtype,+ a.lat, a.lon, a.pubMillis, a.nThumbsUp == null ? 0 : a.nThumbsUp, a.type, a.street, a.city));+ }+ return out;+ }++ // ── account persistence ──────────────────────────────────────────────────++ private WazeSession restoreOrCreateSession() {+ String blob = SecureStore.INSTANCE.get(ctx, KEY_ACCOUNT);+ if (blob == null || blob.isEmpty()) return new WazeSession(region, DeviceIdentity.random(), null, http);+ try {+ JSONObject o = new JSONObject(blob);+ WazeCredentials creds = new WazeCredentials(o.getString("community"), o.getString("secret"));+ DeviceIdentity device = new DeviceIdentity(+ o.getString("manufacturer"), o.getString("model"), o.getString("os"),+ o.getInt("w"), o.getInt("h"), o.getString("installation_id"));+ return new WazeSession(region, device, creds, http);+ } catch (Exception e) {+ Log.w(TAG, "Stored Waze account unreadable, registering a new one: " + e.getMessage());+ return new WazeSession(region, DeviceIdentity.random(), null, http);+ }+ }++ private void saveAccount(WazeCredentials c, DeviceIdentity d) {+ if (c == null || d == null) return;+ try {+ JSONObject o = new JSONObject();+ o.put("community", c.community);+ o.put("secret", c.secret);+ o.put("manufacturer", d.manufacturer);+ o.put("model", d.model);+ o.put("os", d.osVersion);+ o.put("w", d.screenW);+ o.put("h", d.screenH);+ o.put("installation_id", d.installationId);+ SecureStore.INSTANCE.put(ctx, KEY_ACCOUNT, o.toString());+ } catch (Exception e) {+ Log.w(TAG, "Could not persist the Waze account: " + e.getMessage());+ }+ }++ /** Wipe the stored anonymous account. Also the Settings "forget" action. */+ public synchronized void forgetAccount() {+ SecureStore.INSTANCE.put(ctx, KEY_ACCOUNT, ""); // empty clears the entry+ cache.clear();+ session = null;+ }++ public synchronized boolean hasAccount() {+ String blob = SecureStore.INSTANCE.get(ctx, KEY_ACCOUNT);+ return blob != null && !blob.isEmpty();+ }++ // ── registration cap + backoff ───────────────────────────────────────────++ private SharedPreferences prefs() {+ return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE);+ }++ private boolean windowRolledOver() {+ long start = prefs().getLong(KEY_REG_WINDOW, 0L);+ return start == 0L || System.currentTimeMillis() - start >= DAY_MS;+ }++ private boolean canRegisterToday() {+ if (windowRolledOver()) return true;+ return prefs().getInt(KEY_REG_COUNT, 0) < WazeConstants.MAX_ACCOUNTS_PER_DAY;+ }++ private void noteRegistration() {+ SharedPreferences p = prefs();+ if (windowRolledOver()) {+ p.edit().putLong(KEY_REG_WINDOW, System.currentTimeMillis()).putInt(KEY_REG_COUNT, 1).apply();+ } else {+ p.edit().putInt(KEY_REG_COUNT, p.getInt(KEY_REG_COUNT, 0) + 1).apply();+ }+ }++ private void setBackoff() {+ int step = Math.min(Math.max(consecutiveRejections, 1), 5);+ long delay = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * (1L << (step - 1)));+ backoffUntilMs = SystemClock.elapsedRealtime() + delay;+ Log.w(TAG, "Waze RT backing off " + (delay / 1000) + "s");+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.javanew file mode 100644index 0000000..1a53258--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java@@ -0,0 +1,284 @@+package com.rfsentinel.app.online.wazert;++// Vendored from highway-radar-sabre-plus (MIT). See LICENSE in this directory.+// Changed for RF Sentinel: package declaration, the user-report submission+// methods are removed — RF Sentinel only reads alerts, it never reports — and+// the debug logs no longer print the anonymous account name or session id.++import android.os.SystemClock;+import android.util.Log;++import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;++/**+ * One Waze "RT" protocol session: mints an anonymous account (register), logs in,+ * and runs alert queries. Single-slot, synchronous (runs on the caller's worker+ * thread). Follows the Waze client's own session sequence for the fetch path+ * (no keepalive or session pooling).+ *+ * No backend or pre-shared credentials are needed: register() asks Waze itself for+ * a fresh username/password. Credentials + device can be injected (persisted across+ * runs) so we don't re-register on every fetch, Waze caps anonymous accounts per day.+ */+final class WazeSession {+ private static final String TAG = "WazeRT";++ private final String region;+ private final DeviceIdentity device;+ private final WazeHttpClient http;++ private WazeCredentials credentials; // from register() or injected+ private WazeSessionInfo session; // from login()+ private int seqCount = 1;+ private long lastRequestMs = 0L;+ /** Server session the handshake last ran on (0 = none), so it runs once per login. */+ private long handshakedSessionId = 0L;++ WazeSession(String region) {+ this(region, DeviceIdentity.random(), null);+ }++ WazeSession(String region, DeviceIdentity device, WazeCredentials credentials) {+ this(region, device, credentials, new WazeHttpClient());+ }++ /** Test seam: same as above with the transport supplied by the caller. */+ WazeSession(String region, DeviceIdentity device, WazeCredentials credentials, WazeHttpClient http) {+ this.region = region;+ this.device = device;+ this.credentials = credentials;+ this.http = http;+ }++ WazeCredentials getCredentials() { return credentials; }+ DeviceIdentity getDevice() { return device; }++ /** Server session id (0 if not logged in), lets the caller detect a re-login. */+ long currentServerSessionId() { return session != null ? session.serverSessionId : 0L; }++ /** Drop the logged-in session but KEEP credentials, so the next call re-logs in+ * (with the in-memory account) instead of registering a brand-new one. */+ void invalidateSession() { session = null; }++ /**+ * Inspect a parsed response batch for in-band errors the server returns with an+ * HTTP 200: a {@code ServerError} element, or a {@code LoginError}. Without this,+ * a server that invalidates the session but replies 200 looks like success and+ * the session zombies: {@code lastRequestMs} keeps updating so it never idles+ * out, and no alerts are ever merged again.+ */+ static void checkErrors(WazeProto.Batch batch)+ throws WazeExceptions.AccountRejectedException,+ WazeExceptions.SessionExpiredException,+ WazeExceptions.WazeOperationException {+ for (WazeProto.Element el : batch.getElementList()) {+ if (el.hasError()) {+ WazeProto.ServerError err = el.getError();+ int code = err.getCode();+ String desc = err.getDescription().toLowerCase(Locale.US);+ if (desc.contains("relogin") || desc.contains("unknown userid")+ || desc.contains("secretkey missing") || desc.contains("secret key missing"))+ throw new WazeExceptions.SessionExpiredException(+ "server error: " + err.getDescription());+ if (code >= 400 && code < 500)+ throw new WazeExceptions.AccountRejectedException(+ "server error " + code + ": " + err.getDescription());+ if (code >= 500)+ throw new WazeExceptions.WazeOperationException(+ "server error " + code + ": " + err.getDescription());+ // Informational / unknown (incl. the proto default code 0), the+ // official ignores these; a normal 200 batch can legitimately carry+ // one, so do NOT fail the whole refresh over it.+ Log.w(TAG, "Ignoring non-fatal server error " + code + ": " + err.getDescription());+ }+ if (el.hasLoginError()) throwForLoginError(el.getLoginError().getErrorType());+ }+ }++ /**+ * Map a Waze auth-error type to an exception. Transient server-side problems+ * (INTERNAL_ISSUES / UNKNOWN) are operational, they must NOT nuke a good account+ * by triggering a re-register; only genuine credential/authorization failures do.+ */+ private static void throwForLoginError(WazeProto.LoginError.AuthErrorType t)+ throws WazeExceptions.AccountRejectedException, WazeExceptions.WazeOperationException {+ if (t == WazeProto.LoginError.AuthErrorType.INTERNAL_ISSUES+ || t == WazeProto.LoginError.AuthErrorType.UNKNOWN_ERROR)+ throw new WazeExceptions.WazeOperationException("login error: " + t);+ throw new WazeExceptions.AccountRejectedException("login error: " + t);+ }++ private String url(String path) { return "https://" + WazeConstants.rtHost(region) + path; }+ private String nextSeq() { return String.valueOf(seqCount++); }++ private boolean sessionValid() {+ return session != null+ && (SystemClock.elapsedRealtime() - lastRequestMs) < WazeConstants.SESSION_IDLE_TIMEOUT_MS;+ }++ // ── register ─────────────────────────────────────────────────────────────++ void register(double lon, double lat) throws Exception {+ String body = WazeRtCodec.buildClientInfoLine(device, lon, lat)+ + "\n" + WazeRtCodec.buildRegisterLine();++ Map<String, String> headers = new LinkedHashMap<>();+ headers.put("User-Agent", WazeConstants.APP_VERSION); // bare "5.17.1.0"+ headers.put("x-waze-network-version", "3");+ headers.put("sequence-number", nextSeq());++ WazeHttpClient.HttpResult r = http.post(url(WazeConstants.PATH_STATIC),+ body.getBytes(StandardCharsets.UTF_8), headers);+ if (r.code >= 400) throw new WazeExceptions.WazeOperationException("register HTTP " + r.code);+ if (r.body.length == 0) throw new WazeExceptions.WazeOperationException("empty register response");++ WazeProto.Batch batch = WazeProto.Batch.parseFrom(r.body);+ checkErrors(batch);+ for (WazeProto.Element el : batch.getElementList()) {+ if (el.hasRegisterSuccessful()) {+ WazeProto.RegisterSuccessful rs = el.getRegisterSuccessful();+ String user = rs.getUsername(), pass = rs.getPassword();+ if (user == null || user.isEmpty()) throw new WazeExceptions.WazeOperationException("empty community from register");+ if (pass == null || pass.isEmpty()) throw new WazeExceptions.WazeOperationException("empty secret from register");+ credentials = new WazeCredentials(user, pass);+ Log.d(TAG, "Registered an anonymous account");+ return;+ }+ }+ throw new WazeExceptions.WazeOperationException("register: no RegisterSuccessful element (" + r.body.length + "B)");+ }++ // ── login ────────────────────────────────────────────────────────────────++ void login(double lon, double lat) throws Exception {+ if (credentials == null) throw new WazeExceptions.WazeOperationException("login before register");+ http.clearCookies();++ String body = WazeRtCodec.buildClientInfoLine(device, lon, lat)+ + "\n" + WazeRtCodec.buildLoginLine(credentials.community, credentials.secret)+ + "\n" + WazeRtCodec.buildAdsLine();++ Map<String, String> headers = new LinkedHashMap<>();+ headers.put("User-Agent", "waze/" + WazeConstants.APP_VERSION); // login uses the "waze/" prefix+ headers.put("cache-control", "no-cache");+ headers.put("sequence-number", nextSeq());+ headers.put("x-waze-network-version", "3");+ headers.put("x-waze-wait-timeout", WazeConstants.WAIT_TIMEOUT_LOGIN);++ WazeHttpClient.HttpResult r = http.post(url(WazeConstants.PATH_LOGIN),+ body.getBytes(StandardCharsets.UTF_8), headers);+ // A 4xx here means Waze no longer accepts these credentials (anonymous+ // accounts get purged): classify as AccountRejected so the caller clears+ // the persisted account and re-registers instead of failing forever.+ if (r.code >= 400 && r.code < 500)+ throw new WazeExceptions.AccountRejectedException("login HTTP " + r.code);+ if (r.code >= 500) throw new WazeExceptions.WazeOperationException("login HTTP " + r.code);+ if (r.body.length == 0) throw new WazeExceptions.WazeOperationException("empty login response");++ WazeProto.Batch batch = WazeProto.Batch.parseFrom(r.body);+ checkErrors(batch); // in-band LoginError → specific exception, not blanket reject+ for (WazeProto.Element el : batch.getElementList()) {+ // A login failure can arrive nested in the LoginResponse oneof (not just+ // as a top-level LoginError element), classify it too, so a transient+ // INTERNAL_ISSUES doesn't fall through to the blanket AccountRejected+ // below and needlessly re-register.+ if (el.hasLoginResponse() && el.getLoginResponse().hasLoginError())+ throwForLoginError(el.getLoginResponse().getLoginError().getErrorType());+ if (el.hasLoginResponse() && el.getLoginResponse().hasLoginSuccess()) {+ WazeProto.LoginSuccess s = el.getLoginResponse().getLoginSuccess();+ if (s.getServerSessionId() == 0) throw new WazeExceptions.WazeOperationException("zero serverSessionId");+ if (s.getSecretKey() == null || s.getSecretKey().isEmpty()) throw new WazeExceptions.WazeOperationException("empty secretKey");+ session = new WazeSessionInfo(s.getServerSessionId(), s.getSecretKey(),+ String.valueOf(s.getGlobalUserId()));+ seqCount = 2;+ lastRequestMs = SystemClock.elapsedRealtime();+ Log.d(TAG, "Login OK");+ return;+ }+ }+ throw new WazeExceptions.AccountRejectedException("login: no LoginSuccess element (" + r.body.length + "B)");+ }++ // ── command + query ──────────────────────────────────────────────────────++ private WazeProto.Batch command(String payload) throws Exception {+ if (session == null) throw new WazeExceptions.SessionExpiredException("command before login");+ Map<String, String> headers = new LinkedHashMap<>();+ headers.put("User-Agent", WazeConstants.APP_VERSION); // bare "5.17.1.0"+ headers.put("cache-control", "no-cache");+ headers.put("sequence-number", nextSeq());+ headers.put("x-waze-network-version", "3");+ headers.put("x-waze-wait-timeout", WazeConstants.WAIT_TIMEOUT_COMMAND);+ headers.put("uid", WazeRtCodec.buildUidHeader(session));++ WazeHttpClient.HttpResult r = http.post(url(WazeConstants.PATH_COMMAND),+ payload.getBytes(StandardCharsets.UTF_8), headers);+ // 4xx on a command = the server no longer honors this session → re-login.+ if (r.code >= 400 && r.code < 500) {+ session = null;+ throw new WazeExceptions.SessionExpiredException("command HTTP " + r.code);+ }+ if (r.code >= 500) throw new WazeExceptions.WazeOperationException("command HTTP " + r.code);+ if (r.body.length == 0) throw new WazeExceptions.WazeOperationException("empty command response");+ WazeProto.Batch batch = WazeProto.Batch.parseFrom(r.body);+ // Check for an in-band error BEFORE marking the session healthy, so a zombie+ // session (HTTP 200 + "please relogin") doesn't keep refreshing lastRequestMs.+ try {+ checkErrors(batch);+ } catch (WazeExceptions.SessionExpiredException e) {+ session = null; // force ensureReady to re-login next time+ throw e;+ }+ lastRequestMs = SystemClock.elapsedRealtime();+ return batch;+ }++ /** Register (if no creds) and log in (if no valid session). */+ private void ensureReady(double lon, double lat) throws Exception {+ if (credentials == null) register(lon, lat);+ if (!sessionValid()) login(lon, lat);+ }++ /**+ * Register (if no credentials) + log in (if no valid session) + run the+ * SeeMe/SetMood/Location/MapDisplayed handshake once per login, mirroring the+ * official client's ensureAlive (login + handshake only when the session is+ * new or idle; nothing at all otherwise).+ *+ * The handshake's MapDisplayed box is a real viewport query, and the RT server+ * sends each alert once per session, so its response is returned for the+ * caller to merge into the alert cache instead of being discarded. Returns+ * null when the session was already handshaken (no request was sent).+ */+ WazeProto.Batch prepareForArea(double lat, double lon) throws Exception {+ ensureReady(lon, lat);+ if (session != null && session.serverSessionId == handshakedSessionId) return null;+ WazeProto.Batch batch = command(WazeRtCodec.handshakePayload(lon, lat));+ handshakedSessionId = session != null ? session.serverSessionId : 0L;+ return batch;+ }++ /**+ * One MapDisplayed query for a bbox {@code [lonMin, latMin, lonMax, latMax]};+ * returns the raw batch so the caller can parse both added alerts and removed+ * ids from it (the RT response carries both).+ */+ WazeProto.Batch queryBox(double[] bbox) throws Exception {+ return command(WazeRtCodec.mapDisplayedCommand(bbox[0], bbox[1], bbox[2], bbox[3]));+ }++ /** Full flow for a single box: prepare + one query. Used by the debug selfTest. */+ List<WazeAlert> fetchArea(double lat, double lon, double radiusMeters) throws Exception {+ prepareForArea(lat, lon);+ double latDelta = radiusMeters / WazeConstants.M_PER_DEG_LAT;+ double lonDelta = radiusMeters / WazeConstants.mPerDegLon(lat);+ WazeProto.Batch batch = queryBox(new double[]{+ lon - lonDelta, lat - latDelta, lon + lonDelta, lat + latDelta});+ return WazeRtCodec.parseAlerts(batch);+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSessionInfo.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSessionInfo.javanew file mode 100644index 0000000..4cfbc2a--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSessionInfo.java@@ -0,0 +1,17 @@+package com.rfsentinel.app.online.wazert;++// Vendored unmodified from highway-radar-sabre-plus (MIT) except for the+// package declaration. See LICENSE in this directory.++/** Authenticated session state returned by a successful login. */+final class WazeSessionInfo {+ final long serverSessionId;+ final String secretKey;+ final String globalUserId;++ WazeSessionInfo(long serverSessionId, String secretKey, String globalUserId) {+ this.serverSessionId = serverSessionId;+ this.secretKey = secretKey;+ this.globalUserId = globalUserId;+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex e92c30b..6600f00 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -927,33 +927,41 @@ class ScanForegroundService : Service() {/** 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 }) { hit, lat, lon, key ->- pipeline.post { onOnlineHit(hit, lat, lon, key) }+ com.rfsentinel.app.online.OnlineWatch(this, serviceScope, { lastLocation ?: lastFix },+ onCallout = { text -> pipeline.post { AlertPlayer.callout(this, text) } }) { alert ->+ pipeline.post { onOnlineHit(alert) }}}private fun onlineActive() = Prefs.categoryEnabled(this, Category.AIRCRAFT) ||- (Prefs.categoryEnabled(this, Category.POLICE_REPORT) && Prefs.wazeAccepted(this))+ (Prefs.categoryEnabled(this, Category.POLICE_REPORT) && Prefs.wazeReady(this))- /** A police aircraft overhead or a Waze police report: logged, and an alert above the threshold. */- private fun onOnlineHit(hit: Hit, lat: Double, lon: Double, key: String) {+ /**+ * A police aircraft overhead or a Waze report: logged, and an alert above the threshold. What the alert+ * does depends on its level (sound and voice, a notification only, or nothing beyond the log).+ */+ private fun onOnlineHit(alert: com.rfsentinel.app.online.OnlineWatch.Alert) {+ val hit = alert.hitif (!Prefs.categoryEnabled(this, hit.category)) returnval now = System.currentTimeMillis()val loc = lastLocationval tag = Prefs.gpsTaggingEnabled(this)- serviceScope.launch {+ if (alert.log) serviceScope.launch {AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(DetectionEntity(- mac = key.substringBefore(':').uppercase() + " " + key.substringAfter(':'), label = hit.label,+ mac = alert.key.substringBefore(':').uppercase() + " " + alert.key.substringAfter(':'), label = hit.label,source = "ONLINE", rssi = 0, timestamp = now,latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,category = hit.category.name, confidence = hit.confidence, evidence = hit.evidence))}- if (hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {- NotificationHelper.sendMapAlert(this, key, hit, lat = lat, lon = lon)- AlertPlayer.play(this, hit.tier, com.rfsentinel.app.util.Spoken.shortWord(hit))+ if (alert.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&+ hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {+ NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon)+ if (alert.level == com.rfsentinel.app.online.WazePolice.Level.LOUD) {+ AlertPlayer.play(this, hit.tier, alert.spoken ?: com.rfsentinel.app.util.Spoken.shortWord(hit))+ }}}diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 84d9d0a..a1862f2 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -28,8 +28,8 @@ class SettingsActivity : AppCompatActivity() {/** Opens Settings on one section (expanded and scrolled to): e.g. [SECTION_MAP] from the map. */const val EXTRA_SECTION = "open_section"const val SECTION_MAP = "map"- const val WAZE_WARNING_SHORT = "Use at your own risk. Reports come from OpenWeb Ninja, a third-party paid service " +- "RF Sentinel doesn't run or endorse; your key, your account, your responsibility."+ const val WAZE_WARNING_SHORT = "Use at your own risk. Reports come from third-party services RF Sentinel doesn't run or endorse " ++ "(OpenWeb Ninja with your own key, or Waze itself); your account, your responsibility."const val WAZE_WARNING = "Waze police reports are read through OpenWeb Ninja's Waze API with your own API key.\n\n" +"• Use this feature at your own risk.\n" +"• OpenWeb Ninja and Waze are third-party services. RF Sentinel isn't affiliated with them, doesn't endorse them, " +@@ -38,6 +38,14 @@ class SettingsActivity : AppCompatActivity() {"• Reports are unverified crowd reports and can be wrong or out of date.\n\n" +"It stays off unless you enable it, and you can turn it off at any time."+ const val WAZE_DIRECT_WARNING = "Direct reads Waze police reports from Waze itself, using the Waze app's own protocol.\n\n" ++ "• Use this feature at your own risk.\n" ++ "• RF Sentinel registers an anonymous Waze account on this phone (stored encrypted) and presents itself to Waze as the Waze app. " ++ "Each update sends Waze, a Google service, your IP address and your position rounded to a 1 km grid (about 500 m off at most), as often as you set below (every minute by default).\n" ++ "• Waze isn't affiliated with RF Sentinel and may change or block this at any time; you're responsible for following their terms and your local laws.\n" ++ "• Reports are unverified crowd reports and can be wrong or out of date. Only police reports are used.\n\n" ++ "It stays off unless you enable it, and you can switch back to OpenWeb Ninja or turn it off at any time."+/*** Scroll position to restore after a theme change restyles this screen* (possibly twice: ours + AppCompat's night-mode switch).@@ -309,7 +317,16 @@ class SettingsActivity : AppCompatActivity() {"Police aircraft and Waze reports are online sources, off by default. Aircraft: every minute, a position " +"rounded to about 1 km goes to the community ADS-B feeds adsb.fi / adsb.lol; matched against a list of " +"about 1,400 US and Canadian law-enforcement aircraft, plus unlisted aircraft circling low overhead. " +- "Waze: police reports within 2 km through your own OpenWeb Ninja key, at your own risk.\n\n" ++ "Waze: crowd reports (police, and any other kind you tick), at your own risk. Either through your own OpenWeb Ninja key " ++ "(Waze never sees you), or Waze direct: no key, free, but an anonymous Waze account on this phone sends Waze (Google) your " ++ "IP address and a position rounded to a 1 km grid.\n" ++ "• Alert range: how close a report must be to alert. Map range: how far the map shows them.\n" ++ "• Check every: how often Waze is asked. Slower when parked, faster on fast roads (direct), if you leave that on. " ++ "OpenWeb Ninja bills every check.\n" ++ "• Only alert for reports ahead: while you drive, reports behind you stay on the list but stay quiet.\n" ++ "• Call out again: speaks at 1 km, 500 m and 200 m as a report gets closer (voice alerts on, or in the car).\n" ++ "• Each kind of report has its own level: sound and voice, notification only, or silent (list and map only).\n" ++ "• Pull the list down, or use the menu, to check right now. Waze status shows what is sent, and when.\n\n" +"Card skimmers: the Bluetooth modules built into gas-pump and ATM skimmers (HC-05 / HC-06 style names). " +"Hacking tools (off by default): Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi " +"networks (one network name, two makers, one open) and Bluetooth pairing-pop-up spam floods.\n\n" +@@ -382,7 +399,7 @@ class SettingsActivity : AppCompatActivity() {"Adapter not working? Export its log and send it to the developer."),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."),+ "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" +"Forget device history: new / returning status, detect counts and the cell towers remembered for the " +@@ -630,6 +647,156 @@ class SettingsActivity : AppCompatActivity() {textSize = 12falpha = 0.75f})+ val ninjaBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "OpenWeb Ninja (your own API key; Waze never sees you)" }+ val directBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "Waze direct (no key; sends a position rounded to 1 km to Waze)" }+ val backendGroup = android.widget.RadioGroup(this).apply { addView(ninjaBtn); addView(directBtn) }+ box.addView(backendGroup)+ // Two independent ranges (both backends): how close a report must be to alert, and how far the map shows them.+ fun rangeSlider(label: String, from: Float, to: Float, km: Int, desc: String, save: (Int) -> Unit) {+ val text = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }+ fun show(v: Int) { text.text = "$label $v km" }+ show(km)+ box.addView(text)+ box.addView(com.google.android.material.slider.Slider(this).apply {+ valueFrom = from; valueTo = to; stepSize = 1f+ value = km.toFloat().coerceIn(from, to)+ contentDescription = desc+ setLabelFormatter { "${it.toInt()} km" }+ addOnChangeListener { _, v, fromUser ->+ if (!fromUser) return@addOnChangeListener+ save(v.toInt()); show(v.toInt())+ }+ })+ }+ // The alert range steps through fixed distances, from 100 m up.+ val steps = Prefs.WAZE_ALERT_STEPS_M+ val alertText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }+ fun showAlert(m: Int) { alertText.text = "Alert when a report is within ${Prefs.formatRange(m)}" }+ val alertNow = Prefs.wazeAlertM(this)+ showAlert(alertNow)+ box.addView(alertText)+ box.addView(com.google.android.material.slider.Slider(this).apply {+ valueFrom = 0f; valueTo = (steps.size - 1).toFloat(); stepSize = 1f+ value = steps.indexOf(alertNow).coerceAtLeast(0).toFloat()+ contentDescription = "Waze alert distance"+ setLabelFormatter { Prefs.formatRange(steps[it.toInt().coerceIn(0, steps.size - 1)]) }+ addOnChangeListener { _, v, fromUser ->+ if (!fromUser) return@addOnChangeListener+ val m = steps[v.toInt().coerceIn(0, steps.size - 1)]+ Prefs.setWazeAlertM(this@SettingsActivity, m); showAlert(m)+ }+ })+ rangeSlider("Show reports on the map within", 1f, 20f, Prefs.wazeViewKm(this), "Waze map view range in kilometres") { Prefs.setWazeViewKm(this, it) }+ // How often Waze is asked. Each backend has its own steps; only the chosen backend's slider shows.+ fun intervalBlock(direct: Boolean): android.widget.LinearLayout {+ val steps = if (direct) Prefs.WAZE_DIRECT_INTERVALS_S else Prefs.WAZE_NINJA_INTERVALS_S+ val col = android.widget.LinearLayout(this).apply { orientation = android.widget.LinearLayout.VERTICAL }+ val text = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }+ val hint = android.widget.TextView(this).apply { textSize = 11f; alpha = 0.6f }+ fun show(sec: Int) {+ text.text = "Check for new reports every ${Prefs.formatInterval(sec)}"+ hint.text = when {+ !direct -> "OpenWeb Ninja bills every check (about half a cent each on pay-as-you-go, check your plan): ${3600 / sec} an hour at this setting."+ sec < 60 -> "Fresher reports, but your position goes to Waze more often."+ sec > 90 -> "Over 90 s Waze ends the session in between, so each check logs in again (more data)."+ else -> ""+ }+ hint.visibility = if (hint.text.isEmpty()) View.GONE else View.VISIBLE+ }+ val now = Prefs.wazeIntervalS(this, direct)+ show(now)+ col.addView(text)+ col.addView(com.google.android.material.slider.Slider(this).apply {+ valueFrom = 0f; valueTo = (steps.size - 1).toFloat(); stepSize = 1f+ value = steps.indexOf(now).coerceAtLeast(0).toFloat()+ contentDescription = "How often to check Waze"+ setLabelFormatter { Prefs.formatInterval(steps[it.toInt().coerceIn(0, steps.size - 1)]) }+ addOnChangeListener { _, v, fromUser ->+ if (!fromUser) return@addOnChangeListener+ val sec = steps[v.toInt().coerceIn(0, steps.size - 1)]+ Prefs.setWazeIntervalS(this@SettingsActivity, direct, sec); show(sec)+ }+ })+ col.addView(hint)+ return col+ }+ val directInterval = intervalBlock(true)+ val ninjaInterval = intervalBlock(false)+ box.addView(directInterval)+ box.addView(ninjaInterval)+ // Behaviour switches: each has a line under it saying what it does.+ fun switchRow(label: String, hint: String, checked: Boolean, save: (Boolean) -> Unit) {+ box.addView(SwitchMaterial(this).apply {+ text = label+ isChecked = checked+ setOnCheckedChangeListener { _, on -> save(on) }+ })+ box.addView(android.widget.TextView(this).apply { text = hint; textSize = 11f; alpha = 0.6f })+ }+ switchRow("Slower when parked, faster on fast roads",+ "Parked for 90 s: checks run 4 times less often. Over 80 km/h: twice as often (Waze direct only).",+ Prefs.wazeAdaptive(this)) { Prefs.setWazeAdaptive(this, it) }+ switchRow("Only alert for reports ahead of me",+ "While you drive, reports behind you stay on the list but don't alert, flash or speak.",+ Prefs.wazeAheadOnly(this)) { Prefs.setWazeAheadOnly(this, it) }+ switchRow("Call out again as I get closer",+ "Speaks at 1 km, 500 m and 200 m when voice alerts are on, or in the car.",+ Prefs.wazeApproach(this)) { Prefs.setWazeApproach(this, it) }+ // What to watch (ticked) and what an alert of that kind does (the menu beside it).+ box.addView(android.widget.TextView(this).apply { text = "What to alert on, and how loud"; textSize = 12f; alpha = 0.75f })+ val levels = com.rfsentinel.app.online.WazePolice.Level.entries+ for (t in com.rfsentinel.app.online.WazePolice.Type.entries) {+ val row = android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.HORIZONTAL+ gravity = android.view.Gravity.CENTER_VERTICAL+ }+ row.addView(com.google.android.material.checkbox.MaterialCheckBox(this).apply {+ layoutParams = android.widget.LinearLayout.LayoutParams(0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1f)+ text = t.label+ isChecked = t.name in Prefs.wazeTypes(this@SettingsActivity)+ setOnCheckedChangeListener { _, on ->+ val now = Prefs.wazeTypes(this@SettingsActivity).toMutableSet()+ if (on) now.add(t.name) else now.remove(t.name)+ if (now.isEmpty()) { isChecked = true; return@setOnCheckedChangeListener } // keep at least one+ Prefs.setWazeTypes(this@SettingsActivity, now)+ }+ })+ row.addView(androidx.appcompat.widget.AppCompatSpinner(this).apply {+ adapter = android.widget.ArrayAdapter(this@SettingsActivity, android.R.layout.simple_spinner_item, levels.map { it.label }).also {+ it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)+ }+ setSelection(Prefs.wazeLevel(this@SettingsActivity, t).ordinal)+ contentDescription = "What a ${t.label.lowercase()} alert does"+ onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {+ override fun onItemSelected(parent: android.widget.AdapterView<*>?, view: View?, position: Int, id: Long) {+ Prefs.setWazeLevel(this@SettingsActivity, t, levels[position])+ }+ override fun onNothingSelected(parent: android.widget.AdapterView<*>?) {}+ }+ })+ box.addView(row)+ }+ val jamNote = android.widget.TextView(this).apply {+ text = "OpenWeb Ninja doesn't offer traffic jams as alerts; they only come through Waze direct."+ textSize = 11f; alpha = 0.6f+ }+ box.addView(jamNote)+ val directNote = android.widget.TextView(this).apply {+ text = "Direct: free and live. Uses an anonymous Waze account on this phone."+ textSize = 12f; alpha = 0.75f+ }+ val forgetBtn = android.widget.Button(this).apply {+ text = "Forget Waze account"+ setOnClickListener {+ com.rfsentinel.app.online.wazert.WazeRtFetcher.forgetStoredAccount(this@SettingsActivity)+ android.widget.Toast.makeText(this@SettingsActivity, "Waze account forgotten; a new one is made on the next poll", android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ val directBox = android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.VERTICAL+ addView(directNote); addView(forgetBtn)+ }+ box.addView(directBox)wazeKeyInput = android.widget.EditText(this).apply {hint = "OpenWeb Ninja API key"isSingleLine = true@@ -638,19 +805,53 @@ class SettingsActivity : AppCompatActivity() {setText(com.rfsentinel.app.util.SecureStore.get(this@SettingsActivity, com.rfsentinel.app.online.OnlineWatch.WAZE_KEY_NAME).orEmpty())}box.addView(wazeKeyInput)+ fun showBackend(direct: Boolean) {+ wazeKeyInput?.visibility = if (direct) View.GONE else View.VISIBLE+ directInterval.visibility = if (direct) View.VISIBLE else View.GONE+ jamNote.visibility = if (direct) View.GONE else View.VISIBLE+ ninjaInterval.visibility = if (direct) View.GONE else View.VISIBLE+ directBox.visibility = if (direct) View.VISIBLE else View.GONE+ }+ val directNow = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT+ backendGroup.check(if (directNow) directBtn.id else ninjaBtn.id)+ showBackend(directNow)+ backendGroup.setOnCheckedChangeListener { _, id ->+ if (id == directBtn.id) {+ if (Prefs.wazeDirectAccepted(this)) { Prefs.setWazeBackend(this, Prefs.WAZE_DIRECT); showBackend(true) }+ else {+ backendGroup.check(ninjaBtn.id)+ AlertDialog.Builder(this)+ .setTitle("Waze direct: use at your own risk")+ .setMessage(WAZE_DIRECT_WARNING)+ .setPositiveButton("I understand, use direct") { _, _ ->+ Prefs.setWazeDirectAccepted(this, true)+ Prefs.setWazeBackend(this, Prefs.WAZE_DIRECT)+ backendGroup.check(directBtn.id)+ }+ .setNegativeButton("Cancel", null)+ .show()+ }+ } else { Prefs.setWazeBackend(this, Prefs.WAZE_NINJA); showBackend(false) }+ }wazeStatusText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }box.addView(wazeStatusText)showNote(wazeStatusText, com.rfsentinel.app.online.OnlineWatch.wazeStatus)+ box.addView(android.widget.Button(this).apply {+ text = "Waze status"+ setOnClickListener { com.rfsentinel.app.ui.WazeUi.openStatus(this@SettingsActivity) }+ })box.visibility = if (sw.isChecked) View.VISIBLE else View.GONEbinding.categoryContainer.addView(box)sw.setOnCheckedChangeListener { _, on ->- if (on && !Prefs.wazeAccepted(this)) {+ if (on && !Prefs.wazeReady(this)) {sw.isChecked = false+ val direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECTAlertDialog.Builder(this)- .setTitle("Waze police reports: use at your own risk")- .setMessage(WAZE_WARNING)+ .setTitle("Waze reports: use at your own risk")+ .setMessage(if (direct) WAZE_DIRECT_WARNING else WAZE_WARNING).setPositiveButton("I understand, enable") { _, _ ->Prefs.setWazeAccepted(this, true)+ if (direct) Prefs.setWazeDirectAccepted(this, true)sw.isChecked = true}.setNegativeButton("Cancel", null)diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.ktindex 25b8c53..367003b 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"),+ /** 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. */EXTERNAL("External");@@ -29,7 +31,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 -> false+ CELLS, WAZE -> 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/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex 22ebb53..1ef5607 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -86,6 +86,8 @@ class MapActivity : AppCompatActivity() {private var filter = DeviceFilter.ALLprivate 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@@ -95,6 +97,8 @@ class MapActivity : AppCompatActivity() {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 {@@ -154,9 +158,15 @@ class MapActivity : AppCompatActivity() {binding.recordButton.setOnClickListener { toggleRecording() }lifecycleScope.launch {repeatOnLifecycle(Lifecycle.State.STARTED) {- while (isActive) {- renderLive()- delay(3_000)+ // 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()}}}@@ -171,7 +181,19 @@ class MapActivity : AppCompatActivity() {map.setTileSource(TileSourceFactory.MAPNIK)map.setMultiTouchControls(true)map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT)- map.controller.setZoom(16.0)+ // 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.0map.maxZoomLevel = 20.0@@ -186,6 +208,7 @@ class MapActivity : AppCompatActivity() {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 {@@ -212,10 +235,20 @@ class MapActivity : AppCompatActivity() {centeredOnce = true} else if (tripId == null) {// Live map: keep your position centred from the first fix until you pan away.- setFollow(true)+ setFollow(true, quiet = true)myLocation.runOnFirstFix {- runOnUiThread { if (!centeredOnce) { centeredOnce = true; if (following) centerOnMe() } }+ 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)@@ -244,6 +277,7 @@ class MapActivity : AppCompatActivity() {}override fun onPause() {+ saveView()if (tripId == null) ScanForegroundService.mapHidden(this)myLocation.disableMyLocation()binding.map.onPause()@@ -256,6 +290,9 @@ class MapActivity : AppCompatActivity() {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()}@@ -289,17 +326,21 @@ class MapActivity : AppCompatActivity() {private fun updateFilterCounts(devices: List<DeviceRegistry.Snapshot>) {val placed = devices.filter { it.bestPosition != null }for ((f, chip) in filterChips) {- val n = if (f == DeviceFilter.CELLS) towerCount else placed.count { f.matches(it) }+ 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) {+ private fun setFollow(on: Boolean, quiet: Boolean = false) {following = onif (on) {myLocation.enableFollowLocation()- centerOnMe()+ centerOnMe(quiet)} else {myLocation.disableFollowLocation()}@@ -316,11 +357,42 @@ class MapActivity : AppCompatActivity() {binding.centerButton.contentDescription = if (on) "Following your position" else "Follow my position"}- private fun centerOnMe() {+ private fun centerOnMe(quiet: Boolean = false) {val fix = myLocation.myLocation?: TripRecorder.livePoints().lastOrNull()?.let { GeoPoint(it.lat, it.lon) }- if (fix != null) binding.map.controller.animateTo(fix)- else Toast.makeText(this, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()+ 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 ----------------------------------------------------------------@@ -361,6 +433,7 @@ class MapActivity : AppCompatActivity() {updateFilterCounts(devices)drawDrones(devices.filter { it.remoteId?.hasPosition == true })drawAircraft()+ drawWaze()val positioned = devices.count { it.bestPosition != null }binding.statusText.text = when {@@ -541,6 +614,44 @@ class MapActivity : AppCompatActivity() {}}+ /** 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@@ -976,6 +1087,8 @@ class MapActivity : AppCompatActivity() {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)@@ -997,6 +1110,8 @@ class MapActivity : AppCompatActivity() {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)}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapStart.kt b/app/src/main/java/com/rfsentinel/app/ui/MapStart.ktnew file mode 100644index 0000000..1f9e86c--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapStart.kt@@ -0,0 +1,38 @@+package com.rfsentinel.app.ui++import kotlin.math.abs++/**+ * Where the live map first looks. Waiting for the phone's own GPS fix left it on (0, 0) at street zoom,+ * which is open sea, until the first fix arrived a few seconds later. With a position already known it opens+ * on your area at once, and the tiles seen there last time come straight from the cache.+ */+object MapStart {+ const val DEFAULT_ZOOM = 16.0+ /** Knowing nothing about where you are, a world view (a few cached tiles) beats zooming in on open sea. */+ const val WORLD_ZOOM = 3.0+ /** A fix this young is where you are, not just where you were. */+ const val FRESH_MS = 2 * 60_000L++ /** A position and when it was taken (epoch milliseconds). */+ data class Fix(val lat: Double, val lon: Double, val timeMs: Long)++ /** Where to centre, how far in, and whether the position is current (then the map need not move again). */+ data class View(val lat: Double, val lon: Double, val zoom: Double, val fresh: Boolean)++ /**+ * The newest of the known [fixes] (the running scan's, the system's last known), else the place the map+ * last looked ([saved], remembered only with GPS tagging on). [savedZoom] is reused when it is a+ * sensible street-to-city zoom; null when nothing at all is known.+ */+ fun pick(fixes: List<Fix?>, saved: Pair<Double, Double>?, savedZoom: Double?, now: Long): View? {+ val zoom = savedZoom?.takeIf { it in 11.0..19.0 } ?: DEFAULT_ZOOM+ val newest = fixes.filterNotNull().filter { !isOrigin(it.lat, it.lon) }.maxByOrNull { it.timeMs }+ if (newest != null) return View(newest.lat, newest.lon, zoom, fresh = now - newest.timeMs <= FRESH_MS)+ if (saved != null && !isOrigin(saved.first, saved.second)) return View(saved.first, saved.second, zoom, fresh = false)+ return null+ }++ /** (0, 0) is what a missing position looks like; it is never a real place to start from. */+ private fun isOrigin(lat: Double, lon: Double) = abs(lat) < 1e-4 && abs(lon) < 1e-4+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.ktnew file mode 100644index 0000000..9b251a4--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt@@ -0,0 +1,130 @@+package com.rfsentinel.app.ui++import android.os.Bundle+import android.view.View+import android.widget.LinearLayout+import android.widget.ScrollView+import android.widget.TextView+import androidx.appcompat.app.AppCompatActivity+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.lifecycleScope+import androidx.lifecycle.repeatOnLifecycle+import com.google.android.material.button.MaterialButton+import com.rfsentinel.app.online.MotionTracker+import com.rfsentinel.app.online.OnlineWatch+import com.rfsentinel.app.online.WazePolice+import com.rfsentinel.app.online.WazeStatus+import com.rfsentinel.app.online.wazert.WazeRtFetcher+import com.rfsentinel.app.online.wazert.WazeRtFetcher.Diagnostics+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.util.Prefs+import com.rfsentinel.app.util.SecureStore+import com.rfsentinel.app.util.applySystemBarInsets+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import java.util.Locale++/**+ * What the Waze checks are doing and what they tell the other side: the source, the position that goes+ * out, the account, when the last and next checks are, and what came back. With Check now, Pause and+ * Forget account.+ */+class WazeStatusActivity : AppCompatActivity() {++ private lateinit var body: TextView+ private lateinit var pause: MaterialButton+ private lateinit var forget: MaterialButton++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ title = "Waze status"+ supportActionBar?.setDisplayHomeAsUpEnabled(true)+ val dp = resources.displayMetrics.density+ fun pad(v: Int) = (v * dp).toInt()++ body = TextView(this).apply { textSize = 14f; setLineSpacing(0f, 1.2f); setTextIsSelectable(true) }+ fun button(label: String, onClick: () -> Unit) = MaterialButton(this).apply {+ text = label+ setOnClickListener { onClick(); refresh() }+ layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)+ .apply { topMargin = pad(8) }+ }+ pause = button("Pause Waze checks") { Prefs.setWazePaused(this, !Prefs.wazePaused(this)) }+ forget = button("Forget Waze account") {+ WazeRtFetcher.forgetStoredAccount(this)+ android.widget.Toast.makeText(this, "Waze account forgotten; a new one is made on the next check", android.widget.Toast.LENGTH_SHORT).show()+ }+ val column = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(pad(16), pad(16), pad(16), pad(16))+ addView(body)+ addView(button("Check now") { WazeUi.checkNow(this@WazeStatusActivity) })+ addView(pause)+ addView(forget)+ addView(button("Waze settings") {+ startActivity(android.content.Intent(this@WazeStatusActivity, com.rfsentinel.app.settings.SettingsActivity::class.java))+ })+ }+ val scroll = ScrollView(this).apply { addView(column) }+ setContentView(scroll)+ scroll.applySystemBarInsets()++ lifecycleScope.launch {+ repeatOnLifecycle(Lifecycle.State.STARTED) {+ while (true) { refresh(); delay(1_000) }+ }+ }+ }++ override fun onSupportNavigateUp(): Boolean { finish(); return true }++ private fun refresh() {+ val now = System.currentTimeMillis()+ val direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT+ val paused = Prefs.wazePaused(this)+ pause.text = if (paused) "Resume Waze checks" else "Pause Waze checks"+ forget.visibility = if (direct) View.VISIBLE else View.GONE++ fun ago(t: Long) = if (t <= 0) "never" else "${((now - t) / 1000).coerceAtLeast(0)} s ago"+ val state = when {+ !WazeUi.on(this) -> "Off: turn on Waze reports in Settings"+ !ScanForegroundService.isRunning -> "Not scanning: Waze is checked while scanning"+ paused -> "Paused"+ WazePolice.running -> "Checking"+ else -> "Starting"+ }+ val motion = when (WazeStatus.motion) {+ MotionTracker.State.PARKED -> "parked"+ MotionTracker.State.FAST -> "on a fast road"+ MotionTracker.State.MOVING -> "moving"+ }+ val lines = ArrayList<String>()+ lines += "State: $state"+ if (WazePolice.running && !paused) {+ val adapted = if (WazeStatus.everyS != WazeStatus.baseS) " (set to ${Prefs.formatInterval(WazeStatus.baseS)}, adapted: you are $motion)" else ""+ lines += "Checks every: ${Prefs.formatInterval(WazeStatus.everyS)}$adapted"+ lines += "Next check: in ${((WazeStatus.nextCheckAt - now) / 1000).coerceAtLeast(0)} s"+ }+ lines += "Last check: ${ago(WazeStatus.lastCheckAt)}" ++ (if (WazeStatus.lastCheckAt > 0) ", took ${String.format(Locale.US, "%.1f", WazeStatus.lastCheckMs / 1000.0)} s" else "") ++ " · ${WazeStatus.checks} this session"+ lines += "Reports: ${WazeStatus.onMap} on the map, ${WazeStatus.inAlertRange} in alert range"+ lines += ""+ if (direct) {+ lines += "Source: Waze direct" + (if (Diagnostics.host.isNotEmpty()) " (${Diagnostics.host})" else "")+ lines += if (Diagnostics.sentLat.isNaN()) "Sent to Waze: nothing yet"+ else "Sent to Waze: your IP address and a 1 km grid square centred on " ++ "${String.format(Locale.US, "%.3f", Diagnostics.sentLat)}, ${String.format(Locale.US, "%.3f", Diagnostics.sentLon)} (never your exact position)"+ lines += "Account: " + (if (WazeRtFetcher.hasStoredAccount(this)) "an anonymous account is stored on this phone" else "none yet; one is made on the next check") ++ " (${WazeRtFetcher.accountsMadeToday(this)} of ${WazeRtFetcher.dailyAccountLimit()} made today)"+ if (Diagnostics.lastError.isNotEmpty()) lines += "Last problem: ${Diagnostics.lastError}"+ } else {+ lines += "Source: OpenWeb Ninja (api.openwebninja.com)"+ lines += "Sent: your API key and a box of about ${Prefs.formatRange(maxOf(Prefs.wazeViewKm(this) * 1000, Prefs.wazeAlertM(this)))} around your position (not rounded)"+ lines += "API key: " + (if (SecureStore.get(this, OnlineWatch.WAZE_KEY_NAME).isNullOrBlank()) "not set" else "set")+ }+ lines += ""+ lines += OnlineWatch.wazeStatus.ifEmpty { "No answer yet" }+ body.text = lines.joinToString("\n")+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/WazeUi.kt b/app/src/main/java/com/rfsentinel/app/ui/WazeUi.ktnew file mode 100644index 0000000..3854d08--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/WazeUi.kt@@ -0,0 +1,36 @@+package com.rfsentinel.app.ui++import android.content.Context+import android.content.Intent+import android.widget.Toast+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.online.WazePolice+import com.rfsentinel.app.online.WazeTiming+import com.rfsentinel.app.util.Prefs++/** Small helpers shared by the screens that offer "Check Waze now" and "Waze status". */+object WazeUi {++ /** Waze reports are switched on (the category, and the warning for the chosen source accepted). */+ fun on(context: Context): Boolean = Prefs.categoryEnabled(context, Category.POLICE_REPORT) && Prefs.wazeReady(context)++ /**+ * Asks the poller to check Waze right now and tells the user what happened. Returns true only+ * when a check was asked for; checks are spaced out (10 s on Waze direct, 60 s on OpenWeb Ninja).+ */+ fun checkNow(context: Context): Boolean {+ val (message, asked) = when {+ !on(context) -> "Turn on Waze reports in Settings first" to false+ Prefs.wazePaused(context) -> "Waze checks are paused - resume them in Waze status" to false+ !WazePolice.running -> "Waze is checked while scanning - start scanning first" to false+ else -> {+ val wait = WazePolice.requestCheckNow(WazeTiming.minGapS(Prefs.wazeBackend(context) == Prefs.WAZE_DIRECT))+ if (wait == null) "Checking Waze now..." to true else "Checked a moment ago - try again in $wait s" to false+ }+ }+ Toast.makeText(context, message, Toast.LENGTH_SHORT).show()+ return asked+ }++ fun openStatus(context: Context) = context.startActivity(Intent(context, WazeStatusActivity::class.java))+}diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.ktindex f00ce58..aff9a2f 100644--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt@@ -196,6 +196,16 @@ object AlertPlayer {Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)}+ /**+ * A spoken call-out only, no beep or vibration (Waze reports getting closer). It follows the voice+ * settings: spoken when voice alerts are on or Android Auto is connected, and never when muted or snoozed.+ */+ fun callout(context: Context, text: String) {+ val inCar = CarState.connected+ if (Prefs.alertsSilenced(context) || !(Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))) return+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (inCar) carSpeechAttributes else phoneSpeechAttributes)+ }+/** The Settings "Test voice" button: speaks right away with the chosen voice and speed. */fun testVoice(context: Context, short: Boolean = Prefs.shortVoice(context)) {Voice.test(context.applicationContext, if (short) "Body cam" else "RF Sentinel voice alerts. Axon body camera nearby.",diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 8a832ad..da8094c 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -71,6 +71,71 @@ object Prefs {fun wazeAccepted(context: Context): Boolean = bool(context, "waze_accepted", false)fun setWazeAccepted(context: Context, value: Boolean) = setBool(context, "waze_accepted", value)+ /** Waze backend: "ninja" (OpenWeb Ninja key, default) or "direct" (Waze app protocol, anonymous account). */+ const val WAZE_NINJA = "ninja"+ const val WAZE_DIRECT = "direct"+ fun wazeBackend(context: Context): String =+ if (sp(context).getString("waze_backend", WAZE_NINJA) == WAZE_DIRECT) WAZE_DIRECT else WAZE_NINJA+ fun setWazeBackend(context: Context, value: String) = sp(context).edit { putString("waze_backend", value) }+ /** How far away (km, 1-20, default 5) Waze reports are drawn on the map. */+ fun wazeViewKm(context: Context): Int = int(context, "waze_view_km", 5).coerceIn(1, 20)+ fun setWazeViewKm(context: Context, km: Int) = setInt(context, "waze_view_km", km.coerceIn(1, 20))+ /** The distances the Waze alert-range slider steps through, in metres (100 m up to 10 km). */+ val WAZE_ALERT_STEPS_M = intArrayOf(100, 200, 300, 500, 750, 1000, 1500, 2000, 3000, 5000, 7500, 10000)+ /** How close (metres, default 2000) a Waze report must be to alert, independent of the view range. */+ fun wazeAlertM(context: Context): Int {+ val m = int(context, "waze_alert_m", 2000)+ return WAZE_ALERT_STEPS_M.minByOrNull { kotlin.math.abs(it - m) } ?: 2000+ }+ fun setWazeAlertM(context: Context, m: Int) = setInt(context, "waze_alert_m", m)+ /** "100 m", "750 m", "1.5 km", "10 km". */+ fun formatRange(m: Int): String = if (m < 1000) "$m m" else if (m % 1000 == 0) "${m / 1000} km" else "${m / 1000.0} km"+ /** How often Waze is asked for reports, in seconds: each backend has its own steps and default. */+ val WAZE_DIRECT_INTERVALS_S get() = com.rfsentinel.app.online.WazeTiming.DIRECT_STEPS_S+ val WAZE_NINJA_INTERVALS_S get() = com.rfsentinel.app.online.WazeTiming.NINJA_STEPS_S+ private fun wazeIntervalKey(direct: Boolean) = if (direct) "waze_interval_direct_s" else "waze_interval_ninja_s"+ fun wazeIntervalS(context: Context, direct: Boolean): Int {+ val steps = com.rfsentinel.app.online.WazeTiming.steps(direct)+ val v = int(context, wazeIntervalKey(direct),+ if (direct) com.rfsentinel.app.online.WazeTiming.DIRECT_DEFAULT_S else com.rfsentinel.app.online.WazeTiming.NINJA_DEFAULT_S)+ return steps.minByOrNull { kotlin.math.abs(it - v) } ?: steps[0]+ }+ fun setWazeIntervalS(context: Context, direct: Boolean, seconds: Int) = setInt(context, wazeIntervalKey(direct), seconds)+ /** "15 s", "90 s", "2 min", "10 min". */+ fun formatInterval(seconds: Int): String = if (seconds < 120) "$seconds s" else "${seconds / 60} min"++ /** Slower checks when parked and faster on fast roads (Waze direct only). On by default. */+ fun wazeAdaptive(context: Context): Boolean = bool(context, "waze_adaptive", true)+ fun setWazeAdaptive(context: Context, value: Boolean) = setBool(context, "waze_adaptive", value)+ /** Alert only for reports that are not behind you while you drive. Off by default. */+ fun wazeAheadOnly(context: Context): Boolean = bool(context, "waze_ahead_only", false)+ fun setWazeAheadOnly(context: Context, value: Boolean) = setBool(context, "waze_ahead_only", value)+ /** Speak again as a report gets closer (1 km, 500 m, 200 m). On by default. */+ fun wazeApproach(context: Context): Boolean = bool(context, "waze_approach", true)+ fun setWazeApproach(context: Context, value: Boolean) = setBool(context, "waze_approach", value)+ /** Waze checks paused from the Waze status screen (nothing is asked or shown). */+ fun wazePaused(context: Context): Boolean = bool(context, "waze_paused", false)+ fun setWazePaused(context: Context, value: Boolean) = setBool(context, "waze_paused", value)+ /** What an alert of one Waze event type does: sound and voice, a notification only, or nothing beyond the list and map. */+ fun wazeLevel(context: Context, type: com.rfsentinel.app.online.WazePolice.Type): com.rfsentinel.app.online.WazePolice.Level {+ val levels = com.rfsentinel.app.online.WazePolice.Level.entries+ return levels.getOrNull(int(context, "waze_level_${type.name}", type.defaultLevel.ordinal)) ?: type.defaultLevel+ }+ fun setWazeLevel(context: Context, type: com.rfsentinel.app.online.WazePolice.Type, level: com.rfsentinel.app.online.WazePolice.Level) =+ setInt(context, "waze_level_${type.name}", level.ordinal)++ /** Which Waze event kinds to alert on (WazePolice.Type names); police only by default. */+ fun wazeTypes(context: Context): Set<String> =+ sp(context).getStringSet("waze_types", null)?.takeIf { it.isNotEmpty() } ?: setOf("POLICE")+ fun setWazeTypes(context: Context, value: Set<String>) = sp(context).edit { putStringSet("waze_types", value) }++ /** The user read and accepted the warning that "direct" sends a (blurred) position to Waze, a Google service. */+ fun wazeDirectAccepted(context: Context): Boolean = bool(context, "waze_direct_accepted", false)+ fun setWazeDirectAccepted(context: Context, value: Boolean) = setBool(context, "waze_direct_accepted", value)+ /** True when the chosen Waze backend's warning has been accepted. */+ fun wazeReady(context: Context): Boolean =+ wazeAccepted(context) && (wazeBackend(context) != WAZE_DIRECT || wazeDirectAccepted(context))+fun alertsMuted(context: Context): Boolean = bool(context, "alerts_muted", false)fun setAlertsMuted(context: Context, value: Boolean) = setBool(context, "alerts_muted", value)@@ -157,6 +222,23 @@ object Prefs {* Map device filter (a [com.rfsentinel.app.ui.DeviceFilter] name). Older* versions had only "all devices" on/off: off becomes Flagged.*/+ /** The live map's last zoom. A zoom level is not a place, so it is always kept. */+ fun mapZoom(context: Context): Double? = sp(context).getFloat("map_zoom", -1f).takeIf { it > 0f }?.toDouble()++ /** Where the live map last looked; remembered only with GPS tagging on, like the other saved positions. */+ fun lastMapCenter(context: Context): Pair<Double, Double>? {+ if (!gpsTaggingEnabled(context)) return null+ val parts = sp(context).getString("map_center", null)?.split(',') ?: return null+ val lat = parts.getOrNull(0)?.toDoubleOrNull() ?: return null+ val lon = parts.getOrNull(1)?.toDoubleOrNull() ?: return null+ return lat to lon+ }++ fun saveMapView(context: Context, lat: Double, lon: Double, zoom: Double) = sp(context).edit {+ putFloat("map_zoom", zoom.toFloat())+ if (gpsTaggingEnabled(context)) putString("map_center", "$lat,$lon") else remove("map_center")+ }+fun mapFilter(context: Context): String =sp(context).getString("map_filter", null) ?: if (bool(context, "map_show_all", true)) "ALL" else "FLAGGED"fun setMapFilter(context: Context, name: String) = sp(context).edit { putString("map_filter", name) } /** Last destinations picked in the car (newest first, kept on this phone only). */diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.ktindex 45f54be..f9fb599 100644--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt@@ -30,6 +30,39 @@ object Spoken {}}+ /** A distance said aloud: "300 meters" (to the nearest 50), "1 kilometer", "1.2 kilometers". */+ fun distanceWords(m: Double): String {+ val r = Math.round(m / 50.0) * 50+ if (r < 1000) return "${r.coerceAtLeast(50)} meters"+ val km = Math.round(m / 100.0) / 10.0+ return if (km == Math.floor(km)) "${km.toLong()} kilometer${if (km == 1.0) "" else "s"}" else "$km kilometers"+ }++ /** Where a report is, said aloud; empty when the heading is unknown. */+ fun sideWords(side: com.rfsentinel.app.online.WazePolice.Side?): String = when (side) {+ com.rfsentinel.app.online.WazePolice.Side.AHEAD -> "ahead"+ com.rfsentinel.app.online.WazePolice.Side.BEHIND -> "behind you"+ com.rfsentinel.app.online.WazePolice.Side.LEFT -> "on your left"+ com.rfsentinel.app.online.WazePolice.Side.RIGHT -> "on your right"+ null -> ""+ }++ /**+ * What is said for a Waze report: "Police ahead, 800 meters" (short), or+ * "Police reported on Waze, 800 meters ahead" (full). The same short form is used as you get closer.+ */+ fun wazePhrase(type: com.rfsentinel.app.online.WazePolice.Type, distanceM: Double,+ side: com.rfsentinel.app.online.WazePolice.Side?, short: Boolean): String {+ val where = sideWords(side)+ val dist = distanceWords(distanceM)+ return if (short) type.singular + (if (where.isEmpty()) "" else " $where") + ", $dist"+ else "${type.singular} reported on Waze, $dist" + (if (where.isEmpty()) "" else " $where")+ }++ /** [wazePhrase] in the style Settings asks for (short spoken alerts, or the radar-detector style). */+ fun waze(context: Context, type: com.rfsentinel.app.online.WazePolice.Type, distanceM: Double,+ side: com.rfsentinel.app.online.WazePolice.Side?): String = wazePhrase(type, distanceM, side, short(context))+fun shortWord(hit: Hit): String = when (hit.category) {Category.BODY_CAM -> "Body cam"Category.ALPR -> "Plate camera"@@ -43,7 +76,8 @@ object Spoken {Category.RADIO -> "Radio nearby"Category.GNSS -> "GPS warning"Category.AIRCRAFT -> if (hit.label.startsWith("Police")) "Police aircraft" else "Aircraft circling"- Category.POLICE_REPORT -> "Waze police"+ Category.POLICE_REPORT -> "Waze " + (com.rfsentinel.app.online.WazePolice.Type.entries+ .firstOrNull { hit.label.startsWith(it.singular) }?.singular?.lowercase() ?: "report")Category.SKIMMER -> "Card skimmer"Category.OTHER_CAMERA -> if (hit.label.startsWith("Hidden")) "Hidden camera" else "Action camera"Category.HACKER -> "Hacking tool"diff --git a/app/src/main/proto/waze.proto b/app/src/main/proto/waze.protonew file mode 100644index 0000000..f6585c8--- /dev/null+++ b/app/src/main/proto/waze.proto@@ -0,0 +1,583 @@+// Vendored from highway-radar-sabre-plus (MIT, (c) 2026 highway-radar-sabre-plus+// contributors) — see app/src/main/java/com/rfsentinel/app/online/wazert/LICENSE.+// Unmodified except for java_package, which points at RF Sentinel's own package.+//+// Minimal, wire-compatible description of the Waze mobile RT protocol, limited+// to the messages this plugin exchanges. Field numbers and wire types match+// what the Waze client sends and accepts on the wire.+//+// Scope: ONLY the messages needed for the area-alert FETCH path+// (ClientInfo / register / login + incoming RealtimeAlert parsing). Reporting+// messages, alert "details" sub-trees, and other unrelated Element members are+// intentionally omitted. Because every field is proto2 optional/repeated, the+// omitted fields are simply skipped on the wire and do not affect compatibility.+//+// All integer scalars use plain int32/int64 (the writers emit writeInt32 /+// writeInt64 -- NOT writeSInt32/writeUInt32 -- so there is no zig-zag encoding,+// e.g. Coordinate.lat/lon and AlertInfo.azymuth are int32).++syntax = "proto2";++option java_package = "com.rfsentinel.app.online.wazert";+option java_outer_classname = "WazeProto";+option optimize_for = LITE_RUNTIME;++// ---------------------------------------------------------------------------+// Top-level container+// ---------------------------------------------------------------------------++message Batch {+ repeated Element element = 1001;+ optional int64 expiration_gmt = 1002;+}++// The big polymorphic container. Each Element carries exactly one logical+// payload (selected by the caller); proto2 makes them all independent optional+// fields rather than a oneof. Only the members this plugin uses are declared+// here; many other high-numbered members exist in the full schema.+message Element {+ optional int32 request_id = 1;+ optional string old_command = 2001;+ optional ServerError error = 2003;+ optional ReportAdsSettings report_ads_setting = 2108;+ optional ResponseTimestamp response_timestamp = 2150;+ optional ClientInfo client_info = 2184;+ optional Register register = 2219;+ optional RegisterSuccessful register_successful = 2220;+ optional UID uid = 2221;+ optional LoginError login_error = 2224;+ optional LoginSuccessful login_successful = 2225;+ optional AT at = 2384;+ optional AddAlertAction add_alert_action = 2708;+ optional AddUserReportedAlertRequest add_user_reported_alert_request = 2737;+ optional AddUserReportedAlertResponse add_user_reported_alert_response = 2738;+ optional LoginRequest login_request = 2744;+ optional LoginResponse login_response = 2745;+}++// ---------------------------------------------------------------------------+// Shared scalar/helper messages+// ---------------------------------------------------------------------------++message StringEntry {+ optional string key = 1;+ optional string value = 2;+}++message StringMap {+ repeated StringEntry entry = 1;+}++message Coordinate {+ optional int32 lon_times1000000 = 101;+ optional int32 lat_times1000000 = 102;+}++// ---------------------------------------------------------------------------+// Top-level enums+// ---------------------------------------------------------------------------++enum DeviceType {+ UNKNOWN_DEVICE_TYPE = 0;+ SYMBIAN_NO_TOUCH_SCREEN_DEVICE = 10;+ SYMBIAN_TOUCH_SCREEN_DEVICE = 11;+ IPHONE_DEVICE = 21;+ CE_NO_TOUCH_SCREEN_DEVICE = 30;+ CE_TOUCH_SCREEN_DEVICE = 31;+ ANDROID_DEVICE = 50;+ WP8_DEVICE = 80;+ LINUX_DEVICE = 90;+ WEB = 100;+}++enum AppType {+ UNKNOWN_APP_TYPE = 0;+ WAZE = 1;+ RIDER = 2;+ BROADCAST = 3;+ WAZE_BUILT_IN_DISPLAY = 4;+ WAZE_BUILT_IN_DISPLAY_PHONE = 5;+ WAZE_BUILT_IN_DISPLAY_CARPLAY = 6;+ WEB_CLIENT = 7;+ CARPOOL_ALERTS_ORCHESTRATOR = 8;+ WAZE_ANDROID_AUTOMOTIVE_OS = 9;+}++enum AppFlavor {+ UNKNOWN_APP_FLAVOR = 0;+ RELEASE = 1;+ FISHFOOD = 2;+ DOGFOOD = 3;+ PRE_BETA = 4;+ ALPHA = 5;+ DEV = 6;+ ONEOFF = 7;+ BETA = 8;+}++enum ClientApiType {+ UNKNOWN_CLIENT_API = 0;+ TRANSPORT = 1;+ AUDIO = 2;+}++enum SegmentDirection {+ SEGMENT_DIRECTION_UNSPECIFIED = 0;+ SEGMENT_DIRECTION_FORWARD = 1;+ SEGMENT_DIRECTION_BACKWARD = 2;+ SEGMENT_DIRECTION_BOTH = 3;+}++enum AlertType {+ UNKNOWN_TYPE = 0;+ CHIT_CHAT = 1;+ POLICE = 2;+ ACCIDENT = 3;+ JAM = 4;+ TRAFFIC_INFO = 5;+ HAZARD = 6;+ MISC = 7;+ CONSTRUCTION = 8;+ PARKING = 9;+ DYNAMIC = 10;+ CAMERA = 11;+ __NOT_IN_USE__PARKED = 12;+ ROAD_CLOSED = 13;+ SYSTEM_ROAD_CLOSED = 14;+ UNKNOWN_ALERT = 15;+ SOS = 16;+ CRASH_PRONE = 17;+ TURN_CLOSED = 19;+ NEW_BAD_WEATHER = 100;+ NEW_LANE_CLOSED = 101;+ PERMANENT_HAZARD = 103;+ PERSONAL_SAFETY = 104;+}++enum AlertSubType {+ NO_SUBTYPE = 0;+ POLICE_VISIBLE = 201;+ POLICE_HIDING = 202;+ POLICE_WITH_MOBILE_CAMERA = 203;+ ACCIDENT_MINOR = 301;+ ACCIDENT_MAJOR = 302;+ JAM_MODERATE_TRAFFIC = 401;+ JAM_HEAVY_TRAFFIC = 402;+ JAM_STAND_STILL_TRAFFIC = 403;+ JAM_LIGHT_TRAFFIC = 404;+ HAZARD_ON_ROAD = 601;+ HAZARD_ON_SHOULDER = 602;+ HAZARD_WEATHER = 603;+ HAZARD_ON_ROAD_OBJECT = 604;+ HAZARD_ON_ROAD_POT_HOLE = 605;+ HAZARD_ON_ROAD_ROAD_KILL = 606;+ HAZARD_ON_SHOULDER_CAR_STOPPED = 607;+ HAZARD_ON_SHOULDER_ANIMALS = 608;+ HAZARD_ON_SHOULDER_MISSING_SIGN = 609;+ HAZARD_WEATHER_FOG = 610;+ HAZARD_WEATHER_HAIL = 611;+ HAZARD_WEATHER_HEAVY_RAIN = 612;+ HAZARD_WEATHER_HEAVY_SNOW = 613;+ HAZARD_WEATHER_FLOOD = 614;+ HAZARD_WEATHER_MONSOON = 615;+ HAZARD_WEATHER_TORNADO = 616;+ HAZARD_WEATHER_HEAT_WAVE = 617;+ HAZARD_WEATHER_HURRICANE = 618;+ HAZARD_WEATHER_FREEZING_RAIN = 619;+ HAZARD_ON_ROAD_LANE_CLOSED = 620;+ HAZARD_ON_ROAD_OIL = 621;+ HAZARD_ON_ROAD_ICE = 622;+ HAZARD_ON_ROAD_CONSTRUCTION = 623;+ HAZARD_ON_ROAD_CAR_STOPPED = 624;+ HAZARD_ON_ROAD_TRAFFIC_LIGHT_FAULT = 625;+ HAZARD_ON_ROAD_EMERGENCY_VEHICLE = 626;+ __NOT_IN_USE__PARKED_ON = 1201;+ __NOT_IN_USE__PARKED_OFF = 1202;+ ROAD_CLOSED_HAZARD = 1301;+ ROAD_CLOSED_CONSTRUCTION = 1302;+ ROAD_CLOSED_EVENT = 1303;+ SOS_FLAT_TIRE = 1601;+ SOS_NO_FUEL = 1602;+ SOS_MEDICAL_HELP = 1603;+ SOS_MECHANICAL_PROBLEM = 1604;+ SOS_OTHER = 1605;+ SOS_BATTERY_ISSUE = 1606;+ CRASH_PRONE_SHORT_ALERT_LENGTH = 1701;+ CRASH_PRONE_LONG_ALERT_LENGTH = 1702;+ TURN_CLOSED_EVENT = 1901;+ BAD_WEATHER_DEFAULT = 2000;+ BAD_WEATHER_SLIPPERY_ROAD = 2001;+ LANE_CLOSURE_BLOCKED_LANES = 2002;+ LANE_CLOSURE_LEFT_LANE = 2003;+ LANE_CLOSURE_RIGHT_LANE = 2004;+ LANE_CLOSURE_CENTER_LANE = 2005;+ PERMANENT_HAZARD_SPEED_BUMP = 3001;+ PERMANENT_HAZARD_TOPES = 3002;+ PERMANENT_HAZARD_TOLL_BOOTH = 3003;+ PERMANENT_HAZARD_DANGEROUS_CURVE = 3004;+ PERMANENT_HAZARD_DANGEROUS_INTERSECTION = 3005;+ PERMANENT_HAZARD_DANGEROUS_SPLIT = 3006;+ PERMANENT_HAZARD_DANGEROUS_MERGE = 3007;+ PERMANENT_HAZARD_SCHOOL_ZONE = 3008;+ DEFAULT_PERSONAL_SAFETY = 4001;+ DEFAULT_CAMERA = 5001;+}++// ---------------------------------------------------------------------------+// ClientInfo (most failure-prone for register/login handshakes)+// ---------------------------------------------------------------------------++message ClientInfo {+ // Nested per generated source: WazeProtocol.ClientInfo.ClientApi+ message ClientApi {+ optional ClientApiType type = 1;+ optional string package_name = 2;+ }++ enum Environment {+ STAGING = 1;+ AUTOPUSH = 2;+ PRODUCTION = 3;+ }++ optional int32 protocol = 1;+ optional string device = 2;+ optional string client_version = 3;+ optional Coordinate last_position = 4;+ optional string manufacturer = 5;+ optional string model = 6;+ optional string name = 7;+ optional int32 width = 8;+ optional int32 height = 9;+ optional string application_type = 10;+ optional string os_version = 11;+ optional int32 applicatin_mode_bitmap = 12;+ optional StringMap client_ab_tests = 13;+ optional bool return_text = 14;+ optional bool simulated = 15;+ optional string locale = 16;+ optional string installation_id = 17;+ optional DeviceType device_type = 18;+ optional AppType app_type = 19;+ repeated ClientApi client_api = 20;+ optional Environment environment = 21;+ optional StringMap debug_options = 22;+ optional string user_agent = 23;+ repeated Display display = 24;+ optional string os_language_id = 25;+ optional string session_uuid = 26;+ optional bool is_jailbroken = 27;+ optional int64 current_time_millis = 28;+ optional string device_brand = 29;+ optional bool is_24_hour_format = 30;+ optional AppFlavor app_flavor = 31;+}++message Display {+ enum Type {+ UNKNOWN = 1;+ BUILT_IN = 2;+ CARPLAY = 3;+ ANDROID_AUTO = 4;+ SMART_DEVICE_LINK = 5;+ WEB_LINK = 6;+ PIONEER = 7;+ WEB = 8;+ }+ optional Type type = 1;+ optional int32 width = 2;+ optional int32 height = 3;+}++message ReportAdsSettings {+ optional string advertising_id = 1;+ optional bool opted_out_of_tracking = 2;+}++// ---------------------------------------------------------------------------+// Registration+// ---------------------------------------------------------------------------++// NOTE: Register carries only `code`; the username/password live in+// RegisterSuccessful (the server response).+message Register {+ optional string code = 1;+}++message RegisterSuccessful {+ optional string username = 1;+ optional string password = 2;+ optional string token = 3;+ optional int64 user_id = 4;+}++// ---------------------------------------------------------------------------+// Login+// ---------------------------------------------------------------------------++message PasswordCredential {+ optional string username = 1;+ optional string password = 2;+}++message TokenCredential {+ optional string token = 1;+}++message LoginRequest {+ enum LoginReason {+ NORMAL = 0;+ SIGN_IN = 1;+ }+ enum ExcludedLoginResponse {+ FORMAT_UNSPECIFIED = 0;+ USER_PROFILE = 1;+ LOGIN_ENCOURAGEMENT = 2;+ GET_MEETINGS = 3;+ CONSENT = 4;+ POINTS = 6;+ }+ oneof credential {+ PasswordCredential password_credential = 1;+ TokenCredential token_credential = 2;+ }+ optional LoginReason reason = 3;+ optional bool logout_other_devices = 4 [default = true];+ repeated ExcludedLoginResponse excluded_login_responses = 5;+}++message LoginSuccess {+ optional int64 server_session_id = 1;+ optional string global_user_id = 2;+ optional string secret_key = 3;+ optional string session_id = 4;+}++message LoginError {+ enum AuthErrorType {+ UNKNOWN_ERROR = 0;+ WRONG_USER_PASSWORD = 1;+ INTERNAL_ISSUES = 2;+ NOT_AUTHORIZED = 3;+ REFRESH_TOKEN = 4;+ ANOTHER_DEVICE_LOGGED_IN = 5;+ INVALID_TOKEN = 6;+ UNAUTHENTICATED_TOKEN = 7;+ TOKEN_QUOTA_EXCEEDED = 8;+ APP_VERSION_NOT_SUPPORTED = 9;+ }+ optional int64 reason = 1;+ optional AuthErrorType error_type = 2;+ // Omitted: another_device_logged_in_details=3, app_version_not_supported_details=4,+ // internal_issues_details=5 (detail sub-messages, not needed for fetch path).+}++message LoginResponse {+ oneof response {+ LoginSuccess login_success = 1;+ LoginError login_error = 2;+ }+}++// ---------------------------------------------------------------------------+// Auth header helpers referenced by Element+// ---------------------------------------------------------------------------++message UID {+ optional int64 id = 1;+ optional string secret_key = 2;+ optional int32 protocol = 3;+}++// ---------------------------------------------------------------------------+// Alert FETCH payloads+// ---------------------------------------------------------------------------++message AddAlertAction {+ optional RealtimeAlert realtime_alert = 1;+}++message RealtimeAlert {+ optional int64 id = 1;+ optional AlertInfo alert_info = 2;+ optional AlertReportingInfo alert_reporting_info = 3;+ // Field 4 is not present in this protocol version.+ optional bool notify_alerter_shown = 5;+ optional string alert_uuid = 6;+ optional string alerter_shown_token = 7;+}++message AlertInfo {+ optional AlertType type = 1;+ optional AlertSubType sub_type = 2;+ optional Coordinate position = 3;+ // Omitted: segment_direction_id = 4 (SegmentNodes sub-message).+ optional SegmentDirection seg_direction = 5;+ optional int32 azymuth = 6;+ optional bool on_route = 7;+ optional int32 priority = 8;+ // Omitted: alert_details = 9 (large AlertDetails sub-tree).+}++message AlertReportingInfo {+ optional int64 primary_alert_id = 1;+ optional int32 kind = 2;+ optional string description = 3;+ optional int64 report_time = 4;+ optional string reporter_username = 5;+ optional bool current_user_is_reporter = 6;+ optional string report_image_id = 7;+ optional AlertAddress alert_address = 8;+ optional int32 thumbs_up_count = 9;+ optional bool current_user_thumbed_up = 10;+ optional int32 seconds_to_report = 11;+ optional bool should_ping_user = 12;+ optional bool archive = 13;+ // Omitted: beep_info=14, comment_info=15, chat_info=16, alert_source_info=17+ // (sub-messages, not needed for the fetch path).+}++message AlertAddress {+ optional string location_near_by_report = 1;+ optional string street = 2;+ optional string city = 3;+}++// ---------------------------------------------------------------------------+// Server bookkeeping members referenced by Element (minimal stubs).+// Field numbers preserved; bodies kept empty so they parse as opaque and are+// skipped, since the fetch path never reads them.+// ---------------------------------------------------------------------------++message ServerError {+ optional int32 code = 10101;+ optional string description = 10102;+ optional string request_id = 10103;+ optional string command_name = 10105;+ optional string service_name = 10106;+ optional string exception_type = 10107;+ optional string exception_detail = 10108;+}++// Referenced by Element (fields 2150, 2225, 2384). Bodies intentionally left+// empty: the fetch path does not read their contents, and an empty proto2+// message parses any wire bytes as unknown fields, preserving compatibility.+message ResponseTimestamp {}+message LoginSuccessful {}+message AT {}++// ---------------------------------------------------------------------------+// Alert REPORTING (write) path (plain int32/int64/enum/double/message, no+// zig-zag). Built by WazeReportCodec.+// ---------------------------------------------------------------------------++message CoordinateWithAlt {+ optional int32 lon_times1000000 = 101;+ optional int32 lat_times1000000 = 102;+ optional int32 alt_times1000000 = 103;+}++message SegmentNodes {+ optional int64 from_node = 1;+ optional int64 to_node = 2;+}++message GpsPosition {+ optional CoordinateWithAlt coordinate = 1;+ optional double horizontal_accuracy_meters = 2;+ optional int64 time_epoch_ms = 3;+}++message UserPosition {+ optional GpsPosition gps_position = 1;+ optional SegmentNodes segment_nodes = 2;+}++message Timestamp {+ optional int64 seconds = 1;+ optional int32 nanos = 2;+}++enum ReportingManner {+ REPORTING_MANNER_UNSPECIFIED = 0;+ REPORTING_MANNER_DEFAULT = 1;+ REPORTING_MANNER_VOICE = 2;+ REPORTING_MANNER_VOICE_CONVERSATION = 3;+}++enum PoliceAlertSubType {+ POLICE_UNSPECIFIED = 0;+ POLICE_DEFAULT = 1;+ POLICE_HIDDEN_REPORT = 2;+ POLICE_MOBILE_CAMERA = 3;+}+message PoliceDetails { optional PoliceAlertSubType type = 1; }++enum CrashReportSubType {+ CRASH_REPORT_UNSPECIFIED = 0;+ CRASH_REPORT_DEFAULT = 1;+ CRASH_REPORT_PILE_UP = 2;+ CRASH_REPORT_MAJOR = 3;+ CRASH_REPORT_MINOR = 4;+}+message CrashDetails { optional CrashReportSubType type = 1; }++enum TrafficReportSubType {+ TRAFFIC_REPORT_UNSPECIFIED = 0;+ TRAFFIC_REPORT_DEFAULT = 1;+ TRAFFIC_REPORT_STANDSTILL = 2;+ TRAFFIC_REPORT_LIGHT = 3;+ TRAFFIC_REPORT_MODERATE = 4;+ TRAFFIC_REPORT_HEAVY = 5;+}+message TrafficDetails { optional TrafficReportSubType type = 1; }++enum HazardReportSubType {+ HAZARD_REPORT_UNSPECIFIED = 0;+ HAZARD_REPORT_DEFAULT = 1;+ HAZARD_REPORT_CONSTRUCTION = 2;+ HAZARD_REPORT_VEHICLE_STOPPED = 3;+ HAZARD_REPORT_OBJECT_ON_ROAD = 4;+ HAZARD_REPORT_POTHOLE = 5;+ HAZARD_REPORT_BROKEN_TRAFFIC_LIGHT = 6;+ HAZARD_REPORT_OIL = 7;+ HAZARD_REPORT_ANIMALS = 8;+ HAZARD_REPORT_MISSING_SIGN = 9;+ HAZARD_REPORT_ROAD_KILL = 10;+ HAZARD_REPORT_SHOULDER = 11;+ HAZARD_REPORT_SHOULDER_VEHICLE_STOPPED = 12;+ HAZARD_REPORT_EMERGENCY_VEHICLE = 13;+}+message HazardOnRoadDetails { optional HazardReportSubType type = 1; }++message AlertDetails {+ oneof details {+ TrafficDetails traffic = 1;+ PoliceDetails police = 2;+ CrashDetails crash = 3;+ HazardOnRoadDetails hazard_on_road = 4;+ }+}++message AddUserReportedAlertRequest {+ optional UserPosition user_position = 1;+ optional int32 azymuth = 2;+ optional AlertDetails alert_details = 3;+ optional SegmentDirection segment_direction = 4;+ optional Timestamp report_time = 5;+ optional bool is_offline_delayed_report = 6;+ optional ReportingManner reporting_manner = 7;+}++message AddUserReportedAlertResponse {+ enum AddAlertStatus {+ STATUS_UNSPECIFIED = 0;+ SUCCESS = 1;+ FAILURE = 2;+ }+ optional AddAlertStatus status = 1;+ optional int32 received_points_count = 2;+ optional int64 client_alert_id = 3;+ optional AlertDetails alert_details = 4;+ optional string alert_uuid = 5;+}diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xmlindex 765d106..64f94ca 100644--- a/app/src/main/res/layout/activity_main.xml+++ b/app/src/main/res/layout/activity_main.xml@@ -157,12 +157,19 @@android:layout_height="0dp"android:layout_weight="1">- <androidx.recyclerview.widget.RecyclerView- android:id="@+id/recyclerView"+ <!-- 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"- android:clipToPadding="false"- android:paddingBottom="8dp" />+ 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><com.rfsentinel.app.ui.RadarViewandroid:id="@+id/radarView"diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xmlindex 28495db..bf953c1 100644--- a/app/src/main/res/menu/menu_main.xml+++ b/app/src/main/res/menu/menu_main.xml@@ -12,6 +12,8 @@android:icon="@drawable/ic_car_volume"android:title="Mute alerts"app:showAsAction="ifRoom" />+ <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" />diff --git a/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt b/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.ktindex 4cc0ba4..55ffcfd 100644--- a/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt@@ -68,10 +68,10 @@ class GnssAnalyzerTest {@Testfun clockSkewAndImpossibleJumps() {val a = GnssAnalyzer()- assertTrue(a.onFix(GnssAnalyzer.Fix(1_000_000, 1_000_000, 45.0, -73.0, 5f)).isEmpty())- val jump = a.onFix(GnssAnalyzer.Fix(1_002_000, 1_002_000, 46.0, -73.0, 5f)) // ~111 km in 2 s+ assertTrue(a.onFix(GnssAnalyzer.Fix(1_000_000, 1_000_000, 10.0, -20.0, 5f)).isEmpty())+ val jump = a.onFix(GnssAnalyzer.Fix(1_002_000, 1_002_000, 11.0, -20.0, 5f)) // ~111 km in 2 sassertEquals("jump", jump.single().key)- val skew = a.onFix(GnssAnalyzer.Fix(1_004_000 + 3_600_000, 1_004_000, 46.0, -73.0, 5f))+ val skew = a.onFix(GnssAnalyzer.Fix(1_004_000 + 3_600_000, 1_004_000, 11.0, -20.0, 5f))assertTrue(skew.any { it.key == "time" })}}diff --git a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.ktindex b543b4f..6beda23 100644--- a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt+++ b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt@@ -11,10 +11,10 @@ import org.junit.Testclass OnlineSourcesTest {private val feed = """{"now":1,"aircraft":[- {"hex":"a27635","flight":"N258LE ","r":"N258LE","t":"OH58","lat":45.10,"lon":-73.10,"alt_baro":1200,"gs":90.0,"track":10.0},- {"hex":"ab6800","flight":"JBU698","r":"N834JB","t":"A320","ownOp":"JETBLUE AIRWAYS","lat":45.12,"lon":-73.11,"alt_baro":"ground"},- {"hex":"c0ffee","r":"N1PD","t":"B407","ownOp":"CITY OF SPRINGFIELD POLICE DEPARTMENT","lat":45.11,"lon":-73.12,"alt_baro":800},- {"hex":"000001","lat":45.0}+ {"hex":"a27635","flight":"N258LE ","r":"N258LE","t":"OH58","lat":10.10,"lon":-20.10,"alt_baro":1200,"gs":90.0,"track":10.0},+ {"hex":"ab6800","flight":"JBU698","r":"N834JB","t":"A320","ownOp":"JETBLUE AIRWAYS","lat":10.12,"lon":-20.11,"alt_baro":"ground"},+ {"hex":"c0ffee","r":"N1PD","t":"B407","ownOp":"CITY OF SPRINGFIELD POLICE DEPARTMENT","lat":10.11,"lon":-20.12,"alt_baro":800},+ {"hex":"000001","lat":10.0}]}"""@Test@@ -48,31 +48,67 @@ class OnlineSourcesTest {val orbit = PoliceAircraft.LoiterTracker()var circling = falsefor (i in 0..12) { // a full turn every 4 minutes, 1 fix a minute, staying put- val p = base.copy(trackDeg = (i * 90.0) % 360, lat = 45.10 + 0.002 * (i % 2), lon = -73.10)+ val p = base.copy(trackDeg = (i * 90.0) % 360, lat = 10.10 + 0.002 * (i % 2), lon = -20.10)circling = orbit.update(p, i * 60_000L)}assertTrue(circling)val straight = PoliceAircraft.LoiterTracker()var flagged = false- for (i in 0..12) flagged = straight.update(base.copy(trackDeg = 10.0, lat = 45.10 + 0.02 * i), i * 60_000L)+ for (i in 0..12) flagged = straight.update(base.copy(trackDeg = 10.0, lat = 10.10 + 0.02 * i), i * 60_000L)assertFalse(flagged)}@Testfun wazeParsingAndScore() {val json = """{"data":{"alerts":[- {"alert_id":"a1","type":"POLICE","latitude":45.0,"longitude":-73.0,"publish_datetime_utc":"2026-10-05T12:00:00.000Z","street":"Main St","num_thumbs_up":2},- {"alert_id":"a2","type":"ACCIDENT","latitude":45.0,"longitude":-73.0}]}}"""+ {"alert_id":"a1","type":"POLICE","latitude":10.0,"longitude":-20.0,"publish_datetime_utc":"2026-10-05T12:00:00.000Z","street":"Main St","num_thumbs_up":2},+ {"alert_id":"a2","type":"ACCIDENT","latitude":10.0,"longitude":-20.0}]}}"""val r = WazePolice.parse(json).single()assertEquals("a1", r.id)- assertEquals(74, WazePolice.score(50.0, 0, 2)) // close, fresh, confirmed- assertEquals(40, WazePolice.score(2_000.0, 0, 0)) // edge of the search box- assertEquals(58, WazePolice.score(100.0, WazePolice.MAX_AGE_MS, 0)) // 45 min old- val hit = WazePolice.hit(r, 45.0, -73.0, r.publishedMs!! + 5 * 60_000L)!!.first+ assertEquals(94, WazePolice.score(50.0, 0, 2)) // close, fresh, confirmed+ assertEquals(70, WazePolice.score(2_000.0, 0, 0)) // edge of the search box+ assertEquals(82, WazePolice.score(100.0, WazePolice.MAX_AGE_MS, 0)) // 45 min old+ val hit = WazePolice.hit(r, 10.0, -20.0, r.publishedMs!! + 5 * 60_000L)!!.firstassertEquals(Category.POLICE_REPORT, hit.category)assertTrue(hit.evidence.contains("5 min ago on Main St"))}+ @Test+ fun wazeDirectAlertIsScoredWithThumbsUp() {+ val a = com.rfsentinel.app.online.wazert.WazeRtFetcher.PoliceAlert("u1", "", 10.0, -20.0, 1_000_000L, 3, "POLICE")+ val r = WazePolice.fromDirect(a)+ val hit = WazePolice.hit(r, 10.0, -20.0, 1_000_000L + 60_000L, WazePolice.VIA_DIRECT)!!.first+ assertEquals(95, hit.confidence) // 90 close, -0.2 decay (1 min), +6 for 3 thumbs up+ assertTrue(hit.evidence.contains("Waze direct"))+ assertTrue(hit.evidence.contains("3 drivers confirmed"))+ }++ @Test+ fun wazeTypesAndRadius() {+ val json = """{"data":{"alerts":[+ {"alert_id":"p","type":"POLICE","latitude":10.0,"longitude":-20.0},+ {"alert_id":"h","type":"HAZARD","latitude":10.0,"longitude":-20.0},+ {"alert_id":"c","type":"ROAD_CLOSED","latitude":10.0,"longitude":-20.0}]}}"""+ assertEquals(listOf("p"), WazePolice.parse(json).map { it.id }) // police only by default+ val picked = setOf(WazePolice.Type.POLICE, WazePolice.Type.HAZARD)+ assertEquals(listOf("p", "h"), WazePolice.parse(json, picked).map { it.id })+ assertTrue(WazePolice.url(10.0, -20.0, 2_000.0, picked).contains("alert_types=POLICE,HAZARD"))+ // A hazard starts lower than police, and a bigger radius keeps a far report alive.+ assertEquals(70, WazePolice.score(50.0, 0, 0, base = WazePolice.Type.HAZARD.baseScore))+ val r = WazePolice.parse(json, picked)[0]+ assertEquals(null, WazePolice.hit(r, 10.04, -20.0, 0L, radiusM = 2_000.0)) // 4.4 km away+ assertTrue(WazePolice.hit(r, 10.04, -20.0, 0L, radiusM = 5_000.0) != null)+ }++ @Test+ fun wazeViewRangeDoesNotChangeTheScore() {+ val r = WazePolice.Report("x", 10.0, -20.0, null, null, null, 0, null)+ val near = WazePolice.hit(r, 10.01, -20.0, 0L, radiusM = 2_000.0, maxM = 5_000.0)!!.first // ~1.1 km+ val wider = WazePolice.hit(r, 10.01, -20.0, 0L, radiusM = 2_000.0, maxM = 20_000.0)!!.first+ assertEquals(near.confidence, wider.confidence) // view range only decides what is kept+ assertEquals(null, WazePolice.hit(r, 10.1, -20.0, 0L, radiusM = 2_000.0, maxM = 5_000.0)) // ~11 km: past the view range+ }+@Testfun cameraScoreFallsWithDistance() {assertEquals(90, KnownCameras.proximityScore(30.0))diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeFeedTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeFeedTest.ktnew file mode 100644index 0000000..b4e7f5a--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazeFeedTest.kt@@ -0,0 +1,70 @@+package com.rfsentinel.app.online++import com.rfsentinel.app.util.Spoken+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class WazeFeedTest {++ private fun report(id: String, type: WazePolice.Type) =+ WazePolice.Report(id, 10.0, 10.0, null, null, null, 0, null, type)++ @Test+ fun screensHearEveryPublishAndStopWhenRemoved() {+ var calls = 0+ val stop = WazePolice.addListener { calls++ }+ val hit = WazePolice.hit(report("a", WazePolice.Type.POLICE), 10.0, 10.0, 0L)!!.first+ WazePolice.publish(listOf(WazePolice.Shown(report("a", WazePolice.Type.POLICE), hit, WazePolice.Where(0.0, "N", null, null))), 5L)+ assertEquals(1, calls)+ assertEquals(1, WazePolice.latest.size)+ assertEquals(5L, WazePolice.latestAt)+ WazePolice.publish(emptyList(), 0L) // a cleared list is a change too+ assertEquals(2, calls)+ assertTrue(WazePolice.latest.isEmpty())+ stop()+ WazePolice.publish(emptyList(), 0L)+ assertEquals(2, calls) // removed: no more calls+ }++ @Test+ fun checkNowIsSpacedOut() {+ WazePolice.lastCheckStartedAt = 0L+ assertNull("none yet: asked at once", WazePolice.requestCheckNow(10, now = 1_000_000L))+ WazePolice.lastCheckStartedAt = 1_000_000L+ assertEquals("3 s after the last: wait 7 more", 7, WazePolice.requestCheckNow(10, now = 1_003_000L))+ assertNull(WazePolice.requestCheckNow(10, now = 1_011_000L))+ assertEquals(1_011_000L, WazePolice.checkNowAt)+ WazePolice.lastCheckStartedAt = 0L+ }++ @Test+ fun aBrokenListenerDoesNotStopTheOthers() {+ var heard = false+ val bad = WazePolice.addListener { throw IllegalStateException("boom") }+ val good = WazePolice.addListener { heard = true }+ WazePolice.publish(emptyList(), 0L)+ bad(); good()+ assertTrue(heard)+ }++ @Test+ fun theSpokenWordNamesTheEventNotAlwaysPolice() {+ fun said(t: WazePolice.Type) = Spoken.shortWord(WazePolice.hit(report("x", t), 10.0, 10.0, 0L)!!.first)+ assertEquals("Waze police", said(WazePolice.Type.POLICE))+ assertEquals("Waze accident", said(WazePolice.Type.ACCIDENT))+ assertEquals("Waze hazard", said(WazePolice.Type.HAZARD))+ assertEquals("Waze road closure", said(WazePolice.Type.ROAD_CLOSED))+ assertEquals("Waze traffic jam", said(WazePolice.Type.JAM))+ }++ @Test+ fun everyEventTypeScoresAboveItsOwnFloorButBelowPolice() {+ val police = WazePolice.score(50.0, 0, 0, base = WazePolice.Type.POLICE.baseScore)+ for (t in WazePolice.Type.entries.filter { it != WazePolice.Type.POLICE }) {+ val s = WazePolice.score(50.0, 0, 0, base = t.baseScore)+ assertTrue("$t $s", s in 50 until police)+ }+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeLogicTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeLogicTest.ktnew file mode 100644index 0000000..b864279--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazeLogicTest.kt@@ -0,0 +1,303 @@+package com.rfsentinel.app.online++import com.rfsentinel.app.online.MotionTracker.State+import com.rfsentinel.app.util.Spoken+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/** Pure logic behind the adaptive checks, the approach trend, the readable report text and the spoken call-outs. */+class MotionTrackerTest {+ /** Degrees of latitude covered in one second at 25 m/s (about 90 km/h). */+ private val northPerSecond = 25.0 / 111_000.0++ @Test+ fun beforeAnyPositionItActsAsDriving() {+ assertEquals(State.MOVING, MotionTracker().state(0L))+ }++ @Test+ fun parkedOnlyAfterNinetySecondsWithinSixtyMetres() {+ val m = MotionTracker()+ for (s in 0..80) m.update(10.0 + (s % 3) * 0.00005, 10.0, 0f, s * 1000L) // wanders about 5 m+ assertEquals(State.MOVING, m.state(80_000L))+ for (s in 81..95) m.update(10.0, 10.0, 0f, s * 1000L)+ assertEquals(State.PARKED, m.state(95_000L))+ }++ @Test+ fun leavingTheSpotEndsParked() {+ val m = MotionTracker()+ for (s in 0..100) m.update(10.0, 10.0, 0f, s * 1000L)+ assertEquals(State.PARKED, m.state(100_000L))+ m.update(10.0 + 200.0 / 111_000.0, 10.0, 5f, 101_000L) // 200 m away+ assertEquals(State.MOVING, m.state(101_000L))+ }++ @Test+ fun fastRoadFromTheFixSpeed() {+ val m = MotionTracker()+ for (s in 0..10) m.update(10.0 + s * northPerSecond, 10.0, 25f, s * 1000L)+ assertEquals(State.FAST, m.state(10_000L))+ }++ @Test+ fun speedIsWorkedOutFromPositionsWhenTheFixHasNone() {+ val m = MotionTracker()+ for (s in 0..10) m.update(10.0 + s * northPerSecond, 10.0, null, s * 1000L)+ assertEquals(State.FAST, m.state(10_000L))+ }++ @Test+ fun walkingPaceIsJustMoving() {+ val m = MotionTracker()+ for (s in 0..120) m.update(10.0 + s * (1.4 / 111_000.0), 10.0, 1.4f, s * 1000L)+ assertEquals(State.MOVING, m.state(120_000L))+ }+}++class WazeTimingTest {+ @Test+ fun withAdaptingOffItIsTheChosenInterval() {+ for (s in State.entries) assertEquals(60, WazeTiming.effectiveS(60, s, true, false))+ }++ @Test+ fun directParkedIsFourTimesSlowerButNeverOverFiveMinutes() {+ assertEquals(240, WazeTiming.effectiveS(60, State.PARKED, true, true))+ assertEquals(300, WazeTiming.effectiveS(90, State.PARKED, true, true))+ assertEquals(300, WazeTiming.effectiveS(300, State.PARKED, true, true))+ assertEquals(60, WazeTiming.effectiveS(15, State.PARKED, true, true))+ }++ @Test+ fun directOnAFastRoadIsTwiceAsOftenButNeverUnderFifteenSeconds() {+ assertEquals(30, WazeTiming.effectiveS(60, State.FAST, true, true))+ assertEquals(15, WazeTiming.effectiveS(30, State.FAST, true, true))+ assertEquals(15, WazeTiming.effectiveS(15, State.FAST, true, true))+ assertEquals(60, WazeTiming.effectiveS(60, State.MOVING, true, true))+ }++ @Test+ fun openWebNinjaOnlySlowsDownBecauseEveryCheckIsBilled() {+ assertEquals(600, WazeTiming.effectiveS(240, State.PARKED, false, true))+ assertEquals(480, WazeTiming.effectiveS(120, State.PARKED, false, true))+ assertEquals(600, WazeTiming.effectiveS(600, State.PARKED, false, true))+ assertEquals(240, WazeTiming.effectiveS(240, State.FAST, false, true))+ assertEquals(180, WazeTiming.effectiveS(180, State.MOVING, false, true))+ }++ @Test+ fun aCheckIsDueFirstThenWhenTheIntervalRunsOutOrWhenAskedForByHand() {+ assertTrue("the very first", WazeTiming.checkDue(1_000L, 0L, 60, false, 10))+ assertFalse(WazeTiming.checkDue(50_000L, 1_000L, 60, false, 10)) // 49 s into 60 s+ assertTrue(WazeTiming.checkDue(61_000L, 1_000L, 60, false, 10)) // 60 s passed+ assertTrue("asked for, well after the last", WazeTiming.checkDue(20_000L, 1_000L, 60, true, 10))+ assertFalse("asked for, too soon after the last", WazeTiming.checkDue(5_000L, 1_000L, 60, true, 10))+ assertFalse("nothing asked, not due", WazeTiming.checkDue(20_000L, 1_000L, 60, false, 10))+ }++ @Test+ fun manualChecksAreSpacedOutAndTheSlidersHaveTheirSteps() {+ assertEquals(10, WazeTiming.minGapS(true))+ assertEquals(60, WazeTiming.minGapS(false))+ assertEquals(listOf(15, 30, 60, 90, 120, 300), WazeTiming.DIRECT_STEPS_S.toList())+ assertEquals(listOf(120, 180, 240, 300, 600), WazeTiming.NINJA_STEPS_S.toList())+ }+}++class WazeTrendTest {+ @Test+ fun needsAFewSecondsOfHistory() {+ val t = WazeTrend()+ t.update("a", 500.0, 0L)+ t.update("a", 400.0, 2_000L)+ assertEquals(WazeTrend.Trend.STEADY, t.trend("a"))+ }++ @Test+ fun closingWhenTheDistanceDropsByFifteenMetresOrMore() {+ val t = WazeTrend()+ t.update("a", 500.0, 0L)+ t.update("a", 480.0, 3_000L)+ t.update("a", 450.0, 5_000L)+ assertEquals(WazeTrend.Trend.CLOSING, t.trend("a"))+ }++ @Test+ fun awayWhenItGrows() {+ val t = WazeTrend()+ t.update("a", 450.0, 0L)+ t.update("a", 500.0, 6_000L)+ assertEquals(WazeTrend.Trend.AWAY, t.trend("a"))+ }++ @Test+ fun smallChangesAreSteady() {+ val t = WazeTrend()+ t.update("a", 500.0, 0L)+ t.update("a", 490.0, 6_000L)+ assertEquals(WazeTrend.Trend.STEADY, t.trend("a"))+ }++ @Test+ fun onlyTheLastTenSecondsCount() {+ val t = WazeTrend()+ t.update("a", 1000.0, 0L)+ t.update("a", 900.0, 5_000L)+ t.update("a", 900.0, 20_000L)+ t.update("a", 900.0, 25_000L) // it was closing early on, but has been still for a while+ assertEquals(WazeTrend.Trend.STEADY, t.trend("a"))+ }++ @Test+ fun forgetsReportsThatAreGone() {+ val t = WazeTrend()+ t.update("a", 500.0, 0L)+ t.update("a", 400.0, 6_000L)+ t.keepOnly(emptySet())+ assertEquals(WazeTrend.Trend.STEADY, t.trend("a"))+ }+}++class WazeWhereTest {+ private fun at(heading: Double?, dLat: Double, dLon: Double) =+ WazePolice.where(10.0, 10.0, heading, 10.0 + dLat, 10.0 + dLon)++ @Test+ fun straightAheadWhenDrivingNorthToAPointNorth() {+ val w = at(0.0, 0.008, 0.0)+ assertEquals("N", w.compass)+ assertEquals(WazePolice.Side.AHEAD, w.side)+ assertEquals(889.6, w.distanceM, 3.0)+ assertFalse(w.isBehind)+ }++ @Test+ fun behindWhenDrivingAwayFromIt() {+ val w = at(0.0, -0.008, 0.0)+ assertEquals("S", w.compass)+ assertEquals(WazePolice.Side.BEHIND, w.side)+ assertTrue(w.isBehind)+ }++ @Test+ fun leftAndRightFollowTheHeading() {+ assertEquals(WazePolice.Side.RIGHT, at(0.0, 0.0, 0.008).side)+ assertEquals("E", at(0.0, 0.0, 0.008).compass)+ assertEquals(WazePolice.Side.LEFT, at(0.0, 0.0, -0.008).side)+ // Heading east: north is now on the left.+ assertEquals(WazePolice.Side.LEFT, at(90.0, 0.008, 0.0).side)+ }++ @Test+ fun withoutAHeadingThereIsNoSideAndNothingIsBehind() {+ val w = at(null, -0.008, 0.0)+ assertNull(w.side)+ assertNull(w.relDeg)+ assertFalse(w.isBehind)+ assertEquals("S", w.compass)+ }++ @Test+ fun behindStartsPastOneHundredDegreesOffTheHeading() {+ // 120 degrees off the heading: still called "to your right", but already counted as behind.+ val w = at(0.0, -0.004, 0.00704)+ assertEquals(WazePolice.Side.RIGHT, w.side)+ assertTrue(w.isBehind)+ // 80 degrees off: not behind.+ assertFalse(at(0.0, 0.001, 0.0057).isBehind)+ }++ @Test+ fun relativeTextSaysWhereAndWhichWay() {+ val ahead = WazePolice.Where(412.0, "NE", WazePolice.Side.AHEAD, 10f)+ assertEquals("412 m NE · ahead · closing in", WazePolice.relativeText(ahead, WazeTrend.Trend.CLOSING))+ assertEquals("412 m NE · ahead · moving away", WazePolice.relativeText(ahead, WazeTrend.Trend.AWAY))+ assertEquals("412 m NE · ahead", WazePolice.relativeText(ahead))+ val behind = WazePolice.Where(412.0, "SW", WazePolice.Side.BEHIND, 170f)+ assertEquals("412 m SW · behind you", WazePolice.relativeText(behind, WazeTrend.Trend.AWAY))+ assertEquals("1.25 km N", WazePolice.relativeText(WazePolice.Where(1250.0, "N", null, null)))+ }+}++class WazeSubtypeTest {+ @Test+ fun knownSubtypesReadNaturally() {+ assertEquals("hiding", WazePolice.subtypeLabel("POLICE_HIDING"))+ assertEquals("visible", WazePolice.subtypeLabel("POLICE_VISIBLE"))+ assertEquals("mobile speed camera", WazePolice.subtypeLabel("POLICE_WITH_MOBILE_CAMERA"))+ assertEquals("major", WazePolice.subtypeLabel("ACCIDENT_MAJOR"))+ assertEquals("standstill", WazePolice.subtypeLabel("JAM_STAND_STILL_TRAFFIC"))+ assertEquals("pothole", WazePolice.subtypeLabel("HAZARD_ON_ROAD_POT_HOLE"))+ assertEquals("heavy rain", WazePolice.subtypeLabel("HAZARD_WEATHER_HEAVY_RAIN"))+ assertEquals("event", WazePolice.subtypeLabel("ROAD_CLOSED_EVENT"))+ }++ @Test+ fun unknownOnesAreTidiedUpAndNoneIsNull() {+ assertEquals("something new", WazePolice.subtypeLabel("HAZARD_SOMETHING_NEW"))+ assertEquals("hiding", WazePolice.subtypeLabel("police_hiding"))+ assertNull(WazePolice.subtypeLabel(null))+ assertNull(WazePolice.subtypeLabel(""))+ assertNull(WazePolice.subtypeLabel("NO_SUBTYPE"))+ }++ @Test+ fun theSubtypeIsInTheLabelAndTheTypeStillResolves() {+ val r = WazePolice.Report("x", 10.0, 10.0, null, null, null, 0, null, WazePolice.Type.POLICE, "POLICE_HIDING")+ val hit = WazePolice.hit(r, 10.0, 10.0, 0L)!!.first+ assertEquals("Police reported on Waze (hiding)", hit.label)+ assertEquals(WazePolice.Type.POLICE, WazePolice.Type.ofHit(hit))+ val plain = WazePolice.hit(r.copy(subtype = null), 10.0, 10.0, 0L)!!.first+ assertEquals("Police reported on Waze", plain.label)+ }++ @Test+ fun ninjaSubtypesAreRead() {+ val json = """{"data":{"alerts":[{"alert_id":"a","type":"POLICE","subtype":"POLICE_HIDING","latitude":10.0,"longitude":10.0}]}}"""+ assertEquals("POLICE_HIDING", WazePolice.parse(json).single().subtype)+ }+}++class WazeSpokenTest {+ @Test+ fun distancesAreSaidInWords() {+ assertEquals("50 meters", Spoken.distanceWords(20.0))+ assertEquals("300 meters", Spoken.distanceWords(310.0))+ assertEquals("950 meters", Spoken.distanceWords(940.0))+ assertEquals("1 kilometer", Spoken.distanceWords(990.0))+ assertEquals("1.2 kilometers", Spoken.distanceWords(1200.0))+ assertEquals("2 kilometers", Spoken.distanceWords(2000.0))+ }++ @Test+ fun theShortCallOutNamesTheEventTheSideAndTheDistance() {+ val police = WazePolice.Type.POLICE+ assertEquals("Police ahead, 800 meters", Spoken.wazePhrase(police, 800.0, WazePolice.Side.AHEAD, true))+ assertEquals("Police, 800 meters", Spoken.wazePhrase(police, 800.0, null, true))+ assertEquals("Accident behind you, 400 meters", Spoken.wazePhrase(WazePolice.Type.ACCIDENT, 400.0, WazePolice.Side.BEHIND, true))+ assertEquals("Hazard on your left, 150 meters", Spoken.wazePhrase(WazePolice.Type.HAZARD, 150.0, WazePolice.Side.LEFT, true))+ }++ @Test+ fun theFullCallOutSaysItIsFromWaze() {+ assertEquals("Police reported on Waze, 800 meters ahead",+ Spoken.wazePhrase(WazePolice.Type.POLICE, 800.0, WazePolice.Side.AHEAD, false))+ assertEquals("Traffic jam reported on Waze, 1.5 kilometers",+ Spoken.wazePhrase(WazePolice.Type.JAM, 1500.0, null, false))+ }+}++class WazeLevelDefaultsTest {+ @Test+ fun policeIsLoudJamsAreSilentTheRestNotifyOnly() {+ assertEquals(WazePolice.Level.LOUD, WazePolice.Type.POLICE.defaultLevel)+ assertEquals(WazePolice.Level.LOUD, WazePolice.Type.ACCIDENT.defaultLevel)+ assertEquals(WazePolice.Level.NOTIFY, WazePolice.Type.HAZARD.defaultLevel)+ assertEquals(WazePolice.Level.NOTIFY, WazePolice.Type.ROAD_CLOSED.defaultLevel)+ assertEquals(WazePolice.Level.LOG, WazePolice.Type.JAM.defaultLevel)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/WazePrefsTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazePrefsTest.ktnew file mode 100644index 0000000..2ddd634--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazePrefsTest.kt@@ -0,0 +1,81 @@+package com.rfsentinel.app.online++import android.app.Application+import com.rfsentinel.app.util.Prefs+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class WazePrefsTest {+ private val ctx get() = RuntimeEnvironment.getApplication()++ @Test+ fun defaultsAreTheShippedBehaviour() {+ assertEquals(2000, Prefs.wazeAlertM(ctx))+ assertEquals(5, Prefs.wazeViewKm(ctx))+ assertEquals(60, Prefs.wazeIntervalS(ctx, direct = true))+ assertEquals(240, Prefs.wazeIntervalS(ctx, direct = false))+ assertEquals(setOf("POLICE"), Prefs.wazeTypes(ctx))+ }++ @Test+ fun savedValuesSnapToTheSliderSteps() {+ Prefs.setWazeAlertM(ctx, 1234)+ assertEquals(1000, Prefs.wazeAlertM(ctx))+ Prefs.setWazeAlertM(ctx, 50)+ assertEquals(100, Prefs.wazeAlertM(ctx)) // never below 100 m+ Prefs.setWazeIntervalS(ctx, true, 20)+ assertEquals(15, Prefs.wazeIntervalS(ctx, true))+ Prefs.setWazeIntervalS(ctx, false, 10)+ assertEquals(120, Prefs.wazeIntervalS(ctx, false)) // OpenWeb Ninja is never polled faster than 2 min+ Prefs.setWazeViewKm(ctx, 99)+ assertEquals(20, Prefs.wazeViewKm(ctx))+ }++ @Test+ fun emptyTypeSetFallsBackToPolice() {+ Prefs.setWazeTypes(ctx, emptySet())+ assertEquals(setOf("POLICE"), Prefs.wazeTypes(ctx))+ Prefs.setWazeTypes(ctx, setOf("POLICE", "HAZARD"))+ assertEquals(setOf("POLICE", "HAZARD"), Prefs.wazeTypes(ctx))+ }++ @Test+ fun theNewSwitchesStartWhereTheyShouldAndRememberTheirChoice() {+ assertTrue("adapting is on by default", Prefs.wazeAdaptive(ctx))+ assertFalse("ahead-only is opt-in", Prefs.wazeAheadOnly(ctx))+ assertTrue("call-outs are on by default", Prefs.wazeApproach(ctx))+ assertFalse(Prefs.wazePaused(ctx))+ Prefs.setWazeAdaptive(ctx, false); Prefs.setWazeAheadOnly(ctx, true); Prefs.setWazeApproach(ctx, false); Prefs.setWazePaused(ctx, true)+ assertFalse(Prefs.wazeAdaptive(ctx)); assertTrue(Prefs.wazeAheadOnly(ctx)); assertFalse(Prefs.wazeApproach(ctx)); assertTrue(Prefs.wazePaused(ctx))+ }++ @Test+ fun eachEventTypeRemembersWhatItsAlertDoes() {+ assertEquals(WazePolice.Level.LOUD, Prefs.wazeLevel(ctx, WazePolice.Type.POLICE))+ assertEquals(WazePolice.Level.LOG, Prefs.wazeLevel(ctx, WazePolice.Type.JAM))+ Prefs.setWazeLevel(ctx, WazePolice.Type.JAM, WazePolice.Level.LOUD)+ Prefs.setWazeLevel(ctx, WazePolice.Type.POLICE, WazePolice.Level.NOTIFY)+ assertEquals(WazePolice.Level.LOUD, Prefs.wazeLevel(ctx, WazePolice.Type.JAM))+ assertEquals(WazePolice.Level.NOTIFY, Prefs.wazeLevel(ctx, WazePolice.Type.POLICE))+ assertEquals("the others are untouched", WazePolice.Level.NOTIFY, Prefs.wazeLevel(ctx, WazePolice.Type.HAZARD))+ }++ @Test+ fun readableLabels() {+ assertEquals("100 m", Prefs.formatRange(100))+ assertEquals("1.5 km", Prefs.formatRange(1500))+ assertEquals("10 km", Prefs.formatRange(10000))+ assertEquals("15 s", Prefs.formatInterval(15))+ assertEquals("90 s", Prefs.formatInterval(90))+ assertEquals("2 min", Prefs.formatInterval(120))+ assertEquals("10 min", Prefs.formatInterval(600))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.ktnew file mode 100644index 0000000..eedfba4--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazeRelativeTest.kt@@ -0,0 +1,38 @@+package com.rfsentinel.app.online++import android.location.Location+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = android.app.Application::class)+class WazeRelativeTest {+ private fun me(bearing: Float? = null, speed: Float? = null) = Location("t").apply {+ latitude = 10.0; longitude = 10.0+ bearing?.let { this.bearing = it }+ speed?.let { this.speed = it }+ }++ @Test+ fun distanceIsExactMetresThenKm() {+ assertEquals("412 m", WazePolice.preciseDistance(412.7))+ assertEquals("1.25 km", WazePolice.preciseDistance(1250.0))+ }++ @Test+ fun directionIsCompassAndAheadWhenDriving() {+ // About 0.9 km due north of the phone.+ val north = WazePolice.relative(me(), 10.008, 10.0)+ assertTrue(north, north.endsWith(" N"))+ assertTrue(north, north.startsWith("8") || north.startsWith("9"))+ // Driving north: it is ahead. Driving south: behind.+ assertTrue(WazePolice.relative(me(0f, 20f), 10.008, 10.0).endsWith("N · ahead"))+ assertTrue(WazePolice.relative(me(180f, 20f), 10.008, 10.0).endsWith("N · behind you"))+ // Driving east: due north is on the left.+ assertTrue(WazePolice.relative(me(90f, 20f), 10.008, 10.0).endsWith("to your left"))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.ktnew file mode 100644index 0000000..312ddf0--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt@@ -0,0 +1,124 @@+package com.rfsentinel.app.online++import android.app.Application+import android.os.Looper+import android.view.View+import android.view.ViewGroup+import android.widget.TextView+import androidx.appcompat.widget.AppCompatSpinner+import androidx.recyclerview.widget.ListAdapter+import androidx.recyclerview.widget.RecyclerView+import com.google.android.material.slider.Slider+import com.rfsentinel.app.MainActivity+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.settings.SettingsActivity+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.DeviceRow+import com.rfsentinel.app.ui.WazeStatusActivity+import com.rfsentinel.app.util.Prefs+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * Opens the screens that carry the Waze controls, so a layout or slider mistake fails here and not on the+ * phone: the Material slider throws when its value does not line up with its steps, and only when measured.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class WazeScreensTest {+ private val ctx get() = RuntimeEnvironment.getApplication()++ @After+ fun tearDown() {+ ScanForegroundService.isRunning = false+ WazePolice.running = false+ WazePolice.publish(emptyList(), 0L)+ }++ private fun allViews(root: View): List<View> {+ val out = ArrayList<View>()+ fun walk(v: View) { out += v; if (v is ViewGroup) for (i in 0 until v.childCount) walk(v.getChildAt(i)) }+ walk(root)+ return out+ }++ private fun wazeOn(direct: Boolean) {+ Prefs.setCategoryEnabled(ctx, Category.POLICE_REPORT, true)+ Prefs.setWazeAccepted(ctx, true)+ Prefs.setWazeDirectAccepted(ctx, true)+ Prefs.setWazeBackend(ctx, if (direct) Prefs.WAZE_DIRECT else Prefs.WAZE_NINJA)+ }++ @Test+ fun settingsBuildsEveryWazeControlForBothSources() {+ for (direct in listOf(false, true)) {+ wazeOn(direct)+ val activity = Robolectric.buildActivity(SettingsActivity::class.java).setup().get()+ val views = allViews(activity.window.decorView)+ val sliders = views.filterIsInstance<Slider>()+ val exactly = View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY)+ val atMost = View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST)+ // Waze alone adds four: alert range, map range, and one interval slider per source.+ assertTrue("sliders: ${sliders.size}", sliders.size >= 4)+ sliders.forEach { it.measure(exactly, atMost) } // throws if a value does not fit its steps+ assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().size)+ val text = views.filterIsInstance<TextView>().joinToString("\n") { it.text }+ assertTrue(text.contains("Alert when a report is within"))+ assertTrue(text.contains("Show reports on the map within"))+ assertTrue(text.contains("Check for new reports every"))+ assertTrue(text.contains("Only alert for reports ahead of me"))+ assertTrue(text.contains("What to alert on, and how loud"))+ activity.finish()+ }+ }++ @Test+ fun theStatusScreenSaysWhatIsSentAndWhen() {+ wazeOn(direct = true)+ ScanForegroundService.isRunning = true+ WazePolice.running = true+ WazeStatus.baseS = 60+ WazeStatus.everyS = 240+ WazeStatus.motion = MotionTracker.State.PARKED+ val activity = Robolectric.buildActivity(WazeStatusActivity::class.java).setup().get()+ shadowOf(Looper.getMainLooper()).idle()+ val text = allViews(activity.window.decorView).filterIsInstance<TextView>().joinToString("\n") { it.text }+ assertTrue(text, text.contains("State: Checking"))+ assertTrue(text, text.contains("Checks every: 4 min (set to 60 s, adapted: you are parked)"))+ assertTrue(text, text.contains("Source: Waze direct"))+ assertTrue(text, text.contains("never your exact position") || text.contains("Sent to Waze: nothing yet"))+ assertTrue(text, text.contains("Pause Waze checks"))+ assertTrue(text, text.contains("Forget Waze account"))+ activity.finish()+ }++ @Test+ fun theMainListPinsAnUrgentWazeReportAboveEverythingElse() {+ wazeOn(direct = true)+ ScanForegroundService.isRunning = true+ val report = WazePolice.Report("r1", 10.0, 10.0, null, null, null, 0, null)+ val hit = WazePolice.hit(report, 10.0, 10.0, 0L)!!.first+ WazePolice.publish(+ listOf(WazePolice.Shown(report, hit, WazePolice.Where(120.0, "N", WazePolice.Side.AHEAD, 5f), WazeTrend.Trend.CLOSING)),+ 1L+ )+ val activity = Robolectric.buildActivity(MainActivity::class.java).setup().get()+ shadowOf(Looper.getMainLooper()).idle()+ val list = activity.findViewById<RecyclerView>(com.rfsentinel.app.R.id.recyclerView)+ @Suppress("UNCHECKED_CAST")+ val rows = (list.adapter as ListAdapter<DeviceRow, *>).currentList+ val first = rows.first()+ assertEquals("Police reported on Waze", first.title)+ assertEquals("120 m N · ahead · closing in", first.subtitle)+ assertTrue("flashing: it is above the alert threshold", first.flashing)+ activity.finish()+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.ktnew file mode 100644index 0000000..6c2d1f3--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/WazeWatchTest.kt@@ -0,0 +1,211 @@+package com.rfsentinel.app.online++import android.app.Application+import android.location.Location+import com.rfsentinel.app.online.WazePolice.Level+import com.rfsentinel.app.online.WazePolice.Type+import com.rfsentinel.app.util.Prefs+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config++/**+ * The checker's second-by-second work: which reports are in view, which deserve an alert (the moment one+ * comes in range, not only at the next check), which are behind you, and when to call out again.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class WazeWatchTest {+ private val ctx get() = RuntimeEnvironment.getApplication()+ private val alerts = ArrayList<OnlineWatch.Alert>()+ private val calls = ArrayList<String>()+ private var here = fix(10.0, 10.0)+ private lateinit var watch: WazeWatch++ private fun fix(lat: Double, lon: Double, bearing: Float? = null, speed: Float? = null) = Location("test").apply {+ latitude = lat+ longitude = lon+ bearing?.let { this.bearing = it }+ speed?.let { this.speed = it }+ }++ /** A report [metersNorth] of the origin (negative: south). */+ private fun report(id: String, metersNorth: Double, type: Type = Type.POLICE) =+ WazePolice.Report(id, 10.0 + metersNorth / 110_574.0, 10.0, null, null, null, 0, null, type)++ @Before+ fun setUp() {+ WazePolice.publish(emptyList(), 0L)+ AmbientThreats.waze = null+ here = fix(10.0, 10.0)+ watch = WazeWatch(ctx, CoroutineScope(Job()), { here }, { alerts += it }, { calls += it })+ }++ @Test+ fun aReportInRangeAlertsOnceAndIsShown() {+ watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals(1, alerts.size)+ val a = alerts[0]+ assertTrue(a.log)+ assertEquals(Level.LOUD, a.level)+ assertEquals("waze:a", a.key)+ assertTrue(a.spoken!!, a.spoken!!.contains("800 meters"))+ assertEquals(1, WazePolice.latest.size)+ watch.evaluate(2_000L, publish = false)+ assertEquals("no second alert for the same report", 1, alerts.size)+ }++ @Test+ fun aReportOutsideTheAlertRangeIsShownAndAlertsWhenYouGetClose() {+ watch.ingest(listOf(report("far", 3_000.0)), WazePolice.VIA_DIRECT, 1_000L) // view range 5 km, alert range 2 km+ assertTrue(alerts.isEmpty())+ assertEquals(1, WazePolice.latest.size)+ here = fix(10.0 + 1_500.0 / 110_574.0, 10.0) // drive 1.5 km towards it, between two checks+ watch.evaluate(2_000L, publish = false)+ assertEquals(1, alerts.size)+ }++ @Test+ fun reportsBehindYouDoNotAlertWhenOnlyAheadCounts() {+ Prefs.setWazeAheadOnly(ctx, true)+ here = fix(10.0, 10.0, bearing = 0f, speed = 10f) // driving north+ watch.ingest(listOf(report("behind", -800.0)), WazePolice.VIA_DIRECT, 1_000L)+ assertTrue(alerts.isEmpty())+ assertTrue("still listed", WazePolice.latest.single().where.isBehind)+ here = fix(10.0, 10.0, bearing = 180f, speed = 10f) // turn round: now it is ahead+ watch.evaluate(2_000L, publish = false)+ assertEquals(1, alerts.size)+ }++ @Test+ fun behindStillAlertsWhenOnlyAheadIsOff() {+ here = fix(10.0, 10.0, bearing = 0f, speed = 10f)+ watch.ingest(listOf(report("behind", -800.0)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals(1, alerts.size)+ }++ @Test+ fun aWeakReportAlertsLaterWhenItClearsTheThreshold() {+ Prefs.setAlertThreshold(ctx, 99)+ watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals("seen and logged at once", 1, alerts.size)+ assertTrue(alerts[0].log)+ Prefs.setAlertThreshold(ctx, 50)+ watch.evaluate(2_000L, publish = false)+ assertEquals(2, alerts.size)+ assertFalse("already logged: only the alert is repeated", alerts[1].log)+ watch.evaluate(3_000L, publish = false)+ assertEquals(2, alerts.size)+ }++ @Test+ fun callsOutAgainAtOneKilometerFiveHundredAndTwoHundredMeters() {+ here = fix(10.0, 10.0, bearing = 0f, speed = 25f)+ watch.ingest(listOf(report("p", 1_500.0)), WazePolice.VIA_DIRECT, 0L)+ assertTrue(alerts.single().spoken!!.contains("ahead"))+ // Drive towards it at 25 m/s for a minute.+ for (t in 1..55) {+ here = fix(10.0 + 25.0 * t / 110_574.0, 10.0, bearing = 0f, speed = 25f)+ watch.evaluate(t * 1_000L, publish = false)+ }+ assertEquals(calls.toString(), 3, calls.size)+ assertTrue(calls.all { it.startsWith("Police ahead, ") })+ assertEquals("only the first sighting alerts", 1, alerts.size)+ }++ @Test+ fun noCallOutsWhenItIsNotGettingCloser() {+ here = fix(10.0, 10.0, bearing = 0f, speed = 25f)+ watch.ingest(listOf(report("p", 1_500.0)), WazePolice.VIA_DIRECT, 0L)+ for (t in 1..30) watch.evaluate(t * 1_000L, publish = false) // standing still+ assertTrue(calls.isEmpty())+ }++ @Test+ fun noCallOutsWhenSwitchedOff() {+ Prefs.setWazeApproach(ctx, false)+ here = fix(10.0, 10.0, bearing = 0f, speed = 25f)+ watch.ingest(listOf(report("p", 1_500.0)), WazePolice.VIA_DIRECT, 0L)+ for (t in 1..55) {+ here = fix(10.0 + 25.0 * t / 110_574.0, 10.0, bearing = 0f, speed = 25f)+ watch.evaluate(t * 1_000L, publish = false)+ }+ assertTrue(calls.isEmpty())+ }++ @Test+ fun jamsAreLoggedOnlyAndNeverTheHeadline() {+ Prefs.setWazeTypes(ctx, setOf("JAM"))+ watch.ingest(listOf(report("j", 500.0, Type.JAM)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals(Level.LOG, alerts.single().level)+ assertNull(AmbientThreats.waze)+ }++ @Test+ fun hazardsDefaultToNotificationOnlyAndPoliceBecomesTheHeadline() {+ Prefs.setWazeTypes(ctx, setOf("POLICE", "HAZARD"))+ watch.ingest(listOf(report("h", 500.0, Type.HAZARD)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals(Level.NOTIFY, alerts.single().level)+ watch.ingest(listOf(report("p", 400.0)), WazePolice.VIA_DIRECT, 2_000L)+ val headline = AmbientThreats.waze+ assertNotNull(headline)+ assertTrue(headline!!.second.label.startsWith("Police reported"))+ }++ @Test+ fun theLevelSetInSettingsIsUsed() {+ Prefs.setWazeLevel(ctx, Type.POLICE, Level.NOTIFY)+ watch.ingest(listOf(report("p", 500.0)), WazePolice.VIA_DIRECT, 1_000L)+ assertEquals(Level.NOTIFY, alerts.single().level)+ }++ @Test+ fun reportsAreDroppedWhenNoCheckHasAnsweredForTooLong() {+ watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 0L)+ assertEquals(1, WazePolice.latest.size)+ watch.evaluate(20 * 60_000L, publish = false)+ assertTrue(WazePolice.latest.isEmpty())+ }++ @Test+ fun screensAreWokenOnlyWhenSomethingTheyShowHasChanged() {+ var wakes = 0+ val stop = WazePolice.addListener { wakes++ }+ try {+ watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 1_000L)+ val afterCheck = wakes+ assertTrue(afterCheck >= 1)+ watch.evaluate(2_000L, publish = false)+ watch.evaluate(3_000L, publish = false)+ assertEquals("nothing changed: no wake-up", afterCheck, wakes)+ here = fix(10.0 + 6_000.0 / 110_574.0, 10.0) // drive away until it leaves the 5 km view+ watch.evaluate(4_000L, publish = false)+ assertTrue("the report left the view", wakes > afterCheck)+ assertTrue(WazePolice.latest.isEmpty())+ } finally {+ stop()+ }+ }++ @Test+ fun distanceAndDirectionFollowYouBetweenChecks() {+ here = fix(10.0, 10.0, bearing = 0f, speed = 10f)+ watch.ingest(listOf(report("a", 800.0)), WazePolice.VIA_DIRECT, 0L)+ val first = WazePolice.latest.single().distanceM+ here = fix(10.0 + 300.0 / 110_574.0, 10.0, bearing = 0f, speed = 10f)+ watch.evaluate(1_000L, publish = false)+ val second = WazePolice.latest.single().distanceM+ assertTrue("$first -> $second", first - second in 290.0..310.0)+ assertEquals(WazePolice.Side.AHEAD, WazePolice.latest.single().where.side)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFetcherTest.kt b/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFetcherTest.ktnew file mode 100644index 0000000..1273e55--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFetcherTest.kt@@ -0,0 +1,63 @@+package com.rfsentinel.app.online.wazert++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.util.Random++/** What position Waze is told, and that the rounding never costs the query its coverage. */+class WazeRtFetcherTest {++ private fun metresLat(deg: Double) = Math.abs(deg) * WazeConstants.M_PER_DEG_LAT++ @Test+ fun everyPointInACellSnapsToTheSameCentre() {+ for (lat in listOf(0.0, 10.0, 45.0, 70.0)) {+ val c = WazeRtFetcher.snapToGrid(lat + 0.0003, 10.0003)+ val east = 400.0 / WazeConstants.mPerDegLon(c[0])+ val north = 400.0 / WazeConstants.M_PER_DEG_LAT+ // 400 m either way from the centre is still inside the ~1 km cell.+ for (dLat in listOf(-north, 0.0, north)) for (dLon in listOf(-east, 0.0, east)) {+ val s = WazeRtFetcher.snapToGrid(c[0] + dLat, c[1] + dLon)+ assertEquals(c[0], s[0], 1e-9)+ assertEquals(c[1], s[1], 1e-9)+ }+ }+ }++ @Test+ fun theRoundingErrorStaysUnderAboutFiveHundredMetres() {+ val rnd = Random(7)+ repeat(2000) {+ val lat = rnd.nextDouble() * 140 - 70+ val lon = rnd.nextDouble() * 340 - 170+ val s = WazeRtFetcher.snapToGrid(lat, lon)+ assertTrue(metresLat(s[0] - lat) <= 500.5)+ assertTrue(Math.abs(s[1] - lon) * WazeConstants.mPerDegLon(s[0]) <= 500.5)+ }+ }++ @Test+ fun theSmallestBoxStillHoldsTheTruePosition() {+ val rnd = Random(11)+ for (radius in listOf(8000.0, 9600.0, 16000.0, 24000.0)) {+ val steps = WazeRtFetcher.boxSteps(radius)+ repeat(500) {+ val lat = rnd.nextDouble() * 120 - 60+ val lon = rnd.nextDouble() * 340 - 170+ val s = WazeRtFetcher.snapToGrid(lat, lon)+ // The query boxes are centred on the rounded point, and each is shrunk to 0.75 before it is sent.+ val box = GeoBoxes.shrinkingBoxes(s[1], s[0], radius, steps).last().let { GeoBoxes.shrink(it, 0.75) }+ assertTrue("lat $lat lon $lon r $radius", lat in box[1]..box[3] && lon in box[0]..box[2])+ }+ }+ }++ @Test+ fun boxCountStopsBeforeTheBoxesGetTooNarrow() {+ assertEquals(1, WazeRtFetcher.boxSteps(1000.0))+ assertEquals(2, WazeRtFetcher.boxSteps(3000.0))+ assertEquals(4, WazeRtFetcher.boxSteps(8000.0))+ assertEquals(5, WazeRtFetcher.boxSteps(24000.0))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFlowTest.kt b/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFlowTest.ktnew file mode 100644index 0000000..db29352--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/online/wazert/WazeRtFlowTest.kt@@ -0,0 +1,212 @@+package com.rfsentinel.app.online.wazert++import android.app.Application+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config+import java.util.Base64+import kotlin.math.abs+import kotlin.math.roundToInt++/**+ * The whole Waze protocol flow against a fake server: register, log in, handshake and the query boxes.+ * It decodes what comes back, and checks every request that goes out: the exact position never does,+ * only the rounded one. (The fake speaks the field numbers of waze.proto; it is not recorded Waze traffic.)+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class WazeRtFlowTest {+ private val ctx get() = RuntimeEnvironment.getApplication()++ // A made-up place: nothing here is anyone's real location.+ private val exactLat = 10.1234567+ private val exactLon = -20.6543211++ private class FakeServer : WazeHttpClient() {+ /** Every request: the URL path and the body as text. */+ val requests = ArrayList<Pair<String, String>>()+ var registrations = 0+ var handshakeAlerts: List<WazeProto.Element> = emptyList()+ /** Elements added to the answer of the very next query box, once. */+ var nextQueryExtras: List<WazeProto.Element> = emptyList()++ private fun batch(vararg els: WazeProto.Element): ByteArray =+ WazeProto.Batch.newBuilder().apply { els.forEach { addElement(it) } }.build().toByteArray()++ private fun filler() = WazeProto.Element.newBuilder().setRequestId(1).build()++ override fun clearCookies() {}++ override fun post(url: String, body: ByteArray, headers: MutableMap<String, String>?): WazeHttpClient.HttpResult {+ val path = url.substringAfter("waze.com")+ requests += path to String(body, Charsets.UTF_8)+ return when (path) {+ WazeConstants.PATH_STATIC -> {+ registrations+++ WazeHttpClient.HttpResult(200, batch(WazeProto.Element.newBuilder().setRegisterSuccessful(+ WazeProto.RegisterSuccessful.newBuilder().setUsername("anon").setPassword("secret")).build()))+ }+ WazeConstants.PATH_LOGIN -> WazeHttpClient.HttpResult(200, batch(WazeProto.Element.newBuilder().setLoginResponse(+ WazeProto.LoginResponse.newBuilder().setLoginSuccess(+ WazeProto.LoginSuccess.newBuilder().setServerSessionId(42).setSecretKey("key").setGlobalUserId("7"))).build()))+ else -> {+ val text = String(body, Charsets.UTF_8)+ if (text.startsWith("SeeMe")) WazeHttpClient.HttpResult(200, batch(filler(), *handshakeAlerts.toTypedArray()))+ else {+ val extras = nextQueryExtras+ nextQueryExtras = emptyList()+ WazeHttpClient.HttpResult(200, batch(filler(), *extras.toTypedArray()))+ }+ }+ }+ }+ }++ private fun alert(uuid: String, type: WazeProto.AlertType, sub: WazeProto.AlertSubType, lat: Double, lon: Double,+ thumbs: Int = 0, street: String = "") =+ WazeProto.Element.newBuilder().setAddAlertAction(+ WazeProto.AddAlertAction.newBuilder().setRealtimeAlert(+ WazeProto.RealtimeAlert.newBuilder().setId(1).setAlertUuid(uuid)+ .setAlertInfo(WazeProto.AlertInfo.newBuilder().setType(type).setSubType(sub)+ .setPosition(WazeProto.Coordinate.newBuilder()+ .setLatTimes1000000((lat * 1e6).roundToInt()).setLonTimes1000000((lon * 1e6).roundToInt())))+ .setAlertReportingInfo(WazeProto.AlertReportingInfo.newBuilder()+ .setReportTime(1_700_000_000L).setThumbsUpCount(thumbs)+ .setAlertAddress(WazeProto.AlertAddress.newBuilder().setStreet(street).setCity("Sampleville")))+ )).build()++ private fun police(uuid: String = "p1") =+ alert(uuid, WazeProto.AlertType.POLICE, WazeProto.AlertSubType.POLICE_HIDING, 10.13, -20.65, 3, "Example St")++ private fun removal(uuid: String) = WazeProto.Element.newBuilder().setOldCommand("RmAlert,$uuid").build()++ @Test+ fun theWholeFlowDecodesAlertsAndNeverSendsTheExactPosition() {+ val server = FakeServer().apply {+ handshakeAlerts = listOf(police(), alert("h1", WazeProto.AlertType.HAZARD, WazeProto.AlertSubType.HAZARD_ON_ROAD_POT_HOLE, 10.13, -20.66))+ }+ val fetcher = WazeRtFetcher(ctx, "na", server)++ val alerts = fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE", "HAZARD"))++ // What came back, decoded.+ assertEquals(listOf("p1", "h1"), alerts.map { it.uuid }.sortedByDescending { it == "p1" })+ val p = alerts.single { it.uuid == "p1" }+ assertEquals("POLICE", p.type)+ assertEquals("POLICE_HIDING", p.subtype)+ assertEquals(3, p.thumbsUp)+ assertEquals("Example St", p.street)+ assertEquals("Sampleville", p.city)+ assertEquals(10.13, p.lat, 1e-6)+ assertEquals(-20.65, p.lon, 1e-6)+ assertEquals(1_700_000_000_000L, p.pubMillis)++ // The shape of the exchange: one account, one login, one handshake, four boxes.+ assertEquals(1, server.registrations)+ assertEquals(1, server.requests.count { it.first == WazeConstants.PATH_LOGIN })+ assertEquals(1, server.requests.count { it.second.startsWith("SeeMe") })+ assertEquals(WazeRtFetcher.boxSteps(8_000.0), server.requests.count { it.second.startsWith("MapDisplayed") })++ // What went out: the rounded position only.+ val snapped = WazeRtFetcher.snapToGrid(exactLat, exactLon)+ assertTrue(abs(snapped[0] - exactLat) > 1e-6 && abs(snapped[1] - exactLon) > 1e-6) // it really was rounded+ for ((_, body) in server.requests) {+ assertFalse("exact latitude in a request", body.contains("10.12345"))+ assertFalse("exact longitude in a request", body.contains("20.65432"))+ for (line in body.lines()) {+ val parts = line.split(",")+ when {+ line.startsWith("Location,") -> {+ assertEquals(snapped[1], parts[1].toDouble(), 1e-9)+ assertEquals(snapped[0], parts[2].toDouble(), 1e-9)+ }+ line.startsWith("MapDisplayed,") -> { // the centre of the box is field 9 (lon) and 10 (lat)+ assertEquals(snapped[1], parts[9].toDouble(), 1e-5)+ assertEquals(snapped[0], parts[10].toDouble(), 1e-5)+ }+ line.startsWith("ProtoBase64,") -> {+ val batch = WazeProto.Batch.parseFrom(Base64.getDecoder().decode(line.removePrefix("ProtoBase64,")))+ for (el in batch.elementList) if (el.hasClientInfo()) {+ val pos = el.clientInfo.lastPosition+ // Rounded to the grid, then blurred by up to 500 m more: never the exact position.+ assertTrue(abs(pos.latTimes1000000 / 1e6 - snapped[0]) * 110_574 <= 501)+ assertTrue(abs(pos.lonTimes1000000 / 1e6 - snapped[1]) * WazeConstants.mPerDegLon(snapped[0]) <= 501)+ }+ }+ }+ }+ }+ }++ @Test+ fun onlyTheWantedTypesComeBack() {+ val server = FakeServer().apply {+ handshakeAlerts = listOf(police(), alert("h1", WazeProto.AlertType.HAZARD, WazeProto.AlertSubType.HAZARD_ON_ROAD, 10.13, -20.66))+ }+ val alerts = WazeRtFetcher(ctx, "na", server).fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE"))+ assertEquals(listOf("p1"), alerts.map { it.uuid })+ }++ @Test+ fun aClearedAlertDisappearsOnTheNextCheck() {+ val server = FakeServer().apply { handshakeAlerts = listOf(police("p1"), police("p2")) }+ val fetcher = WazeRtFetcher(ctx, "na", server)+ assertEquals(setOf("p1", "p2"), fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE")).map { it.uuid }.toSet())+ server.nextQueryExtras = listOf(removal("p1"))+ assertEquals(listOf("p2"), fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE")).map { it.uuid })+ }++ @Test+ fun forgettingTheAccountMakesTheNextCheckRegisterAgain() {+ val server = FakeServer().apply { handshakeAlerts = listOf(police()) }+ val fetcher = WazeRtFetcher(ctx, "na", server)+ fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE"))+ fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE"))+ assertEquals("the account is reused", 1, server.registrations)+ WazeRtFetcher.forgetStoredAccount(ctx)+ fetcher.fetchAlertsNear(exactLat, exactLon, 5_000.0, setOf("POLICE"))+ assertEquals("forgotten: a new one is made", 2, server.registrations)+ }++ @Test+ fun theLoginBlurStaysWithinFiveHundredMetres() {+ val device = DeviceIdentity.random()+ repeat(500) {+ val line = WazeRtCodec.buildClientInfoLine(device, exactLon, exactLat)+ val batch = WazeProto.Batch.parseFrom(Base64.getDecoder().decode(line.removePrefix("ProtoBase64,")))+ val pos = batch.getElement(0).clientInfo.lastPosition+ assertTrue(abs(pos.latTimes1000000 / 1e6 - exactLat) * 110_574 <= 501)+ assertTrue(abs(pos.lonTimes1000000 / 1e6 - exactLon) * WazeConstants.mPerDegLon(exactLat) <= 501)+ }+ }++ /**+ * A response encoded by hand from the field numbers in waze.proto (tools: a few lines of Python, not the+ * generated classes), so renumbering a field breaks this test instead of silently losing alerts.+ * One police alert (west of the prime meridian, so a negative longitude) and one removal.+ */+ @Test+ fun handEncodedBytesDecodeToTheExpectedAlert() {+ val hex = "ca3e53a2a9014f0a4d08b960121b080210ca011a12a8068fae93f6ffffffffff01b006c0f1e904305a1a232080e2cfaa064219120a" ++ "4578616d706c652053741a0b53616d706c6576696c6c6548033206757569642d31ca3e118a7d0e526d416c6572742c757569642d30"+ val bytes = hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+ val batch = WazeProto.Batch.parseFrom(bytes)++ val alert = WazeRtCodec.parseAlerts(batch).single()+ assertEquals("uuid-1", alert.uuid)+ assertEquals("POLICE", alert.type)+ assertEquals("POLICE_HIDING", alert.subtype)+ assertEquals(10.123456, alert.lat, 1e-9)+ assertEquals(-20.654321, alert.lon, 1e-9)+ assertEquals(3, alert.nThumbsUp)+ assertEquals("Example St", alert.street)+ assertEquals("Sampleville", alert.city)+ assertEquals(1_700_000_000_000L, alert.pubMillis)+ assertEquals(listOf("uuid-0"), WazeRtCodec.parseRemovedAlertIds(batch))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.ktnew file mode 100644index 0000000..d25f36e--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/MapStartTest.kt@@ -0,0 +1,194 @@+package com.rfsentinel.app.ui++import android.Manifest+import android.app.Application+import android.location.Location+import android.net.ConnectivityManager+import android.os.Looper+import com.rfsentinel.app.R+import com.rfsentinel.app.service.ScanForegroundService+import com.rfsentinel.app.ui.MapStart.Fix+import com.rfsentinel.app.util.Prefs+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.osmdroid.views.MapView+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/** Where the live map opens: on your area at once, not on open sea until the first GPS fix. */+class MapStartPickTest {+ private val now = 1_000_000L++ @Test+ fun aFreshFixIsWhereYouAreAndIsUsedAsIs() {+ val v = MapStart.pick(listOf(Fix(10.5, 20.5, now - 5_000)), null, null, now)!!+ assertEquals(10.5, v.lat, 1e-9)+ assertEquals(20.5, v.lon, 1e-9)+ assertTrue(v.fresh)+ assertEquals(MapStart.DEFAULT_ZOOM, v.zoom, 0.0)+ }++ @Test+ fun anOldFixStillCentresTheMapButIsNotCurrent() {+ val v = MapStart.pick(listOf(Fix(10.5, 20.5, now - 3 * 3_600_000L)), null, null, now)!!+ assertEquals(10.5, v.lat, 1e-9)+ assertFalse(v.fresh)+ }++ @Test+ fun theNewestFixWinsAmongTheKnownOnes() {+ val old = Fix(1.0, 2.0, now - 600_000)+ val newer = Fix(3.0, 4.0, now - 10_000)+ val v = MapStart.pick(listOf(old, null, newer), null, null, now)!!+ assertEquals(3.0, v.lat, 1e-9)+ }++ @Test+ fun withoutAFixTheLastPlaceTheMapLookedIsUsedAndIsNotCurrent() {+ val v = MapStart.pick(listOf(null, null), 11.0 to 22.0, 15.0, now)!!+ assertEquals(11.0, v.lat, 1e-9)+ assertEquals(22.0, v.lon, 1e-9)+ assertEquals(15.0, v.zoom, 0.0)+ assertFalse(v.fresh)+ }++ @Test+ fun aFixBeatsTheSavedPlaceEvenWhenOld() {+ val v = MapStart.pick(listOf(Fix(5.0, 6.0, now - 86_400_000L)), 11.0 to 22.0, null, now)!!+ assertEquals(5.0, v.lat, 1e-9)+ }++ @Test+ fun nothingKnownMeansNoStartView() {+ assertNull(MapStart.pick(emptyList(), null, null, now))+ assertNull(MapStart.pick(listOf(null), null, 14.0, now))+ }++ @Test+ fun theOriginIsNeverARealStart() {+ assertNull(MapStart.pick(listOf(Fix(0.0, 0.0, now)), 0.0 to 0.0, null, now))+ val v = MapStart.pick(listOf(Fix(0.0, 0.0, now)), 11.0 to 22.0, null, now)!!+ assertEquals("a (0, 0) fix is skipped for the saved place", 11.0, v.lat, 1e-9)+ }++ @Test+ fun theSavedZoomIsKeptOnlyWhenItSuitsAStreetToCityView() {+ fun zoom(z: Double?) = MapStart.pick(listOf(Fix(10.0, 10.0, now)), null, z, now)!!.zoom+ assertEquals(14.0, zoom(14.0), 0.0)+ assertEquals(11.0, zoom(11.0), 0.0)+ assertEquals("zoomed out to look at a country: not worth reopening on", 16.0, zoom(6.0), 0.0)+ assertEquals(16.0, zoom(null), 0.0)+ assertEquals(16.0, zoom(20.0), 0.0)+ }+}++/** The live map screen itself, opened in each situation. Tile downloads are switched off (no network in tests). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class LiveMapOpensTest {+ private val ctx get() = RuntimeEnvironment.getApplication()++ @After+ fun tearDown() {+ ScanForegroundService.setLastFixForTest(null)+ }++ private fun offlineWithLocationPermission(granted: Boolean) {+ shadowOf(ctx.getSystemService(ConnectivityManager::class.java)).setActiveNetworkInfo(null)+ if (granted) shadowOf(ctx).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)+ }++ private fun openMap(): Pair<MapActivity, MapView> {+ val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()+ shadowOf(Looper.getMainLooper()).idle()+ val activity = controller.get()+ return activity to activity.findViewById(R.id.map)+ }++ private fun fix(lat: Double, lon: Double, ageMs: Long) = Location("test").apply {+ latitude = lat; longitude = lon; time = System.currentTimeMillis() - ageMs+ }++ @Test+ fun opensOnTheScansCurrentFixAtStreetZoom() {+ offlineWithLocationPermission(true)+ ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5_000))+ val (activity, map) = openMap()+ assertEquals(10.5, map.mapCenter.latitude, 1e-3)+ assertEquals(20.5, map.mapCenter.longitude, 1e-3)+ assertEquals(MapStart.DEFAULT_ZOOM, map.zoomLevelDouble, 0.0)+ activity.finish()+ }++ @Test+ fun opensOnAnOldFixToo() {+ offlineWithLocationPermission(true)+ ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5 * 3_600_000L))+ val (activity, map) = openMap()+ assertEquals(10.5, map.mapCenter.latitude, 1e-3)+ assertEquals(20.5, map.mapCenter.longitude, 1e-3)+ activity.finish()+ }++ @Test+ fun opensOnTheSavedViewWhenNothingElseIsKnown() {+ offlineWithLocationPermission(true)+ Prefs.setGpsTaggingEnabled(ctx, true)+ Prefs.saveMapView(ctx, 11.0, 22.0, 15.0)+ val (activity, map) = openMap()+ assertEquals(11.0, map.mapCenter.latitude, 1e-3)+ assertEquals(22.0, map.mapCenter.longitude, 1e-3)+ assertEquals(15.0, map.zoomLevelDouble, 0.0)+ activity.finish()+ }++ @Test+ fun opensOnAWorldViewWhenNothingAtAllIsKnown() {+ offlineWithLocationPermission(true)+ val (activity, map) = openMap()+ assertEquals(MapStart.WORLD_ZOOM, map.zoomLevelDouble, 0.0)+ activity.finish()+ }++ @Test+ fun withoutLocationPermissionItStillOpens() {+ offlineWithLocationPermission(false)+ val (activity, map) = openMap()+ assertNotNull(map)+ activity.finish()+ }++ @Test+ fun leavingRemembersTheZoomAlwaysAndThePlaceOnlyWithGpsTagging() {+ offlineWithLocationPermission(true)+ ScanForegroundService.setLastFixForTest(fix(10.5, 20.5, ageMs = 5_000))+ run {+ val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()+ shadowOf(Looper.getMainLooper()).idle()+ controller.pause()+ assertEquals(MapStart.DEFAULT_ZOOM, Prefs.mapZoom(ctx)!!, 0.0)+ assertNull("GPS tagging is off: no place is kept", Prefs.lastMapCenter(ctx))+ controller.destroy()+ }+ Prefs.setGpsTaggingEnabled(ctx, true)+ run {+ val controller = Robolectric.buildActivity(MapActivity::class.java).setup().visible()+ shadowOf(Looper.getMainLooper()).idle()+ controller.pause()+ val saved = Prefs.lastMapCenter(ctx)+ assertNotNull(saved)+ assertEquals(10.5, saved!!.first, 1e-3)+ assertEquals(20.5, saved.second, 1e-3)+ controller.destroy()+ }+ }+}diff --git a/build.gradle.kts b/build.gradle.ktsindex 91748fc..96b19a9 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -3,4 +3,5 @@plugins {id("com.android.application") version "9.4.0" apply falseid("com.google.devtools.ksp") version "2.3.12" apply false+ id("com.google.protobuf") version "0.10.0" apply false}diff --git a/docs/index.html b/docs/index.htmlindex c9ca5ca..192e3e7 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.15.3", "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.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></head><body><a class="skip" href="#main">Skip to content</a>@@ -76,7 +76,7 @@<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups</td></tr><tr><td>Action & hidden cameras <i>(optional)</i></td><td>GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO and other action cams; WiFi spy cameras in setup mode (V380, LookCam Pro...)</td><td>Bluetooth company IDs and services, maker prefixes, default camera and setup-hotspot network names</td></tr><tr><td>Police aircraft <i>(online, optional)</i></td><td>Police, sheriff, state patrol, federal and RCMP / provincial police aircraft; unlisted aircraft circling low overhead</td><td>Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries</td></tr>-<tr><td>Waze police reports <i>(online, optional)</i></td><td>Police reported by Waze users within 2 km</td><td>Your own OpenWeb Ninja API key, scored by distance and age; third-party service, at your own risk</td></tr>+<tr><td>Waze reports <i>(online, optional)</i></td><td>Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), inside an alert range you choose</td><td>Your own OpenWeb Ninja API key, or Waze direct (opt-in: sends Waze your IP address and a position rounded to a 1 km grid); scored by distance and age and re-scored every second as you move; third-party service, at your own risk</td></tr></tbody></table></div><p>Every match shows its evidence, its source and a confidence tier: <b>weak</b> (< 50), <b>probable</b> (50-79) or <b>strong</b> (80+). Full rules: <a href="how-it-works.html">how detection works</a> and the <a href="https://github.com/CIS-C0/RFSentinel/blob/main/docs/SIGNATURES.md" rel="noopener">signature reference</a>.</p>@@ -154,7 +154,7 @@<ul><li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li><li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>- <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze police reports through your own OpenWeb Ninja key, at your own risk.</li>+ <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li><li><b>Data leaves the phone only when you export or share it.</b></li></ul><section class="community" aria-label="Community">diff --git a/docs/qa.html b/docs/qa.htmlindex ce780b1..b19ed95 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 police reports through your own OpenWeb Ninja API key, a third-party service 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: 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>@@ -713,7 +713,7 @@<details class="faq" id="data-collected"><summary>What data does it collect?</summary><div>-<p>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 police reports through your own OpenWeb Ninja API key, a third-party service used at your own risk.</p>+<p>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.</p></div></details>diff --git a/docs/sitemap.xml b/docs/sitemap.xmlindex 501f782..b804aaa 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-06</lastmod><priority>1.0</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/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-05</lastmod><priority>0.9</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/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 74e09db..e46ce06 100644--- a/site/pages/index.html+++ b/site/pages/index.html@@ -36,7 +36,7 @@<tr><td>Hacking tools <i>(optional)</i></td><td>Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi, Bluetooth spam floods</td><td>Flipper IDs, Pwnagotchi beacon JSON, default network names, same network name from two makers with mismatched security, bursts of pairing pop-ups</td></tr><tr><td>Action & hidden cameras <i>(optional)</i></td><td>GoPro, Insta360, DJI Osmo, YI, SJCAM, AKASO and other action cams; WiFi spy cameras in setup mode (V380, LookCam Pro...)</td><td>Bluetooth company IDs and services, maker prefixes, default camera and setup-hotspot network names</td></tr><tr><td>Police aircraft <i>(online, optional)</i></td><td>Police, sheriff, state patrol, federal and RCMP / provincial police aircraft; unlisted aircraft circling low overhead</td><td>Community ADS-B feeds (adsb.fi / adsb.lol) matched against ~1,400 law-enforcement airframes from the FAA and Transport Canada registries</td></tr>-<tr><td>Waze police reports <i>(online, optional)</i></td><td>Police reported by Waze users within 2 km</td><td>Your own OpenWeb Ninja API key, scored by distance and age; third-party service, at your own risk</td></tr>+<tr><td>Waze reports <i>(online, optional)</i></td><td>Police reported by Waze users, and any other kind you tick (accidents, hazards, road closures, traffic jams), inside an alert range you choose</td><td>Your own OpenWeb Ninja API key, or Waze direct (opt-in: sends Waze your IP address and a position rounded to a 1 km grid); scored by distance and age and re-scored every second as you move; third-party service, at your own risk</td></tr></tbody></table></div><p>Every match shows its evidence, its source and a confidence tier: <b>weak</b> (< 50), <b>probable</b> (50-79) or <b>strong</b> (80+). Full rules: <a href="how-it-works.html">how detection works</a> and the <a href="{{REPO}}/blob/main/docs/SIGNATURES.md" rel="noopener">signature reference</a>.</p>@@ -114,6 +114,6 @@<ul><li><b>Receive-only.</b> The app never transmits, jams, spoofs or connects to the devices it detects.</li><li><b>No accounts, no cloud, no analytics.</b> Detections live in a local database excluded from cloud backup.</li>- <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze police reports through your own OpenWeb Ninja key, at your own risk.</li>+ <li><b>Network use:</b> OpenStreetMap map tiles and camera data (Overpass API, DeFlock CDN), and in Android Auto, Nominatim search and OSRM routing, only when used. Those servers see your IP and the area or route, never your scans. Two optional sources are off by default: police aircraft (a position rounded to ~1 km goes to the ADS-B feeds adsb.fi / adsb.lol) and Waze reports, either through your own OpenWeb Ninja key or straight from Waze (Waze direct: your IP address and a position rounded to a 1 km grid), at your own risk.</li><li><b>Data leaves the phone only when you export or share it.</b></li></ul>diff --git a/site/pages/qa.html b/site/pages/qa.htmlindex 8eaad80..a67d0ff 100644--- a/site/pages/qa.html+++ b/site/pages/qa.html@@ -673,7 +673,7 @@<details class="faq" id="data-collected"><summary>What data does it collect?</summary><div>-<p>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 police reports through your own OpenWeb Ninja API key, a third-party service used at your own risk.</p>+<p>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.</p></div></details>