Skip to content

RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.

Live read card on the map and floating map while locating or pinpointing

CIS-C00215bd9f7045
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 78d313b..2aa5c85 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -223,6 +223,8 @@ class ScanForegroundService : Service() {
private var locationMode = 0
/** A flagged device was heard recently: GPS runs precise and fast so it can be pinpointed. */
@Volatile private var locatingUntil = 0L
+ /** This round of [locatingUntil] pinpoints (the setting is on and precise location allowed). */
+ @Volatile private var pinpointing = false
private val locatingHandler = android.os.Handler(Looper.getMainLooper())
private val locatingCheck = object : Runnable {
override fun run() {
@@ -455,17 +457,24 @@ class ScanForegroundService : Service() {
return DeviceRegistry.GeoSample(now, lat, lon)
}
- /** A flagged device was heard: keep precise, fast GPS on for a while so it can be pinpointed. */
- private fun noteLocating() {
+ /**
+ * A flagged device ([mac]) was heard: keep precise, fast GPS on for a while so it can be pinpointed, and show
+ * its live read on the map ([com.rfsentinel.app.ui.LiveRead]).
+ */
+ private fun noteLocating(mac: String) {
val now = System.currentTimeMillis()
val was = now < locatingUntil
locatingUntil = now + LOCATING_HOLD_MS
// Called for every packet of a flagged device: only the switch-on does the setting / permission checks.
- if (!was && Prefs.pinpointFlagged(this) && hasFineLocation()) {
- updateLocationOnMain()
- locatingHandler.removeCallbacks(locatingCheck)
- locatingHandler.postDelayed(locatingCheck, LOCATING_HOLD_MS + 1_000)
+ if (!was) {
+ pinpointing = Prefs.pinpointFlagged(this) && hasFineLocation()
+ if (pinpointing) {
+ updateLocationOnMain()
+ locatingHandler.removeCallbacks(locatingCheck)
+ locatingHandler.postDelayed(locatingCheck, LOCATING_HOLD_MS + 1_000)
+ }
}
+ if (pinpointing) com.rfsentinel.app.ui.LiveRead.pinpoint(mac, now, locatingUntil)
}
/** A fix good enough to pin a device on the map: under 30 s old and within ~50 m. */
@@ -693,7 +702,7 @@ class ScanForegroundService : Service() {
this, mac, trackerHit.label, a.rssi, now, DeviceRegistry.linkedFrom(mac))
) return
if (WhitelistCache.contains(mac)) return
- noteLocating()
+ noteLocating(mac)
maybeLog(a, best, c.vendor, loc, now)
maybeAlert(a, best, now, via)
@@ -1664,6 +1673,7 @@ class ScanForegroundService : Service() {
}
override fun onDestroy() {
+ com.rfsentinel.app.ui.LiveRead.reset()
com.rfsentinel.app.usb.DeauthWatch.onAttack = null
com.rfsentinel.app.usb.DeauthWatch.clear()
com.rfsentinel.app.usb.KarmaWatch.onAttack = null
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index 2db174d..f9d840a 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -2,8 +2,6 @@ package com.rfsentinel.app.ui
import android.content.Intent
import android.graphics.Typeface
-import android.media.AudioManager
-import android.media.ToneGenerator
import android.net.Uri
import android.os.Bundle
import android.util.TypedValue
@@ -17,7 +15,6 @@ import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
-import com.rfsentinel.app.util.AlertPlayer
import com.rfsentinel.app.data.AppDatabase
import com.rfsentinel.app.data.DetectionEntity
import com.rfsentinel.app.data.DeviceNames
@@ -37,7 +34,6 @@ import com.rfsentinel.app.util.MacUtil
import com.rfsentinel.app.util.ProximityUtil
import com.rfsentinel.app.util.applySystemBarInsets
import com.rfsentinel.app.util.Prefs
-import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
@@ -70,8 +66,6 @@ class DeviceDetailActivity : AppCompatActivity() {
/** The saved record's type as this version names it. */
private val knownType get() = known?.let { DeviceIntel.savedType(it.deviceType, it.vendor, it.mac) }
private var pastMatches: List<DetectionEntity> = emptyList()
- private var locateJob: Job? = null
- private var tone: ToneGenerator? = null
private val dateFmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
private val timeFmt = DateFormat.getTimeInstance(DateFormat.MEDIUM)
@@ -158,11 +152,6 @@ class DeviceDetailActivity : AppCompatActivity() {
private val visual get() = VisualMode.on(this, VisualMode.Screen.DEVICE_DETAIL)
- override fun onPause() {
- stopLocate()
- super.onPause()
- }
-
// ---- Rendering ------------------------------------------------------------
private fun isRotatingTracker(s: DeviceRegistry.Snapshot?) =
@@ -219,16 +208,8 @@ class DeviceDetailActivity : AppCompatActivity() {
// Live signal (from the newest address when it rotated)
if (live != null) {
binding.rssiText.text = "${live.rssi}"
- val recent = live.history.takeLast(6).dropLast(1)
- val trendDir = if (recent.isEmpty()) 0 else {
- val avg = recent.map { it.rssi }.average()
- when {
- live.rssi > avg + 3 -> 1
- live.rssi < avg - 3 -> -1
- else -> 0
- }
- }
- val trend = if (recent.isEmpty()) "" else when (trendDir) {
+ val trendDir = LiveRead.trend(live)
+ val trend = if (live.history.size < 2) "" else when (trendDir) {
1 -> " ↑ getting closer"; -1 -> " ↓ moving away"; else -> " → steady"
}
binding.gauge.set(live.rssi, live.bestRssi, trendDir)
@@ -237,6 +218,7 @@ class DeviceDetailActivity : AppCompatActivity() {
(if (liveMac != mac) "\nNow heard as $liveMac" else "")
binding.graph.setSamples(live.history)
binding.locateButton.isEnabled = true
+ binding.locateButton.text = if (locatingThis()) "Stop" else "Locate"
} else {
binding.rssiText.text = "--"
binding.gauge.set(null, null, 0)
@@ -690,40 +672,21 @@ class DeviceDetailActivity : AppCompatActivity() {
// ---- Locate (Geiger-counter beeps) ------------------------------------------
+ // Locate runs in LiveRead, so it keeps going while you look at the map (its live read card shows there).
+ private fun locatingThis() = LiveRead.locating == mac
+
private fun toggleLocate() {
- if (locateJob != null) stopLocate() else startLocate()
+ if (locatingThis()) stopLocate() else startLocate()
}
- /** The address Locate is following (changes when the device rotates its address). */
- private var followed: String? = null
-
private fun startLocate() {
- followed = null
- tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
+ LiveRead.startLocate(this, mac)
binding.locateButton.text = "Stop"
- Toast.makeText(this, "Walk around: beeps speed up as the signal gets stronger", Toast.LENGTH_LONG).show()
- locateJob = lifecycleScope.launch {
- while (isActive) {
- // Keeps following it when it changes its address (a tag rotating its random address).
- val liveMac = DeviceRegistry.currentAddress(mac)
- if (liveMac != followed) {
- if (followed != null) Toast.makeText(this@DeviceDetailActivity, "It changed its address - still following it", Toast.LENGTH_SHORT).show()
- followed = liveMac
- }
- val rssi = DeviceRegistry.get(liveMac)?.rssi ?: -100
- // Faster as the signal gets stronger (same curve as the radar beeps).
- val interval = com.rfsentinel.app.util.Beeper.tickIntervalMs(rssi)
- if (!AlertPlayer.locateTick(this@DeviceDetailActivity)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)
- delay(interval)
- }
- }
+ Toast.makeText(this, "Walk around: beeps speed up as the signal gets stronger. It keeps going on the map", Toast.LENGTH_LONG).show()
}
private fun stopLocate() {
- locateJob?.cancel()
- locateJob = null
- tone?.release()
- tone = null
+ if (locatingThis()) LiveRead.stopLocate()
if (::binding.isInitialized) binding.locateButton.text = "Locate"
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
index af9d708..8e08fb1 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/FloatingMap.kt
@@ -14,7 +14,9 @@ import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
+import android.view.ContextThemeWrapper
import android.view.Gravity
+import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewOutlineProvider
@@ -23,6 +25,8 @@ import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.edit
+import com.rfsentinel.app.R
+import com.rfsentinel.app.databinding.ViewLiveReadBinding
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.Prefs
import org.maplibre.android.camera.CameraPosition
@@ -82,6 +86,13 @@ object FloatingMap {
private var lastHere: Location? = null
/** Saved-scale zoom (see [ZOOM_SHIFT]). */
private var zoom = ZOOM
+ /** The map window's place and size, which the live read card follows. */
+ private var mapLp: WindowManager.LayoutParams? = null
+ /** The live read card (Locate or pinpointing): a small window of its own just under the map. */
+ private var live: ViewLiveReadBinding? = null
+ private var liveLp: WindowManager.LayoutParams? = null
+ private var liveCard: LiveReadCard? = null
+ private var stopLive: (() -> Unit)? = null
fun canShow(context: Context) = Settings.canDrawOverlays(context)
@@ -131,6 +142,9 @@ object FloatingMap {
private fun removeNow(context: Context) {
val r = root ?: return
+ stopLive?.invoke(); stopLive = null
+ removeLive(context)
+ mapLp = null
runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(r) }
view?.let { v -> runCatching { v.onPause(); v.onStop(); v.onDestroy() } }
root = null; view = null; map = null; badge = null; waiting = null; border = null
@@ -140,6 +154,52 @@ object FloatingMap {
private fun dp(context: Context, v: Float) = (v * context.resources.displayMetrics.density).toInt()
+ private fun overlayType() = if (Build.VERSION.SDK_INT >= 26) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
+ else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE
+
+ /** Shows, updates or (null) removes the live read card under the map. */
+ private fun showLive(context: Context, r: LiveRead.Read?) {
+ if (r == null || root == null) { removeLive(context); return }
+ if (live == null) {
+ val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ val b = ViewLiveReadBinding.inflate(LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_RFSentinel)))
+ // A little smaller than on the full map: it sits beside another app.
+ b.liveTitle.textSize = 14f; b.liveDetail.textSize = 12f
+ b.root.elevation = 6f * context.resources.displayMetrics.density
+ val lp = WindowManager.LayoutParams(
+ WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, overlayType(),
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT
+ ).apply { gravity = Gravity.TOP or Gravity.END }
+ if (runCatching { wm.addView(b.root, lp) }.isFailure) return
+ live = b; liveLp = lp; liveCard = LiveReadCard(b)
+ // Placed again once its height is known (above the map when there is no room below).
+ b.root.addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom ->
+ if (bottom - top != oldBottom - oldTop) placeLive(context)
+ }
+ }
+ liveCard?.show(r)
+ placeLive(context)
+ }
+
+ /** The card just under the map, its right edge on the map's, at least as wide as the map; above it near the bottom. */
+ private fun placeLive(context: Context) {
+ val b = live ?: return; val lp = liveLp ?: return; val m = mapLp ?: return
+ val dm = context.resources.displayMetrics
+ val gap = dp(context, 6f)
+ lp.width = maxOf(m.width, dp(context, 240f)).coerceAtMost(dm.widthPixels - dp(context, 16f))
+ // Gravity END: x is from the right edge; kept on screen when the map is near the left.
+ lp.x = m.x.coerceIn(0, (dm.widthPixels - lp.width).coerceAtLeast(0))
+ val h = b.root.height.takeIf { it > 0 } ?: dp(context, 84f)
+ lp.y = if (m.y + m.height + gap + h <= dm.heightPixels) m.y + m.height + gap else (m.y - gap - h).coerceAtLeast(0)
+ runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).updateViewLayout(b.root, lp) }
+ }
+
+ private fun removeLive(context: Context) {
+ val b = live ?: return
+ runCatching { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(b.root) }
+ live = null; liveLp = null; liveCard = null
+ }
+
@SuppressLint("ClickableViewAccessibility", "SetTextI18n")
private fun add(context: Context): FrameLayout? {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@@ -150,9 +210,7 @@ object FloatingMap {
val maxSize = (context.resources.displayMetrics.widthPixels - dp(context, 16f)).coerceAtLeast(minSize)
val size = prefs.getInt("size", dp(context, SIZE_DP.toFloat())).coerceIn(minSize, maxSize)
val lp = WindowManager.LayoutParams(
- size, size,
- if (Build.VERSION.SDK_INT >= 26) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
- else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE,
+ size, size, overlayType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT
).apply {
@@ -254,7 +312,7 @@ object FloatingMap {
val dx = e.rawX - downX; val dy = e.rawY - downY
if (abs(dx) > 8 * d || abs(dy) > 8 * d) moved = true
// Gravity END: x grows to the left.
- if (moved) { lp.x = startX - dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(frame, lp) } }
+ if (moved) { lp.x = startX - dx.toInt(); lp.y = startY + dy.toInt(); runCatching { wm.updateViewLayout(frame, lp) }; placeLive(context) }
}
MotionEvent.ACTION_UP -> {
if (pinched) prefs.edit { putFloat("zoom", zoom.toFloat()) }
@@ -291,7 +349,7 @@ object FloatingMap {
// Out (left / down) grows it, in (right / up) shrinks it; it stays square.
val grow = maxOf(resizeDownX - e.rawX, e.rawY - resizeDownY)
val n = (startSize + grow).toInt().coerceIn(minSize, maxSize)
- if (n != lp.width) { lp.width = n; lp.height = n; runCatching { wm.updateViewLayout(frame, lp) } }
+ if (n != lp.width) { lp.width = n; lp.height = n; runCatching { wm.updateViewLayout(frame, lp) }; placeLive(context) }
}
MotionEvent.ACTION_UP -> prefs.edit { putInt("size", lp.width) }
}
@@ -301,8 +359,9 @@ object FloatingMap {
return runCatching {
wm.addView(frame, lp)
m.onStart(); m.onResume()
- root = frame; view = m; badge = count; waiting = wait
+ root = frame; view = m; badge = count; waiting = wait; mapLp = lp
ScanForegroundService.mapShown(context)
+ stopLive = LiveRead.addListener { showLive(context, it) }
frame
}.getOrNull()
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
new file mode 100644
index 0000000..1d60a77
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
@@ -0,0 +1,212 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.content.res.ColorStateList
+import android.media.AudioManager
+import android.media.ToneGenerator
+import android.os.Handler
+import android.os.Looper
+import android.view.View
+import android.widget.Toast
+import com.rfsentinel.app.data.DeviceNames
+import com.rfsentinel.app.databinding.ViewLiveReadBinding
+import com.rfsentinel.app.detect.DeviceIntel
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.util.AlertPlayer
+import com.rfsentinel.app.util.Beeper
+import com.rfsentinel.app.util.Prefs
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * The live read of the device being followed - by Locate (the device screen's beeps) or by pinpointing a flagged
+ * device - for the card over the map and under the floating map ([LiveReadCard]): what it is, how strong, how far.
+ * Locate keeps beeping when you leave the device screen to look at the map, until Stop, the card's ✕, the scan
+ * stopping or the device going out of range.
+ */
+object LiveRead {
+
+ enum class Mode(val label: String) { LOCATE("LOCATING"), PINPOINT("PINPOINTING") }
+
+ /** [rssi] and [distanceM] are null while it isn't heard; [trend] 1 getting closer, -1 moving away, 0 steady. */
+ data class Read(
+ val mode: Mode, val mac: String, val title: String, val tag: String?, val color: Int,
+ val rssi: Int?, val distanceM: Double?, val trend: Int
+ )
+
+ private const val TICK_MS = 1_000L
+ /** Heard within this: its signal is live. */
+ private const val HEARD_MS = 10_000L
+ /** A pinpointed device unheard this long gives way to another flagged one. */
+ private const val PINPOINT_SWITCH_MS = 15_000L
+ private const val NO_FLAG_COLOR = 0xFF9AA5AD.toInt()
+
+ private val main = Handler(Looper.getMainLooper())
+ private val listeners = CopyOnWriteArrayList<(Read?) -> Unit>()
+
+ // ---- Locate (main thread) ----
+ /** The address Locate was started on, null when off. */
+ @Volatile var locating: String? = null
+ private set
+ /** The address it is heard under now (it changes when the device rotates its address). */
+ private var followed: String? = null
+ private var tone: ToneGenerator? = null
+ private var appContext: Context? = null
+
+ // ---- Pinpoint (the scan's pipeline thread) ----
+ private var pinMac: String? = null
+ private var pinHeard = 0L
+ @Volatile private var pinUntil = 0L
+ /** The pinpointed device whose card was dismissed (it comes back for another device or the next pinpointing). */
+ @Volatile private var dismissedPin: String? = null
+
+ /** Starts Locate on [mac]: beeps that speed up as the signal gets stronger. Main thread. */
+ fun startLocate(context: Context, mac: String) {
+ stopLocate()
+ appContext = context.applicationContext
+ locating = mac
+ followed = null
+ tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
+ main.post(beep)
+ tick()
+ }
+
+ /** Main thread. */
+ fun stopLocate() {
+ main.removeCallbacks(beep)
+ val was = locating != null
+ locating = null; followed = null
+ tone?.release(); tone = null
+ if (was) tick()
+ }
+
+ private val beep = object : Runnable {
+ override fun run() {
+ val mac = locating ?: return
+ val ctx = appContext ?: return
+ // Keeps following it when it changes its address (a tag rotating its random address).
+ val liveMac = DeviceRegistry.currentAddress(mac)
+ if (liveMac != followed) {
+ if (followed != null) Toast.makeText(ctx, "It changed its address - still following it", Toast.LENGTH_SHORT).show()
+ followed = liveMac
+ }
+ // Out of range (gone from the list): Locate ends, as on the device screen.
+ val s = DeviceRegistry.get(liveMac) ?: DeviceRegistry.get(mac) ?: run { stopLocate(); return }
+ if (!AlertPlayer.locateTick(ctx)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)
+ // Faster as the signal gets stronger (same curve as the radar beeps).
+ main.postDelayed(this, Beeper.tickIntervalMs(s.rssi))
+ }
+ }
+
+ /**
+ * A flagged device was heard while pinpointing is on (any thread): it becomes the one read, unless the one
+ * already read was heard in the last [PINPOINT_SWITCH_MS]. [until]: when pinpointing ends unless heard again.
+ */
+ @Synchronized
+ fun pinpoint(mac: String, now: Long, until: Long) {
+ val cur = pinMac
+ if (now > pinUntil) dismissedPin = null // a new round of pinpointing
+ if (cur == null || cur == mac || now > pinUntil || now - pinHeard > PINPOINT_SWITCH_MS) { pinMac = mac; pinHeard = now }
+ val starting = now > pinUntil
+ pinUntil = until
+ if (starting) main.post { tick() }
+ }
+
+ /** The scan stopped: no Locate, no pinpointing. */
+ fun reset() = main.post {
+ stopLocate()
+ synchronized(this) { pinMac = null; pinUntil = 0L; dismissedPin = null }
+ tick()
+ }
+
+ /** The card's ✕: ends Locate, or hides the card for the device being pinpointed. Main thread. */
+ fun dismiss() {
+ if (locating != null) { stopLocate(); return }
+ dismissedPin = synchronized(this) { pinMac }
+ tick()
+ }
+
+ /** What to show now, or null for no card. */
+ fun current(now: Long = System.currentTimeMillis()): Read? {
+ locating?.let { m -> return read(Mode.LOCATE, m, now) }
+ val p = synchronized(this) { pinMac } ?: return null
+ if (now > pinUntil || p == dismissedPin) return null
+ return read(Mode.PINPOINT, p, now)
+ }
+
+ private fun read(mode: Mode, mac: String, now: Long): Read {
+ val liveMac = DeviceRegistry.currentAddress(mac)
+ val s = DeviceRegistry.get(liveMac) ?: DeviceRegistry.get(mac)
+ val hit = s?.best
+ val heard = s != null && now - s.lastSeen <= HEARD_MS
+ return Read(
+ mode, liveMac,
+ title = DeviceNames.of(mac) ?: hit?.label ?: s?.name ?: s?.deviceType ?: mac,
+ tag = hit?.category?.shortTag,
+ color = hit?.category?.colorArgb ?: NO_FLAG_COLOR,
+ rssi = s?.rssi?.takeIf { heard },
+ distanceM = s?.distanceM?.takeIf { heard && it > 0 },
+ trend = if (heard) trend(s!!) else 0
+ )
+ }
+
+ /** 1 getting closer, -1 moving away, 0 steady: the newest reading against the few before it. */
+ fun trend(s: DeviceRegistry.Snapshot): Int {
+ val recent = s.history.takeLast(6).dropLast(1)
+ if (recent.isEmpty()) return 0
+ val avg = recent.map { it.rssi }.average()
+ return when {
+ s.rssi > avg + 3 -> 1
+ s.rssi < avg - 3 -> -1
+ else -> 0
+ }
+ }
+
+ /** Calls [onRead] now and about once a second while there is something to read (null once it ends). Main thread. */
+ fun addListener(onRead: (Read?) -> Unit): () -> Unit {
+ listeners.add(onRead)
+ tick()
+ return { listeners.remove(onRead) }
+ }
+
+ private val ticker = Runnable { tick() }
+
+ private fun tick() {
+ main.removeCallbacks(ticker)
+ if (listeners.isEmpty()) return
+ val r = current()
+ listeners.forEach { runCatching { it(r) } }
+ if (r != null || locating != null || System.currentTimeMillis() <= pinUntil) main.postDelayed(ticker, TICK_MS)
+ }
+}
+
+/**
+ * The live read card: a rounded dark card like the map's alert card, with what is being followed, a signal bar
+ * and the rough distance, and a ✕ ([LiveRead.dismiss]). Respects Discreet mode (no name, no flag).
+ */
+internal class LiveReadCard(private val b: ViewLiveReadBinding) {
+ private val ctx = b.root.context
+
+ init {
+ b.liveClose.imageTintList = ColorStateList.valueOf(0xFFB0BAC1.toInt())
+ b.liveClose.setOnClickListener { LiveRead.dismiss() }
+ b.liveBar.track = 0x33FFFFFF
+ }
+
+ fun show(r: LiveRead.Read?) {
+ if (r == null) { b.root.visibility = View.GONE; return }
+ val discreet = Prefs.discreetMode(ctx)
+ b.liveContext.text = r.mode.label
+ b.liveTag.text = if (discreet) "" else r.tag.orEmpty()
+ b.liveTag.setTextColor(r.color)
+ b.liveTitle.text = if (discreet) "Live read" else r.title
+ b.liveDetail.text = if (r.rssi == null) "Not heard right now" else listOfNotNull(
+ "${r.rssi} dBm",
+ r.distanceM?.let { DeviceIntel.formatDistance(it) + " (rough)" },
+ when (r.trend) { 1 -> "▲ closer"; -1 -> "▼ farther"; else -> null }
+ ).joinToString(" · ")
+ val level = VisualMode.dbmLevel(r.rssi)
+ b.liveBar.set(level, VisualMode.heat(level))
+ b.liveClose.contentDescription = if (r.mode == LiveRead.Mode.LOCATE) "Stop locating" else "Hide the live read"
+ b.root.visibility = View.VISIBLE
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
index 2a16c64..197facf 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
@@ -178,6 +178,7 @@ class MapFragment : Fragment() {
private var navArgsHandled = false
private var alertCards: AlertCardController? = null
private var stopAlertCards: (() -> Unit)? = null
+ private var stopLiveRead: (() -> Unit)? = null
private var rf: RfMap? = null
private val map: MapEngine? get() = rf?.map
private var lastFix: Location? = null
@@ -294,6 +295,9 @@ class MapFragment : Fragment() {
// One that came in just before this screen opened (tapping its notification, say) is still shown.
AlertCards.latest?.takeIf { System.currentTimeMillis() - it.atMs < 6_000L }?.let { cards.show(it) }
}
+ // Locate or pinpointing: the followed device's live signal, on the full map and the main screen's pane.
+ val live = LiveReadCard(binding.liveRead)
+ stopLiveRead = LiveRead.addListener { live.show(it) }
} else {
binding.searchButton.visibility = View.GONE
}
@@ -1257,6 +1261,7 @@ class MapFragment : Fragment() {
override fun onDestroyView() {
if (safetyArmed) { safetyArmed = false; MapSafety.disarm(act) } // leaving normally is not a crash
stopAlertCards?.invoke(); stopAlertCards = null
+ stopLiveRead?.invoke(); stopLiveRead = null
alertCards?.hide(); alertCards = null
nav?.destroy(); nav = null
stopObservingBulk?.invoke()
diff --git a/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt b/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt
index 007aaef..ea6fe0f 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt
@@ -127,6 +127,14 @@ object VisualMode {
else -> 0xFFD0503C.toInt()
}
+ /** Cold blue at the weakest, warm red at the strongest (the signal gauge's scale). */
+ fun heat(level: Float): Int {
+ val stops = intArrayOf(0xFF3D7BD9.toInt(), 0xFF2EA6A0.toInt(), 0xFFE0A33A.toInt(), 0xFFD0503C.toInt())
+ val x = level.coerceIn(0f, 1f) * (stops.size - 1)
+ val i = x.toInt().coerceAtMost(stops.size - 2)
+ return android.animation.ArgbEvaluator().evaluate(x - i, stops[i], stops[i + 1]) as Int
+ }
+
/** Signal strength 0..1 over -100..-30 dBm. */
fun dbmLevel(dbm: Int?): Float = dbm?.let { ((it + 100) / 70f).coerceIn(0f, 1f) } ?: 0f
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/VisualViews.kt b/app/src/main/java/com/rfsentinel/app/ui/VisualViews.kt
index b20b278..c041614 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/VisualViews.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/VisualViews.kt
@@ -57,6 +57,8 @@ class LevelBarView @JvmOverloads constructor(context: Context, attrs: AttributeS
private val ink = ChipStyle.onSurface(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val rect = RectF()
+ /** The empty part's colour, for a bar on a background of its own (the live read card); default a faint ink. */
+ var track: Int? = null
fun set(fraction: Float, color: Int) { this.fraction = fraction.coerceIn(0f, 1f); this.color = color; invalidate() }
@@ -66,7 +68,7 @@ class LevelBarView @JvmOverloads constructor(context: Context, attrs: AttributeS
override fun onDraw(canvas: Canvas) {
val r = height / 2f
rect.set(0f, 0f, width.toFloat(), height.toFloat())
- paint.color = alpha(ink, 0x22); canvas.drawRoundRect(rect, r, r, paint)
+ paint.color = track ?: alpha(ink, 0x22); canvas.drawRoundRect(rect, r, r, paint)
if (fraction > 0f) {
rect.right = width * fraction
paint.color = color; canvas.drawRoundRect(rect, r, r, paint)
@@ -147,13 +149,7 @@ class SignalGaugeView @JvmOverloads constructor(context: Context, attrs: Attribu
private fun trendText() = when (trend) { 1 -> "getting closer"; -1 -> "moving away"; else -> "steady" }
- /** Cold blue at the weakest, warm red at the strongest. */
- private fun heat(level: Float): Int {
- val stops = intArrayOf(0xFF3D7BD9.toInt(), 0xFF2EA6A0.toInt(), 0xFFE0A33A.toInt(), 0xFFD0503C.toInt())
- val x = level.coerceIn(0f, 1f) * (stops.size - 1)
- val i = x.toInt().coerceAtMost(stops.size - 2)
- return android.animation.ArgbEvaluator().evaluate(x - i, stops[i], stops[i + 1]) as Int
- }
+ private fun heat(level: Float) = VisualMode.heat(level)
override fun onMeasure(w: Int, h: Int) {
val width = MeasureSpec.getSize(w)
diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xml
index 2978561..6b7bedc 100644
--- a/app/src/main/res/layout/activity_map.xml
+++ b/app/src/main/res/layout/activity_map.xml
@@ -283,6 +283,14 @@
android:src="@drawable/ic_nav_close"
app:tint="#B0BAC1" />
</LinearLayout>
+
+ <!-- Locate or pinpointing: the followed device's signal, live (LiveReadCard). -->
+ <include
+ android:id="@+id/liveRead"
+ layout="@layout/view_live_read"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="6dp" />
</LinearLayout>
<!-- Bottom: follow button, device filter chips, controls -->
diff --git a/app/src/main/res/layout/view_live_read.xml b/app/src/main/res/layout/view_live_read.xml
new file mode 100644
index 0000000..35d18c2
--- /dev/null
+++ b/app/src/main/res/layout/view_live_read.xml
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The live read while Locate or pinpointing follows a device (LiveReadCard): looks like the map's alert card. -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:accessibilityLiveRegion="polite"
+ android:background="@drawable/alert_card_bg"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
+ android:paddingStart="12dp"
+ android:paddingTop="10dp"
+ android:paddingEnd="4dp"
+ android:paddingBottom="10dp"
+ android:visibility="gone">
+
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/liveContext"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:letterSpacing="0.08"
+ android:maxLines="1"
+ android:textColor="#9AA5AD"
+ android:textSize="11sp" />
+
+ <TextView
+ android:id="@+id/liveTag"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:maxLines="1"
+ android:textSize="12sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+
+ <TextView
+ android:id="@+id/liveTitle"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textColor="#FFFFFF"
+ android:textSize="16sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/liveDetail"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textColor="#B0BAC1"
+ android:textSize="13sp" />
+
+ <com.rfsentinel.app.ui.LevelBarView
+ android:id="@+id/liveBar"
+ android:layout_width="match_parent"
+ android:layout_height="6dp"
+ android:layout_marginTop="6dp" />
+ </LinearLayout>
+
+ <ImageButton
+ android:id="@+id/liveClose"
+ android:layout_width="40dp"
+ android:layout_height="40dp"
+ android:layout_marginStart="4dp"
+ android:background="?android:attr/selectableItemBackgroundBorderless"
+ android:padding="10dp"
+ android:scaleType="fitCenter"
+ android:src="@drawable/ic_nav_close" />
+</LinearLayout>