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
RF Sentinel 2.15.2 changes
CIS-C016c57efd3ea9
diff --git a/README.md b/README.mdindex f9668ff..28daacc 100644--- a/README.md+++ b/README.md@@ -89,7 +89,7 @@| **Patrol vehicles** | Two or more kinds of police-type gear travelling together | Signal correlation between body cams, radios, in-car routers, printers, rugged laptops || **Public-safety gear** | P25 / TETRA radios, in-car cellular routers (Sierra Wireless, Cradlepoint, Peplink, Inseego), in-car printers (Zebra, Brother), police radar makers, vehicle upfit, breath / drug screening devices, cell-site simulator and forensic makers | Company IDs, UUIDs, IEEE prefixes, Zebra factory-serial names || **Trackers** | AirTag & Find My, Google Find Hub, Samsung SmartTag, Tile | Separated-from-owner frames, then follow detection |-| **Drones** | Any ASTM F3411 / FAA / EU Remote ID broadcaster | Decoded Remote ID over BLE and WiFi: serial, position, altitude, speed, operator location |+| **Drones** | Any ASTM F3411 / FAA / EU Remote ID broadcaster, and the French *signalement électronique* | Decoded Remote ID over BLE and WiFi: serial, position, altitude, speed, operator / take-off location || **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 |@@ -116,7 +116,7 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer- **Fake cell tower signs** checked every 15 s, with persistence, call and border suppression (modelled on [EFF's Rayhunter](https://github.com/EFForg/rayhunter) as far as Android allows without root)- **Hidden WiFi networks** identified from WPS data, Cisco AP names and vendor elements, and linked to the visible network on the same router- Ordinary devices named precisely: exact AirPods / Beats model, device class, IEEE registrant; decoded Apple Continuity, iBeacon, Eddystone, Fast Pair-- Editable **watchlist** (exact addresses, prefixes, name / vendor rules) with Global, Canada and US presets; per-category on/off switches+- Editable **watchlist** (exact addresses, prefixes, name / vendor rules) with Global, Canada, US and France presets; per-category on/off switches- Bluetooth 5 extended advertising and LE Coded (long range) where the phone supports it**Known cameras**@@ -207,7 +207,7 @@ Details: [How it works](https://cis-c0.github.io/RFSentinel/how-it-works.html) a### Main screen- **Threat banner:** all clear, weak, probable or strong, or *may be following you*.-- **Live list:** every device heard in the last 3 minutes, with vendor, type,+- **Live list:** every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable), with vendor, type,radio, signal, rough distance, and NEW / ★ / FOLLOWING badges. A green**INTERNAL** badge means the phone heard it; a blue **ESP32** badge means aconnected board reported it. Flagged devices sort first and flash in their@@ -246,15 +246,23 @@ the raw advertisement.heard around you, placed where your phone was when its signal was strongest.That's an approximation, not a fix. Each dot stays pinned to its spot as youpan and zoom; tap a spot where several devices were heard to pick one from a list.-- **Cell towers** (map menu ⋮ → *Show cell towers*): towers seen while scanning,+- **Cell towers** (map ⚙ → Settings → *Map* → *Show cell towers*): towers seen while scanning,at the spot where your phone heard them strongest - an estimate, not thetower's real position (looking that up online would reveal where you are).-- **Known cameras** (map menu ⋮): *Download nearby cameras* fetches plate readers- within your radius (10-200 km, 100 by default); *Download Flock* fetches every+- **Known cameras** (Settings → *Known cameras*): *Download cameras around me* fetches plate readers+ within your radius (10-200 km, 100 by default); *US & Canada plate cameras* fetches everyplate reader mapped in the US and Canada (~18 MB, refreshed weekly on WiFi).Both use [DeFlock](https://deflock.org)'s hourly snapshot of OpenStreetMap,plus cameras it leaves out, straight from OpenStreetMap. Tap a camera →*Ignore alerts* to never be warned about it again.+- **CCTV cameras** (Settings → *Known cameras* → *Show CCTV cameras*, off by default):+ ordinary surveillance cameras mapped in OpenStreetMap - city street cameras,+ shop and building cameras. Everything within your camera download radius is+ fetched in the background (also by *Download cameras around me*); they show from+ city zoom, with a shaded view cone where the direction is mapped when you zoom in.+ Public ones by default; *Include private and indoor CCTV* adds the rest. Map only+ (no alerts). Most are wired, so no scanner can detect them; this shows the ones+ volunteers have mapped (the same data as [Surveillance under Surveillance](https://sunders.uber.space/)).- **Record trace** saves your route and every device heard along it, with thescreen off, and can start with each scan.- **Screen:** *always on*, *on while charging* (default) or *normal*.@@ -669,6 +677,7 @@ detection and WiFi identification, is in [docs/SIGNATURES.md](docs/SIGNATURES.md- **all-cameras-are-beacons** signature reference (Apache-2.0): signature values and confidence ladder- **opendroneid-core-c** (Apache-2.0): Remote ID message layout+- **droneID_FR** (github.com/khancyr/droneID_FR): French electronic drone ID beacon layout- **IEEE Registration Authority:** vendor database- **Bluetooth SIG assigned numbers:** company IDs, service UUIDs, appearance valuesdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 0a91a8d..5054b43 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 = 37-val appVersionName = "2.15.1"+val appVersionCode = 38+val appVersionName = "2.15.2"// Release signing credentials live in keystore.properties (git-ignored).// Without that file, release builds are produced unsigned.diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 5b41fa4..2e1b979 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -62,6 +62,11 @@<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>+ <!-- Voice "play RF Sentinel" (Android Auto media app): the scan starts through the media session. -->+ <intent-filter>+ <action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter></activity><activity android:name=".settings.SettingsActivity" android:exported="false" />diff --git a/app/src/main/assets/oui_presets/france.json b/app/src/main/assets/oui_presets/france.jsonnew file mode 100644index 0000000..2e92525--- /dev/null+++ b/app/src/main/assets/oui_presets/france.json@@ -0,0 +1,106 @@+[+ {+ "prefix": "4C:CC:34",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:1F:92",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:18:85",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:04:7D",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "10:74:6F",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "B8:E2:8C",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "9C:86:2B",+ "label": "Motorola Solutions - in France: VB400 body cams of the Police nationale and Gendarmerie (~30,000 since 2021), also municipal police; radios",+ "source": "IEEE MA-L registry; French Interior Ministry body-cam contract awarded to Motorola Solutions (VB400, Wi-Fi + Bluetooth, Bluetooth holster trigger), interieur.gouv.fr / AEF info. Weak: the same blocks carry radios and other gear",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "48:46:8D",+ "label": "Zepcam body camera - used by French municipal police",+ "source": "IEEE MA-L registry (Zepcam B.V.); Zepcam supplied the first French municipal police body cams",+ "confidence": "confirmed",+ "score": 75,+ "category": "BODY_CAM"+ },+ {+ "prefix": "00:25:DF",+ "label": "Axon (TASER of the Police nationale / Gendarmerie; body cams at some municipal police)",+ "source": "IEEE MA-L registry (Axon Enterprise); Axon has supplied the French Interior Ministry since 2005-2006",+ "confidence": "confirmed",+ "score": 75,+ "category": "BODY_CAM"+ },+ {+ "prefix": "00:0A:3E",+ "label": "EADS / Airbus TETRAPOL radio (INPT / ACROPOL police and RUBIS gendarmerie networks)",+ "source": "IEEE MA-L registry (EADS Telecom); TETRAPOL is the French police / gendarmerie radio network. Weak: firefighters use it too",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "C4:7C:8D:9",+ "label": "Airbus DS SLC (TETRAPOL TPH900 radios, Réseau Radio du Futur of French police, gendarmerie and fire services)",+ "source": "IEEE MA-M registry (Airbus DS - SLC, Élancourt); Airbus co-leads the RRF consortium. Match all 28 bits",+ "confidence": "candidate",+ "score": 50,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:23:B9",+ "label": "Airbus Defence and Space (TETRAPOL radios of French police / gendarmerie)",+ "source": "IEEE MA-L registry; public-safety radio maker. Weak: also defence equipment",+ "confidence": "candidate",+ "score": 45,+ "category": "PUBLIC_SAFETY"+ },+ {+ "prefix": "00:24:AE",+ "label": "Idemia Public Security France (police fingerprint / ID terminals, plate readers)",+ "source": "IEEE MA-L registry (Idemia Public Security France); French maker of police biometric terminals and LAPI plate readers",+ "confidence": "candidate",+ "score": 50,+ "category": "ALPR"+ }+]\ No newline at end of filediff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex cb18d55..1b1cf28 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -47,8 +47,6 @@ class MainActivity : AppCompatActivity() {private const val CELL_ROW = "cell:"private const val BLUETOOTH_TAG_COLOR = 0xFF1565C0.toInt()private const val WIFI_TAG_COLOR = 0xFF00838F.toInt()- /** A flagged row flashes while its device was heard within this window. */- private const val FLASH_WINDOW_MS = 60_000Lprivate const val REFRESH_MS = 1_000Lprivate const val WEAK_COLOR = 0xFFB26A00.toInt()private const val WHITELIST_COLOR = 0xFF6B7B80.toInt()@@ -308,11 +306,12 @@ class MainActivity : AppCompatActivity() {val bleMs = Prefs.liveBleSec(this) * 1000Lval wifiMs = Prefs.liveWifiSec(this) * 1000Lval all = DeviceRegistry.snapshot(now).filter {- com.rfsentinel.app.ui.LiveWindow.keep(it, it.best != null && !WhitelistCache.contains(it.mac), now, bleMs, wifiMs)+ com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs)}val threshold = Prefs.alertThreshold(this)deviceCount = all.size- val flagged = all.filter { it.best != null && !WhitelistCache.contains(it.mac) }+ // The banner and radar alert only for flagged devices still in range.+ val flagged = all.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }flaggedCount = flagged.sizeupdateBanner(flagged, threshold)updateStatus()@@ -334,7 +333,7 @@ class MainActivity : AppCompatActivity() {if (binding.radarView.visibility == View.VISIBLE) {binding.radarView.setBlips(visible.take(200).map { s ->- val alert = s.best != null && !WhitelistCache.contains(s.mac)+ val alert = com.rfsentinel.app.ui.LiveWindow.alerting(s, now)RadarView.Blip(s.mac, s.rssi,if (alert) colorFor(s) else binding.radarView.ordinaryColor(),@@ -454,7 +453,8 @@ class MainActivity : AppCompatActivity() {else -> colorFor(s)},highlight = if (alert) colorFor(s) else null,- flashing = alert && now - s.lastSeen < FLASH_WINDOW_MS &&+ // Flashes only while still in range (like the beeps); a gone device keeps a steady tint.+ flashing = alert && com.rfsentinel.app.ui.LiveWindow.inRange(s, now) &&(s.following || (best!!.confidence >= threshold && best.category != Category.TRACKER)),bold = alert,heardByEsp = com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac, now),diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.ktindex 7bf01ce..bbd5f37 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt@@ -121,6 +121,7 @@ object AlprStore {var found = 0var ok = 0var lastError: Exception? = null+ val failed = mutableListOf<Int>()tiles.forEachIndexed { i, t ->val report = { detail: String -> onProgress(Progress(i + 1, i, tiles.size, found, i - ok, "${name(i)}: $detail")) }try {@@ -130,9 +131,31 @@ object AlprStore {throw e} catch (e: Exception) {lastError = e+ failed += i}onProgress(Progress(i + 1, i + 1, tiles.size, found, i + 1 - ok,- if (ok == i + 1) "${name(i)} done" else "${name(i)} failed - the map will fetch it later"))+ if (ok == i + 1) "${name(i)} done" else "${name(i)} failed - retrying at the end"))+ }+ // The public servers rate-limit bursts: give the refused areas one more go after a pause.+ if (failed.isNotEmpty()) {+ onProgress(Progress(tiles.size, tiles.size, tiles.size, found, failed.size,+ "retrying ${failed.size} area(s) the servers refused in 30 s"))+ kotlinx.coroutines.delay(30_000)+ for (i in failed) {+ val t = tiles[i]+ try {+ found += download(context, t[0], t[1], t[2], t[3]) { d ->+ onProgress(Progress(i + 1, tiles.size, tiles.size, found, tiles.size - ok, "${name(i)} (retry): $d"))+ }+ ok+++ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Exception) {+ lastError = e+ }+ }+ onProgress(Progress(tiles.size, tiles.size, tiles.size, found, tiles.size - ok,+ if (ok == tiles.size) "all areas done" else "${tiles.size - ok} area(s) failed - the map will fetch them later"))}if (ok == 0) throw lastError ?: java.io.IOException("No answer")return found@@ -181,7 +204,7 @@ object AlprStore {* 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 {+ internal suspend fun fetchFirst(body: String, status: (String) -> Unit): String {val requests = kotlinx.coroutines.CoroutineScope(Dispatchers.IO + kotlinx.coroutines.SupervisorJob())val result = kotlinx.coroutines.CompletableDeferred<String>()val failures = kotlinx.coroutines.flow.MutableStateFlow(0)diff --git a/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt b/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.ktindex 2429759..fe09177 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt@@ -116,7 +116,14 @@ object CameraPrefetch {failed = p.failedset(State.Downloading(p.done, p.total, p.found, p.detail))}- set(State.Done(n, failed, radius))+ if (com.rfsentinel.app.util.Prefs.showCctv(app)) {+ runCatching {+ CctvStore.downloadAround(app, here.latitude, here.longitude, radius.toDouble()) { p ->+ set(State.Downloading(0, 0, n, "CCTV cameras: $p"))+ }+ }+ }+ set(State.Done(n, failed + if (com.rfsentinel.app.util.Prefs.showCctv(app)) CctvStore.missingAreas else 0, radius))// A running scan starts watching for the new cameras.if (ScanForegroundService.isRunning) runCatching {app.startService(Intent(app, ScanForegroundService::class.java).setAction(ScanForegroundService.ACTION_REFRESH_LOCATION))diff --git a/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt b/app/src/main/java/com/rfsentinel/app/alpr/Cctv.ktnew file mode 100644index 0000000..bea376c--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt@@ -0,0 +1,307 @@+package com.rfsentinel.app.alpr++import android.content.Context+import com.google.gson.Gson+import com.google.gson.JsonParser+import com.google.gson.reflect.TypeToken+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.net.URLEncoder++/**+ * An ordinary surveillance camera mapped in OpenStreetMap (`man_made=surveillance`,+ * `surveillance:type=camera`): city street cameras, shop and building cameras. Mostly wired,+ * so no radio can detect them - the map is the only way to see them. The same data the+ * "Surveillance under Surveillance" map (sunders) shows.+ */+data class CctvCamera(+ val osmId: String,+ val lat: Double,+ val lon: Double,+ /** `surveillance`: public, outdoor (private, facing outside), indoor - or null if not mapped. */+ val zone: String?,+ /** `camera:type`: fixed, dome, panning. */+ val cameraType: String?,+ /** `camera:direction` in degrees (0 = north), if mapped. */+ val direction: Int?,+ /** `camera:angle`: the view's width in degrees, if mapped. */+ val angle: Int?,+ /** Height above the ground in metres, if mapped. */+ val height: Double?,+ val operator: String?,+ /** `camera:mount`: pole, wall, ceiling... */+ val mount: String?,+ /** `surveillance:zone`: town, traffic, shop, parking... */+ val area: String?+) {+ /** Public street cameras, or unmapped (shown by default); private outdoor / indoor ones only on request. */+ val isPrivate get() = zone.equals("outdoor", true) || zone.equals("indoor", true)+}++object Cctv {++ /** Overpass query for the surveillance cameras in a box (plate readers have their own layer). */+ fun query(south: Double, west: Double, north: Double, east: Double): String {+ val b = "($south,$west,$north,$east)"+ return "[out:json][timeout:60];" ++ "nwr[\"man_made\"=\"surveillance\"][\"surveillance:type\"=\"camera\"]$b;" ++ "out tags center qt;"+ }++ fun parse(json: String): List<CctvCamera> {+ val root = JsonParser.parseString(json).asJsonObject+ val elements = root.getAsJsonArray("elements") ?: return emptyList()+ return elements.mapNotNull { el ->+ val o = el.asJsonObject+ val type = o.get("type")?.asString ?: return@mapNotNull null+ val id = o.get("id")?.asLong ?: return@mapNotNull null+ val pos = if (o.has("lat")) o else o.getAsJsonObject("center") ?: return@mapNotNull null+ val lat = pos.get("lat")?.asDouble ?: return@mapNotNull null+ val lon = pos.get("lon")?.asDouble ?: return@mapNotNull null+ val tags = o.getAsJsonObject("tags")+ fun tag(vararg keys: String) = keys.firstNotNullOfOrNull { k -> tags?.get(k)?.asString?.trim()?.takeIf { it.isNotEmpty() } }+ CctvCamera(+ osmId = "$type/$id", lat = lat, lon = lon,+ zone = tag("surveillance")?.lowercase(),+ cameraType = tag("camera:type")?.lowercase(),+ direction = KnownCameras.parseDirection(tag("camera:direction", "direction")),+ angle = tag("camera:angle")?.let(::parseAngle),+ height = tag("height", "camera:height")?.let(::parseHeight),+ operator = tag("operator", "surveillance:operator"),+ mount = tag("camera:mount")?.lowercase(),+ area = tag("surveillance:zone")?.lowercase()+ )+ }+ }++ /** "60", "60°" -> 60; a range "40-90" -> its upper end. Null if not a sensible width. */+ fun parseAngle(v: String): Int? =+ Regex("(\\d{1,3})").findAll(v).lastOrNull()?.value?.toIntOrNull()?.takeIf { it in 5..360 }++ /** "4", "4.5 m", "4,5" -> metres. */+ fun parseHeight(v: String): Double? =+ Regex("(\\d+(?:[.,]\\d+)?)").find(v)?.value?.replace(',', '.')?.toDoubleOrNull()?.takeIf { it in 0.5..100.0 }++ /**+ * How far the drawn view reaches (m): higher cameras see further. Like sunders: about+ * 5x the mounting height, 15-60 m; 25 m when the height isn't mapped.+ */+ fun viewRangeM(c: CctvCamera): Double = c.height?.let { (it * 5).coerceIn(15.0, 60.0) } ?: 25.0++ /** The drawn view's width (degrees): the mapped angle, else 60° for fixed / 90° for dome cameras. */+ fun viewAngle(c: CctvCamera): Int = c.angle ?: if (c.cameraType == "dome") 90 else 60++ /** A short title for the tap dialog: "Public dome camera", "Private camera (facing outside)"... */+ fun title(c: CctvCamera): String {+ val kind = when (c.cameraType) { "dome" -> "dome camera"; "panning" -> "panning camera"; "fixed" -> "fixed camera"; else -> "camera" }+ return when (c.zone) {+ "public" -> "Public $kind"+ "outdoor" -> "Private $kind (facing outside)"+ "indoor" -> "Indoor $kind"+ else -> "Surveillance $kind"+ }+ }+}++/**+ * Offline cache of the CCTV cameras. With the layer on, everything within the camera+ * download radius (Settings, 100 km by default) around you is fetched in the background,+ * in tiles; panning further away fetches the area on screen. Overpass, like the plate+ * cameras: only the areas are sent.+ */+object CctvStore {++ private const val FILE = "cctv.json"+ private const val AREAS_FILE = "cctv_areas.json"+ /** Largest box one request covers (degrees, ~55 km): city regions hold tens of thousands of cameras. */+ const val MAX_SPAN_DEG = 0.5+ private const val MIN_SPAN_DEG = 0.1+ /** Downloaded areas are fetched again after this long. */+ private const val REFRESH_MS = 14 * 24 * 3600_000L+ private const val RETRY_MS = 60_000L+ /** Keeps the cache bounded. */+ private const val MAX_CAMERAS = 150_000++ private val gson = Gson()+ private val listType = object : TypeToken<List<CctvCamera>>() {}.type+ private val areaListType = object : TypeToken<List<CameraArea>>() {}.type+ private val scope = kotlinx.coroutines.CoroutineScope(Dispatchers.Main + kotlinx.coroutines.SupervisorJob())++ @Volatile var cameras: List<CctvCamera> = emptyList()+ private set+ @Volatile private var areas: List<CameraArea> = emptyList()+ @Volatile private var loaded = false+ private val busy = java.util.concurrent.atomic.AtomicBoolean(false)+ @Volatile private var lastFailed: CameraArea? = null+ /** When the last download failed (0 = the last one worked), for the map's status line. */+ @Volatile var lastFailureAt = 0L+ private set+ val isBusy get() = busy.get()++ /** The download around you while it runs ("4/24 areas, 1234 found"), else null. */+ @Volatile var progress: String? = null+ private set+ /** Called on the main thread while cameras are being added (the map redraws). */+ @Volatile var onChanged: (() -> Unit)? = null++ /** True when the box isn't covered by a fresh download yet. */+ fun needsDownload(south: Double, west: Double, north: Double, east: Double) =+ CameraArea.needsDownload(areas, south, west, north, east, System.currentTimeMillis(), REFRESH_MS)++ private fun file(c: Context) = File(c.filesDir, FILE)+ private fun areasFile(c: Context) = File(c.filesDir, AREAS_FILE)++ @Synchronized+ fun load(context: Context) {+ if (loaded) return+ cameras = runCatching { file(context).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<CctvCamera>>(it, listType) } }+ .getOrNull().orEmpty()+ areas = runCatching { areasFile(context).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<CameraArea>>(it, areaListType) } }+ .getOrNull().orEmpty()+ loaded = true+ }++ /**+ * Makes sure everything within [radiusKm] of a point is cached: downloads the missing+ * tiles in the background, one run at a time.+ */+ fun ensureAround(context: Context, lat: Double, lon: Double, radiusKm: Double) {+ val app = context.applicationContext+ if (busy.get()) return+ scope.launch {+ withContext(Dispatchers.IO) { load(app) }+ val tiles = CameraArea.tilesAround(lat, lon, radiusKm, MAX_SPAN_DEG)+ .filter { needsDownload(it[0], it[1], it[2], it[3]) }+ if (tiles.isEmpty()) return@launch+ runCatching { downloadTiles(app, tiles) }+ }+ }++ /** "Download cameras around me" (Settings): the CCTV within the radius; how many were found. */+ suspend fun downloadAround(context: Context, lat: Double, lon: Double, radiusKm: Double, onProgress: (String) -> Unit = {}): Int {+ withContext(Dispatchers.IO) { load(context) }+ return downloadTiles(context, CameraArea.tilesAround(lat, lon, radiusKm, MAX_SPAN_DEG), onProgress)+ }++ /** Areas still missing after the last download around you (retried the next time the map opens). */+ @Volatile var missingAreas = 0+ private set++ /**+ * Downloads the tiles one by one, 2 s apart (the public servers rate-limit bursts), waiting+ * while a plate-camera download uses them. Failed tiles get two more rounds after 30 s and+ * 60 s; any still missing stay un-cached, so the next run picks them up.+ */+ private suspend fun downloadTiles(context: Context, tiles: List<DoubleArray>, onProgress: (String) -> Unit = {}): Int {+ if (!busy.compareAndSet(false, true)) return 0+ var found = 0+ var pending = tiles+ try {+ for (round in 0 until 3) {+ if (pending.isEmpty()) break+ if (round > 0) {+ val text = "retrying ${pending.size} area${if (pending.size == 1) "" else "s"} the servers refused, $found found"+ progress = text; onProgress(text); onChanged?.invoke()+ kotlinx.coroutines.delay(30_000L * round)+ }+ val failed = mutableListOf<DoubleArray>()+ pending.forEachIndexed { i, t ->+ // Let a plate-camera download finish first: both hit the same servers.+ var waited = 0+ while ((AlprStore.isBusy || DeflockBulk.isRunning) && waited < 120) { kotlinx.coroutines.delay(1_000); waited++ }+ val text = (if (round == 0) "${i + 1}/${pending.size} areas" else "retry ${i + 1}/${pending.size}") + ", $found found"+ progress = text; onProgress(text); onChanged?.invoke()+ try {+ val json = AlprStore.fetchFirst("data=" + URLEncoder.encode(Cctv.query(t[0], t[1], t[2], t[3]), "UTF-8")) { }+ val cams = withContext(Dispatchers.Default) { Cctv.parse(json) }+ found += cams.size+ withContext(Dispatchers.Default) { mergeInMemory(CameraArea(t[0], t[1], t[2], t[3], System.currentTimeMillis()), cams) }+ onChanged?.invoke()+ } catch (ex: kotlinx.coroutines.CancellationException) {+ throw ex+ } catch (ex: Exception) {+ failed += t+ android.util.Log.w("CctvStore", "CCTV tile failed (round ${round + 1}): ${ex.message}")+ }+ if (i < pending.size - 1) kotlinx.coroutines.delay(2_000)+ }+ pending = failed+ }+ missingAreas = pending.size+ lastFailureAt = if (pending.size == tiles.size && tiles.isNotEmpty()) System.currentTimeMillis() else 0L+ } finally {+ withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { save(context) }+ progress = null+ busy.set(false)+ onChanged?.invoke()+ }+ if (pending.size == tiles.size && tiles.isNotEmpty()) throw java.io.IOException("OpenStreetMap servers busy - try again later")+ return found+ }++ /** Fetches the area on screen if it isn't cached (outside the area around you); true when the cache changed. */+ suspend fun autoDownload(context: Context, south: Double, west: Double, north: Double, east: Double): Boolean {+ withContext(Dispatchers.IO) { load(context) }+ val now = System.currentTimeMillis()+ if (!CameraArea.needsDownload(areas, south, west, north, east, now, REFRESH_MS)) return false+ if (lastFailed?.let { now - it.time < RETRY_MS && it.contains(south, west, north, east) } == true) return false+ if (!busy.compareAndSet(false, true)) return false+ val (s, w, n, e) = expand(south, west, north, east)+ return try {+ val json = AlprStore.fetchFirst("data=" + URLEncoder.encode(Cctv.query(s, w, n, e), "UTF-8")) { }+ val found = withContext(Dispatchers.Default) { Cctv.parse(json) }+ withContext(Dispatchers.Default) { mergeInMemory(CameraArea(s, w, n, e, System.currentTimeMillis()), found) }+ withContext(Dispatchers.IO) { save(context) }+ lastFailureAt = 0L+ true+ } catch (ex: kotlinx.coroutines.CancellationException) {+ throw ex+ } catch (ex: Exception) {+ android.util.Log.w("CctvStore", "CCTV download failed: ${ex.message}")+ lastFailed = CameraArea(s, w, n, e, System.currentTimeMillis())+ lastFailureAt = System.currentTimeMillis()+ false+ } finally {+ busy.set(false)+ }+ }++ /** The visible box doubled, between [MIN_SPAN_DEG] and [MAX_SPAN_DEG] a side. */+ fun expand(s: Double, w: Double, n: Double, e: Double): List<Double> {+ fun pad(span: Double) = (((span * 2).coerceIn(MIN_SPAN_DEG, MAX_SPAN_DEG) - span) / 2).coerceAtLeast(0.0)+ val lat = pad(n - s); val lon = pad(e - w)+ return listOf(s - lat, w - lon, n + lat, e + lon)+ }++ @Synchronized+ private fun mergeInMemory(area: CameraArea, found: List<CctvCamera>) {+ val outside = cameras.filterNot { it.lat in area.south..area.north && it.lon in area.west..area.east }+ cameras = (found + outside).distinctBy { it.osmId }.take(MAX_CAMERAS)+ areas = (areas.filterNot { area.contains(it) } + area).takeLast(600)+ }++ @Synchronized+ private fun save(context: Context) {+ runCatching {+ withTmp(file(context)) { it.writeText(gson.toJson(cameras)) }+ withTmp(areasFile(context)) { it.writeText(gson.toJson(areas)) }+ }+ }++ private fun withTmp(target: File, write: (File) -> Unit) {+ val tmp = File(target.parentFile, target.name + ".tmp")+ write(tmp)+ if (!tmp.renameTo(target)) { target.delete(); tmp.renameTo(target) }+ }++ @Synchronized+ fun clear(context: Context) {+ file(context).delete(); areasFile(context).delete()+ cameras = emptyList(); areas = emptyList()+ }++ @androidx.annotation.VisibleForTesting+ fun setForTest(list: List<CctvCamera>) { cameras = list; loaded = true }+}diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.ktindex df9450d..6988852 100644--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt@@ -148,7 +148,7 @@ object CarUi {devices: List<DeviceRegistry.Snapshot>, threshold: Int,ambient: com.rfsentinel.app.online.AmbientThreats.Threat? = null): Pair<Int, String> {- val flagged = devices.filter { isFlagged(it) }+ val flagged = devices.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it) }val following = flagged.firstOrNull { it.following }val top = flagged.maxByOrNull { it.best!!.confidence }// A camera close by, a police aircraft or a Waze report, when it outranks the devices.diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.ktindex e506e87..67c51d5 100644--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt@@ -48,7 +48,7 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {return Model(running = running,devices = devices.size,- flagged = devices.count { CarUi.isFlagged(it) },+ flagged = devices.count { com.rfsentinel.app.ui.LiveWindow.alerting(it) },headline = if (running) CarUi.threat(devices, Prefs.alertThreshold(carContext),com.rfsentinel.app.online.AmbientThreats.top(carContext)) else null,camera = CarUi.nextCamera(carContext),diff --git a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.ktindex 2319b03..55a321e 100644--- a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt+++ b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt@@ -181,7 +181,7 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {val silenced = CarUi.silencedText(this)return listOfNotNull(playable(ACTION_SCAN, if (running) "Stop scanning" else "Start scanning",- if (running) "Scanning · ${devices.size} nearby · ${devices.count { CarUi.isFlagged(it) }} flagged" else "Not scanning",+ if (running) "Scanning · ${devices.size} nearby · ${devices.count { com.rfsentinel.app.ui.LiveWindow.alerting(it) }} flagged" else "Not scanning",dot(if (running) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)),playable(ACTION_MUTE, if (silenced.isEmpty()) "Mute alerts for 30 minutes" else "Turn alert sound back on",silenced.ifEmpty { "Alert sound and voice are on" }, dot(if (silenced.isEmpty()) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)),@@ -218,6 +218,12 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {refresh()}+ /** Voice "play RF Sentinel" in the car: starts scanning (never stops it). */+ override fun onPlayFromSearch(query: String?, extras: Bundle?) {+ if (!ScanForegroundService.isRunning) toggleScan()+ refresh()+ }+override fun onSkipToNext() = step(1)override fun onSkipToPrevious() = step(-1)}@@ -290,8 +296,8 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {val ambient = com.rfsentinel.app.online.AmbientThreats.top(this)val (color, text) = CarUi.threat(devices, Prefs.alertThreshold(this), ambient)val lead = ambient?.takeIf { it.label == text }- val top = devices.filter { CarUi.isFlagged(it) }.maxByOrNull { it.best!!.confidence }- val line = listOf("${devices.size} nearby · ${devices.count { CarUi.isFlagged(it) }} flagged", CarUi.silencedText(this))+ val top = devices.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it) }.maxByOrNull { it.best!!.confidence }+ val line = listOf("${devices.size} nearby · ${devices.count { com.rfsentinel.app.ui.LiveWindow.alerting(it) }} flagged", CarUi.silencedText(this)).filter { it.isNotEmpty() }.joinToString(" · ")if (lead != null) return Card(HEADLINE, text, line, null, color, lead.category.shortTag, "${lead.score}%")return Card(HEADLINE, text, line, top?.let { CarUi.signalLine(it) }, color,diff --git a/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.kt b/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.ktnew file mode 100644index 0000000..0d6ac95--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.kt@@ -0,0 +1,35 @@+package com.rfsentinel.app.detect++/**+ * Keeps the weak Flock clues from flagging everyday gadgets. The "community list" module+ * prefixes (Liteon, Silicon Labs, Espressif... chips Flock cameras happen to use) and the+ * generic "FS-<hex>" name are shared with speakers, scooters, bulbs and meeting-room boxes:+ * - a module-prefix match is dropped when the device names itself as something else+ * (a Flock module has no name or a Flock-style one);+ * - outside Flock's market (France preset on, US and Canada off) both are dropped entirely.+ * Strong Flock signatures (Penguin / Falcon / Raven names, Flock's own service, the+ * battery name, XUNTONG ID) are never touched.+ */+object FlockNoise {++ /** Names a Flock camera, battery or module can carry. */+ private val FLOCK_NAME = Regex("^(penguin|fs[ -]|flock|falcon|sparrow|raven|\\d{8,12}$)", RegexOption.IGNORE_CASE)++ fun isCommunityPrefix(h: Hit) =+ h.category == Category.ALPR && h.label.contains("seen on Flock", ignoreCase = true) &&+ h.label.contains("community list", ignoreCase = true)++ fun isGenericFsName(h: Hit) =+ h.category == Category.ALPR && h.evidence.contains("generic white-label", ignoreCase = true)++ fun filter(hits: List<Hit>, name: String?, flockRegion: Boolean): List<Hit> {+ val named = name?.trim()?.takeIf { it.isNotEmpty() }+ return hits.filterNot { h ->+ when {+ isCommunityPrefix(h) -> !flockRegion || (named != null && !FLOCK_NAME.containsMatchIn(named))+ isGenericFsName(h) -> !flockRegion+ else -> false+ }+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.ktindex 83bf6db..10e2777 100644--- a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt@@ -46,7 +46,7 @@ object HackerWatch {/** Default WiFi / Bluetooth names of action cameras whose makers use generic chips. */private val ACTION_CAMERA_NAMES = listOf(- Regex("osmo ?(action|pocket|360)", RegexOption.IGNORE_CASE) to "DJI Osmo camera",+ Regex("osmo ?(action|pocket|360|nano)", RegexOption.IGNORE_CASE) to "DJI Osmo camera",Regex("^(hero\\d{1,2}\\b|gp\\d{8}$)", RegexOption.IGNORE_CASE) to "GoPro camera",Regex("^(sjcam|sj\\d{1,2}(pro|air|c)?\\b|sj\\d{4})", RegexOption.IGNORE_CASE) to "SJCAM camera",Regex("akaso", RegexOption.IGNORE_CASE) to "AKASO camera",diff --git a/app/src/main/java/com/rfsentinel/app/detect/RemoteId.kt b/app/src/main/java/com/rfsentinel/app/detect/RemoteId.ktindex 5bc5302..994877a 100644--- a/app/src/main/java/com/rfsentinel/app/detect/RemoteId.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/RemoteId.kt@@ -11,6 +11,9 @@ package com.rfsentinel.app.detect* [0x0D app code][counter][25-byte message or message pack]* - WiFi beacons: vendor IE (221) with OUI FA:0B:BC, type 0x0D, then* [counter][message pack]+ * - The French "signalement electronique" (decree / arrêté of 27 Dec 2019, required in+ * France since June 2020 for drones of 800 g and more): vendor IE with OUI 6A:5C:35,+ * type 0x01, then TLVs (layout from the reference beacon github.com/khancyr/droneID_FR).*/object RemoteId {@@ -55,14 +58,65 @@ object RemoteId {/** Decodes a WiFi vendor IE payload (starting at the OUI), merging into [prev]. */fun decodeWifiIe(ie: ByteArray, prev: Info?): Info? {- if (!isWifiIe(ie) || ie.size < 5 + 3) return null+ if (isFrenchIe(ie)) return decodeFrench(ie, prev ?: Info())+ if (!isAstmWifiIe(ie) || ie.size < 5 + 3) return nullreturn decodeMessage(ie, 5, prev ?: Info())}- fun isWifiIe(ie: ByteArray): Boolean =+ /** ASTM F3411 or French drone ID vendor IE. */+ fun isWifiIe(ie: ByteArray): Boolean = isAstmWifiIe(ie) || isFrenchIe(ie)++ fun isAstmWifiIe(ie: ByteArray): Boolean =ie.size >= 4 && Bytes.u8(ie, 0) == 0xFA && Bytes.u8(ie, 1) == 0x0B &&Bytes.u8(ie, 2) == 0xBC && Bytes.u8(ie, 3) == APP_CODE+ fun isFrenchIe(ie: ByteArray): Boolean =+ ie.size >= 4 && Bytes.u8(ie, 0) == 0x6A && Bytes.u8(ie, 1) == 0x5C &&+ Bytes.u8(ie, 2) == 0x35 && Bytes.u8(ie, 3) == 0x01++ /**+ * French TLVs: 2 = French ID (30 chars), 3 = ANSI/CTA-2063 serial, 4/5 = latitude /+ * longitude (int32 big-endian, degrees x 1e5), 6 = altitude MSL (int16 m), 7 = height+ * above take-off (int16 m), 8/9 = take-off point, 10 = ground speed (m/s), 11 = heading (deg).+ */+ private fun decodeFrench(b: ByteArray, info: Info): Info {+ var acc = info.copy(uaType = info.uaType ?: "Drone (French electronic ID)")+ var i = 4+ while (i + 2 <= b.size) {+ val type = Bytes.u8(b, i)+ val len = Bytes.u8(b, i + 1)+ val v = i + 2+ if (v + len > b.size) break+ fun int(): Int {+ var x = 0+ for (k in 0 until len) x = (x shl 8) or Bytes.u8(b, v + k)+ val bits = len * 8+ return if (bits in 1..31 && x and (1 shl (bits - 1)) != 0) x - (1 shl bits) else x+ }+ acc = when (type) {+ 2 -> Bytes.ascii(b, v, len)?.trim()?.takeIf { it.isNotEmpty() }+ ?.let { acc.copy(uasId = it, idType = "French ID (signalement électronique)") } ?: acc+ 3 -> if (acc.idType?.startsWith("French") == true) acc else Bytes.ascii(b, v, len)?.trim()+ ?.takeIf { it.isNotEmpty() }?.let { acc.copy(uasId = it, idType = ID_TYPES[1]) } ?: acc+ 4 -> if (len == 4) acc.copy(latitude = int() * 1e-5) else acc+ 5 -> if (len == 4) acc.copy(longitude = int() * 1e-5) else acc+ 6 -> if (len == 2) acc.copy(altitudeGeoM = int().toDouble()) else acc+ 7 -> if (len == 2) acc.copy(heightM = int().toDouble()) else acc+ 8 -> if (len == 4) acc.copy(operatorLatitude = int() * 1e-5) else acc+ 9 -> if (len == 4) acc.copy(operatorLongitude = int() * 1e-5) else acc+ 10 -> if (len == 1) acc.copy(speedMs = Bytes.u8(b, v).toDouble()) else acc+ 11 -> if (len == 2) acc.copy(directionDeg = int().takeIf { it in 0..359 } ?: acc.directionDeg) else acc+ else -> acc+ }+ i = v + len+ }+ // (0, 0) means no GPS fix yet.+ if (acc.latitude == 0.0 && acc.longitude == 0.0) acc = acc.copy(latitude = info.latitude, longitude = info.longitude)+ if (acc.operatorLatitude == 0.0 && acc.operatorLongitude == 0.0)+ acc = acc.copy(operatorLatitude = info.operatorLatitude, operatorLongitude = info.operatorLongitude)+ return acc+ }+fun isBleRemoteId(serviceData: ByteArray): Boolean =serviceData.size >= 2 + MESSAGE_SIZE && Bytes.u8(serviceData, 0) == APP_CODEdiff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.ktindex e53375b..23cfbc4 100644--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt@@ -402,7 +402,11 @@ object SignatureEngine {// its WPS device name, not a network).if (a.wifi?.client != true) policeVehicleSsid(ssid)?.let { hits += it }a.wifi?.infoElements?.firstOrNull { it.first == 221 && RemoteId.isWifiIe(it.second) }?.let {- hits += Hit(Category.DRONE, "Drone broadcasting Remote ID (WiFi)", 95,+ hits += if (RemoteId.isFrenchIe(it.second))+ Hit(Category.DRONE, "Drone broadcasting its French electronic ID (WiFi)", 95,+ "French \"signalement électronique\" vendor information element (OUI 6A:5C:35) in the WiFi beacon",+ "Arrêté of 27 December 2019 (France); github.com/khancyr/droneID_FR")+ else Hit(Category.DRONE, "Drone broadcasting Remote ID (WiFi)", 95,"ASTM F3411 vendor information element (OUI FA:0B:BC) in the WiFi beacon", ASTM)}if (!isLocallyAdministered(a.mac)) {@@ -426,8 +430,12 @@ object SignatureEngine {return hits}+ /** DJI's handheld cameras and gimbals share its address blocks; they aren't drones. */+ private val DJI_HANDHELD = Regex("^(dji ?)?osmo|^om ?\\d", RegexOption.IGNORE_CASE)+private fun droneByPrefix(a: Advert): Hit? {if (isLocallyAdministered(a.mac)) return null+ if (a.name?.trim()?.let { DJI_HANDHELD.containsMatchIn(it) } == true) return nullval (prefix, vendor) = DRONE_PREFIXES.match(a.mac) ?: return nullreturn Hit(Category.DRONE, "$vendor equipment (drone or controller)", 60,"Address in $vendor's registered block ${fmtPrefix(prefix)}; no Remote ID decoded",diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.ktindex 8a86d9c..1e16420 100644--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt@@ -39,15 +39,31 @@ object OuiWatchlist {val all: List<OuiEntry>)+ /**+ * False when only the France preset is on among the regional ones (no US / Canada): Flock+ * isn't deployed there, so its weak module-prefix clues are ignored (see FlockNoise).+ */+ @Volatile+ var flockRegion = true+ private set++ /** Bumped on every (re)load, so a running scan can re-check devices against the new list. */+ @Volatile+ var version = 0+ private set+@Volatileprivate var state = State(emptyMap(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyList())- val availablePresets = listOf("global", "canada", "us")+ /** Load order: regional presets after "global", so their labels win for shared prefixes. */+ val availablePresets = listOf("global", "canada", "us", "france")@Synchronizedfun load(context: Context) {val byKey = linkedMapOf<String, OuiEntry>()- for (preset in getEnabledPresets(context)) {+ val enabled = getEnabledPresets(context)+ flockRegion = "france" !in enabled || "us" in enabled || "canada" in enabled+ for (preset in availablePresets.filter { it in enabled }) {loadPresetAsset(context, preset).forEach { byKey[it.prefix] = it }}readCustom(context).forEach { byKey[it.prefix] = it }@@ -60,6 +76,7 @@ object OuiWatchlist {fingerprintRules = all.filter { it.isFingerprintRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },all = all)+ version++}private fun loadPresetAsset(context: Context, preset: String): List<OuiEntry> {diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.ktindex 0224cf5..b6901aa 100644--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt@@ -286,6 +286,21 @@ object DeviceRegistry {}/** Full snapshot (history, path, raw advert) for the detail screen. */+ /** The last advert of every device in this session (to re-check them after the watchlist changes). */+ fun lastAdverts(): List<Advert> = tracks.values.mapNotNull { t -> synchronized(t) { t.advert } }++ /**+ * Replaces a device's matches right away (watchlist changed): a held match that the+ * fresh evaluation no longer produces is dropped instead of lingering for [HIT_HOLD_MS].+ */+ fun replaceHits(mac: String, hits: List<Hit>) {+ val t = tracks[mac] ?: return+ synchronized(t) {+ if (t.heldHit?.let { h -> hits.none { it.label == h.label } } == true) { t.heldHit = null; t.heldUntil = 0L }+ t.hits = hits.sortedByDescending { it.confidence }+ }+ }+fun get(mac: String): Snapshot? = tracks[mac]?.let { t -> synchronized(t) { snap(t, full = true) } }/** Devices heard since [since] with their summary, for persisting to known_devices. */diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex ba0563a..e92c30b 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -64,10 +64,11 @@ import java.util.concurrent.ConcurrentHashMapclass ScanForegroundService : Service() {companion object {- /** Radar beeps: start after the alert's own beeps, last up to 2 min, stop 10 s after the device is lost. */+ /** Radar beeps: start after the alert's own beeps, last up to 2 min, stop once the device is out of range. */private const val RADAR_QUIET_MS = 2_500Lprivate const val RADAR_HOLD_MS = 120_000L- private const val RADAR_LOST_MS = 10_000L+ /** "GPS connected" again only after the fix was lost this long. */+ private const val GPS_RECONNECT_MS = 120_000Lprivate const val TAG = "ScanForegroundService"const val ACTION_STOP = "com.rfsentinel.app.action.STOP"@@ -180,7 +181,15 @@ class ScanForegroundService : Service() {@Volatile private var lastLocation: Location? = nullprivate var locationListening = falseprivate var locationFastMode = false+ /** Radar-detector sound style: last good GPS fix, to say "GPS connected" when it locks or comes back. */+ private var lastGoodGpsAt = 0L+private val locationListener = LocationListener {+ if (it.provider == LocationManager.GPS_PROVIDER && it.hasAccuracy() && it.accuracy <= 50f) {+ val now = System.currentTimeMillis()+ if (now - lastGoodGpsAt > GPS_RECONNECT_MS) AlertPlayer.gpsConnected(this)+ lastGoodGpsAt = now+ }lastLocation = itlastFix = itTripRecorder.onLocation(it)@@ -257,6 +266,9 @@ class ScanForegroundService : Service() {}DeviceRegistry.startSession()classified.clear()+ lastGoodGpsAt = 0L+ AlertPlayer.preload(this)+ AlertPlayer.startup(this)serviceScope.launch { pruneOldData() }}@@ -358,7 +370,9 @@ class ScanForegroundService : Service() {while (isActive) {holdAwake()wifiEngine.requestScan()- delay(Prefs.scanIntervalMs(this@ScanForegroundService))+ val interval = Prefs.scanIntervalMs(this@ScanForegroundService)+ com.rfsentinel.app.ui.LiveWindow.wifiScanMs = interval+ delay(interval)}}}@@ -431,6 +445,7 @@ class ScanForegroundService : Service() {private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null) {val now = a.timestampval mac = a.mac+ if (OuiWatchlist.version != watchlistVersion) recheckWatchlist(now)// Remote ID messages arrive one type at a time; merge every packet.var remoteId: RemoteId.Info? = reportedRemoteId@@ -551,6 +566,24 @@ class ScanForegroundService : Service() {process(advert, e.remoteId)}+ /** The watchlist version the cached classifications were made with. */+ private var watchlistVersion = OuiWatchlist.version++ /**+ * The watchlist changed (entry added or removed, preset switched): re-check every device+ * now instead of waiting for cached results and held matches to expire. A device that is+ * no longer flagged stops its radar beeps and can alert again if it's re-added.+ */+ private fun recheckWatchlist(now: Long) {+ watchlistVersion = OuiWatchlist.version+ classified.clear()+ for (a in DeviceRegistry.lastAdverts()) {+ val c = classify(a, now)+ DeviceRegistry.replaceHits(a.mac, c.hits)+ if (c.hits.isEmpty()) lastAlerted.remove(a.mac)+ }+ }+private fun classify(a: Advert, now: Long, extra: List<Hit> = emptyList()): Classified {val macVendor = VendorDb.macVendor(a.mac)val identity = DeviceIntel.identify(a, macVendor)@@ -566,7 +599,7 @@ class ScanForegroundService : Service() {probeHits[a.mac]?.takeIf { now - it.first < ESP_HIT_TTL_MS }?.second.orEmpty() +extraval noAirTags = Prefs.excludeAirTags(this)- val hits = EvidenceFusion.fuse(raw.filter {+ val hits = EvidenceFusion.fuse(com.rfsentinel.app.detect.FlockNoise.filter(raw, a.name, OuiWatchlist.flockRegion).filter {Prefs.categoryEnabled(this, it.category) && !(noAirTags && SignatureEngine.isAppleFindMy(it))})return Classified(now, hits, identity, vendor)@@ -736,7 +769,7 @@ class ScanForegroundService : Service() {delay(STATUS_INTERVAL_MS)holdAwake()val devices = DeviceRegistry.snapshot()- val flagged = devices.count { d -> d.best != null && !WhitelistCache.contains(d.mac) }+ val flagged = devices.count { d -> com.rfsentinel.app.ui.LiveWindow.alerting(d) }val text = "${devices.size} device${if (devices.size == 1) "" else "s"} nearby" +if (flagged > 0) " · $flagged flagged" else ""NotificationHelper.updateServiceNotification(this@ScanForegroundService, text)@@ -998,7 +1031,7 @@ class ScanForegroundService : Service() {val target = if (!Prefs.radarBeep(ctx)) null else lastAlerted.entries.filter { now - it.value in RADAR_QUIET_MS..RADAR_HOLD_MS && !WhitelistCache.contains(it.key) }.mapNotNull { DeviceRegistry.get(it.key) }- .filter { now - it.lastSeen <= RADAR_LOST_MS }+ .filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }.maxByOrNull { it.rssi }if (target == null) delay(1_000L)else {@@ -1027,7 +1060,8 @@ class ScanForegroundService : Service() {com.rfsentinel.app.ui.FloatingMap.hide(ctx)} else {val devices = DeviceRegistry.snapshot()- val flagged = devices.filter { it.best != null && !WhitelistCache.contains(it.mac) }+ // Only devices still in range: the bubble clears as soon as a threat is gone.+ val flagged = devices.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it) }val threshold = Prefs.alertThreshold(ctx)val top = flagged.maxOfOrNull { it.best!!.confidence } ?: 0val cellWarning = CellMonitor.lastAnomaly?.takeIf { System.currentTimeMillis() - it.first < 15 * 60_000L }@@ -1093,6 +1127,7 @@ class ScanForegroundService : Service() {runCatching { (getSystemService(LOCATION_SERVICE) as LocationManager).removeUpdates(locationListener) }locationListening = false}+ AlertPlayer.stopIntro()serviceScope.cancel()pipelineThread.quitSafely()cellMonitor?.close()diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex f5f7623..9d70c0c 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,9 @@ import kotlinx.coroutines.launchclass SettingsActivity : AppCompatActivity() {companion object {+ /** 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 = "Waze police reports are read through OpenWeb Ninja's Waze API with your own API key.\n\n" +@@ -293,7 +296,8 @@ class SettingsActivity : AppCompatActivity() {"WiFi interval: Android allows about one WiFi scan per 30 s unless \"Wi-Fi scan throttling\" " +"is turned off in Developer options; then down to 5 s works, at some battery cost.\n\n" +"Background scanning: lets the scan keep running with the screen off.\n\n" +- "Remove from the list: how long an ordinary device stays in the list and radar once it stops being heard (default 30 s Bluetooth, 60 s WiFi). Flagged, favourite and following devices always stay 3 minutes."),+ "Remove from the list: how long an ordinary device stays in the list and radar once it stops being heard (default 30 s Bluetooth, 60 s WiFi). Flagged devices follow these too; favourite and following devices stay 3 minutes. " ++ "Both can go down to 5 s (WiFi only when Developer options are on and the WiFi interval is under 30 s)."),Section("autostart", binding.headerAutoStart, binding.sectionAutoStart,"When the phone starts: begins scanning after a reboot.\n\n" +"In the car: starts scanning when the phone connects to your car's Bluetooth and stops when you leave. " +@@ -312,12 +316,20 @@ class SettingsActivity : AppCompatActivity() {"Watchlist presets are lists of vendor MAC prefixes:\n" +"• Global: Axon, Flock, Zepcam, WatchGuard, Digital Ally, ShotSpotter, traffic cameras...\n" +"• Canada: Axon, Cyberkar, Getac, Genetec, Motorola, ticket printers...\n" +- "• United States"),+ "• United States\n" ++ "• France: Motorola VB400 body cams (Police nationale, Gendarmerie), Zepcam, Axon, TETRAPOL radios, Idemia. " ++ "French drone electronic IDs are decoded in every region. With France on (and not US / Canada), " ++ "the weak Flock clues are ignored: Flock isn't used in France."),Section("alerts", binding.headerAlerts, binding.sectionAlerts,"Threshold: \"Weak\" alerts on every match (more false alarms); \"Strong only\" on near-certain ones.\n\n" +"Vibration: 1 pulse weak, 2 probable, 3 strong.\n\n" +"Radar-detector beeps (off by default): after a device alert, keeps beeping faster as its signal " +"gets stronger, like a radar detector; stops when it's gone or after 2 minutes.\n\n" ++ "Radar-detector sound (off by default): radar-detector alert sounds instead of the plain beeps - " ++ "by strength (effect 1 strong, 2 probable, 3 weak, 4 following) or always the effect you pick - then " ++ "the short voice says what it is (\"Body cam\"); the proximity beeps use a pulse of the same effect. " ++ "A power-on sweep when a scan starts, and \"GPS connected\" when the GPS locks.\n\n" ++ "Intro sound (off by default): plays when a scan starts.\n\n" +"Re-alert: how long before the same device can alert again."),Section("voice", binding.headerVoice, binding.sectionVoice,"Speaks each alert, for example while driving. Short alerts say just the type " +@@ -330,13 +342,22 @@ class SettingsActivity : AppCompatActivity() {Section("follow", binding.headerFollow, binding.sectionFollow,"Warns when a tracker or flagged device keeps moving with you for at least the time and distance set here.\n\n" +"Your own tag: long-press it in the list > Ignore this tracker."),+ Section("map", binding.headerMap, binding.sectionMap,+ "What the map shows.\n\n" ++ "Plate, speed and red-light cameras: from OpenStreetMap (Known cameras has the downloads, warnings and CCTV).\n\n" ++ "Cell towers: placed where your phone heard each one strongest - an estimate, not the tower's real position."),Section("cameras", binding.headerCameras, binding.sectionCameras,"Plate-reader and speed / red-light camera positions come from OpenStreetMap.\n\n" +- "Show on the map: downloads the cameras of the area you look at (the Overpass server sees that area, like map tiles).\n\n" ++ "Download automatically: fetches the cameras of the map area you look at (the Overpass server sees that area, like map tiles).\n\n" +"Download around me: saves the cameras within the radius for offline use. Larger areas take longer and use more data.\n\n" +"US & Canada: every plate reader in DeFlock's hourly OpenStreetMap snapshot " +"(cdn.deflock.me sees only the download, not your position); refreshes weekly on Wi-Fi.\n\n" +- "To silence one camera: tap it on the map > Ignore alerts."),+ "To silence one camera: tap it on the map > Ignore alerts.\n\n" ++ "CCTV cameras: ordinary surveillance cameras volunteers mapped in OpenStreetMap (street, shop, building cameras). " ++ "Everything within the download radius around you is fetched in the background; they show from city zoom, with a " ++ "shaded area where their direction is mapped when you zoom in close. Most are wired, so the scan can't detect them. " ++ "Public ones by default; private outdoor and indoor ones on request. Map only, no alerts.\n\n" ++ "Delete downloaded cameras: removes the saved plate, speed, red-light and CCTV cameras (they download again as you use the map)."),Section("cell", binding.headerCell, binding.sectionCell,"Tower change alerts are frequent while driving; most useful when parked.\n\n" +"Turning off \"Allow 2G\" (Android 12+) is the strongest protection against fake towers: " +@@ -402,6 +423,8 @@ class SettingsActivity : AppCompatActivity() {if (i > 0) parent.addView(View(this).apply { setBackgroundColor(divider) }, at,android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, maxOf(1, dp.toInt())))s.body.setPadding(0, 0, 0, (10 * dp).toInt())+ val requested = intent.getStringExtra(EXTRA_SECTION) == s.key+ if (requested) ui.edit().putBoolean(s.key, true).apply()var open = ui.getBoolean(s.key, s.key in defaultOpen)fun show() {s.body.visibility = if (open) View.VISIBLE else View.GONE@@ -409,6 +432,8 @@ class SettingsActivity : AppCompatActivity() {row.contentDescription = "$title, ${if (open) "expanded" else "collapsed"}"}show()+ // After the sections above have laid out (expanded / collapsed), so the header lands on top.+ if (requested) binding.root.postDelayed({ if (!isFinishing) binding.root.smoothScrollTo(0, row.top) }, 250)row.setOnClickListener {open = !openui.edit().putBoolean(s.key, open).apply()@@ -417,6 +442,44 @@ class SettingsActivity : AppCompatActivity() {}}+ /** Settings > Map: what the map shows (moved here from the map's menu). Saved as you switch. */+ private fun setupMapSection() {+ binding.mapKnownCamerasSwitch.isChecked = Prefs.showKnownAlpr(this)+ binding.mapKnownCamerasSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowKnownAlpr(this, on) }+ binding.mapTowersSwitch.isChecked = Prefs.showCellTowers(this)+ binding.mapTowersSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowCellTowers(this, on) }+ binding.mapCctvSwitch.isChecked = Prefs.showCctv(this)+ binding.mapCctvPrivateSwitch.isChecked = Prefs.cctvPrivate(this)+ binding.mapCctvPrivateSwitch.isEnabled = binding.mapCctvSwitch.isChecked+ binding.mapCctvSwitch.setOnCheckedChangeListener { _, on ->+ Prefs.setShowCctv(this, on)+ binding.mapCctvPrivateSwitch.isEnabled = on+ }+ binding.mapCctvPrivateSwitch.setOnCheckedChangeListener { _, on -> Prefs.setCctvPrivate(this, on) }+ binding.mapTracesButton.setOnClickListener {+ startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java))+ }+ binding.mapDeleteCamerasButton.setOnClickListener {+ AlertDialog.Builder(this)+ .setTitle("Delete downloaded cameras?")+ .setMessage("Removes the saved plate, speed, red-light and CCTV cameras. They download again as you use the map.")+ .setPositiveButton("Delete") { _, _ ->+ // 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)+ com.rfsentinel.app.alpr.CctvStore.clear(this)+ // A running scan drops the deleted cameras from its warnings too.+ if (com.rfsentinel.app.service.ScanForegroundService.isRunning) runCatching {+ startService(Intent(this, com.rfsentinel.app.service.ScanForegroundService::class.java)+ .setAction(com.rfsentinel.app.service.ScanForegroundService.ACTION_REFRESH_LOCATION))+ }+ Toast.makeText(this, "Downloaded cameras deleted", Toast.LENGTH_SHORT).show()+ }+ .setNegativeButton("Cancel", null)+ .show()+ }+ }+/** A small grey line under a category switch, indented like the AirTag option. */private fun indentedNote(text: String) = android.widget.TextView(this).apply {this.text = text@@ -436,15 +499,46 @@ class SettingsActivity : AppCompatActivity() {* How long ordinary devices stay in the list and radar after they're last heard* (flagged, favourite and following ones always stay 3 minutes). Saved as you slide.*/+ /** True while the "Test intro" button's intro plays. */+ private var introTesting = false++ private val detectorEffectNames = arrayOf(+ "By strength (1 strong, 2 probable, 3 weak, 4 following)",+ "Effect 1", "Effect 2", "Effect 3", "Effect 4"+ )++ private fun updateDetectorEffectButton() {+ binding.detectorEffectButton.text = "Detector sound effect: " ++ detectorEffectNames[Prefs.detectorEffect(this)].substringBefore(" (")+ }++ /** Pick the radar-detector sound effect; each choice plays as a preview. */+ private fun chooseDetectorEffect() {+ var picked = Prefs.detectorEffect(this)+ AlertDialog.Builder(this)+ .setTitle("Detector sound effect")+ .setSingleChoiceItems(detectorEffectNames, picked) { _, which ->+ picked = which+ com.rfsentinel.app.util.AlertPlayer.previewEffect(this, which)+ }+ .setPositiveButton("OK") { _, _ ->+ Prefs.setDetectorEffect(this, picked)+ updateDetectorEffectButton()+ }+ .setNegativeButton("Cancel", null)+ .setOnDismissListener { com.rfsentinel.app.util.AlertPlayer.stopPreview(false) }+ .show()+ }+private fun addLiveWindowSliders() {- fun slider(label: (Int) -> String, from: Int, to: Int, value: Int, save: (Int) -> Unit) {+ fun slider(label: (Int) -> String, from: Int, to: Int, value: Int, save: (Int) -> Unit): com.google.android.material.slider.Slider {val text = android.widget.TextView(this).apply {textSize = 13fsetPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)this.text = label(value)}binding.sectionScanning.addView(text)- binding.sectionScanning.addView(com.google.android.material.slider.Slider(this).apply {+ val s = com.google.android.material.slider.Slider(this).apply {valueFrom = from.toFloat(); valueTo = to.toFloat(); stepSize = 5fthis.value = (value - value % 5).coerceIn(from, to).toFloat()setLabelFormatter { "${it.toInt()} s" }@@ -453,14 +547,35 @@ class SettingsActivity : AppCompatActivity() {if (!fromUser) return@addOnChangeListenersave(v.toInt()); text.text = label(v.toInt())}- })+ }+ binding.sectionScanning.addView(s)+ return s}- slider({ "Remove Bluetooth devices from the list after $it s out of range" }, 10, 180, Prefs.liveBleSec(this)) {+ slider({ "Remove Bluetooth devices from the list after $it s out of range" }, 5, 180, Prefs.liveBleSec(this)) {Prefs.setLiveBleSec(this, it)}- slider({ "Remove WiFi devices from the list after $it s out of range" }, 30, 180, Prefs.liveWifiSec(this)) {+ // Below 30 s only with Developer options on and a WiFi scan interval under 30 s.+ val wifiLabel = { s: Int -> "Remove WiFi devices from the list after $s s out of range" }+ val wifiSlider = slider(wifiLabel, Prefs.minLiveWifiSec(this), 180, Prefs.liveWifiSec(this)) {Prefs.setLiveWifiSec(this, it)}+ // Follow the WiFi interval as it's typed.+ binding.intervalInput.addTextChangedListener(object : android.text.TextWatcher {+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}+ override fun afterTextChanged(s: android.text.Editable?) {+ val sec = s?.toString()?.toLongOrNull() ?: return+ val min = Prefs.minLiveWifiSec(this@SettingsActivity, sec.coerceAtLeast(5) * 1000L)+ if (wifiSlider.valueFrom.toInt() == min) return+ if (wifiSlider.value < min) {+ wifiSlider.value = min.toFloat()+ Prefs.setLiveWifiSec(this@SettingsActivity, min)+ (binding.sectionScanning.getChildAt(binding.sectionScanning.indexOfChild(wifiSlider) - 1)+ as? android.widget.TextView)?.text = wifiLabel(min)+ }+ wifiSlider.valueFrom = min.toFloat()+ }+ })}/** Aircraft search radius (10-50 km) and the feed status, under the aircraft switch. */@@ -675,6 +790,8 @@ class SettingsActivity : AppCompatActivity() {binding.presetGlobal.isChecked = "global" in enabledPresetsbinding.presetCanada.isChecked = "canada" in enabledPresetsbinding.presetUs.isChecked = "us" in enabledPresets+ binding.presetFrance.isChecked = "france" in enabledPresets+ binding.presetFrance.setOnCheckedChangeListener { _, on -> if (on) com.rfsentinel.app.ui.FranceNotice.show(this) }// Alertsval threshold = Prefs.alertThreshold(this)@@ -688,6 +805,19 @@ class SettingsActivity : AppCompatActivity() {binding.soundSwitch.isChecked = Prefs.soundEnabled(this)binding.vibrateSwitch.isChecked = Prefs.vibrateEnabled(this)binding.radarBeepSwitch.isChecked = Prefs.radarBeep(this)+ binding.detectorSoundSwitch.isChecked = Prefs.detectorSound(this)+ binding.scanIntroSwitch.isChecked = Prefs.scanIntro(this)+ updateDetectorEffectButton()+ binding.detectorEffectButton.isEnabled = binding.detectorSoundSwitch.isChecked+ binding.detectorSoundSwitch.setOnCheckedChangeListener { _, on -> binding.detectorEffectButton.isEnabled = on }+ binding.detectorEffectButton.setOnClickListener { chooseDetectorEffect() }+ binding.testIntroButton.setOnClickListener {+ introTesting = com.rfsentinel.app.util.AlertPlayer.testIntro(this) {+ introTesting = false+ binding.testIntroButton.text = "Test intro"+ }+ binding.testIntroButton.text = if (introTesting) "Stop intro" else "Test intro"+ }binding.voiceSwitch.isChecked = Prefs.voiceEnabled(this)binding.shortVoiceSwitch.isChecked = Prefs.shortVoice(this)setupVoiceControls()@@ -756,6 +886,7 @@ class SettingsActivity : AppCompatActivity() {binding.cellChangeSwitch.isChecked = Prefs.cellChangeAlerts(this)binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)+ setupMapSection()binding.autoUpdateSwitch.isChecked = Prefs.autoUpdateCheck(this)fun showRadius(km: Int) {binding.cameraRadiusText.text = "Download radius: $km km"@@ -843,18 +974,22 @@ class SettingsActivity : AppCompatActivity() {}/**- * Opens Developer options, where "Wi-Fi scan throttling" lives (Networking- * section). If they aren't unlocked yet, opens About phone instead and says how.+ * Opens Developer options scrolled to "Wi-Fi scan throttling", highlighted (Settings'+ * fragment-args key; ignored on phones that don't support it, which just open the+ * list). If they aren't unlocked yet, opens About phone instead and says how.*/private fun openWifiThrottleSetting() {val devEnabled = runCatching {Settings.Global.getInt(contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0}.getOrDefault(false)if (devEnabled && runCatching {- startActivity(Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS))+ startActivity(Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)+ .putExtra(":settings:fragment_args_key", "wifi_scan_throttling")+ .putExtra(":settings:show_fragment_args",+ android.os.Bundle().apply { putString(":settings:fragment_args_key", "wifi_scan_throttling") }))}.isSuccess) {- Toast.makeText(this, "Scroll to Networking and turn off \"Wi-Fi scan throttling\"", Toast.LENGTH_LONG).show()+ Toast.makeText(this, "Turn off the highlighted \"Wi-Fi scan throttling\"", Toast.LENGTH_LONG).show()return}// Explain first, then open About phone: a dialog shown behind it would go unseen.@@ -874,8 +1009,11 @@ class SettingsActivity : AppCompatActivity() {}/** Android's WiFi scan throttle (Developer options), on unless the user disabled it. */+ /** Android 11+ keeps the developer toggle in the WiFi service; older versions in a global setting. */private fun wifiScanThrottled(): Boolean =- runCatching { Settings.Global.getInt(contentResolver, "wifi_scan_throttle_enabled", 1) != 0 }.getOrDefault(true)+ if (android.os.Build.VERSION.SDK_INT >= 30)+ runCatching { getSystemService(android.net.wifi.WifiManager::class.java).isScanThrottleEnabled }.getOrDefault(true)+ else runCatching { Settings.Global.getInt(contentResolver, "wifi_scan_throttle_enabled", 1) != 0 }.getOrDefault(true)private fun confirm(title: String, message: String, action: () -> Unit) {AlertDialog.Builder(this)@@ -888,6 +1026,9 @@ class SettingsActivity : AppCompatActivity() {/** Settings save themselves: whenever this screen is left (back, home, another screen). */override fun onPause() {+ // Leaving Settings ends any sound preview (not an intro played by a starting scan).+ com.rfsentinel.app.util.AlertPlayer.stopPreview(stopIntro = introTesting)+ if (introTesting) { introTesting = false; binding.testIntroButton.text = "Test intro" }super.onPause()if (loaded) save()}@@ -919,6 +1060,7 @@ class SettingsActivity : AppCompatActivity() {if (binding.presetGlobal.isChecked) presets.add("global")if (binding.presetCanada.isChecked) presets.add("canada")if (binding.presetUs.isChecked) presets.add("us")+ if (binding.presetFrance.isChecked) presets.add("france")OuiWatchlist.setEnabledPresets(this, presets)Prefs.setAlertThreshold(@@ -931,6 +1073,8 @@ class SettingsActivity : AppCompatActivity() {)Prefs.setSoundEnabled(this, binding.soundSwitch.isChecked)Prefs.setRadarBeep(this, binding.radarBeepSwitch.isChecked)+ Prefs.setDetectorSound(this, binding.detectorSoundSwitch.isChecked)+ Prefs.setScanIntro(this, binding.scanIntroSwitch.isChecked)Prefs.setVibrateEnabled(this, binding.vibrateSwitch.isChecked)Prefs.setVoiceEnabled(this, binding.voiceSwitch.isChecked)Prefs.setShortVoice(this, binding.shortVoiceSwitch.isChecked)diff --git a/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.kt b/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.ktnew file mode 100644index 0000000..2b29cfe--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/CctvConeOverlay.kt@@ -0,0 +1,68 @@+package com.rfsentinel.app.ui++import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.Path+import android.graphics.RectF+import com.rfsentinel.app.alpr.Cctv+import com.rfsentinel.app.alpr.CctvCamera+import org.osmdroid.util.GeoPoint+import org.osmdroid.views.MapView+import org.osmdroid.views.overlay.Overlay++/**+ * The area each CCTV camera watches: a translucent wedge toward `camera:direction`, as wide+ * as `camera:angle` and reaching about 5x the mounting height (see [Cctv.viewRangeM]);+ * a faint circle for dome / panning cameras with no mapped direction. Drawn under the icons.+ */+class CctvConeOverlay(private val density: Float) : Overlay() {++ @Volatile var cameras: List<CctvCamera> = emptyList()++ private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }+ private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }+ private val px = android.graphics.Point()+ private val path = Path()+ private val oval = RectF()++ override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) {+ if (shadow) return+ val proj = mapView.projection+ val zoom = mapView.zoomLevelDouble+ val w = mapView.width; val h = mapView.height+ edge.strokeWidth = 1f * density+ for (c in cameras) {+ proj.toPixels(GeoPoint(c.lat, c.lon), px)+ val x = px.x.toFloat(); val y = px.y.toFloat()+ val r = proj.metersToPixels(Cctv.viewRangeM(c).toFloat(), c.lat, zoom)+ if (x < -w - r || y < -h - r || x > 2 * w + r || y > 2 * h + r) continue+ val color = if (c.isPrivate) PRIVATE_COLOR else PUBLIC_COLOR+ fill.color = (color and 0x00FFFFFF) or 0x33000000+ edge.color = (color and 0x00FFFFFF) or 0x88000000.toInt()+ val dir = c.direction+ if (dir == null) {+ // No direction: only domes / panning cameras get a (fainter, smaller) all-round area.+ if (c.cameraType != "dome" && c.cameraType != "panning") continue+ fill.color = (color and 0x00FFFFFF) or 0x1A000000+ canvas.drawCircle(x, y, r * 0.6f, fill)+ continue+ }+ val sweep = Cctv.viewAngle(c).toFloat()+ // A full-circle view: Android treats a 360° arc as empty.+ if (sweep >= 359f) { canvas.drawCircle(x, y, r, fill); canvas.drawCircle(x, y, r, edge); continue }+ oval.set(x - r, y - r, x + r, y + r)+ path.reset()+ path.moveTo(x, y)+ // Bearings run clockwise from north; Android arcs start at 3 o'clock.+ path.arcTo(oval, dir - 90f - sweep / 2f, sweep)+ path.close()+ canvas.drawPath(path, fill)+ canvas.drawPath(path, edge)+ }+ }++ companion object {+ const val PUBLIC_COLOR = 0xFF455A64.toInt() // slate+ const val PRIVATE_COLOR = 0xFF8D6E63.toInt() // brown-grey+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.ktindex f016d6a..9859a54 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt@@ -22,7 +22,7 @@ data class DeviceRow(val tagColor: Int,/** Row tint colour for flagged devices, else null. */val highlight: Int?,- /** Pulse the tint (flagged, above the alert threshold, heard within the last minute). */+ /** Pulse the tint (flagged, above the alert threshold, still in range). */val flashing: Boolean,val bold: Boolean,/** Heard by an ESP32 board (blue badge) and/or the phone's own radios (green badge). */diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.ktindex 1243919..fe794f2 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt@@ -16,6 +16,7 @@ import androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycleimport com.google.android.material.button.MaterialButton+import com.rfsentinel.app.util.AlertPlayerimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.DetectionEntityimport com.rfsentinel.app.data.Favorites@@ -438,9 +439,9 @@ class DeviceDetailActivity : AppCompatActivity() {locateJob = lifecycleScope.launch {while (isActive) {val rssi = DeviceRegistry.get(mac)?.rssi ?: -100- // -95 dBm -> ~1.6 s between beeps, -40 dBm -> ~0.1 s.- val interval = (1600 - ((rssi + 95).coerceIn(0, 55) / 55.0) * 1500).toLong()- tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)+ // Faster as the signal gets stronger (same curve as the radar beeps).+ val interval = com.rfsentinel.app.util.Beeper.tickIntervalMs(rssi)+ if (!AlertPlayer.locateTick(this@DeviceDetailActivity)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)delay(interval)}}diff --git a/app/src/main/java/com/rfsentinel/app/ui/FranceNotice.kt b/app/src/main/java/com/rfsentinel/app/ui/FranceNotice.ktnew file mode 100644index 0000000..6240fdf--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/FranceNotice.kt@@ -0,0 +1,26 @@+package com.rfsentinel.app.ui++import android.content.Context+import androidx.appcompat.app.AlertDialog++/**+ * Shown when the France preset is switched on: French law bans radar detectors and any+ * device or app that signals speed cameras (Code de la route R413-15, décret 2012-3).+ */+object FranceNotice {++ const val TEXT = "In France, radar detectors and devices or apps that signal the location of speed cameras " ++ "are illegal (Code de la route R413-15, décret n° 2012-3: €1,500 fine, 6 points, device seized). " ++ "Since 2021 the authorities can also require apps to hide police checks on given roads.\n\n" ++ "If you drive in France, turn off speed-camera and red-light camera warnings (Settings > Known cameras) " ++ "and Waze police reports, and don't use RF Sentinel to locate speed-enforcement equipment. " ++ "You are responsible for complying with the law."++ fun show(context: Context) {+ AlertDialog.Builder(context)+ .setTitle("Driving in France")+ .setMessage(TEXT)+ .setPositiveButton("I understand", null)+ .show()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.ktindex f73456a..5ec749e 100644--- a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt@@ -5,13 +5,36 @@ import com.rfsentinel.app.service.DeviceRegistry/*** How long a device stays in the live list and radar after it was last heard (Settings >- * Scanning, defaults 30 s Bluetooth / 60 s WiFi). Flagged, favourite and following devices- * stay for the registry's full 3 minutes so a passing threat doesn't vanish between sightings.+ * Scanning, defaults 30 s Bluetooth / 60 s WiFi), flagged devices included - never shorter+ * than while they still count as in range. Favourite and following devices stay for the+ * registry's full 3 minutes.*/object LiveWindow {- fun keep(s: DeviceRegistry.Snapshot, important: Boolean, now: Long, bleMs: Long, wifiMs: Long): Boolean {- if (important || s.following || s.known?.favorite == true) return true- val window = if (Advert.Source.WIFI in s.sources || s.source == Advert.Source.WIFI) wifiMs else bleMs- return now - s.lastSeen <= window+ /** A Bluetooth device not heard for this long is out of range (adverts come every second or so). */+ const val BLE_IN_RANGE_MS = 8_000L++ /** The WiFi scan interval in use (kept current by the scan service): WiFi devices only refresh once per scan. */+ @Volatile var wifiScanMs = 30_000L++ /** Still being heard: Bluetooth within 8 s, WiFi within one scan round + 10 s. */+ fun inRange(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): Boolean {+ val wifi = Advert.Source.WIFI in s.sources || s.source == Advert.Source.WIFI+ return now - s.lastSeen <= if (wifi) wifiScanMs + 10_000L else BLE_IN_RANGE_MS+ }++ /**+ * Flagged AND in range: what drives the live alerts (bubble, banner, radar blips, car+ * headline, proximity beeps). A flagged device that's gone stops alerting right away but+ * stays in the list and history.+ */+ fun alerting(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): Boolean =+ s.best != null && !com.rfsentinel.app.data.WhitelistCache.contains(s.mac) && inRange(s, now)++ fun keep(s: DeviceRegistry.Snapshot, now: Long, bleMs: Long, wifiMs: Long): Boolean {+ if (s.following || s.known?.favorite == true) return true+ val wifi = Advert.Source.WIFI in s.sources || s.source == Advert.Source.WIFI+ // A flagged device never leaves the list while it still alerts (bubble, banner, beeps).+ if (s.best != null && inRange(s, now)) return true+ return now - s.lastSeen <= if (wifi) wifiMs else bleMs}}diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.ktindex e7672c3..22ebb53 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt@@ -101,6 +101,11 @@ class MapActivity : AppCompatActivity() {PointsOverlay<com.rfsentinel.app.alpr.KnownCamera>(resources.displayMetrics.density) { showKnownCamera(it.first()) }}private var knownAlprDrawnFor: BoundingBox? = null+ /** CCTV cameras mapped in OpenStreetMap (map menu, off by default): icons over their view cones. */+ private val cctv by lazy {+ PointsOverlay<com.rfsentinel.app.alpr.CctvCamera>(resources.displayMetrics.density) { showCctv(it.first()) }+ }+ private val cctvCones by lazy { CctvConeOverlay(resources.displayMetrics.density) }/** Cell towers seen while scanning, at their estimated (strongest-signal) spot. */private val towers by lazy {PointsOverlay<com.rfsentinel.app.service.CellTowerStore.Tower>(resources.displayMetrics.density) { showTower(it.first()) }@@ -174,6 +179,8 @@ class MapActivity : AppCompatActivity() {color = if (tripId == null) TRACE_COLOR else PAST_TRACE_COLORstrokeWidth = 7f * resources.displayMetrics.density / 2}+ map.overlays.add(cctvCones)+ map.overlays.add(cctv)map.overlays.add(knownAlpr)map.overlays.add(towers)map.overlays.add(trace)@@ -226,7 +233,14 @@ class MapActivity : AppCompatActivity() {}// Precise GPS while the map is on screen, so devices land where they were heard.if (tripId == null) ScanForegroundService.mapShown(this)+ // Back from Settings > Map: show what's switched on now (and nothing that was switched off).drawTowers()+ drawKnownAlpr()+ if (com.rfsentinel.app.util.Prefs.showCctv(this)) lifecycleScope.launch {+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.rfsentinel.app.alpr.CctvStore.load(this@MapActivity) }+ drawCctv()+ maybeDownloadCctv()+ } else drawCctv()}override fun onPause() {@@ -238,6 +252,7 @@ class MapActivity : AppCompatActivity() {override fun onDestroy() {stopObservingBulk?.invoke()+ com.rfsentinel.app.alpr.CctvStore.onChanged = nullmyLocation.disableMyLocation()binding.map.removeCallbacks(autoDownloadCameras)binding.map.removeCallbacks(redrawKnownAlpr)@@ -362,7 +377,7 @@ class MapActivity : AppCompatActivity() {}positioned == 0 -> "Scanning · waiting for GPS to place devices"else -> "Scanning · ${drawn.size} on map" + if (filter != DeviceFilter.ALL) " (${filter.label} only)" else ""- }+ } + (cctvLine?.let { "\n$it" } ?: "")binding.statusText.background.mutate().setTint(if (recording) 0xFFB3261E.toInt() else 0xCC0B5C63.toInt())binding.map.invalidate()}@@ -650,6 +665,132 @@ class MapActivity : AppCompatActivity() {private fun drawKnownAlprSoon() {binding.map.removeCallbacks(redrawKnownAlpr)binding.map.postDelayed(redrawKnownAlpr, 250)+ binding.map.removeCallbacks(redrawCctv)+ binding.map.postDelayed(redrawCctv, 250)+ }++ // ---- CCTV cameras (OpenStreetMap) ---------------------------------------------------------------++ private val redrawCctv = Runnable { drawCctv() }+ private fun drawCctvSoon() {+ binding.map.removeCallbacks(redrawCctv)+ binding.map.postDelayed(redrawCctv, 300)+ }+ private val downloadCctv = Runnable { maybeDownloadCctv() }++ /** Below this zoom the layer is hidden (cities hold thousands of cameras); view cones from [cctvConeZoom]. */+ private val cctvMinZoom = 12.0+ private val cctvConeZoom = 15.0++ /** What the CCTV layer is doing, added to the status line (null while the layer is off). */+ @Volatile private var cctvLine: String? = null++ private fun setCctvLine(text: String?) {+ if (text == cctvLine) return+ cctvLine = text+ if (tripId == null) renderLive()+ }++ private fun drawCctv() {+ com.rfsentinel.app.alpr.CctvStore.onChanged = { if (!isFinishing && !isDestroyed) drawCctvSoon() }+ val map = binding.map+ val on = com.rfsentinel.app.util.Prefs.showCctv(this) && tripId == null+ if (!on || map.zoomLevelDouble < cctvMinZoom) {+ if (cctv.points.isNotEmpty() || cctvCones.cameras.isNotEmpty()) {+ cctv.points = emptyList(); cctvCones.cameras = emptyList(); map.invalidate()+ }+ setCctvLine(if (!on) null else com.rfsentinel.app.alpr.CctvStore.progress?.let { "CCTV: downloading around you, $it" }+ ?: "CCTV: zoom in to see the cameras")+ return+ }+ map.removeCallbacks(downloadCctv)+ map.postDelayed(downloadCctv, 1_200)+ val private = com.rfsentinel.app.util.Prefs.cctvPrivate(this)+ val box = map.boundingBox.increaseByScale(1.5f)+ val center = map.mapCenter+ val inView = com.rfsentinel.app.alpr.CctvStore.cameras.filter {+ (private || !it.isPrivate) && it.lat in box.latSouth..box.latNorth && it.lon in box.lonWest..box.lonEast+ }.let { all ->+ // Zoomed out over a city: the ones nearest the centre of the screen.+ if (all.size <= 3000) all+ else all.sortedBy { (it.lat - center.latitude).let { d -> d * d } + (it.lon - center.longitude).let { d -> d * d } }.take(3000)+ }+ val dp = resources.displayMetrics.density+ val publicIcon = MapIcons.cctvIcon(dp, false); val privateIcon = MapIcons.cctvIcon(dp, true)+ cctvCones.cameras = if (map.zoomLevelDouble >= cctvConeZoom) inView else emptyList()+ cctv.points = inView.map { PointsOverlay.Point(it.lat, it.lon, it, icon = if (it.isPrivate) privateIcon else publicIcon) }+ map.invalidate()+ val store = com.rfsentinel.app.alpr.CctvStore+ val view = map.boundingBox+ val hiddenPrivate = if (private) 0 else store.cameras.count {+ it.isPrivate && it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast+ }+ val shown = inView.count { it.lat in view.latSouth..view.latNorth && it.lon in view.lonWest..view.lonEast }+ setCctvLine(when {+ store.progress != null -> "CCTV: downloading around you, ${store.progress}"+ store.isBusy -> "CCTV: downloading..."+ System.currentTimeMillis() - store.lastFailureAt < 60_000 -> "CCTV: map server busy - retrying"+ store.missingAreas > 0 && shown > 0 -> "CCTV: $shown in view - ${store.missingAreas} area(s) around you still missing (servers busy), retried next time"+ shown == 0 && store.needsDownload(view.latSouth, view.lonWest, view.latNorth, view.lonEast) -> "CCTV: downloading..."+ shown == 0 && hiddenPrivate > 0 -> "CCTV: only private ones here ($hiddenPrivate) - Settings > Known cameras > Include private"+ shown == 0 -> "CCTV: none mapped here"+ else -> "CCTV: $shown in view" + if (hiddenPrivate > 0) " (+$hiddenPrivate private hidden)" else ""+ })+ }++ /**+ * Fetches the CCTV cameras within the download radius around you (once, in the+ * background), and the area on screen when you look somewhere outside it.+ */+ private fun maybeDownloadCctv() {+ val map = binding.map+ if (!com.rfsentinel.app.util.Prefs.showCctv(this) || tripId != null) return+ val store = com.rfsentinel.app.alpr.CctvStore+ if (map.isAnimating || store.isBusy) { map.postDelayed(downloadCctv, 2_000); return }+ val here = myLocation.myLocation ?: ScanForegroundService.lastFix?.let { GeoPoint(it.latitude, it.longitude) }+ if (here != null) {+ val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(this).toDouble()+ store.ensureAround(this, here.latitude, here.longitude, radius)+ if (store.isBusy) return+ }+ if (map.zoomLevelDouble < cctvMinZoom) return+ val box = map.boundingBox+ lifecycleScope.launch {+ com.rfsentinel.app.alpr.CctvStore.autoDownload(this@MapActivity, box.latSouth, box.lonWest, box.latNorth, box.lonEast)+ // Redraw either way: new cameras, or the status line (none mapped / server busy).+ drawCctv()+ // After a failure, try again once the back-off has passed.+ if (System.currentTimeMillis() - com.rfsentinel.app.alpr.CctvStore.lastFailureAt < 60_000)+ binding.map.postDelayed(downloadCctv, 61_000)+ }+ }++ private fun showCctv(c: com.rfsentinel.app.alpr.CctvCamera) {+ val text = buildString {+ append(when (c.zone) {+ "public" -> "Watches a public space (street, square, station...).\n"+ "outdoor" -> "A private camera that watches outside (an entrance, a car park...).\n"+ "indoor" -> "Inside a building or shop.\n"+ else -> "Whether it watches public space isn't mapped.\n"+ })+ c.area?.let { append("Watches: $it\n") }+ c.operator?.let { append("Operator: $it\n") }+ c.mount?.let { append("Mounted on: $it\n") }+ c.height?.let { append("Height: ${"%.0f".format(it)} m\n") }+ c.direction?.let { append("Faces: $it°" + (c.angle?.let { a -> ", $a° wide" } ?: "") + "\n") }+ append("OSM: ${c.osmId}\n\n")+ append("Mapped by OpenStreetMap volunteers. Most of these cameras are wired and give off no Bluetooth or WiFi " ++ "signal, so the scan can't detect them - this layer shows the ones that have been mapped. " ++ "The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")+ }+ AlertDialog.Builder(this)+ .setTitle(com.rfsentinel.app.alpr.Cctv.title(c))+ .setMessage(text)+ .setPositiveButton("Close", null)+ .setNeutralButton("Open in OpenStreetMap") { _, _ ->+ runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${c.osmId}"))) }+ }+ .show()}private val autoDownloadCameras = Runnable { maybeAutoDownloadCameras() }@@ -786,40 +927,6 @@ class MapActivity : AppCompatActivity() {.show()}- /**- * DeFlock's snapshot - all of the US & Canada, or with [nearby] only within- * the download radius set in Settings 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- val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(this)- announceWhere = if (nearby) "within ~$radius 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, radius.toDouble())- }-- /** Picks the radius (same setting as in Settings and the setup wizard), then downloads. */- private fun askNearbyRadius() {- val d = resources.displayMetrics.density- val body = CameraRadiusSlider.create(this).apply {- setPadding((24 * d).toInt(), (8 * d).toInt(), (24 * d).toInt(), 0)- }- AlertDialog.Builder(this)- .setTitle("Download nearby cameras")- .setView(body)- .setPositiveButton("Download") { _, _ -> downloadAllPlateCameras(nearby = true) }- .setNegativeButton("Cancel", null)- .show()- }-- /** Set when a download was started (or followed) from this screen: show its result. */- private var announceWhere: String? = nullprivate var stopObservingBulk: (() -> Unit)? = null/** Status text while a DeFlock download runs, or null when none does. */@@ -851,17 +958,9 @@ class MapActivity : AppCompatActivity() {is com.rfsentinel.app.alpr.DeflockBulk.State.Done -> {bar.visibility = View.GONEdrawKnownAlpr(); 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}@@ -877,15 +976,10 @@ class MapActivity : AppCompatActivity() {menu.add(0, 2, 1, "Rename")menu.add(0, 3, 2, "Delete")} else {- menu.add(0, 4, 0, "Recorded traces")- 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)- }- menu.add(0, 7, 3, "Delete downloaded cameras")- menu.add(0, 9, 4, "Show cell towers").apply {- isCheckable = true; isChecked = com.rfsentinel.app.util.Prefs.showCellTowers(this@MapActivity)+ // The map's options live in Settings > Map.+ menu.add(0, 12, 0, "Map settings").apply {+ setIcon(com.rfsentinel.app.R.drawable.ic_settings)+ setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)}}return true@@ -897,27 +991,11 @@ class MapActivity : AppCompatActivity() {1 -> { id?.let { Exporter.showTripExport(this, it) }; true }2 -> { id?.let { rename(it) }; true }3 -> { id?.let { confirmDelete(it) }; true }- 4 -> { startActivity(Intent(this, TripsActivity::class.java)); true }- 5 -> { askNearbyRadius(); true }- 6 -> {- val show = !com.rfsentinel.app.util.Prefs.showKnownAlpr(this)- com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, show)- item.isChecked = show- 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 }- 9 -> {- val show = !com.rfsentinel.app.util.Prefs.showCellTowers(this)- com.rfsentinel.app.util.Prefs.setShowCellTowers(this, show)- item.isChecked = show- drawTowers(); true+ 12 -> {+ startActivity(Intent(this, com.rfsentinel.app.settings.SettingsActivity::class.java)+ .putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION,+ com.rfsentinel.app.settings.SettingsActivity.SECTION_MAP))+ true}android.R.id.home -> { finish(); true }else -> super.onOptionsItemSelected(item)diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.ktindex 011ad29..d2e50a4 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapIcons.kt@@ -15,6 +15,24 @@ import java.io.File/** Map pieces shared by the phone map and the Android Auto map. */object MapIcons {+ /** A small CCTV camera (body on a bracket) for the OpenStreetMap CCTV layer. */+ fun cctvIcon(dp: Float, private: Boolean): Bitmap {+ val w = (16 * dp).toInt(); val h = (14 * dp).toInt()+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val c = Canvas(bmp)+ val p = Paint(Paint.ANTI_ALIAS_FLAG)+ val color = if (private) CctvConeOverlay.PRIVATE_COLOR else CctvConeOverlay.PUBLIC_COLOR+ val body = RectF(1.5f * dp, 2 * dp, w - 3 * dp, 8 * dp)+ p.color = color+ c.drawRoundRect(body, 2 * dp, 2 * dp, p)+ c.drawRect(w / 2f - 1 * dp, 8 * dp, w / 2f + 1 * dp, h - 1.5f * dp, p)+ p.style = Paint.Style.STROKE; p.strokeWidth = 1.2f * dp; p.color = Color.WHITE+ c.drawRoundRect(body, 2 * dp, 2 * dp, p)+ p.style = Paint.Style.FILL+ c.drawCircle(w - 4.5f * dp, 5 * dp, 1.3f * dp, p)+ return bmp+ }+/** osmdroid: identify ourselves to the tile server (OSM tile policy), cache tiles privately. */fun configureOsm(context: Context) {Configuration.getInstance().apply {diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.ktindex 2943f35..d5d333a 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt@@ -158,10 +158,12 @@ class SetupActivity : AppCompatActivity() {listOf("global" to "Global - body cams (Axon, Zepcam, WatchGuard...), Flock, ShotSpotter, traffic cameras, radios","canada" to "Canada - adds Cyberkar in-car systems, Getac body cams, Genetec plate readers",- "us" to "United States"+ "us" to "United States",+ "france" to "France - Motorola VB400 body cams of the Police nationale and Gendarmerie, Zepcam, TETRAPOL radios").forEach { (key, label) ->check(label, key in enabled) { on ->if (on) enabled += key else enabled -= key+ if (on && key == "france") FranceNotice.show(this)OuiWatchlist.setEnabledPresets(this, enabled)}}diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.ktindex 7faafb3..6753f6a 100644--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt@@ -62,11 +62,25 @@ object AlertPlayer {var beepMs = 0if (!muted && Prefs.soundEnabled(context) && (inCar || ringerAllowsSound(context))) {// Speech holds its own audio focus for exactly as long as it talks; this covers the beeps.- duckOthers(context, 2_500L)+ val detector = Prefs.detectorSound(context)+ duckOthers(context, if (detector) 4_500L else 2_500L)// Our own beeps (1 weak, 2 probable, 3 strong, long-short-long following) at// media volume, like Locate: the notification chime was too soft and too quiet.val beeps = when (tier) { Tier.STRONG -> 3; Tier.MEDIUM -> 2; else -> 1 }- beepMs = Beeper.play(if (inCar) carToneAttributes else phoneToneAttributes, Beeper.pattern(beeps, following))+ val attrs = if (inCar) carToneAttributes else phoneToneAttributes+ beepMs = if (detector) {+ val chosen = Prefs.detectorEffect(context)+ val clip = SoundClips.Clip.effect(when {+ chosen != 0 -> chosen+ following -> 4+ beeps == 3 -> 1+ beeps == 2 -> 2+ else -> 3+ })+ SoundClips.play(context, attrs, clip).takeIf { it > 0 }+ ?: Beeper.playTones(attrs, Beeper.detectorAlert(if (following) 3 else beeps))+ } else Beeper.play(attrs, Beeper.pattern(beeps, following))+ alertSoundUntil = System.currentTimeMillis() + beepMs}if (Prefs.vibrateEnabled(context)) {val pattern = when {@@ -100,7 +114,79 @@ object AlertPlayer {fun tick(context: Context) {val inCar = CarState.connectedif (Prefs.alertsSilenced(context) || !Prefs.soundEnabled(context) || !(inCar || ringerAllowsSound(context))) return- Beeper.play(if (inCar) carToneAttributes else phoneToneAttributes, listOf(70 to 0))+ // Never over an alert sound that is still playing.+ if (System.currentTimeMillis() < alertSoundUntil) return+ val attrs = if (inCar) carToneAttributes else phoneToneAttributes+ if (Prefs.detectorSound(context)) detectorTick(context, attrs) else Beeper.play(attrs, listOf(70 to 0))+ }++ /** The recorded detector pulse, or the synthesized chirp until the clips are loaded. */+ private fun detectorTick(context: Context, attrs: AudioAttributes) {+ val tick = SoundClips.Clip.tick(Prefs.detectorEffect(context).takeIf { it != 0 } ?: 1)+ if (SoundClips.play(context, attrs, tick) == 0) Beeper.playTones(attrs, Beeper.detectorTick)+ }++ /** Settings preview of a detector effect (0 = the strong one), whatever the alert settings. */+ fun previewEffect(context: Context, effect: Int) {+ main.removeCallbacks(retryPreview)+ val clip = SoundClips.Clip.effect(effect.takeIf { it != 0 } ?: 1)+ if (SoundClips.playPreview(context, phoneToneAttributes, clip)) return+ // First use: the clips are still loading.+ retryPreview = Runnable { SoundClips.playPreview(context, phoneToneAttributes, clip) }+ main.postDelayed(retryPreview, 250L)+ }++ private var retryPreview = Runnable { }++ /** Stops a Settings preview (an effect or the intro test). */+ fun stopPreview(stopIntro: Boolean) {+ main.removeCallbacks(retryPreview)+ SoundClips.stopPreview()+ if (stopIntro) SoundClips.stopIntro()+ }++ /** The Settings "Test intro" button: plays the intro, or stops it if playing. True if it started. */+ fun testIntro(context: Context, onDone: () -> Unit): Boolean {+ stopPreview(false)+ if (SoundClips.introPlaying()) { SoundClips.stopIntro(); return false }+ SoundClips.playIntro(context, phoneToneAttributes) { main.post(onDone) }+ return true+ }++ /** Until when an alert sound plays (radar ticks wait for it). */+ @Volatile private var alertSoundUntil = 0L++ /** Loads the recorded sounds so the first alert can use them. */+ fun preload(context: Context) = SoundClips.preload(context, phoneToneAttributes)++ /**+ * One Locate tick (the device screen's proximity beeps) in the radar-detector sound style.+ * Started by the user, so it plays whatever the alert settings; false when the style is off.+ */+ fun locateTick(context: Context): Boolean {+ if (!Prefs.detectorSound(context)) return false+ detectorTick(context, phoneToneAttributes)+ return true+ }++ /**+ * When a scan starts: the optional intro sound, else the radar-detector power-on sweep+ * (in that sound style). Same rules as the alert sound.+ */+ fun startup(context: Context) {+ val inCar = CarState.connected+ val intro = Prefs.scanIntro(context)+ if (!intro && !Prefs.detectorSound(context)) return+ if (Prefs.alertsSilenced(context) || !Prefs.soundEnabled(context) || !(inCar || ringerAllowsSound(context))) return+ val attrs = if (inCar) carToneAttributes else phoneToneAttributes+ if (intro) SoundClips.playIntro(context, attrs) else Beeper.playTones(attrs, Beeper.detectorStartup)+ }++ fun stopIntro() = SoundClips.stopIntro()++ /** Radar-detector sound style: "GPS connected" once the first good fix arrives. */+ fun gpsConnected(context: Context) {+ if (Prefs.detectorSound(context)) announce(context, "GPS connected")}/** A spoken navigation instruction (no beep, no vibration); silent when alerts are muted. */diff --git a/app/src/main/java/com/rfsentinel/app/util/Beeper.kt b/app/src/main/java/com/rfsentinel/app/util/Beeper.ktindex d54d160..8412239 100644--- a/app/src/main/java/com/rfsentinel/app/util/Beeper.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Beeper.kt@@ -7,6 +7,7 @@ import android.os.Handlerimport android.os.Looperimport kotlin.math.PIimport kotlin.math.min+import kotlin.math.powimport kotlin.math.sin/**@@ -26,12 +27,60 @@ object Beeper {else -> List(beeps.coerceIn(1, 3)) { i -> 140 to if (i == beeps - 1) 0 else 110 }}- /** Milliseconds between radar ticks: -95 dBm -> 1.6 s, -40 dBm and closer -> 0.15 s (like Locate). */- fun tickIntervalMs(rssi: Int): Long = (1600 - ((rssi + 95).coerceIn(0, 55) / 55.0) * 1450).toLong()-+ /**+ * Milliseconds between proximity ticks (radar beeps and Locate): slow while faint, then+ * sharply faster up close, like a detector locking on. -95 dBm -> 1.3 s, -70 -> ~0.4 s,+ * -55 -> ~0.14 s, -45 dBm and closer -> 0.06 s.+ */+ fun tickIntervalMs(rssi: Int): Long {+ val t = ((rssi + 95).coerceIn(0, 50) / 50.0).pow(1.4)+ return (1300 * (60.0 / 1300).pow(t)).toLong()+ }fun durationMs(pattern: List<Pair<Int, Int>>) = pattern.sumOf { it.first + it.second }+ // ---- Radar-detector sound style (synthesized, in the spirit of a dash radar detector) ----++ /** A tone that glides from [fromHz] to [toHz] over [ms], then [gapMs] of silence. */+ data class Tone(val ms: Int, val fromHz: Double, val toHz: Double = fromHz, val gapMs: Int = 0)++ /** Strong / following: fast high warble ("Ka" style). Probable: two-tone ("K"). Weak: slow single tone ("X"). */+ fun detectorAlert(strength: Int): List<Tone> = when {+ strength >= 3 -> List(5) { listOf(Tone(50, 2600.0, 3500.0, 10), Tone(50, 3500.0, 2600.0, 40)) }.flatten()+ strength == 2 -> List(3) { listOf(Tone(90, 1450.0, gapMs = 25), Tone(90, 1050.0, gapMs = 110)) }.flatten()+ else -> List(2) { Tone(170, 900.0, gapMs = 150) }+ }++ /** One radar-mode tick: a short rising chirp. */+ val detectorTick = listOf(Tone(45, 2500.0, 3300.0))++ /** Power-on: a rising sweep and two confirmation blips. */+ val detectorStartup = listOf(Tone(380, 500.0, 2600.0, 70), Tone(90, 2200.0, gapMs = 50), Tone(90, 3000.0))++ fun toneDurationMs(tones: List<Tone>) = tones.sumOf { it.ms + it.gapMs }++ /** 16-bit mono PCM for a tone list, phase-continuous through each glide (pure; unit-tested). */+ fun tonePcm(tones: List<Tone>): ShortArray {+ val out = ShortArray(toneDurationMs(tones) * RATE / 1000)+ var pos = 0+ val fade = FADE_MS * RATE / 1000+ for (t in tones) {+ val n = t.ms * RATE / 1000+ var phase = 0.0+ for (i in 0 until n) {+ val f = t.fromHz + (t.toHz - t.fromHz) * i / n+ phase += 2 * PI * f / RATE+ val env = min(1.0, min(i, n - 1 - i).toDouble() / fade)+ if (pos + i < out.size) out[pos + i] = (sin(phase) * env * 0.8 * Short.MAX_VALUE).toInt().toShort()+ }+ pos += n + t.gapMs * RATE / 1000+ }+ return out+ }++ fun playTones(attributes: AudioAttributes, tones: List<Tone>): Int =+ playPcm(attributes, tonePcm(tones), toneDurationMs(tones))+/** 16-bit mono PCM for a pattern (pure; unit-tested). */fun pcm(pattern: List<Pair<Int, Int>>): ShortArray {val out = ShortArray(durationMs(pattern) * RATE / 1000)@@ -50,8 +99,10 @@ object Beeper {}/** Plays the pattern; returns how long it lasts (ms), or 0 if audio failed. */- fun play(attributes: AudioAttributes, pattern: List<Pair<Int, Int>>): Int {- val data = pcm(pattern)+ fun play(attributes: AudioAttributes, pattern: List<Pair<Int, Int>>): Int =+ playPcm(attributes, pcm(pattern), durationMs(pattern))++ private fun playPcm(attributes: AudioAttributes, data: ShortArray, ms: Int): Int {return try {val track = AudioTrack.Builder().setAudioAttributes(attributes)@@ -67,7 +118,6 @@ object Beeper {.build()track.write(data, 0, data.size)track.play()- val ms = durationMs(pattern)Handler(Looper.getMainLooper()).postDelayed({ runCatching { track.release() } }, ms + 300L)ms} catch (e: Exception) {diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 87871ce..659c0a1 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -119,10 +119,25 @@ object Prefs {/** Radius of "download the cameras around me" (Settings, setup wizard, map menu), in km. *//** How far to look for aircraft (ADS-B feeds), 10-50 km. *//** How long an ordinary device stays in the list / radar after it was last heard (seconds). */- fun liveBleSec(context: Context): Int = int(context, "live_ble_sec", 30).coerceIn(10, 180)- fun setLiveBleSec(context: Context, sec: Int) = setInt(context, "live_ble_sec", sec.coerceIn(10, 180))- fun liveWifiSec(context: Context): Int = int(context, "live_wifi_sec", 60).coerceIn(30, 180)- fun setLiveWifiSec(context: Context, sec: Int) = setInt(context, "live_wifi_sec", sec.coerceIn(30, 180))+ fun liveBleSec(context: Context): Int = int(context, "live_ble_sec", 30).coerceIn(5, 180)+ fun setLiveBleSec(context: Context, sec: Int) = setInt(context, "live_ble_sec", sec.coerceIn(5, 180))+ fun liveWifiSec(context: Context): Int = int(context, "live_wifi_sec", 60).coerceIn(minLiveWifiSec(context), 180)++ /**+ * The WiFi list window can go below 30 s only when Developer options are on and the WiFi+ * scan interval is under 30 s (i.e. scan throttling turned off): otherwise devices would+ * drop out between two scans.+ */+ fun minLiveWifiSec(context: Context, intervalMs: Long = scanIntervalMs(context)): Int =+ if (fastWifiScans(context, intervalMs)) 5 else 30++ fun fastWifiScans(context: Context, intervalMs: Long = scanIntervalMs(context)): Boolean =+ intervalMs < 30_000L && runCatching {+ android.provider.Settings.Global.getInt(context.contentResolver,+ android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) == 1+ }.getOrDefault(false)+ // Stored as chosen (down to 5 s); [liveWifiSec] raises it to 30 s whenever fast WiFi scans are off.+ fun setLiveWifiSec(context: Context, sec: Int) = setInt(context, "live_wifi_sec", sec.coerceIn(5, 180))fun aircraftRadiusKm(context: Context): Int = int(context, "aircraft_radius_km", 30).coerceIn(10, 50)fun setAircraftRadiusKm(context: Context, km: Int) = setInt(context, "aircraft_radius_km", km.coerceIn(10, 50))@@ -191,6 +206,12 @@ object Prefs {/** Alert each time the phone switches to another serving cell tower (off by default: frequent while driving). */fun cellChangeAlerts(context: Context): Boolean = bool(context, "cell_change_alerts", false)fun setCellChangeAlerts(context: Context, value: Boolean) = setBool(context, "cell_change_alerts", value)+ /** Map layer: ordinary CCTV cameras mapped in OpenStreetMap (off by default); private ones on request. */+ fun showCctv(context: Context): Boolean = bool(context, "show_cctv", false)+ fun setShowCctv(context: Context, value: Boolean) = setBool(context, "show_cctv", value)+ fun cctvPrivate(context: Context): Boolean = bool(context, "cctv_private", false)+ fun setCctvPrivate(context: Context, value: Boolean) = setBool(context, "cctv_private", value)+fun showCellTowers(context: Context): Boolean = bool(context, "show_cell_towers", false)fun setShowCellTowers(context: Context, value: Boolean) = setBool(context, "show_cell_towers", value)fun showKnownAlpr(context: Context): Boolean = bool(context, "show_known_alpr", true)@@ -215,6 +236,21 @@ object Prefs {fun radarBeep(context: Context): Boolean = bool(context, "radar_beep", false)fun setRadarBeep(context: Context, value: Boolean) = setBool(context, "radar_beep", value)+ /** Radar-detector sound style: Ka / K / X style tones, startup sweep, "GPS connected", short voice. */+ fun detectorSound(context: Context): Boolean = bool(context, "detector_sound", false)+ fun setDetectorSound(context: Context, value: Boolean) = setBool(context, "detector_sound", value)++ /**+ * Radar-detector sound effect: 0 = by strength (1 strong, 2 probable, 3 weak, 4 following),+ * 1-4 = always that effect. The proximity beeps use a pulse of the same effect.+ */+ fun detectorEffect(context: Context): Int = int(context, "detector_effect", 0).coerceIn(0, 4)+ fun setDetectorEffect(context: Context, value: Int) = setInt(context, "detector_effect", value.coerceIn(0, 4))++ /** Play the intro sound when a scan starts. */+ fun scanIntro(context: Context): Boolean = bool(context, "scan_intro", false)+ fun setScanIntro(context: Context, value: Boolean) = setBool(context, "scan_intro", value)+fun threatBubble(context: Context): Boolean = bool(context, "threat_bubble", false)fun setThreatBubble(context: Context, value: Boolean) = setBool(context, "threat_bubble", value)diff --git a/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt b/app/src/main/java/com/rfsentinel/app/util/SoundClips.ktnew file mode 100644index 0000000..d419b37--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/SoundClips.kt@@ -0,0 +1,101 @@+package com.rfsentinel.app.util++import android.content.Context+import android.media.AudioAttributes+import android.media.MediaPlayer+import android.media.SoundPool+import com.rfsentinel.app.R++/**+ * Recorded sounds for the radar-detector sound style (res/raw): four alert effects, a+ * pulse of each for the proximity beeps, and the optional scan intro. Short clips go through a SoundPool+ * (loaded once, ready before the first alert); the long intro streams from a MediaPlayer.+ */+object SoundClips {++ /** The four detector alert sounds and, for each, one of its pulses for the proximity beeps. */+ enum class Clip(val res: Int, val ms: Int) {+ EFFECT_1(R.raw.detector_effect_1, 2_950),+ EFFECT_2(R.raw.detector_effect_2, 2_950),+ EFFECT_3(R.raw.detector_effect_3, 2_950),+ EFFECT_4(R.raw.detector_effect_4, 3_800),+ TICK_1(R.raw.detector_tick_1, 75),+ TICK_2(R.raw.detector_tick_2, 70),+ TICK_3(R.raw.detector_tick_3, 90),+ TICK_4(R.raw.detector_tick_4, 125);++ companion object {+ fun effect(n: Int) = entries[(n - 1).coerceIn(0, 3)]+ fun tick(n: Int) = entries[4 + (n - 1).coerceIn(0, 3)]+ }+ }++ private var pool: SoundPool? = null+ private val ids = HashMap<Clip, Int>()+ private val ready = HashSet<Int>()+ private var intro: MediaPlayer? = null+ private var previewStream = 0++ /** Loads the clips (async); call early, e.g. when a scan starts. */+ @Synchronized+ fun preload(context: Context, attributes: AudioAttributes) {+ if (pool != null) return+ val p = SoundPool.Builder().setMaxStreams(2).setAudioAttributes(attributes).build()+ p.setOnLoadCompleteListener { _, id, status -> if (status == 0) synchronized(this) { ready += id } }+ val app = context.applicationContext+ for (c in Clip.entries) ids[c] = p.load(app, c.res, 1)+ pool = p+ }++ /** Plays a clip; returns its length (ms), or 0 if it isn't loaded yet (caller falls back). */+ @Synchronized+ fun play(context: Context, attributes: AudioAttributes, clip: Clip): Int {+ preload(context, attributes)+ val id = ids[clip] ?: return 0+ if (id !in ready) return 0+ return if ((pool?.play(id, 1f, 1f, 1, 0, 1f) ?: 0) != 0) clip.ms else 0+ }++ /** A Settings preview: stops the previous preview first so two never overlap. */+ @Synchronized+ fun playPreview(context: Context, attributes: AudioAttributes, clip: Clip): Boolean {+ stopPreview()+ preload(context, attributes)+ val id = ids[clip] ?: return false+ if (id !in ready) return false+ previewStream = pool?.play(id, 1f, 1f, 1, 0, 1f) ?: 0+ return previewStream != 0+ }++ @Synchronized+ fun stopPreview() {+ if (previewStream != 0) pool?.stop(previewStream)+ previewStream = 0+ }++ @Synchronized+ fun introPlaying() = intro != null++ /** The optional scan intro (about 12 s); [onDone] runs when it ends or fails. */+ @Synchronized+ fun playIntro(context: Context, attributes: AudioAttributes, onDone: (() -> Unit)? = null) {+ stopIntro()+ val mp = MediaPlayer()+ runCatching {+ context.applicationContext.resources.openRawResourceFd(R.raw.scan_intro).use {+ mp.setDataSource(it.fileDescriptor, it.startOffset, it.length)+ }+ mp.setAudioAttributes(attributes)+ mp.setOnPreparedListener { it.start() }+ mp.setOnCompletionListener { synchronized(this) { if (intro === it) intro = null }; it.release(); onDone?.invoke() }+ mp.prepareAsync()+ intro = mp+ }.onFailure { mp.release(); onDone?.invoke() }+ }++ @Synchronized+ fun stopIntro() {+ intro?.let { runCatching { it.stop() }; it.release() }+ intro = null+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.ktindex 7109d83..45f54be 100644--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt@@ -11,7 +11,9 @@ import com.rfsentinel.app.detect.Hit*/object Spoken {- fun short(context: Context) = Prefs.shortVoice(context)+ /** Short phrases; always in the radar-detector sound style, which speaks like a detector. */+ /** Short phrases; always in the radar-detector sound style, which speaks like a detector. */+ fun short(context: Context) = Prefs.shortVoice(context) || Prefs.detectorSound(context) || Prefs.detectorSound(context)fun device(context: Context, hit: Hit, following: Boolean = false): String {if (!short(context)) return if (following) "Warning. ${hit.label} may be following you." else "${hit.label} nearby"diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xmlnew file mode 100644index 0000000..e86ba79--- /dev/null+++ b/app/src/main/res/drawable/ic_settings.xml@@ -0,0 +1,11 @@+<!-- Material Icons "settings" (Apache License 2.0). -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24"+ android:tint="?attr/colorControlNormal">+ <path+ android:fillColor="@android:color/white"+ android:pathData="M19.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94c0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 -0.12,-0.61L19.14,12.94zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6s3.6,1.62 3.6,3.6S13.98,15.6 12,15.6z" />+</vector>diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex a1b4c9e..c869caa 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -185,6 +185,7 @@<CheckBox android:id="@+id/presetGlobal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Global" /><CheckBox android:id="@+id/presetCanada" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Canada" /><CheckBox android:id="@+id/presetUs" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="United States" />+ <CheckBox android:id="@+id/presetFrance" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="France" /></LinearLayout><!-- ================= Alerts ================= -->@@ -221,6 +222,32 @@android:layout_height="wrap_content"android:text="Radar-detector beeps (faster as it gets closer)" />+ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/detectorSoundSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Radar-detector sound (Ka / K / X tones, GPS connected)" />++ <Button+ android:id="@+id/detectorEffectButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Detector sound effect" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/scanIntroSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Intro sound when a scan starts" />++ <Button+ android:id="@+id/testIntroButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Test intro" />+<TextView style="@style/SettingsLabel" android:text="Re-alert the same device after (minutes)" /><EditText@@ -369,6 +396,35 @@</LinearLayout><!-- ================= Known cameras ================= -->+ <TextView android:id="@+id/headerMap" style="@style/SettingsHeader" android:text="Map" />+ <LinearLayout android:id="@+id/sectionMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/mapKnownCamerasSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Show plate, speed and red-light cameras" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/mapTowersSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Show cell towers" />++ <LinearLayout+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:orientation="horizontal">++ <Button+ android:id="@+id/mapTracesButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Recorded traces" />+ </LinearLayout>+ </LinearLayout>+<TextView android:id="@+id/headerCameras" style="@style/SettingsHeader" android:text="Known cameras" /><LinearLayout android:id="@+id/sectionCameras" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">@@ -388,7 +444,20 @@android:id="@+id/autoCamerasSwitch"android:layout_width="match_parent"android:layout_height="wrap_content"- android:text="Show known cameras on the map" />+ android:text="Download cameras automatically for the map area" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/mapCctvSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Show CCTV cameras (OpenStreetMap)" />++ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/mapCctvPrivateSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:paddingStart="24dp"+ android:text="Include private and indoor CCTV" /><!-- Radius of "download the cameras around me" (also the setup wizard and the map menu). --><TextView@@ -413,6 +482,13 @@android:layout_height="wrap_content"android:text="Download cameras around me" />+ <Button+ android:id="@+id/mapDeleteCamerasButton"+ style="@style/Widget.MaterialComponents.Button.TextButton"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Delete downloaded cameras" />+<TextViewandroid:id="@+id/prefetchCamerasText"style="@style/SettingsLabel"diff --git a/app/src/main/res/raw/detector_effect_1.ogg b/app/src/main/res/raw/detector_effect_1.oggnew file mode 100644index 0000000..b3434e1Binary files /dev/null and b/app/src/main/res/raw/detector_effect_1.ogg differdiff --git a/app/src/main/res/raw/detector_effect_2.ogg b/app/src/main/res/raw/detector_effect_2.oggnew file mode 100644index 0000000..cd06ba8Binary files /dev/null and b/app/src/main/res/raw/detector_effect_2.ogg differdiff --git a/app/src/main/res/raw/detector_effect_3.ogg b/app/src/main/res/raw/detector_effect_3.oggnew file mode 100644index 0000000..931a21cBinary files /dev/null and b/app/src/main/res/raw/detector_effect_3.ogg differdiff --git a/app/src/main/res/raw/detector_effect_4.ogg b/app/src/main/res/raw/detector_effect_4.oggnew file mode 100644index 0000000..13f5403Binary files /dev/null and b/app/src/main/res/raw/detector_effect_4.ogg differdiff --git a/app/src/main/res/raw/detector_tick_1.wav b/app/src/main/res/raw/detector_tick_1.wavnew file mode 100644index 0000000..b3d183cBinary files /dev/null and b/app/src/main/res/raw/detector_tick_1.wav differdiff --git a/app/src/main/res/raw/detector_tick_2.wav b/app/src/main/res/raw/detector_tick_2.wavnew file mode 100644index 0000000..c528dd2Binary files /dev/null and b/app/src/main/res/raw/detector_tick_2.wav differdiff --git a/app/src/main/res/raw/detector_tick_3.wav b/app/src/main/res/raw/detector_tick_3.wavnew file mode 100644index 0000000..71d09d3Binary files /dev/null and b/app/src/main/res/raw/detector_tick_3.wav differdiff --git a/app/src/main/res/raw/detector_tick_4.wav b/app/src/main/res/raw/detector_tick_4.wavnew file mode 100644index 0000000..654beceBinary files /dev/null and b/app/src/main/res/raw/detector_tick_4.wav differdiff --git a/app/src/main/res/raw/scan_intro.ogg b/app/src/main/res/raw/scan_intro.oggnew file mode 100644index 0000000..ac679bcBinary files /dev/null and b/app/src/main/res/raw/scan_intro.ogg differdiff --git a/app/src/test/java/com/rfsentinel/app/alpr/CctvTest.kt b/app/src/test/java/com/rfsentinel/app/alpr/CctvTest.ktnew file mode 100644index 0000000..72d7157--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/alpr/CctvTest.kt@@ -0,0 +1,65 @@+package com.rfsentinel.app.alpr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class CctvTest {++ private val json = """+ {"elements":[+ {"type":"node","id":1,"lat":10.5,"lon":-20.5,"tags":{"man_made":"surveillance","surveillance:type":"camera",+ "surveillance":"public","camera:type":"fixed","camera:direction":"NE","camera:angle":"40","height":"6 m",+ "operator":"City police","camera:mount":"pole","surveillance:zone":"town"}},+ {"type":"node","id":2,"lat":10.5004,"lon":-20.5008,"tags":{"surveillance":"outdoor","camera:type":"dome"}},+ {"type":"way","id":3,"center":{"lat":10.5009,"lon":-20.5018},"tags":{"surveillance":"indoor"}},+ {"type":"node","id":4,"lat":10.5014,"lon":-20.5028},+ {"type":"node","id":5,"tags":{"surveillance":"public"}}+ ]}+ """.trimIndent()++ @Test+ fun parsesOverpassAnswer() {+ val cams = Cctv.parse(json)+ assertEquals(4, cams.size) // the one without a position is skipped+ val c = cams[0]+ assertEquals("node/1", c.osmId)+ assertEquals("public", c.zone)+ assertEquals(45, c.direction)+ assertEquals(40, c.angle)+ assertEquals(6.0, c.height!!, 0.0)+ assertEquals("pole", c.mount)+ assertEquals("town", c.area)+ assertFalse(c.isPrivate)+ assertTrue(cams[1].isPrivate)+ assertEquals("way/3", cams[2].osmId)+ assertTrue(cams[2].isPrivate)+ assertNull(cams[3].zone)+ assertFalse(cams[3].isPrivate) // unmapped counts as public: shown by default+ }++ @Test+ fun viewConeAndTitles() {+ val c = Cctv.parse(json)+ assertEquals(30.0, Cctv.viewRangeM(c[0]), 0.0) // 6 m high -> 30 m+ assertEquals(25.0, Cctv.viewRangeM(c[1]), 0.0) // height unknown+ assertEquals(40, Cctv.viewAngle(c[0]))+ assertEquals(90, Cctv.viewAngle(c[1])) // dome default+ assertEquals("Public fixed camera", Cctv.title(c[0]))+ assertEquals("Private dome camera (facing outside)", Cctv.title(c[1]))+ assertEquals("Surveillance camera", Cctv.title(c[3]))+ assertEquals(90, Cctv.parseAngle("40-90"))+ assertEquals(4.5, Cctv.parseHeight("4,5")!!, 0.0)+ assertNull(Cctv.parseAngle("0"))+ }++ @Test+ fun downloadBoxStaysSmall() {+ val (s, w, n, e) = CctvStore.expand(10.50, -20.51, 10.51, -20.50)+ assertTrue(n - s <= CctvStore.MAX_SPAN_DEG + 1e-9 && e - w <= CctvStore.MAX_SPAN_DEG + 1e-9)+ assertTrue(n - s >= 0.02)+ assertTrue(Cctv.query(s, w, n, e).contains("\"surveillance:type\"=\"camera\""))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.kt b/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.ktnew file mode 100644index 0000000..0763753--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.kt@@ -0,0 +1,40 @@+package com.rfsentinel.app.detect++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class FlockNoiseTest {++ private val liteon = Hit(Category.ALPR, "Liteon module seen on Flock cameras (community list)", 35,+ "Address is in the watchlisted block 12:34:56", "flock-you")+ private val fsName = Hit(Category.ALPR, "Flock Safety device", 70,+ "Name pattern \"FS-<hex>\" (generic white-label prefix - verify)", "test")+ private val penguin = Hit(Category.ALPR, "Flock Safety device", 70, "Name pattern \"Penguin-<digits>\"", "test")++ @Test+ fun namedGadgetsLoseTheModulePrefixMatch() {+ for (name in listOf("PHANTOM", "ClickShare-Room", "SILENCE-1234567", "Brompton_Elec", "RGB smart bulb"))+ assertTrue(name, FlockNoise.filter(listOf(liteon), name, flockRegion = true).isEmpty())+ // No name, or a Flock-style one: still a (weak) clue.+ assertEquals(1, FlockNoise.filter(listOf(liteon), null, true).size)+ assertEquals(1, FlockNoise.filter(listOf(liteon), "Penguin-1234567890", true).size)+ assertEquals(1, FlockNoise.filter(listOf(liteon), "FS Ext Battery", true).size)+ }++ @Test+ fun outsideFlocksMarketOnlyStrongSignaturesCount() {+ assertTrue(FlockNoise.filter(listOf(liteon, fsName), null, flockRegion = false).isEmpty())+ assertEquals(listOf(penguin), FlockNoise.filter(listOf(liteon, fsName, penguin), "Penguin-1234567890", false))+ assertEquals(1, FlockNoise.filter(listOf(fsName), "FS-ABC123", flockRegion = true).size)+ }++ @Test+ fun djiOsmoIsAnActionCameraNotADrone() {+ val osmo = SignatureEngine.classify(Advert("4C:43:F6:11:22:33", Advert.Source.BLE, -70, "OsmoNano-AB12"))+ assertTrue(osmo.none { it.category == Category.DRONE })+ assertEquals("DJI Osmo camera", osmo.first { it.category == Category.OTHER_CAMERA }.label)+ val drone = SignatureEngine.classify(Advert("4C:43:F6:11:22:34", Advert.Source.BLE, -70, "Mavic"))+ assertTrue(drone.any { it.category == Category.DRONE })+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/detect/FrenchDroneIdTest.kt b/app/src/test/java/com/rfsentinel/app/detect/FrenchDroneIdTest.ktnew file mode 100644index 0000000..a0518bf--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/detect/FrenchDroneIdTest.kt@@ -0,0 +1,59 @@+package com.rfsentinel.app.detect++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream++class FrenchDroneIdTest {++ /** A beacon IE as the reference implementation (khancyr/droneID_FR) builds it, from the OUI on. */+ private fun ie(lat: Int, lon: Int, id: String = "ILLDEMO00000000000000000000001"): ByteArray {+ val o = ByteArrayOutputStream()+ fun tlv(t: Int, v: ByteArray) { o.write(t); o.write(v.size); o.write(v) }+ fun be(x: Int, n: Int) = ByteArray(n) { ((x shr (8 * (n - 1 - it))) and 0xFF).toByte() }+ o.write(byteArrayOf(0x6A, 0x5C, 0x35, 0x01))+ tlv(1, byteArrayOf(1))+ tlv(2, id.padEnd(30, '0').toByteArray())+ tlv(4, be(lat, 4)); tlv(5, be(lon, 4))+ tlv(6, be(-12, 2)); tlv(7, be(85, 2))+ tlv(8, be(1_040_000, 4)); tlv(9, be(-2_040_000, 4))+ tlv(10, byteArrayOf(7)); tlv(11, be(270, 2))+ return o.toByteArray()+ }++ @Test+ fun decodesFrenchElectronicId() {+ val b = ie(1_050_000, -2_050_000)+ assertTrue(RemoteId.isWifiIe(b))+ assertTrue(RemoteId.isFrenchIe(b))+ assertFalse(RemoteId.isAstmWifiIe(b))+ val i = RemoteId.decodeWifiIe(b, null)!!+ assertEquals("ILLDEMO00000000000000000000001", i.uasId)+ assertEquals("French ID (signalement électronique)", i.idType)+ assertEquals(10.5, i.latitude!!, 1e-6)+ assertEquals(-20.5, i.longitude!!, 1e-6)+ assertEquals(-12.0, i.altitudeGeoM!!, 0.0)+ assertEquals(85.0, i.heightM!!, 0.0)+ assertEquals(10.4, i.operatorLatitude!!, 1e-6)+ assertEquals(7.0, i.speedMs!!, 0.0)+ assertEquals(270, i.directionDeg)+ }++ @Test+ fun negativeCoordinatesAndNoFix() {+ val west = RemoteId.decodeWifiIe(ie(-2_050_000, -3_050_000), null)!!+ assertEquals(-20.5, west.latitude!!, 1e-6)+ assertEquals(-30.5, west.longitude!!, 1e-6)+ val noFix = RemoteId.decodeWifiIe(ie(0, 0), west)!!+ assertEquals(-20.5, noFix.latitude!!, 1e-6)+ }++ @Test+ fun otherVendorIesAreIgnored() {+ assertFalse(RemoteId.isWifiIe(byteArrayOf(0x6A, 0x5C, 0x35, 0x02, 0x01)))+ assertNull(RemoteId.decodeWifiIe(byteArrayOf(0x00, 0x50, 0xF2.toByte(), 0x04), null))+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt b/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.ktnew file mode 100644index 0000000..03472e5--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt@@ -0,0 +1,79 @@+package com.rfsentinel.app.service++import android.app.Application+import com.rfsentinel.app.detect.Advert+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.DeviceIntel+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.ui.LiveWindow+import org.junit.After+import org.junit.Assert.assertFalse+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.annotation.Config++/** Live alerts stop once a flagged device is out of range, and a removed watchlist match doesn't linger. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class AlertRangeTest {++ private val t0 = 1_000_000L+ private val hit = Hit(Category.BODY_CAM, "Watched device", 90, "Your watchlist", "Your watchlist")+ private val id = DeviceIntel.Identity("Device", emptyList())++ @Before fun setUp() { DeviceRegistry.clear(); DeviceRegistry.startSession(t0); LiveWindow.wifiScanMs = 30_000L }+ @After fun tearDown() = DeviceRegistry.clear()++ @Test+ fun bluetoothStopsAlertingSecondsAfterItIsLastHeard() {+ DeviceRegistry.report(Advert("AA:00:00:00:00:01", Advert.Source.BLE, -60, "x"), listOf(hit), id, null, null, null, t0)+ val s = DeviceRegistry.get("AA:00:00:00:00:01")!!+ assertTrue(LiveWindow.alerting(s, t0 + 5_000))+ assertFalse(LiveWindow.alerting(s, t0 + LiveWindow.BLE_IN_RANGE_MS + 1_000))+ }++ @Test+ fun wifiStopsAlertingAfterAMissedScanRound() {+ DeviceRegistry.report(Advert("AA:00:00:00:00:02", Advert.Source.WIFI, -60, "x"), listOf(hit), id, null, null, null, t0)+ val s = DeviceRegistry.get("AA:00:00:00:00:02")!!+ assertTrue(LiveWindow.alerting(s, t0 + 35_000))+ assertFalse(LiveWindow.alerting(s, t0 + 41_000))+ }++ @Test+ fun flaggedDevicesFollowTheListSlider() {+ DeviceRegistry.report(Advert("AA:00:00:00:00:04", Advert.Source.BLE, -60, "x"), listOf(hit), id, null, null, null, t0)+ val s = DeviceRegistry.get("AA:00:00:00:00:04")!!+ assertTrue(LiveWindow.keep(s, t0 + 9_000, 10_000, 60_000))+ assertFalse(LiveWindow.keep(s, t0 + 11_000, 10_000, 60_000))+ // Never removed while it still counts as in range, even with a shorter setting.+ assertTrue(LiveWindow.keep(s, t0 + 7_000, 5_000, 60_000))+ }++ @Test+ fun wifiListWindowBelow30sIsSavedOnlyUsedWithFastScans() {+ val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext<Application>()+ android.provider.Settings.Global.putInt(ctx.contentResolver, android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1)+ com.rfsentinel.app.util.Prefs.setScanIntervalMs(ctx, 10_000L)+ com.rfsentinel.app.util.Prefs.setLiveWifiSec(ctx, 5)+ org.junit.Assert.assertEquals(5, com.rfsentinel.app.util.Prefs.liveWifiSec(ctx))+ // Back to a 30 s interval: the saved 5 s is raised to 30 s.+ com.rfsentinel.app.util.Prefs.setScanIntervalMs(ctx, 30_000L)+ org.junit.Assert.assertEquals(30, com.rfsentinel.app.util.Prefs.liveWifiSec(ctx))+ }++ @Test+ fun removedWatchlistMatchIsDroppedRightAway() {+ val mac = "AA:00:00:00:00:03"+ DeviceRegistry.report(Advert(mac, Advert.Source.BLE, -60, "x"), listOf(hit), id, null, null, null, t0)+ DeviceRegistry.replaceHits(mac, emptyList())+ assertNull(DeviceRegistry.get(mac)!!.best)+ // The next sighting (no match any more) doesn't bring the held match back.+ DeviceRegistry.report(Advert(mac, Advert.Source.BLE, -60, "x"), emptyList(), id, null, null, null, t0 + 1_000)+ assertNull(DeviceRegistry.get(mac)!!.best)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/util/BeeperTest.kt b/app/src/test/java/com/rfsentinel/app/util/BeeperTest.ktindex 515da33..0a61b84 100644--- a/app/src/test/java/com/rfsentinel/app/util/BeeperTest.kt+++ b/app/src/test/java/com/rfsentinel/app/util/BeeperTest.kt@@ -8,11 +8,23 @@ class BeeperTest {@Testfun radarTicksSpeedUpAsTheSignalGetsStronger() {- assertEquals(1600L, Beeper.tickIntervalMs(-100))- assertEquals(150L, Beeper.tickIntervalMs(-30))+ assertEquals(1300L, Beeper.tickIntervalMs(-100))+ assertEquals(60L, Beeper.tickIntervalMs(-30))+ assertTrue(Beeper.tickIntervalMs(-55) < 200 && Beeper.tickIntervalMs(-75) > 350)assertTrue(Beeper.tickIntervalMs(-60) < Beeper.tickIntervalMs(-80))}+ @Test+ fun detectorTonesGetFasterAndHigherWithStrength() {+ val ka = Beeper.detectorAlert(3); val k = Beeper.detectorAlert(2); val x = Beeper.detectorAlert(1)+ assertTrue(ka.size > k.size && k.size > x.size)+ assertTrue(ka.maxOf { it.toHz } > k.maxOf { it.fromHz } && k.maxOf { it.fromHz } > x.maxOf { it.fromHz })+ assertTrue(Beeper.toneDurationMs(ka) < 1_000 && Beeper.toneDurationMs(Beeper.detectorStartup) < 1_000)+ val pcm = Beeper.tonePcm(Beeper.detectorStartup)+ assertEquals(Beeper.toneDurationMs(Beeper.detectorStartup) * 22_050 / 1000, pcm.size)+ assertTrue(pcm.maxOf { it.toInt() } > 20_000)+ }+@Testfun patternMatchesTierAndFollowing() {assertEquals(1, Beeper.pattern(1, following = false).size)diff --git a/docs/index.html b/docs/index.htmlindex 7db9c77..2925502 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.1", "dateModified": "2026-10-05", "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.15.2", "dateModified": "2026-10-06", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "url": "https://cis-c0.github.io/RFSentinel/"}]}</script></head><body><a class="skip" href="#main">Skip to content</a>@@ -93,9 +93,9 @@<h2 id="features">Features</h2><div class="grid">- <div class="card"><h3>Live list & radar</h3><p>Every device heard in the last 3 minutes with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>- <div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer.</p></div>+ <div class="card"><h3>Live list & radar</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>+ <div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>+ <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>diff --git a/docs/sitemap.xml b/docs/sitemap.xmlindex 8f96202..dc7ca2f 100644--- a/docs/sitemap.xml+++ b/docs/sitemap.xml@@ -7,7 +7,7 @@<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-05</lastmod><priority>1.0</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/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-05</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>diff --git a/site/pages/index.html b/site/pages/index.htmlindex 829f8a6..74e09db 100644--- a/site/pages/index.html+++ b/site/pages/index.html@@ -53,9 +53,9 @@<h2 id="features">Features</h2><div class="grid">- <div class="card"><h3>Live list & radar</h3><p>Every device heard in the last 3 minutes with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>- <div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected.</p></div>- <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer.</p></div>+ <div class="card"><h3>Live list & radar</h3><p>Every device in range (each leaves 30 s after it was last heard on Bluetooth, 60 s on WiFi, adjustable) with vendor, type, radio, RSSI, rough distance and NEW / ★ / FOLLOWING badges. Flagged devices sort first. Filter chips with live counts.</p></div>+ <div class="card"><h3>Alerts</h3><p>Sound, vibration pattern per tier (1 / 2 / 3 pulses), spoken announcements through the phone's TTS, optional radar-detector beeps that speed up as a flagged device gets closer, discreet mode, floating threat bubble over Waze or Google Maps with a pop-up saying what was detected. Radar-detector sound style with selectable alert effects and an optional intro.</p></div>+ <div class="card"><h3>Map & traces</h3><p>OpenStreetMap with your GPS trace, devices placed where their signal peaked, history heatmap and timeline, offline known-camera layer. Optional CCTV layer: street, shop and building cameras mapped in OpenStreetMap, with their view cones.</p></div><div class="card"><h3>Android Auto</h3><p>Police alerts on the car screen as messages read aloud (reply "mute"), and an RF Sentinel screen with threats, cameras ahead, recent alerts and Scan / Mute buttons. The full car app with live map and navigation runs on Google's Desktop Head Unit. <a href="android-auto.html">Details</a></p></div><div class="card"><h3>Auto start in the car</h3><p>Starts when the phone connects to your car's Bluetooth or Android Auto, stops when you leave.</p></div><div class="card"><h3>Tools</h3><p>Cell towers (serving and neighbour cells, IDs, channel, signal, history, optional map layer and change alert) and WiFi channel / spectrum analyzers for 2.4, 5 and 6 GHz.</p></div>