RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Per-category alert threshold, Mobile printers category, P25 call log, police aircraft voice alerts, swipe whitelist/watchlist, ignored network names with telecom presets, trace every sighting
CIS-C09d51806d5926
diff --git a/app/src/main/assets/oui_presets/canada.json b/app/src/main/assets/oui_presets/canada.jsonindex 2ec2a1a..3bdb424 100644--- a/app/src/main/assets/oui_presets/canada.json+++ b/app/src/main/assets/oui_presets/canada.json@@ -157,7 +157,7 @@"source": "IEEE MA-L (Texas Instruments); seen on Zebra ZQ-series mobile printers. Very weak: TI chips are in countless products - listed so these devices are highlighted, not alerted","confidence": "candidate","score": 20,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "name:RJ-4230B",@@ -165,7 +165,7 @@"source": "Brother Mobile Solutions public-safety/eCitation material. Brother's default Bluetooth name starts with the model - verify","confidence": "candidate","score": 40,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "name:RJ-4250WB",@@ -173,7 +173,7 @@"source": "Brother RuggedJet 4200 public-safety datasheet (e-citations, accident reports, parking). Default name starts with the model - verify","confidence": "candidate","score": 40,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "name:RJ-4040",@@ -181,7 +181,7 @@"source": "Brother eCitation material; older RuggedJet model still in fleets. Name form - verify","confidence": "candidate","score": 35,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "name:PJ-763",@@ -189,7 +189,7 @@"source": "Brother: PocketJet is the most common 8.5-inch in-car citation/report printer. Name form - verify","confidence": "candidate","score": 35,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "name:PJ-883",@@ -197,7 +197,7 @@"source": "Brother PocketJet 8 (Patrol PC in-car mount). Name form - verify","confidence": "candidate","score": 35,- "category": "PUBLIC_SAFETY"+ "category": "MOBILE_PRINTER"},{"prefix": "00:30:44",diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex e69af59..3d12036 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -743,6 +743,7 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.ui.DeviceFilter.CELLS -> liveCellCount(now)com.rfsentinel.app.ui.DeviceFilter.WAZE -> currentWaze(now).sizecom.rfsentinel.app.ui.DeviceFilter.AIRCRAFT -> currentAircraft(now).size+ com.rfsentinel.app.ui.DeviceFilter.FLAGGED -> all.count { f.matches(it) } + currentAircraft(now).count { it.hit != null }com.rfsentinel.app.ui.DeviceFilter.RADIO -> if (ScanForegroundService.isRunning) com.rfsentinel.app.sdr.RadioLog.current(now).size else 0else -> all.count { f.matches(it) }}@@ -773,7 +774,7 @@ class MainActivity : AppCompatActivity() {panes.update(flagged.maxByOrNull { it.best?.confidence ?: 0 }?.let { colorFor(it) })var radioBlips = 0if (panes.radarShown) {- val radio = radioBlips(now, threshold)+ val radio = radioBlips(now, Prefs.alertThreshold(this, Category.RADIO))radioBlips = radio.sizeval fix = if (demoMode) com.rfsentinel.app.ui.DemoData.fakeLocation else ScanForegroundService.lastFix// Heading-up from the compass (and the GPS course while driving), north-up without either.@@ -799,9 +800,9 @@ class MainActivity : AppCompatActivity() {}if (panes.listShown) {val cells = cellRows(now)- val waze = wazeRows(now, threshold)- val radio = radioRows(now, threshold)- val air = aircraftRows(now, threshold)+ val waze = wazeRows(now, Prefs.alertThreshold(this, Category.POLICE_REPORT))+ val radio = radioRows(now, Prefs.alertThreshold(this, Category.RADIO))+ val air = aircraftRows(now, Prefs.alertThreshold(this, Category.AIRCRAFT))// Waze reports, radios on the air and aircraft that meet the alert threshold flash at the very top;// the rest follow the devices.val (urgent, quiet) = waze.partition { it.flashing }@@ -1007,12 +1008,13 @@ class MainActivity : AppCompatActivity() {}/**- * Aircraft as rows: under All only the law-enforcement ones (so airliners don't fill the list), under+ * Aircraft as rows: under All and Flagged only the law-enforcement ones (so airliners don't fill the list), under* Aircraft every one, police first, then nearest. A police one at or above the alert threshold is* tinted, flashes and is pinned to the top. Tap: the aircraft on the map.*/private fun aircraftRows(now: Long, threshold: Int): List<DeviceRow> {- if (filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.AIRCRAFT) return emptyList()+ if (filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.AIRCRAFT &&+ filter != com.rfsentinel.app.ui.DeviceFilter.FLAGGED) return emptyList()val all = filter == com.rfsentinel.app.ui.DeviceFilter.AIRCRAFTval me = (if (demoMode) com.rfsentinel.app.ui.DemoData.fakeLocation else ScanForegroundService.lastFix)?.let { it.latitude to it.longitude }val color = com.rfsentinel.app.ui.ThemeManager.ink(this, Category.AIRCRAFT.colorArgb)@@ -1145,6 +1147,8 @@ class MainActivity : AppCompatActivity() {when (it) {"mute" -> r.canMute && !noMute"hide" -> r.canMute || noMute+ // A device heard now (not an aircraft, radio or Waze row).+ "whitelist", "watchlist" -> r.canMute && DeviceRegistry.get(r.mac) != nullelse -> false}}@@ -1176,6 +1180,13 @@ class MainActivity : AppCompatActivity() {when (swipeAction(r, direction == swipeRight)) {"mute" -> toggleMute(r, false)"hide" -> hideRow(r)+ "whitelist" -> DeviceRegistry.get(r.mac).let { s ->+ com.rfsentinel.app.ui.DeviceActions.whitelist(this@MainActivity, r.mac, s?.best?.label ?: s?.name ?: r.title,+ com.rfsentinel.app.ui.DeviceActions.ssidOf(s))+ }+ "watchlist" -> DeviceRegistry.get(r.mac).let { s ->+ com.rfsentinel.app.ui.DeviceActions.addToWatchlist(this@MainActivity, r.mac, s?.name, s?.advert?.isWifi == true)+ }}}override fun onChildDraw(c: android.graphics.Canvas, rv: androidx.recyclerview.widget.RecyclerView, vh: androidx.recyclerview.widget.RecyclerView.ViewHolder,@@ -1184,12 +1195,19 @@ class MainActivity : AppCompatActivity() {if (dX != 0f) {val right = dX > 0val r = row(vh)- val mute = r != null && swipeAction(r, right) == "mute"+ val action = r?.let { swipeAction(it, right) }+ val mute = action == "mute" || action == "watchlist"paint.color = if (mute) accent else com.rfsentinel.app.ui.ThemeManager.ink(this@MainActivity, WHITELIST_COLOR)if (right) c.drawRect(v.left.toFloat(), v.top.toFloat(), v.left + dX, v.bottom.toFloat(), paint)else c.drawRect(v.right + dX, v.top.toFloat(), v.right.toFloat(), v.bottom.toFloat(), paint)paint.color = if (mute) onAccent else android.graphics.Color.WHITE- val label = if (mute) (if (r?.muted == true) "Unmute" else "Mute") else if (r != null && hidesWhole(r)) "Hide" else "Dismiss"+ val label = when {+ action == "whitelist" -> "Whitelist"+ action == "watchlist" -> "Watchlist"+ mute -> if (r?.muted == true) "Unmute" else "Mute"+ r != null && hidesWhole(r) -> "Hide"+ else -> "Dismiss"+ }val y = (v.top + v.bottom) / 2f - (paint.descent() + paint.ascent()) / 2if (right) c.drawText(label, v.left + 20 * dp, y, paint)else c.drawText(label, v.right - 20 * dp - paint.measureText(label), y, paint)@@ -1244,7 +1262,7 @@ class MainActivity : AppCompatActivity() {highlight = if (alert) colorFor(s) else null,// Flashes only while still in range (like the beeps); a gone device keeps a steady tint.flashing = alert && !muted && com.rfsentinel.app.ui.LiveWindow.inRange(s, now) &&- (s.following || (best!!.confidence >= threshold && best.category != Category.TRACKER)),+ (s.following || (best!!.confidence >= Prefs.alertThreshold(this, best.category) && best.category != Category.TRACKER)),bold = alert,heardByEsp = com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac, now),heardByUsb = com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac, now),@@ -1284,7 +1302,7 @@ class MainActivity : AppCompatActivity() {following != null -> 0xFFB3261E.toInt() to "⚠ ${following.best!!.label} may be following you"top == null -> 0xFF2E7D32.toInt() to "✓ All clear - no flagged equipment nearby"top.best!!.tier == Tier.STRONG -> 0xFFB3261E.toInt() to "⚠ Strong match nearby: ${top.best!!.label}"- top.best!!.confidence >= threshold -> 0xFFC8431A.toInt() to "Probable match nearby: ${top.best!!.label}"+ top.best!!.confidence >= Prefs.alertThreshold(this, top.best!!.category) -> 0xFFC8431A.toInt() to "Probable match nearby: ${top.best!!.label}"else -> WEAK_COLOR to "Weak match only (verify): ${top.best!!.label}"}banner.text = if (flagged.size > 1 && following == null) "$text (+${flagged.size - 1} more)" else textdiff --git a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.ktindex 9cbe655..ae89228 100644--- a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt+++ b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt@@ -10,9 +10,10 @@ import androidx.sqlite.db.SupportSQLiteDatabase@Database(entities = [DetectionEntity::class, WhitelistEntity::class, KnownDeviceEntity::class,- TripEntity::class, TripPointEntity::class, TripDeviceEntity::class, DeviceDetailsEntity::class+ TripEntity::class, TripPointEntity::class, TripDeviceEntity::class, DeviceDetailsEntity::class,+ TripPingEntity::class],- version = 8,+ version = 9,exportSchema = false)abstract class AppDatabase : RoomDatabase() {@@ -107,13 +108,23 @@ abstract class AppDatabase : RoomDatabase() {}}+ /** v2.33: every sighting of a device during a trace, where you were (optional). */+ val MIGRATION_8_9 = object : Migration(8, 9) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL("CREATE TABLE IF NOT EXISTS trip_pings (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, tripId INTEGER NOT NULL, " ++ "mac TEXT NOT NULL, time INTEGER NOT NULL, rssi INTEGER NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, " ++ "FOREIGN KEY(tripId) REFERENCES trips(id) ON UPDATE NO ACTION ON DELETE CASCADE)")+ db.execSQL("CREATE INDEX IF NOT EXISTS index_trip_pings_tripId ON trip_pings (tripId)")+ }+ }+fun getInstance(context: Context): AppDatabase {return INSTANCE ?: synchronized(this) {INSTANCE ?: Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"rfsentinel.db"- ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8).build().also { INSTANCE = it }+ ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9).build().also { INSTANCE = it }}}}diff --git a/app/src/main/java/com/rfsentinel/app/data/Trips.kt b/app/src/main/java/com/rfsentinel/app/data/Trips.ktindex c68979e..05ebb44 100644--- a/app/src/main/java/com/rfsentinel/app/data/Trips.kt+++ b/app/src/main/java/com/rfsentinel/app/data/Trips.kt@@ -49,6 +49,22 @@ data class TripPointEntity(val speedMs: Float? = null)+/** One time a device was heard during a trace, where your phone was then (Settings › Log every sighting in traces). */+@Entity(+ tableName = "trip_pings",+ foreignKeys = [ForeignKey(entity = TripEntity::class, parentColumns = ["id"], childColumns = ["tripId"], onDelete = ForeignKey.CASCADE)],+ indices = [Index("tripId")]+)+data class TripPingEntity(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val tripId: Long,+ val mac: String,+ val time: Long,+ val rssi: Int,+ val lat: Double,+ val lon: Double+)+/*** A device heard during a trip. Its position is where YOUR phone was when the* device's signal was strongest - an approximation of where it was, not a fix.@@ -113,6 +129,12 @@ interface TripDao {@Query("SELECT * FROM trip_points WHERE tripId = :tripId ORDER BY time")suspend fun points(tripId: Long): List<TripPointEntity>+ @Insert+ suspend fun insertPings(pings: List<TripPingEntity>)++ @Query("SELECT * FROM trip_pings WHERE tripId = :tripId ORDER BY time")+ suspend fun pings(tripId: Long): List<TripPingEntity>+@Upsertsuspend fun upsertDevices(devices: List<TripDeviceEntity>)diff --git a/app/src/main/java/com/rfsentinel/app/detect/Category.kt b/app/src/main/java/com/rfsentinel/app/detect/Category.ktindex 5b1dda2..bf20d0f 100644--- a/app/src/main/java/com/rfsentinel/app/detect/Category.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/Category.kt@@ -15,6 +15,8 @@ enum class Category(ALPR("License-plate / traffic enforcement camera", "ALPR", 0xFFB3261E.toInt(), true),AUDIO_SENSOR("Audio / gunshot sensor (Flock Raven, ShotSpotter)", "AUDIO", 0xFF9C2A6B.toInt(), true),PUBLIC_SAFETY("Public-safety vendor gear (Motorola, i-PRO...)", "PUBLIC SAFETY", 0xFFB26A00.toInt(), true),+ /** Zebra / Brother mobile printers: in-car e-ticket printers, but also couriers and field techs. Follows Public safety until set. */+ MOBILE_PRINTER("Mobile printers (Zebra, Brother RuggedJet / PocketJet e-ticket printers)", "PRINTER", 0xFF455A64.toInt(), true),DRONE("Drone (Remote ID / drone maker)", "DRONE", 0xFF1F5FBF.toInt(), true),TRACKER("Item tracker away from its owner", "TRACKER", 0xFF6A3FB5.toInt(), true),GLASSES("Smart / recording glasses", "GLASSES", 0xFF00796B.toInt(), true),diff --git a/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.kt b/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.ktindex 5b39907..df5a8ad 100644--- a/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/FlockNoise.kt@@ -6,7 +6,9 @@ package com.rfsentinel.app.detect* generic "FS-<hex>" name are shared with speakers, scooters, bulbs and meeting-room boxes:* - a module-prefix match is dropped when the device names itself as something else* (a Flock module has no name or a Flock-style one);- * - outside Flock's market (a European preset on, US and Canada off) both are dropped entirely.+ * - outside Flock's market (a European preset on, US and Canada off) both are dropped entirely, and so are the+ * "Possible Flock camera" probe clues (probe shape, module prefix without Flock's element), which ordinary+ * phones and boards also match.* Strong Flock signatures (Penguin / Falcon / Raven names, Flock's own service, the* battery name, XUNTONG ID) are never touched.*/@@ -22,12 +24,15 @@ object FlockNoise {fun isGenericFsName(h: Hit) =h.category == Category.ALPR && h.evidence.contains("generic white-label", ignoreCase = true)+ fun isWeakProbe(h: Hit) =+ h.category == Category.ALPR && h.label.startsWith("Possible Flock camera (probe")+fun filter(hits: List<Hit>, name: String?, flockRegion: Boolean): List<Hit> {val named = name?.trim()?.takeIf { it.isNotEmpty() }return hits.filterNot { h ->when {isCommunityPrefix(h) -> !flockRegion || (named != null && !FLOCK_NAME.containsMatchIn(named))- isGenericFsName(h) -> !flockRegion+ isGenericFsName(h) || isWeakProbe(h) -> !flockRegionelse -> false}}diff --git a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.ktindex ea1c13f..e190c77 100644--- a/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/PatrolCluster.kt@@ -80,7 +80,7 @@ object PatrolCluster {val hits = allHits.filter { it.source != SOURCE }hits.firstOrNull { it.category == Category.BODY_CAM }?.let { return "body camera" }hits.firstOrNull { it.category == Category.ALPR }?.let { return "plate reader" }- val text = listOfNotNull(vendor) + hits.filter { it.category == Category.PUBLIC_SAFETY }.map { it.label }+ val text = listOfNotNull(vendor) + hits.filter { it.category == Category.PUBLIC_SAFETY || it.category == Category.MOBILE_PRINTER }.map { it.label }text.forEach { t -> ROLE_BY_VENDOR.firstOrNull { it.first.containsMatchIn(t) }?.let { return it.second } }if (name != null) ROLE_BY_NAME.firstOrNull { it.first.containsMatchIn(name) }?.let { return it.second }return nulldiff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.ktindex 5f5e469..6905729 100644--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt@@ -249,29 +249,29 @@ object SignatureEngine {// ---- Mobile ticket printers (e-citations) ---------------------------ZEBRA_UUIDS.firstOrNull { it in allShorts }?.let { u ->hits += if (ZEBRA_SERIAL.matches(name)) {- Hit(Category.PUBLIC_SAFETY, "Zebra mobile printer (e-ticket printer in patrol cars)", 50,+ Hit(Category.MOBILE_PRINTER, "Zebra mobile printer (e-ticket printer in patrol cars)", 50,String.format("Service UUID 0x%04X (Zebra)", u) +" and a factory serial-number name \"$name\" - an unrenamed " +"fleet printer. Also used by parking officers, couriers and field technicians","$SIG; Zebra Link-OS BLE app note (default friendly name = serial); field capture")} else {- Hit(Category.PUBLIC_SAFETY, "Zebra printer", 30,+ Hit(Category.MOBILE_PRINTER, "Zebra printer", 30,String.format("Service UUID 0x%04X (Zebra Technologies)", u) +" - common in warehouses, stores and deliveries", SIG)}}if (CID_ZEBRA in a.manufacturerData && ZEBRA_UUIDS.none { it in allShorts }) {- hits += Hit(Category.PUBLIC_SAFETY, "Zebra device (mobile printer or handheld)", 25,+ hits += Hit(Category.MOBILE_PRINTER, "Zebra device (mobile printer or handheld)", 25,"Zebra Technologies company ID 0x01F1 - mobile printers (incl. e-ticket printers) but also " +"store scanners and handhelds", SIG)}if (CID_BROTHER in a.manufacturerData) {// RuggedJet (RJ-) and PocketJet (PJ-) are the mobile models, named after the model by default.- hits += if (BROTHER_MOBILE.containsMatchIn(name)) Hit(Category.PUBLIC_SAFETY, "Brother mobile printer (RuggedJet / PocketJet)", 35,+ hits += if (BROTHER_MOBILE.containsMatchIn(name)) Hit(Category.MOBILE_PRINTER, "Brother mobile printer (RuggedJet / PocketJet)", 35,"Brother Industries company ID 0x0755 and a mobile-printer model name \"$name\" - in-car printers for " +"tickets and reports, but also utility, delivery and field-service vans", SIG)- else Hit(Category.PUBLIC_SAFETY, "Brother printer", 20,+ else Hit(Category.MOBILE_PRINTER, "Brother printer", 20,"Brother Industries company ID 0x0755 - RuggedJet / PocketJet in-car printers, but mostly " +"home and office printers", SIG)}diff --git a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.ktindex 68158c3..3669a29 100644--- a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt@@ -93,9 +93,9 @@ class OnlineWatch(val hit = PoliceAircraft.classify(p, registry, circling, distanceM)seen += PoliceAircraft.Seen(p, hit)if (hit == null) continue- val loud = PoliceAircraft.alerts(hit, distanceM)+ val loud = PoliceAircraft.alerts(hit, distanceM, Prefs.aircraftCircling(context))if (loud && (best == null || hit.confidence > best!!.confidence)) best = hit- reportAircraft(hit, p.hex, p.lat, p.lon, loud, now)+ reportAircraft(hit, p.hex, p.lat, p.lon, loud, now, said(hit, distanceM, me, p))}loiter.prune(now)lastAircraftHit.entries.removeAll { now - it.value > AIRCRAFT_REPEAT_MS }@@ -126,9 +126,9 @@ class OnlineWatch(val hit = PoliceAircraft.classify(p, registry, circling, distanceM, PoliceAircraft.VIA_LOCAL)seen += PoliceAircraft.Seen(p, hit)if (hit == null) continue- val loud = PoliceAircraft.alerts(hit, distanceM)+ val loud = PoliceAircraft.alerts(hit, distanceM, Prefs.aircraftCircling(context))if (loud && (best == null || hit.confidence > best!!.confidence)) best = hit- reportAircraft(hit, p.hex, p.lat, p.lon, loud, now)+ reportAircraft(hit, p.hex, p.lat, p.lon, loud, now, said(hit, distanceM, me, p))}// No position: logged where you are, which is where it was heard; its distance is unknown, so no alert.if (me != null) for (hex in unlocated) PoliceAircraft.heardNearby(hex, registry)?.let {@@ -149,14 +149,19 @@ class OnlineWatch(* Logs an aircraft hit once per aircraft per 20 minutes; [loud] (strong and close, [PoliceAircraft.alerts]) also* alerts, once more when one that was only logged comes close. Called with [loiter] held.*/- private fun reportAircraft(hit: Hit, hex: String, lat: Double, lon: Double, loud: Boolean, now: Long) {+ /** What an aircraft alert says: kind, distance and direction (short voice: the kind only). */+ private fun said(hit: Hit, distanceM: Double?, me: Location?, p: PoliceAircraft.Plane): String? =+ if (com.rfsentinel.app.util.Spoken.short(context)) null else com.rfsentinel.app.util.Spoken.aircraft(+ hit, distanceM, me?.let { com.rfsentinel.app.ui.AircraftActivity.bearing(it.latitude, it.longitude, p.lat, p.lon) })++ private fun reportAircraft(hit: Hit, hex: String, lat: Double, lon: Double, loud: Boolean, now: Long, spoken: String? = null) {val key = if (loud) "$hex!" else hexif (now - (lastAircraftHit[key] ?: 0L) < AIRCRAFT_REPEAT_MS) return// Logged already while it was far: the alert needn't log it again.val loggedRecently = loud && now - (lastAircraftHit[hex] ?: 0L) < AIRCRAFT_REPEAT_MSlastAircraftHit[key] = nowlastAircraftHit[hex] = now- onAlert(Alert(hit, lat, lon, "air:$hex", level = if (loud) WazePolice.Level.LOUD else WazePolice.Level.LOG, log = !loggedRecently))+ onAlert(Alert(hit, lat, lon, "air:$hex", spoken, level = if (loud) WazePolice.Level.LOUD else WazePolice.Level.LOG, log = !loggedRecently))}private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))diff --git a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.ktindex 5d8ce4f..fab807f 100644--- a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt+++ b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt@@ -42,6 +42,16 @@ object PoliceAircraft {RegexOption.IGNORE_CASE)+ /** Government owners (agencies, states, counties, cities, the Crown): not proof of police, but a public-service flight. */+ private val GOV_OWNER = Regex(+ "GOVERNMENT|DEPARTMENT OF|DEPT OF|MINISTRY|STATE OF|COMMONWEALTH OF|PROVINCE OF|COUNTY OF|CITY OF|" ++ "HIS MAJESTY|HER MAJESTY|NATIONAL GUARD|COAST GUARD",+ RegexOption.IGNORE_CASE+ )++ /** The label of an unlisted aircraft circling overhead ([classify]). */+ const val CIRCLING = "Aircraft circling overhead"+@Volatile private var registry: Map<String, Entry>? = nullfun load(context: Context): Map<String, Entry> = registry ?: synchronized(this) {@@ -107,9 +117,15 @@ object PoliceAircraft {if (circling) " It is circling." else "","ADS-B owner / operator (adsb.fi)")}+ p.owner?.takeIf { GOV_OWNER.containsMatchIn(it) }?.let { owner ->+ return Hit(Category.AIRCRAFT, "Government aircraft overhead: ${titleCase(owner)}", if (circling) 85 else 80,+ "${p.registration ?: p.hex.uppercase()} (${p.type ?: "aircraft"}), operated by ${titleCase(owner)}. $where" ++ (if (circling) " It is circling." else "") + " A government owner isn't always police - verify.",+ "ADS-B owner / operator (adsb.fi)")+ }if (circling) {val low = (p.altitudeFt ?: 0) in 1..3_000- return Hit(Category.AIRCRAFT, "Aircraft circling overhead", if (low) 55 else 45,+ return Hit(Category.AIRCRAFT, CIRCLING, if (low) 55 else 45,"${p.registration ?: p.callsign ?: p.hex.uppercase()} (${p.type ?: "aircraft"}) keeps circling over the same area. $where " +"Police and surveillance flights orbit like this, but so do news, training and survey flights - verify.","$via track (loiter detection)")@@ -136,9 +152,13 @@ object PoliceAircraft {/** Closer than this (ground distance) a strong match alerts; farther, or weaker, it's only logged and listed. */const val ALERT_M = 5_000.0- /** Whether a hit alerts (sound, voice, notification): a strong match within [ALERT_M]; otherwise it's only logged. */- fun alerts(hit: Hit, distanceM: Double?): Boolean =- hit.confidence >= com.rfsentinel.app.detect.Tier.STRONG.min && distanceM != null && distanceM <= ALERT_M+ /**+ * Whether a hit alerts (sound, voice, notification): a strong match (police, government) within [ALERT_M], or with+ * [circlingOn] (Settings) any aircraft circling within it; otherwise it's only logged.+ */+ fun alerts(hit: Hit, distanceM: Double?, circlingOn: Boolean = false): Boolean =+ distanceM != null && distanceM <= ALERT_M &&+ (hit.confidence >= com.rfsentinel.app.detect.Tier.STRONG.min || (circlingOn && hit.label == CIRCLING))const val VIA_ONLINE = "ADS-B (adsb.fi / adsb.lol)"const val VIA_LOCAL = "ADS-B heard by your RTL-SDR"diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.ktindex 137b3d2..6f37624 100644--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt@@ -248,7 +248,7 @@ class WazeWatch(val viewM = maxOf(Prefs.wazeViewKm(context) * 1000.0, alertM) // never narrower than the alert rangeval aheadOnly = Prefs.wazeAheadOnly(context)val approachOn = Prefs.wazeApproach(context)- val threshold = Prefs.alertThreshold(context)+ val threshold = Prefs.alertThreshold(context, com.rfsentinel.app.detect.Category.POLICE_REPORT)val levels = WazePolice.Type.entries.associateWith { Prefs.wazeLevel(context, it) }val shown = ArrayList<WazePolice.Shown>(known.size)diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25History.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25History.ktnew file mode 100644index 0000000..543b4f0--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25History.kt@@ -0,0 +1,84 @@+package com.rfsentinel.app.sdr++import android.content.Context+import com.rfsentinel.app.util.Prefs+import java.io.File+import java.util.Calendar+import java.util.concurrent.Executors++/**+ * Every P25 call the control channel granted, kept on the phone for [Prefs.p25LogDays] days (Settings › RTL-SDR+ * radio) so talkgroup activity can be looked back on and exported without internet or a RadioReference list.+ * One CSV line per call start, written off the SDR thread. Signalling only: no voice.+ */+object P25History {++ /** One call: [tg] null for a private call to radio [target]. [site] is "system-rfss-site" when the site was heard. */+ data class Call(val time: Long, val tg: Int?, val target: Int?, val source: Int?, val channel: Int?, val hz: Long?,+ val emergency: Boolean, val encrypted: Boolean, val site: String?)++ /** Per talkgroup over the kept days, for the history screen. [byHour]: calls in each hour of the day (0-23). */+ data class Summary(val tg: Int?, val target: Int?, val lastDay: Int, val lastWeek: Int, val all: Int, val lastAt: Long,+ val radios: Int, val emergency: Boolean, val encrypted: Boolean, val byHour: IntArray) {+ /** The hour of the day with the most calls, or null with none. */+ val busiestHour get() = byHour.indices.maxByOrNull { byHour[it] }?.takeIf { byHour[it] > 0 }+ }++ const val HEADER = "time,talkgroup,private_to,radio,channel,frequency_hz,emergency,encrypted,site"+ private const val DAY_MS = 24 * 60 * 60_000L+ private const val PRUNE_EVERY_MS = 60 * 60_000L++ private val io = Executors.newSingleThreadExecutor()+ @Volatile private var lastPrune = 0L++ fun file(context: Context) = File(context.filesDir, "p25/calls.csv")++ /** Adds [calls] in the background; trims to the kept days about once an hour. Off (0 days): nothing is kept. */+ fun append(context: Context, calls: List<Call>) {+ if (calls.isEmpty()) return+ val app = context.applicationContext+ io.execute {+ runCatching {+ val days = Prefs.p25LogDays(app)+ val f = file(app)+ if (days <= 0) { f.delete(); return@runCatching }+ f.parentFile?.mkdirs()+ if (!f.exists()) f.writeText(HEADER + "\n")+ f.appendText(calls.joinToString("") { line(it) + "\n" })+ val now = System.currentTimeMillis()+ if (now - lastPrune > PRUNE_EVERY_MS) { lastPrune = now; prune(f, now - days * DAY_MS) }+ }+ }+ }++ /** Every kept call, oldest first. Call off the main thread. */+ fun read(context: Context): List<Call> = file(context).takeIf { it.exists() }?.useLines { lines ->+ lines.drop(1).mapNotNull(::parse).toList()+ }.orEmpty()++ private fun prune(f: File, cutoff: Long) {+ val kept = f.readLines().drop(1).filter { (it.substringBefore(',').toLongOrNull() ?: 0L) >= cutoff }+ f.writeText((listOf(HEADER) + kept).joinToString("\n", postfix = "\n"))+ }++ internal fun line(c: Call) = listOf(c.time, c.tg ?: "", c.target ?: "", c.source ?: "", c.channel ?: "", c.hz ?: "",+ if (c.emergency) 1 else 0, if (c.encrypted) 1 else 0, c.site.orEmpty()).joinToString(",")++ internal fun parse(line: String): Call? {+ val f = line.split(',')+ if (f.size < 9) return null+ return Call(f[0].toLongOrNull() ?: return null, f[1].toIntOrNull(), f[2].toIntOrNull(), f[3].toIntOrNull(),+ f[4].toIntOrNull(), f[5].toLongOrNull(), f[6] == "1", f[7] == "1", f[8].ifEmpty { null })+ }++ /** Talkgroups (and private calls) by most recent call, counted over the last day, week and everything kept. */+ fun summarize(calls: List<Call>, now: Long): List<Summary> = calls.groupBy { it.tg to (if (it.tg == null) it.target else null) }+ .map { (k, list) ->+ val hours = IntArray(24)+ val cal = Calendar.getInstance()+ for (c in list) { cal.timeInMillis = c.time; hours[cal.get(Calendar.HOUR_OF_DAY)]++ }+ Summary(k.first, k.second, list.count { now - it.time <= DAY_MS }, list.count { now - it.time <= 7 * DAY_MS }, list.size,+ list.maxOf { it.time }, list.mapNotNull { it.source }.toSet().size, list.any { it.emergency }, list.any { it.encrypted }, hours)+ }+ .sortedByDescending { it.lastAt }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.ktindex c53094e..3606c2f 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt@@ -24,6 +24,8 @@ class P25Log {private var messages = 0Lprivate var registrations = 0private var since = 0L+ /** Calls started since [takeCalls], for the kept call log ([P25History]). */+ private val started = ArrayList<P25History.Call>()/** A new control channel: forget the last site. */@Synchronized fun clear(now: Long) {@@ -55,6 +57,8 @@ class P25Log {if (source != null) { g.lastSource = source; g.radios += source }g.emergency = g.emergency || emergencyg.encrypted = encrypted || (g.encrypted && source == null) // an update doesn't say: keep the last grant's+ if (new) started += P25History.Call(now, tg, target, source, channel, channels.hz(channel), emergency, g.encrypted,+ site?.let { s -> listOfNotNull("%03X".format(s.sysId), s.rfss?.toString(), s.site?.toString()).joinToString("-") })return if (new) tg else null}@@ -66,6 +70,9 @@ class P25Log {@Synchronized fun summary() = Summary(site, messages, registrations, since)+ /** The calls started since the last time this was asked, oldest first. */+ @Synchronized fun takeCalls(): List<P25History.Call> = started.toList().also { started.clear() }+companion object {/** A grant or update for a talkgroup heard within this long is the same call going on. */const val CALL_GAP_MS = 10_000Ldiff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex c30ba36..7670e85 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -428,6 +428,7 @@ object SdrRadio {messages++; p25Messages++val now = System.currentTimeMillis()for (tg in p25Log.add(it, now)) onP25Call?.invoke(tg)+ appContext?.let { c -> P25History.append(c, p25Log.takeCalls()) }if (now - lastStatus >= 2_000L && !halted) { lastStatus = now; status = "$deviceLabel · P25 · control channel $where · $messages messages" + turnNote() }}if (lost) p25Lock = nulldiff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 54fe8f0..f68ff36 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -762,7 +762,7 @@ class ScanForegroundService : Service() {this, mac, trackerHit.label, a.rssi, now, DeviceRegistry.linkedFrom(mac))) returnif (WhitelistCache.contains(mac)) return- if (!com.rfsentinel.app.detect.FixedRouter.quiet(mac, c.hits, Prefs.alertThreshold(this))) noteLocating(mac)+ if (!com.rfsentinel.app.detect.FixedRouter.quiet(mac, c.hits, Prefs.alertThreshold(this, best.category))) noteLocating(mac)maybeLog(a, best, c.vendor, loc, now)maybeAlert(a, best, c.hits, now, via)@@ -1037,7 +1037,10 @@ class ScanForegroundService : Service() {val vendor = macVendor ?: companyVendors.firstOrNull()// Per-packet rules, the watchlist, matches carried over from a rotated address and the// patrol-vehicle cluster, then fused into one calibrated score.- val raw = SignatureEngine.classify(a) ++ // A network whose name has one of your ignored words (Settings › Ignored network names): listed, never flagged.+ val ignored = a.source == Advert.Source.WIFI && a.wifi?.client != true &&+ a.name?.let { n -> Prefs.ignoredSsidAll(this).any { n.contains(it, ignoreCase = true) } } == true+ val raw = if (ignored) emptyList() else SignatureEngine.classify(a) +OuiWatchlist.hits(a.mac, a.name, listOfNotNull(macVendor) + companyVendors) +OuiWatchlist.advertHits(a) +DeviceRegistry.inheritedHits(a.mac) +@@ -1095,9 +1098,9 @@ class ScanForegroundService : Service() {private fun maybeAlert(a: Advert, best: Hit, hits: List<Hit>, now: Long, via: String? = null) {// Someone else's tracker nearby is normal; trackers only alert when they follow you.if (best.category == Category.TRACKER) return- if (best.listOnly || best.confidence < Prefs.alertThreshold(this)) return+ if (best.listOnly || best.confidence < Prefs.alertThreshold(this, best.category)) return// A shop's router you pass every day: listed and logged, no alert.- if (com.rfsentinel.app.detect.FixedRouter.quiet(a.mac, hits, Prefs.alertThreshold(this))) return+ if (com.rfsentinel.app.detect.FixedRouter.quiet(a.mac, hits, Prefs.alertThreshold(this, best.category))) return// Acknowledged from the list: listed and logged, no alert.if (com.rfsentinel.app.data.AlertMutes.isMuted(this, a.mac, now)) returnval window = Prefs.dedupeWindowMs(this)@@ -1463,7 +1466,7 @@ class ScanForegroundService : Service() {if (named == null && com.rfsentinel.app.sdr.RadioReference.ready(this)) (lastLocation ?: lastFix)?.let { l ->serviceScope.launch { com.rfsentinel.app.sdr.RadioReference.refreshAround(this@ScanForegroundService, l.latitude, l.longitude) }}- val threshold = Prefs.alertThreshold(this)+ val threshold = Prefs.alertThreshold(this, Category.RADIO)val trend = com.rfsentinel.app.sdr.RadioLog.observe(e, name, Prefs.radioTrendDb(this), now)val cell = e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.CELLULAR_UPLINKif (trend != null && e.confidence >= threshold && via == null) {@@ -1544,7 +1547,7 @@ class ScanForegroundService : Service() {"Heard on the site's control channel: the radios may be anywhere the site covers, not necessarily near you."val hit = Hit(Category.RADIO, "Talkgroup active: $called", P25_CONFIDENCE, detail, "P25 control channel (signalling only, no voice)")radioDetection(hit, "P25 TG $tg", 0, detail, System.currentTimeMillis(), "p25:$tg", "Talkgroup $called active",- P25_CONFIDENCE >= Prefs.alertThreshold(this))+ P25_CONFIDENCE >= Prefs.alertThreshold(this, Category.RADIO))}/** "154.43" for 154.430 MHz: three decimals, trailing zeros dropped, read well by the voice. */@@ -1588,7 +1591,9 @@ class ScanForegroundService : Service() {}// An aircraft or Waze report hidden from the list (swiped left): logged, no alert.if (alert.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&- hit.confidence >= Prefs.alertThreshold(this) && !com.rfsentinel.app.data.AlertMutes.isMuted(this, alert.key, now)) {+ // A circling aircraft you asked to hear about (Settings) alerts below the threshold: it's never strong.+ (hit.confidence >= Prefs.alertThreshold(this, hit.category) || hit.label == com.rfsentinel.app.online.PoliceAircraft.CIRCLING) &&+ !com.rfsentinel.app.data.AlertMutes.isMuted(this, alert.key, now)) {val off = alertsOff(hit.category)NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon, online = alert.key,banner = AlertKind.BANNER !in off)@@ -1627,7 +1632,7 @@ class ScanForegroundService : Service() {))}- if (a.confidence >= Prefs.alertThreshold(this)) {+ if (a.confidence >= Prefs.alertThreshold(this, hit.category)) {val off = alertsOff(hit.category)NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java, banner = AlertKind.BANNER !in off)AlertPlayer.play(this, hit.tier, a.title, off = off)@@ -1693,7 +1698,7 @@ class ScanForegroundService : Service() {))}- if (hit.confidence >= Prefs.alertThreshold(this)) {+ if (hit.confidence >= Prefs.alertThreshold(this, hit.category)) {val off = alertsOff(hit.category)NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)AlertPlayer.play(this, hit.tier, spoken, off = off)@@ -1718,7 +1723,7 @@ class ScanForegroundService : Service() {))}- if (a.confidence >= Prefs.alertThreshold(this)) {+ if (a.confidence >= Prefs.alertThreshold(this, hit.category)) {val off = alertsOff(hit.category)NotificationHelper.sendMapAlert(this, "cell:" + a.key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)AlertPlayer.play(this, hit.tier, "Cell network warning", off = off)@@ -1774,12 +1779,12 @@ class ScanForegroundService : Service() {val devices = DeviceRegistry.snapshot()// Only devices still in range: the bubble clears as soon as a threat is gone.val flagged = devices.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it) }- val threshold = Prefs.alertThreshold(ctx)val top = flagged.maxOfOrNull { it.best!!.confidence } ?: 0+ val probable = flagged.any { it.best!!.confidence >= Prefs.alertThreshold(ctx, it.best!!.category) }val cellWarning = CellMonitor.lastAnomaly?.takeIf { System.currentTimeMillis() - it.first < 15 * 60_000L }val level = when {flagged.any { it.following } || top >= 80 -> com.rfsentinel.app.ui.ThreatBubble.Level.DANGER- top >= threshold || cellWarning != null -> com.rfsentinel.app.ui.ThreatBubble.Level.PROBABLE+ probable || cellWarning != null -> com.rfsentinel.app.ui.ThreatBubble.Level.PROBABLEflagged.isNotEmpty() -> com.rfsentinel.app.ui.ThreatBubble.Level.WEAKelse -> com.rfsentinel.app.ui.ThreatBubble.Level.CLEAR}diff --git a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.ktindex f83bd72..88b8b45 100644--- a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt+++ b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt@@ -5,6 +5,7 @@ import android.location.Locationimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.TripDeviceEntityimport com.rfsentinel.app.data.TripEntity+import com.rfsentinel.app.data.TripPingEntityimport com.rfsentinel.app.data.TripPointEntityimport com.rfsentinel.app.detect.Hitimport java.text.SimpleDateFormat@@ -33,6 +34,8 @@ object TripRecorder {*/private const val DEVICES_IN_MEMORY = 2_000private const val DEVICE_IDLE_MS = 10 * 60_000L+ /** Every-sighting mode: at most one sighting per device this often (a scan hears a device several times a second). */+ private const val PING_INTERVAL_MS = 3_000Ldata class LivePoint(val time: Long, val lat: Double, val lon: Double)@@ -47,6 +50,10 @@ object TripRecorder {private val points = mutableListOf<LivePoint>() // whole trace (for the live map)private val pendingPoints = mutableListOf<TripPointEntity>()+ /** Every-sighting mode ([com.rfsentinel.app.util.Prefs.traceEveryPing]), read when the trip starts. */+ @Volatile private var everyPing = false+ private val pendingPings = mutableListOf<TripPingEntity>()+ private val lastPing = ConcurrentHashMap<String, Long>()private val devices = ConcurrentHashMap<String, TripDeviceEntity>()private val dirty = ConcurrentHashMap.newKeySet<String>()/** Devices let go from memory (all written), and which of them are flagged, for the totals. */@@ -75,6 +82,8 @@ object TripRecorder {val id = dao.insertTrip(TripEntity(name = label, startTime = now))synchronized(this) {tripDao = dao+ everyPing = com.rfsentinel.app.util.Prefs.traceEveryPing(context)+ pendingPings.clear(); lastPing.clear()points.clear(); pendingPoints.clear()devices.clear(); dirty.clear(); evicted.clear(); evictedFlagged.clear()distanceM = 0.0@@ -89,6 +98,7 @@ object TripRecorder {val id: Long,val points: List<TripPointEntity>,val devices: List<TripDeviceEntity>,+ val pings: List<TripPingEntity>,val distanceM: Double,val totalPoints: Int,val deviceCount: Int,@@ -104,12 +114,12 @@ object TripRecorder {val id = activeTripId ?: return nullval changed = takeDirty()Final(- id, pendingPoints.toList(), changed, distanceM, points.size,+ id, pendingPoints.toList(), changed, pendingPings.toList(), distanceM, points.size,deviceCount(), flaggedCount()).also {// Drop the live trace too: the process often outlives the scan (and a swiped-away// app), and the live map would keep drawing the old route.- points.clear(); pendingPoints.clear()+ points.clear(); pendingPoints.clear(); pendingPings.clear(); lastPing.clear()devices.clear(); dirty.clear(); evicted.clear(); evictedFlagged.clear()distanceM = 0.0activeTripId = null@@ -121,6 +131,7 @@ object TripRecorder {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) }+ if (f.pings.isNotEmpty()) f.pings.chunked(500).forEach { dao.insertPings(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)@@ -192,6 +203,12 @@ object TripRecorder {)}dirty += mac+ if (everyPing && loc != null && now - (lastPing[mac] ?: 0L) >= PING_INTERVAL_MS) {+ lastPing[mac] = now+ synchronized(this) {+ if (activeTripId == id) pendingPings += TripPingEntity(tripId = id, mac = mac, time = now, rssi = rssi, lat = loc.latitude, lon = loc.longitude)+ }+ }}/** A device let go from memory earlier, read back from the database (null when it is new). */@@ -225,18 +242,21 @@ object TripRecorder {val id: Longval newPoints: List<TripPointEntity>val changed: List<TripDeviceEntity>+ val newPings: List<TripPingEntity>val totalPoints: Intval distance: Doublesynchronized(this) {id = activeTripId ?: return@withLocknewPoints = pendingPoints.toList(); pendingPoints.clear()changed = takeDirty()+ newPings = pendingPings.toList(); pendingPings.clear()totalPoints = points.sizedistance = 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) }// Stopped while writing: the trip's final totals come from persist (which waits for this), not from here.if (activeTripId != id) return@withLockevictIdle(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.ktindex 9446b20..c8ce4b8 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -163,6 +163,45 @@ class SettingsActivity : AppCompatActivity() {.show()}+ private fun editIgnoredSsids() {+ val pad = (20 * resources.displayMetrics.density).toInt()+ val input = android.widget.EditText(this).apply {+ setText(Prefs.ignoredSsidWords(this@SettingsActivity).joinToString("\n"))+ hint = "One word per line, e.g. Rogers"+ minLines = 3; maxLines = 10; gravity = android.view.Gravity.TOP+ inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO+ }+ val picked = Prefs.ignoredSsidPresets(this)+ val presets = Prefs.ISP_PRESETS.map { (region, words) ->+ region to com.google.android.material.checkbox.MaterialCheckBox(this).apply {+ text = "$region telecoms\n" + words.joinToString(", ")+ isChecked = region in picked+ }+ }+ MaterialAlertDialogBuilder(this)+ .setTitle("Ignored network names")+ .setMessage("WiFi networks whose name contains one of these words are never flagged.")+ .setView(android.widget.LinearLayout(this).apply {+ orientation = android.widget.LinearLayout.VERTICAL+ setPadding(pad, 0, pad, 0)+ presets.forEach { addView(it.second) }+ addView(input)+ })+ .setPositiveButton("Save") { _, _ ->+ Prefs.setIgnoredSsidPresets(this, presets.filter { it.second.isChecked }.map { it.first }.toSet())+ Prefs.setIgnoredSsidWords(this, input.text.split(',', '\n').map { it.trim() }.filter { it.isNotEmpty() }.distinct())+ updateIgnoredSsidsButton()+ }+ .setNegativeButton("Cancel", null)+ .show()+ }++ private fun updateIgnoredSsidsButton() {+ val n = Prefs.ignoredSsidAll(this).size+ binding.ignoredSsidsButton.text = if (n == 0) "Ignored network names" else "Ignored network names · $n"+ }+private fun updateMusicButton() {val app = Prefs.carMusicApp(this)binding.carMusicButton.text = app?.let { "Music app: " + com.rfsentinel.app.receiver.CarMusic.label(this, it) } ?: "Choose music app"@@ -521,6 +560,8 @@ class SettingsActivity : AppCompatActivity() {"• Call out again: speaks at 1 km, 500 m and 200 m as a report gets closer (voice alerts on, or in the car).\n" +"• Each kind of report has its own level: sound and voice, notification only, or silent (list and map only).\n" +"• Pull the list down, or use the menu, to check right now. Waze status shows what is sent, and when.\n\n" ++ "Mobile printers: Zebra and Brother RuggedJet / PocketJet printers, the e-ticket printers in patrol cars, " ++ "but also used by couriers, parking officers and field technicians. Until you set it, it follows Public safety.\n\n" +"Card skimmers: the Bluetooth modules built into gas-pump and ATM skimmers (HC-05 / HC-06 style names). " +"Hacking tools (off by default): Flipper Zero, Pwnagotchi, WiFi Pineapple, deauthers, evil twin WiFi " +"networks (one network name, two makers, one open) and Bluetooth pairing-pop-up spam floods.\n\n" +@@ -978,6 +1019,9 @@ class SettingsActivity : AppCompatActivity() {"Bluetooth scans.")info(binding.rtl5gSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS. Experimental.")info(binding.usbLightSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS: the light blinks with received traffic.")+ info(binding.traceEveryPingSwitch, "A trace normally places each device once, where its signal was strongest. On: it also " ++ "keeps every time it was heard (up to one every 3 s) with your position then, drawn as small dots on the trace map. " ++ "Uses much more storage on long drives; takes effect from the next trace.")info(binding.pinpointSwitch, "Works out where a flagged device is from many readings as you move (GPS runs precise every second while one is in range).")info(binding.pinpointAlertsSwitch, "Pinpoints and shows the live read card only for devices that alerted you, not for every flagged device (a shop's router you pass daily).")info(binding.liveExportSwitch, "Keeps a live copy of matches, devices and radio hits in a folder other apps can read.")@@ -986,6 +1030,10 @@ class SettingsActivity : AppCompatActivity() {info(binding.exportAllButton, "CSV, JSON, KML, GPX or GeoJSON.")info(binding.forgetHistoryButton, "New / returning status, detect counts and the remembered cell towers start over. Favorites are kept.")info(binding.openWhitelistButton, "Trusted devices: never flagged, and hidden from the list when you choose.")+ info(binding.ignoredSsidsButton, "WiFi networks whose name contains one of these words are never flagged, " ++ "for example carriers' home routers (Rogers, Bell) that look like vehicle routers. Matches part of a name, any case.\n\n" ++ "Tick Canada or United States telecoms to add their usual router names in one go (off by default). " ++ "Carrier hotspots in patrol cars can carry these names too, so they won't be flagged either.")}// ---- Search ----------------------------------------------------------------------------@@ -1332,7 +1380,13 @@ class SettingsActivity : AppCompatActivity() {lines("Watch these talkgroups", "1234 Sheriff dispatch\n2001", Prefs.p25Talkgroups(this),"P25: alerts when a call starts on one of them, and names them on the P25 talkgroups screen. One per line: the " +"talkgroup number, with an optional name.") { Prefs.setP25Talkgroups(this, it) }- val talkgroupViews = listOf(box.getChildAt(box.childCount - 2), box.getChildAt(box.childCount - 1))+ slider(0, 60, Prefs.p25LogDays(this), { if (it == 0) "Keep the P25 call log: off" else "Keep the P25 call log: $it days" }) {+ Prefs.setP25LogDays(this, it)+ }+ info(box.getChildAt(box.childCount - 2), "Every call the control channel grants (time, talkgroup, radio, channel) is kept on the " ++ "phone this long, for P25 talkgroups › History and Export: no internet or talkgroup list needed. About 1 MB per busy day. " ++ "0 keeps nothing and deletes the log.", "Keep the P25 call log")+ val talkgroupViews = (box.childCount - 4 until box.childCount).map { box.getChildAt(it) }var sweepViews = emptyList<View>() // the sweep's own settings, belowshowSdrOptions = {val ticked = listOf(sweepBox, adsbBox, p25Box).count { it.isChecked }@@ -1585,7 +1639,7 @@ class SettingsActivity : AppCompatActivity() {val actions = Prefs.SWIPE_ACTIONSfor ((i, right) in listOf(true, false).withIndex()) {val label = if (right) "Swipe right on an alert" else "Swipe left on an alert"- val swipe = choiceRow(label, listOf("Mute / unmute", "Hide", "None"), actions.indexOf(Prefs.swipeAction(this, right))) {+ val swipe = choiceRow(label, listOf("Mute / unmute", "Hide", "None", "Whitelist", "Watchlist"), actions.indexOf(Prefs.swipeAction(this, right))) {Prefs.setSwipeAction(this, right, actions[it])}section.addView(infoRow(swipe, "What swiping a flagged row of the main list does. Both sides can do the same thing.\n\n" +@@ -1593,6 +1647,8 @@ class SettingsActivity : AppCompatActivity() {"Hide: a flagged device or radio transmission stays listed as an ordinary one, a Waze report or an aircraft " +"leaves the list. No alerts from it for 30 min or until the scan stops, then it comes back as it was. " +"Undo at the bottom puts it back at once.\n\n" ++ "Whitelist / Watchlist: asks to add the device to your whitelist (never flagged) or watchlist, as on its page. " ++ "Devices only.\n\n" +"None: that swipe does nothing. Aircraft and radio rows have no mute: only Hide works on them.", label), at + 2 + i)}}@@ -1896,6 +1952,14 @@ class SettingsActivity : AppCompatActivity() {orientation = android.widget.LinearLayout.VERTICALsetPadding((24 * dp).toInt(), 0, 0, (4 * dp).toInt())}+ val own = Prefs.categoryThreshold(this, c)+ val level = choiceRow("Alert from", listOf("Alerts setting", "Weak", "Probable", "Strong only"),+ when { own == null -> 0; own < 50 -> 1; own < 80 -> 2; else -> 3 }) {+ Prefs.setCategoryThreshold(this, c, listOf(null, 0, 50, 80)[it])+ }+ box.addView(level)+ info(level, "How sure a match must be before this category alerts you. \"Alerts setting\" follows Settings › Alerts; " ++ "pick Weak, Probable or Strong only to set this category on its own. Weaker matches are still listed.", "Alert from")box.addView(android.widget.TextView(this).apply {text = "Alerts you with"setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.text_caption))@@ -1958,6 +2022,11 @@ class SettingsActivity : AppCompatActivity() {setOnCheckedChangeListener { _, v -> Prefs.setAircraftOnline(this@SettingsActivity, v) }}, "Asks adsb.fi / adsb.lol every minute for aircraft near a position rounded to about 1 km. Turn off to use only " +"the aircraft your RTL-SDR hears itself (Settings › RTL-SDR radio › ADS-B aircraft receiver): nothing leaves the phone."))+ box.addView(detectRow(SwitchMaterial(this).apply {+ text = "Alert for circling aircraft"; isChecked = Prefs.aircraftCircling(this@SettingsActivity)+ setOnCheckedChangeListener { _, v -> Prefs.setAircraftCircling(this@SettingsActivity, v) }+ }, "Police and government aircraft within 5 km always alert. Turn this on to also hear about any other aircraft " ++ "circling within 5 km (news, training, survey and unlisted police flights orbit too). Off: they're only listed and logged."))val radiusText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }fun showRadius(km: Int) { radiusText.text = "Look for aircraft within ${com.rfsentinel.app.util.Units.km(km)}" }val km = Prefs.aircraftRadiusKm(this)@@ -2573,6 +2642,7 @@ class SettingsActivity : AppCompatActivity() {binding.pinpointSwitch.isChecked = Prefs.pinpointFlagged(this)binding.pinpointAlertsSwitch.isChecked = Prefs.pinpointAlertsOnly(this)binding.autoRecordSwitch.isChecked = Prefs.autoRecordTrace(this)+ binding.traceEveryPingSwitch.isChecked = Prefs.traceEveryPing(this)binding.ouiSpyRelaySwitch.isChecked = Prefs.ouiSpyRelayAll(this)binding.ouiSpyPhoneBleSwitch.isChecked = Prefs.ouiSpyPhoneBle(this)binding.screenModeGroup.check(when (Prefs.screenMode(this)) {@@ -2662,6 +2732,8 @@ class SettingsActivity : AppCompatActivity() {// Lists, tools & about (moved here from the main screen's menu).binding.openWatchlistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ouilist.OuiListActivity::class.java)) }binding.openWhitelistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.whitelist.WhitelistActivity::class.java)) }+ binding.ignoredSsidsButton.setOnClickListener { editIgnoredSsids() }+ updateIgnoredSsidsButton()binding.checkUpdateButton.setOnClickListener { com.rfsentinel.app.util.UpdateChecker.check(this) }binding.aboutButton.setOnClickListener { com.rfsentinel.app.ui.AboutDialog.show(this) }binding.exportCrashLogButton.setOnClickListener { com.rfsentinel.app.util.CrashLog.share(this) }@@ -2857,6 +2929,7 @@ class SettingsActivity : AppCompatActivity() {Prefs.setPinpointFlagged(this, binding.pinpointSwitch.isChecked)Prefs.setPinpointAlertsOnly(this, binding.pinpointAlertsSwitch.isChecked)Prefs.setAutoRecordTrace(this, binding.autoRecordSwitch.isChecked)+ Prefs.setTraceEveryPing(this, binding.traceEveryPingSwitch.isChecked)Prefs.setOuiSpyRelayAll(this, binding.ouiSpyRelaySwitch.isChecked)Prefs.setOuiSpyPhoneBle(this, binding.ouiSpyPhoneBleSwitch.isChecked)Prefs.setScreenMode(this, when (binding.screenModeGroup.checkedRadioButtonId) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.ktindex 53efdf9..bdbb5fd 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt@@ -149,6 +149,7 @@ class DetectionLogActivity : AppCompatActivity() {Category.ALPR -> "Plate cameras"Category.AUDIO_SENSOR -> "Audio sensors"Category.PUBLIC_SAFETY -> "Public safety"+ Category.MOBILE_PRINTER -> "Printers"Category.DRONE -> "Drones"Category.TRACKER -> "Trackers"Category.GLASSES -> "Glasses"diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex 3a44d52..1a842fe 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -1480,11 +1480,13 @@ class MapFragment : Fragment() {trip = tval points = dao.points(id).map { it.lat to it.lon }val devices = dao.devices(id)+ val pings = dao.pings(id)if (!alive) return@launchval r = rfr?.safe("trip") {r.drawTrace(points, RfMap.PAST_TRACE_COLOR)r.drawPins(devices.filter { it.lat != null && filter.matches(it) }.map { it.toPin() })+ r.drawPings(pings)}val placed = devices.filter { it.lat != null }for ((f, chip) in filterChips) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.ktindex 4f79b14..9030874 100644--- a/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt@@ -2,6 +2,8 @@ package com.rfsentinel.app.uiimport android.annotation.SuppressLintimport android.os.Bundle+import android.view.Menu+import android.view.MenuItemimport android.text.format.DateUtilsimport android.view.LayoutInflaterimport android.view.View@@ -16,24 +18,31 @@ import androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.rfsentinel.app.databinding.ActivityLogBindingimport com.rfsentinel.app.databinding.ItemDetectionBinding+import com.rfsentinel.app.sdr.P25Historyimport com.rfsentinel.app.sdr.P25Logimport com.rfsentinel.app.sdr.P25Tsbkimport com.rfsentinel.app.sdr.SdrRadioimport com.rfsentinel.app.util.Prefsimport com.rfsentinel.app.util.applySystemBarInsets+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.delay+import kotlinx.coroutines.withContextimport kotlinx.coroutines.launchimport java.util.Locale/*** The P25 control channel the SDR follows (Settings > RTL-SDR radio > P25 control channel): its site, and the* talkgroups and private calls granted a channel there, most recent first. Watched talkgroups are named and- * marked. Signalling only: nothing here is voice.+ * marked. History: the kept call log ([P25History]) per talkgroup over the last day and week, and its busiest hour.+ * Signalling only: nothing here is voice.*/class P25Activity : AppCompatActivity() {private lateinit var binding: ActivityLogBindingprivate var rows: List<P25Log.Row> = emptyList()+ /** History mode: the kept log per talkgroup, read every [HISTORY_MS] (null: showing the live control channel). */+ private var history: List<P25History.Summary>? = null+ private var historyAt = 0Lprivate var watched: Map<Int, String> = emptyMap()private val header by lazy {TextView(this).apply {@@ -43,11 +52,12 @@ class P25Activity : AppCompatActivity() {}private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {- override fun getItemCount() = rows.size+ override fun getItemCount() = history?.size ?: rows.sizeoverride fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {+ history?.let { bindHistory(ItemDetectionBinding.bind(holder.itemView), it[position]); return }val r = rows[position]ItemDetectionBinding.bind(holder.itemView).apply {val name = r.tg?.let { watched[it] }@@ -91,10 +101,56 @@ class P25Activity : AppCompatActivity() {override fun onSupportNavigateUp(): Boolean { finish(); return true }+ override fun onCreateOptionsMenu(menu: Menu): Boolean {+ menu.add(0, MENU_HISTORY, 0, if (history == null) "History" else "Live")+ .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)+ menu.add(0, MENU_EXPORT, 1, "Export call log")+ return true+ }++ override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {+ MENU_HISTORY -> {+ history = if (history == null) emptyList() else null+ historyAt = 0L+ title = if (history == null) "P25 talkgroups" else "P25 history"+ invalidateOptionsMenu(); refresh(); true+ }+ MENU_EXPORT -> { exportLog(); true }+ else -> super.onOptionsItemSelected(item)+ }++ private fun exportLog() = lifecycleScope.launch {+ val text = withContext(Dispatchers.IO) { P25History.file(this@P25Activity).takeIf { it.exists() }?.readText() }+ if (text == null || text.lines().size <= 2) {+ android.widget.Toast.makeText(this@P25Activity, "No calls logged yet", android.widget.Toast.LENGTH_LONG).show()+ return@launch+ }+ com.rfsentinel.app.util.Exporter.share(this@P25Activity, "rf_sentinel_p25_calls_${com.rfsentinel.app.util.Exporter.stamp()}.csv",+ text, "text/csv", "Export P25 call log")+ }++ private fun bindHistory(b: ItemDetectionBinding, h: P25History.Summary) {+ val name = h.tg?.let { watched[it] }+ b.labelText.text = listOfNotNull(h.tg?.let { "Talkgroup $it" } ?: "Private call to radio ${h.target}", name?.ifEmpty { "watched" },+ "EMERGENCY".takeIf { h.emergency }, "encrypted".takeIf { h.encrypted }).joinToString(" · ")+ b.labelText.setTextColor(when {+ h.emergency -> EMERGENCY+ name != null -> ChipStyle.accent(this).first+ else -> b.macText.currentTextColor+ })+ b.macText.text = "${h.lastDay} today · ${h.lastWeek} this week · ${h.all} kept"+ b.metaText.text = listOfNotNull(+ h.busiestHour?.let { String.format(Locale.US, "busiest %02d:00", it) },+ "${h.radios} radio${if (h.radios == 1) "" else "s"}",+ DateUtils.getRelativeTimeSpanString(h.lastAt, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)+ ).joinToString(" · ")+ }+@SuppressLint("NotifyDataSetChanged")private fun refresh() {watched = P25Log.watched(Prefs.p25Talkgroups(this))val q = binding.searchInput.text?.toString()?.trim().orEmpty()+ if (history != null) { refreshHistory(q); return }rows = SdrRadio.p25Log.rows().filter { r ->q.isEmpty() || listOfNotNull(title(r), r.tg?.let { watched[it] }, r.lastSource?.toString()).any { it.contains(q, ignoreCase = true) }}@@ -119,7 +175,39 @@ class P25Activity : AppCompatActivity() {binding.emptyText.visibility = if (empty != null) View.VISIBLE else View.GONE}+ private var all: List<P25History.Summary> = emptyList()++ @SuppressLint("NotifyDataSetChanged")+ private fun refreshHistory(q: String) {+ val now = System.currentTimeMillis()+ if (now - historyAt >= HISTORY_MS) {+ historyAt = now+ lifecycleScope.launch {+ all = withContext(Dispatchers.IO) { P25History.summarize(P25History.read(this@P25Activity), System.currentTimeMillis()) }+ if (history != null) refreshHistory(binding.searchInput.text?.toString()?.trim().orEmpty())+ }+ }+ history = all.filter { h ->+ q.isEmpty() || listOfNotNull(h.tg?.toString(), h.target?.toString(), h.tg?.let { watched[it] }).any { it.contains(q, ignoreCase = true) }+ }+ val days = Prefs.p25LogDays(this)+ header.text = if (days == 0) "The call log is off (Settings › RTL-SDR radio › Keep the P25 call log)."+ else "Calls kept for $days days: ${all.sumOf { it.all }} calls, ${all.size} talkgroups / private calls."+ adapter.notifyDataSetChanged()+ val empty = when {+ history!!.isNotEmpty() -> null+ q.isNotEmpty() && all.isNotEmpty() -> "Nothing matches."+ else -> "No calls logged yet.\nCalls are kept as the control channel grants them while P25 runs."+ }+ binding.recyclerView.visibility = if (empty == null) View.VISIBLE else View.GONE+ binding.emptyText.text = empty.orEmpty()+ binding.emptyText.visibility = if (empty != null) View.VISIBLE else View.GONE+ }+companion object {+ private const val MENU_HISTORY = 1+ private const val MENU_EXPORT = 2+ private const val HISTORY_MS = 30_000Lprivate val EMERGENCY = 0xFFD0503C.toInt()/** "Talkgroup 1234", or "Private call to radio 123456". */diff --git a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt b/app/src/main/java/com/rfsentinel/app/ui/RfMap.ktindex f28c06e..2258624 100644--- a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt@@ -50,6 +50,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngineprivate const val DEVICES = "rf-devices"; private const val DOTS = "rf-device-dots"; private const val LABELS = "rf-device-labels"private const val WAZE = "rf-waze"; private const val DRONE_OPS = "rf-drone-ops"; private const val DRONES = "rf-drones"private const val AIRCRAFT = "rf-aircraft"+ private const val PINGS = "rf-pings"private const val WIGLE = "rf-wigle"; private const val WIGLE_COLOR = "#8E24AA"private const val ASKED = "rf-asked"; private const val ASKED_COLOR = "#00897B"private const val NAV_ROUTES = "rf-nav-routes"; private const val NAV_PLACES = "rf-nav-places"@@ -150,7 +151,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine/** Every layer, as map style JSON (the same on both engines). */private fun addLayers(dark: Boolean) {- listOf(NAV_ROUTES, NAV_PLACES, PRECISION, CONES, CAM_CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, DEVICES, WIGLE, ASKED, WAZE, DRONE_OPS, DRONES, AIRCRAFT)+ listOf(NAV_ROUTES, NAV_PLACES, PRECISION, CONES, CAM_CONES, TRACE, DRONE_LINES, TOWERS, CCTV, CAMERAS, PINGS, DEVICES, WIGLE, ASKED, WAZE, DRONE_OPS, DRONES, AIRCRAFT).forEach { map.addSource(it) }fun get(k: String) = a("get", k)val color = a("to-color", get("color"))@@ -201,6 +202,8 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine// Plate, speed and red-light cameras; the ones whose alerts you turned off, faded.layer(CAMERAS, "symbol", minzoom = CAMERAS_MIN_ZOOM, layout = o("icon-image" to get("icon"), *overlap),paint = o("icon-opacity" to get("opacity"))),+ // A saved trace's every sighting of each device (Settings › Log every sighting in traces): small, under the devices.+ layer(PINGS, "circle", paint = o("circle-color" to color, "circle-radius" to 3.0, "circle-opacity" to 0.8)),// Devices: flagged ones bigger and on top, in the same colours as the list.layer(DOTS, "circle", DEVICES, layout = o("circle-sort-key" to a("case", flagged, 1.0, 0.0)),paint = o("circle-color" to color, "circle-radius" to a("case", flagged, 8.0, 5.0),@@ -270,6 +273,14 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine})}+ /** Every sighting of the drawn devices in a saved trace, in each device's colour (draw after [drawPins]). */+ fun drawPings(pings: List<com.rfsentinel.app.data.TripPingEntity>) {+ if (!ready()) return+ set(PINGS, pings.mapNotNull { p ->+ pins[p.mac]?.let { GeoJson.feature(GeoJson.point(p.lat, p.lon), "mac" to p.mac, "color" to hex(it.color)) }+ })+ }+/*** Routes to follow: [lines] as (lat, lon) lists, the one at [selected] on top in blue and the* others grey. Empty clears them.@@ -523,7 +534,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngineval r = 22f * activity.resources.displayMetrics.densityval box = RectF(x - r, y - r, x + r, y + r)val asked = listOf(AIRCRAFT to "hex", WAZE to "id", DRONES to "mac", DRONE_OPS to "mac", DOTS to "mac",- CAMERAS to "id", CCTV to "id", TOWERS to "id", WIGLE to "id", ASKED to "id")+ CAMERAS to "id", CCTV to "id", TOWERS to "id", WIGLE to "id", ASKED to "id", PINGS to "mac")map.query(box, asked) { found ->if (activity.isFinishing || activity.isDestroyed) return@querysafe("tap") { showTapped(found, me) }@@ -546,7 +557,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine(drone + op).firstNotNullOfOrNull { drones[it] }?.let { s ->MapDialogs.showDrone(activity, s.mac, MapDialogs.droneDetails(s, s.remoteId!!)); return}- val here = dots.distinct().mapNotNull { pins[it] }+ val here = (dots + found[10]).distinct().mapNotNull { pins[it] }if (here.isNotEmpty()) { MapDialogs.showPins(activity, here); return }cams.firstNotNullOfOrNull { cameras[it] }?.let { c -> MapDialogs.showKnownCamera(activity, c) { maybeRedrawStatic(force = true) }; return }cctv.firstNotNullOfOrNull { cctvs[it] }?.let { MapDialogs.showCctv(activity, it); return }diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex d9b0ccf..832cf39 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -41,7 +41,8 @@ object Prefs {// ---- Detection ------------------------------------------------------------fun categoryEnabled(context: Context, category: Category): Boolean =- bool(context, "cat_" + category.name, category.defaultEnabled)+ bool(context, "cat_" + category.name,+ if (category == Category.MOBILE_PRINTER) categoryEnabled(context, Category.PUBLIC_SAFETY) else category.defaultEnabled)fun setCategoryEnabled(context: Context, category: Category, value: Boolean) =setBool(context, "cat_" + category.name, value)@@ -196,7 +197,7 @@ object Prefs {(sp(context).getString(if (right) "swipe_right" else "swipe_left", null) ?: if (right) "mute" else "hide").takeIf { it in SWIPE_ACTIONS } ?: "none"fun setSwipeAction(context: Context, right: Boolean, action: String) =sp(context).edit { putString(if (right) "swipe_right" else "swipe_left", action) }- val SWIPE_ACTIONS = listOf("mute", "hide", "none")+ val SWIPE_ACTIONS = listOf("mute", "hide", "none", "whitelist", "watchlist")/** Muted, or snoozed for a while: no alert sound or voice. */fun alertsSilenced(context: Context, now: Long = System.currentTimeMillis()): Boolean =@@ -209,6 +210,14 @@ object Prefs {/** Minimum confidence (0-100) that sounds an alert; weaker matches are only highlighted. */fun alertThreshold(context: Context): Int = int(context, "alert_threshold", 50)fun setAlertThreshold(context: Context, value: Int) = setInt(context, "alert_threshold", value)+ /** [category]'s own threshold (What to detect › its ▾), or null to follow [alertThreshold]. */+ fun categoryThreshold(context: Context, category: Category): Int? =+ int(context, "cat_threshold_" + category.name, -1).takeIf { it >= 0 }+ fun setCategoryThreshold(context: Context, category: Category, value: Int?) = sp(context).edit {+ if (value == null) remove("cat_threshold_" + category.name) else putInt("cat_threshold_" + category.name, value)+ }+ /** The threshold that sounds an alert for [category]: its own if set, else the Alerts setting. */+ fun alertThreshold(context: Context, category: Category): Int = categoryThreshold(context, category) ?: alertThreshold(context)/** Hide what was detected on the lock screen and in the status notification. */fun discreetMode(context: Context): Boolean = bool(context, "discreet_mode", false)@@ -285,6 +294,32 @@ object Prefs {fun aircraftOnline(context: Context): Boolean = bool(context, "aircraft_online", true)fun setAircraftOnline(context: Context, v: Boolean) = setBool(context, "aircraft_online", v)+ /** Traces keep every sighting of a device where you were, not only where it was strongest (off by default: much more data). */+ fun traceEveryPing(context: Context): Boolean = bool(context, "trace_every_ping", false)+ fun setTraceEveryPing(context: Context, v: Boolean) = setBool(context, "trace_every_ping", v)++ /** Words that make a WiFi network never flagged when its name contains one ("Rogers", "Bell"): carriers' home routers. */+ fun ignoredSsidWords(context: Context): List<String> =+ sp(context).getString("ignored_ssid_words", "").orEmpty().split(',', '\n').map { it.trim() }.filter { it.isNotEmpty() }+ fun setIgnoredSsidWords(context: Context, words: List<String>) =+ sp(context).edit { putString("ignored_ssid_words", words.joinToString("\n")) }++ /** Ready-made Ignored network names: the words popular telecoms put in their routers' default names. Off until picked. */+ val ISP_PRESETS = linkedMapOf(+ "Canada" to listOf("Bell", "Rogers", "Telus", "Videotron", "Helix", "Shaw", "Cogeco", "Fido", "Virgin", "Koodo",+ "Eastlink", "Freedom", "SaskTel", "Distributel", "TekSavvy", "Ebox", "Xplore"),+ "United States" to listOf("Xfinity", "ATT", "Spectrum", "Verizon", "Fios", "CenturyLink", "Frontier", "Cox",+ "Optimum", "Windstream", "TMobile", "T-Mobile", "Mediacom", "Sparklight", "GFiber"))+ fun ignoredSsidPresets(context: Context): Set<String> = sp(context).getStringSet("ignored_ssid_presets", emptySet()).orEmpty()+ fun setIgnoredSsidPresets(context: Context, v: Set<String>) = sp(context).edit { putStringSet("ignored_ssid_presets", v) }+ /** Your words plus the picked presets' ([ISP_PRESETS]). */+ fun ignoredSsidAll(context: Context): List<String> =+ (ignoredSsidWords(context) + ignoredSsidPresets(context).flatMap { ISP_PRESETS[it].orEmpty() }).distinct()++ /** Alert (sound, voice) for any aircraft circling close, not only police and government ones (off by default). */+ fun aircraftCircling(context: Context): Boolean = bool(context, "aircraft_circling", false)+ fun setAircraftCircling(context: Context, v: Boolean) = setBool(context, "aircraft_circling", v)+fun aircraftRadiusKm(context: Context): Int = int(context, "aircraft_radius_km", 30).coerceIn(10, 50)fun setAircraftRadiusKm(context: Context, km: Int) = setInt(context, "aircraft_radius_km", km.coerceIn(10, 50))@@ -613,6 +648,9 @@ object Prefs {/** P25 talkgroups to alert on, "1234 Name" a line ([com.rfsentinel.app.sdr.P25Log.watched]). */fun p25Talkgroups(context: Context) = str(context, "p25_talkgroups")fun setP25Talkgroups(context: Context, v: String) = setStr(context, "p25_talkgroups", v)+ /** How many days the P25 call log is kept on the phone (0: not kept). */+ fun p25LogDays(context: Context): Int = int(context, "p25_log_days", 14).coerceIn(0, 60)+ fun setP25LogDays(context: Context, days: Int) = setInt(context, "p25_log_days", days.coerceIn(0, 60))/** Seconds the SDR gives each ticked scan in turn, 30-300: a first P25 search takes up to about 15 s. */fun sdrTurnS(context: Context): Int = int(context, "sdr_turn_s", 60).coerceIn(30, 300)fun setSdrTurnS(context: Context, v: Int) = setInt(context, "sdr_turn_s", v.coerceIn(30, 300))diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.ktindex 5b56af2..e497c1b 100644--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt@@ -40,6 +40,15 @@ object Spoken {return if (km == Math.floor(km)) "${km.toLong()} kilometer${if (km == 1.0) "" else "s"}" else "$km kilometers"}+ /** An aircraft alert said aloud: "Police aircraft overhead", or "Police aircraft, 2 kilometers northeast". */+ fun aircraft(hit: Hit, distanceM: Double?, bearingDeg: Double?): String {+ val word = shortWord(hit)+ if (distanceM == null) return word+ if (distanceM < 500) return "$word overhead"+ val dir = bearingDeg?.let { " " + arrayOf("north", "northeast", "east", "southeast", "south", "southwest", "west", "northwest")[((it + 22.5) / 45).toInt().mod(8)] }.orEmpty()+ return "$word, ${distanceWords(distanceM)}$dir"+ }+/** Where a report is, said aloud; empty when the heading is unknown. */fun sideWords(side: com.rfsentinel.app.online.WazePolice.Side?): String = when (side) {com.rfsentinel.app.online.WazePolice.Side.AHEAD -> "ahead"@@ -70,6 +79,7 @@ object Spoken {Category.ALPR -> "Plate camera"Category.AUDIO_SENSOR -> "Audio sensor"Category.PUBLIC_SAFETY -> if (hit.label.contains("police vehicle", ignoreCase = true)) "Police car" else "Police gear"+ Category.MOBILE_PRINTER -> "Mobile printer"Category.DRONE -> "Drone"Category.TRACKER -> "Tracker"Category.GLASSES -> "Camera glasses"@@ -77,7 +87,12 @@ object Spoken {Category.CELL_ANOMALY -> "Cell warning"Category.RADIO -> "Radio nearby"Category.GNSS -> "GPS warning"- Category.AIRCRAFT -> if (hit.label.startsWith("Police")) "Police aircraft" else "Aircraft circling"+ Category.AIRCRAFT -> when {+ hit.label.startsWith("Police") -> "Police aircraft"+ hit.label.startsWith("Government") -> "Government aircraft"+ hit.label.startsWith("Military") -> "Military aircraft"+ else -> "Aircraft circling"+ }Category.POLICE_REPORT -> "Waze " + (com.rfsentinel.app.online.WazePolice.Type.entries.firstOrNull { hit.label.startsWith(it.singular) }?.singular?.lowercase() ?: "report")Category.SKIMMER -> "Card skimmer"diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex 8cfd494..486b84b 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -901,6 +901,12 @@android:layout_height="wrap_content"android:text="Record a trace whenever scanning starts" />+ <com.google.android.material.switchmaterial.SwitchMaterial+ android:id="@+id/traceEveryPingSwitch"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:text="Log every sighting in traces" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/gpsSwitch"android:layout_width="match_parent"@@ -1019,6 +1025,14 @@android:layout_marginTop="8dp"android:text="Whitelist" />+ <Button+ android:id="@+id/ignoredSsidsButton"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="8dp"+ android:text="Ignored network names" />+<Buttonandroid:id="@+id/checkUpdateButton"style="@style/Widget.MaterialComponents.Button.OutlinedButton"diff --git a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.ktindex ebdf389..6357799 100644--- a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt@@ -67,7 +67,7 @@ class DetectionTest {@Testfun printerVehicleAndScreeningMakersAreWeakClues() {val zebra = best(ble(mfg = mapOf(0x01F1 to bytes(1))))- assertEquals(Category.PUBLIC_SAFETY, zebra?.category)+ assertEquals(Category.MOBILE_PRINTER, zebra?.category)assertEquals(25, zebra?.confidence)// The Zebra printer UUID rule takes over when both are present.assertEquals(30, best(ble(mfg = mapOf(0x01F1 to bytes(1)), uuids = listOf(Advert.uuid16(0xFE79))))?.confidence)@@ -93,7 +93,7 @@ class DetectionTest {@Testfun zebraPrinterNeedsSerialNameToBeProbable() {val fleet = best(ble(name = "XXRBJ000000001", uuids = listOf(Advert.uuid16(0xFE79))))- assertEquals(Category.PUBLIC_SAFETY, fleet?.category)+ assertEquals(Category.MOBILE_PRINTER, fleet?.category)assertEquals(Tier.MEDIUM, fleet?.tier)val renamed = best(ble(name = "Warehouse 3", uuids = listOf(Advert.uuid16(0xFE79))))assertEquals(Tier.WEAK, renamed?.tier)diff --git a/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.kt b/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.ktindex 0763753..e02a642 100644--- a/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/FlockNoiseTest.kt@@ -27,6 +27,9 @@ class FlockNoiseTest {assertTrue(FlockNoise.filter(listOf(liteon, fsName), null, flockRegion = false).isEmpty())assertEquals(listOf(penguin), FlockNoise.filter(listOf(liteon, fsName, penguin), "Penguin-1234567890", false))assertEquals(1, FlockNoise.filter(listOf(fsName), "FS-ABC123", flockRegion = true).size)+ val shape = Hit(Category.ALPR, "Possible Flock camera (probe shape)", 35, "", "")+ assertTrue(FlockNoise.filter(listOf(shape), null, flockRegion = false).isEmpty())+ assertEquals(1, FlockNoise.filter(listOf(shape), null, flockRegion = true).size)}@Testdiff --git a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.ktindex edc6687..27f3dc4 100644--- a/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt+++ b/app/src/test/java/com/rfsentinel/app/detect/IdentificationTest.kt@@ -65,7 +65,7 @@ class IdentificationTest {@Testfun rolesComeFromHitsVendorsAndNames() {- assertEquals("mobile printer", PatrolCluster.roleOf(listOf(hit(Category.PUBLIC_SAFETY, "Zebra mobile printer", 50)), "Texas Instruments", null))+ assertEquals("mobile printer", PatrolCluster.roleOf(listOf(hit(Category.MOBILE_PRINTER, "Zebra mobile printer", 50)), "Texas Instruments", null))assertEquals("two-way radio", PatrolCluster.roleOf(emptyList(), "Motorola Solutions Inc.", null))assertEquals("body camera", PatrolCluster.roleOf(listOf(hit(Category.BODY_CAM, "Axon body camera", 90)), null, null))assertEquals("mobile printer", PatrolCluster.roleOf(emptyList(), null, "RJ-4250WB_1234"))diff --git a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.ktindex ba8d758..9477858 100644--- a/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt+++ b/app/src/test/java/com/rfsentinel/app/online/OnlineSourcesTest.kt@@ -39,7 +39,13 @@ class OnlineSourcesTest {assertNull(PoliceAircraft.classify(airline, registry, circling = false, distanceM = 2000.0))assertEquals(80, PoliceAircraft.classify(police, registry, circling = false, distanceM = 3000.0)!!.confidence)val circling = PoliceAircraft.classify(airline.copy(altitudeFt = 1500), registry, circling = true, distanceM = 500.0)!!- assertEquals("Aircraft circling overhead", circling.label)+ assertEquals(PoliceAircraft.CIRCLING, circling.label)+ assertTrue(!PoliceAircraft.alerts(circling, 500.0) && PoliceAircraft.alerts(circling, 500.0, circlingOn = true))+ assertTrue(!PoliceAircraft.alerts(circling, 9000.0, circlingOn = true))+ val gov = PoliceAircraft.classify(airline.copy(owner = "STATE OF MINNESOTA DEPT OF NATURAL RESOURCES"), registry, circling = false, distanceM = 900.0)!!+ assertTrue(gov.label.startsWith("Government aircraft") && PoliceAircraft.alerts(gov, 900.0))+ assertEquals("Police aircraft overhead", com.rfsentinel.app.util.Spoken.aircraft(h1, 300.0, 0.0))+ assertEquals("Police aircraft, 2 kilometers northeast", com.rfsentinel.app.util.Spoken.aircraft(h1, 2000.0, 50.0))}@Testdiff --git a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.ktindex cf56d76..5a6cb95 100644--- a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt+++ b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt@@ -69,7 +69,7 @@ class WazeScreensTest {// Waze alone adds four: alert range, map range, and one interval slider per source.assertTrue("sliders: ${sliders.size}", sliders.size >= 4)sliders.forEach { it.measure(exactly, atMost) } // throws if a value does not fit its steps- assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().count { it.contentDescription !in setOf("Snooze length", "Swipe right on an alert", "Swipe left on an alert", "Re-center after") })+ assertEquals("one level menu per kind of report", WazePolice.Type.entries.size, views.filterIsInstance<AppCompatSpinner>().count { it.contentDescription !in setOf("Snooze length", "Swipe right on an alert", "Swipe left on an alert", "Re-center after", "Alert from") })val text = views.filterIsInstance<TextView>().joinToString("\n") { it.text }assertTrue(text.contains("Alert when a report is within"))assertTrue(text.contains("Show reports on the map within"))diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25HistoryTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25HistoryTest.ktnew file mode 100644index 0000000..62df401--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25HistoryTest.kt@@ -0,0 +1,29 @@+package com.rfsentinel.app.sdr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class P25HistoryTest {++ @Test+ fun lineRoundTripsAndSummaryCounts() {+ val day = 24 * 60 * 60_000L+ val now = 10 * day+ val a = P25History.Call(now - 1_000, 1234, null, 5001, 0x1A2, 851_012_500L, emergency = true, encrypted = false, site = "1A3-1-4")+ val b = P25History.Call(now - 3 * day, 1234, null, 5002, null, null, emergency = false, encrypted = true, site = null)+ val p = P25History.Call(now - 2_000, null, 777, 5003, 0x10, null, emergency = false, encrypted = false, site = null)+ assertEquals(a, P25History.parse(P25History.line(a)))+ assertEquals(b, P25History.parse(P25History.line(b)))+ assertNull(P25History.parse(P25History.HEADER))++ val s = P25History.summarize(listOf(b, p, a), now)+ val tg = s.first { it.tg == 1234 }+ assertEquals(1, tg.lastDay); assertEquals(2, tg.lastWeek); assertEquals(2, tg.all)+ assertEquals(2, tg.radios)+ assertTrue(tg.emergency && tg.encrypted)+ assertEquals(777, s.first { it.tg == null }.target)+ assertEquals(1234, s.first().tg) // most recent call first+ }+}