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.

Fix 16 bugs found in code review (v2.8.2)

CIS-C0031f7ba0e1e8
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 940c52a..e87c912 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 = 15
-val appVersionName = "2.8.1"
+val appVersionCode = 16
+val appVersionName = "2.8.2"
// Release signing credentials live in keystore.properties (git-ignored).
// Without that file, release builds are produced unsigned.
diff --git a/app/src/main/java/com/rfsentinel/app/detect/EvidenceFusion.kt b/app/src/main/java/com/rfsentinel/app/detect/EvidenceFusion.kt
index 0ee8711..a3b8532 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/EvidenceFusion.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/EvidenceFusion.kt
@@ -6,8 +6,8 @@ import kotlin.math.roundToInt
* Combines several matches on one device into a single, better-calibrated
* score. Each rule reports a confidence on its own; when two *different* rules
* of the same category agree (for example a Zebra service UUID plus a watchlisted
- * address, or a vendor block plus a patrol-vehicle cluster), the device is more
- * likely what they both claim.
+ * address), the device is more likely what they both claim. The patrol-vehicle
+ * hit is excluded: it is derived from the device's own matches.
*
* Uses noisy-OR with every supporting hit discounted by half, because rules
* often look at related evidence (same vendor, same packet) and are not truly
@@ -23,8 +23,12 @@ object EvidenceFusion {
fun fuse(hits: List<Hit>): List<Hit> {
if (hits.size < 2) return hits
val sorted = hits.sortedByDescending { it.confidence }
- val top = sorted.first()
- val support = sorted.drop(1)
+ // The patrol-vehicle hit is itself derived from this device's own matches (they give
+ // it its role), so it neither corroborates them nor is corroborated by them: fusing
+ // the two would count the same evidence twice.
+ val top = sorted.firstOrNull { it.source != PatrolCluster.SOURCE } ?: return sorted
+ val support = sorted
+ .filter { it !== top && it.source != PatrolCluster.SOURCE }
.filter { it.category == top.category && it.confidence >= MIN_SUPPORT && it.label != top.label }
.distinctBy { it.label }
if (support.isEmpty() || top.confidence >= FUSED_CAP) return sorted
@@ -40,6 +44,6 @@ object EvidenceFusion {
support.joinToString("; ") { "${it.label} (${it.confidence}%)" } +
" - combined ${top.confidence}% -> $fused%"
)
- return listOf(combined) + sorted.drop(1)
+ return (sorted.map { if (it === top) combined else it }).sortedByDescending { it.confidence }
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt
index acddc06..6c49bb7 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt
@@ -40,11 +40,11 @@ object PatrolCluster {
private val ROLE_BY_VENDOR = listOf(
Regex("axon|taser", RegexOption.IGNORE_CASE) to "Axon / TASER gear",
- Regex("motorola solutions|harris corp|l3harris|kenwood", RegexOption.IGNORE_CASE) to "two-way radio",
+ Regex("motorola solutions|harris corp|l3harris", RegexOption.IGNORE_CASE) to "two-way radio",
Regex("cradlepoint|sierra wireless", RegexOption.IGNORE_CASE) to "vehicle cellular router",
Regex("zebra|ruggedjet|pocketjet", RegexOption.IGNORE_CASE) to "mobile printer",
- Regex("cyberkar|havis", RegexOption.IGNORE_CASE) to "in-car computer / console",
- Regex("getac|panasonic connect", RegexOption.IGNORE_CASE) to "rugged laptop / body cam",
+ Regex("cyberkar", RegexOption.IGNORE_CASE) to "in-car computer / console",
+ Regex("getac", RegexOption.IGNORE_CASE) to "rugged laptop / body cam",
Regex("genetec", RegexOption.IGNORE_CASE) to "plate reader",
Regex("utility,? inc|digital ally|watchguard|i-pro", RegexOption.IGNORE_CASE) to "police camera"
)
@@ -75,12 +75,18 @@ object PatrolCluster {
for (i in live.indices) for (j in i + 1 until live.size) {
val a = live[i]; val b = live[j]
if (a.role == b.role) continue
- val r = correlation(a.samples, b.samples, now)
- val together = (r != null && r >= MIN_CORRELATION) ||
- (r == null && kotlin.math.abs(a.firstSeen - b.firstSeen) <= ARRIVAL_WINDOW_MS)
+ val m = motion(a.samples, b.samples, now)
+ val together = when (m) {
+ is Motion.Moving -> m.r >= MIN_CORRELATION
+ // Both parked: signals can't correlate, so arriving together is the only clue.
+ Motion.BothFlat -> kotlin.math.abs(a.firstSeen - b.firstSeen) <= ARRIVAL_WINDOW_MS
+ // One moves while the other sits still: not the same vehicle. Too little
+ // overlap: no evidence either way, so don't group.
+ Motion.OneFlat, Motion.TooShort -> false
+ }
if (together) {
parent[find(i)] = find(j)
- if (r != null) { correlatedPairs += i; correlatedPairs += j }
+ if (m is Motion.Moving) { correlatedPairs += i; correlatedPairs += j }
}
}
return live.indices.groupBy { find(it) }.values
@@ -104,23 +110,36 @@ object PatrolCluster {
)
}
+ /** How two devices' signals behave over the same seconds. */
+ sealed interface Motion {
+ /** Both signals vary: [r] is their Pearson correlation. */
+ data class Moving(val r: Double) : Motion
+ /** Both signals are flat: both parked relative to you. */
+ data object BothFlat : Motion
+ /** One varies while the other is flat: they aren't moving together. */
+ data object OneFlat : Motion
+ /** Fewer than [MIN_OVERLAP] shared seconds. */
+ data object TooShort : Motion
+ }
+
/**
- * Pearson correlation of two RSSI series over the last [WINDOW_MS], aligned
- * by second. Null when there's too little overlap or both signals are flat
- * (parked next to each other and to you: correlation says nothing then).
+ * Compares two RSSI series over the last [WINDOW_MS], aligned by second.
+ * A signal whose standard deviation is under [MIN_SPREAD_DB] counts as flat.
*/
- fun correlation(a: List<Pair<Long, Int>>, b: List<Pair<Long, Int>>, now: Long): Double? {
+ fun motion(a: List<Pair<Long, Int>>, b: List<Pair<Long, Int>>, now: Long): Motion {
fun bucket(s: List<Pair<Long, Int>>) =
s.filter { now - it.first <= WINDOW_MS }.associate { it.first / 1000 to it.second.toDouble() }
val ba = bucket(a); val bb = bucket(b)
val keys = ba.keys.intersect(bb.keys)
- if (keys.size < MIN_OVERLAP) return null
+ if (keys.size < MIN_OVERLAP) return Motion.TooShort
val xs = keys.map { ba.getValue(it) }; val ys = keys.map { bb.getValue(it) }
val mx = xs.average(); val my = ys.average()
val sx = sqrt(xs.sumOf { (it - mx) * (it - mx) } / xs.size)
val sy = sqrt(ys.sumOf { (it - my) * (it - my) } / ys.size)
- if (sx < MIN_SPREAD_DB || sy < MIN_SPREAD_DB) return null
+ val flatX = sx < MIN_SPREAD_DB; val flatY = sy < MIN_SPREAD_DB
+ if (flatX && flatY) return Motion.BothFlat
+ if (flatX || flatY) return Motion.OneFlat
val cov = xs.indices.sumOf { (xs[it] - mx) * (ys[it] - my) } / xs.size
- return cov / (sx * sy)
+ return Motion.Moving(cov / (sx * sy))
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt b/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt
index af791b1..1ca4487 100644
--- a/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/AdvertFactory.kt
@@ -84,7 +84,10 @@ object AdvertFactory {
rssi = r.level,
name = ssid,
addressType = AddressType.ofWifi(mac),
- wifi = Advert.WifiInfo(r.frequency, r.capabilities.orEmpty(), standard, ies)
+ wifi = Advert.WifiInfo(r.frequency, r.capabilities.orEmpty(), standard, ies),
+ // When the AP was actually heard, not when the cached result was read.
+ timestamp = System.currentTimeMillis() -
+ ((android.os.SystemClock.elapsedRealtime() * 1000 - r.timestamp) / 1000).coerceAtLeast(0)
)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
index 6d44455..2c2ae8b 100644
--- a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
@@ -30,7 +30,9 @@ class BleScanEngine(
private val onResult: (ScanResult) -> Unit
) {
private var scanner: BluetoothLeScanner? = null
+ /** Tracked separately: either scan can fail on its own, and both must always be stopped. */
@Volatile private var scanning = false
+ @Volatile private var filteredScanning = false
private val callback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) = onResult(result)
@@ -46,6 +48,7 @@ class BleScanEngine(
override fun onBatchScanResults(results: MutableList<ScanResult>) = results.forEach(onResult)
override fun onScanFailed(errorCode: Int) {
Log.w(TAG, "Filtered BLE scan failed: $errorCode")
+ filteredScanning = false
}
}
@@ -56,6 +59,8 @@ class BleScanEngine(
@SuppressLint("MissingPermission")
fun start(scanMode: Int, watchedMacs: List<String>) {
if (scanning) return
+ // A previous unfiltered scan may have failed on its own while the filtered one kept running.
+ stop()
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager ?: return
val adapter = manager.adapter ?: return
if (!adapter.isEnabled) return
@@ -80,6 +85,7 @@ class BleScanEngine(
}
try {
scanner?.startScan(buildFilters(watchedMacs), settings(ScanSettings.SCAN_MODE_BALANCED), filteredCallback)
+ filteredScanning = true
} catch (e: Exception) {
Log.w(TAG, "Filtered scan unavailable", e)
}
@@ -87,14 +93,16 @@ class BleScanEngine(
@SuppressLint("MissingPermission")
fun stop() {
- if (!scanning) return
- try {
- scanner?.stopScan(callback)
- scanner?.stopScan(filteredCallback)
- } catch (e: Exception) {
- // Adapter already turned off (IllegalStateException) or permission revoked.
+ if (scanning) {
+ try { scanner?.stopScan(callback) } catch (e: Exception) {
+ // Adapter already turned off (IllegalStateException) or permission revoked.
+ }
+ }
+ if (filteredScanning) {
+ try { scanner?.stopScan(filteredCallback) } catch (e: Exception) {}
}
scanning = false
+ filteredScanning = false
}
fun isScanning() = scanning
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 e89cc79..4f9b0b1 100644
--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
@@ -1,6 +1,7 @@
package com.rfsentinel.app.service
import com.rfsentinel.app.data.KnownDeviceEntity
+import com.rfsentinel.app.data.WhitelistCache
import com.rfsentinel.app.detect.AddressType
import com.rfsentinel.app.detect.Advert
import com.rfsentinel.app.detect.AdvertFingerprint
@@ -32,6 +33,8 @@ object DeviceRegistry {
private const val HISTORY_MIN_SPACING_MS = 1000L
private const val LOCATION_SPACING_MS = 45_000L
private const val ROTATION_SILENCE_MS = 1_500L
+ /** How long a device keeps a match after the evidence was last observed. */
+ const val HIT_HOLD_MS = 120_000L
private const val ROTATION_WINDOW_MS = 30_000L
data class Sample(val time: Long, val rssi: Int)
@@ -98,6 +101,9 @@ object DeviceRegistry {
/** The address this device most likely used before its address rotated. */
var linkedFrom: String? = null
var inherited: List<Hit> = emptyList()
+ /** The device's own strongest recent match, held for [HIT_HOLD_MS] after it was last seen. */
+ var heldHit: Hit? = null
+ var heldUntil = 0L
}
private val tracks = ConcurrentHashMap<String, Track>()
@@ -134,8 +140,7 @@ object DeviceRegistry {
vendor?.let { t.vendor = it }
// Keep the richest identity: a later advert may lack the fields an earlier one had.
if (identity.facts.size >= t.identity.facts.size || t.identity.type == "Device") t.identity = identity
- // Keep the strongest evidence seen this session (payload tags can be intermittent).
- if (hits.isNotEmpty() && (t.hits.isEmpty() || hits.first().confidence >= t.hits.first().confidence)) t.hits = hits
+ t.hits = mergeHits(t, hits, now)
remoteId?.let { t.remoteId = it }
t.rssi = a.rssi
if (location != null && (a.rssi >= t.bestRssi || t.bestPosition == null)) t.bestPosition = location
@@ -155,6 +160,25 @@ object DeviceRegistry {
return isFirst
}
+ /**
+ * Current matches plus the device's own strongest recent one. Payload tags
+ * can be intermittent (not every packet carries them), so a match is held
+ * for [HIT_HOLD_MS] after it was last observed instead of flickering, then
+ * fades. The patrol-vehicle hit is never held: it is recomputed from the live
+ * group every classification, so it disappears when the group breaks up.
+ */
+ private fun mergeHits(t: Track, hits: List<Hit>, now: Long): List<Hit> {
+ val own = hits.firstOrNull { it.source != PatrolCluster.SOURCE }
+ if (own != null) {
+ val held = t.heldHit
+ if (held == null || now > t.heldUntil || own.confidence >= held.confidence) t.heldHit = own
+ if (own.label == t.heldHit?.label) t.heldUntil = now + HIT_HOLD_MS
+ }
+ val held = t.heldHit?.takeIf { now <= t.heldUntil }
+ val merged = if (held != null && hits.none { it.label == held.label }) hits + held else hits
+ return merged.sortedByDescending { it.confidence }
+ }
+
/**
* Address-rotation linking: if exactly one device with the same advert
* fingerprint went silent shortly before this new address appeared, treat
@@ -197,7 +221,8 @@ object DeviceRegistry {
fun clusterHit(mac: String, now: Long = System.currentTimeMillis()): Hit? {
var (time, groups) = groupCache
if (now - time >= 2_000L) {
- val members = tracks.values.mapNotNull { t ->
+ // Devices the user trusts (whitelisted) never make others look like a patrol car.
+ val members = tracks.values.filterNot { WhitelistCache.contains(it.mac) }.mapNotNull { t ->
synchronized(t) {
t.role?.let { role ->
PatrolCluster.Member(t.mac, role, t.firstSeen, t.lastSeen, t.history.map { it.time to it.rssi })
@@ -287,7 +312,7 @@ object DeviceRegistry {
*/
private fun sameApFacts(t: Track): List<Pair<String, String>> {
val siblings = tracks.values.filter { o ->
- o !== t && Advert.Source.WIFI in o.sources && WifiFingerprint.sameAccessPoint(t.mac, o.mac)
+ o !== t && WifiFingerprint.sameAccessPoint(t.mac, o.mac) && synchronized(o) { Advert.Source.WIFI in o.sources }
}.map { o -> synchronized(o) { Triple(o.mac, o.name, o.identity.type) } }
if (siblings.isEmpty()) return emptyList()
val out = mutableListOf<Pair<String, String>>()
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 08f66eb..84f4db6 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -15,6 +15,8 @@ import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
+import android.os.Handler
+import android.os.HandlerThread
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
@@ -74,6 +76,8 @@ class ScanForegroundService : Service() {
private const val CLASSIFY_INTERVAL_MS = 2_000L
private const val STATUS_INTERVAL_MS = 10_000L
+ /** Each periodic job holds a short wake lock only while it runs. */
+ private const val WAKE_SLICE_MS = 10_000L
private const val HISTORY_FLUSH_MS = 60_000L
/** True while an instance is alive in this process. Source of truth for the UI. */
@@ -95,6 +99,14 @@ class ScanForegroundService : Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private var wakeLock: PowerManager.WakeLock? = null
+ /**
+ * Scan results arrive on the main thread (BLE callbacks, the WiFi broadcast).
+ * Detection runs here instead, one result at a time in arrival order, so a
+ * busy street never stalls the UI.
+ */
+ private lateinit var pipelineThread: HandlerThread
+ private lateinit var pipeline: Handler
+
private lateinit var bleEngine: BleScanEngine
private lateinit var wifiEngine: WifiScanEngine
@@ -130,8 +142,12 @@ class ScanForegroundService : Service() {
NotificationHelper.createChannels(this)
OuiWatchlist.load(this)
- bleEngine = BleScanEngine(this) { r -> AdvertFactory.fromBle(r)?.let(::process) }
- wifiEngine = WifiScanEngine(this) { r -> AdvertFactory.fromWifi(r)?.let(::process) }
+ pipelineThread = HandlerThread("rf-pipeline").apply { start() }
+ pipeline = Handler(pipelineThread.looper)
+ bleEngine = BleScanEngine(this) { r -> pipeline.post { AdvertFactory.fromBle(r)?.let(::process) } }
+ wifiEngine = WifiScanEngine(this) { results ->
+ pipeline.post { results.forEach { r -> AdvertFactory.fromWifi(r)?.let(::process) } }
+ }
val pm = getSystemService(POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RFSentinel::ScanWakeLock")
@@ -152,9 +168,6 @@ class ScanForegroundService : Service() {
return START_NOT_STICKY
}
- // Safety-capped wake lock; renewed implicitly each time the service restarts.
- wakeLock?.let { if (!it.isHeld) it.acquire(12 * 60 * 60 * 1000L) }
-
if (!btStateReceiverRegistered) {
ContextCompat.registerReceiver(
this, btStateReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED),
@@ -243,6 +256,7 @@ class ScanForegroundService : Service() {
wifiPollJob?.cancel()
wifiPollJob = serviceScope.launch {
while (isActive) {
+ holdAwake()
wifiEngine.requestScan()
delay(Prefs.scanIntervalMs(this@ScanForegroundService))
}
@@ -402,15 +416,34 @@ class ScanForegroundService : Service() {
DeviceRegistry.setKnown(mac, known)
}
- /** Merges this session's sightings into known_devices (throttled, batched). */
- private suspend fun flushHistory() {
+ /**
+ * Keeps the CPU awake for one short slice of periodic work (a WiFi scan
+ * request, a status/trace/history update). The lock is never held between
+ * slices, so the phone can still deep-sleep; BLE results wake it by themselves.
+ */
+ private fun holdAwake() {
+ runCatching { wakeLock?.acquire(WAKE_SLICE_MS) }
+ }
+
+ /** Sightings to merge into known_devices, taken synchronously from memory. */
+ private class HistoryBatch(val seen: List<DeviceRegistry.Snapshot>, val sessionStart: Long)
+
+ private fun takeHistory(): HistoryBatch? {
val since = lastHistoryFlush
lastHistoryFlush = System.currentTimeMillis()
val seen = DeviceRegistry.summaries(since)
- if (seen.isEmpty()) return
+ return if (seen.isEmpty()) null else HistoryBatch(seen, DeviceRegistry.sessionStart)
+ }
+
+ /** Merges this session's sightings into known_devices (throttled, batched). */
+ private suspend fun flushHistory() {
+ takeHistory()?.let { writeHistory(it) }
+ }
+
+ private suspend fun writeHistory(batch: HistoryBatch) {
val dao = AppDatabase.getInstance(this).knownDeviceDao()
- val sessionStart = DeviceRegistry.sessionStart
- seen.chunked(400).forEach { chunk ->
+ val sessionStart = batch.sessionStart
+ batch.seen.chunked(400).forEach { chunk ->
val existing = dao.getAll(chunk.map { it.mac }).associateBy { it.mac }
dao.upsertAll(chunk.map { s ->
val e = existing[s.mac]
@@ -444,6 +477,7 @@ class ScanForegroundService : Service() {
housekeepingJob = serviceScope.launch {
while (isActive) {
delay(STATUS_INTERVAL_MS)
+ holdAwake()
val devices = DeviceRegistry.snapshot()
val flagged = devices.count { d -> d.best != null && !WhitelistCache.contains(d.mac) }
val text = "${devices.size} device${if (devices.size == 1) "" else "s"} nearby" +
@@ -481,12 +515,15 @@ class ScanForegroundService : Service() {
locationListening = false
}
serviceScope.cancel()
- // Final history flush outlives the service scope.
+ pipelineThread.quitSafely()
+ // Take the final history and trace synchronously, so a scan restarted right
+ // away (new session, new trace) can't clear or reuse them; write them after.
+ val history = takeHistory()
+ val trip = TripRecorder.detach() // stopping the scanner ends the trace recording too
val app = application as RFSentinelApp
app.appScope.launch {
- runCatching { flushHistory() }
- // Stopping the scanner ends the trace recording too.
- runCatching { TripRecorder.stop(app) }
+ history?.let { runCatching { writeHistory(it) }.onFailure { e -> Log.w(TAG, "History flush failed", e) } }
+ trip?.let { runCatching { TripRecorder.persist(app, it) }.onFailure { e -> Log.w(TAG, "Trace save failed", e) } }
}
wakeLock?.let { if (it.isHeld) it.release() }
isRunning = false
diff --git a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt
index 63e6c38..67553e7 100644
--- a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt
@@ -64,15 +64,60 @@ object TripRecorder {
return id
}
+ /** What's left to write for a trip that was just stopped (see [detach]). */
+ class Final internal constructor(
+ val id: Long,
+ val points: List<TripPointEntity>,
+ val devices: List<TripDeviceEntity>,
+ val distanceM: Double,
+ val totalPoints: Int,
+ val deviceCount: Int,
+ val flaggedCount: Int
+ )
+
+ /**
+ * Stops recording immediately and hands back everything not yet written.
+ * Synchronous, so a scan restarted right after sees no active trip and can
+ * start a new one; write the result with [persist].
+ */
+ fun detach(): Final? = synchronized(this) {
+ val id = activeTripId ?: return null
+ val changed = takeDirty()
+ Final(
+ id, pendingPoints.toList(), changed, distanceM, points.size,
+ devices.size, devices.values.count { it.flagged }
+ ).also {
+ pendingPoints.clear()
+ activeTripId = null
+ }
+ }
+
+ /** Writes a detached trip and closes it; deletes it if nothing was recorded. */
+ suspend fun persist(context: Context, f: Final) {
+ val dao = AppDatabase.getInstance(context).tripDao()
+ if (f.points.isNotEmpty()) dao.insertPoints(f.points)
+ if (f.devices.isNotEmpty()) f.devices.chunked(300).forEach { dao.upsertDevices(it) }
+ dao.updateStats(f.id, System.currentTimeMillis(), f.distanceM, f.totalPoints, f.deviceCount, f.flaggedCount)
+ // An empty trip (no GPS fix at all) isn't worth keeping.
+ val trip = dao.get(f.id)
+ if (trip != null && trip.pointCount == 0 && trip.deviceCount == 0) dao.delete(f.id)
+ }
+
/** Stops recording and writes the final state. */
suspend fun stop(context: Context) {
- val id = activeTripId ?: return
- flush(context, closing = true)
- synchronized(this) { activeTripId = null }
- // An empty trip (no GPS fix at all) isn't worth keeping.
- val dao = AppDatabase.getInstance(context).tripDao()
- val trip = dao.get(id)
- if (trip != null && trip.pointCount == 0 && trip.deviceCount == 0) dao.delete(id)
+ detach()?.let { persist(context, it) }
+ }
+
+ /**
+ * Takes the changed devices. Clearing only what was read (not the whole set)
+ * means a device marked dirty by a scanner thread meanwhile stays dirty for
+ * the next flush instead of being lost; its state is read after removal, so
+ * it's never older than what's recorded.
+ */
+ private fun takeDirty(): List<TripDeviceEntity> {
+ val keys = dirty.toList()
+ dirty.removeAll(keys.toSet())
+ return keys.mapNotNull { devices[it] }
}
/** Called for every location fix while recording. */
@@ -131,7 +176,7 @@ object TripRecorder {
val totalPoints: Int
synchronized(this) {
newPoints = pendingPoints.toList(); pendingPoints.clear()
- changed = dirty.mapNotNull { devices[it] }; dirty.clear()
+ changed = takeDirty()
totalPoints = points.size
}
val dao = AppDatabase.getInstance(context).tripDao()
diff --git a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
index 0ff34d3..cf52600 100644
--- a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
@@ -6,6 +6,7 @@ import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
+import android.os.SystemClock
import androidx.core.content.ContextCompat
/**
@@ -20,7 +21,7 @@ import androidx.core.content.ContextCompat
*/
class WifiScanEngine(
private val context: Context,
- private val onResult: (ScanResult) -> Unit
+ private val onResults: (List<ScanResult>) -> Unit
) {
private val wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
@@ -29,15 +30,25 @@ class WifiScanEngine(
private val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
// Even when OUR request was throttled (EXTRA_RESULTS_UPDATED = false) the
- // cached results may come from another app's fresh scan, so use them either way.
+ // cached results may come from another app's fresh scan, so use them - but
+ // only entries actually heard recently. The cache also holds access points
+ // from minutes ago; replaying those as "seen now" would place them at your
+ // current position and could fake a device following you.
try {
- wifiManager.scanResults.forEach(onResult)
+ val nowUs = SystemClock.elapsedRealtime() * 1000
+ val fresh = wifiManager.scanResults.filter { nowUs - it.timestamp <= MAX_RESULT_AGE_US }
+ if (fresh.isNotEmpty()) onResults(fresh)
} catch (e: SecurityException) {
// Missing location permission - caller should have requested it already.
}
}
}
+ companion object {
+ /** Cached scan results older than this are ignored (ScanResult.timestamp is µs since boot). */
+ const val MAX_RESULT_AGE_US = 30_000_000L
+ }
+
fun start() {
if (registered) return
val filter = IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
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 cd83f0a..934e3d0 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -116,6 +116,9 @@ object AlertPlayer {
vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1))
}
+ /** Announcements raised while the speech engine is still starting. */
+ private val pending = mutableListOf<Pair<String, AudioAttributes>>()
+
@Synchronized
private fun speak(context: Context, text: String, attrs: AudioAttributes) {
val engine = tts
@@ -124,16 +127,32 @@ object AlertPlayer {
engine.speak(text, TextToSpeech.QUEUE_ADD, null, "rf-${System.nanoTime()}")
return
}
+ // Still starting: queue it (bounded) so it's spoken once ready.
+ if (pending.size < 5) pending += text to attrs
if (engine == null) {
- tts = TextToSpeech(context) { status ->
- ttsReady = status == TextToSpeech.SUCCESS
- if (ttsReady) {
- tts?.language = Locale.getDefault()
- tts?.setAudioAttributes(attrs)
- tts?.speak(text, TextToSpeech.QUEUE_ADD, null, "rf-first")
- }
- }
+ tts = TextToSpeech(context) { status -> onTtsInit(status) }
+ }
+ }
+
+ @Synchronized
+ private fun onTtsInit(status: Int) {
+ val engine = tts ?: return
+ if (status != TextToSpeech.SUCCESS) {
+ // Engine missing or still updating: drop it so the next alert tries again,
+ // instead of staying silent until the app restarts.
+ runCatching { engine.shutdown() }
+ tts = null
+ ttsReady = false
+ pending.clear()
+ return
+ }
+ ttsReady = true
+ engine.language = Locale.getDefault()
+ pending.forEach { (text, attrs) ->
+ engine.setAudioAttributes(attrs)
+ engine.speak(text, TextToSpeech.QUEUE_ADD, null, "rf-${System.nanoTime()}")
}
+ pending.clear()
}
@Synchronized
@@ -141,5 +160,6 @@ object AlertPlayer {
tts?.shutdown()
tts = null
ttsReady = false
+ pending.clear()
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
index 1bb267a..0188aa3 100644
--- a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
@@ -228,7 +228,6 @@ object DeviceExport {
fun pretty(el: com.google.gson.JsonElement): String = gson.toJson(el)
- private fun q(s: String?): String = if (s == null) "" else "\"" + s.replace("\"", "\"\"") + "\""
- private fun x(s: String): String =
- s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
+ private fun q(s: String?): String = ExportText.csv(s)
+ private fun x(s: String): String = ExportText.xml(s)
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/ExportText.kt b/app/src/main/java/com/rfsentinel/app/util/ExportText.kt
new file mode 100644
index 0000000..d1c360d
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/util/ExportText.kt
@@ -0,0 +1,52 @@
+package com.rfsentinel.app.util
+
+/**
+ * Safe text for exported files. Device names and WiFi SSIDs are chosen by
+ * whoever owns the device, so exports must treat them as hostile input.
+ */
+object ExportText {
+
+ /** Characters that make a spreadsheet treat a cell as a formula (CSV/formula injection). */
+ private val FORMULA_START = charArrayOf('=', '+', '-', '@', '\t', '\r')
+
+ /**
+ * A quoted CSV field (RFC 4180). A value that a spreadsheet would run as a
+ * formula gets a leading apostrophe, so it is shown as text instead
+ * (OWASP CSV-injection guidance).
+ */
+ fun csv(s: String?): String {
+ if (s == null) return ""
+ val safe = if (s.isNotEmpty() && s[0] in FORMULA_START) "'$s" else s
+ return "\"" + safe.replace("\"", "\"\"") + "\""
+ }
+
+ /**
+ * XML 1.0 text or attribute value: escapes markup characters and drops the
+ * characters XML 1.0 forbids even when escaped (most control characters,
+ * U+FFFE/U+FFFF and unpaired surrogates), which would make the file unparseable.
+ */
+ fun xml(s: String?): String {
+ if (s.isNullOrEmpty()) return ""
+ val sb = StringBuilder(s.length + 16)
+ var i = 0
+ while (i < s.length) {
+ val c = s[i]
+ when {
+ Character.isHighSurrogate(c) && i + 1 < s.length && Character.isLowSurrogate(s[i + 1]) -> {
+ sb.append(c).append(s[i + 1]); i++
+ }
+ Character.isSurrogate(c) -> Unit // unpaired: not allowed
+ c == '&' -> sb.append("&amp;")
+ c == '<' -> sb.append("&lt;")
+ c == '>' -> sb.append("&gt;")
+ c == '"' -> sb.append("&quot;")
+ c == '\'' -> sb.append("&apos;")
+ c == '\t' || c == '\n' || c == '\r' -> sb.append(c)
+ c < ' ' || c == '￾' || c == '￿' -> Unit
+ else -> sb.append(c)
+ }
+ i++
+ }
+ return sb.toString()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
index ba78e24..2d3e45f 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
@@ -241,8 +241,7 @@ object Exporter {
return sb.toString()
}
- /** RFC 4180: quote free text and double any embedded quotes. */
- private fun q(s: String?): String = if (s == null) "" else "\"" + s.replace("\"", "\"\"") + "\""
+ private fun q(s: String?): String = ExportText.csv(s)
fun gpx(rows: List<DetectionEntity>): String {
val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
@@ -277,8 +276,7 @@ object Exporter {
return sb.toString()
}
- private fun x(s: String): String =
- s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
+ private fun x(s: String): String = ExportText.xml(s)
internal fun stamp() = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
diff --git a/app/src/main/java/com/rfsentinel/app/util/TripExport.kt b/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
index 9cfbf0c..1cb28d3 100644
--- a/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
@@ -20,9 +20,8 @@ object TripExport {
private fun iso(t: Long): String =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(t))
private fun local(t: Long): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(t))
- private fun x(s: String?): String = (s ?: "").replace("&", "&amp;").replace("<", "&lt;")
- .replace(">", "&gt;").replace("\"", "&quot;")
- private fun q(s: String?): String = if (s == null) "" else "\"" + s.replace("\"", "\"\"") + "\""
+ private fun x(s: String?): String = ExportText.xml(s)
+ private fun q(s: String?): String = ExportText.csv(s)
private fun describe(d: TripDeviceEntity) = buildString {
append(d.mac)
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 2a28749..46b1613 100644
--- a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt
@@ -45,6 +45,18 @@ class IdentificationTest {
assertEquals(EvidenceFusion.FUSED_CAP, many.first().confidence)
}
+ @Test
+ fun clusterHitIsNeverFusedWithTheDevicesOwnMatch() {
+ // A 2-role group scores 48 (weak). The radio's own 45 is what gave it its role,
+ // so fusing the two would double-count and push it past the 50% alert line.
+ val fused = EvidenceFusion.fuse(listOf(
+ hit(Category.PUBLIC_SAFETY, "Motorola Solutions equipment", 45),
+ hit(Category.PUBLIC_SAFETY, "Two-way radio in a possible police vehicle", 48, PatrolCluster.SOURCE)
+ ))
+ assertEquals(48, fused.first().confidence)
+ assertTrue(fused.all { it.confidence < 50 })
+ }
+
// ---- Patrol-vehicle clusters ----------------------------------------------
private fun wave(start: Long, phase: Double = 0.0, offset: Int = -70) =
@@ -93,6 +105,40 @@ class IdentificationTest {
assertTrue(PatrolCluster.groups(stale, now).isEmpty())
}
+ @Test
+ fun aMovingDeviceAndAParkedOneAreNotAVehicle() {
+ val now = 60_000L
+ val parked = (0 until 60).map { it * 1000L to -60 }
+ val members = listOf(
+ PatrolCluster.Member("AA:00:00:00:00:01", "two-way radio", 0, now, wave(0)),
+ PatrolCluster.Member("AA:00:00:00:00:02", "mobile printer", 5_000, now, parked)
+ )
+ assertTrue(PatrolCluster.groups(members, now).isEmpty())
+ assertEquals(PatrolCluster.Motion.OneFlat, PatrolCluster.motion(wave(0), parked, now))
+ }
+
+ @Test
+ fun consumerBrandsHaveNoPatrolRole() {
+ assertNull(PatrolCluster.roleOf(emptyList(), "JVCKENWOOD Corporation", "KENWOOD CAR"))
+ assertNull(PatrolCluster.roleOf(emptyList(), "Panasonic Connect Co., Ltd.", null))
+ }
+
+ @Test
+ fun matchesFadeAfterTheEvidenceStops() {
+ DeviceRegistry.startSession(0)
+ val mac = "00:25:DF:00:00:42"
+ val a = { t: Long -> Advert(mac, Advert.Source.BLE, -60, null, timestamp = t) }
+ val id = DeviceIntel.Identity("x", emptyList())
+ val axon = Hit(Category.BODY_CAM, "Axon body camera", 90, "e", "s")
+ DeviceRegistry.report(a(1_000), listOf(axon), id, null, null, null, 1_000)
+ // Intermittent tag: a packet without it keeps the match for a while...
+ DeviceRegistry.report(a(30_000), emptyList(), id, null, null, null, 30_000)
+ assertEquals("Axon body camera", DeviceRegistry.get(mac)!!.best?.label)
+ // ...but not forever.
+ DeviceRegistry.report(a(1_000 + DeviceRegistry.HIT_HOLD_MS + 1), emptyList(), id, null, null, null, 1_000 + DeviceRegistry.HIT_HOLD_MS + 1)
+ assertNull(DeviceRegistry.get(mac)!!.best)
+ }
+
@Test
fun flatSignalsFallBackToArrivalTime() {
val flat = (0 until 30).map { it * 1000L to -60 }
diff --git a/app/src/test/java/com/rfsentinel/app/util/ExportTextTest.kt b/app/src/test/java/com/rfsentinel/app/util/ExportTextTest.kt
new file mode 100644
index 0000000..8ae5630
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/util/ExportTextTest.kt
@@ -0,0 +1,31 @@
+package com.rfsentinel.app.util
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Test
+import javax.xml.parsers.DocumentBuilderFactory
+
+class ExportTextTest {
+
+ @Test
+ fun csvNeutralisesFormulas() {
+ assertEquals("\"'=HYPERLINK(\"\"x\"\")\"", ExportText.csv("=HYPERLINK(\"x\")"))
+ assertEquals("\"'+1\"", ExportText.csv("+1"))
+ assertEquals("\"'-2\"", ExportText.csv("-2"))
+ assertEquals("\"'@SUM(A1)\"", ExportText.csv("@SUM(A1)"))
+ assertEquals("\"NETGEAR-5G\"", ExportText.csv("NETGEAR-5G"))
+ assertEquals("", ExportText.csv(null))
+ }
+
+ @Test
+ fun xmlDropsForbiddenCharactersAndStaysParseable() {
+ val hostile = "Evil\u0001SSID\u001B<b>&\"'￾\uD800 ok 📡"
+ val escaped = ExportText.xml(hostile)
+ assertFalse(escaped.contains('\u0001'))
+ assertFalse(escaped.contains('￾'))
+ val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
+ .parse("<a v=\"$escaped\">$escaped</a>".byteInputStream())
+ assertEquals("EvilSSID<b>&\"' ok 📡", doc.documentElement.textContent)
+ assertEquals("EvilSSID<b>&\"' ok 📡", doc.documentElement.getAttribute("v"))
+ }
+}
diff --git a/docs/SIGNATURES.md b/docs/SIGNATURES.md
index 24d3913..073dabf 100644
--- a/docs/SIGNATURES.md
+++ b/docs/SIGNATURES.md
@@ -69,20 +69,28 @@ Single rules are only the first pass. Every 2 s per device the scanner also:
device, the scores combine by noisy-OR, with each supporting hit discounted by
half because rules often share evidence. Hits under 30 never corroborate.
Fusion alone never goes past 90. Example: watchlisted address 70 plus Zebra
- serial name 50 gives 78.
+ serial name 50 gives 78. The patrol-vehicle hit (below) is never fused: it is
+ derived from the device's own matches, so fusing would count them twice.
2. **Detects patrol-vehicle kits.** Every device gets a *role* when its matches
or IEEE registrant say it is police-type gear: body camera, plate reader,
two-way radio, vehicle cellular router, mobile printer, in-car computer,
- rugged laptop or police camera. At least two *different* roles count as one
- vehicle when either condition holds:
+ rugged laptop or police camera. Consumer brands that also make car audio or
+ office gear (Kenwood, Panasonic Connect, Havis) get no role from their vendor
+ name alone, and whitelisted devices never count. At least two *different* roles
+ count as one vehicle when either condition holds:
- their RSSI rises and falls together (Pearson r ≥ 0.6 over at least 8
aligned seconds);
- both signals are flat (parked) and they appeared within 30 s of each other.
Each member then gets "Possible police vehicle" at 24 + 12 × roles,
+10 when the signals move together, capped at 88. So two roles score 48 and
- stay weak; three moving together score 70. Separate signals that don't move
- together (r < 0.6) are never grouped.
+ stay weak; three moving together score 70. Never grouped: signals that don't
+ move together (r < 0.6), one moving device next to a parked one, or fewer than
+ 8 shared seconds. The group hit is recomputed every 2 s, so it disappears when
+ the group breaks up.
+
+ A device's own match is held for 2 minutes after its evidence was last seen
+ (some body cams only include their tag in some packets), then fades.
3. **Links rotated addresses.** A structural advert fingerprint survives address
rotation: names, service UUIDs, service-data and company-ID payload sizes,
TX power and connectable flag. When a new private address appears with the