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.

Visual style for nine screens, with the old list style kept as an option

CIS-C05911480951a8
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 33c463f..52dcd7f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -86,6 +86,7 @@
<activity android:name=".ui.WazeStatusActivity" android:exported="false" />
<activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" />
<activity android:name=".ui.AntennaCheckActivity" android:exported="false" />
+ <activity android:name=".ui.AircraftActivity" android:exported="false" />
<activity
android:name=".ui.SetupActivity"
android:exported="false" />
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index f6e6546..077a6f2 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -61,6 +61,10 @@ class MainActivity : AppCompatActivity() {
private var query = ""
private var deviceCount = 0
private var flaggedCount = 0
+ private var bleCount = 0
+ private var wifiCount = 0
+ /** The visual style's status: counters and hardware cards (Settings > Appearance). */
+ private val statusPanel by lazy { com.rfsentinel.app.ui.StatusPanel(this) }
private var demoMode = false
private val permissionLauncher = registerForActivityResult(
@@ -99,6 +103,9 @@ class MainActivity : AppCompatActivity() {
)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
+ (binding.statusText.parent as android.view.ViewGroup).let { p ->
+ p.addView(statusPanel.root, p.indexOfChild(binding.statusText) + 1)
+ }
binding.newAlertPill.setOnClickListener {
binding.recyclerView.smoothScrollToPosition(0)
showNewAlertPill(false)
@@ -145,13 +152,16 @@ class MainActivity : AppCompatActivity() {
menu.add(0, 3, 2, "WiFi spectrum")
menu.add(0, 4, 3, "Satellites")
menu.add(0, 5, 4, "Antenna check")
+ menu.add(0, 6, 5, "Aircraft")
setOnMenuItemClickListener { item ->
when (item.itemId) {
+ 6 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AircraftActivity::class.java)
+ .putExtra("demo", demoMode))
5 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AntennaCheckActivity::class.java)
.putExtra("demo", demoMode).putExtra("single", intent.getBooleanExtra("single", false)))
1 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.CellTowersActivity::class.java))
2 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java))
- 4 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.GnssActivity::class.java))
+ 4 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.GnssActivity::class.java).putExtra("demo", demoMode))
else -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java)
.putExtra(com.rfsentinel.app.ui.WifiAnalyzerActivity.EXTRA_SPECTRUM, true))
}
@@ -309,6 +319,36 @@ class MainActivity : AppCompatActivity() {
binding.startStopButton.setTextColor(fg)
binding.startStopButton.iconTint = android.content.res.ColorStateList.valueOf(fg)
}
+ val visual = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.STATUS)
+ binding.statusText.visibility = if (visual) View.GONE else View.VISIBLE
+ statusPanel.root.visibility = if (visual) View.VISIBLE else View.GONE
+ if (visual) {
+ val now = System.currentTimeMillis()
+ val warning = when {
+ running && !bluetoothOn() && !demoMode -> "Scanning WiFi only - turn on Bluetooth for BLE (picked up automatically)"
+ else -> listOfNotNull(
+ com.rfsentinel.app.service.CellMonitor.lastAnomaly?.takeIf { now - it.first < 15 * 60_000L }?.second?.title,
+ ScanForegroundService.lastWatchdogRestart?.takeIf { now - it.first < 10 * 60_000L }?.let {
+ "${it.second} scan restarted " + java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(it.first))
+ }
+ ).joinToString(" · ").ifEmpty { null }
+ }
+ val hardware = if (!running) emptyList() else listOfNotNull(
+ com.rfsentinel.app.esp.OuiSpyBle.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) },
+ com.rfsentinel.app.esp.EspBoards.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) },
+ com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let {
+ com.rfsentinel.app.ui.StatusPanel.Hardware(it, { com.rfsentinel.app.usb.MonitorFrames.frameCount.get() }, " frames/s")
+ },
+ com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let {
+ com.rfsentinel.app.ui.StatusPanel.Hardware(it,
+ if (it.contains("ADS-B")) ({ com.rfsentinel.app.sdr.SdrRadio.adsbMessages }) else null, " msg/s")
+ },
+ com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }
+ ?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) }
+ )
+ statusPanel.update(running, bleCount, wifiCount, liveCellCount(now), flaggedCount, warning, hardware)
+ return
+ }
binding.statusText.text = when {
!running -> "Idle - tap Start to listen for nearby devices"
!bluetoothOn() && !demoMode -> "Scanning WiFi only - turn on Bluetooth for BLE (picked up automatically)"
@@ -458,6 +498,9 @@ class MainActivity : AppCompatActivity() {
val threshold = Prefs.alertThreshold(this)
binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && panes.listShown
deviceCount = all.size
+ bleCount = all.count { Advert.Source.BLE in it.sources }
+ wifiCount = all.count { Advert.Source.WIFI in it.sources }
+ adapter.visual = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.DEVICE_LIST)
// The banner and radar alert only for flagged devices still in range.
val flagged = all.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }
flaggedCount = flagged.size
@@ -582,7 +625,8 @@ class MainActivity : AppCompatActivity() {
tagColor = w.report.type.color,
highlight = if (urgent) w.report.type.color else null,
flashing = urgent,
- bold = urgent
+ bold = urgent,
+ confidence = w.hit.confidence
)
}
}
@@ -617,7 +661,8 @@ class MainActivity : AppCompatActivity() {
tagColor = color,
highlight = if (urgent) color else null,
flashing = urgent,
- bold = live
+ bold = live,
+ confidence = r.confidence
)
}
}
@@ -647,7 +692,8 @@ class MainActivity : AppCompatActivity() {
(c.dbm?.let { " · $it dBm" } ?: "") + " · " + (if (ageSec < 2) "now" else "${ageSec}s ago"),
tag = if (c.registered) "CELL · serving" else "CELL",
tagColor = 0xFF5E35B1.toInt(),
- highlight = null, flashing = false, bold = c.registered
+ highlight = null, flashing = false, bold = c.registered,
+ rssi = c.dbm, barBoost = 10
)
}
}
@@ -705,7 +751,9 @@ class MainActivity : AppCompatActivity() {
bold = alert,
heardByEsp = com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac, now),
heardByUsb = com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac, now),
- heardByPhone = com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac, now)
+ heardByPhone = com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac, now),
+ rssi = s.rssi,
+ confidence = best?.confidence?.takeIf { !whitelisted }
)
}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt b/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt
index 59f03b8..fc1fe84 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt
@@ -33,7 +33,7 @@ class GnssAnalyzer {
}
data class Sat(val system: System, val svid: Int, val cn0: Float, val elevation: Float, val usedInFix: Boolean,
- val carrierMhz: Float? = null)
+ val carrierMhz: Float? = null, val azimuth: Float = 0f)
/** One receiver report: the satellites, and the input gain when the phone reports it. */
data class Snapshot(val time: Long, val sats: List<Sat>, val agcDb: Double? = null)
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
index 2cd5a62..9660451 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
@@ -31,6 +31,18 @@ object WazeStatus {
/** From the last answer: reports on the map, and how many of them are inside the alert range. */
@Volatile var onMap = 0
@Volatile var inAlertRange = 0
+
+ /** One finished check, for the status screen's timeline: when, how long it took, the reports it gave, whether it answered. */
+ class Check(val at: Long, val ms: Long, val reports: Int, val ok: Boolean)
+
+ /** The last [KEEP] checks, oldest first. */
+ val recent = java.util.concurrent.ConcurrentLinkedDeque<Check>()
+ const val KEEP = 20
+
+ fun record(c: Check) {
+ recent.addLast(c)
+ while (recent.size > KEEP) recent.pollFirst()
+ }
}
/**
@@ -131,6 +143,7 @@ class WazeWatch(
WazeStatus.lastCheckAt = now
WazeStatus.lastCheckMs = SystemClock.elapsedRealtime() - began
WazeStatus.checks++
+ WazeStatus.record(WazeStatus.Check(now, WazeStatus.lastCheckMs, WazeStatus.onMap, lastOkAt >= now))
} else {
// No GPS fix or key yet: look again in a few seconds instead of waiting out the interval.
lastStart = now - every * 1000L + RETRY_MS
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
index 1b3ad1b..b9d66cc 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -32,6 +32,8 @@ object SdrRadio {
private const val ADSB_PUSH_MS = 2_000L
@Volatile var status: String = ""; private set
+ /** ADS-B messages decoded since the app started, for the main screen's messages-per-second line. */
+ @Volatile var adsbMessages = 0L; private set
/** What to watch (Settings > RTL-SDR radio); picked up at the next sweep. */
@Volatile var config = RadioWatch.Config()
private var receiver: BroadcastReceiver? = null
@@ -165,6 +167,7 @@ object SdrRadio {
val me = location?.invoke()
for (f in frames) tracker.add(f, now, me?.first, me?.second)
messages += frames.size
+ adsbMessages += frames.size
System.arraycopy(mag, total - ModeS.OVERLAP, mag, 0, ModeS.OVERLAP)
have = ModeS.OVERLAP
if (now - lastPush >= ADSB_PUSH_MS) {
diff --git a/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
index 9f39b45..a75da8b 100644
--- a/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
@@ -40,7 +40,8 @@ object GnssWatch {
GnssAnalyzer.Sat(
GnssAnalyzer.System.of(status.getConstellationType(i)), status.getSvid(i), status.getCn0DbHz(i),
status.getElevationDegrees(i), status.usedInFix(i),
- if (status.hasCarrierFrequencyHz(i)) status.getCarrierFrequencyHz(i) / 1e6f else null
+ if (status.hasCarrierFrequencyHz(i)) status.getCarrierFrequencyHz(i) / 1e6f else null,
+ status.getAzimuthDegrees(i)
)
}
val snap = GnssAnalyzer.Snapshot(now, sats, agcDb?.takeIf { now - agcAt < 5_000L })
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index 8f229b1..1b70f44 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -1814,6 +1814,24 @@ class SettingsActivity : AppCompatActivity() {
btn("Import a theme file...") { themeFilePicker.launch(arrayOf("application/json", "text/plain", "*/*")) }
info(row.getChildAt(0), "Make your own theme: colours, font, banner, header and map marker. Export it as a file to share it.")
box.addView(row, at + 1)
+ setupScreenStyle()
+ }
+
+ /** Per screen: the visual style (gauges, bars, charts) or the plain list it had before. */
+ private fun setupScreenStyle() {
+ val box = binding.sectionAppearance
+ val dp = resources.displayMetrics.density
+ box.addView(infoRow(android.widget.TextView(this).apply {
+ text = "Screen style"; setPadding(0, (14 * dp).toInt(), 0, 0); textSize = 13f
+ }, "On: the screen shows gauges, signal bars and charts.\n\nOff: the plain text list it had before.\n\n" +
+ "Each of these screens also has a list / visual button at the top to switch it there."))
+ com.rfsentinel.app.ui.VisualMode.Screen.values().forEach { s ->
+ box.addView(SwitchMaterial(this).apply {
+ text = s.label
+ isChecked = com.rfsentinel.app.ui.VisualMode.on(this@SettingsActivity, s)
+ setOnCheckedChangeListener { _, on -> com.rfsentinel.app.ui.VisualMode.set(this@SettingsActivity, s, on) }
+ }, android.widget.LinearLayout.LayoutParams(-1, -2))
+ }
}
override fun onDestroy() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
new file mode 100644
index 0000000..0dd174b
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
@@ -0,0 +1,239 @@
+package com.rfsentinel.app.ui
+
+import android.annotation.SuppressLint
+import android.content.Intent
+import android.graphics.Typeface
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.rfsentinel.app.databinding.ActivityLogBinding
+import com.rfsentinel.app.databinding.ItemDetectionBinding
+import com.rfsentinel.app.online.PoliceAircraft
+import com.rfsentinel.app.sdr.SdrRadio
+import com.rfsentinel.app.service.DeviceRegistry
+import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.util.Units
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import java.util.Locale
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.sin
+
+/**
+ * The aircraft around you, from the RTL-SDR's ADS-B receiver and the online feeds (when on): as a
+ * radar seen from above, or as a list, nearest first. Law-enforcement ones are marked. Tap one to
+ * see it on the map.
+ */
+class AircraftActivity : AppCompatActivity() {
+
+ private lateinit var binding: ActivityLogBinding
+
+ /** One aircraft with where it is from you. */
+ private class Row(val seen: PoliceAircraft.Seen, val distanceKm: Double?, val bearingDeg: Double?)
+
+ private var rows: List<Row> = emptyList()
+ private val demo get() = com.rfsentinel.app.BuildConfig.DEBUG && intent.getBooleanExtra("demo", false)
+
+ private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
+ override fun getItemCount() = rows.size
+ override 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) {
+ val r = rows[position]
+ val p = r.seen.plane
+ ItemDetectionBinding.bind(holder.itemView).apply {
+ labelText.text = name(p) + if (r.seen.hit != null) " · ${r.seen.hit.label}" else ""
+ labelText.setTextColor(if (r.seen.hit != null) POLICE else macText.currentTextColor)
+ macText.text = listOfNotNull(p.type, p.owner, p.registration?.takeIf { it != name(p) }).joinToString(" · ").ifEmpty { p.hex.uppercase() }
+ metaText.text = listOfNotNull(
+ r.distanceKm?.let { Units.distance(it * 1000) + (r.bearingDeg?.let { b -> " ${compass(b)}" } ?: "") },
+ altitude(p), p.speedKt?.let { String.format(Locale.US, "%.0f kt", it) }, p.trackDeg?.let { "heading ${it.toInt()}°" }
+ ).joinToString(" · ")
+ }
+ holder.itemView.setOnClickListener { openOnMap(p) }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityLogBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.root.applySystemBarInsets()
+ title = "Aircraft"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding.recyclerView.layoutManager = LinearLayoutManager(this)
+ binding.recyclerView.adapter = adapter
+ binding.root.addView(visual.root, 0)
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(1_000) }
+ }
+ }
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.AIRCRAFT); return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.AIRCRAFT) { invalidateOptionsMenu(); refresh() } || super.onOptionsItemSelected(item)
+
+ private val visual by lazy { Visual() }
+
+ /** The visual style: counts, the radar, and the RTL-SDR's messages per second. */
+ private inner class Visual {
+ val ctx = this@AircraftActivity
+ val dp = resources.displayMetrics.density
+ val accent = ChipStyle.accent(ctx).first
+ val box = LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL }
+ val root = android.widget.ScrollView(ctx).apply { addView(box); visibility = View.GONE }
+ val tiles = listOf(VisualMode.tile(ctx, "0", "aircraft", accent), VisualMode.tile(ctx, "0", "law enforcement", POLICE),
+ VisualMode.tile(ctx, "–", "nearest", accent))
+ val radar = AircraftRadarView(ctx)
+ val sources = TextView(ctx).apply { textSize = 12f; alpha = 0.8f }
+ val rateCard: LinearLayout
+ val rate = SparklineView(ctx)
+ val rateText = TextView(ctx).apply { textSize = 12f; alpha = 0.8f }
+ val history = ArrayDeque<Float>()
+ var lastCount = -1L
+ var lastAt = 0L
+
+ fun title(t: String) = TextView(ctx).apply {
+ text = t; textSize = 12f; setTypeface(typeface, Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
+ }
+
+ fun card(vararg views: View) = LinearLayout(ctx).apply {
+ orientation = LinearLayout.VERTICAL
+ background = VisualMode.card(ctx)
+ val p = (12 * dp).toInt(); setPadding(p, p, p, p)
+ views.forEach { addView(it) }
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ }
+
+ init {
+ box.addView(VisualMode.tileRow(ctx, tiles).apply {
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ })
+ box.addView(card(title("RADAR · NORTH UP"), radar, sources))
+ rateCard = card(title("RTL-SDR · ADS-B MESSAGES PER SECOND"), rate, rateText)
+ box.addView(rateCard)
+ }
+
+ fun value(tile: View, v: String) { ((tile as LinearLayout).getChildAt(0) as TextView).text = v }
+
+ fun show(list: List<Row>) {
+ value(tiles[0], "${list.size}")
+ value(tiles[1], "${list.count { it.seen.hit != null }}")
+ value(tiles[2], list.firstNotNullOfOrNull { it.distanceKm }?.let { Units.distance(it * 1000) } ?: "–")
+ val far = list.mapNotNull { it.distanceKm }.maxOrNull() ?: 0.0
+ val range = listOf(10.0, 25.0, 50.0, 100.0, 200.0).firstOrNull { far <= it } ?: 200.0
+ radar.set(list.mapNotNull { r ->
+ val d = r.distanceKm ?: return@mapNotNull null
+ val b = r.bearingDeg ?: return@mapNotNull null
+ AircraftRadarView.Blip(b, d, r.seen.plane.trackDeg, name(r.seen.plane), altitude(r.seen.plane), r.seen.hit != null)
+ }, range)
+ val now = System.currentTimeMillis()
+ val mine = if (now - PoliceAircraft.localAt <= 30_000L) PoliceAircraft.local.size else 0
+ val online = if (now - PoliceAircraft.latestAt <= 3 * 60_000L) PoliceAircraft.latest.size else 0
+ sources.text = if (demo) "Demo aircraft" else "RTL-SDR: $mine · online feeds: $online" +
+ if (list.any { it.distanceKm == null }) " · ${list.count { it.distanceKm == null }} not placed (no position yet)" else ""
+ // The RTL-SDR's receiver: messages decoded per second over the last minute.
+ val adsb = SdrRadio.status.contains("ADS-B")
+ rateCard.visibility = if (adsb) View.VISIBLE else View.GONE
+ if (adsb) {
+ val n = SdrRadio.adsbMessages
+ if (lastCount >= 0 && now - lastAt >= 900) {
+ history.addLast((n - lastCount).coerceAtLeast(0) * 1000f / (now - lastAt))
+ while (history.size > 60) history.removeFirst()
+ }
+ if (lastCount < 0 || now - lastAt >= 900) { lastCount = n; lastAt = now }
+ rate.set(history.toFloatArray(), accent, 5f)
+ rateText.text = history.lastOrNull()?.let { String.format(Locale.US, "%.0f messages/s now", it) } ?: "Counting…"
+ }
+ }
+ }
+
+ @SuppressLint("NotifyDataSetChanged")
+ private fun refresh() {
+ val now = System.currentTimeMillis()
+ val me = if (demo) (DemoData.fakeLocation?.let { it.latitude to it.longitude } ?: (0.0 to 0.0))
+ else ScanForegroundService.lastFix?.let { it.latitude to it.longitude }
+ val seen = if (demo) demoAircraft(me!!) else PoliceAircraft.all(now)
+ rows = seen.map { s ->
+ val p = s.plane
+ if (me == null) Row(s, null, null)
+ else Row(s, DeviceRegistry.metersBetween(me.first, me.second, p.lat, p.lon) / 1000, bearing(me.first, me.second, p.lat, p.lon))
+ }.sortedWith(compareByDescending<Row> { it.seen.hit != null }.thenBy { it.distanceKm ?: Double.MAX_VALUE })
+ val visualOn = VisualMode.on(this, VisualMode.Screen.AIRCRAFT)
+ val empty = when {
+ rows.isNotEmpty() -> null
+ !ScanForegroundService.isRunning && !demo -> "Not scanning.\nAircraft come from an RTL-SDR on USB (ADS-B) or the online feeds, while scanning."
+ else -> "No aircraft heard yet.\nThey come from an RTL-SDR on USB set to ADS-B, or from the online feeds when that's on in Settings."
+ }
+ visual.root.visibility = if (visualOn && empty == null) View.VISIBLE else View.GONE
+ binding.recyclerView.visibility = if (!visualOn && empty == null) View.VISIBLE else View.GONE
+ if (visualOn) visual.show(rows) else adapter.notifyDataSetChanged()
+ binding.emptyText.text = empty.orEmpty()
+ binding.emptyText.visibility = if (empty != null) View.VISIBLE else View.GONE
+ }
+
+ private fun openOnMap(p: PoliceAircraft.Plane) {
+ startActivity(Intent(this, MapActivity::class.java)
+ .putExtra(MapActivity.EXTRA_CENTER_LAT, p.lat)
+ .putExtra(MapActivity.EXTRA_CENTER_LON, p.lon))
+ }
+
+ private fun name(p: PoliceAircraft.Plane) = p.callsign?.trim()?.ifEmpty { null } ?: p.registration ?: p.hex.uppercase()
+
+ private fun altitude(p: PoliceAircraft.Plane): String? = p.altitudeFt?.let {
+ if (Units.imperial) String.format(Locale.US, "%,d ft", it) else String.format(Locale.US, "%,d m", (it * 0.3048).toInt())
+ }
+
+ private fun compass(deg: Double) = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")[((deg + 22.5) / 45).toInt() % 8]
+
+ private fun bearing(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
+ val p1 = Math.toRadians(lat1); val p2 = Math.toRadians(lat2); val dl = Math.toRadians(lon2 - lon1)
+ val y = sin(dl) * cos(p2)
+ val x = cos(p1) * sin(p2) - sin(p1) * cos(p2) * cos(dl)
+ return (Math.toDegrees(atan2(y, x)) + 360) % 360
+ }
+
+ /** Debug builds' demo: a few made-up aircraft around [me], drifting along their headings. */
+ private fun demoAircraft(me: Pair<Double, Double>): List<PoliceAircraft.Seen> {
+ val t = (System.currentTimeMillis() / 1000 % 600) / 3600.0
+ fun plane(hex: String, call: String, km: Double, brg: Double, trk: Double, ft: Int, kt: Double, police: Boolean): PoliceAircraft.Seen {
+ val moved = km + kt * 1.852 * t * cos(Math.toRadians(trk - brg))
+ val lat = me.first + moved / 111.0 * cos(Math.toRadians(brg))
+ val lon = me.second + moved / (111.0 * cos(Math.toRadians(me.first)).coerceAtLeast(0.1)) * sin(Math.toRadians(brg))
+ val p = PoliceAircraft.Plane(hex, call, null, if (police) "Helicopter" else "Airliner", if (police) "Demo police air unit" else null,
+ lat, lon, ft, kt, trk, false)
+ val hit = if (police) com.rfsentinel.app.detect.Hit(com.rfsentinel.app.detect.Category.AIRCRAFT, "Police helicopter", 85,
+ "Demo data", "Demo") else null
+ return PoliceAircraft.Seen(p, hit)
+ }
+ return listOf(
+ plane("demo01", "POLICE1", 6.0, 40.0, 120.0, 1500, 90.0, true),
+ plane("demo02", "DEMO123", 28.0, 200.0, 20.0, 31000, 450.0, false),
+ plane("demo03", "DEMO456", 15.0, 300.0, 250.0, 12000, 280.0, false),
+ plane("demo04", "DEMO789", 40.0, 110.0, 300.0, 36000, 470.0, false)
+ )
+ }
+
+ companion object {
+ private val POLICE = 0xFFD0503C.toInt()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
index 0c06dcd..bbebe54 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
@@ -42,28 +42,59 @@ class CellTowersActivity : AppCompatActivity() {
data class Header(val text: String) : Row
data class Live(val cell: CellAnalyzer.Cell) : Row
data class Seen(val tower: CellTowerStore.Tower) : Row
+ /** Visual style: the serving cell as a card with its signal over the last minutes. */
+ data class Serving(val cell: CellAnalyzer.Cell) : Row
}
+ private val visualOn get() = VisualMode.on(this, VisualMode.Screen.CELLS)
+
+ /** The serving cell's signal at each refresh (time, dBm), and when the phone last moved to another tower. */
+ private val servingHistory = ArrayDeque<Pair<Long, Int>>()
+ private var servingKey: String? = null
+ private var servingChangedAt = 0L
+
private var rows: List<Row> = emptyList()
private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun getItemCount() = rows.size
- override fun getItemViewType(position: Int) = if (rows[position] is Row.Header) 0 else 1
+ override fun getItemViewType(position: Int) = when (rows[position]) {
+ is Row.Header -> 0
+ is Row.Serving -> 3
+ else -> if (visualOn) 2 else 1
+ }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
- val v = if (viewType == 0) TextView(parent.context).apply {
- setTypeface(typeface, Typeface.BOLD)
- textSize = 15f
- setPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())
- } else ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
+ val v = when (viewType) {
+ 0 -> TextView(parent.context).apply {
+ setTypeface(typeface, Typeface.BOLD)
+ textSize = 15f
+ setPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())
+ }
+ 3 -> ServingCard()
+ // Visual rows: signal bars beside the usual three lines.
+ 2 -> android.widget.LinearLayout(parent.context).apply {
+ orientation = android.widget.LinearLayout.HORIZONTAL
+ gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(SignalBarsView(parent.context),
+ android.widget.LinearLayout.LayoutParams(-2, -2).apply { marginEnd = (4 * resources.displayMetrics.density).toInt() })
+ addView(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), this, false).root,
+ android.widget.LinearLayout.LayoutParams(0, -2, 1f))
+ layoutParams = RecyclerView.LayoutParams(-1, -2)
+ }
+ else -> ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
+ }
return object : RecyclerView.ViewHolder(v) {}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
+ val v = holder.itemView
+ val bars = (v as? android.widget.LinearLayout)?.getChildAt(0) as? SignalBarsView
+ val item = if (bars != null) (v as android.widget.LinearLayout).getChildAt(1) else v
when (val r = rows[position]) {
- is Row.Header -> (holder.itemView as TextView).text = r.text
- is Row.Live -> bindLive(ItemDetectionBinding.bind(holder.itemView), r.cell)
- is Row.Seen -> bindSeen(ItemDetectionBinding.bind(holder.itemView), r.tower)
+ is Row.Header -> (v as TextView).text = r.text
+ is Row.Serving -> (v as ServingCard).bind(r.cell)
+ is Row.Live -> { bindLive(ItemDetectionBinding.bind(item), r.cell); bars?.set(r.cell.dbm?.let { it + CELL_OFFSET }) }
+ is Row.Seen -> { bindSeen(ItemDetectionBinding.bind(item), r.tower); bars?.set(r.tower.bestDbm?.let { it + CELL_OFFSET }) }
}
}
}
@@ -95,6 +126,74 @@ class CellTowersActivity : AppCompatActivity() {
override fun onSupportNavigateUp(): Boolean { finish(); return true }
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.CELLS); return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.CELLS) {
+ invalidateOptionsMenu(); lifecycleScope.launch { refresh() }
+ } || super.onOptionsItemSelected(item)
+
+ /** The serving cell, big: its radio and network, signal now with bars, and a line of its signal over the last 5 minutes. */
+ private inner class ServingCard : android.widget.LinearLayout(this@CellTowersActivity) {
+ private val dp = resources.displayMetrics.density
+ private val accent = ChipStyle.accent(context).first
+ private val ratChip = TextView(context).apply { textSize = 12f; setTypeface(typeface, Typeface.BOLD) }
+ private val title = TextView(context).apply { textSize = 17f; setTypeface(typeface, Typeface.BOLD) }
+ private val dbm = TextView(context).apply { textSize = 34f; setTypeface(typeface, Typeface.BOLD) }
+ private val unit = TextView(context).apply { textSize = 13f; alpha = 0.75f; text = " dBm" }
+ private val bars = SignalBarsView(context)
+ private val spark = SparklineView(context)
+ private val sparkLabel = TextView(context).apply { textSize = 11f; alpha = 0.7f }
+ private val idText = TextView(context).apply { textSize = 12f; typeface = Typeface.MONOSPACE; alpha = 0.85f }
+
+ init {
+ orientation = VERTICAL
+ background = VisualMode.card(context)
+ val p = (14 * dp).toInt(); setPadding(p, p, p, p)
+ layoutParams = RecyclerView.LayoutParams(-1, -2).apply { topMargin = (8 * dp).toInt() }
+ addView(android.widget.LinearLayout(context).apply {
+ orientation = HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(TextView(context).apply {
+ text = "SERVING CELL"; textSize = 12f; setTypeface(typeface, Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
+ }, LayoutParams(0, -2, 1f))
+ addView(ratChip)
+ })
+ addView(title, LayoutParams(-1, -2).apply { topMargin = (4 * dp).toInt() })
+ addView(android.widget.LinearLayout(context).apply {
+ orientation = HORIZONTAL; gravity = android.view.Gravity.BOTTOM
+ addView(dbm); addView(unit, LayoutParams(0, -2, 1f).apply { bottomMargin = (7 * dp).toInt() })
+ addView(bars, LayoutParams((40 * dp).toInt(), (30 * dp).toInt()).apply { bottomMargin = (8 * dp).toInt() })
+ })
+ addView(spark, LayoutParams(-1, (44 * dp).toInt()).apply { topMargin = (4 * dp).toInt() })
+ addView(sparkLabel)
+ addView(idText, LayoutParams(-1, -2).apply { topMargin = (6 * dp).toInt() })
+ }
+
+ fun bind(c: CellAnalyzer.Cell) {
+ val level = VisualMode.dbmLevel(c.dbm?.let { it + CELL_OFFSET })
+ val color = VisualMode.levelColor(level)
+ ratChip.text = c.rat.label
+ VisualMode.chip(ratChip, accent)
+ title.text = network(c.mcc, c.mnc, c.operator).ifEmpty { "Unknown network" }
+ dbm.text = c.dbm?.toString() ?: "--"
+ dbm.setTextColor(color)
+ bars.set(c.dbm?.let { it + CELL_OFFSET }, color)
+ val now = System.currentTimeMillis()
+ // One slot per refresh over the last 5 minutes, NaN where none.
+ val slots = (HISTORY_MS / REFRESH_MS).toInt()
+ val values = FloatArray(slots) { Float.NaN }
+ servingHistory.filter { now - it.first <= HISTORY_MS }.forEach { (t, v) ->
+ values[(slots - 1 - ((now - t) / REFRESH_MS).toInt()).coerceIn(0, slots - 1)] = v.toFloat()
+ }
+ spark.set(values, color, 6f)
+ sparkLabel.text = "Last 5 minutes" + if (servingChangedAt > 0 && now - servingChangedAt < HISTORY_MS)
+ " · moved to this tower at ${DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(servingChangedAt))}" else ""
+ idText.text = ids(c.rat, c.area, c.cellId, c.pci, c.channel)
+ }
+ }
+
private suspend fun refresh() {
if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
show(emptyList(), "Cell information needs the location permission.\nStart a scan once to grant it.")
@@ -107,9 +206,23 @@ class CellTowersActivity : AppCompatActivity() {
val seen = CellTowerStore.all(this).sortedByDescending { it.lastSeen }
val out = ArrayList<Row>()
- out += Row.Header("Now · ${live.size} ${if (live.size == 1) "cell" else "cells"}")
- live.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })
- .forEach { out += Row.Live(it) }
+ val sorted = live.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })
+ val serving = sorted.firstOrNull { it.registered }
+ val now = System.currentTimeMillis()
+ if (serving != null) {
+ if (servingKey != null && servingKey != serving.key) servingChangedAt = now
+ servingKey = serving.key
+ serving.dbm?.let { servingHistory.addLast(now to it) }
+ while (servingHistory.isNotEmpty() && now - servingHistory.first().first > HISTORY_MS) servingHistory.removeFirst()
+ }
+ if (visualOn && serving != null) {
+ out += Row.Serving(serving)
+ if (sorted.size > 1) out += Row.Header("Neighbours · ${sorted.size - 1}")
+ sorted.filter { it !== serving }.forEach { out += Row.Live(it) }
+ } else {
+ out += Row.Header("Now · ${live.size} ${if (live.size == 1) "cell" else "cells"}")
+ sorted.forEach { out += Row.Live(it) }
+ }
out += Row.Header("Seen while scanning · ${seen.size}")
seen.forEach { out += Row.Seen(it) }
val empty = if (live.isEmpty() && seen.isEmpty())
@@ -196,5 +309,8 @@ class CellTowersActivity : AppCompatActivity() {
companion object {
private const val REFRESH_MS = 5_000L
+ private const val HISTORY_MS = 5 * 60_000L
+ /** Cell signals run about 10 dB lower than WiFi and Bluetooth for the same bars. */
+ private const val CELL_OFFSET = 10
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
index 9859a54..2f516fd 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
@@ -28,7 +28,12 @@ data class DeviceRow(
/** Heard by an ESP32 board (blue badge) and/or the phone's own radios (green badge). */
val heardByEsp: Boolean = false,
val heardByUsb: Boolean = false,
- val heardByPhone: Boolean = false
+ val heardByPhone: Boolean = false,
+ /** For the visual style: the signal for the bars (null = none), and the match's confidence (null = not a match). */
+ val rssi: Int? = null,
+ val confidence: Int? = null,
+ /** Added to [rssi] for the bars only: cell signals run about 10 dB lower than WiFi and Bluetooth. */
+ val barBoost: Int = 0
)
private const val ESP_BADGE = 0xFF1E88E5.toInt()
@@ -59,6 +64,11 @@ class DeviceAdapter(
private val onLongPress: (DeviceRow) -> Unit
) : ListAdapter<DeviceRow, DeviceAdapter.VH>(Diff) {
+ /** Visual style: signal bars and a confidence bar on each row (Settings > Appearance, or the list's own choice). */
+ @android.annotation.SuppressLint("NotifyDataSetChanged")
+ var visual = false
+ set(v) { if (field != v) { field = v; notifyDataSetChanged() } }
+
object Diff : DiffUtil.ItemCallback<DeviceRow>() {
override fun areItemsTheSame(a: DeviceRow, b: DeviceRow) = a.mac == b.mac
override fun areContentsTheSame(a: DeviceRow, b: DeviceRow) = a == b
@@ -121,6 +131,14 @@ class DeviceAdapter(
b.titleText.setTypeface(null, if (row.bold) Typeface.BOLD else Typeface.NORMAL)
b.macText.text = row.subtitle
b.metaText.text = metaWithBadges(row)
+ val conf = row.confidence
+ b.confidenceBar.visibility = if (visual && conf != null) View.VISIBLE else View.GONE
+ if (visual && conf != null) b.confidenceBar.set(conf / 100f, row.tagColor)
+ b.signalBox.visibility = if (visual && row.rssi != null) View.VISIBLE else View.GONE
+ if (visual && row.rssi != null) {
+ b.signalBars.set(row.rssi + row.barBoost)
+ b.signalText.text = "${row.rssi}"
+ }
holder.setHighlight(row.highlight, row.flashing)
holder.itemView.setOnClickListener { onClick(row) }
holder.itemView.setOnLongClickListener { onLongPress(row); true }
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 218d4d0..2cea0fc 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -120,6 +120,16 @@ class DeviceDetailActivity : AppCompatActivity() {
return true
}
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.DEVICE_DETAIL); return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.DEVICE_DETAIL) { invalidateOptionsMenu(); refresh() } ||
+ super.onOptionsItemSelected(item)
+
+ private val visual get() = VisualMode.on(this, VisualMode.Screen.DEVICE_DETAIL)
+
override fun onPause() {
stopLocate()
super.onPause()
@@ -161,25 +171,40 @@ class DeviceDetailActivity : AppCompatActivity() {
else -> "In range · heard ${ago(now - s.lastSeen)} · ${s.sightings} packets received"
}
+ // Visual style: the dial and ring take the place of the big number.
+ val visual = this.visual
+ binding.visualTop.visibility = if (visual) View.VISIBLE else View.GONE
+ binding.rssiText.visibility = if (visual) View.GONE else View.VISIBLE
+ val ringHit = best?.takeIf { !whitelisted }
+ binding.ring.visibility = if (ringHit != null) View.VISIBLE else View.GONE
+ if (ringHit != null) binding.ring.set(ringHit.confidence,
+ ThemeManager.ink(this, if (ringHit.tier == Tier.WEAK) 0xFFB26A00.toInt() else ringHit.category.colorArgb),
+ ringHit.tier.label.lowercase() + " match")
+
// 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 trend = if (recent.isEmpty()) "" else {
+ val trendDir = if (recent.isEmpty()) 0 else {
val avg = recent.map { it.rssi }.average()
when {
- live.rssi > avg + 3 -> " ↑ getting closer"
- live.rssi < avg - 3 -> " ↓ moving away"
- else -> " → steady"
+ live.rssi > avg + 3 -> 1
+ live.rssi < avg - 3 -> -1
+ else -> 0
}
}
- binding.rssiDetail.text = "dBm · ${ProximityUtil.band(live.rssi)} $trend\n" +
+ val trend = if (recent.isEmpty()) "" else when (trendDir) {
+ 1 -> " ↑ getting closer"; -1 -> " ↓ moving away"; else -> " → steady"
+ }
+ binding.gauge.set(live.rssi, live.bestRssi, trendDir)
+ binding.rssiDetail.text = (if (visual) "${ProximityUtil.band(live.rssi)}\n" else "dBm · ${ProximityUtil.band(live.rssi)} $trend\n") +
"${DeviceIntel.formatDistance(live.distanceM)} (rough) · best ${live.bestRssi} dBm" +
(if (liveMac != mac) "\nNow heard as $liveMac" else "")
binding.graph.setSamples(live.history)
binding.locateButton.isEnabled = true
} else {
binding.rssiText.text = "--"
+ binding.gauge.set(null, null, 0)
binding.rssiDetail.text = "Not currently heard"
binding.graph.setSamples(emptyList())
binding.locateButton.isEnabled = false
@@ -201,7 +226,7 @@ class DeviceDetailActivity : AppCompatActivity() {
// Sections: rebuilt only when their content changes (keeps scroll & selection stable).
val content = buildSections(s)
- val key = content.joinToString("|") { it.first + it.second.joinToString { r -> r.first + r.second } }
+ val key = visual.toString() + content.joinToString("|") { it.first + it.second.joinToString { r -> r.first + r.second } }
if (key != sectionsKey) {
sectionsKey = key
renderSections(content)
@@ -348,6 +373,7 @@ class DeviceDetailActivity : AppCompatActivity() {
val container = binding.sections
container.removeAllViews()
val dp = resources.displayMetrics.density
+ val hits = DeviceRegistry.get(mac)?.hits.orEmpty()
for ((title, rows) in sections) {
container.addView(TextView(this).apply {
text = title
@@ -355,6 +381,10 @@ class DeviceDetailActivity : AppCompatActivity() {
setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
setPadding(0, (18 * dp).toInt(), 0, (4 * dp).toInt())
})
+ if (visual && title == "Why it's flagged" && hits.isNotEmpty()) {
+ hits.forEach { container.addView(hitCard(it)) }
+ continue
+ }
for ((k, v) in rows) {
container.addView(LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
@@ -380,6 +410,59 @@ class DeviceDetailActivity : AppCompatActivity() {
}
}
+ /** Visual style: one card per match, with its confidence as a bar and what it rests on as chips. */
+ private fun hitCard(h: com.rfsentinel.app.detect.Hit): View {
+ val dp = resources.displayMetrics.density
+ val color = ThemeManager.ink(this, if (h.tier == Tier.WEAK) 0xFFB26A00.toInt() else h.category.colorArgb)
+ return LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ background = VisualMode.card(this@DeviceDetailActivity, color, 0x18, 0x77, 14f)
+ val p = (12 * dp).toInt(); setPadding(p, p, p, p)
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = (4 * dp).toInt(); bottomMargin = (4 * dp).toInt() }
+ addView(LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(TextView(context).apply {
+ text = h.label; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
+ }, LinearLayout.LayoutParams(0, -2, 1f))
+ addView(TextView(context).apply {
+ text = "${h.confidence}%"; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f); setTextColor(color)
+ })
+ })
+ addView(LevelBarView(context).apply { set(h.confidence / 100f, color) },
+ LinearLayout.LayoutParams(-1, (6 * dp).toInt()).apply { topMargin = (6 * dp).toInt(); bottomMargin = (8 * dp).toInt() })
+ addView(com.google.android.material.chip.ChipGroup(context).apply {
+ chipSpacingVertical = (4 * dp).toInt()
+ addView(VisualMode.chip(context, "${h.category.title} · ${h.tier.label}", color))
+ evidenceKinds(h.evidence).forEach { addView(VisualMode.chip(context, it, ChipStyle.accent(context).first)) }
+ })
+ addView(TextView(context).apply {
+ text = h.evidence; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
+ setPadding(0, (8 * dp).toInt(), 0, 0)
+ })
+ addView(TextView(context).apply {
+ text = "Source: ${h.source}"; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f); alpha = 0.7f
+ setPadding(0, (4 * dp).toInt(), 0, 0)
+ })
+ }
+ }
+
+ /** What a match's evidence rests on, as short chip labels. */
+ private fun evidenceKinds(evidence: String): List<String> {
+ val e = evidence.lowercase()
+ return buildList {
+ if ("service uuid" in e || "uuid" in e) add("Service UUID")
+ if ("company id" in e || "manufacturer data" in e) add("Company ID")
+ if ("payload" in e || "tag" in e) add("Payload")
+ if ("name" in e) add("Name")
+ if ("oui" in e || "address prefix" in e || "mac prefix" in e || "registrant" in e) add("Address prefix")
+ if ("probe" in e || "fingerprint" in e) add("Probe")
+ if ("remote id" in e) add("Remote ID")
+ if ("following" in e || "moving with you" in e || "with you" in e) add("Follows you")
+ if ("corroborated" in e) add("Corroborated")
+ if ("ssid" in e || "network" in e) add("WiFi")
+ }.distinct()
+ }
+
private fun addDroneButtons(container: LinearLayout) {
val r = DeviceRegistry.get(mac)?.remoteId ?: return
if (r.hasPosition) container.addView(mapButton("Drone on map", r.latitude!!, r.longitude!!, "Drone ${r.uasId ?: ""}"))
diff --git a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
index 7edf9fd..dd166e5 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
@@ -75,6 +75,7 @@ class GnssActivity : AppCompatActivity() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
+ binding.root.addView(visual.root, 0)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
while (true) { refresh(); delay(1_000) }
@@ -101,16 +102,105 @@ class GnssActivity : AppCompatActivity() {
override fun onSupportNavigateUp(): Boolean { finish(); return true }
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.SATELLITES); return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.SATELLITES) { invalidateOptionsMenu(); refresh() } || super.onOptionsItemSelected(item)
+
+ private val demo get() = com.rfsentinel.app.BuildConfig.DEBUG && intent.getBooleanExtra("demo", false)
+
+ /** The visual style: the check, counts, the sky plot and a bar per satellite. */
+ private val visual by lazy { Visual() }
+
+ private inner class Visual {
+ val dp = resources.displayMetrics.density
+ val accent = ChipStyle.accent(this@GnssActivity).first
+ val box = android.widget.LinearLayout(this@GnssActivity).apply { orientation = android.widget.LinearLayout.VERTICAL }
+ val root = android.widget.ScrollView(this@GnssActivity).apply { addView(box); visibility = View.GONE }
+ val verdict = TextView(this@GnssActivity).apply { textSize = 15f; setTypeface(typeface, Typeface.BOLD) }
+ val verdictSub = TextView(this@GnssActivity).apply { textSize = 12f; alpha = 0.8f }
+ val tiles = android.widget.FrameLayout(this@GnssActivity)
+ val sky = SkyPlotView(this@GnssActivity)
+ val legend = com.google.android.material.chip.ChipGroup(this@GnssActivity).apply { chipSpacingVertical = (4 * dp).toInt() }
+ val bars = SatBarsView(this@GnssActivity)
+ var legendKey = ""
+
+ fun title(t: String) = TextView(this@GnssActivity).apply {
+ text = t; textSize = 12f; setTypeface(typeface, Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
+ }
+
+ fun card(vararg views: View) = android.widget.LinearLayout(this@GnssActivity).apply {
+ orientation = android.widget.LinearLayout.VERTICAL
+ background = VisualMode.card(this@GnssActivity)
+ val p = (12 * dp).toInt(); setPadding(p, p, p, p)
+ views.forEach { addView(it) }
+ layoutParams = android.widget.LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ }
+
+ init {
+ box.addView(card(title("CHECK"), verdict, verdictSub))
+ box.addView(tiles, android.widget.LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() })
+ box.addView(card(title("SKY · NORTH UP"), sky, legend))
+ box.addView(card(title("SIGNAL PER SATELLITE · dB-Hz"), bars,
+ TextView(this@GnssActivity).apply { text = "Filled: used for your position. Outlined: heard only."; textSize = 11f; alpha = 0.7f }))
+ }
+
+ fun show(snap: GnssAnalyzer.Snapshot, verdictText: String, sub: String, good: Boolean) {
+ val heard = snap.sats.filter { it.cn0 > 0f }
+ verdict.text = verdictText
+ verdict.setTextColor(if (good) ThemeManager.ink(this@GnssActivity, 0xFF0B7A3E.toInt()) else 0xFFE0A33A.toInt())
+ verdictSub.text = sub
+ tiles.removeAllViews()
+ tiles.addView(VisualMode.tileRow(this@GnssActivity, listOf(
+ VisualMode.tile(this@GnssActivity, "${heard.size}", "heard", accent),
+ VisualMode.tile(this@GnssActivity, "${snap.sats.count { it.usedInFix }}", "used", accent),
+ VisualMode.tile(this@GnssActivity, heard.maxOfOrNull { it.cn0 }?.let { "%.0f".format(it) } ?: "-", "best dB-Hz", accent))))
+ sky.set(snap.sats)
+ bars.set(snap.sats)
+ val systems = snap.sats.map { it.system }.distinct().sortedBy { it.ordinal }
+ val key = systems.joinToString()
+ if (key != legendKey) {
+ legendKey = key
+ legend.removeAllViews()
+ systems.forEach { legend.addView(VisualMode.chip(this@GnssActivity, it.label, GnssColors.of(it))) }
+ }
+ }
+ }
+
+ /** Debug builds' demo: a made-up sky for checking the screen indoors or on an emulator. */
+ private fun demoSnapshot(): GnssAnalyzer.Snapshot {
+ val t = System.currentTimeMillis() / 1000 % 360
+ val sats = listOf(GnssAnalyzer.System.GPS to 9, GnssAnalyzer.System.GALILEO to 6, GnssAnalyzer.System.GLONASS to 5,
+ GnssAnalyzer.System.BEIDOU to 6).flatMap { (sys, n) ->
+ (1..n).map { i ->
+ val el = (10 + (i * 37 + sys.ordinal * 11) % 75).toFloat()
+ GnssAnalyzer.Sat(sys, i * 3 + sys.ordinal, 18f + el / 2.2f + (i % 3) * 2, el, i % 4 != 0, 1575.42f,
+ ((i * 71 + sys.ordinal * 47 + t / 30f) % 360).toFloat())
+ }
+ }
+ return GnssAnalyzer.Snapshot(System.currentTimeMillis(), sats, 22.5)
+ }
+
@SuppressLint("NotifyDataSetChanged")
private fun refresh() {
if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
show(emptyList(), "The satellite view needs the location permission.\nStart a scan once to grant it."); return
}
- val snap = GnssWatch.latest?.takeIf { System.currentTimeMillis() - GnssWatch.latestAt < 10_000L }
+ val snap = if (demo) demoSnapshot() else GnssWatch.latest?.takeIf { System.currentTimeMillis() - GnssWatch.latestAt < 10_000L }
if (snap == null) {
show(emptyList(), "Listening for satellites…\nIt can take up to a minute; outdoors or near a window works best."); return
}
val tracked = snap.sats.filter { it.cn0 > 0f }
+ if (VisualMode.on(this, VisualMode.Screen.SATELLITES)) {
+ visual.show(snap, GnssWatch.analyzer.verdict,
+ if (GnssWatch.hasAgc) "Receiver noise (AGC) ${snap.agcDb?.let { "%.1f dB".format(it) } ?: "-"} · jamming check on"
+ else "This phone doesn't report receiver noise: jamming is only suspected on a total loss",
+ GnssWatch.analyzer.verdict.startsWith("No "))
+ show(emptyList(), null, visualShown = true)
+ return
+ }
val out = ArrayList<Row>()
out += Row.Header("Check")
out += Row.Line(GnssWatch.analyzer.verdict,
@@ -146,7 +236,9 @@ class GnssActivity : AppCompatActivity() {
private fun bars(cn0: Float): String { val n = ((cn0 - 15) / 7).toInt().coerceIn(0, 5); return "▮".repeat(n) + "▯".repeat(5 - n) }
@SuppressLint("NotifyDataSetChanged")
- private fun show(list: List<Row>, emptyText: String?) {
+ private fun show(list: List<Row>, emptyText: String?, visualShown: Boolean = false) {
+ visual.root.visibility = if (visualShown) View.VISIBLE else View.GONE
+ binding.recyclerView.visibility = if (visualShown) View.GONE else View.VISIBLE
rows = list
adapter.notifyDataSetChanged()
binding.emptyText.text = emptyText.orEmpty()
diff --git a/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt b/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt
new file mode 100644
index 0000000..beb98a1
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt
@@ -0,0 +1,159 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.Typeface
+import android.graphics.drawable.GradientDrawable
+import android.view.Gravity
+import android.view.View
+import android.widget.LinearLayout
+import android.widget.TextView
+
+/**
+ * The main screen's status in the visual style: counters for what's heard (Bluetooth, WiFi, cells,
+ * flagged), a warning chip when there is one, and a card per piece of USB / ESP32 hardware with a
+ * coloured dot for its state and, for the WiFi adapter and the RTL-SDR, a line of its packets per second.
+ */
+class StatusPanel(private val context: Context) {
+
+ /** One line of hardware status ("USB WiFi (MT7612U) · live · …") with an optional per-second counter. */
+ class Hardware(val status: String, val counter: (() -> Long)? = null, val unit: String = "/s")
+
+ private val dp = context.resources.displayMetrics.density
+ private val accent = ChipStyle.accent(context).first
+ val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL; visibility = View.GONE }
+ private val counters = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
+ private val note = TextView(context).apply { textSize = 12f; visibility = View.GONE }
+ private val cards = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
+ private val counterViews = List(4) { pill() }
+
+ /** Per hardware name: the counter's last reading and its rate over the last minute. */
+ private class Rate(var last: Long = -1, var at: Long = 0, val history: ArrayDeque<Float> = ArrayDeque())
+ private val rates = HashMap<String, Rate>()
+ private var cardKey = ""
+
+ init {
+ counterViews.forEachIndexed { i, v ->
+ // A fixed height so the text can shrink to fit narrow screens ("Flagged 12" on a small phone).
+ counters.addView(v, LinearLayout.LayoutParams(0, (26 * dp).toInt(), 1f).apply { if (i > 0) marginStart = (5 * dp).toInt() })
+ }
+ root.addView(counters)
+ root.addView(note, LinearLayout.LayoutParams(-1, -2).apply { topMargin = (5 * dp).toInt() })
+ root.addView(cards)
+ root.setPadding(0, 0, 0, (6 * dp).toInt())
+ }
+
+ private fun pill() = TextView(context).apply {
+ textSize = 12f
+ setTypeface(typeface, Typeface.BOLD)
+ gravity = Gravity.CENTER
+ maxLines = 1
+ androidx.core.widget.TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this, 8, 12, 1, android.util.TypedValue.COMPLEX_UNIT_SP)
+ }
+
+ private fun setPill(v: TextView, text: String, color: Int) {
+ if (v.text != text) v.text = text
+ VisualMode.chip(v, color)
+ v.setPadding((4 * dp).toInt(), (2 * dp).toInt(), (4 * dp).toInt(), (2 * dp).toInt())
+ }
+
+ /**
+ * [running]: scanning; [ble], [wifi], [cells], [flagged]: what's heard now; [warning]: a fake-cell or
+ * restarted-scan note; [hardware]: the non-blank hardware status lines.
+ */
+ fun update(running: Boolean, ble: Int, wifi: Int, cells: Int, flagged: Int, warning: String?, hardware: List<Hardware>) {
+ val grey = (ChipStyle.onSurface(context) and 0x00FFFFFF) or 0x99000000.toInt()
+ setPill(counterViews[0], "BLE $ble", if (running) accent else grey)
+ setPill(counterViews[1], "WiFi $wifi", if (running) accent else grey)
+ setPill(counterViews[2], "Cells $cells", if (running) accent else grey)
+ setPill(counterViews[3], "Flagged $flagged", if (flagged > 0) 0xFFD0503C.toInt() else if (running) accent else grey)
+ val shown = if (!running) "Idle - tap Start to listen for nearby devices" else warning?.let { "⚠ $it" }
+ note.visibility = if (shown != null) View.VISIBLE else View.GONE
+ if (shown != null) {
+ VisualMode.text(note, shown)
+ VisualMode.chip(note, if (running) 0xFFE0A33A.toInt() else grey)
+ }
+ showHardware(hardware)
+ }
+
+ private fun showHardware(list: List<Hardware>) {
+ val now = System.currentTimeMillis()
+ val key = list.joinToString("|") { name(it.status) }
+ if (key != cardKey) {
+ cardKey = key
+ cards.removeAllViews()
+ list.forEach { cards.addView(card(), LinearLayout.LayoutParams(-1, -2).apply { topMargin = (5 * dp).toInt() }) }
+ rates.keys.retainAll(list.map { name(it.status) }.toSet())
+ }
+ list.forEachIndexed { i, h -> bind(cards.getChildAt(i) as LinearLayout, h, now) }
+ }
+
+ private fun card() = LinearLayout(context).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ val p = (8 * dp).toInt(); setPadding((10 * dp).toInt(), p, (10 * dp).toInt(), p)
+ addView(View(context), LinearLayout.LayoutParams((10 * dp).toInt(), (10 * dp).toInt()).apply { marginEnd = (8 * dp).toInt() })
+ addView(LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(TextView(context).apply { textSize = 13f; setTypeface(typeface, Typeface.BOLD); maxLines = 1
+ ellipsize = android.text.TextUtils.TruncateAt.END })
+ addView(TextView(context).apply { textSize = 12f; alpha = 0.8f; maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END })
+ }, LinearLayout.LayoutParams(0, -2, 1f))
+ addView(LinearLayout(context).apply {
+ orientation = LinearLayout.VERTICAL
+ gravity = Gravity.END
+ addView(SparklineView(context), LinearLayout.LayoutParams((64 * dp).toInt(), (22 * dp).toInt()))
+ addView(TextView(context).apply { textSize = 10f; alpha = 0.75f; gravity = Gravity.END })
+ }, LinearLayout.LayoutParams(-2, -2).apply { marginStart = (8 * dp).toInt() })
+ }
+
+ private fun bind(card: LinearLayout, h: Hardware, now: Long) {
+ val color = when (stateOf(h.status)) {
+ State.ERROR -> 0xFFD0503C.toInt()
+ State.WAIT -> 0xFFE0A33A.toInt()
+ State.LIVE -> 0xFF2E9E5B.toInt()
+ }
+ card.background = VisualMode.card(context, color, 0x16, 0x66, 12f)
+ card.getChildAt(0).background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(color) }
+ val texts = card.getChildAt(1) as LinearLayout
+ val name = name(h.status)
+ VisualMode.text(texts.getChildAt(0) as TextView, name)
+ VisualMode.text(texts.getChildAt(1) as TextView, detail(h.status))
+ val side = card.getChildAt(2) as LinearLayout
+ val counter = h.counter
+ side.visibility = if (counter != null) View.VISIBLE else View.GONE
+ if (counter == null) return
+ // Rate over each refresh, the last minute of it as a line.
+ val r = rates.getOrPut(name) { Rate() }
+ val n = counter()
+ if (r.last >= 0 && now - r.at >= 900) {
+ r.history.addLast((n - r.last).coerceAtLeast(0) * 1000f / (now - r.at))
+ while (r.history.size > 60) r.history.removeFirst()
+ }
+ if (r.last < 0 || now - r.at >= 900) { r.last = n; r.at = now }
+ (side.getChildAt(0) as SparklineView).set(r.history.toFloatArray(), color, 5f)
+ VisualMode.text(side.getChildAt(1) as TextView, r.history.lastOrNull()?.let { "%.0f%s".format(it, h.unit) } ?: "–")
+ }
+
+ private enum class State { LIVE, WAIT, ERROR }
+
+ private fun stateOf(s: String): State {
+ val l = s.lowercase()
+ return when {
+ listOf("error", "couldn't", "isn't supported", "didn't lock", "failed", "isn't the", "is off", "disconnected").any { it in l } -> State.ERROR
+ listOf("starting", "allow", "found", "needs", "learning", "connecting", "reconnecting", "setting up", "looking up", "tap ",
+ "waiting", "listening on").any { it in l } -> State.WAIT
+ else -> State.LIVE
+ }
+ }
+
+ /** "USB WiFi (MT7612U)" from "USB WiFi (MT7612U) · live · …", "OUI-SPY" from "OUI-SPY: connecting…". */
+ private fun name(s: String): String {
+ val cut = listOf(" · ", ": ", " - ").mapNotNull { sep -> s.indexOf(sep).takeIf { it > 0 } }.minOrNull() ?: return s
+ return s.substring(0, cut)
+ }
+
+ private fun detail(s: String): String {
+ val n = name(s)
+ return s.removePrefix(n).trimStart(' ', '·', ':', '-').replaceFirstChar { it.uppercase() }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
index e349cc1..a60bef5 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
@@ -37,13 +37,23 @@ class TripsActivity : AppCompatActivity() {
override fun areContentsTheSame(a: TripEntity, b: TripEntity) = a == b
}
) {
+ override fun getItemViewType(position: Int) = if (VisualMode.on(this@TripsActivity, VisualMode.Screen.TRIPS)) 1 else 0
+
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
object : RecyclerView.ViewHolder(
- ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
+ if (viewType == 1) TripCard() else ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
) {}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val t = getItem(position)
+ (holder.itemView as? TripCard)?.let { card ->
+ card.bind(t)
+ holder.itemView.setOnClickListener {
+ startActivity(Intent(this@TripsActivity, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id))
+ }
+ holder.itemView.setOnLongClickListener { actions(t); true }
+ return
+ }
val b = ItemDetectionBinding.bind(holder.itemView)
val live = t.id == TripRecorder.activeTripId
b.labelText.text = (if (live) "● " else "") + t.name
@@ -79,6 +89,68 @@ class TripsActivity : AppCompatActivity() {
}
}
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.TRIPS); return true
+ }
+
+ @android.annotation.SuppressLint("NotifyDataSetChanged")
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.TRIPS) { invalidateOptionsMenu(); adapter.notifyDataSetChanged() } ||
+ super.onOptionsItemSelected(item)
+
+ /** A trace's route and flagged devices, loaded once per trace (again while it's still recording). */
+ private class Outline(val points: Int, val route: List<Pair<Double, Double>>, val flagged: List<Pair<Double, Double>>)
+ private val outlines = HashMap<Long, Outline>()
+
+ /** Visual style: a card per trace with the route's outline and its numbers. */
+ private inner class TripCard : android.widget.LinearLayout(this@TripsActivity) {
+ private val dp = resources.displayMetrics.density
+ private val accent = ChipStyle.accent(context).first
+ private val name = android.widget.TextView(context).apply { textSize = 16f; setTypeface(typeface, android.graphics.Typeface.BOLD) }
+ private val date = android.widget.TextView(context).apply { textSize = 12f; alpha = 0.75f }
+ private val route = RouteOutlineView(context)
+ private val stats = com.google.android.material.chip.ChipGroup(context).apply { chipSpacingVertical = (4 * dp).toInt() }
+ private var boundId = -1L
+
+ init {
+ orientation = VERTICAL
+ val p = (12 * dp).toInt(); setPadding(p, p, p, p)
+ layoutParams = RecyclerView.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ addView(name); addView(date)
+ addView(route, LayoutParams(-1, (110 * dp).toInt()).apply { topMargin = (8 * dp).toInt(); bottomMargin = (8 * dp).toInt() })
+ addView(stats)
+ }
+
+ fun bind(t: TripEntity) {
+ val live = t.id == TripRecorder.activeTripId
+ val color = if (live) 0xFFB3261E.toInt() else if (t.flaggedCount > 0) 0xFFC8431A.toInt() else accent
+ background = VisualMode.card(context, color)
+ name.text = (if (live) "● " else "") + t.name
+ name.setTextColor(if (live || t.flaggedCount > 0) color else ChipStyle.onSurface(context))
+ date.text = fmt.format(Date(t.startTime)) + if (live) " · recording now" else ""
+ val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000
+ stats.removeAllViews()
+ listOf(String.format(Locale.US, "%.2f km", t.distanceM / 1000), String.format(Locale.US, "%d:%02d", mins / 60, mins % 60),
+ devicesLabel(t.deviceCount)).forEach { stats.addView(VisualMode.chip(context, it, accent)) }
+ stats.addView(VisualMode.chip(context, "${t.flaggedCount} flagged", if (t.flaggedCount > 0) 0xFFD0503C.toInt() else accent))
+ boundId = t.id
+ val o = outlines[t.id]
+ route.set(o?.route.orEmpty(), o?.flagged.orEmpty(), color)
+ if (o == null || (live && o.points != t.pointCount)) {
+ lifecycleScope.launch {
+ val dao = AppDatabase.getInstance(this@TripsActivity).tripDao()
+ val pts = dao.points(t.id)
+ // At most ~400 points: plenty for a small outline.
+ val step = (pts.size / 400).coerceAtLeast(1)
+ val line = pts.filterIndexed { i, _ -> i % step == 0 || i == pts.lastIndex }.map { it.lat to it.lon }
+ val flagged = dao.devices(t.id).filter { it.flagged && it.lat != null && it.lon != null }.map { it.lat!! to it.lon!! }
+ outlines[t.id] = Outline(t.pointCount, line, flagged)
+ if (boundId == t.id) route.set(line, flagged, color)
+ }
+ }
+ }
+ }
+
private fun actions(t: TripEntity) {
AlertDialog.Builder(this)
.setTitle(t.name)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt b/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt
new file mode 100644
index 0000000..007aaef
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/VisualMode.kt
@@ -0,0 +1,132 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.drawable.GradientDrawable
+import android.view.Menu
+import android.view.MenuItem
+import android.view.View
+import android.widget.TextView
+import com.rfsentinel.app.R
+
+/**
+ * Visual or list, per screen: the visual style draws gauges, bars and charts (after Wardrive Go's);
+ * the list style is the plain text the screens always had. Each screen remembers its own choice,
+ * switched from its top bar or from Settings > Appearance.
+ */
+object VisualMode {
+
+ enum class Screen(val key: String, val label: String) {
+ DEVICE_LIST("list", "Device list"),
+ STATUS("status", "Status bar"),
+ DEVICE_DETAIL("detail", "Device details"),
+ SATELLITES("gnss", "Satellites"),
+ CELLS("cells", "Cell towers"),
+ WAZE("waze", "Waze status"),
+ AIRCRAFT("aircraft", "Aircraft"),
+ TRIPS("trips", "Recorded traces")
+ }
+
+ private const val PREFS = "rf_sentinel_prefs"
+ private const val MENU_ID = 0x7653
+
+ fun on(context: Context, screen: Screen): Boolean =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("visual_" + screen.key, true)
+
+ fun set(context: Context, screen: Screen, on: Boolean) =
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("visual_" + screen.key, on).apply()
+
+ /** The top bar's list / visual button: shows the style you'd switch to. */
+ fun addMenu(menu: Menu, context: Context, screen: Screen) {
+ val visual = on(context, screen)
+ menu.add(0, MENU_ID, 0, if (visual) "List view" else "Visual view").apply {
+ setIcon(if (visual) com.rfsentinel.app.R.drawable.ic_view_list else com.rfsentinel.app.R.drawable.ic_view_visual)
+ setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
+ icon?.mutate()?.setTint(ChipStyle.onSurface(context))
+ }
+ }
+
+ /** True when [item] was the list / visual button (the choice is flipped and [apply] runs). */
+ fun handle(item: MenuItem, context: Context, screen: Screen, apply: () -> Unit): Boolean {
+ if (item.itemId != MENU_ID) return false
+ set(context, screen, !on(context, screen))
+ apply()
+ return true
+ }
+
+ // ---- shared look -------------------------------------------------------
+
+ fun tint(color: Int, alpha: Int) = (color and 0x00FFFFFF) or (alpha shl 24)
+
+ /** The antenna check's cards: a light fill of [color] with a thin edge. */
+ fun card(context: Context, color: Int = ChipStyle.accent(context).first, fillAlpha: Int = 0x14, strokeAlpha: Int = 0x66,
+ radiusDp: Float = 16f) = GradientDrawable().apply {
+ val dp = context.resources.displayMetrics.density
+ cornerRadius = radiusDp * dp
+ setColor(tint(color, fillAlpha))
+ if (strokeAlpha > 0) setStroke((1.2f * dp).toInt().coerceAtLeast(1), tint(color, strokeAlpha))
+ }
+
+ /** A small rounded label ("5 GHz ch 36", "LTE"), like the antenna check's channel chip. */
+ fun chip(view: TextView, color: Int) {
+ // Restyled every refresh: skip when nothing changed, so the screen can go idle (TalkBack, tests).
+ if (view.getTag(R.id.visual_chip_color) == color) return
+ view.setTag(R.id.visual_chip_color, color)
+ val dp = view.resources.displayMetrics.density
+ view.background = card(view.context, color, 0x26, 0x99, 12f)
+ view.setTextColor(color)
+ view.setPadding((10 * dp).toInt(), (3 * dp).toInt(), (10 * dp).toInt(), (3 * dp).toInt())
+ }
+
+ /** Sets [text] only when it differs, so a refresh that changes nothing sends no update to TalkBack. */
+ fun text(view: TextView, text: CharSequence) {
+ if (view.text.toString() != text.toString()) view.text = text
+ }
+
+ fun chip(context: Context, text: String, color: Int): TextView = TextView(context).apply {
+ this.text = text
+ textSize = 12f
+ setTypeface(typeface, android.graphics.Typeface.BOLD)
+ chip(this, color)
+ }
+
+ /** A stat tile: a big number over a small caption. */
+ fun tile(context: Context, value: String, caption: String, color: Int): View {
+ val dp = context.resources.displayMetrics.density
+ return android.widget.LinearLayout(context).apply {
+ orientation = android.widget.LinearLayout.VERTICAL
+ gravity = android.view.Gravity.CENTER
+ background = card(context, color, 0x1E, 0x55, 14f)
+ setPadding((6 * dp).toInt(), (8 * dp).toInt(), (6 * dp).toInt(), (8 * dp).toInt())
+ addView(TextView(context).apply {
+ text = value; textSize = 22f; setTextColor(color); gravity = android.view.Gravity.CENTER
+ setTypeface(typeface, android.graphics.Typeface.BOLD); maxLines = 1
+ })
+ addView(TextView(context).apply {
+ text = caption; textSize = 11f; gravity = android.view.Gravity.CENTER; alpha = 0.75f
+ })
+ }
+ }
+
+ /** A row of [tiles] sharing the width equally, with a small gap between them. */
+ fun tileRow(context: Context, tiles: List<View>): android.widget.LinearLayout {
+ val dp = context.resources.displayMetrics.density
+ return android.widget.LinearLayout(context).apply {
+ orientation = android.widget.LinearLayout.HORIZONTAL
+ tiles.forEachIndexed { i, t ->
+ addView(t, android.widget.LinearLayout.LayoutParams(0, -2, 1f).apply {
+ if (i > 0) marginStart = (6 * dp).toInt()
+ })
+ }
+ }
+ }
+
+ /** A colour from red (weak) through amber to green (strong) for a 0..1 [level]. */
+ fun levelColor(level: Float): Int = when {
+ level >= 0.6f -> 0xFF2E9E5B.toInt()
+ level >= 0.35f -> 0xFFE0A33A.toInt()
+ else -> 0xFFD0503C.toInt()
+ }
+
+ /** 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
new file mode 100644
index 0000000..b00c915
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/VisualViews.kt
@@ -0,0 +1,552 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Typeface
+import android.util.AttributeSet
+import android.view.View
+import com.rfsentinel.app.detect.GnssAnalyzer
+import kotlin.math.abs
+import kotlin.math.cos
+import kotlin.math.min
+import kotlin.math.sin
+
+/** Shared bits of the visual-style views. */
+private val View.dp get() = resources.displayMetrics.density
+private fun alpha(c: Int, a: Int) = (c and 0x00FFFFFF) or (a shl 24)
+
+/** Four signal bars, filled up to the level of [dbm], for list rows. */
+class SignalBarsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var level = 0f
+ private var color = ChipStyle.accent(context).first
+ private val ink = ChipStyle.onSurface(context)
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val rect = RectF()
+
+ fun set(dbm: Int?, color: Int? = null) {
+ level = VisualMode.dbmLevel(dbm)
+ this.color = color ?: VisualMode.levelColor(level)
+ contentDescription = dbm?.let { "$it dBm" } ?: "no signal"
+ invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) =
+ setMeasuredDimension(resolveSize((26 * dp).toInt(), w), resolveSize((20 * dp).toInt(), h))
+
+ override fun onDraw(canvas: Canvas) {
+ val n = 4
+ val gap = 2.5f * dp
+ val bw = (width - gap * (n - 1)) / n
+ val lit = if (level <= 0f) 0 else (level * n + 0.5f).toInt().coerceIn(1, n)
+ for (i in 0 until n) {
+ val h = height * (i + 1f) / n
+ rect.set(i * (bw + gap), height - h, i * (bw + gap) + bw, height.toFloat())
+ paint.color = if (i < lit) color else alpha(ink, 0x30)
+ canvas.drawRoundRect(rect, 1.5f * dp, 1.5f * dp, paint)
+ }
+ }
+}
+
+/** A thin horizontal bar filled to [fraction], for confidence on list rows. */
+class LevelBarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var fraction = 0f
+ private var color = ChipStyle.accent(context).first
+ private val ink = ChipStyle.onSurface(context)
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val rect = RectF()
+
+ fun set(fraction: Float, color: Int) { this.fraction = fraction.coerceIn(0f, 1f); this.color = color; invalidate() }
+
+ override fun onMeasure(w: Int, h: Int) =
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize((4 * dp).toInt(), h))
+
+ 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)
+ if (fraction > 0f) {
+ rect.right = width * fraction
+ paint.color = color; canvas.drawRoundRect(rect, r, r, paint)
+ }
+ }
+}
+
+/** A ring filled to [percent] with the number in the middle and a caption under it. */
+class ConfidenceRingView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var percent = 0
+ private var caption = ""
+ private var color = ChipStyle.accent(context).first
+ private var center = ""
+ private val ink = ChipStyle.onSurface(context)
+ private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER }
+ private val oval = RectF()
+ private var shown = 0f
+
+ /** [centerText] replaces "NN%" in the middle (a countdown "42 s"). */
+ fun set(percent: Int, color: Int, caption: String, centerText: String? = null) {
+ this.percent = percent.coerceIn(0, 100); this.color = color; this.caption = caption
+ center = centerText ?: "${this.percent}%"
+ contentDescription = "$center $caption"
+ invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) {
+ val s = resolveSize((112 * dp).toInt(), w)
+ setMeasuredDimension(s, resolveSize(s, h))
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val stroke = min(width, height) * 0.09f
+ ring.strokeWidth = stroke
+ val r = min(width, height) / 2f - stroke
+ val cx = width / 2f; val cy = height / 2f
+ oval.set(cx - r, cy - r, cx + r, cy + r)
+ ring.color = alpha(ink, 0x22)
+ canvas.drawArc(oval, 0f, 360f, false, ring)
+ shown += (percent - shown) * 0.2f
+ if (abs(percent - shown) > 0.3f) postInvalidateOnAnimation() else shown = percent.toFloat()
+ ring.color = color
+ if (shown > 0f) canvas.drawArc(oval, -90f, 360f * shown / 100f, false, ring)
+ text.color = color
+ text.typeface = Typeface.DEFAULT_BOLD
+ text.textSize = r * 0.55f
+ if (text.measureText(center) > r * 1.6f) text.textSize *= r * 1.6f / text.measureText(center)
+ canvas.drawText(center, cx, cy + text.textSize * 0.2f, text)
+ text.typeface = Typeface.DEFAULT
+ text.color = alpha(ink, 0xAA)
+ text.textSize = r * 0.24f
+ if (text.measureText(caption) > r * 1.5f) text.textSize *= r * 1.5f / text.measureText(caption)
+ canvas.drawText(caption, cx, cy + r * 0.48f, text)
+ }
+}
+
+/**
+ * The device's signal as a half-dial (−100 to −30 dBm) that warms from blue to red as it gets
+ * stronger, with the reading in the middle and whether you're getting closer: a hot / cold finder.
+ */
+class SignalGaugeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var dbm: Int? = null
+ private var best: Int? = null
+ private var trend = 0
+ private val ink = ChipStyle.onSurface(context)
+ private val arc = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER }
+ private val oval = RectF()
+ private var shown = 0f
+
+ /** [trend]: 1 getting closer, -1 moving away, 0 steady. */
+ fun set(dbm: Int?, best: Int?, trend: Int) {
+ this.dbm = dbm; this.best = best; this.trend = trend
+ contentDescription = dbm?.let { "$it dBm, " + trendText() } ?: "not heard"
+ invalidate()
+ }
+
+ 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
+ }
+
+ override fun onMeasure(w: Int, h: Int) {
+ val width = MeasureSpec.getSize(w)
+ setMeasuredDimension(width, resolveSize((width * 0.62f).toInt().coerceIn((150 * dp).toInt(), (230 * dp).toInt()), h))
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val stroke = 16 * dp
+ val r = min(width / 2f - stroke, height - stroke - 30 * dp)
+ val cx = width / 2f; val cy = stroke / 2 + r + 4 * dp
+ oval.set(cx - r, cy - r, cx + r, cy + r)
+ arc.strokeWidth = stroke
+ // The track, in ticks of colour so the scale reads at a glance.
+ val steps = 28
+ for (i in 0 until steps) {
+ arc.color = alpha(heat(i / (steps - 1f)), 0x40)
+ canvas.drawArc(oval, 180f + i * 180f / steps + 1f, 180f / steps - 2f, false, arc)
+ }
+ val target = VisualMode.dbmLevel(dbm)
+ shown += (target - shown) * 0.2f
+ if (abs(target - shown) > 0.003f) postInvalidateOnAnimation() else shown = target
+ val lit = (shown * steps).toInt()
+ for (i in 0 until lit) {
+ arc.color = heat(i / (steps - 1f))
+ canvas.drawArc(oval, 180f + i * 180f / steps + 1f, 180f / steps - 2f, false, arc)
+ }
+ // Best reading so far: a small notch.
+ best?.let {
+ val a = Math.toRadians(180.0 + 180.0 * VisualMode.dbmLevel(it))
+ val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ink; strokeWidth = 2.5f * dp }
+ canvas.drawLine(cx + ((r - stroke) * cos(a)).toFloat(), cy + ((r - stroke) * sin(a)).toFloat(),
+ cx + ((r + stroke) * cos(a)).toFloat(), cy + ((r + stroke) * sin(a)).toFloat(), p)
+ }
+ val color = if (dbm == null) alpha(ink, 0x88) else heat(target)
+ text.color = color
+ text.typeface = Typeface.DEFAULT_BOLD
+ text.textSize = r * 0.42f
+ canvas.drawText(dbm?.toString() ?: "--", cx, cy - r * 0.12f, text)
+ text.typeface = Typeface.DEFAULT
+ text.textSize = 12 * dp
+ text.color = alpha(ink, 0xAA)
+ canvas.drawText("dBm", cx, cy + 8 * dp, text)
+ if (dbm != null) {
+ text.typeface = Typeface.DEFAULT_BOLD
+ text.textSize = 15 * dp
+ text.color = when (trend) { 1 -> 0xFFD0503C.toInt(); -1 -> 0xFF3D7BD9.toInt(); else -> alpha(ink, 0xCC) }
+ val label = when (trend) { 1 -> "▲ Getting closer"; -1 -> "▼ Moving away"; else -> "● Steady" }
+ canvas.drawText(label, cx, cy + 28 * dp, text)
+ }
+ text.typeface = Typeface.DEFAULT
+ text.textSize = 10 * dp
+ text.color = alpha(ink, 0x88)
+ canvas.drawText("−100", cx - r, cy + 18 * dp, text)
+ canvas.drawText("−30", cx + r, cy + 18 * dp, text)
+ }
+}
+
+/** A line of recent values (NaN = gap), scaled to its own range, filled underneath. */
+class SparklineView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var values = FloatArray(0)
+ private var color = ChipStyle.accent(context).first
+ private var minRange = 1f
+ private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeJoin = Paint.Join.ROUND }
+ private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val path = Path()
+ private val area = Path()
+
+ /** [minRange]: the smallest span the height covers, so a steady value stays a flat line. */
+ fun set(values: FloatArray, color: Int, minRange: Float = 1f) {
+ this.values = values; this.color = color; this.minRange = minRange; invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) =
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize((36 * dp).toInt(), h))
+
+ override fun onDraw(canvas: Canvas) {
+ line.strokeWidth = 1.8f * dp
+ line.color = color
+ val vals = values.filter { !it.isNaN() }
+ val bottom = height - line.strokeWidth
+ if (vals.size < 2) {
+ line.alpha = 0x50
+ canvas.drawLine(0f, bottom, width.toFloat(), bottom, line)
+ return
+ }
+ var lo = vals.min(); var hi = vals.max()
+ if (hi - lo < minRange) { val mid = (hi + lo) / 2; lo = mid - minRange / 2; hi = mid + minRange / 2 }
+ val top = line.strokeWidth
+ path.reset(); area.reset()
+ var started = false; var lastX = 0f
+ values.forEachIndexed { i, v ->
+ if (v.isNaN()) return@forEachIndexed
+ val x = width * i / (values.size - 1).coerceAtLeast(1).toFloat()
+ val y = bottom - (bottom - top) * (v - lo) / (hi - lo)
+ if (!started) { path.moveTo(x, y); area.moveTo(x, height.toFloat()); area.lineTo(x, y); started = true }
+ else { path.lineTo(x, y); area.lineTo(x, y) }
+ lastX = x
+ }
+ area.lineTo(lastX, height.toFloat()); area.close()
+ fill.color = alpha(color, 0x30)
+ canvas.drawPath(area, fill)
+ line.alpha = 0xFF
+ canvas.drawPath(path, line)
+ }
+}
+
+/** Satellite colours by system, shared by the sky plot and the signal bars. */
+object GnssColors {
+ fun of(s: GnssAnalyzer.System): Int = when (s) {
+ GnssAnalyzer.System.GPS -> 0xFF3D7BD9.toInt()
+ GnssAnalyzer.System.GLONASS -> 0xFFD0503C.toInt()
+ GnssAnalyzer.System.GALILEO -> 0xFFE0A33A.toInt()
+ GnssAnalyzer.System.BEIDOU -> 0xFF9C5BD0.toInt()
+ GnssAnalyzer.System.QZSS -> 0xFF2EA6A0.toInt()
+ GnssAnalyzer.System.NAVIC -> 0xFF2E9E5B.toInt()
+ else -> 0xFF8A8A8A.toInt()
+ }
+}
+
+/**
+ * Where each satellite sits in the sky: the outer ring is the horizon, the centre straight up,
+ * north at the top. Filled dots are used for the position; size follows the signal.
+ */
+class SkyPlotView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var sats: List<GnssAnalyzer.Sat> = emptyList()
+ private val ink = ChipStyle.onSurface(context)
+ private val grid = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
+ private val dot = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER }
+
+ fun set(list: List<GnssAnalyzer.Sat>) {
+ sats = list
+ contentDescription = "${list.count { it.cn0 > 0f }} satellites in the sky plot"
+ invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) {
+ val s = MeasureSpec.getSize(w).coerceAtMost((360 * dp).toInt())
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize(s, h))
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val cx = width / 2f; val cy = height / 2f
+ val r = min(width, height) / 2f - 16 * dp
+ grid.strokeWidth = 1.2f * dp
+ grid.color = alpha(ink, 0x40)
+ for (el in intArrayOf(0, 30, 60)) canvas.drawCircle(cx, cy, r * (90 - el) / 90f, grid)
+ grid.color = alpha(ink, 0x25)
+ canvas.drawLine(cx - r, cy, cx + r, cy, grid)
+ canvas.drawLine(cx, cy - r, cx, cy + r, grid)
+ text.textSize = 11 * dp
+ text.typeface = Typeface.DEFAULT_BOLD
+ text.color = alpha(ink, 0xAA)
+ canvas.drawText("N", cx, cy - r - 4 * dp, text)
+ canvas.drawText("S", cx, cy + r + 13 * dp, text)
+ canvas.drawText("E", cx + r + 9 * dp, cy + 4 * dp, text)
+ canvas.drawText("W", cx - r - 9 * dp, cy + 4 * dp, text)
+ text.typeface = Typeface.DEFAULT
+ text.textSize = 9 * dp
+ text.color = alpha(ink, 0x77)
+ canvas.drawText("30°", cx + 3 * dp, cy - r * 60 / 90f - 2 * dp, text)
+ canvas.drawText("60°", cx + 3 * dp, cy - r * 30 / 90f - 2 * dp, text)
+ // Weakest first so strong ones sit on top.
+ for (s in sats.filter { it.cn0 > 0f && it.elevation >= 0f }.sortedBy { it.cn0 }) {
+ val rr = r * (90f - s.elevation.coerceIn(0f, 90f)) / 90f
+ val a = Math.toRadians(s.azimuth.toDouble() - 90.0)
+ val x = cx + (rr * cos(a)).toFloat(); val y = cy + (rr * sin(a)).toFloat()
+ val size = (3.5f + (s.cn0 - 15f).coerceIn(0f, 35f) / 35f * 5f) * dp
+ val c = GnssColors.of(s.system)
+ if (s.usedInFix) {
+ dot.style = Paint.Style.FILL; dot.color = c
+ } else {
+ dot.style = Paint.Style.STROKE; dot.strokeWidth = 1.8f * dp; dot.color = alpha(c, 0xCC)
+ }
+ canvas.drawCircle(x, y, size, dot)
+ text.color = alpha(ink, 0xCC)
+ text.textSize = 8.5f * dp
+ canvas.drawText("${s.svid}", x, y - size - 2 * dp, text)
+ }
+ }
+}
+
+/** One bar per satellite heard, its signal (dB-Hz) as the height, coloured by system; outlined when not used. */
+class SatBarsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var sats: List<GnssAnalyzer.Sat> = emptyList()
+ private val ink = ChipStyle.onSurface(context)
+ private val bar = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER }
+ private val rect = RectF()
+
+ fun set(list: List<GnssAnalyzer.Sat>) {
+ sats = list.filter { it.cn0 > 0f }.sortedWith(compareBy<GnssAnalyzer.Sat> { it.system.ordinal }.thenByDescending { it.cn0 })
+ invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) =
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize((150 * dp).toInt(), h))
+
+ override fun onDraw(canvas: Canvas) {
+ val labelH = 12 * dp
+ val top = 14 * dp; val bottom = height - labelH
+ text.textSize = 8.5f * dp
+ text.color = alpha(ink, 0x77)
+ val grid = Paint().apply { color = alpha(ink, 0x20); strokeWidth = dp }
+ for (v in intArrayOf(20, 30, 40, 50)) {
+ val y = bottom - (bottom - top) * (v - 10) / 45f
+ canvas.drawLine(0f, y, width.toFloat(), y, grid)
+ }
+ if (sats.isEmpty()) return
+ // Only as many as fit at a readable width; the strongest of each system stay.
+ val maxBars = (width / (9 * dp)).toInt().coerceAtLeast(1)
+ val shown = if (sats.size <= maxBars) sats else sats.sortedByDescending { it.cn0 }.take(maxBars)
+ .sortedWith(compareBy<GnssAnalyzer.Sat> { it.system.ordinal }.thenByDescending { it.cn0 })
+ val slot = width.toFloat() / shown.size
+ val bw = (slot * 0.7f).coerceAtMost(22 * dp)
+ shown.forEachIndexed { i, s ->
+ val c = GnssColors.of(s.system)
+ val x = slot * i + (slot - bw) / 2
+ val y = bottom - (bottom - top) * ((s.cn0 - 10f) / 45f).coerceIn(0.03f, 1f)
+ rect.set(x, y, x + bw, bottom)
+ if (s.usedInFix) { bar.style = Paint.Style.FILL; bar.color = c }
+ else { bar.style = Paint.Style.STROKE; bar.strokeWidth = 1.5f * dp; bar.color = c; rect.inset(0.75f * dp, 0.75f * dp) }
+ canvas.drawRoundRect(rect, 2 * dp, 2 * dp, bar)
+ if (slot >= 14 * dp) {
+ text.color = alpha(ink, 0xAA)
+ canvas.drawText("${s.svid}", x + bw / 2, height - 2 * dp, text)
+ canvas.drawText("%.0f".format(s.cn0), x + bw / 2, y - 3 * dp, text)
+ }
+ }
+ }
+}
+
+/**
+ * The aircraft around you seen from above: you in the middle, north up, rings at a quarter, half
+ * and the whole of [rangeKm]. Each one points where it's flying, with its callsign and altitude;
+ * law-enforcement ones in red.
+ */
+class AircraftRadarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ class Blip(val bearingDeg: Double, val distanceKm: Double, val trackDeg: Double?, val label: String, val altitude: String?, val police: Boolean)
+
+ private var blips: List<Blip> = emptyList()
+ private var rangeKm = 50.0
+ private val ink = ChipStyle.onSurface(context)
+ private val accent = ChipStyle.accent(context).first
+ private val grid = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
+ private val plane = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val path = Path()
+
+ fun set(list: List<Blip>, rangeKm: Double) {
+ blips = list; this.rangeKm = rangeKm
+ contentDescription = "${list.size} aircraft within ${rangeKm.toInt()} km"
+ invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) {
+ val s = MeasureSpec.getSize(w).coerceAtMost((420 * dp).toInt())
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize(s, h))
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val cx = width / 2f; val cy = height / 2f
+ val r = min(width, height) / 2f - 14 * dp
+ grid.strokeWidth = 1.2f * dp
+ text.textAlign = Paint.Align.LEFT
+ text.textSize = 9 * dp
+ text.typeface = Typeface.DEFAULT
+ for (k in 1..4) {
+ grid.color = alpha(accent, if (k == 4) 0x77 else 0x35)
+ canvas.drawCircle(cx, cy, r * k / 4f, grid)
+ if (k % 2 == 0) {
+ text.color = alpha(ink, 0x88)
+ canvas.drawText("${(rangeKm * k / 4).toInt()} km", cx + 3 * dp, cy - r * k / 4f + 11 * dp, text)
+ }
+ }
+ grid.color = alpha(accent, 0x25)
+ canvas.drawLine(cx - r, cy, cx + r, cy, grid)
+ canvas.drawLine(cx, cy - r, cx, cy + r, grid)
+ text.textAlign = Paint.Align.CENTER
+ text.typeface = Typeface.DEFAULT_BOLD
+ text.textSize = 11 * dp
+ text.color = alpha(ink, 0xAA)
+ canvas.drawText("N", cx, cy - r - 3 * dp, text)
+ plane.color = accent
+ canvas.drawCircle(cx, cy, 4 * dp, plane)
+
+ for (b in blips.sortedBy { it.police }) {
+ val f = (b.distanceKm / rangeKm).coerceAtMost(1.0)
+ val a = Math.toRadians(b.bearingDeg - 90)
+ val x = cx + (r * f * cos(a)).toFloat(); val y = cy + (r * f * sin(a)).toFloat()
+ val c = if (b.police) 0xFFD0503C.toInt() else ink
+ plane.color = c
+ canvas.save()
+ canvas.translate(x, y)
+ canvas.rotate((b.trackDeg ?: 0.0).toFloat())
+ path.reset()
+ val s = (if (b.police) 9f else 7f) * dp
+ if (b.trackDeg != null) {
+ path.moveTo(0f, -s); path.lineTo(s * 0.7f, s * 0.8f); path.lineTo(0f, s * 0.4f); path.lineTo(-s * 0.7f, s * 0.8f); path.close()
+ canvas.drawPath(path, plane)
+ } else canvas.drawCircle(0f, 0f, s * 0.5f, plane)
+ canvas.restore()
+ text.textAlign = Paint.Align.LEFT
+ text.typeface = if (b.police) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
+ text.textSize = 10 * dp
+ text.color = c
+ val lx = if (x > cx + r * 0.5f) x - text.measureText(b.label) - s - 2 * dp else x + s + 2 * dp
+ canvas.drawText(b.label, lx, y, text)
+ b.altitude?.let {
+ text.textSize = 9 * dp
+ text.color = alpha(c, 0xAA)
+ canvas.drawText(it, lx, y + 11 * dp, text)
+ }
+ }
+ }
+}
+
+/** A trace's route as an outline (north up, kept to its own shape), with its flagged devices as dots. */
+class RouteOutlineView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var points: List<Pair<Double, Double>> = emptyList()
+ private var flagged: List<Pair<Double, Double>> = emptyList()
+ private var color = ChipStyle.accent(context).first
+ private val ink = ChipStyle.onSurface(context)
+ private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeJoin = Paint.Join.ROUND; strokeCap = Paint.Cap.ROUND }
+ private val dot = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val path = Path()
+
+ fun set(points: List<Pair<Double, Double>>, flagged: List<Pair<Double, Double>>, color: Int) {
+ this.points = points; this.flagged = flagged; this.color = color
+ contentDescription = if (points.size < 2) "No route" else "Route, ${flagged.size} flagged along it"
+ invalidate()
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val pad = 6 * dp
+ if (points.size < 2) {
+ line.color = alpha(ink, 0x40); line.strokeWidth = 2 * dp
+ canvas.drawLine(pad, height / 2f, width - pad, height / 2f, line)
+ return
+ }
+ val lat0 = points.sumOf { it.first } / points.size
+ val k = cos(Math.toRadians(lat0))
+ val minX = points.minOf { it.second } * k; val maxX = points.maxOf { it.second } * k
+ val minY = points.minOf { it.first }; val maxY = points.maxOf { it.first }
+ val span = maxOf(maxX - minX, maxY - minY, 1e-6)
+ val scale = min((width - 2 * pad) / (maxX - minX).coerceAtLeast(span * 0.05), (height - 2 * pad) / (maxY - minY).coerceAtLeast(span * 0.05))
+ val ox = pad + ((width - 2 * pad) - (maxX - minX) * scale) / 2
+ val oy = pad + ((height - 2 * pad) - (maxY - minY) * scale) / 2
+ fun x(lon: Double) = (ox + (lon * k - minX) * scale).toFloat()
+ fun y(lat: Double) = (oy + (maxY - lat) * scale).toFloat()
+ path.reset()
+ points.forEachIndexed { i, p -> if (i == 0) path.moveTo(x(p.second), y(p.first)) else path.lineTo(x(p.second), y(p.first)) }
+ line.color = color; line.strokeWidth = 2.5f * dp
+ canvas.drawPath(path, line)
+ dot.color = color
+ canvas.drawCircle(x(points.first().second), y(points.first().first), 3.5f * dp, dot)
+ dot.color = ink
+ canvas.drawCircle(x(points.last().second), y(points.last().first), 3.5f * dp, dot)
+ dot.color = 0xFFD0503C.toInt()
+ for (f in flagged) canvas.drawCircle(x(f.second), y(f.first), 3f * dp, dot)
+ }
+}
+
+/** Small bars, one per entry, each with its own colour (a timeline of checks); a stub where a value is 0. */
+class MiniBarsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+ private var values = FloatArray(0)
+ private var colors = IntArray(0)
+ private var slots = 20
+ private val ink = ChipStyle.onSurface(context)
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val rect = RectF()
+
+ /** [slots]: how many places the width is cut into (the newest bar sits at the right). */
+ fun set(values: FloatArray, colors: IntArray, slots: Int) {
+ this.values = values; this.colors = colors; this.slots = slots.coerceAtLeast(values.size).coerceAtLeast(1); invalidate()
+ }
+
+ override fun onMeasure(w: Int, h: Int) =
+ setMeasuredDimension(MeasureSpec.getSize(w), resolveSize((40 * dp).toInt(), h))
+
+ override fun onDraw(canvas: Canvas) {
+ val slot = width.toFloat() / slots
+ val bw = slot * 0.65f
+ val max = (values.maxOrNull() ?: 0f).coerceAtLeast(1f)
+ paint.color = alpha(ink, 0x25)
+ canvas.drawRect(0f, height - dp, width.toFloat(), height.toFloat(), paint)
+ val first = slots - values.size
+ values.forEachIndexed { i, v ->
+ val x = slot * (first + i) + (slot - bw) / 2
+ val h = (height * v / max).coerceAtLeast(3 * dp)
+ rect.set(x, height - h, x + bw, height.toFloat())
+ paint.color = colors.getOrElse(i) { ink }
+ canvas.drawRoundRect(rect, 2 * dp, 2 * dp, paint)
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
index 9b251a4..d9b1f4b 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
@@ -57,6 +57,7 @@ class WazeStatusActivity : AppCompatActivity() {
val column = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(pad(16), pad(16), pad(16), pad(16))
+ addView(visual.box)
addView(body)
addView(button("Check now") { WazeUi.checkNow(this@WazeStatusActivity) })
addView(pause)
@@ -78,7 +79,142 @@ class WazeStatusActivity : AppCompatActivity() {
override fun onSupportNavigateUp(): Boolean { finish(); return true }
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ VisualMode.addMenu(menu, this, VisualMode.Screen.WAZE); return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean =
+ VisualMode.handle(item, this, VisualMode.Screen.WAZE) { invalidateOptionsMenu(); refresh() } || super.onOptionsItemSelected(item)
+
+ private val visual by lazy { Visual() }
+
+ /** The visual style: state and countdown, counts, a timeline of the last checks, and what goes out. */
+ private inner class Visual {
+ val ctx = this@WazeStatusActivity
+ val dp = resources.displayMetrics.density
+ val accent = ChipStyle.accent(ctx).first
+ val box = LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL }
+ val stateChip = TextView(ctx).apply { textSize = 12f; setTypeface(typeface, android.graphics.Typeface.BOLD) }
+ val source = TextView(ctx).apply { textSize = 13f }
+ val ring = ConfidenceRingView(ctx)
+ val every = TextView(ctx).apply { textSize = 14f; setTypeface(typeface, android.graphics.Typeface.BOLD) }
+ val last = TextView(ctx).apply { textSize = 12f; alpha = 0.8f }
+ val tiles = listOf(VisualMode.tile(ctx, "0", "on the map", accent), VisualMode.tile(ctx, "0", "in alert range", accent),
+ VisualMode.tile(ctx, "0", "checks", accent))
+ val timeline = MiniBarsView(ctx)
+ val timelineNote = TextView(ctx).apply { textSize = 11f; alpha = 0.7f }
+ val out = TextView(ctx).apply { textSize = 13f; setLineSpacing(0f, 1.15f); setTextIsSelectable(true) }
+ val answer = TextView(ctx).apply { textSize = 12f; alpha = 0.8f; setTextIsSelectable(true) }
+
+ fun title(t: String) = TextView(ctx).apply {
+ text = t; textSize = 12f; setTypeface(typeface, android.graphics.Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
+ }
+
+ fun card(vararg views: View) = LinearLayout(ctx).apply {
+ orientation = LinearLayout.VERTICAL
+ background = VisualMode.card(ctx)
+ val p = (12 * dp).toInt(); setPadding(p, p, p, p)
+ views.forEach { addView(it) }
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ }
+
+ init {
+ val head = LinearLayout(ctx).apply {
+ orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(title("WAZE CHECKS"), LinearLayout.LayoutParams(0, -2, 1f))
+ addView(stateChip)
+ }
+ val timing = LinearLayout(ctx).apply {
+ orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(ring, LinearLayout.LayoutParams((96 * dp).toInt(), (96 * dp).toInt()).apply { marginEnd = (12 * dp).toInt() })
+ addView(LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL; addView(every); addView(last) },
+ LinearLayout.LayoutParams(0, -2, 1f))
+ setPadding(0, (8 * dp).toInt(), 0, 0)
+ }
+ box.addView(card(head, source, timing))
+ box.addView(VisualMode.tileRow(ctx, tiles).apply {
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+ })
+ box.addView(card(title("LAST CHECKS"), timeline, timelineNote))
+ box.addView(card(title("WHAT GOES OUT"), out))
+ box.addView(card(title("LAST ANSWER"), answer))
+ }
+
+ fun value(tile: View, v: String) { ((tile as LinearLayout).getChildAt(0) as TextView).text = v }
+ }
+
private fun refresh() {
+ if (VisualMode.on(this, VisualMode.Screen.WAZE)) { refreshVisual(); return }
+ visual.box.visibility = View.GONE
+ body.visibility = View.VISIBLE
+ refreshList()
+ }
+
+ private fun refreshVisual() {
+ val v = visual
+ v.box.visibility = View.VISIBLE
+ body.visibility = View.GONE
+ val now = System.currentTimeMillis()
+ val direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT
+ val paused = Prefs.wazePaused(this)
+ pause.text = if (paused) "Resume Waze checks" else "Pause Waze checks"
+ forget.visibility = if (direct) View.VISIBLE else View.GONE
+ val running = WazePolice.running && !paused
+ val (state, stateColor) = when {
+ !WazeUi.on(this) -> "Off" to 0xFF8A8A8A.toInt()
+ !ScanForegroundService.isRunning -> "Not scanning" to 0xFF8A8A8A.toInt()
+ paused -> "Paused" to 0xFFE0A33A.toInt()
+ WazePolice.running -> "Checking" to 0xFF2E9E5B.toInt()
+ else -> "Starting" to 0xFFE0A33A.toInt()
+ }
+ v.stateChip.text = state
+ VisualMode.chip(v.stateChip, stateColor)
+ v.source.text = if (direct) "Waze direct" + (if (Diagnostics.host.isNotEmpty()) " · ${Diagnostics.host}" else "") else "OpenWeb Ninja"
+ if (running && WazeStatus.everyS > 0) {
+ val left = ((WazeStatus.nextCheckAt - now) / 1000).coerceAtLeast(0)
+ v.ring.set((100 * left / WazeStatus.everyS.coerceAtLeast(1)).toInt(), v.accent, "next check", "$left s")
+ val motion = when (WazeStatus.motion) {
+ MotionTracker.State.PARKED -> "parked"
+ MotionTracker.State.FAST -> "on a fast road"
+ MotionTracker.State.MOVING -> "moving"
+ }
+ v.every.text = "Every ${Prefs.formatInterval(WazeStatus.everyS)}" +
+ if (WazeStatus.everyS != WazeStatus.baseS) "\nadapted: you are $motion" else ""
+ } else {
+ v.ring.set(0, 0xFF8A8A8A.toInt(), "next check", "–")
+ v.every.text = when {
+ !WazeUi.on(this) -> "Turn on Waze reports in Settings"
+ !ScanForegroundService.isRunning -> "Waze is checked while scanning"
+ paused -> "Checks are paused"
+ else -> "Starting…"
+ }
+ }
+ v.last.text = "Last check ${if (WazeStatus.lastCheckAt <= 0) "never" else "${((now - WazeStatus.lastCheckAt) / 1000).coerceAtLeast(0)} s ago"}" +
+ if (WazeStatus.lastCheckAt > 0) ", took ${String.format(Locale.US, "%.1f", WazeStatus.lastCheckMs / 1000.0)} s" else ""
+ v.value(v.tiles[0], "${WazeStatus.onMap}")
+ v.value(v.tiles[1], "${WazeStatus.inAlertRange}")
+ v.value(v.tiles[2], "${WazeStatus.checks}")
+ val checks = WazeStatus.recent.toList()
+ val red = 0xFFD0503C.toInt()
+ v.timeline.set(FloatArray(checks.size) { checks[it].reports.toFloat() },
+ IntArray(checks.size) { if (checks[it].ok) v.accent else red }, WazeStatus.KEEP)
+ v.timelineNote.text = if (checks.isEmpty()) "No checks yet this session."
+ else "One bar per check, newest on the right; its height is the reports on the map. Red: no answer."
+ v.out.text = if (direct) listOfNotNull(
+ if (Diagnostics.sentLat.isNaN()) "Nothing sent yet"
+ else "Your IP address and a 1 km grid square centred on " +
+ "${String.format(Locale.US, "%.3f", Diagnostics.sentLat)}, ${String.format(Locale.US, "%.3f", Diagnostics.sentLon)} (never your exact position)",
+ "Account: " + (if (WazeRtFetcher.hasStoredAccount(this)) "an anonymous account is stored on this phone" else "none yet; one is made on the next check") +
+ " (${WazeRtFetcher.accountsMadeToday(this)} of ${WazeRtFetcher.dailyAccountLimit()} made today)",
+ Diagnostics.lastError.takeIf { it.isNotEmpty() }?.let { "Last problem: $it" }
+ ).joinToString("\n") else listOf(
+ "Your API key and a box of about ${Prefs.formatRange(maxOf(Prefs.wazeViewKm(this) * 1000, Prefs.wazeAlertM(this)))} around your position (not rounded)",
+ "API key: " + (if (SecureStore.get(this, OnlineWatch.WAZE_KEY_NAME).isNullOrBlank()) "not set" else "set")
+ ).joinToString("\n")
+ v.answer.text = OnlineWatch.wazeStatus.ifEmpty { "No answer yet" }
+ }
+
+ private fun refreshList() {
val now = System.currentTimeMillis()
val direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT
val paused = Prefs.wazePaused(this)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
index 18bb9d8..aae51a6 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
@@ -48,6 +48,7 @@ class MonitorFrames {
*/
fun frame(b: ByteArray, d: Int, end: Int, channel: Int, rssi: Int?, now: Long = System.currentTimeMillis(),
pathA: Int? = null, pathB: Int? = null) {
+ frameCount.incrementAndGet()
PcapRecorder.frame(b, d, end, channel, rssi, now)
if (end - d < 24 || end > b.size) return
fun u8(i: Int) = b[i].toInt() and 0xff
@@ -236,6 +237,9 @@ class MonitorFrames {
}
companion object {
+ /** Every frame the adapters received, for the main screen's frames-per-second line. */
+ val frameCount = java.util.concurrent.atomic.AtomicLong()
+
const val PRUNE_MS = 60_000L
/** Reported for a device whose frames never carried a signal reading. */
const val NOMINAL_RSSI = -60
diff --git a/app/src/main/res/drawable/ic_view_list.xml b/app/src/main/res/drawable/ic_view_list.xml
new file mode 100644
index 0000000..698c78b
--- /dev/null
+++ b/app/src/main/res/drawable/ic_view_list.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Design icon (Apache-2.0), used on the Android Auto screens. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M3,13h2v-2H3v2zM3,17h2v-2H3v2zM3,9h2V7H3v2zM7,13h14v-2H7v2zM7,17h14v-2H7v2zM7,7v2h14V7H7z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_view_visual.xml b/app/src/main/res/drawable/ic_view_visual.xml
new file mode 100644
index 0000000..aea12c2
--- /dev/null
+++ b/app/src/main/res/drawable/ic_view_visual.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <!-- Three bars: the visual (gauges and charts) style. -->
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M4,20V11H8V20H4ZM10,20V4H14V20H10ZM16,20V14H20V20H16Z" />
+</vector>
diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xml
index 547af3d..5e1706e 100644
--- a/app/src/main/res/layout/activity_device_detail.xml
+++ b/app/src/main/res/layout/activity_device_detail.xml
@@ -48,6 +48,30 @@
android:textColor="#888888"
android:textSize="12sp" />
+ <!-- Visual style: hot / cold signal dial and the match's confidence ring -->
+ <LinearLayout
+ android:id="@+id/visualTop"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="12dp"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
+ android:visibility="gone">
+
+ <com.rfsentinel.app.ui.SignalGaugeView
+ android:id="@+id/gauge"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1.6" />
+
+ <com.rfsentinel.app.ui.ConfidenceRingView
+ android:id="@+id/ring"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:layout_weight="1" />
+ </LinearLayout>
+
<!-- Live signal -->
<LinearLayout
android:layout_width="match_parent"
diff --git a/app/src/main/res/layout/item_device.xml b/app/src/main/res/layout/item_device.xml
index c0038d4..d1ab5e1 100644
--- a/app/src/main/res/layout/item_device.xml
+++ b/app/src/main/res/layout/item_device.xml
@@ -7,46 +7,86 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:orientation="vertical"
+ android:gravity="center_vertical"
+ android:orientation="horizontal"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
- <TextView
- android:id="@+id/tagText"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="4dp"
- android:background="@color/match_tag_bg"
- android:paddingStart="6dp"
- android:paddingEnd="6dp"
- android:paddingTop="1dp"
- android:paddingBottom="1dp"
- android:textColor="@android:color/white"
- android:textSize="11sp"
- android:textStyle="bold"
- android:visibility="gone" />
-
- <TextView
- android:id="@+id/titleText"
- android:layout_width="match_parent"
+ <LinearLayout
+ android:layout_width="0dp"
android:layout_height="wrap_content"
- android:textSize="15sp" />
+ android:layout_weight="1"
+ android:orientation="vertical">
- <TextView
- android:id="@+id/macText"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:fontFamily="monospace"
- android:textSize="13sp" />
+ <TextView
+ android:id="@+id/tagText"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginBottom="4dp"
+ android:background="@color/match_tag_bg"
+ android:paddingStart="6dp"
+ android:paddingEnd="6dp"
+ android:paddingTop="1dp"
+ android:paddingBottom="1dp"
+ android:textColor="@android:color/white"
+ android:textSize="11sp"
+ android:textStyle="bold"
+ android:visibility="gone" />
+
+ <!-- Visual style: the match's confidence -->
+ <com.rfsentinel.app.ui.LevelBarView
+ android:id="@+id/confidenceBar"
+ android:layout_width="match_parent"
+ android:layout_height="4dp"
+ android:layout_marginBottom="5dp"
+ android:visibility="gone" />
+
+ <TextView
+ android:id="@+id/titleText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textSize="15sp" />
- <TextView
- android:id="@+id/metaText"
- android:layout_width="match_parent"
+ <TextView
+ android:id="@+id/macText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:fontFamily="monospace"
+ android:textSize="13sp" />
+
+ <TextView
+ android:id="@+id/metaText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textColor="#888888"
+ android:textSize="12sp" />
+ </LinearLayout>
+
+ <!-- Visual style: signal bars -->
+ <LinearLayout
+ android:id="@+id/signalBox"
+ android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:textColor="#888888"
- android:textSize="12sp" />
+ android:layout_marginStart="10dp"
+ android:gravity="center_horizontal"
+ android:orientation="vertical"
+ android:visibility="gone">
+
+ <com.rfsentinel.app.ui.SignalBarsView
+ android:id="@+id/signalBars"
+ android:layout_width="28dp"
+ android:layout_height="22dp" />
+
+ <TextView
+ android:id="@+id/signalText"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="2dp"
+ android:textColor="#888888"
+ android:textSize="10sp" />
+ </LinearLayout>
</LinearLayout>
<View
diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xml
index a47f60f..2dfaeb2 100644
--- a/app/src/main/res/values/ids.xml
+++ b/app/src/main/res/values/ids.xml
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="mapHost" type="id" />
+ <item name="visual_chip_color" type="id" />
</resources>
diff --git a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt
index 312ddf0..e7d306e 100644
--- a/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/online/WazeScreensTest.kt
@@ -88,6 +88,8 @@ class WazeScreensTest {
WazeStatus.baseS = 60
WazeStatus.everyS = 240
WazeStatus.motion = MotionTracker.State.PARKED
+ // The list style (Settings > Appearance > Screen style).
+ com.rfsentinel.app.ui.VisualMode.set(ctx, com.rfsentinel.app.ui.VisualMode.Screen.WAZE, false)
val activity = Robolectric.buildActivity(WazeStatusActivity::class.java).setup().get()
shadowOf(Looper.getMainLooper()).idle()
val text = allViews(activity.window.decorView).filterIsInstance<TextView>().joinToString("\n") { it.text }
@@ -98,6 +100,20 @@ class WazeScreensTest {
assertTrue(text, text.contains("Pause Waze checks"))
assertTrue(text, text.contains("Forget Waze account"))
activity.finish()
+
+ // The visual style says the same.
+ com.rfsentinel.app.ui.VisualMode.set(ctx, com.rfsentinel.app.ui.VisualMode.Screen.WAZE, true)
+ val visual = Robolectric.buildActivity(WazeStatusActivity::class.java).setup().get()
+ shadowOf(Looper.getMainLooper()).idle()
+ val v = allViews(visual.window.decorView).filter { it.isShown }.filterIsInstance<TextView>().joinToString("\n") { it.text }
+ assertTrue(v, v.contains("Checking"))
+ assertTrue(v, v.contains("Every 4 min"))
+ assertTrue(v, v.contains("adapted: you are parked"))
+ assertTrue(v, v.contains("Waze direct"))
+ assertTrue(v, v.contains("WHAT GOES OUT"))
+ assertTrue(v, v.contains("Pause Waze checks"))
+ assertTrue(v, v.contains("Forget Waze account"))
+ visual.finish()
}
@Test
diff --git a/app/src/test/java/com/rfsentinel/app/ui/TripsScreenTest.kt b/app/src/test/java/com/rfsentinel/app/ui/TripsScreenTest.kt
new file mode 100644
index 0000000..7cc6e4d
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/TripsScreenTest.kt
@@ -0,0 +1,90 @@
+package com.rfsentinel.app.ui
+
+import android.app.Application
+import android.os.Looper
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import com.rfsentinel.app.data.AppDatabase
+import com.rfsentinel.app.data.TripDeviceEntity
+import com.rfsentinel.app.data.TripEntity
+import com.rfsentinel.app.data.TripPointEntity
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+
+/** Recorded traces in both styles: the list rows, and the visual cards with the route's outline. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class TripsScreenTest {
+ private val ctx get() = RuntimeEnvironment.getApplication()
+
+ private fun allViews(root: View): List<View> {
+ val out = ArrayList<View>()
+ fun walk(v: View) { out += v; if (v is ViewGroup) for (i in 0 until v.childCount) walk(v.getChildAt(i)) }
+ walk(root)
+ return out
+ }
+
+ /** A made-up trace: a small square around 0,0 with one flagged device on it. */
+ private fun seed() = runBlocking {
+ val dao = AppDatabase.getInstance(ctx).tripDao()
+ // The database outlives a single test here: start from none.
+ dao.allFlow().first().forEach { dao.delete(it.id) }
+ val start = 1_700_000_000_000L
+ val id = dao.insertTrip(TripEntity(name = "Test trace", startTime = start, endTime = start + 754_000L,
+ distanceM = 2_400.0, pointCount = 5, deviceCount = 12, flaggedCount = 1))
+ dao.insertPoints(listOf(0.0 to 0.0, 0.0 to 0.005, 0.005 to 0.005, 0.005 to 0.0, 0.0 to 0.0).mapIndexed { i, (lat, lon) ->
+ TripPointEntity(tripId = id, time = start + i * 1000L, lat = lat, lon = lon)
+ })
+ dao.upsertDevices(listOf(TripDeviceEntity(tripId = id, mac = "AA:BB:CC:00:00:01", label = "Test camera", name = null,
+ vendor = null, deviceType = null, source = "BLE", category = "BODY_CAM", confidence = 90, evidence = null,
+ firstSeen = start, lastSeen = start, bestRssi = -60, lat = 0.005, lon = 0.0025)))
+ }
+
+ private fun open(visual: Boolean): List<View> {
+ VisualMode.set(ctx, VisualMode.Screen.TRIPS, visual)
+ val activity = Robolectric.buildActivity(TripsActivity::class.java).setup().get()
+ // The list and the route load off the main thread.
+ repeat(40) {
+ shadowOf(Looper.getMainLooper()).idle()
+ val views = allViews(activity.window.decorView)
+ val ready = if (visual) views.filterIsInstance<RouteOutlineView>().any { it.contentDescription?.startsWith("Route") == true }
+ else views.filterIsInstance<TextView>().any { it.text.contains("Test trace") }
+ if (ready) return views
+ Thread.sleep(50)
+ }
+ return allViews(activity.window.decorView)
+ }
+
+ @Test
+ fun theListStyleKeepsTheTextRow() {
+ seed()
+ val text = open(visual = false).filterIsInstance<TextView>().joinToString("\n") { it.text }
+ assertTrue(text, text.contains("Test trace"))
+ assertTrue(text, text.contains("12 devices · 1 flagged · 5 GPS points"))
+ }
+
+ @Test
+ fun theVisualStyleDrawsTheRouteAndItsNumbers() {
+ seed()
+ val views = open(visual = true)
+ val route = views.filterIsInstance<RouteOutlineView>()
+ assertEquals(1, route.size)
+ assertEquals("Route, 1 flagged along it", route[0].contentDescription)
+ val text = views.filterIsInstance<TextView>().joinToString("\n") { it.text }
+ assertTrue(text, text.contains("Test trace"))
+ assertTrue(text, text.contains("2.40 km"))
+ assertTrue(text, text.contains("0:12"))
+ assertTrue(text, text.contains("12 devices"))
+ assertTrue(text, text.contains("1 flagged"))
+ }
+}