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.10.4
CIS-C04ce304add1af
diff --git a/README.md b/README.mdindex 1ace89e..8ad80d7 100644--- a/README.md+++ b/README.md@@ -183,7 +183,19 @@ The app never connects to a device. The details screen shows:in the same colours as the list and radar, placed where your phone was when itssignal was strongest. That approximates the device's position, not a fix: onlyprecise, fresh GPS fixes are used, and the map switches to GPS while it's open.- Tap *All devices* to show flagged ones only.+ Tap *All devices* to show flagged ones only. Devices heard from the same spot+ fan out around it when you zoom in, so every dot can be tapped.+- **Known cameras** (map menu ⋮): *Download nearby cameras* fetches the plate+ readers within ~100 km; *Download Flock* fetches every plate reader mapped in+ the US and Canada (~18 MB, about 143,000, refreshed weekly on Wi-Fi). Both use+ [DeFlock](https://deflock.org)'s hourly snapshot of OpenStreetMap, then add the+ ones it leaves out (other tagging, Flock cameras mapped as ordinary cameras)+ straight from OpenStreetMap. A progress bar shows under the status card, and+ the cameras appear as soon as DeFlock's part is saved. Speed and red-light+ cameras come with the automatic downloads for the area you look at.+- **Screen:** Settings (and the setup wizard) choose whether the screen stays on+ while RF Sentinel is open: *always*, *while charging* (default - car mount,+ desk) or *normal*.- **Record trace** saves your GPS route and every device heard along it. Itkeeps running with the screen off, and can start automatically with each scan.- Traces export as **GPX**, **KML**, **GeoJSON** or **CSV**, with all devices or@@ -338,13 +350,15 @@ Pick a theme in the setup wizard or under **Settings → Appearance**.- **Receive-only.** Nothing is transmitted, jammed, spoofed or connected to.- **No accounts, no cloud, no analytics.** Detections are stored in a localdatabase and excluded from cloud backup.-- **Network use is limited to OpenStreetMap:** map tiles while the map is open,+- **Network use is limited to OpenStreetMap data:** map tiles while the map is open,and the known-camera list for the area you look at on the map (or around you onthe Android Auto camera map), fetched once per area and refreshed weekly, fromoverpass-api.de or the public mirrors overpass.kumi.systems andoverpass.private.coffee when it's busy. Those servers see your IP address andthat area - like the map tiles - never your scans. Turn off *Show known cameras- automatically* in Settings to fetch only when you tap *Download known cameras*.+ automatically* in Settings to fetch only when you tap a download. The camera+ downloads also fetch DeFlock's region files from cdn.deflock.me (it sees which+ 20° region is requested and your IP address, nothing else).In Android Auto, navigation also uses OpenStreetMap's Nominatim (destinationsearch) and the OSRM routing server, only when you search or start a route.Map data © OpenStreetMap contributors (ODbL).@@ -450,7 +464,10 @@ in [Flock You](https://github.com/colonelpanichacks/flock-you) and[Flock-You-Android](https://github.com/MaxwellDPS/Flock-You-Android) and[Fieldwatch](https://github.com/OffGridPete/Fieldwatch) - thank you. Every prefixwas re-checked against its IEEE registrant; see-[docs/SIGNATURES.md](docs/SIGNATURES.md#community-lists-compared-2026-10). The DedSec theme font is Share Tech Mono (SIL Open+[docs/SIGNATURES.md](docs/SIGNATURES.md#community-lists-compared-2026-10). Known+plate-reader locations come from [DeFlock](https://github.com/FoggedLens/deflock)'s+snapshot of OpenStreetMap, mapped by its volunteers (data © OpenStreetMap+contributors, ODbL) - thank you. The DedSec theme font is Share Tech Mono (SIL OpenFont License 1.1). The DedSec theme is an unofficial, original homage andcontains no Ubisoft artwork.diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 6cb522c..d72970d 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -6,8 +6,8 @@ plugins {}// Bump both for every release. versionName ends up in the APK file name.-val appVersionCode = 25-val appVersionName = "2.10.3"+val appVersionCode = 26+val appVersionName = "2.10.4"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.ktindex 9e3bcc2..93a2d08 100644--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt@@ -26,6 +26,7 @@ class RFSentinelApp : Application() {override fun onCreate() {super.onCreate()com.rfsentinel.app.ui.ThemeManager.install(this)+ com.rfsentinel.app.ui.ScreenAwake.install(this)registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {override fun onActivityStarted(a: android.app.Activity) { visibleActivities++ }override fun onActivityStopped(a: android.app.Activity) { visibleActivities = (visibleActivities - 1).coerceAtLeast(0) }@@ -47,6 +48,7 @@ class RFSentinelApp : Application() {appScope.launch { runCatching { com.rfsentinel.app.service.TripRecorder.closeStale(this@RFSentinelApp) } }appScope.launch(Dispatchers.IO) {runCatching { com.rfsentinel.app.alpr.AlprStore.load(this@RFSentinelApp) }+ runCatching { com.rfsentinel.app.alpr.DeflockBulk.refreshIfDue(this@RFSentinelApp) }// A scanner started before the cache loaded (e.g. at boot) must now watch for cameras.if (com.rfsentinel.app.service.ScanForegroundService.isRunning && com.rfsentinel.app.alpr.AlprStore.cameras.isNotEmpty()) {runCatching {diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.ktindex 943ded2..7438b03 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt@@ -168,13 +168,12 @@ object AlprStore {found.size}- private const val STAGGER_MS = 4_000Lprivate const val RETRY_PAUSE_MS = 5_000L/**- * Asks the main server first and each mirror a few seconds later (at once- * if the earlier ones already failed); the first JSON answer wins and the- * others are abandoned. Throws an IOException when every server failed.+ * Asks the main server and every mirror at the same time; the first JSON+ * answer wins and the other requests are cancelled right away (their+ * connections closed). Throws an IOException when every server failed.*/private suspend fun fetchFirst(body: String, status: (String) -> Unit): String {val requests = kotlinx.coroutines.CoroutineScope(Dispatchers.IO + kotlinx.coroutines.SupervisorJob())@@ -184,7 +183,6 @@ object AlprStore {val open = java.util.Collections.synchronizedList(mutableListOf<HttpURLConnection>())ENDPOINTS.forEachIndexed { i, endpoint ->requests.launch {- if (i > 0) kotlinx.coroutines.withTimeoutOrNull(STAGGER_MS * i) { failures.first { it >= i } }if (result.isCompleted) return@launchval host = URL(endpoint).hoststatus("asking $host")@@ -257,13 +255,54 @@ object AlprStore {}}+ /**+ * Swaps in a complete set of plate readers for [boxes] (DeFlock's snapshot):+ * plate-reader nodes inside them are replaced, everything else - speed and+ * red-light cameras, plate readers mapped as ways, other regions - is kept.+ */+ fun mergePlateReaders(context: Context, boxes: List<DoubleArray>, found: List<KnownCamera>) {+ synchronized(this) {+ val merged = mergeCameras(cameras, boxes, found)+ file(context).writeText(gson.toJson(merged))+ cameras = merged+ }+ }++ /**+ * Fetches the plate readers DeFlock's snapshot leaves out for a box (see+ * [KnownCameras.extrasQuery]) from Overpass and adds them. Returns how many.+ */+ suspend fun downloadExtras(context: Context, south: Double, west: Double, north: Double, east: Double): Int =+ withContext(Dispatchers.IO) {+ val body = "data=" + URLEncoder.encode(KnownCameras.extrasQuery(south, west, north, east), "UTF-8")+ val found = KnownCameras.parse(fetchFirst(body) {}).filter { it.type == KnownCamera.Kind.ALPR }+ mergePlateReaders(context, emptyList(), found)+ found.size+ }++ /**+ * Pure part of [mergePlateReaders] (unit-tested): adds the new cameras and+ * updates ones already cached (same OSM id). Nothing is removed - DeFlock's+ * snapshot leaves out some plate readers OpenStreetMap has (no+ * `man_made=surveillance`, mapped as ways, very recent), and the map's area+ * downloads may have fetched those. [boxes] is kept for callers' bookkeeping.+ */+ @Suppress("UNUSED_PARAMETER")+ fun mergeCameras(current: List<KnownCamera>, boxes: List<DoubleArray>, found: List<KnownCamera>): List<KnownCamera> {+ val ids = found.mapTo(HashSet()) { it.osmId }+ return current.filterNot { it.osmId in ids } + found+ }+/** Tests only: set the cache without files or network. */@androidx.annotation.VisibleForTestingfun setForTest(list: List<KnownCamera>) { cameras = list }+ // Synchronized with the merges, so a save that was mid-write can't bring cameras back.+ @Synchronizedfun clear(context: Context) {file(context).delete()areasFile(context).delete()+ com.rfsentinel.app.util.Prefs.setDeflockUpdated(context, 0L)cameras = emptyList()areas = emptyList()}diff --git a/app/src/main/java/com/rfsentinel/app/alpr/DeflockBulk.kt b/app/src/main/java/com/rfsentinel/app/alpr/DeflockBulk.ktnew file mode 100644index 0000000..6d86b3e--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/alpr/DeflockBulk.kt@@ -0,0 +1,257 @@+package com.rfsentinel.app.alpr++import android.content.Context+import android.net.ConnectivityManager+import android.os.Handler+import android.os.Looper+import com.google.gson.JsonParser+import com.rfsentinel.app.BuildConfig+import com.rfsentinel.app.util.Prefs+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.net.HttpURLConnection+import java.net.URL++/**+ * Every plate reader in the US and Canada in one go, from DeFlock's hourly+ * snapshot of OpenStreetMap (`man_made=surveillance` + `surveillance:type=ALPR`+ * nodes, served as 20-degree tiles on cdn.deflock.me). Same data the map gets+ * from Overpass, but complete instead of area by area. Only the tile files are+ * requested - no position is sent. Data © OpenStreetMap contributors, ODbL.+ */+object DeflockBulk {++ private const val INDEX_URL = "https://cdn.deflock.me/regions/index.json"+ /** Refreshed weekly (on Wi-Fi) once you've downloaded it. */+ const val REFRESH_MS = 7 * 24 * 3600_000L++ /**+ * The US (with Alaska) and Canada: south, west, north, east. 20°N keeps the+ * 0-20°N tiles (Central / South America) out; the map's area downloads still+ * cover anywhere else you look.+ */+ val NORTH_AMERICA = doubleArrayOf(20.0, -170.0, 84.0, -52.0)++ data class Index(val regions: List<String>, val tileUrl: String, val tileSizeDeg: Int)++ sealed interface State {+ data object Idle : State+ /** [fraction] of the DeFlock part (by bytes), 0..1. */+ data class Downloading(val done: Int, val total: Int, val found: Int, val fraction: Float = 0f, val detail: String = "") : State+ /** DeFlock's cameras are saved and on the map; OpenStreetMap is being checked for the ones it leaves out. */+ data class CheckingExtras(val cameras: Int) : State+ /** [extrasSkipped]: OpenStreetMap was too busy - those few extras come next time. */+ data class Done(val cameras: Int, val extrasSkipped: Boolean = false) : State+ data class Failed(val reason: String) : State+ }++ /** OpenStreetMap step limit: a busy public server must not hold up the result. */+ private const val EXTRAS_TIMEOUT_MS = 45_000L++ // ---- pure parts (unit-tested) ----++ fun parseIndex(json: String): Index {+ val o = JsonParser.parseString(json).asJsonObject+ return Index(+ regions = o.getAsJsonArray("regions").map { it.asString },+ tileUrl = o.get("tile_url").asString,+ tileSizeDeg = o.get("tile_size_degrees").asInt+ )+ }++ /** The available tiles ("lat/lon" of their south-west corner) that overlap a box. */+ fun tilesFor(index: Index, box: DoubleArray): List<String> {+ val (s, w, n, e) = box.toList()+ val size = index.tileSizeDeg+ return index.regions.filter { key ->+ val (lat, lon) = key.split('/').map { it.toInt() }+ lat < n && lat + size > s && lon < e && lon + size > w+ }+ }++ /** The bounding box of a tile key: south, west, north, east. */+ fun tileBox(key: String, size: Int): DoubleArray {+ val (lat, lon) = key.split('/').map { it.toDouble() }+ return doubleArrayOf(lat, lon, lat + size, lon + size)+ }++ fun tileUrl(index: Index, key: String) = index.tileUrl.replace("{lat}/{lon}", key)++ /** One tile: `[{"id":..,"lat":..,"lon":..,"tags":{..}}, ...]`, all plate readers. */+ fun parseTile(json: String): List<KnownCamera> =+ JsonParser.parseString(json).asJsonArray.mapNotNull { el ->+ val o = el.asJsonObject+ val id = o.get("id")?.asLong ?: return@mapNotNull null+ val lat = o.get("lat")?.asDouble ?: return@mapNotNull null+ val lon = o.get("lon")?.asDouble ?: return@mapNotNull null+ val tags = o.getAsJsonObject("tags")+ fun tag(vararg keys: String) = keys.firstNotNullOfOrNull { k -> tags?.get(k)?.asString?.takeIf { it.isNotBlank() } }+ KnownCamera(+ osmId = "node/$id", lat = lat, lon = lon,+ brand = tag("manufacturer", "surveillance:manufacturer", "brand", "surveillance:brand"),+ operator = tag("operator", "surveillance:operator"),+ direction = KnownCameras.parseDirection(tag("camera:direction", "direction")),+ kind = KnownCamera.Kind.ALPR+ )+ }++ // ---- download ----++ // Lazy: the pure parts above are unit-tested on the JVM, which has no main looper.+ private val scope by lazy { CoroutineScope(Dispatchers.Main + SupervisorJob()) }+ private val main by lazy { Handler(Looper.getMainLooper()) }+ private var job: Job? = null+ private val listeners = mutableSetOf<(State) -> Unit>()++ @Volatile var state: State = State.Idle+ private set++ val isRunning: Boolean get() = job?.isActive == true++ fun observe(listener: (State) -> Unit): () -> Unit {+ listeners += listener+ listener(state)+ return { listeners -= listener }+ }++ private fun set(s: State) = main.post {+ // Progress posted just before a cancel must not show up after it.+ if ((s is State.Downloading || s is State.CheckingExtras) && job?.isActive != true) return@post+ state = s+ listeners.toList().forEach { it(s) }+ }++ /** A square of about [radiusKm] around a point: south, west, north, east. */+ fun boxAround(lat: Double, lon: Double, radiusKm: Double): DoubleArray {+ val dLat = radiusKm / 111.32+ val dLon = radiusKm / (111.32 * kotlin.math.cos(Math.toRadians(lat)).coerceAtLeast(0.05))+ return doubleArrayOf(lat - dLat, lon - dLon, lat + dLat, lon + dLon)+ }++ fun inBox(c: KnownCamera, b: DoubleArray) = c.lat >= b[0] && c.lon >= b[1] && c.lat < b[2] && c.lon < b[3]++ /**+ * Downloads (or refreshes) every plate reader in the US and Canada in the+ * background - or, with [around], only those within ~[radiusKm] of that point+ * (same tiles, filtered: fast, and the rest of the cache is left alone).+ */+ fun start(context: Context, around: Pair<Double, Double>? = null, radiusKm: Double = 100.0) {+ if (job?.isActive == true) return+ val app = context.applicationContext+ val area = around?.let { boxAround(it.first, it.second, radiusKm) }+ job = scope.launch {+ try {+ val index = parseIndex(withContext(Dispatchers.IO) { get(INDEX_URL) })+ val keys = tilesFor(index, area ?: NORTH_AMERICA)+ if (keys.isEmpty()) error(if (area != null) "No plate cameras are mapped around here" else "DeFlock has no tiles for this region")+ var found = 0+ val boxes = ArrayList<DoubleArray>()+ val cams = ArrayList<KnownCamera>()+ // Progress by bytes across all tiles; sizes come from each answer's Content-Length.+ var bytesBefore = 0L+ set(State.Downloading(0, keys.size, 0, 0f, "connecting to DeFlock"))+ keys.forEachIndexed { i, key ->+ val text = withContext(Dispatchers.IO) {+ get(tileUrl(index, key)) { read, total ->+ // Unknown (or compressed, so smaller than what's read) sizes: keep the bar moving.+ val perTile = if (total > 0 && read <= total) total else read + 1_000_000L+ val frac = ((i + read.toFloat() / perTile) / keys.size).coerceIn(0f, 1f)+ set(State.Downloading(i, keys.size, found, frac,+ "region ${i + 1}/${keys.size}: ${mb(bytesBefore + read)} MB"))+ }+ }+ bytesBefore += text.length+ var tile = withContext(Dispatchers.Default) { parseTile(text) }+ if (area != null) tile = tile.filter { inBox(it, area) }+ cams += tile+ boxes += area ?: tileBox(key, index.tileSizeDeg)+ found += tile.size+ set(State.Downloading(i + 1, keys.size, found, (i + 1f) / keys.size, "region ${i + 1}/${keys.size} done"))+ }+ withContext(Dispatchers.IO) { AlprStore.mergePlateReaders(app, boxes, cams) }+ if (area == null) Prefs.setDeflockUpdated(app, System.currentTimeMillis())+ refreshScanner(app)+ // DeFlock's cameras are on the map now. Then the plate readers it leaves out (other+ // tagging, ways, Flock cameras mapped as ordinary cameras), straight from OpenStreetMap -+ // best effort and time-limited, since the public servers are often busy.+ set(State.CheckingExtras(found))+ val b = area ?: NORTH_AMERICA+ val extras = runCatching {+ kotlinx.coroutines.withTimeout(EXTRAS_TIMEOUT_MS) { AlprStore.downloadExtras(app, b[0], b[1], b[2], b[3]) }+ }.onFailure {+ if (it is kotlinx.coroutines.CancellationException && it !is kotlinx.coroutines.TimeoutCancellationException) throw it+ android.util.Log.w("DeflockBulk", "extras skipped: ${it.message}")+ }.getOrNull()+ if (extras != null && extras > 0) refreshScanner(app)+ set(State.Done(found + (extras ?: 0), extrasSkipped = extras == null))+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Exception) {+ android.util.Log.w("DeflockBulk", "download failed: ${e.message}")+ set(State.Failed(when (e) {+ is java.net.UnknownHostException -> "No internet connection"+ is java.net.SocketTimeoutException -> "DeFlock didn't answer in time - try again later"+ else -> "Download failed (${e.message ?: e.javaClass.simpleName})"+ }))+ }+ }+ }++ /** Stops a running download (e.g. the downloaded cameras are being deleted). */+ fun cancel() {+ job?.cancel()+ job = null+ set(State.Idle)+ }++ /** Weekly refresh, only after a first manual download and only on an unmetered network. */+ fun refreshIfDue(context: Context) {+ val last = Prefs.deflockUpdated(context)+ if (last == 0L || System.currentTimeMillis() - last < REFRESH_MS || isRunning) return+ val cm = context.getSystemService(ConnectivityManager::class.java) ?: return+ if (cm.isActiveNetworkMetered) return+ start(context)+ }++ private fun mb(bytes: Long) = String.format(java.util.Locale.US, "%.1f", bytes / 1_000_000.0)++ /** A running scan starts watching for the new cameras. */+ private fun refreshScanner(app: Context) {+ if (com.rfsentinel.app.service.ScanForegroundService.isRunning) runCatching {+ app.startService(android.content.Intent(app, com.rfsentinel.app.service.ScanForegroundService::class.java)+ .setAction(com.rfsentinel.app.service.ScanForegroundService.ACTION_REFRESH_LOCATION))+ }+ }++ /** GET as text; [onProgress] gets (bytes read, total or -1) about every 64 KB. */+ private fun get(url: String, onProgress: (Long, Long) -> Unit = { _, _ -> }): String {+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {+ connectTimeout = 15_000+ readTimeout = 60_000+ setRequestProperty("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}")+ }+ try {+ if (conn.responseCode != 200) error("HTTP ${conn.responseCode}")+ val total = conn.contentLengthLong+ val out = java.io.ByteArrayOutputStream(if (total in 1..64_000_000) total.toInt() else 1 shl 16)+ conn.inputStream.use { input ->+ val buf = ByteArray(16 * 1024)+ var last = 0L+ while (true) {+ val n = input.read(buf)+ if (n < 0) break+ out.write(buf, 0, n)+ if (out.size() - last >= 64 * 1024) { last = out.size().toLong(); onProgress(last, total) }+ }+ }+ onProgress(out.size().toLong(), total)+ return out.toString("UTF-8")+ } finally {+ conn.disconnect()+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.ktindex ab9f1e3..16226c7 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/KnownCameras.kt@@ -27,14 +27,17 @@ data class KnownCamera(/** Null in caches saved before speed cameras were added: those are all plate readers. */val kind: Kind? = null,/** Enforced speed limit (km/h) for speed cameras, when mapped. */- val maxspeed: Int? = null+ val maxspeed: Int? = null,+ /** A Flock camera mapped as an ordinary camera: most are plate readers, some only record video. */+ val probable: Boolean? = null) {enum class Kind { ALPR, SPEED, RED_LIGHT }val type: Kind get() = kind ?: Kind.ALPRval label: String get() = when (type) {- Kind.ALPR -> (brand ?: "Plate reader") + " (ALPR)"+ Kind.ALPR -> if (probable == true) "${brand ?: "Flock"} camera (probably a plate reader)"+ else (brand ?: "Plate reader") + " (ALPR)"Kind.SPEED -> "Speed camera" + (maxspeed?.let { " ($it km/h)" } ?: "")Kind.RED_LIGHT -> "Red-light camera"}@@ -63,12 +66,37 @@ object KnownCameras {"node[\"highway\"=\"speed_camera\"]$b;" +"node[\"enforcement\"]$b;" +"relation[\"type\"=\"enforcement\"]$b;" ++ BRAND_KEYS.joinToString("") { k -> "nwr[\"surveillance:type\"=\"camera\"][\"$k\"~\"^Flock\",i]$b;" } ++ ");out center tags;"+ }++ private val BRAND_KEYS = listOf("brand", "manufacturer", "surveillance:brand", "surveillance:manufacturer", "operator")++ /** A Flock-branded camera mapped as an ordinary camera (not tagged ALPR). */+ fun isFlockCamera(tag: (String) -> String?) =+ tag("surveillance:type").equals("camera", ignoreCase = true) &&+ BRAND_KEYS.any { tag(it)?.startsWith("Flock", ignoreCase = true) == true }++ /**+ * What DeFlock's snapshot leaves out, for a box: plate readers without+ * `man_made=surveillance`, plate readers mapped as ways, and Flock cameras+ * mapped as ordinary cameras. Small, so it stays cheap even for a large box.+ */+ fun extrasQuery(south: Double, west: Double, north: Double, east: Double): String {+ val b = "($south,$west,$north,$east)"+ val flock = BRAND_KEYS.joinToString("") { k -> "nwr[\"surveillance:type\"=\"camera\"][\"$k\"~\"^Flock\",i]$b;" }+ return "[out:json][timeout:90];(" ++ "node[\"surveillance:type\"=\"ALPR\"][\"man_made\"!=\"surveillance\"]$b;" ++ "way[\"surveillance:type\"=\"ALPR\"]$b;" ++ "relation[\"surveillance:type\"=\"ALPR\"]$b;" ++ flock +");out center tags;"}/** What an OSM element is, from its tags; null when it's none of ours. */fun kindOf(tag: (String) -> String?): KnownCamera.Kind? = when {tag("surveillance:type").equals("ALPR", ignoreCase = true) -> KnownCamera.Kind.ALPR+ isFlockCamera(tag) -> KnownCamera.Kind.ALPRtag("enforcement") == "traffic_signals" -> KnownCamera.Kind.RED_LIGHTtag("highway") == "speed_camera" || tag("enforcement") in setOf("maxspeed", "average_speed") -> KnownCamera.Kind.SPEEDelse -> null@@ -129,7 +157,8 @@ object KnownCameras {operator = tag("operator"),direction = parseDirection(tag("camera:direction", "direction")),kind = kind,- maxspeed = if (kind == KnownCamera.Kind.SPEED) parseMaxspeed(tag("maxspeed")) else null+ maxspeed = if (kind == KnownCamera.Kind.SPEED) parseMaxspeed(tag("maxspeed")) else null,+ probable = if (!tag("surveillance:type").equals("ALPR", ignoreCase = true) && isFlockCamera { tag(it) }) true else null)}.let(::dedupe)}diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.ktindex afb4fd7..35f1237 100644--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt@@ -56,7 +56,12 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {items.addItem(navRow("Flagged nearby", flagged, R.drawable.ic_car_warning, DeviceListScreen.Filter.FLAGGED))items.addItem(navRow("Drones & trackers", dronesTrackers, R.drawable.ic_car_drone, DeviceListScreen.Filter.DRONES_TRACKERS))items.addItem(navRow("All nearby devices", devices.size, R.drawable.ic_car_list, DeviceListScreen.Filter.ALL))- val liveMap = runCatching { carContext.carAppApiLevel >= androidx.car.app.versioning.CarAppApiLevels.LEVEL_7 }.getOrDefault(false)+ // Our own map needs Car API 7 and the surface permission (not every build declares it).+ val liveMap = runCatching {+ carContext.carAppApiLevel >= androidx.car.app.versioning.CarAppApiLevels.LEVEL_7 &&+ carContext.checkSelfPermission("androidx.car.app.ACCESS_SURFACE") ==+ android.content.pm.PackageManager.PERMISSION_GRANTED+ }.getOrDefault(false)items.addItem(Row.Builder().setTitle(if (liveMap) "Live map & navigation" else "Map: devices & cameras around me")diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.ktindex 8465850..4c148d9 100644--- a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt@@ -52,7 +52,7 @@ class NearbyMapScreen(list.setNoItemsMessage("Waiting for your location...")} else if (items.isEmpty()) {list.setNoItemsMessage(- if (AlprStore.cameras.isEmpty()) "No known cameras downloaded - on your phone: Map > menu > Download known cameras"+ if (AlprStore.cameras.isEmpty()) "No known cameras downloaded - on your phone: Map > menu > Download nearby cameras"else "No known cameras or drones within ${(SEARCH_RADIUS_M / 1000).toInt()} km")}diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 39b26ad..d5866cd 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -25,6 +25,7 @@ import kotlinx.coroutines.launchclass SettingsActivity : AppCompatActivity() {private lateinit var binding: ActivitySettingsBindingprivate var stopObservingPrefetch: (() -> Unit)? = null+ private var stopObservingDeflock: (() -> Unit)? = nullprivate val categorySwitches = mutableMapOf<Category, SwitchMaterial>()private val bannerPicker = registerForActivityResult(@@ -179,6 +180,7 @@ class SettingsActivity : AppCompatActivity() {com.rfsentinel.app.esp.EspBoards.onStatusChanged = nullcom.rfsentinel.app.esp.OuiSpyBle.onStatusChanged = nullstopObservingPrefetch?.invoke()+ stopObservingDeflock?.invoke()super.onDestroy()}@@ -319,6 +321,11 @@ class SettingsActivity : AppCompatActivity() {binding.gpsSwitch.isChecked = Prefs.gpsTaggingEnabled(this)binding.autoRecordSwitch.isChecked = Prefs.autoRecordTrace(this)binding.ouiSpyRelaySwitch.isChecked = Prefs.ouiSpyRelayAll(this)+ binding.screenModeGroup.check(when (Prefs.screenMode(this)) {+ Prefs.ScreenMode.ALWAYS_ON -> R.id.screenAlwaysOn+ Prefs.ScreenMode.ON_WHILE_CHARGING -> R.id.screenOnCharging+ Prefs.ScreenMode.NORMAL -> R.id.screenNormal+ })binding.knownAlprSwitch.isChecked = Prefs.knownAlprAlerts(this)binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)@@ -329,6 +336,23 @@ class SettingsActivity : AppCompatActivity() {s !is com.rfsentinel.app.alpr.CameraPrefetch.State.Locating && s !is com.rfsentinel.app.alpr.CameraPrefetch.State.Downloadingbinding.prefetchCamerasText.text = com.rfsentinel.app.ui.cameraPrefetchText(s, located)}+ binding.deflockButton.setOnClickListener { com.rfsentinel.app.alpr.DeflockBulk.start(this) }+ stopObservingDeflock = com.rfsentinel.app.alpr.DeflockBulk.observe { s ->+ binding.deflockButton.isEnabled = !com.rfsentinel.app.alpr.DeflockBulk.isRunning+ val last = Prefs.deflockUpdated(this)+ binding.deflockText.text = when (s) {+ is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading ->+ "Downloading · ${s.detail.ifEmpty { "${s.done}/${s.total} regions" }} · ${s.found} plate cameras so far"+ is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras ->+ "${s.cameras} plate cameras saved · checking OpenStreetMap for more (up to 45 s)..."+ is com.rfsentinel.app.alpr.DeflockBulk.State.Done ->+ "${s.cameras} plate cameras saved - they work offline and refresh weekly on Wi-Fi."+ is com.rfsentinel.app.alpr.DeflockBulk.State.Failed -> s.reason+ else -> if (last > 0) "Last downloaded " ++ android.text.format.DateUtils.getRelativeTimeSpanString(last) + "; refreshes weekly on Wi-Fi."+ else "Every plate reader mapped in OpenStreetMap, from DeFlock's hourly snapshot (cdn.deflock.me sees only the download, not your position)."+ }+ }// Databinding.retentionInput.setText(Prefs.retentionDays(this).toString())@@ -459,6 +483,12 @@ class SettingsActivity : AppCompatActivity() {Prefs.setGpsTaggingEnabled(this, binding.gpsSwitch.isChecked)Prefs.setAutoRecordTrace(this, binding.autoRecordSwitch.isChecked)Prefs.setOuiSpyRelayAll(this, binding.ouiSpyRelaySwitch.isChecked)+ Prefs.setScreenMode(this, when (binding.screenModeGroup.checkedRadioButtonId) {+ R.id.screenAlwaysOn -> Prefs.ScreenMode.ALWAYS_ON+ R.id.screenNormal -> Prefs.ScreenMode.NORMAL+ else -> Prefs.ScreenMode.ON_WHILE_CHARGING+ })+ com.rfsentinel.app.ui.ScreenAwake.apply(this)Prefs.setKnownAlprAlerts(this, binding.knownAlprSwitch.isChecked)Prefs.setSpeedCameraAlerts(this, binding.speedCameraSwitch.isChecked)Prefs.setAutoCameras(this, binding.autoCamerasSwitch.isChecked)diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex 718c0ef..53b5433 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -103,7 +103,7 @@ class MapActivity : AppCompatActivity() {ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())binding.controls.updatePadding(bottom = bars.bottom + (6 * resources.displayMetrics.density).toInt())- binding.statusText.translationY = bars.top.toFloat()+ binding.statusBox.translationY = bars.top.toFloat()insets}@@ -121,6 +121,7 @@ class MapActivity : AppCompatActivity() {binding.tracesButton.setOnClickListener { startActivity(Intent(this, TripsActivity::class.java)) }if (tripId == null) {+ observeBulk()binding.recordButton.setOnClickListener { toggleRecording() }lifecycleScope.launch {repeatOnLifecycle(Lifecycle.State.STARTED) {@@ -156,7 +157,12 @@ class MapActivity : AppCompatActivity() {// Redraw the camera layer for the visible area after panning / zooming.map.addMapListener(object : org.osmdroid.events.MapListener {override fun onScroll(event: org.osmdroid.events.ScrollEvent?) = false.also { drawKnownAlprSoon() }- override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also { drawKnownAlprSoon() }+ override fun onZoom(event: org.osmdroid.events.ZoomEvent?) = false.also {+ drawKnownAlprSoon()+ // The fan-out of stacked dots depends on the zoom.+ map.removeCallbacks(respreadPins)+ map.postDelayed(respreadPins, 150)+ }})myLocation = MyLocationNewOverlay(GpsMyLocationProvider(this), map)@@ -187,6 +193,7 @@ class MapActivity : AppCompatActivity() {}override fun onDestroy() {+ stopObservingBulk?.invoke()myLocation.disableMyLocation()binding.map.removeCallbacks(autoDownloadCameras)binding.map.removeCallbacks(redrawKnownAlpr)@@ -235,6 +242,7 @@ class MapActivity : AppCompatActivity() {val positioned = devices.count { it.bestPosition != null }binding.statusText.text = when {+ bulkStatus() != null -> bulkStatus() // a camera download's progress wins!ScanForegroundService.isRunning -> "Not scanning - start scanning, then Record trace to save your route"recording -> {val mins = (System.currentTimeMillis() - TripRecorder.startedAt) / 60000@@ -350,12 +358,31 @@ class MapActivity : AppCompatActivity() {// ---- Drawing ----------------------------------------------------------------------+ private var lastPins: List<Pin> = emptyList()+ private val respreadPins = Runnable { drawPins(lastPins); binding.map.invalidate() }++ /** Metres per screen pixel at the map's current zoom, near [lat]. */+ private fun metersPerPx(lat: Double, lon: Double): Double {+ val proj = binding.map.projection+ val a = proj.toPixels(GeoPoint(lat, lon), null)+ val b = proj.toPixels(GeoPoint(lat + 0.001, lon), null)+ val px = kotlin.math.abs(b.y - a.y).toDouble()+ return if (px > 0) 111.32 / px else 0.0+ }+private fun drawPins(list: List<Pin>) {+ lastPins = listpins.items.clear()val dp = resources.displayMetrics.density// Ordinary devices first so flagged ones end up on top.- list.sortedBy { it.flagged }.forEach { p ->- val size = ((if (p.flagged) 18 else 10) * dp).toInt()+ val sorted = list.sortedBy { it.flagged }+ // Devices heard from the same spot share coordinates: fan them out so each can be tapped.+ val center = binding.map.mapCenter+ val real = sorted.map { it.lat to it.lon }+ val shown = if (binding.map.zoomLevelDouble < PinSpread.MIN_ZOOM) real+ else PinSpread.spread(real, metersPerPx(center.latitude, center.longitude), 30.0 * dp)+ sorted.forEachIndexed { i, p ->+ val size = ((if (p.flagged) 24 else 16) * dp).toInt()val dot = GradientDrawable().apply {shape = GradientDrawable.OVALsetColor(p.color)@@ -363,7 +390,7 @@ class MapActivity : AppCompatActivity() {setSize(size, size)}pins.add(Marker(binding.map).apply {- position = GeoPoint(p.lat, p.lon)+ position = GeoPoint(shown[i].first, shown[i].second)icon = dotsetAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)title = p.label@@ -548,44 +575,6 @@ class MapActivity : AppCompatActivity() {.show()}- /** Downloads the known cameras for the visible area, after saying what that reveals. */- private fun downloadKnownAlpr() {- val box = binding.map.boundingBox- val span = com.rfsentinel.app.alpr.AlprStore.MAX_SPAN_DEG- if (box.latNorth - box.latSouth > span || box.lonEast - box.lonWest > span) {- Toast.makeText(this, "Zoom in first: one download covers up to about 200 km", Toast.LENGTH_LONG).show()- return- }- AlertDialog.Builder(this)- .setTitle("Download known cameras?")- .setMessage(- "Fetches the license-plate readers, speed cameras and red-light cameras mapped in " +- "OpenStreetMap for the area on screen, " +- "then keeps them on this phone for offline warnings.\n\n" +- "Privacy: the OpenStreetMap Overpass server (overpass-api.de, or a public mirror when it is busy: overpass.kumi.systems, overpass.private.coffee) sees this area and your IP address, " +- "like when loading map tiles. Nothing about your scans is sent."- )- .setPositiveButton("Download") { _, _ ->- binding.statusText.text = "Downloading known cameras..."- lifecycleScope.launch {- val result = runCatching {- com.rfsentinel.app.alpr.AlprStore.download(this@MapActivity, box.latSouth, box.lonWest, box.latNorth, box.lonEast)- }- result.onSuccess { n ->- val total = com.rfsentinel.app.alpr.AlprStore.cameras.size- Toast.makeText(this@MapActivity, "$n cameras in this area ($total saved in total)", Toast.LENGTH_LONG).show()- com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this@MapActivity, true)- drawKnownAlpr()- refreshServiceLocation() // start watching for them while scanning- }.onFailure { e ->- Toast.makeText(this@MapActivity, "Download failed: ${e.message ?: "no connection"}", Toast.LENGTH_LONG).show()- }- }- }- .setNegativeButton("Cancel", null)- .show()- }-private fun showPin(p: Pin) {AlertDialog.Builder(this).setTitle(p.label)@@ -595,6 +584,74 @@ class MapActivity : AppCompatActivity() {.show()}+ /**+ * DeFlock's snapshot - all of the US & Canada, or with [nearby] only ~100 km+ * around you (or the map centre without a GPS fix). Progress in the status+ * bar; the map redraws when done.+ */+ private fun downloadAllPlateCameras(nearby: Boolean = false) {+ val bulk = com.rfsentinel.app.alpr.DeflockBulk+ announceWhere = if (nearby) "within ~100 km" else "(US & Canada)"+ // One download at a time: tapping again while one runs just follows its progress (bar on the map).+ if (bulk.isRunning) return+ val around = if (!nearby) null else {+ val fix = myLocation.myLocation ?: binding.map.mapCenter.let { GeoPoint(it.latitude, it.longitude) }+ fix.latitude to fix.longitude+ }+ bulk.start(this, around)+ }++ /** Set when a download was started (or followed) from this screen: show its result. */+ private var announceWhere: String? = null+ private var stopObservingBulk: (() -> Unit)? = null++ /** Status text while a DeFlock download runs, or null when none does. */+ private fun bulkStatus(): String? = when (val s = com.rfsentinel.app.alpr.DeflockBulk.state) {+ is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading ->+ "Downloading plate cameras · ${s.detail.ifEmpty { "${s.done}/${s.total} regions" }} · ${s.found} found"+ is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras ->+ "${s.cameras} plate cameras on the map · checking OpenStreetMap for more (up to 45 s)..."+ else -> null+ }++ /** Follows every DeFlock download (from here, Settings or the weekly refresh) with the progress bar. */+ private fun observeBulk() {+ stopObservingBulk = com.rfsentinel.app.alpr.DeflockBulk.observe { s ->+ if (isFinishing || isDestroyed) return@observe+ val bar = binding.downloadProgress+ when (s) {+ is com.rfsentinel.app.alpr.DeflockBulk.State.Downloading -> {+ if (bar.isIndeterminate) { bar.visibility = View.INVISIBLE; bar.isIndeterminate = false }+ bar.visibility = View.VISIBLE+ bar.setProgressCompat((s.fraction * 100).toInt(), true)+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.CheckingExtras -> {+ // DeFlock's cameras are saved: show them now; the bar keeps moving for the extras.+ com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, true)+ drawKnownAlpr(); refreshServiceLocation()+ bar.visibility = View.INVISIBLE; bar.isIndeterminate = true; bar.visibility = View.VISIBLE+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.Done -> {+ bar.visibility = View.GONE+ drawKnownAlpr(); refreshServiceLocation()+ announceWhere?.let { where ->+ Toast.makeText(this, "${s.cameras} plate cameras saved $where" ++ if (s.extrasSkipped) " (OpenStreetMap was busy - a few extras will come next time)" else "",+ Toast.LENGTH_LONG).show()+ }+ announceWhere = null+ }+ is com.rfsentinel.app.alpr.DeflockBulk.State.Failed -> {+ bar.visibility = View.GONE+ announceWhere?.let { Toast.makeText(this, s.reason, Toast.LENGTH_LONG).show() }+ announceWhere = null+ }+ com.rfsentinel.app.alpr.DeflockBulk.State.Idle -> bar.visibility = View.GONE+ }+ bulkStatus()?.let { binding.statusText.text = it }+ }+ }+// ---- Menu (trip mode) ---------------------------------------------------------------override fun onCreateOptionsMenu(menu: Menu): Boolean {@@ -604,7 +661,8 @@ class MapActivity : AppCompatActivity() {menu.add(0, 3, 2, "Delete")} else {menu.add(0, 4, 0, "Recorded traces")- menu.add(0, 5, 1, "Download known cameras here")+ menu.add(0, 5, 1, "Download nearby cameras")+ menu.add(0, 8, 1, "Download all US & CA")menu.add(0, 6, 2, "Show known cameras").apply {isCheckable = true; isChecked = com.rfsentinel.app.util.Prefs.showKnownAlpr(this@MapActivity)}@@ -620,7 +678,7 @@ class MapActivity : AppCompatActivity() {2 -> { id?.let { rename(it) }; true }3 -> { id?.let { confirmDelete(it) }; true }4 -> { startActivity(Intent(this, TripsActivity::class.java)); true }- 5 -> { downloadKnownAlpr(); true }+ 5 -> { downloadAllPlateCameras(nearby = true); true }6 -> {val show = !com.rfsentinel.app.util.Prefs.showKnownAlpr(this)com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, show)@@ -628,10 +686,13 @@ class MapActivity : AppCompatActivity() {drawKnownAlpr(); true}7 -> {+ // Stop a running download first, or it would put cameras back afterwards.+ com.rfsentinel.app.alpr.DeflockBulk.cancel()com.rfsentinel.app.alpr.AlprStore.clear(this)drawKnownAlpr(); refreshServiceLocation()Toast.makeText(this, "Downloaded cameras deleted", Toast.LENGTH_SHORT).show(); true}+ 8 -> { downloadAllPlateCameras(); true }android.R.id.home -> { finish(); true }else -> super.onOptionsItemSelected(item)}diff --git a/app/src/main/java/com/rfsentinel/app/ui/PinSpread.kt b/app/src/main/java/com/rfsentinel/app/ui/PinSpread.ktnew file mode 100644index 0000000..c4fdd91--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/PinSpread.kt@@ -0,0 +1,64 @@+package com.rfsentinel.app.ui++import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.sin++/**+ * Devices are placed where the phone heard them loudest, so everything heard+ * from one spot shares the same coordinates and the dots stack on top of each+ * other. This fans dots that would overlap on screen out into rings around+ * their shared spot, so each one can be tapped. Pure (unit-tested).+ */+object PinSpread {++ /** Dots further apart than this in reality are never regrouped. */+ const val MAX_GROUP_M = 30.0+ /** Below this zoom the map shows dots where they are, overlapping or not. */+ const val MIN_ZOOM = 15.0++ /**+ * Returns a display position for every input position (same order).+ * [metersPerPx] is the map's current scale and [spacingPx] the on-screen gap+ * wanted between dot centres.+ */+ fun spread(+ points: List<Pair<Double, Double>>, metersPerPx: Double, spacingPx: Double,+ maxGroupM: Double = MAX_GROUP_M+ ): List<Pair<Double, Double>> {+ if (points.size < 2 || metersPerPx <= 0.0) return points+ val spacingM = spacingPx * metersPerPx+ // Only dots heard from (nearly) the same spot are fanned out - never ones that just look close when zoomed out.+ val joinM = minOf(spacingM, maxGroupM)+ // Greedy grouping: a dot joins the first group whose centre is close enough.+ val groups = ArrayList<MutableList<Int>>()+ for (i in points.indices) {+ val g = groups.firstOrNull { metersBetween(points[it.first()], points[i]) < joinM }+ if (g != null) g += i else groups += mutableListOf(i)+ }+ val out = points.toMutableList()+ for (g in groups) {+ if (g.size < 2) continue+ val (lat0, lon0) = points[g.first()]+ val mPerDegLat = 111_320.0+ val mPerDegLon = 111_320.0 * cos(Math.toRadians(lat0)).coerceAtLeast(0.01)+ // The first dot keeps the spot; the rest go on rings of 6, 12, 18... one spacing apart.+ var ring = 1+ var slot = 0+ for (k in 1 until g.size) {+ val perRing = 6 * ring+ val angle = 2 * PI * slot / perRing - PI / 2+ val r = spacingM * ring+ out[g[k]] = (lat0 + r * sin(-angle) / mPerDegLat) to (lon0 + r * cos(angle) / mPerDegLon)+ if (++slot == perRing) { ring++; slot = 0 }+ }+ }+ return out+ }++ private fun metersBetween(a: Pair<Double, Double>, b: Pair<Double, Double>): Double {+ val dLat = (b.first - a.first) * 111_320.0+ val dLon = (b.second - a.second) * 111_320.0 * cos(Math.toRadians(a.first))+ return kotlin.math.sqrt(dLat * dLat + dLon * dLon)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/ScreenAwake.kt b/app/src/main/java/com/rfsentinel/app/ui/ScreenAwake.ktnew file mode 100644index 0000000..ba59938--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/ScreenAwake.kt@@ -0,0 +1,71 @@+package com.rfsentinel.app.ui++import android.app.Activity+import android.app.Application+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.os.BatteryManager+import android.os.Bundle+import android.view.WindowManager+import androidx.core.content.ContextCompat+import com.rfsentinel.app.util.Prefs++/**+ * Keeps the screen on while an RF Sentinel screen is open: always, only while+ * the phone is charging (car mount, desk - the default), or never (normal+ * timeout), as chosen in Settings.+ */+object ScreenAwake : Application.ActivityLifecycleCallbacks {++ private var current: Activity? = null++ private val power = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ // The battery status can lag behind this broadcast: trust the action itself.+ current?.let { set(it, intent.action == Intent.ACTION_POWER_CONNECTED) }+ }+ }++ fun install(app: Application) = app.registerActivityLifecycleCallbacks(this)++ private fun plugged(context: Context): Boolean {+ val battery = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) ?: return false+ return battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0+ }++ /** Re-evaluates the current screen (e.g. after the setting changed). */+ fun apply(activity: Activity) = set(activity, plugged(activity))++ private fun set(activity: Activity, charging: Boolean) {+ val on = when (Prefs.screenMode(activity)) {+ Prefs.ScreenMode.ALWAYS_ON -> true+ Prefs.ScreenMode.ON_WHILE_CHARGING -> charging+ Prefs.ScreenMode.NORMAL -> false+ }+ if (on) activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)+ else activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)+ }++ override fun onActivityResumed(activity: Activity) {+ current = activity+ ContextCompat.registerReceiver(+ activity.applicationContext, power,+ IntentFilter().apply { addAction(Intent.ACTION_POWER_CONNECTED); addAction(Intent.ACTION_POWER_DISCONNECTED) },+ ContextCompat.RECEIVER_NOT_EXPORTED+ )+ apply(activity)+ }++ override fun onActivityPaused(activity: Activity) {+ if (current === activity) current = null+ runCatching { activity.applicationContext.unregisterReceiver(power) }+ }++ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}+ override fun onActivityStarted(activity: Activity) {}+ override fun onActivityStopped(activity: Activity) {}+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}+ override fun onActivityDestroyed(activity: Activity) {}+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.ktindex 3b14bcd..c1601d0 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt@@ -172,6 +172,24 @@ class SetupActivity : AppCompatActivity() {switch("Discreet mode - hide details on the lock screen and in notifications", Prefs.discreetMode(this)) {Prefs.setDiscreetMode(this, it)}+ label("Screen while RF Sentinel is open")+ val screen = RadioGroup(this)+ val mode = Prefs.screenMode(this)+ listOf(+ Prefs.ScreenMode.ALWAYS_ON to "Always on",+ Prefs.ScreenMode.ON_WHILE_CHARGING to "On while charging (car, desk) - recommended",+ Prefs.ScreenMode.NORMAL to "Normal (turns off like other apps)"+ ).forEach { (value, text) ->+ screen.addView(RadioButton(this).apply {+ id = View.generateViewId()+ this.text = text+ isChecked = value == mode+ setOnCheckedChangeListener { _, c ->+ if (c) { Prefs.setScreenMode(this@SetupActivity, value); ScreenAwake.apply(this@SetupActivity) }+ }+ })+ }+ binding.page.addView(screen)}private fun location() {diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 260b0b6..452661c 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -120,6 +120,14 @@ object Prefs {if (address == null) remove("ouispy_board") else putString("ouispy_board", address)}/** Have the OUI-SPY board relay every network and Bluetooth device it hears (its Wardrive engine). */+ /** Whether the screen stays on while an RF Sentinel screen is open. */+ enum class ScreenMode { ALWAYS_ON, ON_WHILE_CHARGING, NORMAL }+ fun screenMode(context: Context): ScreenMode =+ runCatching { ScreenMode.valueOf(sp(context).getString("screen_mode", null)!!) }.getOrDefault(ScreenMode.ON_WHILE_CHARGING)+ fun setScreenMode(context: Context, mode: ScreenMode) = sp(context).edit { putString("screen_mode", mode.name) }+ /** When the US & Canada plate readers were last downloaded from DeFlock (0 = never). */+ fun deflockUpdated(context: Context): Long = sp(context).getLong("deflock_updated", 0L)+ fun setDeflockUpdated(context: Context, time: Long) = sp(context).edit { putLong("deflock_updated", time) }fun ouiSpyRelayAll(context: Context): Boolean = bool(context, "ouispy_relay_all", true)fun setOuiSpyRelayAll(context: Context, value: Boolean) = setBool(context, "ouispy_relay_all", value)fun showKnownAlpr(context: Context): Boolean = bool(context, "show_known_alpr", true)diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xmlindex 5fd65f4..189a9c8 100644--- a/app/src/main/res/layout/activity_map.xml+++ b/app/src/main/res/layout/activity_map.xml@@ -10,20 +10,39 @@android:layout_width="match_parent"android:layout_height="match_parent" />- <!-- Status card -->- <TextView- android:id="@+id/statusText"+ <!-- Status card, with the camera-download progress bar under it -->+ <LinearLayout+ android:id="@+id/statusBox"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="top"android:layout_margin="10dp"- android:background="@drawable/banner_bg"- android:paddingStart="12dp"- android:paddingTop="8dp"- android:paddingEnd="12dp"- android:paddingBottom="8dp"- android:textColor="#FFFFFF"- android:textSize="13sp" />+ android:orientation="vertical">++ <TextView+ android:id="@+id/statusText"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:background="@drawable/banner_bg"+ android:paddingStart="12dp"+ android:paddingTop="8dp"+ android:paddingEnd="12dp"+ android:paddingBottom="8dp"+ android:textColor="#FFFFFF"+ android:textSize="13sp" />++ <com.google.android.material.progressindicator.LinearProgressIndicator+ android:id="@+id/downloadProgress"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"+ android:max="100"+ android:visibility="gone"+ app:indicatorColor="#FFFFFF"+ app:trackColor="#660B5C63"+ app:trackCornerRadius="3dp"+ app:trackThickness="6dp" />+ </LinearLayout><com.google.android.material.floatingactionbutton.FloatingActionButtonandroid:id="@+id/centerButton"diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex eb43a16..27eaca0 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -320,7 +320,7 @@android:id="@+id/knownAlprSwitch"android:layout_width="match_parent"android:layout_height="wrap_content"- android:text="Warn when approaching a known plate-reader camera (download them on the map: menu, Download known cameras)" />+ android:text="Warn when approaching a known plate-reader camera (download them on the map: menu, Download nearby cameras)" /><com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/autoCamerasSwitch"@@ -341,6 +341,19 @@android:paddingTop="0dp"android:textSize="12sp" />+ <Button+ android:id="@+id/deflockButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Download all plate cameras: US & Canada (~18 MB)" />++ <TextView+ android:id="@+id/deflockText"+ style="@style/SettingsLabel"+ android:paddingTop="0dp"+ android:textSize="12sp" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/speedCameraSwitch"android:layout_width="match_parent"@@ -372,6 +385,34 @@android:layout_height="wrap_content"android:text="OUI-SPY: relay every network and Bluetooth device it hears, so RF Sentinel's own lists check them (the board also sends standard Wi-Fi scan probes)" />+ <TextView+ style="@style/SettingsLabel"+ android:text="Screen while RF Sentinel is open" />++ <RadioGroup+ android:id="@+id/screenModeGroup"+ android:layout_width="match_parent"+ android:layout_height="wrap_content">++ <RadioButton+ android:id="@+id/screenAlwaysOn"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Always on" />++ <RadioButton+ android:id="@+id/screenOnCharging"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="On while charging (car, desk)" />++ <RadioButton+ android:id="@+id/screenNormal"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Normal (turns off like other apps)" />+ </RadioGroup>+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/autoRecordSwitch"android:layout_width="match_parent"diff --git a/app/src/test/java/com/rfsentinel/app/alpr/DeflockBulkTest.kt b/app/src/test/java/com/rfsentinel/app/alpr/DeflockBulkTest.ktnew file mode 100644index 0000000..5e61a92--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/alpr/DeflockBulkTest.kt@@ -0,0 +1,71 @@+package com.rfsentinel.app.alpr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/** Made-up positions and ids, shaped like cdn.deflock.me/regions files. */+class DeflockBulkTest {++ private val index = DeflockBulk.parseIndex(+ """{"expiration_utc": 1, "regions": ["40/-80", "20/-100", "40/0", "60/-60", "-40/140", "0/-80"],+ "tile_url": "https://cdn.deflock.me/regions/{lat}/{lon}.json?v=7", "tile_size_degrees": 20}"""+ )++ @Test+ fun picksOnlyNorthAmericanTiles() {+ assertEquals(listOf("40/-80", "20/-100", "60/-60"), DeflockBulk.tilesFor(index, DeflockBulk.NORTH_AMERICA))+ assertEquals("https://cdn.deflock.me/regions/40/-80.json?v=7", DeflockBulk.tileUrl(index, "40/-80"))+ }++ @Test+ fun nearbyAreaIsAbout100kmAndPicksItsTiles() {+ val box = DeflockBulk.boxAround(39.0, -98.0, 100.0)+ assertEquals(0.898, box[2] - 39.0, 0.01) // ~100 km of latitude+ assertEquals(1.156, -98.0 - box[1], 0.02) // wider in degrees of longitude at 39°N+ assertEquals(listOf("20/-100"), DeflockBulk.tilesFor(index, box))+ assertTrue(DeflockBulk.inBox(KnownCamera("node/1", 39.5, -97.5, null, null, null), box))+ assertTrue(!DeflockBulk.inBox(KnownCamera("node/2", 40.5, -97.5, null, null, null), box))+ }++ @Test+ fun flockCamerasMappedAsOrdinaryCamerasCount() {+ val json = """{"elements":[+ {"type":"node","id":7,"lat":41.0,"lon":-79.0,"tags":{"man_made":"surveillance","surveillance:type":"camera","manufacturer":"Flock Safety"}},+ {"type":"node","id":8,"lat":41.0,"lon":-79.0,"tags":{"man_made":"surveillance","surveillance:type":"camera","brand":"Axis"}},+ {"type":"way","id":9,"center":{"lat":41.1,"lon":-79.1},"tags":{"surveillance:type":"ALPR"}}]}"""+ val cams = KnownCameras.parse(json)+ assertEquals(listOf("node/7", "way/9"), cams.map { it.osmId })+ assertEquals("Flock Safety camera (probably a plate reader)", cams[0].label)+ assertEquals("Plate reader (ALPR)", cams[1].label)+ }++ @Test+ fun parsesTileNodes() {+ val cams = DeflockBulk.parseTile(+ """[{"id": 101, "lat": 41.5, "lon": -79.5, "tags": {"surveillance:brand": "Flock Safety", "direction": "SE"}},+ {"id": 102, "lat": 42.0, "lon": -78.0, "tags": {}}]"""+ )+ assertEquals(2, cams.size)+ assertEquals("node/101", cams[0].osmId)+ assertEquals("Flock Safety", cams[0].brand)+ assertEquals(135, cams[0].direction)+ assertTrue(cams.all { it.type == KnownCamera.Kind.ALPR })+ }++ @Test+ fun mergeAddsAndUpdatesButNeverDrops() {+ fun cam(id: String, lat: Double, lon: Double, kind: KnownCamera.Kind = KnownCamera.Kind.ALPR) =+ KnownCamera(id, lat, lon, null, null, null, kind)+ val current = listOf(+ cam("node/1", 41.0, -79.0), // not in DeFlock's snapshot: kept+ cam("way/2", 41.0, -79.0), // plate reader as a way: kept+ cam("node/3", 41.0, -79.0, KnownCamera.Kind.SPEED), // speed camera: kept+ cam("node/4", 10.0, 10.0), // outside the tiles: kept+ cam("node/5", 41.2, -79.2) // also in the new set: not duplicated+ )+ val found = listOf(cam("node/5", 41.2, -79.2), cam("node/6", 42.0, -78.0))+ val merged = AlprStore.mergeCameras(current, listOf(DeflockBulk.tileBox("40/-80", 20)), found)+ assertEquals(listOf("node/1", "way/2", "node/3", "node/4", "node/5", "node/6"), merged.map { it.osmId })+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.kt b/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.ktnew file mode 100644index 0000000..2eb095c--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/PinSpreadTest.kt@@ -0,0 +1,39 @@+package com.rfsentinel.app.ui++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import kotlin.math.cos+import kotlin.math.sqrt++class PinSpreadTest {++ private fun px(a: Pair<Double, Double>, b: Pair<Double, Double>, mPerPx: Double): Double {+ val dLat = (b.first - a.first) * 111_320.0+ val dLon = (b.second - a.second) * 111_320.0 * cos(Math.toRadians(a.first))+ return sqrt(dLat * dLat + dLon * dLon) / mPerPx+ }++ @Test+ fun stackedDotsAllBecomeSeparate() {+ val spot = 39.0 to -98.0+ val out = PinSpread.spread(List(16) { spot }, metersPerPx = 0.3, spacingPx = 24.0)+ assertEquals(spot, out[0]) // the first keeps the real spot+ for (i in out.indices) for (j in i + 1 until out.size) {+ assertTrue("dots $i and $j overlap", px(out[i], out[j], 0.3) >= 23.0)+ }+ }++ @Test+ fun farApartDotsStayPut() {+ val pts = listOf(39.0 to -98.0, 39.01 to -98.0, 39.0 to -98.01)+ assertEquals(pts, PinSpread.spread(pts, metersPerPx = 0.3, spacingPx = 24.0))+ }++ @Test+ fun zoomedOutNeighboursAreNotDraggedAround() {+ // ~100 m apart: at 20 m/px they'd overlap on screen, but they're different spots.+ val pts = listOf(39.0 to -98.0, 39.0009 to -98.0)+ assertEquals(pts, PinSpread.spread(pts, metersPerPx = 20.0, spacingPx = 24.0))+ }+}