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.

Audit fixes: routes, trips, history, mesh, Waze, settings, USB and speech

CIS-C0f3ea73b113ce
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 76470b0..e5357f3 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -744,14 +744,14 @@ class MainActivity : AppCompatActivity() {
adapter.visual = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.DEVICE_LIST)
// The banner and radar alert only for flagged devices still in range.
val flagged = all.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }
- // The status's count is the Flagged chip's (the banner and radar still alert only for those in range).
- flaggedCount = all.count { com.rfsentinel.app.ui.DeviceFilter.FLAGGED.matches(it) }
+ // The status's count is the Flagged chip's, aircraft included (the banner and radar still alert only for those in range).
+ val aircraft = currentAircraft(now)
+ flaggedCount = all.count { com.rfsentinel.app.ui.DeviceFilter.FLAGGED.matches(it) } + aircraft.count { it.hit != null }
updateBanner(flagged, threshold)
updateStatus()
// Live counts on the chips ("Trackers 2"); empty filters stay unlabelled.
val visualChips = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.STATUS)
- val aircraft = currentAircraft(now)
for ((f, chip) in filterChips) {
val n = when (f) {
com.rfsentinel.app.ui.DeviceFilter.CELLS -> liveCellCount(now)
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 9546ac6..084c725 100644
--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt
@@ -205,13 +205,13 @@ object AlprStore {
synchronized(this@AlprStore) {
val inBox = { c: KnownCamera -> c.lat in south..north && c.lon in west..east }
val merged = cameras.filterNot(inBox) + found
- file(context).writeText(gson.toJson(merged))
+ CctvStore.withTmp(file(context)) { it.writeText(gson.toJson(merged)) }
cameras = merged
val now = System.currentTimeMillis()
val area = CameraArea(south, west, north, east, now)
// Long-stale areas only cost space (their cameras stay cached for offline warnings).
areas = areas.filterNot { area.contains(it) || now - it.time > 4 * REFRESH_MS } + area
- runCatching { areasFile(context).writeText(gson.toJson(areas)) }
+ runCatching { CctvStore.withTmp(areasFile(context)) { it.writeText(gson.toJson(areas)) } }
}
found.size
}
@@ -319,7 +319,7 @@ object AlprStore {
synchronized(this) {
load(context)
val merged = mergeCameras(cameras, boxes, found)
- file(context).writeText(gson.toJson(merged))
+ CctvStore.withTmp(file(context)) { it.writeText(gson.toJson(merged)) }
cameras = merged
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt b/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt
index 259dd16..6d9ea7c 100644
--- a/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt
+++ b/app/src/main/java/com/rfsentinel/app/alpr/Cctv.kt
@@ -302,7 +302,7 @@ object CctvStore {
}
}
- private fun withTmp(target: File, write: (File) -> Unit) {
+ internal fun withTmp(target: File, write: (File) -> Unit) {
val tmp = File(target.parentFile, target.name + ".tmp")
write(tmp)
if (!tmp.renameTo(target)) { target.delete(); tmp.renameTo(target) }
diff --git a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
index 0d6b571..36e2447 100644
--- a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
@@ -132,6 +132,8 @@ interface KnownDeviceDao {
AND (alias IS NULL OR alias = '') AND (note IS NULL OR note = '')""")
suspend fun prune(before: Long): Int
- @Query("DELETE FROM known_devices WHERE favorite = 0")
+ /** Forget all but favorites and the devices you named or wrote a note on. */
+ @Query("""DELETE FROM known_devices WHERE favorite = 0
+ AND (alias IS NULL OR alias = '') AND (note IS NULL OR note = '')""")
suspend fun clearNonFavorites()
}
diff --git a/app/src/main/java/com/rfsentinel/app/data/TrustedNetworks.kt b/app/src/main/java/com/rfsentinel/app/data/TrustedNetworks.kt
index e871008..7f2ea05 100644
--- a/app/src/main/java/com/rfsentinel/app/data/TrustedNetworks.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/TrustedNetworks.kt
@@ -38,8 +38,8 @@ object TrustedNetworks {
@Volatile var rules: List<Rule> = emptyList()
private set
- /** Access points heard with a matching SSID (an address that later broadcasts another name drops out). */
- private val trusted = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
+ /** Access points heard with a matching SSID, by address (an address that later broadcasts another name drops out). */
+ private val trusted = java.util.concurrent.ConcurrentHashMap<String, String>()
fun matches(rules: List<Rule>, ssid: String?): Boolean {
val name = ssid?.trim().orEmpty()
@@ -47,7 +47,10 @@ object TrustedNetworks {
return rules.any { it.matches(name) }
}
- fun contains(mac: String): Boolean = mac in trusted
+ fun contains(mac: String): Boolean = trusted.containsKey(mac)
+
+ /** The name [mac] was trusted under: it may be out of range now, or hidden. */
+ fun ssidOf(mac: String): String? = trusted[mac]
/** The rule that trusts this network name, if any. */
fun ruleFor(ssid: String?): Rule? = rules.firstOrNull { matches(listOf(it), ssid) }
@@ -55,7 +58,7 @@ object TrustedNetworks {
/** A WiFi access point was heard: trusted while its SSID matches (a hidden SSID keeps what it had). */
fun onSeen(mac: String, ssid: String?) {
if (ssid.isNullOrBlank()) return
- if (matches(rules, ssid)) trusted.add(mac) else trusted.remove(mac)
+ if (matches(rules, ssid)) trusted[mac] = ssid else trusted.remove(mac)
}
fun load(context: Context) {
@@ -84,8 +87,9 @@ object TrustedNetworks {
/** The rules changed: the networks in range are trusted (or not) at once, not at their next beacon. */
private fun recheck() {
val now = rules
- val caught = DeviceRegistry.snapshot().filter { it.source == com.rfsentinel.app.detect.Advert.Source.WIFI && matches(now, it.name) }.map { it.mac }
- trusted.retainAll(caught.toSet())
- trusted.addAll(caught)
+ val caught = DeviceRegistry.snapshot().filter { it.source == com.rfsentinel.app.detect.Advert.Source.WIFI && matches(now, it.name) }
+ .associate { it.mac to it.name.orEmpty() }
+ trusted.keys.retainAll(caught.keys)
+ trusted.putAll(caught)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
index 2df209e..b73202e 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt
@@ -189,17 +189,17 @@ object MarauderReports {
fun parse(line: String): EspSighting? {
val t = ANSI.replace(line, "").trimEnd('\r', ' ')
BEACON.find(t)?.let { m ->
- val ch = m.groupValues[2].toInt()
+ val ch = m.groupValues[2].toIntOrNull() ?: return null
return EspSighting(
- mac = m.groupValues[3].uppercase(), rssi = m.groupValues[1].toInt(), ble = false,
+ mac = m.groupValues[3].uppercase(), rssi = m.groupValues[1].toIntOrNull() ?: return null, ble = false,
name = m.groupValues[4].trim().takeIf { it.isNotEmpty() && it.any { c -> c.code >= 0x20 } },
frequencyMhz = frequencyOf(ch)
)
}
PROBE.find(t)?.let { m ->
return EspSighting(
- mac = m.groupValues[3].uppercase(), rssi = m.groupValues[1].toInt(), ble = false,
- frequencyMhz = frequencyOf(m.groupValues[2].toInt()), client = true,
+ mac = m.groupValues[3].uppercase(), rssi = m.groupValues[1].toIntOrNull() ?: return null, ble = false,
+ frequencyMhz = frequencyOf(m.groupValues[2].toIntOrNull() ?: return null), client = true,
probedSsids = listOfNotNull(m.groupValues[4].trim().takeIf { com.rfsentinel.app.usb.MonitorFrames.validSsid(it) })
)
}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
index b441ce4..c90ce91 100644
--- a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
@@ -86,7 +86,7 @@ object MeshNode {
private var myNode = 0L
private var hopLimit = 3
private var region = -1
- private var txEnabled = true
+ @Volatile private var txEnabled = true
private val channels = HashMap<Int, MeshProto.From.ChannelInfo>()
/** The node's slot RF Sentinel sends on (1-7), -1 until set up. */
@Volatile var channelIndex = -1; private set
@@ -142,9 +142,15 @@ object MeshNode {
setStatus("")
}
+ /**
+ * Whether [send] would go out: asked before taking devices from the outbox, which counts them as sent.
+ * shortcut: a full write queue (a stalled node) still drops the packet, its devices repeat on their timer.
+ */
+ val canSend get() = ready && channelIndex >= 0 && txEnabled
+
/** Sends one RF Sentinel payload on the RFSentinel channel; false when the node isn't ready. */
fun send(payload: ByteArray, urgent: Boolean): Boolean {
- if (!ready) return false
+ if (!canSend) return false
h.post {
if (!ready || channelIndex < 0 || !txEnabled) return@post
if (ops.count { it is Op.Write } >= MAX_QUEUED) return@post
diff --git a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
index 3af8e94..2bc46c9 100644
--- a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
+++ b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt
@@ -122,6 +122,8 @@ object Navigator {
private var lastReroute = 0L
private var legNow = 0
private var rerouting = false
+ /** A stop or options you asked for while a route was being planned: they run when it finishes. */
+ private val waiting = ArrayDeque<() -> Unit>()
/** Failed attempts at a new route in a row (offline...): the wait before the next one grows. */
private var rerouteFailures = 0
private var saidRerouting = false
@@ -199,7 +201,7 @@ object Navigator {
generation++
prompts = Prompts(NavFormat.miles(app))
offRouteSince = 0L; wrongWaySince = 0L; lastReroute = clock()
- legNow = 0; rerouting = false; status = null
+ legNow = 0; rerouting = false; waiting.clear(); status = null
rerouteFailures = 0; saidRerouting = false; stoppedNearEndSince = 0L; lastFixAt = 0L
state = null
pace = 1.0; paceFromAlong = null; stillSince = 0L; parkedMs = 0L
@@ -229,7 +231,7 @@ object Navigator {
fun stop() {
appContext?.let { listen(it, false); NavigationService.stop(it) }
generation++
- destination = null; route = null; state = null; status = null; stops = emptyList(); rerouting = false; limits = null
+ destination = null; route = null; state = null; status = null; stops = emptyList(); rerouting = false; waiting.clear(); limits = null
lastFix = null // a fix kept after the trip would stand in for a newer position later (the car screens take the newest of two)
changed()
}
@@ -238,9 +240,11 @@ object Navigator {
fun addStop(context: Context, stop: Place) {
val dest = destination ?: return
val from = lastFix ?: return
+ val app = context.applicationContext
status = "Adding stop..."
changed()
- replan(context.applicationContext, from, dest, stops + stop, then = { stops = it })
+ if (rerouting) { waiting += { addStop(app, stop) }; return }
+ replan(app, from, dest, stops + stop, then = { stops = it })
}
/** Plans again from where you are with other route options (avoid tolls, highways or ferries). */
@@ -249,9 +253,11 @@ object Navigator {
val from = lastFix ?: return
status = "Re-routing..."
options = newOptions
- remember(context.applicationContext, newOptions)
+ val app = context.applicationContext
+ remember(app, newOptions)
changed()
- replan(context.applicationContext, from, dest, stops)
+ if (rerouting) { waiting += { changeOptions(app, newOptions) }; return }
+ replan(app, from, dest, stops)
}
private fun replan(app: Context, from: Location, dest: Place, via: List<Place>, then: ((List<Place>) -> Unit)? = null) {
@@ -271,7 +277,10 @@ object Navigator {
status = "No new route (${failureText(it)}) - keeping the old one"
}
}
- if (gen == generation) rerouting = false
+ if (gen == generation) {
+ rerouting = false
+ waiting.removeFirstOrNull()?.invoke()
+ }
changed()
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt
index 0695f02..073c228 100644
--- a/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt
@@ -125,8 +125,8 @@ object RoadTiles {
while (i < geom.size) {
val cmd = (geom[i] and 7).toInt(); val count = (geom[i] ushr 3).toInt(); i++
if (cmd == 1) flush()
- if (cmd == 1 || cmd == 2) repeat(count) {
- if (i + 1 >= geom.size) return@repeat
+ if (cmd == 1 || cmd == 2) for (k in 0 until count) {
+ if (i + 1 >= geom.size) break // a broken tile's count can be huge
x += Pb.zigzag(geom[i]); y += Pb.zigzag(geom[i + 1]); i += 2
val (la, lo) = toLatLon(t, x.toDouble(), y.toDouble(), extent)
lat += la; lon += lo
diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
index 85c8332..90b1712 100644
--- a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
@@ -267,13 +267,18 @@ public final class WazeRtFetcher {
}
long sessionBefore = session.currentServerSessionId();
- WazeProto.Batch handshake = prepareWithRetry(lat, lon);
+ WazeProto.Batch handshake;
+ try {
+ handshake = prepareWithRetry(lat, lon);
+ } finally {
+ // A login refused right after registering still used up one of today's accounts.
+ if (wasUnregistered && session.getCredentials() != null) noteRegistration();
+ }
// Credentials exist now: persist immediately so a failure in the box loop
// below cannot lose a freshly minted account and force a wasteful
// re-register on the next poll.
if (wasUnregistered) {
- noteRegistration();
saveAccount(session.getCredentials(), session.getDevice());
Log.i(TAG, "Registered a new anonymous Waze account");
}
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 1793854..27d14ed 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -1048,7 +1048,7 @@ class ScanForegroundService : Service() {
val box = meshOutbox ?: return
pipeline.postDelayed(this, MESH_TICK_MS)
val node = com.rfsentinel.app.link.MeshNode
- if (!node.ready) return
+ if (!node.canSend) return
val ctx = this@ScanForegroundService
val link = com.rfsentinel.app.link.LinkStore
val now = System.currentTimeMillis()
@@ -1141,7 +1141,7 @@ class ScanForegroundService : Service() {
}
private fun classify(a: Advert, now: Long, extra: List<Hit> = emptyList()): Classified {
- val macVendor = VendorDb.macVendor(a.mac)
+ val macVendor = if (a.randomBle) null else VendorDb.macVendor(a.mac)
val identity = DeviceIntel.identify(a, macVendor)
val companyVendors = a.manufacturerData.keys.mapNotNull { VendorDb.company(it) }
val vendor = macVendor ?: companyVendors.firstOrNull()
@@ -2025,6 +2025,7 @@ class ScanForegroundService : Service() {
}
wakeLock?.let { if (it.isHeld) it.release() }
Prefs.setStartedByCar(this, false)
+ lastFix = null // only true while scanning: kept, it would pass for your position hours later
isRunning = false
refreshTile()
StatusWidget.updateAll(this)
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 88b8b45..658f3f2 100644
--- a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt
@@ -12,6 +12,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
+import androidx.room.withTransaction
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -253,10 +254,24 @@ object TripRecorder {
totalPoints = points.size
distance = distanceM
}
- val dao = AppDatabase.getInstance(context).tripDao()
- if (newPoints.isNotEmpty()) dao.insertPoints(newPoints)
- if (changed.isNotEmpty()) changed.chunked(300).forEach { dao.upsertDevices(it) }
- if (newPings.isNotEmpty()) newPings.chunked(500).forEach { dao.insertPings(it) }
+ val db = AppDatabase.getInstance(context)
+ val dao = db.tripDao()
+ try {
+ // One transaction: after a failure nothing was written, so all of it can go back without duplicates.
+ db.withTransaction {
+ if (newPoints.isNotEmpty()) dao.insertPoints(newPoints)
+ if (changed.isNotEmpty()) changed.chunked(300).forEach { dao.upsertDevices(it) }
+ if (newPings.isNotEmpty()) newPings.chunked(500).forEach { dao.insertPings(it) }
+ }
+ } catch (e: Exception) {
+ synchronized(this) {
+ if (activeTripId == id) {
+ pendingPoints.addAll(0, newPoints); pendingPings.addAll(0, newPings)
+ changed.forEach { dirty += it.mac }
+ }
+ }
+ throw e
+ }
// Stopped while writing: the trip's final totals come from persist (which waits for this), not from here.
if (activeTripId != id) return@withLock
evictIdle(System.currentTimeMillis())
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 c01c99b..d217574 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -95,6 +95,9 @@ class SettingsActivity : AppCompatActivity() {
private var airTagSwitch: SwitchMaterial? = null
private var flockSwitch: SwitchMaterial? = null
private var mappedCamerasSwitch: SwitchMaterial? = null
+ /** What a switch last held. A default that follows another setting is written only once you move the switch. */
+ private val switchWas = HashMap<SwitchMaterial, Boolean>()
+ private fun moved(sw: SwitchMaterial) = switchWas.put(sw, sw.isChecked) != sw.isChecked
private var wazeKeyInput: android.widget.EditText? = null
private var aircraftStatusText: android.widget.TextView? = null
private var wazeStatusText: android.widget.TextView? = null
@@ -924,7 +927,7 @@ class SettingsActivity : AppCompatActivity() {
"rfsentinel_live_matches.csv, rfsentinel_live_matches.kml and rfsentinel_live.geojson (devices on the map and " +
"your position) - so another mapping app can show them close to live. Anything that can read that folder can read them.\n\n" +
"Forget device history: new / returning status, detect counts and the cell towers remembered for the " +
- "fake-cell checks start over. Favorites are kept.\n\n" +
+ "fake-cell checks start over. Favorites and devices you named or noted are kept.\n\n" +
"Changes on this screen are saved automatically."),
Section("more", binding.headerMore, binding.sectionMore,
"Watchlist & rules: the vendor prefixes and rules that flag a device; add your own.\n\n" +
@@ -1061,6 +1064,7 @@ class SettingsActivity : AppCompatActivity() {
mappedCamerasSwitch = SwitchMaterial(this).apply {
text = "Mapped cameras"
isChecked = Prefs.mappedCameras(this@SettingsActivity)
+ switchWas[this] = isChecked
}
binding.categoryContainer.addView(detectRow(mappedCamerasSwitch!!,
"Alerts for cameras mapped in OpenStreetMap, whether or not detected cameras are on. Choose which kinds under Known cameras."))
@@ -1218,7 +1222,7 @@ class SettingsActivity : AppCompatActivity() {
info(binding.ouiSpyRelaySwitch, "Every device the OUI-SPY board hears comes into the list, not just its own matches.")
info(binding.ouiSpyEnginesButton, "Which of the board's detection engines run: Flock BLE and Flock WiFi (Flock Safety " +
"cameras), Sky Spy (drones) and Detector. Where there are no Flock cameras, turn the two Flock engines off. " +
- "RF Sentinel's own checks are set under Categories.")
+ "RF Sentinel's own checks are set under What to detect.")
info(binding.ouiSpyPhoneBleSwitch, "Off: while the OUI-SPY board is connected and live, the phone's own Bluetooth scan " +
"pauses and the board does the Bluetooth scanning (it hears farther, and faster). It comes back on its own if the " +
"board drops out. Turn on Relay everything too, or only the board's engine matches come in.")
@@ -2803,6 +2807,7 @@ class SettingsActivity : AppCompatActivity() {
val fold = foldIcon()
binding.categoryContainer.addView(detectRow(sw, details.ifEmpty { null }, short, fold))
categorySwitches[c] = sw
+ switchWas[sw] = sw.isChecked
addCategoryAlertChips(c, sw, fold)
if (c == Category.TRACKER) {
airTagSwitch = SwitchMaterial(this).apply {
@@ -3047,7 +3052,7 @@ class SettingsActivity : AppCompatActivity() {
Toast.makeText(this, "Crash log cleared", Toast.LENGTH_SHORT).show()
}
binding.forgetHistoryButton.setOnClickListener {
- confirm("Forget device history?", "New/returning status, detect counts and the cell towers remembered for the fake-cell checks 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 and devices you named or noted are kept.") {
lifecycleScope.launch {
AppDatabase.getInstance(this@SettingsActivity).knownDeviceDao().clearNonFavorites()
AppDatabase.getInstance(this@SettingsActivity).deviceDetailsDao().pruneOrphans()
@@ -3169,10 +3174,10 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setCarAutoRecord(this, binding.carRecordSwitch.isChecked)
Prefs.setCarMusic(this, binding.carMusicSwitch.isChecked)
- categorySwitches.forEach { (c, sw) -> Prefs.setCategoryEnabled(this, c, sw.isChecked) }
+ categorySwitches.forEach { (c, sw) -> if (c != Category.MOBILE_PRINTER || moved(sw)) Prefs.setCategoryEnabled(this, c, sw.isChecked) }
airTagSwitch?.let { Prefs.setExcludeAirTags(this, it.isChecked) }
flockSwitch?.let { Prefs.setFlockCameras(this, it.isChecked) }
- mappedCamerasSwitch?.let { Prefs.setMappedCameras(this, it.isChecked) }
+ mappedCamerasSwitch?.let { if (moved(it)) Prefs.setMappedCameras(this, it.isChecked) }
wazeKeyInput?.let { input ->
val key = input.text.toString().trim()
val name = com.rfsentinel.app.online.OnlineWatch.WAZE_KEY_NAME
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt
index 3269e5d..6828fbd 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt
@@ -8,7 +8,6 @@ import android.os.Handler
import android.os.Looper
import android.view.View
import com.rfsentinel.app.R
-import com.rfsentinel.app.car.CarUi
import com.rfsentinel.app.databinding.ActivityMapBinding
import com.rfsentinel.app.detect.Category
import com.rfsentinel.app.detect.DeviceIntel
@@ -133,7 +132,7 @@ internal class AlertCardController(
/** "Strong match · 2 more flagged nearby". */
private fun footerOf(c: AlertCards.Card): String {
val tier = Tier.of(c.confidence).label.substringBefore(" -").replaceFirstChar { it.uppercase() } + " match"
- val others = DeviceRegistry.snapshot().count { CarUi.isFlagged(it) && !it.mac.equals(c.mac, ignoreCase = true) }
+ val others = DeviceRegistry.snapshot().count { LiveWindow.alerting(it) && !it.mac.equals(c.mac, ignoreCase = true) }
return listOfNotNull(tier, others.takeIf { it > 0 }?.let { "$it more flagged nearby" }).joinToString(" · ")
}
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 6ec05cc..2824b70 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -103,7 +103,7 @@ class DeviceDetailActivity : AppCompatActivity() {
refresh()
}
WhitelistCache.inTable(mac) -> DeviceActions.unwhitelist(this, mac)
- com.rfsentinel.app.data.TrustedNetworks.contains(mac) -> { DeviceActions.untrustNetwork(this, DeviceActions.ssidOf(s)); refresh() }
+ com.rfsentinel.app.data.TrustedNetworks.contains(mac) -> { DeviceActions.untrustNetwork(this, DeviceActions.ssidOf(s) ?: com.rfsentinel.app.data.TrustedNetworks.ssidOf(mac)); refresh() }
isRotatingTracker(s) -> DeviceActions.ignoreTracker(this, mac)
else -> DeviceActions.whitelist(this, mac, s?.let { it.best?.label ?: it.name } ?: "", DeviceActions.ssidOf(s))
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
index 2685457..113f006 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
@@ -97,7 +97,10 @@ object FloatingMap {
cameras: List<Cam> = emptyList()) = main.post {
val app = context.applicationContext
if (!canShow(app)) { removeNow(app); return@post }
- if (root == null) add(app) ?: return@post
+ if (root == null) {
+ if (System.currentTimeMillis() - addFailedAt < ADD_RETRY_MS) return@post
+ add(app) ?: return@post
+ }
border?.setStroke(dp(app, 3f), level.color)
badge?.apply {
text = if (flagged == 0) "✓" else if (flagged > 99) "99+" else flagged.toString()
@@ -133,6 +136,8 @@ object FloatingMap {
}
private const val CAMS = "fm-cams"; private const val DOTS = "fm-dots"; private const val ME = "fm-me"
+ private const val ADD_RETRY_MS = 60_000L
+ private var addFailedAt = 0L
fun hide(context: Context) = main.post { removeNow(context.applicationContext) }
@@ -321,12 +326,16 @@ object FloatingMap {
}
return runCatching {
+ ScanForegroundService.mapShown(context) // first: the failure path below takes it back
wm.addView(frame, lp)
m.onStart(); m.onResume()
root = frame; view = m; badge = count; waiting = wait; mapLp = lp
- ScanForegroundService.mapShown(context)
live = LiveReadOverlay(context) { lp, h -> placeLive(context, lp, h) }.also { it.start() }
frame
+ }.onFailure {
+ // The map engine is up by now and would otherwise leak, with its crash guard left armed.
+ root = frame; view = m; addFailedAt = System.currentTimeMillis()
+ removeNow(context)
}.getOrNull()
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
index 7baf4d3..f3cdd01 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt
@@ -222,12 +222,12 @@ class HistoryActivity : AppCompatActivity() {
}
binding.detailText.text = when {
device && positioned.isEmpty() -> "No position saved for it in this period. Spots come from this session's scanning, " +
- "recorded traces and logged matches (Settings > Location > Save GPS position with logged matches)."
+ "recorded traces and logged matches (Settings > Location & traces > Save GPS position with matches)."
device -> "Each dot is where your phone was when it heard it (not the device's own position). " +
"Dots of one encounter are linked in time order; tap one for its time."
events.isEmpty() -> "Scan with alerts on, or record traces, to build your history."
positioned.isEmpty() -> "Top: " + top() +
- "\nNot on the map: turn on Settings > Location > Save GPS position with logged matches, or record traces."
+ "\nNot on the map: turn on Settings > Location & traces > Save GPS position with matches, or record traces."
positioned.size < events.size -> "Top: " + top() + "\n${positioned.size} with a position shown on the map."
else -> "Top: " + top()
}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
index d8768e3..56b5ef3 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
@@ -137,6 +137,7 @@ object Mt7612uMonitor {
*/
private var mcuAsked = 0
private var mcuAnswered = 0
+ private var mcuMissed = 0
@Volatile private var uncalibrated = false
private var mcuGain = 0
private var rssiOff2g = 0; private var rssiOff5g = 0; private var lna2g = 0; private var lna5g = 0
@@ -160,7 +161,7 @@ object Mt7612uMonitor {
if (running) return
this.x0 = x0; tag = if (x0) "MT7610U" else "MT7612U"
HOP = UsbWifi.hops(ALL_HOP)
- running = true; stop = false; frames.clear(); lastCalMs.clear(); mcuLogged = 0; ctlErrors = 0; mcuAsked = 0; mcuAnswered = 0; uncalibrated = false
+ running = true; stop = false; frames.clear(); lastCalMs.clear(); mcuLogged = 0; ctlErrors = 0; mcuAsked = 0; mcuMissed = 0; mcuAnswered = 0; uncalibrated = false
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val c = mgr.openDevice(device) ?: run { onStatus("$chipName: couldn't reopen adapter"); running = false; return }
conn = c
@@ -987,10 +988,13 @@ object Mt7612uMonitor {
mcuAsked++
val rep = epResp ?: run { sleep(10); return null }
val rb = ByteArray(1024)
- repeat(5) {
- val n = conn.bulkTransfer(rep, rb, rb.size, 300)
- if (n >= 4 && (le32(rb, 0) ushr 16) and 0xf == s) { mcuAnswered++; return rb }
+ // An MCU that has stopped answering gets one short look: 1.5 s per command adds up to minutes of bring-up.
+ val silent = mcuMissed >= 3
+ repeat(if (silent) 1 else 5) {
+ val n = conn.bulkTransfer(rep, rb, rb.size, if (silent) 20 else 300)
+ if (n >= 4 && (le32(rb, 0) ushr 16) and 0xf == s) { mcuAnswered++; mcuMissed = 0; return rb }
}
+ mcuMissed++
if (mcuLogged < 6) { mcuLogged++; UsbWifi.log("MT7610U: MCU cmd $cmd - no answer") }
return null
}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
index c497898..e394e56 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -416,7 +416,8 @@ object UsbWifi {
Driver.AR9271 -> Ar9271Monitor.run(context, d, "${chip.name} (experimental)", onStatus, onFrames)
}
}.onFailure { log("Driver stopped: ${describe(it)}"); status = "USB WiFi adapter error: ${it.message}" }
- synchronized(this) { if (runningDevice == d.deviceName) { runningDevice = null; runningChip = null } }
+ // By thread, not name: a replug reuses the name, and a stopped run ending late must not clear the new one.
+ synchronized(this) { if (thread === Thread.currentThread()) { runningDevice = null; runningChip = null } }
}, "usb-wifi").also { it.start() }
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/CarMessages.kt b/app/src/main/java/com/rfsentinel/app/util/CarMessages.kt
index 1d81ac0..6842f11 100644
--- a/app/src/main/java/com/rfsentinel/app/util/CarMessages.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/CarMessages.kt
@@ -41,6 +41,7 @@ object CarMessages {
internal fun command(reply: String?): Command {
val words = reply.orEmpty().lowercase().split(Regex("[^a-z]+")).toSet()
return when {
+ words.any { it in setOf("don", "dont", "not", "never") } -> Command.NONE // the split leaves "don" of a contraction
words.any { it in setOf("mute", "silence", "quiet", "snooze", "stop", "shut") } -> Command.MUTE
"ignore" in words -> Command.IGNORE
else -> Command.NONE
diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
index e497c1b..a90d5d8 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
@@ -32,8 +32,14 @@ object Spoken {
}
}
- /** A distance said aloud: "300 meters" (to the nearest 50), "1 kilometer", "1.2 kilometers". */
- fun distanceWords(m: Double): String {
+ /** A distance said aloud: "300 meters" (to the nearest 50), "1 kilometer", "1.2 kilometers"; "500 feet", "1.2 miles". */
+ fun distanceWords(m: Double, feet: Boolean = Units.imperial): String {
+ if (feet) {
+ val ft = Math.round(m * 3.28084 / 100.0) * 100
+ if (ft < 1000) return "${ft.coerceAtLeast(100)} feet"
+ val mi = Math.round(m / 160.9344) / 10.0
+ return if (mi == Math.floor(mi)) "${mi.toLong()} mile${if (mi == 1.0) "" else "s"}" else "$mi miles"
+ }
val r = Math.round(m / 50.0) * 50
if (r < 1000) return "${r.coerceAtLeast(50)} meters"
val km = Math.round(m / 100.0) / 10.0
diff --git a/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt b/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt
index 601abbf..9977bed 100644
--- a/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt
@@ -96,6 +96,13 @@ class EspReportsTest {
assertFalse(MarauderReports.isFlipperCli("-55 Ch: 1 aa:bb:cc:dd:ee:ff ESSID: x"))
}
+ @Test
+ fun aGarbledNumberIsDroppedNotACrash() {
+ assertNull(MarauderReports.parse("-60 Ch: 99999999999 02:11:22:33:44:55 ESSID: x"))
+ assertNull(MarauderReports.parse("-99999999999 Ch: 1 02:11:22:33:44:55 ESSID: x"))
+ assertNull(MarauderReports.parse("-60 Ch: 99999999999 Client: 02:11:22:33:44:55 Requesting: x"))
+ }
+
@Test
fun flipperZeroIsASerialBoard() {
assertEquals(SerialPort.Chip.NATIVE_USB, SerialPort.chipOf(0x0483, 0x5740))
diff --git a/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt b/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt
index 646fd98..9fdf18d 100644
--- a/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/nav/NavQaTest.kt
@@ -336,6 +336,25 @@ class NavQaTest {
Navigator.remember(ctx, Valhalla.Options())
}
+ @Test
+ fun aStopAddedWhileARouteIsBeingPlannedIsNotLost() {
+ val gate = kotlinx.coroutines.CompletableDeferred<Unit>()
+ val asked = ArrayList<List<Place>>()
+ Navigator.planner = { _, _, _, _, via -> asked += via; gate.await(); listOf(northRoad(2)) }
+ begin(northRoad(2))
+ Navigator.changeOptions(ctx, Valhalla.Options(avoidFerries = true))
+ idle()
+ val stop = Place("Cafe", "2 Main Street", lat(1000.0), lon0)
+ Navigator.addStop(ctx, stop)
+ idle()
+ assertEquals("it waits for the plan in progress", 1, asked.size)
+ gate.complete(Unit)
+ idle()
+ assertEquals(listOf(emptyList(), listOf(stop)), asked)
+ assertEquals(listOf(stop), Navigator.stops)
+ Navigator.remember(ctx, Valhalla.Options())
+ }
+
@Test
fun changingOptionsOnTheTripMenuIsRememberedToo() {
Navigator.remember(ctx, Valhalla.Options())
diff --git a/app/src/test/java/com/rfsentinel/app/util/CarMessagesTest.kt b/app/src/test/java/com/rfsentinel/app/util/CarMessagesTest.kt
index f3aa14f..2dd6b74 100644
--- a/app/src/test/java/com/rfsentinel/app/util/CarMessagesTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/util/CarMessagesTest.kt
@@ -14,6 +14,8 @@ class CarMessagesTest {
assertEquals(CarMessages.Command.MUTE, CarMessages.command("Snooze alerts."))
assertEquals(CarMessages.Command.IGNORE, CarMessages.command("ignore it"))
assertEquals(CarMessages.Command.NONE, CarMessages.command("ok thanks"))
+ assertEquals(CarMessages.Command.NONE, CarMessages.command("don't mute"))
+ assertEquals(CarMessages.Command.NONE, CarMessages.command("do not ignore that"))
assertEquals(CarMessages.Command.NONE, CarMessages.command(null))
assertEquals(CarMessages.Command.NONE, CarMessages.command("muted")) // whole words only
}
diff --git a/app/src/test/java/com/rfsentinel/app/util/UpdateAndSpokenTest.kt b/app/src/test/java/com/rfsentinel/app/util/UpdateAndSpokenTest.kt
index fc56da1..dd80345 100644
--- a/app/src/test/java/com/rfsentinel/app/util/UpdateAndSpokenTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/util/UpdateAndSpokenTest.kt
@@ -28,4 +28,14 @@ class UpdateAndSpokenTest {
assertEquals("Police gear", Spoken.shortWord(hit(Category.PUBLIC_SAFETY, "Motorola Solutions equipment")))
Category.entries.forEach { c -> assertTrue(Spoken.shortWord(hit(c, "x")).split(' ').size <= 2) }
}
+
+ @Test
+ fun distancesAreSaidInFeetAndMilesToo() {
+ assertEquals("100 feet", Spoken.distanceWords(10.0, feet = true))
+ assertEquals("500 feet", Spoken.distanceWords(150.0, feet = true))
+ assertEquals("0.2 miles", Spoken.distanceWords(300.0, feet = true))
+ assertEquals("1 mile", Spoken.distanceWords(1609.0, feet = true))
+ assertEquals("1.2 miles", Spoken.distanceWords(1931.0, feet = true))
+ assertEquals("2 miles", Spoken.distanceWords(3219.0, feet = true))
+ }
}