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
Fix History map crash loop, radio Locate/Watchlist, cameras vanishing until download; add device sightings map
CIS-C02b4af15cb8ce
diff --git a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.ktindex bbd5f37..f6ee0b2 100644--- a/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt+++ b/app/src/main/java/com/rfsentinel/app/alpr/AlprStore.kt@@ -61,13 +61,24 @@ object AlprStore {private fun file(context: Context) = File(context.filesDir, FILE)private fun areasFile(context: Context) = File(context.filesDir, AREAS_FILE)+ /** The saved cache has been read (or replaced): until then [cameras] and [areas] are not the real ones. */+ @Volatile var loaded = false+ private set++ /**+ * Reads the saved cache once (later calls return at once). Everything that changes the cache loads it first:+ * a download that ran before the file was read would merge into an empty list and save over it.+ */+ @Synchronizedfun load(context: Context) {+ if (loaded) returncameras = runCatching {file(context).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<KnownCamera>>(it, listType) }}.getOrNull().orEmpty()areas = runCatching {areasFile(context).takeIf { it.exists() }?.readText()?.let { gson.fromJson<List<CameraArea>>(it, areaListType) }}.getOrNull().orEmpty()+ loaded = true}/** True when the box isn't inside an area downloaded in the last [REFRESH_MS]. */@@ -80,6 +91,8 @@ object AlprStore {* Returns true when a download ran and changed the cache.*/suspend fun autoDownload(context: Context, south: Double, west: Double, north: Double, east: Double): Boolean {+ // Before the saved areas are read, every area looks missing.+ withContext(Dispatchers.IO) { load(context) }val now = System.currentTimeMillis()if (!needsDownload(south, west, north, east, now)) return false// After a failure, leave that same area alone for a minute (other areas may go ahead).@@ -172,6 +185,7 @@ object AlprStore {): Int =withContext(Dispatchers.IO) {require(north - south <= MAX_SPAN_DEG + 1e-9 && east - west <= MAX_SPAN_DEG + 1e-9) { "Area too large - zoom in" }+ load(context)val body = "data=" + URLEncoder.encode(KnownCameras.query(south, west, north, east), "UTF-8")// Public servers often answer 429/504 under load: one more round after a pause.val json = try {@@ -249,6 +263,12 @@ object AlprStore {else -> "failed (${e.message ?: e.javaClass.simpleName})"}+ /** An Overpass answer that stopped part-way: its remark (after the elements) reports a runtime error. */+ internal fun isCutShort(json: String): Boolean =+ CUT_SHORT.containsMatchIn(json.takeLast(2_000))++ private val CUT_SHORT = Regex(""""remark"\s*:\s*"[^"]*runtime error""")+/** One Overpass request; throws unless the answer is a JSON result. Reports KB received. */private fun fetch(endpoint: String, body: String, onOpen: (HttpURLConnection) -> Unit, onKb: (Int) -> Unit = {}): String {val conn = (URL(endpoint).openConnection() as HttpURLConnection).apply {@@ -276,8 +296,9 @@ object AlprStore {}}val text = out.toString("UTF-8")- // An overloaded server can answer 200 with an HTML error page.- if (!text.trimStart().startsWith("{")) error("server error")+ // An overloaded server can answer 200 with an HTML error page, or with JSON cut short by a timeout+ // (a "runtime error" remark): taken as the area's cameras, that would wipe the ones already shown there.+ if (!text.trimStart().startsWith("{") || isCutShort(text)) error("server error")return text} finally {conn.disconnect()@@ -291,6 +312,7 @@ object AlprStore {*/fun mergePlateReaders(context: Context, boxes: List<DoubleArray>, found: List<KnownCamera>) {synchronized(this) {+ load(context)val merged = mergeCameras(cameras, boxes, found)file(context).writeText(gson.toJson(merged))cameras = merged@@ -324,7 +346,7 @@ object AlprStore {/** Tests only: set the cache without files or network. */@androidx.annotation.VisibleForTesting- fun setForTest(list: List<KnownCamera>) { cameras = list }+ fun setForTest(list: List<KnownCamera>) { cameras = list; loaded = true }// Synchronized with the merges, so a save that was mid-write can't bring cameras back.@Synchronized@@ -334,6 +356,7 @@ object AlprStore {com.rfsentinel.app.util.Prefs.setDeflockUpdated(context, 0L)cameras = emptyList()areas = emptyList()+ loaded = true}}diff --git a/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt b/app/src/main/java/com/rfsentinel/app/data/DetectionDao.ktindex 6037b5a..ec51814 100644--- a/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt+++ b/app/src/main/java/com/rfsentinel/app/data/DetectionDao.kt@@ -30,6 +30,10 @@ interface DetectionDao {@Query("SELECT * FROM detections WHERE mac = :mac ORDER BY timestamp DESC LIMIT 200")suspend fun forMac(mac: String): List<DetectionEntity>+ /** One device's logged matches since [since], for its sightings map. */+ @Query("SELECT * FROM detections WHERE mac = :mac AND timestamp >= :since ORDER BY timestamp DESC LIMIT 5000")+ suspend fun forMacSince(mac: String, since: Long): List<DetectionEntity>+@Query("SELECT * FROM detections ORDER BY timestamp DESC")suspend fun allForExport(): List<DetectionEntity>diff --git a/app/src/main/java/com/rfsentinel/app/data/Trips.kt b/app/src/main/java/com/rfsentinel/app/data/Trips.ktindex 77780ce..cb69302 100644--- a/app/src/main/java/com/rfsentinel/app/data/Trips.kt+++ b/app/src/main/java/com/rfsentinel/app/data/Trips.kt@@ -123,4 +123,8 @@ interface TripDao {/** Flagged devices with a position from every recorded trace, for the history map. */@Query("SELECT * FROM trip_devices WHERE category IS NOT NULL AND lat IS NOT NULL AND lastSeen >= :since")suspend fun flaggedDevicesSince(since: Long): List<TripDeviceEntity>++ /** One device in every recorded trace with a position (flagged or not), for its sightings map. */+ @Query("SELECT * FROM trip_devices WHERE mac = :mac AND lat IS NOT NULL AND lastSeen >= :since")+ suspend fun sightingsOf(mac: String, since: Long): List<TripDeviceEntity>}diff --git a/app/src/main/java/com/rfsentinel/app/history/History.kt b/app/src/main/java/com/rfsentinel/app/history/History.ktindex 0cd3ec6..5d48d60 100644--- a/app/src/main/java/com/rfsentinel/app/history/History.kt+++ b/app/src/main/java/com/rfsentinel/app/history/History.kt@@ -46,6 +46,19 @@ object History {return out.sortedByDescending { it.time }}+ /**+ * [events] (oldest first) cut into runs wherever two in a row are more than [gapMs] apart: the+ * sightings of one encounter, to link on a map (a line across days would draw a route never taken).+ */+ fun runs(events: List<HistoryEvent>, gapMs: Long): List<List<HistoryEvent>> {+ val out = mutableListOf<MutableList<HistoryEvent>>()+ for (e in events) {+ val run = out.lastOrNull()+ if (run != null && e.time - run.last().time <= gapMs) run += e else out += mutableListOf(e)+ }+ return out+ }+/** Encounters per hour of day (0-23), in [zone]. */fun byHour(events: List<HistoryEvent>, zone: TimeZone = TimeZone.getDefault()): IntArray {val out = IntArray(24)diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.ktindex bc793aa..9b85cf8 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt@@ -36,6 +36,7 @@ import com.rfsentinel.app.service.DeviceRegistryimport com.rfsentinel.app.util.MacUtilimport com.rfsentinel.app.util.ProximityUtilimport com.rfsentinel.app.util.applySystemBarInsets+import com.rfsentinel.app.util.Prefsimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.isActive@@ -53,6 +54,13 @@ class DeviceDetailActivity : AppCompatActivity() {companion object {const val EXTRA_MAC = "mac"+ /** Two radio frequencies this close are the same channel (half the sweep's 12.5 kHz step). */+ private const val RADIO_SAME_HZ = 6_250L+ private val RADIO_KEY = Regex("""^RADIO (\d+(?:\.\d+)?) MHz$""")++ /** The frequency in a radio transmission's log key ("RADIO 154.4300 MHz"), else null. */+ fun radioHz(key: String): Long? =+ RADIO_KEY.find(key)?.groupValues?.get(1)?.toDoubleOrNull()?.let { Math.round(it * 1_000_000) }}private lateinit var binding: ActivityDeviceDetailBinding@@ -74,7 +82,8 @@ class DeviceDetailActivity : AppCompatActivity() {title = "Device details"supportActionBar?.setDisplayHomeAsUpEnabled(true)- binding.locateButton.setOnClickListener { toggleLocate() }+ radioHz = radioHz(mac)+ binding.locateButton.setOnClickListener { if (radioHz != null) locateRadio() else toggleLocate() }// The main action in the theme's highlight colour (faded while the device isn't heard).ChipStyle.accent(this).let { (accent, onAccent) ->val off = intArrayOf(-android.R.attr.state_enabled)@@ -82,7 +91,7 @@ class DeviceDetailActivity : AppCompatActivity() {binding.locateButton.backgroundTintList = android.content.res.ColorStateList(arrayOf(off, on), intArrayOf((accent and 0x00FFFFFF) or 0x55000000, accent))binding.locateButton.setTextColor(android.content.res.ColorStateList(arrayOf(off, on), intArrayOf((onAccent and 0x00FFFFFF) or 0x99000000.toInt(), onAccent)))}- binding.actionWatchlist.setOnClickListener { onWatchlistAction() }+ binding.actionWatchlist.setOnClickListener { if (radioHz != null) toggleWatchedFrequency() else onWatchlistAction() }binding.actionWhitelist.setOnClickListener {val s = DeviceRegistry.get(mac)when {@@ -107,6 +116,9 @@ class DeviceDetailActivity : AppCompatActivity() {binding.actionRename.setOnClickListener { rename() }binding.actionNote.setOnClickListener { editNote() }binding.noteText.setOnClickListener { editNote() }+ binding.actionSightings.setOnClickListener {+ startActivity(Intent(this, HistoryActivity::class.java).putExtra(HistoryActivity.EXTRA_MAC, mac))+ }binding.actionCopy.setOnClickListener { DeviceActions.copy(this, mac) }binding.actionShare.setOnClickListener { share() }binding.actionLearn.setOnClickListener { DeviceActions.learn(this, mac) }@@ -236,6 +248,11 @@ class DeviceDetailActivity : AppCompatActivity() {val custom = OuiWatchlist.customEntry(mac) ?: OuiWatchlist.customEntry(MacUtil.oui(mac))?: fp?.let { OuiWatchlist.customEntry(com.rfsentinel.app.oui.OuiEntry.FINGERPRINT + it) }binding.actionWatchlist.text = if (custom != null) "Remove from watchlist" else "Add to watchlist"+ radioHz?.let { hz ->+ // A radio transmission (RTL-SDR / HackRF): found with the waterfall, watched as a frequency.+ binding.locateButton.isEnabled = true // without an SDR it says what it needs+ binding.actionWatchlist.text = if (watchedTarget(hz) != null) "Stop watching frequency" else "Watch this frequency"+ }binding.actionWhitelist.text = when {com.rfsentinel.app.data.TrackerMutes.isMuted(mac) -> "Stop ignoring"whitelisted -> "Un-whitelist"@@ -606,6 +623,51 @@ class DeviceDetailActivity : AppCompatActivity() {}, "Share device report"))}+ // ---- Radio transmissions (logged as "RADIO 154.4300 MHz") -----------------------++ /** The frequency of a radio transmission's page, null for a Wi-Fi / Bluetooth device. */+ private var radioHz: Long? = null++ /** Locate for a radio: the waterfall zoomed in on its frequency, live, to walk towards the strongest trace. */+ private fun locateRadio() {+ val hz = radioHz ?: return+ if (!com.rfsentinel.app.sdr.SdrRadio.running) {+ Toast.makeText(this, "Plug in an RTL-SDR or HackRF and start scanning to follow this frequency", Toast.LENGTH_LONG).show()+ return+ }+ startActivity(Intent(this, WaterfallActivity::class.java).putExtra(WaterfallActivity.EXTRA_TUNE_HZ, hz))+ }++ /** The watched-frequency line for [hz] (Settings > RTL-SDR radio > Watch these frequencies), if any. */+ private fun watchedTarget(hz: Long): String? = Prefs.radioTargets(this).lines().firstOrNull { line ->+ com.rfsentinel.app.sdr.RadioSettings.targets(line).firstOrNull()?.let { kotlin.math.abs(it.freqHz - hz) < RADIO_SAME_HZ } == true+ }++ /** Adds the frequency to the watched ones (always reported when active, whatever the sensitivity), or takes it off. */+ private fun toggleWatchedFrequency() {+ val hz = radioHz ?: return+ val before = Prefs.radioTargets(this)+ val line = watchedTarget(hz)+ val after = if (line != null) before.lines().filterNot { it == line }.joinToString("\n")+ else {+ val name = com.rfsentinel.app.sdr.FreqNames.lookup(hz, Prefs.radioMatchKhz(this) * 1000L)?.name ?: DeviceNames.of(mac)+ val add = String.format(java.util.Locale.US, "%.4f", hz / 1e6) + (name?.let { " $it" } ?: "")+ before.trimEnd().let { if (it.isEmpty()) add else "$it\n$add" }+ }+ applyRadioTargets(after)+ com.rfsentinel.app.util.Undo.show(this,+ if (line != null) "No longer watching this frequency" else "Watching this frequency: always reported when active") {+ applyRadioTargets(before)+ }+ }++ private fun applyRadioTargets(text: String) {+ Prefs.setRadioTargets(this, text)+ // A running SDR picks it up at once (the scanner reads the settings again only on its next refresh).+ if (com.rfsentinel.app.sdr.SdrRadio.running) com.rfsentinel.app.sdr.SdrRadio.config = com.rfsentinel.app.sdr.RadioSettings.config(this)+ refresh()+ }+// ---- Locate (Geiger-counter beeps) ------------------------------------------private fun toggleLocate() {diff --git a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.ktindex 9cb9b8b..7baf4d3 100644--- a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt@@ -7,10 +7,12 @@ import androidx.lifecycle.lifecycleScopeimport com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.Rimport com.rfsentinel.app.data.AppDatabase+import com.rfsentinel.app.data.DeviceNamesimport com.rfsentinel.app.databinding.ActivityHistoryBindingimport com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.history.Historyimport com.rfsentinel.app.history.HistoryEvent+import com.rfsentinel.app.service.DeviceRegistryimport com.rfsentinel.app.util.Prefsimport com.rfsentinel.app.util.applySystemBarInsetsimport kotlinx.coroutines.Dispatchers@@ -24,6 +26,9 @@ import java.util.Date* Where and when flagged equipment showed up: a heatmap (or points) of past* encounters on the map, plus hour-of-day and day-of-week patterns. Reads the* match log and recorded traces; everything stays on this phone.+ *+ * Opened for one device ([EXTRA_MAC], its page's Sightings map): every spot it was heard with a position (match+ * log, recorded traces, this session's scanning) as a dot, the ones of one encounter linked in time order.*/class HistoryActivity : AppCompatActivity() {@@ -31,26 +36,61 @@ class HistoryActivity : AppCompatActivity() {private var engine: MapEngine? = nullprivate var map: MapEngine? = nullprivate var events: List<HistoryEvent> = emptyList()+ /** One device's map: the device, and every sighting of it with a position, oldest first. */+ private var deviceMac: String? = null+ private var trail: List<HistoryEvent> = emptyList()/** The encounters drawn as points, to find what a tap hit. */private var shown: List<HistoryEvent> = emptyList()private var fitted = false+ /** The map's start-up is marked on disk until it has drawn the encounters for a few seconds. */+ private var safetyArmed = false+ /** The encounters have been read at least once (the map has had something to draw). */+ private var loaded = falseprivate val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityHistoryBinding.inflate(layoutInflater)setContentView(binding.root)- title = "History map & timeline"+ deviceMac = intent.getStringExtra(EXTRA_MAC)+ title = if (deviceMac != null) "Sightings map" else "History map & timeline"+ deviceMac?.let { mac ->+ supportActionBar?.subtitle = DeviceNames.of(mac) ?: mac+ // Its own spots, linked, rather than a heat cloud; over all the time there is.+ if (savedInstanceState == null) { binding.rangeChips.check(R.id.rangeAll); binding.heatChip.isChecked = false }+ }supportActionBar?.setDisplayHomeAsUpEnabled(true)// Edge-to-edge: keep the filter row below the action bar and the panel above the nav bar.binding.root.applySystemBarInsets()- // The map chosen in Settings > Map (OpenFreeMap or Mapbox).+ // The app closed while a map was starting last time: say so, and try with OpenGL (or ask before trying again).+ if (savedInstanceState == null) MapSafetyUi.tell(this, MapSafety.recover(this), onTryAgain = { addMap(null) })+ else addMap(savedInstanceState)++ var lastRange = binding.rangeChips.checkedChipId+ binding.rangeChips.setOnCheckedStateChangeListener { group, ids ->+ // Tapping the selected period again would leave none selected: keep it selected.+ if (ids.isEmpty()) { group.check(lastRange); return@setOnCheckedStateChangeListener }+ lastRange = ids.first()+ fitted = false; load()+ }+ binding.heatChip.setOnCheckedChangeListener { _, _ -> render() }+ load()+ }++ /**+ * The map chosen in Settings > Map (OpenFreeMap or Mapbox). Its start-up is guarded like the main map's+ * ([MapSafety]): a phone whose graphics driver closes the app while drawing it (seen with the heatmap on+ * Vulkan) gets the OpenGL renderer at the next launch instead of closing every time.+ */+ private fun addMap(state: Bundle?) {+ if (isFinishing || isDestroyed || engine != null) return+ MapSafety.arm(this, MapEngine.chosen(this)); safetyArmed = trueval e = MapEngine.create(this).also { engine = it }binding.map.addView(e.view, android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,android.view.ViewGroup.LayoutParams.MATCH_PARENT))binding.mapCredit.text = e.credit- e.onCreate(savedInstanceState)+ e.onCreate(state)e.whenReady {if (isDestroyed) return@whenReadymap = e@@ -67,16 +107,9 @@ class HistoryActivity : AppCompatActivity() {render()}}-- var lastRange = binding.rangeChips.checkedChipId- binding.rangeChips.setOnCheckedStateChangeListener { group, ids ->- // Tapping the selected period again would leave none selected: keep it selected.- if (ids.isEmpty()) { group.check(lastRange); return@setOnCheckedStateChangeListener }- lastRange = ids.first()- fitted = false; load()- }- binding.heatChip.setOnCheckedChangeListener { _, _ -> render() }- load()+ // Started late (after the "map closed the app" question): catch up with the screen.+ if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) e.onStart()+ if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) e.onResume()}private fun sinceMillis(): Long {@@ -92,6 +125,7 @@ class HistoryActivity : AppCompatActivity() {private fun load() {val since = sinceMillis()+ deviceMac?.let { loadDevice(it, since); return }lifecycleScope.launch {events = withContext(Dispatchers.IO) {val db = AppDatabase.getInstance(this@HistoryActivity)@@ -103,6 +137,31 @@ class HistoryActivity : AppCompatActivity() {}History.encounters(logged + traced)}+ loaded = true+ render()+ }+ }++ /** One device's sightings: logged matches, recorded traces and where this session heard it. */+ private fun loadDevice(mac: String, since: Long) {+ lifecycleScope.launch {+ val all = withContext(Dispatchers.IO) {+ val db = AppDatabase.getInstance(this@HistoryActivity)+ val logged = db.detectionDao().forMacSince(mac, since)+ val category = logged.firstOrNull()?.category+ val label = logged.firstOrNull()?.label ?: DeviceRegistry.get(mac)?.let { it.best?.label ?: it.name } ?: mac+ val traced = db.tripDao().sightingsOf(mac, since)+ // This session: where your phone was each time it heard it (its newer address too, if it changed).+ val live = listOf(mac, DeviceRegistry.currentAddress(mac)).distinct()+ .flatMap { DeviceRegistry.get(it)?.path.orEmpty() }+ .filter { it.time >= since }+ .map { HistoryEvent(it.time, it.lat, it.lon, category ?: "", label, mac) }+ logged.map { HistoryEvent(it.timestamp, it.latitude, it.longitude, it.category, it.label, mac) } ++ traced.map { HistoryEvent(it.firstSeen, it.lat, it.lon, it.category ?: category ?: "", it.label, mac) } + live+ }+ trail = all.filter { it.positioned }.distinctBy { Triple(it.time / 1000, it.lat, it.lon) }.sortedBy { it.time }+ events = History.encounters(all)+ loaded = truerender()}}@@ -113,12 +172,17 @@ class HistoryActivity : AppCompatActivity() {*/private fun addLayers(m: MapEngine) {m.addSource(HEAT)+ m.addSource(TRAIL)m.addSource(POINTS)m.addLayer(JSONObject("""{"id":"$HEAT","type":"heatmap","source":"$HEAT","paint":{"heatmap-radius":38,"heatmap-weight":0.35,"heatmap-opacity":0.9,"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(0,0,0,0)",0.1,"rgba(32,32,160,0.13)",0.3,"rgba(0,229,255,0.44)",0.55,"rgba(0,208,96,0.56)",0.8,"rgba(255,224,0,0.69)",1,"rgba(255,32,32,0.88)"]}}"""))+ // One device's sightings of one encounter, linked in time order (under the dots).+ m.addLayer(JSONObject("""{"id":"$TRAIL","type":"line","source":"$TRAIL",+ "layout":{"line-join":"round","line-cap":"round"},+ "paint":{"line-color":["to-color",["get","color"]],"line-width":3,"line-opacity":0.75}}"""))// Mapbox's night look is lit: a dot that gives off no light of its own goes black on it, so there it glows.val glow = if (m.provider == MapEngine.Provider.MAPBOX) "\"circle-emissive-strength\":1," else ""m.addLayer(JSONObject("""{"id":"$POINTS","type":"circle","source":"$POINTS","paint":{@@ -127,28 +191,40 @@ class HistoryActivity : AppCompatActivity() {}private fun render() {- val positioned = events.filter { it.positioned }+ val device = deviceMac != null+ // On the map: the encounters, or every sighting of the one device.+ val positioned = if (device) trail else events.filter { it.positioned }val showHeat = binding.heatChip.isCheckedval m = map+ fun color(e: HistoryEvent) = String.format("#%06X",+ ThemeManager.ink(this@HistoryActivity, Category.parse(e.category)?.colorArgb ?: 0xFF607D8B.toInt()) and 0xFFFFFF)m?.takeIf { it.styleLoaded }?.let { mm ->runCatching {mm.setData(HEAT, GeoJson.collection(if (showHeat) positioned.map { GeoJson.feature(GeoJson.point(it.lat!!, it.lon!!)) } else emptyList()))- shown = if (showHeat) emptyList() else positioned.take(3000)+ shown = if (showHeat) emptyList() else if (device) positioned.takeLast(3000) else positioned.take(3000)+ mm.setData(TRAIL, GeoJson.collection(if (!device) emptyList() else+ History.runs(shown, ENCOUNTER_GAP_MS).filter { it.size >= 2 }.map { run ->+ GeoJson.feature(GeoJson.line(run.map { it.lat!! to it.lon!! }), "color" to color(run.first()))+ }))mm.setData(POINTS, GeoJson.collection(shown.withIndex().map { (i, e) ->- GeoJson.feature(GeoJson.point(e.lat!!, e.lon!!), "i" to i.toString(),- "color" to String.format("#%06X",- ThemeManager.ink(this@HistoryActivity, Category.parse(e.category)?.colorArgb ?: 0xFF607D8B.toInt()) and 0xFFFFFF))+ GeoJson.feature(GeoJson.point(e.lat!!, e.lon!!), "i" to i.toString(), "color" to color(e))}))}}binding.summaryText.text = when {+ device && events.isEmpty() -> "Not heard in this period"+ device -> "${events.size} encounter${if (events.size == 1) "" else "s"} · ${positioned.size} spot${if (positioned.size == 1) "" else "s"} on the map"events.isEmpty() -> "No flagged equipment logged in this period"else -> "${events.size} encounter${if (events.size == 1) "" else "s"} · " +(History.busiest(events) ?: "")}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)."+ 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."@@ -158,6 +234,10 @@ class HistoryActivity : AppCompatActivity() {binding.hourChart.set(History.byHour(events), List(24) { h -> if (h % 6 == 0) "${h}h" else null })binding.dayChart.set(History.byWeekday(events), listOf("M", "T", "W", "T", "F", "S", "S"))+ // Drawn with the encounters (the heatmap too): once that has lasted a few seconds the map works on this phone.+ if (safetyArmed && loaded && m != null && m.styleLoaded) binding.map.postDelayed({+ if (safetyArmed && !isDestroyed) { safetyArmed = false; MapSafety.worked(this) }+ }, MapSafety.SETTLE_MS)if (!fitted && positioned.isNotEmpty() && m != null && m.styleLoaded) {fitted = truebinding.map.post {@@ -188,15 +268,24 @@ class HistoryActivity : AppCompatActivity() {override fun onStart() { super.onStart(); engine?.onStart() }override fun onResume() { super.onResume(); engine?.onResume() }- override fun onPause() { engine?.onPause(); super.onPause() }+ override fun onPause() {+ engine?.onPause()+ if (safetyArmed) { safetyArmed = false; MapSafety.disarm(this) } // leaving normally is not a crash+ super.onPause()+ }override fun onStop() { engine?.onStop(); super.onStop() }override fun onLowMemory() { super.onLowMemory(); engine?.onLowMemory() }override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); engine?.onSaveInstanceState(outState) }override fun onDestroy() { engine?.onDestroy(); engine = null; map = null; super.onDestroy() }- private companion object {- const val HEAT = "history-heat"- const val POINTS = "history-points"+ companion object {+ /** Show one device's sightings only. */+ const val EXTRA_MAC = "mac"+ private const val HEAT = "history-heat"+ private const val TRAIL = "history-trail"+ private const val POINTS = "history-points"+ /** Sightings further apart than this are separate encounters (not linked), as in [History.encounters]. */+ private const val ENCOUNTER_GAP_MS = 10 * 60_000L}override fun onOptionsItemSelected(item: MenuItem): Boolean {diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex 00ed84f..9b05f42 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -1187,10 +1187,15 @@ class MapFragment : Fragment() {if (tripId == null) ScanForegroundService.mapShown(act)com.rfsentinel.app.alpr.CctvStore.onChanged = { activity?.runOnUiThread { if (alive) rf?.safe("static") { rf?.maybeRedrawStatic(force = true); renderLive() } } }// Back from Settings > Map: show what's switched on now (and nothing that was switched off).- if (Prefs.showCctv(act)) viewLifecycleOwner.lifecycleScope.launch {- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.rfsentinel.app.alpr.CctvStore.load(act) }+ // The saved cameras first: right after the app starts they may still be loading, and a map drawn without+ // them would stay empty until a new download finished.+ viewLifecycleOwner.lifecycleScope.launch {+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ com.rfsentinel.app.alpr.AlprStore.load(act)+ if (Prefs.showCctv(act)) com.rfsentinel.app.alpr.CctvStore.load(act)+ }rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }- } else rf?.safe("static") { rf?.maybeRedrawStatic(force = true) }+ }if (rf != null && rf?.isDark != darkTiles()) loadStyle()styleOrientationButton()applyMode(animate = false)diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.ktindex 36acdec..cfb66f6 100644--- a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt@@ -51,6 +51,8 @@ class WaterfallActivity : AppCompatActivity() {binding.waterfall.onTap = { hz -> zoom(hz) }binding.tuneButton.setOnClickListener { askFrequency() }binding.sweepButton.setOnClickListener { SdrRadio.tuneHz = null; refresh() }+ // Opened from a radio transmission's Locate: straight to its frequency (not again after a rotation).+ if (savedInstanceState == null) intent.getLongExtra(EXTRA_TUNE_HZ, 0L).takeIf { it > 0 }?.let { zoom(it) }lifecycleScope.launch {repeatOnLifecycle(Lifecycle.State.STARTED) {while (true) { refresh(); delay(1000) }@@ -128,10 +130,12 @@ class WaterfallActivity : AppCompatActivity() {binding.tuneButton.isEnabled = running}- private companion object {+ companion object {+ /** A frequency (Hz) to zoom in on as the screen opens. */+ const val EXTRA_TUNE_HZ = "tune_hz"/** Rows waiting for the screen; older ones are dropped if it falls behind. */- const val MAX_QUEUED = 64- const val MIN_MHZ = 1.0- const val MAX_MHZ = 6000.0+ private const val MAX_QUEUED = 64+ private const val MIN_MHZ = 1.0+ private const val MAX_MHZ = 6000.0}}diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xmlindex b3fa2c4..6a2f3a2 100644--- a/app/src/main/res/layout/activity_device_detail.xml+++ b/app/src/main/res/layout/activity_device_detail.xml@@ -177,6 +177,12 @@android:layout_height="wrap_content"android:text="I saw it" />+ <com.google.android.material.chip.Chip+ android:id="@+id/actionSightings"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:text="Sightings map" />+<com.google.android.material.chip.Chipandroid:id="@+id/actionCopy"android:layout_width="wrap_content"diff --git a/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt b/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.ktindex c58c53a..2b39a09 100644--- a/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt+++ b/app/src/test/java/com/rfsentinel/app/alpr/KnownCamerasTest.kt@@ -133,4 +133,15 @@ class KnownCamerasTest {assertFalse(KnownCameras.watchesYourWay(cam, 0.0, direction = 90))assertEquals(mapOf("node/1" to 90, "way/2" to 315), CameraDirections.parse(setOf("node/1=90", "way/2=315", "bad", "node/3=400")))}++ @Test+ fun overpassAnswerCutShortByATimeoutIsRejected() {+ val ok = """{"version":0.6,"elements":[{"type":"node","id":1,"lat":1.0,"lon":2.0}]}"""+ val cut = """{"version":0.6,"elements":[],"remark":"runtime error: Query timed out in \"query\" at line 3 after 26 seconds."}"""+ assertFalse(AlprStore.isCutShort(ok))+ assertTrue(AlprStore.isCutShort(cut))+ // A camera's own tags mentioning a remark are not an error.+ assertFalse(AlprStore.isCutShort("""{"elements":[{"tags":{"note":"remark"}}]}"""))+ }}+diff --git a/app/src/test/java/com/rfsentinel/app/history/HistoryTest.kt b/app/src/test/java/com/rfsentinel/app/history/HistoryTest.ktindex c8b5036..f452dc8 100644--- a/app/src/test/java/com/rfsentinel/app/history/HistoryTest.kt+++ b/app/src/test/java/com/rfsentinel/app/history/HistoryTest.kt@@ -42,4 +42,14 @@ class HistoryTest {assertTrue(History.busiest(enc, utc)!!.startsWith("Busiest: Mon, 08:00-09:00"))assertEquals("Flock Safety camera" to 3, History.topLabels(enc).first())}++ @Test+ fun runsSplitWhereSightingsAreFarApartInTime() {+ val a = ev(at(28, 8, 0), "aa", 1.0); val b = ev(at(28, 8, 5), "aa", 1.1); val c = ev(at(28, 8, 14), "aa", 1.2)+ val d = ev(at(29, 9, 0), "aa", 1.3)+ val runs = History.runs(listOf(a, b, c, d), 10 * 60_000L)+ assertEquals(listOf(listOf(a, b, c), listOf(d)), runs)+ assertTrue(History.runs(emptyList(), 1).isEmpty())+ }}+