Skip to content

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.

Tracker ignore fixes, camera download radius, ignore a camera, fake-cell detector rework, review fixes

CIS-C04f04219453d9
diff --git a/README.md b/README.md
index dae80d0..e765c70 100644
--- a/README.md
+++ b/README.md
@@ -95,10 +95,10 @@ publicly.
- Evidence fusion: independent matches on the same device strengthen each other
- Patrol-vehicle detection: several kinds of police-type equipment whose signals move together are flagged as a possible police vehicle
- Address-rotation linking: follows a device when its Bluetooth address changes
-- Follower alerts: a warning when a tracker or flagged device keeps moving with you
-- **Known plate, speed and red-light cameras:** the cameras mapped in OpenStreetMap (plate readers e.g. by DeFlock, fixed speed and red-light cameras) appear on the map by themselves for the area you look at, and you're warned as you approach one - even the cellular-only cameras no radio scan can detect. Speed cameras warn about 30 seconds ahead, with the limit when it's mapped. Areas are kept offline and refreshed weekly; the setup wizard (and Settings) can pre-download everything within ~100 km of you
+- Follower alerts: a warning when a tracker or flagged device keeps moving with you. Your own tag can be ignored (long-press it): RF Sentinel keeps ignoring it when its address changes
+- **Known plate, speed and red-light cameras:** the cameras mapped in OpenStreetMap (plate readers e.g. by DeFlock, fixed speed and red-light cameras) appear on the map by themselves for the area you look at, and you're warned as you approach one - even the cellular-only cameras no radio scan can detect. Speed cameras warn about 30 seconds ahead, with the limit when it's mapped. Areas are kept offline and refreshed weekly; the setup wizard (and Settings) can pre-download everything around you, within a radius you set (10-200 km, 100 by default). Tap a camera on the map to turn off its alerts for good (it stays on the map, faded)
- **Drones:** live map of each Remote ID drone with its heading, altitude, speed and operator, plus a "drone overhead" alert
-- **Fake cell tower signs (IMSI catchers):** warnings for test network codes, forced 2G downgrades, unexpected networks and other classic signs (heuristic, no root needed)
+- **Fake cell tower signs (IMSI catchers):** test network codes, sudden 4G-to-2G switches (the visible side of the 2G redirect [EFF's Rayhunter](https://github.com/EFForg/rayhunter) watches for), cloned cell identities, reserved cell identities, unexpected networks and other classic signs. Heuristic and no root needed; a sign must persist before it alerts, and drops to 2G during phone calls or area codes flipping at a coverage border don't count
- Editable watchlist with exact addresses, vendor prefixes, and name or vendor rules, plus regional presets (Global, Canada, US)
**Identification**
@@ -189,13 +189,15 @@ The app never connects to a device. The details screen shows:
Tap *All devices* to show flagged ones only. Devices heard from the same spot
fan out around it when you zoom in, so every dot can be tapped.
- **Known cameras** (map menu ⋮): *Download nearby cameras* fetches the plate
- readers within ~100 km; *Download Flock* fetches every plate reader mapped in
+ readers within the download radius set in Settings (10-200 km, 100 by default); *Download Flock* fetches every plate reader mapped in
the US and Canada (~18 MB, about 143,000, refreshed weekly on Wi-Fi). Both use
[DeFlock](https://deflock.org)'s hourly snapshot of OpenStreetMap, then add the
ones it leaves out (other tagging, Flock cameras mapped as ordinary cameras)
straight from OpenStreetMap. A progress bar shows under the status card, and
the cameras appear as soon as DeFlock's part is saved. Speed and red-light
- cameras come with the automatic downloads for the area you look at.
+ cameras come with the automatic downloads for the area you look at. Tap a
+ camera and choose *Ignore alerts* to never be warned about it again; it stays
+ on the map, faded, and *Alert again* (or Settings) turns it back on.
- **Screen:** Settings (and the setup wizard) choose whether the screen stays on
while RF Sentinel is open: *always*, *while charging* (default - car mount,
desk) or *normal*.
@@ -395,6 +397,10 @@ Pick a theme in the setup wizard or under **Settings → Appearance**.
- **Fake cell tower checks are heuristic.** Without root, Android shows the cells the
phone sees but not ciphering or signalling, so each sign has innocent explanations.
The strongest protection is turning off *Allow 2G* in your SIM settings (Android 12+).
+ Android 15+ phones can also warn by themselves when a network asks for your SIM's
+ identity or turns encryption off (*Cellular security > Network notifications*);
+ Settings links there. Rayhunter's other checks need the modem's signalling, which
+ only rooted or dedicated hardware can read.
- **Randomized addresses** defeat vendor-prefix matching. Payload signatures and
address-rotation linking partly compensate.
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 7a66382..7e4add9 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -454,6 +454,7 @@ class MainActivity : AppCompatActivity() {
R.id.action_mute -> {
val muted = !Prefs.alertsMuted(this)
Prefs.setAlertsMuted(this, muted)
+ if (muted) com.rfsentinel.app.util.Voice.silence()
invalidateOptionsMenu()
android.widget.Toast.makeText(
this, if (muted) "Alert sound and voice muted" else "Alert sound on", android.widget.Toast.LENGTH_SHORT
diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
index 93a2d08..b5e45ab 100644
--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt
@@ -42,6 +42,7 @@ class RFSentinelApp : Application() {
OuiWatchlist.load(this)
WhitelistCache.start(this, appScope)
appScope.launch(Dispatchers.IO) { com.rfsentinel.app.data.TrackerMutes.load(this@RFSentinelApp) }
+ appScope.launch(Dispatchers.IO) { com.rfsentinel.app.alpr.IgnoredCameras.load(this@RFSentinelApp) }
CarState.start(this)
// ~60k vendor rows: load off the main thread; lookups return null until ready.
// A trace left "recording" by a crash / force-stop gets closed.
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
index 7438b03..ef412dc 100644
--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
@@ -101,8 +101,8 @@ object AlprStore {
data class Progress(val area: Int, val done: Int, val total: Int, val found: Int, val failed: Int, val detail: String)
/**
- * Downloads every known camera within about [radiusKm] of a point, in up to
- * four tiles (small requests get through busy servers more easily). Tiles
+ * Downloads every known camera within about [radiusKm] of a point, in tiles
+ * of at most a degree (small requests get through busy servers more easily). Tiles
* that fail are skipped - the map fetches them later. Returns how many
* cameras were found, or throws when no tile could be downloaded.
*/
@@ -111,12 +111,13 @@ object AlprStore {
onProgress: (Progress) -> Unit = {}
): Int {
val tiles = CameraArea.tilesAround(lat, lon, radiusKm, MAX_SPAN_DEG / 2)
- val names = listOf("south-west", "south-east", "north-west", "north-east")
+ fun name(i: Int) = if (tiles.size == 4) listOf("south-west", "south-east", "north-west", "north-east")[i] + " area"
+ else "area ${i + 1} of ${tiles.size}"
var found = 0
var ok = 0
var lastError: Exception? = null
tiles.forEachIndexed { i, t ->
- val report = { detail: String -> onProgress(Progress(i + 1, i, tiles.size, found, i - ok, "${names[i]} area: $detail")) }
+ val report = { detail: String -> onProgress(Progress(i + 1, i, tiles.size, found, i - ok, "${name(i)}: $detail")) }
try {
found += download(context, t[0], t[1], t[2], t[3], report)
ok++
@@ -126,7 +127,7 @@ object AlprStore {
lastError = e
}
onProgress(Progress(i + 1, i + 1, tiles.size, found, i + 1 - ok,
- if (ok == i + 1) "${names[i]} area done" else "${names[i]} area failed - the map will fetch it later"))
+ if (ok == i + 1) "${name(i)} done" else "${name(i)} failed - the map will fetch it later"))
}
if (ok == 0) throw lastError ?: java.io.IOException("No answer")
return found
@@ -334,18 +335,25 @@ data class CameraArea(val south: Double, val west: Double, val north: Double, va
}
/**
- * The box within [radiusKm] of a point, split into 2x2 tiles no larger
- * than [maxTileDeg] on a side: [[south, west, north, east], ...].
+ * The box within [radiusKm] of a point, split into a grid (at least 2x2)
+ * of tiles no larger than [maxTileDeg] on a side: [[south, west, north, east], ...],
+ * row by row from the south-west.
*/
fun tilesAround(lat: Double, lon: Double, radiusKm: Double, maxTileDeg: Double): List<DoubleArray> {
- val dLat = (radiusKm / 111.0).coerceAtMost(maxTileDeg)
- val dLon = (radiusKm / (111.0 * kotlin.math.max(0.05, kotlin.math.cos(Math.toRadians(lat))))).coerceAtMost(maxTileDeg)
+ val dLat = radiusKm / 111.0
+ val dLon = radiusKm / (111.0 * kotlin.math.max(0.05, kotlin.math.cos(Math.toRadians(lat))))
val s = (lat - dLat).coerceAtLeast(-90.0); val n = (lat + dLat).coerceAtMost(90.0)
val w = (lon - dLon).coerceAtLeast(-180.0); val e = (lon + dLon).coerceAtMost(180.0)
- return listOf(
- doubleArrayOf(s, w, lat, lon), doubleArrayOf(s, lon, lat, e),
- doubleArrayOf(lat, w, n, lon), doubleArrayOf(lat, lon, n, e)
- )
+ val rows = kotlin.math.max(2, kotlin.math.ceil((n - s) / maxTileDeg - 1e-9).toInt())
+ val cols = kotlin.math.max(2, kotlin.math.ceil((e - w) / maxTileDeg - 1e-9).toInt())
+ return (0 until rows).flatMap { r ->
+ (0 until cols).map { c ->
+ doubleArrayOf(
+ s + (n - s) * r / rows, w + (e - w) * c / cols,
+ s + (n - s) * (r + 1) / rows, w + (e - w) * (c + 1) / cols
+ )
+ }
+ }
}
/** Smallest box one automatic download covers (degrees, ~40 km). */
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt b/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt
index d778986..2429759 100644
--- a/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt
+++ b/app/src/main/java/com/rfsentinel/app/alpr/CameraPrefetch.kt
@@ -23,7 +23,8 @@ import kotlin.coroutines.resume
/**
* "Download the cameras around me": finds where you are and fetches the known
- * plate, speed and red-light cameras within ~100 km, so they're on the map and
+ * plate, speed and red-light cameras within the radius set in Settings (100 km
+ * by default), so they're on the map and
* warn you offline from the start. Runs in the background - leaving the screen
* that started it doesn't stop it. Only the area is sent, never your scans.
*/
@@ -33,7 +34,7 @@ object CameraPrefetch {
data object Idle : State
data object Locating : State
data class Downloading(val done: Int, val total: Int, val found: Int = 0, val detail: String = "") : State
- data class Done(val cameras: Int, val failedAreas: Int = 0) : State
+ data class Done(val cameras: Int, val failedAreas: Int = 0, val radiusKm: Int = 100) : State
data class Failed(val reason: String) : State
}
@@ -91,7 +92,7 @@ object CameraPrefetch {
)
is State.Done -> h.showCameraDownload(
ctx, "Known cameras ready",
- "${s.cameras} plate, speed and red-light cameras saved within ~100 km - they work offline." +
+ "${s.cameras} plate, speed and red-light cameras saved within ~${s.radiusKm} km - they work offline." +
(if (s.failedAreas > 0) " ${s.failedAreas} area(s) failed; the map will fetch them when you look there." else ""),
0, 0, false
)
@@ -107,14 +108,15 @@ object CameraPrefetch {
set(State.Locating)
val here = currentLocation(app)
if (here == null) { set(State.Failed("No location yet - try again outdoors, or open the map later")); return@launch }
+ val radius = com.rfsentinel.app.util.Prefs.cameraRadiusKm(app)
set(State.Downloading(0, 4, detail = "starting"))
try {
var failed = 0
- val n = AlprStore.downloadAround(app, here.latitude, here.longitude) { p ->
+ val n = AlprStore.downloadAround(app, here.latitude, here.longitude, radius.toDouble()) { p ->
failed = p.failed
set(State.Downloading(p.done, p.total, p.found, p.detail))
}
- set(State.Done(n, failed))
+ set(State.Done(n, failed, 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/IgnoredCameras.kt b/app/src/main/java/com/rfsentinel/app/alpr/IgnoredCameras.kt
new file mode 100644
index 0000000..96a5f6d
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/alpr/IgnoredCameras.kt
@@ -0,0 +1,52 @@
+package com.rfsentinel.app.alpr
+
+import android.content.Context
+
+/**
+ * Known cameras the user silenced from the map (tap a camera > Ignore alerts),
+ * by OpenStreetMap id. Kept until the user turns the camera back on (or clears
+ * the list in Settings) - they still show on the map, faded.
+ */
+object IgnoredCameras {
+
+ private const val PREFS = "ignored_cameras"
+ private const val KEY = "osm_ids"
+
+ @Volatile private var ids: Set<String> = emptySet()
+ @Volatile private var loaded = false
+
+ private fun ensure(context: Context) {
+ if (loaded) return
+ synchronized(this) {
+ if (loaded) return
+ ids = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, null).orEmpty().toSet()
+ loaded = true
+ }
+ }
+
+ fun load(context: Context) = ensure(context)
+
+ fun contains(context: Context, osmId: String): Boolean {
+ ensure(context)
+ return osmId in ids
+ }
+
+ @Synchronized
+ fun set(context: Context, osmId: String, ignored: Boolean) {
+ ensure(context)
+ ids = if (ignored) ids + osmId else ids - osmId
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, ids).apply()
+ }
+
+ fun count(context: Context): Int {
+ ensure(context)
+ return ids.size
+ }
+
+ @Synchronized
+ fun clear(context: Context) {
+ ensure(context)
+ ids = emptySet()
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove(KEY).apply()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
index 35f1237..f16979b 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
@@ -107,6 +107,7 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {
.setIcon(CarUi.icon(carContext, if (muted) R.drawable.ic_car_volume_off else R.drawable.ic_car_volume))
.setOnClickListener {
val nowMuted = !Prefs.alertsMuted(carContext)
+ if (nowMuted) com.rfsentinel.app.util.Voice.silence()
Prefs.setAlertsMuted(carContext, nowMuted)
toast(if (nowMuted) "Alert sound muted" else "Alert sound on - plays through the car speakers")
invalidate()
diff --git a/app/src/main/java/com/rfsentinel/app/data/TrackerMutes.kt b/app/src/main/java/com/rfsentinel/app/data/TrackerMutes.kt
index 2ed7650..d19590a 100644
--- a/app/src/main/java/com/rfsentinel/app/data/TrackerMutes.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/TrackerMutes.kt
@@ -33,6 +33,9 @@ object TrackerMutes {
/** In-memory rules; no Android types. */
class Store(var mutes: List<Mute> = emptyList()) {
+ /** When each muted address was last written to storage (last seen is kept fresh in memory). */
+ private val persisted = HashMap<String, Long>()
+
fun isMuted(mac: String, now: Long): Boolean = mutes.any { it.mac == mac && it.until > now }
fun mute(mac: String, kind: String, rssi: Int, now: Long, follow: Boolean) {
@@ -45,26 +48,36 @@ object TrackerMutes {
/**
* A tracker of [kind] was heard. Returns true when it's muted - possibly
* because it just inherited the mute of a "mine" tag whose address changed.
+ * [linkedFrom] is the address the scanner linked this one to (same advert
+ * fingerprint, see DeviceRegistry), the surest sign of an address change.
* Returns whether the stored list changed through [changed].
*/
- fun onSeen(mac: String, kind: String, rssi: Int, now: Long, changed: (Boolean) -> Unit = {}): Boolean {
+ fun onSeen(
+ mac: String, kind: String, rssi: Int, now: Long,
+ linkedFrom: String? = null, changed: (Boolean) -> Unit = {}
+ ): Boolean {
mutes = mutes.filter { it.until > now }
val own = mutes.firstOrNull { it.mac == mac }
if (own != null) {
- // Keep "last seen" fresh, but don't rewrite storage on every packet.
- if (now - own.lastSeen > 30_000) {
- mutes = mutes.map { if (it.mac == mac) it.copy(lastSeen = now, lastRssi = rssi) else it }
+ // "Last seen" stays fresh in memory on every packet, so a tag that's still
+ // around never looks silent (and can't hand its mute to another tag);
+ // storage is rewritten at most every 30 s.
+ mutes = mutes.map { if (it.mac == mac) it.copy(lastSeen = now, lastRssi = rssi) else it }
+ if (now - (persisted[mac] ?: 0L) > 30_000) {
+ persisted[mac] = now
changed(true)
}
return true
}
- val candidates = mutes.filter {
+ // The scanner linked this address to a muted "mine" tag's previous one.
+ val linked = linkedFrom?.let { from -> mutes.firstOrNull { it.follow && it.mac == from } }
+ val prev = linked ?: mutes.filter {
it.follow && it.kind == kind &&
now - it.lastSeen in SILENT_MS..CARRY_WINDOW_MS &&
kotlin.math.abs(it.lastRssi - rssi) <= RSSI_TOLERANCE_DB
- }
- val prev = candidates.singleOrNull() ?: return false
+ }.singleOrNull() ?: return false
mutes = mutes.map { if (it === prev) it.copy(mac = mac, lastSeen = now, lastRssi = rssi) else it }
+ persisted[mac] = now
changed(true)
return true
}
@@ -104,10 +117,13 @@ object TrackerMutes {
fun load(context: Context) = ensure(context)
@Synchronized
- fun onSeen(context: Context, mac: String, kind: String, rssi: Int, now: Long = System.currentTimeMillis()): Boolean {
+ fun onSeen(
+ context: Context, mac: String, kind: String, rssi: Int,
+ now: Long = System.currentTimeMillis(), linkedFrom: String? = null
+ ): Boolean {
ensure(context)
var dirty = false
- val muted = store.onSeen(mac, kind, rssi, now) { dirty = it }
+ val muted = store.onSeen(mac, kind, rssi, now, linkedFrom) { dirty = it }
if (dirty) save(context)
return muted
}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt b/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt
index 135840d..d24e984 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/CellAnalyzer.kt
@@ -7,9 +7,21 @@ package com.rfsentinel.app.detect
* ciphering or signalling messages, so none of this is proof - each sign has
* innocent explanations, which is why most are weak on their own.
*
+ * Several checks follow EFF Rayhunter's analyzers as far as Android lets an
+ * app see them: Rayhunter reads the modem's signalling (a "release with
+ * redirect to 2G", incomplete system information); here only their visible
+ * effects can be checked (a sudden 4G-to-2G jump, a cell announcing reserved
+ * identities). To keep false alarms down, a sign must show in two snapshots in
+ * a row before it's reported (except a test network code), drops to 2G around
+ * phone calls are ignored (many networks fall back to 2G/3G for calls), and an
+ * area code that flips back and forth at a coverage border isn't a sign.
+ *
* Pure Kotlin: fed with snapshots by the scanner, unit-tested on the JVM.
+ *
+ * @param knownAreas the area each cell was seen in before ("RAT mcc-mnc cellId" -> area),
+ * kept across sessions by the caller, for spotting a cloned cell identity.
*/
-class CellAnalyzer {
+class CellAnalyzer(private val knownAreas: MutableMap<String, Int> = LinkedHashMap()) {
enum class Rat(val label: String, val generation: Int) {
GSM("2G (GSM)", 2), CDMA("2G/3G (CDMA)", 2), WCDMA("3G (UMTS)", 3), TDSCDMA("3G (TD-SCDMA)", 3),
@@ -28,6 +40,8 @@ class CellAnalyzer {
val dbm: Int?
) {
val key get() = "${rat.name} ${mcc ?: "?"}-${mnc ?: "?"} ${area ?: "?"}/${cellId ?: "?"}"
+ /** The cell's identity without its area: a cloned cell keeps this and changes the area. */
+ val idKey get() = if (mcc == null || mnc == null || cellId == null) null else "${rat.name} $mcc-$mnc $cellId"
}
/** What the scanner knows about you at the time of a snapshot. */
@@ -37,100 +51,235 @@ class CellAnalyzer {
val simOperator: String?,
val roaming: Boolean,
/** True when GPS shows you haven't moved (speed < ~1 m/s, < 50 m over a few minutes). */
- val stationary: Boolean?
+ val stationary: Boolean?,
+ /** A phone call is going on (or just ended): networks without 4G calling drop to 2G/3G for it. */
+ val inCall: Boolean = false
)
data class Anomaly(val key: String, val title: String, val detail: String, val confidence: Int)
- private data class Seen(val time: Long, val registered: Cell?, val neighbours: Int, val stationary: Boolean?)
+ private data class Seen(
+ val time: Long, val registered: Cell?, val neighbours: Int, val stationary: Boolean?,
+ val inCall: Boolean, val modernDbm: Int?
+ )
private val history = ArrayDeque<Seen>()
+ /** Signs found in the previous snapshot: a sign is reported once it shows twice in a row. */
+ private var lastRaw: Set<String> = emptySet()
+ /** Consecutive snapshots in which a known cell showed up with another area. */
+ private val areaMismatch = HashMap<String, Int>()
/** Analyses one snapshot of visible cells; returns the warning signs found in it. */
fun analyze(cells: List<Cell>, ctx: Context): List<Anomaly> {
- val out = mutableListOf<Anomaly>()
val serving = cells.firstOrNull { it.registered }
val neighbours = cells.count { !it.registered }
- val window = history.filter { ctx.time - it.time <= WINDOW_MS }
+ val modernDbm = cells.filter { !it.registered && it.rat.generation >= 4 }.mapNotNull { it.dbm }.maxOrNull()
+ val now = Seen(ctx.time, serving, neighbours, ctx.stationary, ctx.inCall, modernDbm)
+ val window = history.filter { ctx.time - it.time <= WINDOW_MS } + now
+ val raw = mutableListOf<Pair<Anomaly, Boolean>>() // anomaly to "report right away"
if (serving != null) {
- // 1. Test / reserved network codes: never used by real public networks.
- if (serving.mcc in TEST_MCC) {
- out += Anomaly(
- "test-plmn:${serving.key}", "Test network code on your cell",
- "Your phone is connected to ${serving.rat.label} network ${serving.mcc}-${serving.mnc}. " +
- "MCC ${serving.mcc} is reserved for test networks and lab equipment - real operators never use it, " +
- "but some IMSI catchers do.", 85
- )
- }
+ testNetwork(serving)?.let { raw += it to true }
+ foreignCountry(serving, ctx)?.let { raw += it to false }
+ downgrade(serving, window)?.let { raw += it to false }
+ areaChange(serving, window)?.let { raw += it to false }
+ isolated(serving, window)?.let { raw += it to false }
+ reservedIdentity(serving)?.let { raw += it to false }
+ clonedIdentity(serving)?.let { raw += it to false }
+ }
+ learnAreas(cells)
- // 2. Unexpected country: cell's MCC differs from your SIM's while the phone says it isn't roaming.
- val simMcc = ctx.simOperator?.take(3)
- if (simMcc != null && serving.mcc != null && serving.mcc !in TEST_MCC &&
- serving.mcc != simMcc && !ctx.roaming && simMcc !in SHARED_COUNTRY[serving.mcc].orEmpty()
- ) {
- out += Anomaly(
- "foreign:${serving.key}", "Unexpected network country code",
- "Your cell announces country code ${serving.mcc}, but your SIM is from $simMcc and the phone " +
- "doesn't report roaming. Near a border this can be normal.", 55
- )
- }
+ val out = raw.filter { (a, immediate) -> immediate || a.key in lastRaw }.map { it.first }.toMutableList()
+ // Two or more signs on the same cell at once weigh more than either alone.
+ if (serving != null && out.size >= 2) {
+ out += Anomaly(
+ "combined:${serving.key}", "Several fake-cell signs at once",
+ "Your cell shows ${out.size} warning signs together: " + out.joinToString("; ") { it.title.lowercase() } +
+ ". Each alone has innocent explanations; together they're more telling.",
+ minOf(90, out.maxOf { it.confidence } + 15)
+ )
+ }
+ lastRaw = raw.map { it.first.key }.toSet()
- // 3. Forced 2G: dropped to 2G/CDMA recently after 4G/5G, while 4G/5G cells are still in view.
- val wasModern = window.any { (it.registered?.rat?.generation ?: 0) >= 4 }
- val modernStillVisible = cells.any { !it.registered && it.rat.generation >= 4 }
- if (serving.rat.generation <= 2 && wasModern) {
- out += Anomaly(
- "downgrade:${serving.key}", "Network downgraded to 2G",
- "Your phone moved from 4G/5G to ${serving.rat.label}" +
- (if (modernStillVisible) " although 4G/5G cells are still in range" else "") +
- ". IMSI catchers force phones onto 2G, which has no network authentication. " +
- "Weak coverage can also cause this.",
- if (modernStillVisible) 65 else 40
- )
- }
+ history.addLast(now)
+ while (history.size > 120 || (history.isNotEmpty() && ctx.time - history.first().time > WINDOW_MS)) history.removeFirst()
+ return out
+ }
- // 4. Area changed while you stood still: a fake cell forces a location update.
- val prev = window.lastOrNull()?.registered
- if (ctx.stationary == true && prev != null && prev.rat == serving.rat && prev.mcc == serving.mcc &&
- prev.area != null && serving.area != null && prev.area != serving.area
- ) {
- out += Anomaly(
- "area:${serving.key}", "Location area changed while you weren't moving",
- "Your cell's area code changed from ${prev.area} to ${serving.area} while GPS shows you standing still. " +
- "Fake cells often do this to make phones re-register. Area borders and network load can also cause it.",
- 40
- )
- }
+ // ---- The signs ----------------------------------------------------------------
+
+ /** Test / reserved network codes: never used by real public networks. */
+ private fun testNetwork(serving: Cell): Anomaly? {
+ if (serving.mcc !in TEST_MCC) return null
+ return Anomaly(
+ "test-plmn:${serving.key}", "Test network code on your cell",
+ "Your phone is connected to ${serving.rat.label} network ${serving.mcc}-${serving.mnc}. " +
+ "MCC ${serving.mcc} is reserved for test networks and lab equipment - real operators never use it, " +
+ "but some IMSI catchers do.", 85
+ )
+ }
- // 5. No neighbours on a cell where several were visible moments ago.
- val hadNeighbours = window.takeLast(4).let { recent -> recent.size >= 2 && recent.all { it.neighbours >= 2 } }
- if (neighbours == 0 && hadNeighbours && prev != null && prev.key != serving.key) {
- out += Anomaly(
- "isolated:${serving.key}", "New cell with no neighbours",
- "Your phone switched to a cell that shows no neighbouring cells, where several were visible " +
- "moments ago. Fake stations often advertise no neighbours.", 35
- )
+ /** The cell's country differs from your SIM's while the phone says it isn't roaming. */
+ private fun foreignCountry(serving: Cell, ctx: Context): Anomaly? {
+ val simMcc = ctx.simOperator?.take(3) ?: return null
+ val mcc = serving.mcc ?: return null
+ if (mcc in TEST_MCC || mcc == simMcc || ctx.roaming || simMcc in SHARED_COUNTRY[mcc].orEmpty()) return null
+ return Anomaly(
+ "foreign:${serving.key}", "Unexpected network country code",
+ "Your cell announces country code $mcc, but your SIM is from $simMcc and the phone " +
+ "doesn't report roaming. Near a border this can be normal.", 55
+ )
+ }
+
+ /**
+ * On 2G now after 4G/5G. A jump straight from 4G/5G to 2G with a strong 4G
+ * cell still in view is the visible side of a "release with redirect to 2G"
+ * (Rayhunter's connection-redirect check); a slow slide is usually coverage.
+ * Ignored around phone calls (circuit-switched fallback).
+ */
+ private fun downgrade(serving: Cell, window: List<Seen>): Anomaly? {
+ if (serving.rat.generation > 2) return null
+ val start = runStart(window) { (it.registered?.rat?.generation ?: 9) <= 2 }
+ val run = window.subList(start, window.size)
+ val before = window.getOrNull(start - 1)
+ if (run.any { it.inCall } || before?.inCall == true) return null
+ val wasModern = window.subList(0, start).any { (it.registered?.rat?.generation ?: 0) >= 4 }
+ if (!wasModern) return null
+ val sudden = before != null && (before.registered?.rat?.generation ?: 0) >= 4 &&
+ run.first().time - before.time <= SUDDEN_MS
+ val strongModern = (window.last().modernDbm ?: Int.MIN_VALUE) >= STRONG_DBM
+ val (title, confidence) = when {
+ sudden && strongModern -> "Sudden switch from 4G/5G to 2G" to 70
+ sudden -> "Sudden switch from 4G/5G to 2G" to 50
+ strongModern -> "Network downgraded to 2G" to 50
+ else -> "Network downgraded to 2G" to 35
+ }
+ return Anomaly(
+ "downgrade:${serving.key}", title,
+ "Your phone went from 4G/5G to ${serving.rat.label}" +
+ (if (sudden) " in one step" else "") +
+ (if (strongModern) " although a strong 4G/5G cell is still in range" else "") +
+ ". IMSI catchers push phones onto 2G, which has no network authentication " +
+ "(like the redirect EFF's Rayhunter watches for). Weak coverage can also cause this.",
+ confidence
+ )
+ }
+
+ /**
+ * The area code changed while you stood still: a fake cell forces a location
+ * update. Not when the area just flips back to one seen minutes ago (a border).
+ */
+ private fun areaChange(serving: Cell, window: List<Seen>): Anomaly? {
+ val area = serving.area ?: return null
+ val start = runStart(window) { it.registered?.area == area && it.registered?.rat == serving.rat }
+ val prev = window.getOrNull(start - 1)?.registered ?: return null
+ val run = window.subList(start, window.size)
+ if (prev.rat != serving.rat || prev.mcc != serving.mcc || prev.area == null) return null
+ if (window.last().time - run.first().time > RECENT_MS) return null
+ if (run.any { it.stationary != true } || window[start - 1].stationary != true) return null
+ // Ping-pong at an area border: this area was already in use a few minutes ago.
+ if (window.subList(0, start).any { it.registered?.area == area }) return null
+ return Anomaly(
+ "area:${serving.key}", "Location area changed while you weren't moving",
+ "Your cell's area code changed from ${prev.area} to $area while GPS shows you standing still. " +
+ "Fake cells often do this to make phones re-register. Area borders and network load can also cause it.",
+ 40
+ )
+ }
+
+ /** Switched to a cell that shows no neighbours, where several were visible just before. */
+ private fun isolated(serving: Cell, window: List<Seen>): Anomaly? {
+ val start = runStart(window) { it.registered?.key == serving.key }
+ val run = window.subList(start, window.size)
+ if (run.any { it.neighbours > 0 } || window.last().time - run.first().time > RECENT_MS) return null
+ val before = window.subList(0, start).takeLast(4)
+ if (before.size < 2 || before.any { it.neighbours < 2 }) return null
+ return Anomaly(
+ "isolated:${serving.key}", "New cell with no neighbours",
+ "Your phone switched to a cell that shows no neighbouring cells, where several were visible " +
+ "moments ago. Fake stations often advertise no neighbours.", 35
+ )
+ }
+
+ /**
+ * The cell announces a reserved area or cell number (0, or the "deleted"
+ * values 0xFFFE / 0xFFFF) - real cells don't; minimally configured fake ones
+ * can (compare Rayhunter's incomplete-broadcast check).
+ */
+ private fun reservedIdentity(serving: Cell): Anomaly? {
+ val badArea = serving.area?.takeIf { it in RESERVED_AREA }
+ val badId = serving.cellId?.takeIf { it == 0L }
+ if (badArea == null && badId == null) return null
+ return Anomaly(
+ "reserved:${serving.key}", "Cell announces a reserved identity",
+ "Your cell reports " + listOfNotNull(badArea?.let { "area code $it" }, badId?.let { "cell number 0" }).joinToString(" and ") +
+ ", which real networks don't hand out. Misconfigured test or fake base stations can. " +
+ "Some phones also report this briefly while switching cells.", 45
+ )
+ }
+
+ /** A cell number seen before in another area: a fake cell copying a real cell's identity. */
+ private fun clonedIdentity(serving: Cell): Anomaly? {
+ val id = serving.idKey ?: return null
+ val area = serving.area ?: return null
+ val known = knownAreas[id] ?: return null
+ if (known == area) return null
+ return Anomaly(
+ "clone:${serving.key}", "Known cell number in a different area",
+ "Your cell uses the same network and cell number as one seen before in area $known, but now " +
+ "announces area $area. A fake station may copy a real cell's identity. Operators re-planning " +
+ "their network can also cause this (it stops after a while).", 50
+ )
+ }
+
+ /** Remembers each cell's area; a changed area is adopted once it has persisted (a re-planned network). */
+ private fun learnAreas(cells: List<Cell>) {
+ for (c in cells) {
+ val id = c.idKey ?: continue
+ val area = c.area?.takeIf { it !in RESERVED_AREA } ?: continue
+ val known = knownAreas[id]
+ if (known == null || known == area) {
+ areaMismatch.remove(id)
+ if (known == null) knownAreas[id] = area
+ } else {
+ val n = (areaMismatch[id] ?: 0) + 1
+ areaMismatch[id] = n
+ if (n >= ADOPT_AFTER) { knownAreas[id] = area; areaMismatch.remove(id) }
}
}
+ while (knownAreas.size > MAX_KNOWN) knownAreas.remove(knownAreas.keys.first())
+ }
- history.addLast(Seen(ctx.time, serving, neighbours, ctx.stationary))
- while (history.size > 120 || (history.isNotEmpty() && ctx.time - history.first().time > WINDOW_MS)) history.removeFirst()
- return out
+ /** Index in [window] where the trailing run of snapshots matching [f] starts ([window].size if none). */
+ private inline fun runStart(window: List<Seen>, f: (Seen) -> Boolean): Int {
+ var i = window.size
+ while (i > 0 && f(window[i - 1])) i--
+ return i
}
companion object {
/** Memory for "recently" (downgrade, area change, neighbours). */
const val WINDOW_MS = 10 * 60_000L
+ /** A switch counts as sudden when the snapshots on either side are this close. */
+ const val SUDDEN_MS = 40_000L
+ /** A transition is only a sign for this long after it happened. */
+ const val RECENT_MS = 3 * 60_000L
+ /** A 4G/5G neighbour at least this strong means coverage wasn't the reason for 2G. */
+ const val STRONG_DBM = -105
+ /** Snapshots in a row after which a cell's new area is taken as real. */
+ const val ADOPT_AFTER = 8
+ const val MAX_KNOWN = 5000
/** ITU test / reserved codes. */
val TEST_MCC = setOf("001", "002", "999")
+ /** Area codes reserved in 3GPP (0, and 0xFFFE / 0xFFFF "deleted / no valid area"). */
+ val RESERVED_AREA = setOf(0, 0xFFFE, 0xFFFF)
/** Countries that share networks with a neighbour's MCC (e.g. US 310-316). */
private val SHARED_COUNTRY = mapOf(
"310" to setOf("311", "312", "313", "314", "315", "316"),
"311" to setOf("310", "312", "313", "314", "315", "316"),
"312" to setOf("310", "311"), "313" to setOf("310", "311"), "314" to setOf("310", "311"),
"315" to setOf("310", "311"), "316" to setOf("310", "311"),
- "405" to setOf("404"), "404" to setOf("405")
+ "405" to setOf("404", "406"), "404" to setOf("405", "406"), "406" to setOf("404", "405")
)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt b/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt
index 8b14f94..240fea6 100644
--- a/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/CellMonitor.kt
@@ -26,8 +26,13 @@ import kotlin.coroutines.resume
*/
class CellMonitor(private val context: Context) {
- private val analyzer = CellAnalyzer()
+ /** Each cell's area as seen before (for the cloned-identity check), kept across sessions. */
+ private val knownAreas: MutableMap<String, Int> = loadKnownAreas()
+ private val analyzer = CellAnalyzer(knownAreas)
private val tm = context.getSystemService(TelephonyManager::class.java)
+ private val audio = context.getSystemService(android.media.AudioManager::class.java)
+ private var lastCallAt = 0L
+ private var checks = 0
private val executor = Executors.newSingleThreadExecutor()
private val fixes = ArrayDeque<Location>()
@@ -57,13 +62,39 @@ class CellMonitor(private val context: Context) {
val cells = infos.mapNotNull(::toCell)
if (cells.isEmpty()) return emptyList()
val now = System.currentTimeMillis()
+ // A call (or one that just ended): networks without 4G calling drop to 2G/3G for it.
+ // The audio mode tells without the phone-state permission.
+ if (audio?.mode == android.media.AudioManager.MODE_IN_CALL) lastCallAt = now
val ctx = CellAnalyzer.Context(
time = now,
simOperator = runCatching { tm.simOperator }.getOrNull()?.takeIf { it.length >= 5 },
roaming = runCatching { tm.isNetworkRoaming }.getOrDefault(false),
- stationary = stationary(now)
+ stationary = stationary(now),
+ inCall = now - lastCallAt < CALL_GRACE_MS
)
- return analyzer.analyze(cells, ctx)
+ return synchronized(knownAreas) {
+ if (forgetCells) { knownAreas.clear(); forgetCells = false }
+ analyzer.analyze(cells, ctx).also { if (++checks % SAVE_EVERY == 0) saveKnownAreas() }
+ }
+ }
+
+ private val knownFile get() = java.io.File(context.filesDir, "known_cells.txt")
+
+ /** "RAT mcc-mnc cellId<TAB>area" per line, oldest first. */
+ private fun loadKnownAreas(): MutableMap<String, Int> = LinkedHashMap<String, Int>().also { map ->
+ runCatching {
+ knownFile.takeIf { it.exists() }?.forEachLine { line ->
+ val tab = line.lastIndexOf('\t')
+ if (tab > 0) line.substring(tab + 1).toIntOrNull()?.let { map[line.substring(0, tab)] = it }
+ }
+ }
+ }
+
+ private fun saveKnownAreas() = synchronized(knownAreas) {
+ if (forgetCells) { knownAreas.clear(); forgetCells = false }
+ runCatching {
+ knownFile.writeText(knownAreas.entries.joinToString("\n") { "${it.key}\t${it.value}" })
+ }
}
/** Fresh cell info on Android 10+ (falls back to the cached list). */
@@ -138,9 +169,26 @@ class CellMonitor(private val context: Context) {
private fun android.telephony.CellIdentityWcdma.mncCompat() =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) mncString else mnc.orNull()?.let { "%02d".format(it) }
- fun close() = executor.shutdown()
+ fun close() {
+ saveKnownAreas()
+ executor.shutdown()
+ }
companion object {
+ /** Drops to 2G this long after a call are still put down to the call. */
+ private const val CALL_GRACE_MS = 2 * 60_000L
+ /** The cell memory is written every this many checks (~5 min), and when scanning stops. */
+ private const val SAVE_EVERY = 20
+
+ /** Set by "Forget device history": a running monitor empties its cell memory too. */
+ @Volatile private var forgetCells = false
+
+ /** Erases the remembered cells (which towers you were near) - with the device history. */
+ fun forget(context: Context) {
+ forgetCells = true
+ runCatching { java.io.File(context.filesDir, "known_cells.txt").delete() }
+ }
+
/** Last warning sign raised (for the main screen), and when. */
@Volatile var lastAnomaly: Pair<Long, CellAnalyzer.Anomaly>? = null
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
index ca056a5..0224cf5 100644
--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
@@ -93,6 +93,8 @@ object DeviceRegistry {
var bestRssi = -127
var distance = 0.0
val firstSeen = now
+ /** Heard since (the earlier address's time when linked after an address change): for follow detection. */
+ var since = now
var lastSeen = now
var sightings = 0
val history = ArrayDeque<Sample>()
@@ -213,14 +215,23 @@ object DeviceRegistry {
)
} to (prev.name to prev.role)
}
+ // The follow check carries on too: time with you, where it was heard, and a warning
+ // already given (so a tag changing its address isn't reset - nor warned about again).
+ val follow = synchronized(prev) { Triple(prev.since, prev.path.toList(), prev.following) }
synchronized(t) {
t.linkedFrom = prev.mac
t.inherited = carried.first
if (t.name == null) t.name = carried.second.first
if (t.role == null) t.role = carried.second.second
+ t.since = minOf(t.since, follow.first)
+ follow.second.forEach { t.path.addLast(it) }
+ t.following = t.following || follow.third
}
}
+ /** The address this device used before its address rotated, if it was linked. */
+ fun linkedFrom(mac: String): String? = tracks[mac]?.let { synchronized(it) { it.linkedFrom } }
+
/** Matches carried over from this device's previous (rotated) address. */
fun inheritedHits(mac: String): List<Hit> = tracks[mac]?.let { synchronized(it) { it.inherited } }.orEmpty()
@@ -260,7 +271,7 @@ object DeviceRegistry {
synchronized(t) {
if (t.following || t.path.size < 3) return false
val first = t.path.first
- if (t.lastSeen - t.firstSeen < minDurationMs) return false
+ if (t.lastSeen - t.since < minDurationMs) return false
val moved = t.path.maxOf { metersBetween(first.lat, first.lon, it.lat, it.lon) }
if (moved < minDistanceM) return false
t.following = true
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 5849040..98b5120 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -431,7 +431,11 @@ class ScanForegroundService : Service() {
val best = c.hits.firstOrNull() ?: return
// Ignored trackers (their address changes, so they can't be whitelisted); this is
// also where an ignored "it's mine" tag carries its mute over to a new address.
- if (best.category == Category.TRACKER && com.rfsentinel.app.data.TrackerMutes.onSeen(this, mac, best.label, a.rssi, now)) return
+ // Any tracker match counts, not just the top one.
+ val trackerHit = c.hits.firstOrNull { it.category == Category.TRACKER }
+ if (trackerHit != null && com.rfsentinel.app.data.TrackerMutes.onSeen(
+ this, mac, trackerHit.label, a.rssi, now, DeviceRegistry.linkedFrom(mac))
+ ) return
if (WhitelistCache.contains(mac)) return
maybeLog(a, best, c.vendor, loc, now)
@@ -546,12 +550,17 @@ class ScanForegroundService : Service() {
// Search out to the larger (speed camera) radius, then apply each kind's own.
val radius = KnownCameras.warnRadius(speed, com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED)
val near = KnownCameras.near(AlprStore.cameras, loc.latitude, loc.longitude, radius)
- .filter { (cam, d) -> wantsAlert(cam.type) && d <= KnownCameras.warnRadius(speed, cam.type) }
+ .filter { (cam, d) ->
+ wantsAlert(cam.type) && d <= KnownCameras.warnRadius(speed, cam.type) &&
+ !com.rfsentinel.app.alpr.IgnoredCameras.contains(this, cam.osmId) // silenced from the map
+ }
val nearIds = near.map { it.first.osmId }.toSet()
alprLastDistance.keys.retainAll(nearIds)
for ((cam, d) in near) {
val prev = alprLastDistance.put(cam.osmId, d)
- val approaching = prev == null || d < prev - 3
+ // Only once a second fix shows you getting closer: a camera you just passed
+ // (or one near where the scan started) mustn't warn.
+ val approaching = prev != null && d < prev - 3
if (!approaching || now - (alprLastAlert[cam.osmId] ?: 0L) < KNOWN_ALPR_REPEAT_MS) continue
alprLastAlert[cam.osmId] = now
val alpr = cam.type == com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index 89cb9d0..ace639b 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -121,6 +121,14 @@ class SettingsActivity : AppCompatActivity() {
binding.trackerIgnoreButton.visibility = if (n > 0 || paused) android.view.View.VISIBLE else android.view.View.GONE
}
+ /** Known cameras silenced from the map (tap a camera > Ignore alerts). */
+ private fun updateIgnoredCamerasText() {
+ val n = com.rfsentinel.app.alpr.IgnoredCameras.count(this)
+ binding.ignoredCamerasText.text = if (n == 0) "No ignored cameras (tap a camera on the map to turn off its alerts)"
+ else "$n camera${if (n == 1) "" else "s"} with alerts turned off (shown faded on the map)"
+ binding.ignoredCamerasButton.visibility = if (n > 0) android.view.View.VISIBLE else android.view.View.GONE
+ }
+
/** ESP32 boards on USB (OUI-Spy / GhostESP) and an OUI-SPY board over Bluetooth. */
/** Speed, voice and a test button for spoken alerts; changes apply right away. */
private fun setupVoiceControls() {
@@ -310,6 +318,17 @@ class SettingsActivity : AppCompatActivity() {
Toast.LENGTH_LONG
).show()
}
+ binding.cellSecurityButton.setOnClickListener {
+ // The Cellular security page (Android 15+); else the general security page.
+ val opened = runCatching { startActivity(Intent("android.settings.CELLULAR_NETWORK_SECURITY")) }.isSuccess ||
+ runCatching { startActivity(Intent(Settings.ACTION_SECURITY_SETTINGS)) }.isSuccess
+ Toast.makeText(
+ this,
+ if (opened) "Look for Cellular security > Network notifications (Android 15+ only)"
+ else "Open Settings > Security & privacy > More security & privacy > Cellular security",
+ Toast.LENGTH_LONG
+ ).show()
+ }
updateWifiThrottleHint()
binding.bootSwitch.isChecked = Prefs.autoStartOnBoot(this)
binding.carAutoSwitch.isChecked = Prefs.carAutoStart(this)
@@ -396,7 +415,25 @@ class SettingsActivity : AppCompatActivity() {
binding.knownAlprSwitch.isChecked = Prefs.knownAlprAlerts(this)
binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)
binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)
+ fun showRadius(km: Int) {
+ binding.cameraRadiusText.text = "Download radius: $km km" +
+ if (km > 100) " (larger areas take longer and use more data)" else ""
+ binding.prefetchCamerasButton.text = "Download cameras around me (~$km km)"
+ }
+ Prefs.cameraRadiusKm(this).let { km -> binding.cameraRadiusSlider.value = km.toFloat(); showRadius(km) }
+ binding.cameraRadiusSlider.setLabelFormatter { "${it.toInt()} km" }
+ binding.cameraRadiusSlider.addOnChangeListener { _, value, fromUser ->
+ if (!fromUser) return@addOnChangeListener
+ Prefs.setCameraRadiusKm(this, value.toInt())
+ showRadius(value.toInt())
+ }
binding.prefetchCamerasButton.setOnClickListener { com.rfsentinel.app.alpr.CameraPrefetch.start(this) }
+ updateIgnoredCamerasText()
+ binding.ignoredCamerasButton.setOnClickListener {
+ com.rfsentinel.app.alpr.IgnoredCameras.clear(this)
+ updateIgnoredCamerasText()
+ Toast.makeText(this, "Every camera alerts again", Toast.LENGTH_SHORT).show()
+ }
stopObservingPrefetch = com.rfsentinel.app.alpr.CameraPrefetch.observe { s ->
val located = com.rfsentinel.app.alpr.CameraPrefetch.canRun(this)
binding.prefetchCamerasButton.isEnabled = located &&
@@ -425,9 +462,10 @@ class SettingsActivity : AppCompatActivity() {
binding.retentionInput.setText(Prefs.retentionDays(this).toString())
binding.exportAllButton.setOnClickListener { com.rfsentinel.app.util.Exporter.showExportMenu(this) }
binding.forgetHistoryButton.setOnClickListener {
- confirm("Forget device history?", "New/returning status and detect counts start over. Favorites are kept.") {
+ confirm("Forget device history?", "New/returning status, detect counts and the cell towers remembered for the fake-cell checks start over. Favorites are kept.") {
lifecycleScope.launch {
AppDatabase.getInstance(this@SettingsActivity).knownDeviceDao().clearNonFavorites()
+ com.rfsentinel.app.service.CellMonitor.forget(this@SettingsActivity)
Toast.makeText(this@SettingsActivity, "Device history cleared", Toast.LENGTH_SHORT).show()
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CameraPrefetchText.kt b/app/src/main/java/com/rfsentinel/app/ui/CameraPrefetchText.kt
index e4e05a7..7a3557f 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/CameraPrefetchText.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/CameraPrefetchText.kt
@@ -9,7 +9,7 @@ fun cameraPrefetchText(s: CameraPrefetch.State, located: Boolean): String = when
is CameraPrefetch.State.Downloading ->
"Downloading... ${s.done}/${s.total} areas, ${s.found} cameras so far\n${s.detail}\n" +
"No need to wait - it keeps going in the background (see your notifications)."
- is CameraPrefetch.State.Done -> "✓ ${s.cameras} known cameras saved within ~100 km of you." +
+ is CameraPrefetch.State.Done -> "✓ ${s.cameras} known cameras saved within ~${s.radiusKm} km of you." +
(if (s.failedAreas > 0) " ${s.failedAreas} area(s) failed - the map fetches them when you look there." else "")
is CameraPrefetch.State.Failed -> "Couldn't download: ${s.reason}"
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CameraRadiusSlider.kt b/app/src/main/java/com/rfsentinel/app/ui/CameraRadiusSlider.kt
new file mode 100644
index 0000000..50de257
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/CameraRadiusSlider.kt
@@ -0,0 +1,39 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.widget.LinearLayout
+import android.widget.TextView
+import com.google.android.material.slider.Slider
+import com.rfsentinel.app.util.Prefs
+
+/**
+ * "Download radius: N km" with a 10-200 km slider, saved as you slide. The same
+ * setting as in Settings; used by the setup wizard and the map menu.
+ */
+object CameraRadiusSlider {
+
+ fun text(km: Int) = "Download radius: $km km" +
+ if (km > 100) " (larger areas take longer and use more data)" else ""
+
+ /** A label + slider block; [onChange] runs after each change (already saved). */
+ fun create(context: Context, onChange: (Int) -> Unit = {}): LinearLayout {
+ val label = TextView(context).apply { text = text(Prefs.cameraRadiusKm(context)) }
+ val slider = Slider(context).apply {
+ valueFrom = 10f; valueTo = 200f; stepSize = 10f
+ value = Prefs.cameraRadiusKm(context).toFloat()
+ contentDescription = "Camera download radius in kilometres"
+ setLabelFormatter { "${it.toInt()} km" }
+ addOnChangeListener { _, v, fromUser ->
+ if (!fromUser) return@addOnChangeListener
+ Prefs.setCameraRadiusKm(context, v.toInt())
+ label.text = text(v.toInt())
+ onChange(v.toInt())
+ }
+ }
+ return LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(label)
+ addView(slider, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index 2a14f6b..d6b1deb 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -76,7 +76,11 @@ class DeviceDetailActivity : AppCompatActivity() {
binding.actionWhitelist.setOnClickListener {
val s = DeviceRegistry.get(mac)
when {
- com.rfsentinel.app.data.TrackerMutes.isMuted(mac) -> com.rfsentinel.app.data.TrackerMutes.unmute(this, mac)
+ com.rfsentinel.app.data.TrackerMutes.isMuted(mac) -> {
+ com.rfsentinel.app.data.TrackerMutes.unmute(this, mac)
+ Toast.makeText(this, "Tracker no longer ignored", Toast.LENGTH_SHORT).show()
+ refresh()
+ }
WhitelistCache.inTable(mac) -> DeviceActions.unwhitelist(this, mac)
isRotatingTracker(s) -> DeviceActions.ignoreTracker(this, mac)
else -> DeviceActions.whitelist(this, mac, s?.let { it.best?.label ?: it.name } ?: "")
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
index 1cf76a9..65f97a7 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapActivity.kt
@@ -194,12 +194,18 @@ class MapActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
binding.map.onResume()
+ // The location overlay's GPS runs only while the map is on screen.
+ if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
+ myLocation.enableMyLocation()
+ if (following) myLocation.enableFollowLocation()
+ }
// Precise GPS while the map is on screen, so devices land where they were heard.
if (tripId == null) ScanForegroundService.mapShown(this)
}
override fun onPause() {
if (tripId == null) ScanForegroundService.mapHidden(this)
+ myLocation.disableMyLocation()
binding.map.onPause()
super.onPause()
}
@@ -613,6 +619,8 @@ class MapActivity : AppCompatActivity() {
knownAlpr.add(Marker(map).apply {
position = GeoPoint(cam.lat, cam.lon)
this.icon = icons.getValue(cam.type)
+ // Cameras whose alerts you turned off stay on the map, faded.
+ if (com.rfsentinel.app.alpr.IgnoredCameras.contains(this@MapActivity, cam.osmId)) alpha = 0.35f
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
title = cam.label
setOnMarkerClickListener { _, _ -> showKnownCamera(cam); true }
@@ -625,7 +633,9 @@ class MapActivity : AppCompatActivity() {
private fun cameraIcon(dp: Float, kind: com.rfsentinel.app.alpr.KnownCamera.Kind) = MapIcons.cameraIcon(dp, kind)
private fun showKnownCamera(cam: com.rfsentinel.app.alpr.KnownCamera) {
+ val ignored = com.rfsentinel.app.alpr.IgnoredCameras.contains(this, cam.osmId)
val text = buildString {
+ if (ignored) append("Alerts for this camera are off.\n\n")
append(when (cam.type) {
com.rfsentinel.app.alpr.KnownCamera.Kind.ALPR -> "A license-plate reader mapped in OpenStreetMap.\n\n"
com.rfsentinel.app.alpr.KnownCamera.Kind.SPEED -> "A speed camera mapped in OpenStreetMap.\n\n"
@@ -640,7 +650,14 @@ class MapActivity : AppCompatActivity() {
AlertDialog.Builder(this)
.setTitle(cam.label)
.setMessage(text)
- .setPositiveButton("Close", null)
+ // Kept until turned back on here (or cleared in Settings).
+ .setPositiveButton(if (ignored) "Alert again" else "Ignore alerts") { _, _ ->
+ com.rfsentinel.app.alpr.IgnoredCameras.set(this, cam.osmId, !ignored)
+ Toast.makeText(this, if (ignored) "You'll be warned about this camera again"
+ else "No more alerts for this camera (tap it again to undo)", Toast.LENGTH_SHORT).show()
+ drawKnownAlpr()
+ }
+ .setNegativeButton("Close", null)
.setNeutralButton("Open in OpenStreetMap") { _, _ ->
runCatching { startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse("https://www.openstreetmap.org/${cam.osmId}"))) }
}
@@ -657,20 +674,35 @@ class MapActivity : AppCompatActivity() {
}
/**
- * DeFlock's snapshot - all of the US & Canada, or with [nearby] only ~100 km
- * around you (or the map centre without a GPS fix). Progress in the status
+ * 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
- announceWhere = if (nearby) "within ~100 km" else "(US & Canada)"
+ 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)
+ 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. */
@@ -733,7 +765,7 @@ class MapActivity : AppCompatActivity() {
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, 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)
@@ -750,7 +782,7 @@ class MapActivity : AppCompatActivity() {
2 -> { id?.let { rename(it) }; true }
3 -> { id?.let { confirmDelete(it) }; true }
4 -> { startActivity(Intent(this, TripsActivity::class.java)); true }
- 5 -> { downloadAllPlateCameras(nearby = true); true }
+ 5 -> { askNearbyRadius(); true }
6 -> {
val show = !com.rfsentinel.app.util.Prefs.showKnownAlpr(this)
com.rfsentinel.app.util.Prefs.setShowKnownAlpr(this, show)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
index 8fd9fd5..13184dc 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
@@ -255,10 +255,12 @@ class SetupActivity : AppCompatActivity() {
/** Pre-downloads the known cameras around you, so the map and warnings work offline from the start. */
private fun knownCamerasNearMe() {
label("Known cameras near you")
- para("Download the plate, speed and red-light cameras mapped in OpenStreetMap within about 100 km of you, " +
+ para("Download the plate, speed and red-light cameras mapped in OpenStreetMap around you, " +
"so they're on the map and warn you offline right away. Only that area is sent to the OpenStreetMap server.", small = true)
para("No need to wait for it: tap Finish whenever you like - it keeps downloading in the background, " +
"with its progress in your notifications.", small = true)
+ // Same radius as in Settings and the map menu.
+ binding.page.addView(CameraRadiusSlider.create(this))
val btn = button("Download cameras around me now") { com.rfsentinel.app.alpr.CameraPrefetch.start(this) }
val status = para("", small = true)
check("Download them when I tap Finish (if not started yet)", prefetchOnFinish) { prefetchOnFinish = it }
diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
index 84e1ec4..24e0ee3 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -59,10 +59,10 @@ object AlertPlayer {
val inCar = CarState.connected
val muted = Prefs.alertsMuted(context)
val willSpeak = !muted && spoken != null && (Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))
- // Speech holds its own audio focus for exactly as long as it talks; this covers the beeps.
- if (!muted && Prefs.soundEnabled(context)) duckOthers(context, 2_500L)
var beepMs = 0
if (!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)
// 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 }
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 76e81a5..a1c3434 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -104,6 +104,10 @@ object Prefs {
fun speedCameraAlerts(context: Context): Boolean = bool(context, "speed_camera_alerts", true)
fun setSpeedCameraAlerts(context: Context, value: Boolean) = setBool(context, "speed_camera_alerts", value)
/** Fetch known cameras for the map area on screen (and around you in the car) automatically. */
+ /** Radius of "download the cameras around me" (Settings, setup wizard, map menu), in km. */
+ fun cameraRadiusKm(context: Context): Int = int(context, "camera_radius_km", 100).coerceIn(10, 200)
+ fun setCameraRadiusKm(context: Context, km: Int) = setInt(context, "camera_radius_km", km.coerceIn(10, 200))
+
fun autoCameras(context: Context): Boolean = bool(context, "auto_cameras", true)
fun setAutoCameras(context: Context, value: Boolean) = setBool(context, "auto_cameras", value)
/**
diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
index 7169f6f..2cb3935 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Voice.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
@@ -176,6 +176,15 @@ object Voice {
app?.getSystemService(AudioManager::class.java)?.abandonAudioFocusRequest(req)
}
+ /** Stops what's being said and drops what's queued (alerts muted); the engine stays ready. */
+ fun silence() = main.post {
+ queue.clear()
+ testText = null
+ tts?.stop()
+ speaking = null
+ releaseFocus()
+ }
+
fun shutdown() = main.post {
queue.clear()
speaking = null
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 46ac550..7df20be 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -26,7 +26,7 @@
<TextView
style="@style/SettingsLabel"
- android:text="Banner image - shown above the animated header in the styled themes (DedSec, Night Drive, Synthwave...). Pick any image on your phone (for example a logo you have); it's copied privately into the app." />
+ android:text="Banner image - shown above the animated header in the styled themes (Night Drive, Synthwave...); in DedSec and fsociety it replaces the poster. Pick any image on your phone (for example a logo you have); it&apos;s copied privately into the app." />
<LinearLayout
android:layout_width="match_parent"
@@ -167,6 +167,18 @@
android:layout_height="wrap_content"
android:text="Open SIM settings" />
+ <!-- Android 15+ phones can watch the signalling an app can't see (like EFF's Rayhunter). -->
+ <TextView
+ style="@style/SettingsLabel"
+ android:text="Android 15 and later (e.g. Pixel 8+) can also warn you themselves when a network asks for your SIM's identity or turns encryption off - signalling apps can't see. Turn on &quot;Network notifications&quot; under Security &amp; privacy &gt; More security &amp; privacy &gt; Cellular security." />
+
+ <Button
+ android:id="@+id/cellSecurityButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Open cellular security settings" />
+
<TextView style="@style/SettingsLabel" android:text="Watchlist presets (MAC prefixes)" />
<CheckBox
@@ -381,6 +393,22 @@
android:layout_height="wrap_content"
android:text="Show known cameras automatically: download them from OpenStreetMap for the map area you look at (the Overpass server sees that area, like map tiles)" />
+ <!-- Radius of "download the cameras around me" (also the setup wizard and the map menu). -->
+ <TextView
+ android:id="@+id/cameraRadiusText"
+ style="@style/SettingsLabel"
+ android:text="Download radius: 100 km" />
+
+ <com.google.android.material.slider.Slider
+ android:id="@+id/cameraRadiusSlider"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:contentDescription="Camera download radius in kilometres"
+ android:stepSize="10"
+ android:value="100"
+ android:valueFrom="10"
+ android:valueTo="200" />
+
<Button
android:id="@+id/prefetchCamerasButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
@@ -394,6 +422,20 @@
android:paddingTop="0dp"
android:textSize="12sp" />
+ <!-- Cameras silenced from the map (tap a camera > Ignore alerts). -->
+ <TextView
+ android:id="@+id/ignoredCamerasText"
+ style="@style/SettingsLabel"
+ android:paddingTop="4dp"
+ android:textSize="12sp" />
+
+ <Button
+ android:id="@+id/ignoredCamerasButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Alert for all ignored cameras again" />
+
<Button
android:id="@+id/deflockButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
diff --git a/app/src/test/java/com/rfsentinel/app/alpr/CameraAreaTest.kt b/app/src/test/java/com/rfsentinel/app/alpr/CameraAreaTest.kt
index 51619c8..2104622 100644
--- a/app/src/test/java/com/rfsentinel/app/alpr/CameraAreaTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/alpr/CameraAreaTest.kt
@@ -31,6 +31,17 @@ class CameraAreaTest {
assertTrue(CameraArea.needsDownload(areas, 10.3, -20.7, 11.9, -20.3, now = day, maxAgeMs = 7 * day))
}
+ @Test
+ fun largeRadiusIsSplitIntoSmallTiles() {
+ // 200 km at 45 degrees: about 3.6 x 5.1 degrees, more than the old 2x2 tiles could hold.
+ val tiles = CameraArea.tilesAround(45.0, 10.0, radiusKm = 200.0, maxTileDeg = 1.0)
+ assertTrue(tiles.size > 4)
+ tiles.forEach { assertTrue(it[2] - it[0] <= 1.0 + 1e-9 && it[3] - it[1] <= 1.0 + 1e-9) }
+ val areas = tiles.map { CameraArea(it[0], it[1], it[2], it[3], time = 0L) }
+ // The whole radius is covered: a box reaching 190 km north and east of the point.
+ assertFalse(CameraArea.needsDownload(areas, 45.0, 10.0, 45.0 + 190 / 111.0, 10.0 + 190 / (111.0 * Math.cos(Math.toRadians(45.0))), now = day, maxAgeMs = 7 * day))
+ }
+
@Test
fun expandDoublesWithinLimits() {
// A small zoomed-in box grows to the minimum span.
diff --git a/app/src/test/java/com/rfsentinel/app/data/TrackerMutesTest.kt b/app/src/test/java/com/rfsentinel/app/data/TrackerMutesTest.kt
index 91e2159..1b41076 100644
--- a/app/src/test/java/com/rfsentinel/app/data/TrackerMutesTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/data/TrackerMutesTest.kt
@@ -48,4 +48,29 @@ class TrackerMutesTest {
// Another kind of tracker.
assertFalse(s.onSeen("BB:00:00:00:00:04", "Tile tracker", -50, t0 + 70_000))
}
+
+ @Test
+ fun yourTagStillAroundKeepsItsMute() {
+ val s = TrackerMutes.Store()
+ s.mute("AA:00:00:00:00:01", airtag, -50, t0, follow = true)
+ // Your tag keeps advertising every few seconds for a minute...
+ var t = t0
+ while (t < t0 + 60_000) { t += 5_000; assertTrue(s.onSeen("AA:00:00:00:00:01", airtag, -50, t)) }
+ // ...so a stranger's tag of the same kind showing up now doesn't take its mute.
+ assertFalse(s.onSeen("BB:00:00:00:00:01", airtag, -52, t + 2_000))
+ assertTrue(s.isMuted("AA:00:00:00:00:01", t + 2_000))
+ }
+
+ @Test
+ fun linkedAddressInheritsRightAway() {
+ val s = TrackerMutes.Store()
+ s.mute("AA:00:00:00:00:01", airtag, -50, t0, follow = true)
+ // The scanner linked the new address to the old one (same advert fingerprint):
+ // carried over at once, even at a different strength.
+ assertTrue(s.onSeen("AA:00:00:00:00:02", airtag, -75, t0 + 3_000, linkedFrom = "AA:00:00:00:00:01"))
+ assertTrue(s.isMuted("AA:00:00:00:00:02", t0 + 4_000))
+ // A "today only" mute is never carried, linked or not.
+ s.mute("CC:00:00:00:00:01", airtag, -50, t0, follow = false)
+ assertFalse(s.onSeen("CC:00:00:00:00:02", airtag, -50, t0 + 3_000, linkedFrom = "CC:00:00:00:00:01"))
+ }
}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/CellAnalyzerTest.kt b/app/src/test/java/com/rfsentinel/app/detect/CellAnalyzerTest.kt
index c633dc5..cb75266 100644
--- a/app/src/test/java/com/rfsentinel/app/detect/CellAnalyzerTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/detect/CellAnalyzerTest.kt
@@ -9,61 +9,131 @@ import org.junit.Test
class CellAnalyzerTest {
// Synthetic operator codes: 999-99 style values are only used where a test code is intended.
- private fun cell(rat: Rat, reg: Boolean, area: Int = 100, id: Long = 1, mcc: String = "208", mnc: String = "01") =
- Cell(rat, reg, mcc, mnc, area, id, -80)
+ private fun cell(rat: Rat, reg: Boolean, area: Int = 100, id: Long = 1, mcc: String = "208", mnc: String = "01", dbm: Int = -80) =
+ Cell(rat, reg, mcc, mnc, area, id, dbm)
- private fun ctx(t: Long, stationary: Boolean? = null, sim: String = "20801", roaming: Boolean = false) =
- CellAnalyzer.Context(t, sim, roaming, stationary)
+ private fun ctx(t: Long, stationary: Boolean? = null, sim: String = "20801", roaming: Boolean = false, inCall: Boolean = false) =
+ CellAnalyzer.Context(t, sim, roaming, stationary, inCall)
- private fun modern(reg: Boolean = true, area: Int = 100, id: Long = 1) = cell(Rat.LTE, reg, area, id)
+ private fun modern(reg: Boolean = true, area: Int = 100, id: Long = 1, dbm: Int = -80) = cell(Rat.LTE, reg, area, id, dbm = dbm)
+
+ private fun List<CellAnalyzer.Anomaly>.of(prefix: String) = filter { it.key.startsWith(prefix) }
@Test
- fun testNetworkCodeIsStrong() {
+ fun testNetworkCodeIsStrongAndImmediate() {
val a = CellAnalyzer().analyze(listOf(cell(Rat.GSM, true, mcc = "001", mnc = "01")), ctx(0))
- assertEquals(85, a.single { it.key.startsWith("test-plmn") }.confidence)
+ assertEquals(85, a.of("test-plmn").single().confidence)
+ }
+
+ @Test
+ fun signsNeedTwoSnapshotsInARow() {
+ val cells = listOf(cell(Rat.LTE, true, mcc = "262", mnc = "01"))
+ val an = CellAnalyzer()
+ assertTrue(an.analyze(cells, ctx(0)).isEmpty()) // one glitchy reading: nothing yet
+ assertEquals(55, an.analyze(cells, ctx(15_000)).of("foreign").single().confidence)
}
@Test
- fun forcedDowngradeToGsmWithLteStillVisible() {
+ fun suddenSwitchToGsmWithStrongLteIsTheRedirectSign() {
val an = CellAnalyzer()
- assertTrue(an.analyze(listOf(modern(), modern(false, id = 2)), ctx(0)).isEmpty())
- val a = an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2)), ctx(30_000))
- assertEquals(65, a.single { it.key.startsWith("downgrade") }.confidence)
+ an.analyze(listOf(modern(), modern(false, id = 2)), ctx(0))
+ an.analyze(listOf(modern(), modern(false, id = 2)), ctx(15_000))
+ // Straight to 2G with a strong LTE cell still there; confirmed on the next snapshot.
+ assertTrue(an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2, dbm = -90)), ctx(30_000)).isEmpty())
+ val a = an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2, dbm = -90)), ctx(45_000))
+ assertEquals(70, a.of("downgrade").single().confidence)
}
@Test
- fun downgradeWithoutModernCoverageIsWeak() {
+ fun slowSlideToGsmWithoutCoverageStaysBelowTheAlertLevel() {
+ val an = CellAnalyzer()
+ an.analyze(listOf(modern(dbm = -118)), ctx(0))
+ an.analyze(listOf(cell(Rat.WCDMA, true, id = 5)), ctx(15_000))
+ an.analyze(listOf(cell(Rat.WCDMA, true, id = 5)), ctx(60_000))
+ an.analyze(listOf(cell(Rat.GSM, true, id = 9)), ctx(120_000))
+ val a = an.analyze(listOf(cell(Rat.GSM, true, id = 9)), ctx(135_000))
+ assertEquals(35, a.of("downgrade").single().confidence)
+ }
+
+ @Test
+ fun dropToGsmDuringACallIsIgnored() {
val an = CellAnalyzer()
an.analyze(listOf(modern()), ctx(0))
- val a = an.analyze(listOf(cell(Rat.GSM, true, id = 9)), ctx(30_000))
- assertEquals(40, a.single { it.key.startsWith("downgrade") }.confidence)
+ an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2)), ctx(15_000, inCall = true))
+ // Still on 2G just after the call, then again: the call explains it.
+ an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2)), ctx(30_000))
+ assertTrue(an.analyze(listOf(cell(Rat.GSM, true, id = 9), modern(false, id = 2)), ctx(45_000)).of("downgrade").isEmpty())
}
@Test
fun areaChangeOnlyCountsWhenStandingStill() {
val moving = CellAnalyzer()
moving.analyze(listOf(modern(area = 100)), ctx(0, stationary = false))
- assertTrue(moving.analyze(listOf(modern(area = 200)), ctx(15_000, stationary = false)).none { it.key.startsWith("area") })
+ moving.analyze(listOf(modern(area = 200)), ctx(15_000, stationary = false))
+ assertTrue(moving.analyze(listOf(modern(area = 200)), ctx(30_000, stationary = false)).of("area").isEmpty())
val still = CellAnalyzer()
still.analyze(listOf(modern(area = 100)), ctx(0, stationary = true))
- assertEquals(40, still.analyze(listOf(modern(area = 200)), ctx(15_000, stationary = true)).single { it.key.startsWith("area") }.confidence)
+ still.analyze(listOf(modern(area = 200)), ctx(15_000, stationary = true))
+ assertEquals(40, still.analyze(listOf(modern(area = 200)), ctx(30_000, stationary = true)).of("area").single().confidence)
+ }
+
+ @Test
+ fun areaFlippingBackAtABorderIsNormal() {
+ val an = CellAnalyzer()
+ an.analyze(listOf(modern(area = 200)), ctx(0, stationary = true))
+ an.analyze(listOf(modern(area = 100)), ctx(15_000, stationary = true))
+ an.analyze(listOf(modern(area = 200)), ctx(30_000, stationary = true))
+ assertTrue(an.analyze(listOf(modern(area = 200)), ctx(45_000, stationary = true)).of("area").isEmpty())
}
@Test
fun foreignCountryButNotSharedOrRoaming() {
val cells = listOf(cell(Rat.LTE, true, mcc = "262", mnc = "01"))
- assertEquals(55, CellAnalyzer().analyze(cells, ctx(0)).single { it.key.startsWith("foreign") }.confidence)
- assertTrue(CellAnalyzer().analyze(cells, ctx(0, roaming = true)).isEmpty())
+ CellAnalyzer().also { an -> an.analyze(cells, ctx(0, roaming = true)); assertTrue(an.analyze(cells, ctx(15_000, roaming = true)).isEmpty()) }
// US networks use several MCCs: 311 with a 310 SIM is normal.
- assertTrue(CellAnalyzer().analyze(listOf(cell(Rat.LTE, true, mcc = "311", mnc = "480")), ctx(0, sim = "310260")).isEmpty())
+ val us = listOf(cell(Rat.LTE, true, mcc = "311", mnc = "480"))
+ CellAnalyzer().also { an -> an.analyze(us, ctx(0, sim = "310260")); assertTrue(an.analyze(us, ctx(15_000, sim = "310260")).isEmpty()) }
}
@Test
fun newCellWithNoNeighboursAfterSeveral() {
val an = CellAnalyzer()
repeat(3) { i -> an.analyze(listOf(modern(), modern(false, id = 2), modern(false, id = 3)), ctx(i * 15_000L)) }
- val a = an.analyze(listOf(modern(id = 7)), ctx(60_000))
- assertEquals(35, a.single { it.key.startsWith("isolated") }.confidence)
+ an.analyze(listOf(modern(id = 7)), ctx(45_000))
+ assertEquals(35, an.analyze(listOf(modern(id = 7)), ctx(60_000)).of("isolated").single().confidence)
+ }
+
+ @Test
+ fun reservedAreaCodeIsAWeakSign() {
+ val an = CellAnalyzer()
+ an.analyze(listOf(modern(area = 0xFFFE)), ctx(0))
+ assertEquals(45, an.analyze(listOf(modern(area = 0xFFFE)), ctx(15_000)).of("reserved").single().confidence)
+ }
+
+ @Test
+ fun knownCellNumberInAnotherAreaThenAdopted() {
+ val known = LinkedHashMap<String, Int>()
+ CellAnalyzer(known).analyze(listOf(modern(area = 100, id = 42)), ctx(0)) // learned yesterday
+ val an = CellAnalyzer(known)
+ an.analyze(listOf(modern(area = 300, id = 42)), ctx(1_000_000))
+ assertEquals(50, an.analyze(listOf(modern(area = 300, id = 42)), ctx(1_015_000)).of("clone").single().confidence)
+ // A real re-plan keeps going: the new area is adopted and the sign stops.
+ var t = 1_030_000L
+ repeat(CellAnalyzer.ADOPT_AFTER) { an.analyze(listOf(modern(area = 300, id = 42)), ctx(t)); t += 15_000 }
+ assertEquals(300, known.values.single())
+ an.analyze(listOf(modern(area = 300, id = 42)), ctx(t))
+ assertTrue(an.analyze(listOf(modern(area = 300, id = 42)), ctx(t + 15_000)).of("clone").isEmpty())
+ }
+
+ @Test
+ fun severalSignsTogetherWeighMore() {
+ // A cloned cell number that also jumps area while you stand still.
+ val known = LinkedHashMap<String, Int>()
+ val an = CellAnalyzer(known)
+ an.analyze(listOf(modern(area = 100, id = 42)), ctx(0, stationary = true))
+ an.analyze(listOf(modern(area = 300, id = 42)), ctx(15_000, stationary = true))
+ val a = an.analyze(listOf(modern(area = 300, id = 42)), ctx(30_000, stationary = true))
+ assertEquals(65, a.of("combined").single().confidence)
}
}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt
index 7fe8929..85df314 100644
--- a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt
@@ -187,6 +187,27 @@ class IdentificationTest {
assertTrue(DeviceRegistry.get("5A:11:22:33:44:02")!!.facts.any { it.first == "Previous address" })
}
+ @Test
+ fun rotatedAddressKeepsFollowTracking() {
+ DeviceRegistry.startSession(0)
+ val id = DeviceIntel.Identity("x", emptyList())
+ val axon = Hit(Category.BODY_CAM, "Axon / TASER equipment", 60, "Company ID 0x034D", "SIG")
+ // Heard for 8 minutes along a 1.2 km drive under the first address...
+ for (i in 0..8) {
+ val t = 1_000L + i * 60_000L
+ DeviceRegistry.report(axonAdvert("5A:11:22:33:55:01", t), listOf(axon), id, null, null,
+ DeviceRegistry.GeoSample(t, 45.0 + i * 0.0015, 10.0), t)
+ }
+ // ...then its address changes; 3 more minutes under the new one.
+ for (i in 0..3) {
+ val t = 490_000L + i * 60_000L
+ DeviceRegistry.report(axonAdvert("5A:11:22:33:55:02", t), emptyList(), id, null, null,
+ DeviceRegistry.GeoSample(t, 45.0135 + i * 0.0015, 10.0), t)
+ }
+ // 11 minutes in all: the new address counts the time and distance before the change.
+ assertTrue(DeviceRegistry.checkFollowing("5A:11:22:33:55:02", 10 * 60_000L, 800.0))
+ }
+
@Test
fun ambiguousOrUninformativeAdvertsAreNotLinked() {
DeviceRegistry.startSession(0)