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.

Snapshots, car auto-record, watchlist prefix slider, external-hardware list time, radio on radar, BLE resume after screen on

CIS-C014ca7099bab6
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3e54c68..be4bbb9 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -104,6 +104,10 @@
android:name=".ui.TripsActivity"
android:exported="false"
android:parentActivityName=".MainActivity" />
+ <activity
+ android:name=".ui.SnapshotActivity"
+ android:exported="false"
+ android:parentActivityName=".ui.TripsActivity" />
<activity
android:name=".ui.HistoryActivity"
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 e5e1334..60503ba 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -50,6 +50,8 @@ class MainActivity : AppCompatActivity() {
private const val SOUND_ITEM = 1001
/** A radio row flashes while its transmitter was heard this recently. */
private const val RADIO_LIVE_MS = 15_000L
+ /** Radio transmissions stay on the radar this long after they were last heard (the list keeps 5 minutes). */
+ private const val RADIO_RADAR_MS = 60_000L
private const val BLUETOOTH_TAG_COLOR = 0xFF1565C0.toInt()
private const val WIFI_TAG_COLOR = 0xFF00838F.toInt()
private const val REFRESH_MS = 1_000L
@@ -64,6 +66,8 @@ class MainActivity : AppCompatActivity() {
private val filterChips = HashMap<com.rfsentinel.app.ui.DeviceFilter, com.google.android.material.chip.Chip>()
private var query = ""
private var deviceCount = 0
+ /** The devices the list shows right now (filter and search applied), for Save snapshot. */
+ private var shownDevices: List<DeviceRegistry.Snapshot> = emptyList()
private var flaggedCount = 0
/** The visual style's status: warning chip and hardware strip (Settings > Appearance). */
private val statusPanel by lazy {
@@ -173,7 +177,10 @@ class MainActivity : AppCompatActivity() {
// Rows rebind every second (RSSI / "seen Xs ago"); the default change
// crossfade would make the whole list flicker and fight the match flash.
(binding.recyclerView.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
- binding.radarView.onBlipClick = { DeviceActions.openDetails(this, it) }
+ binding.radarView.onBlipClick = {
+ if (it.startsWith(RADIO_ROW)) startActivity(Intent(this, com.rfsentinel.app.ui.DetectionLogActivity::class.java))
+ else DeviceActions.openDetails(this, it)
+ }
// The app closed while the map was starting last time: switch it to OpenGL, or leave it off the main screen (and say so).
val mapRecovery = com.rfsentinel.app.ui.MapSafety.recover(this)
panes = com.rfsentinel.app.ui.MainPanes(this, binding)
@@ -348,7 +355,7 @@ class MainActivity : AppCompatActivity() {
isCheckable = true
// No invisible 48 dp touch frame around each chip: the row is 16 dp shorter.
setEnsureMinTouchTargetSize(false)
- com.rfsentinel.app.ui.ChipStyle.apply(this)
+ com.rfsentinel.app.ui.ChipStyle.apply(this, minTouchTarget = false)
}
filterChips[f] = chip
binding.filterChips.addView(chip)
@@ -380,10 +387,13 @@ class MainActivity : AppCompatActivity() {
*/
private fun styleFilterChip(chip: com.google.android.material.chip.Chip, visual: Boolean, color: Int?) {
val key = if (visual) "v${color ?: 0}" else "list"
- if (chip.getTag(R.id.visual_chip_color) == key) return
+ val was = chip.getTag(R.id.visual_chip_color) as? String
+ if (was == key) return
chip.setTag(R.id.visual_chip_color, key)
+ // Only the colour changed (the flagged count came or went): recolour, touch nothing that sizes the chip.
+ if (visual && was?.startsWith("v") == true) { tintVisualChip(chip, color); return }
val dp = resources.displayMetrics.density
- com.rfsentinel.app.ui.ChipStyle.apply(chip)
+ com.rfsentinel.app.ui.ChipStyle.apply(chip, minTouchTarget = false)
val stock = chipPadding ?: floatArrayOf(chip.chipStartPadding, chip.textStartPadding, chip.textEndPadding, chip.chipEndPadding)
.also { chipPadding = it }
if (!visual) {
@@ -395,8 +405,15 @@ class MainActivity : AppCompatActivity() {
}
// Tighter sides, so All, Flagged, Bluetooth, WiFi and Cells with their counts fit a phone's width.
chip.chipStartPadding = 2 * dp; chip.textStartPadding = 6 * dp; chip.textEndPadding = 6 * dp; chip.chipEndPadding = 2 * dp
- // No invisible 48 dp touch frame in the visual style: the row is 16 dp shorter.
- chip.setEnsureMinTouchTargetSize(false)
+ tintVisualChip(chip, color)
+ chip.chipStrokeWidth = 1.2f * dp
+ chip.chipMinHeight = 28 * dp
+ chip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 13f)
+ sameSize(chip)
+ }
+
+ /** The visual style's tinted pill in [color] (the theme highlight when null). */
+ private fun tintVisualChip(chip: com.google.android.material.chip.Chip, color: Int?) {
val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)
val c = color ?: accent
val checked = intArrayOf(android.R.attr.state_checked)
@@ -404,11 +421,7 @@ class MainActivity : AppCompatActivity() {
chip.chipBackgroundColor = android.content.res.ColorStateList(arrayOf(checked, none),
intArrayOf(c, com.rfsentinel.app.ui.VisualMode.tint(c, 0x26)))
chip.chipStrokeColor = android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(c, com.rfsentinel.app.ui.VisualMode.tint(c, 0x99)))
- chip.chipStrokeWidth = 1.2f * dp
chip.setTextColor(android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(onAccent, c)))
- chip.chipMinHeight = 28 * dp
- chip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 13f)
- sameSize(chip)
}
/**
@@ -628,10 +641,11 @@ class MainActivity : AppCompatActivity() {
// Ordinary devices leave the list and radar soon after they're out of range (LiveWindow).
val bleMs = Prefs.liveBleSec(this) * 1000L
val wifiMs = Prefs.liveWifiSec(this) * 1000L
+ val externalMs = Prefs.liveExternalSec(this) * 1000L
// Settings > Scanning: trusted (whitelisted) devices can be left out of the list and radar.
val hideTrusted = Prefs.hideWhitelisted(this)
val all = DeviceRegistry.snapshot(now).filter {
- com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs) && !(hideTrusted && WhitelistCache.contains(it.mac))
+ com.rfsentinel.app.ui.LiveWindow.keep(it, now, bleMs, wifiMs, externalMs) && !(hideTrusted && WhitelistCache.contains(it.mac))
}
val threshold = Prefs.alertThreshold(this)
binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && panes.listShown
@@ -665,11 +679,15 @@ class MainActivity : AppCompatActivity() {
.thenBy { bandOrder(ProximityUtil.band(it.rssi)) }
.thenBy { it.firstSeen }
)
+ shownDevices = visible
refreshMuteButton()
// The map and radar frames take the top alert's colour.
panes.update(flagged.maxByOrNull { it.best?.confidence ?: 0 }?.let { colorFor(it) })
+ var radioBlips = 0
if (panes.radarShown) {
+ val radio = radioBlips(now, threshold)
+ radioBlips = radio.size
binding.radarView.setBlips(visible.take(200).map { s ->
val alert = com.rfsentinel.app.ui.LiveWindow.alerting(s, now)
RadarView.Blip(
@@ -678,7 +696,7 @@ class MainActivity : AppCompatActivity() {
alert,
if (alert) s.best?.label else null
)
- })
+ } + radio)
}
if (panes.listShown) {
val cells = cellRows(now)
@@ -693,7 +711,8 @@ class MainActivity : AppCompatActivity() {
submitRows(airUrgent + radioLive + urgent + visible.map { toRow(it, now, threshold) } + airQuiet + radioOld + cells + quiet)
shownCells = cells.size + waze.size + radio.size + air.size
}
- binding.emptyState.visibility = if (visible.isEmpty() && (!panes.listShown || shownCells == 0)) View.VISIBLE else View.GONE
+ binding.emptyState.visibility = if (visible.isEmpty() && (!panes.listShown || shownCells == 0) &&
+ (!panes.radarShown || radioBlips == 0)) View.VISIBLE else View.GONE
// A filter that hides everything heard: one tap back to the full list.
binding.showAllButton.visibility =
if (filter != com.rfsentinel.app.ui.DeviceFilter.ALL && all.isNotEmpty()) View.VISIBLE else View.GONE
@@ -814,6 +833,24 @@ class MainActivity : AppCompatActivity() {
}
}
+ /**
+ * RTL-SDR / HackRF transmissions of the last minute on the radar, under the All and Radio filters: closer to the
+ * centre the stronger the signal. One on the air right now at or above the alert threshold pulses, with its frequency.
+ */
+ private fun radioBlips(now: Long, threshold: Int): List<RadarView.Blip> {
+ if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.RADIO) ||
+ !ScanForegroundService.isRunning) return emptyList()
+ val color = com.rfsentinel.app.ui.ThemeManager.ink(this, Category.RADIO.colorArgb)
+ return com.rfsentinel.app.sdr.RadioLog.current(now)
+ .filter { now - it.lastSeen <= RADIO_RADAR_MS }
+ .map { r ->
+ val alert = now - r.lastSeen <= RADIO_LIVE_MS && r.confidence >= threshold
+ // Signal above the noise as a stand-in RSSI: 40 dB lands in Near, 30 dB in Nearby (as the alert wording).
+ RadarView.Blip(RADIO_ROW + r.freqHz, (-115 + r.snrDb * 3 / 2).coerceIn(-100, -30), color, alert,
+ if (alert) "${r.mhz} MHz" + (r.name?.let { " $it" } ?: "") else null)
+ }
+ }
+
/** The aircraft heard right now (RTL-SDR ADS-B and the online feeds). */
private fun currentAircraft(now: Long): List<com.rfsentinel.app.online.PoliceAircraft.Seen> = when {
!ScanForegroundService.isRunning -> emptyList()
@@ -1153,6 +1190,43 @@ class MainActivity : AppCompatActivity() {
return true
}
+ /** Keeps the device list as shown now (filter and search applied) under a name, to look at later (History > Snapshots). */
+ private fun saveSnapshot() {
+ val devices = shownDevices
+ if (devices.isEmpty()) {
+ android.widget.Toast.makeText(this, "The list is empty: nothing to save", android.widget.Toast.LENGTH_SHORT).show()
+ return
+ }
+ val input = android.widget.EditText(this).apply {
+ setText(com.rfsentinel.app.data.Snapshots.defaultName()); selectAll()
+ setSingleLine()
+ }
+ val pad = (20 * resources.displayMetrics.density).toInt()
+ com.google.android.material.dialog.MaterialAlertDialogBuilder(this)
+ .setTitle("Save snapshot")
+ .setMessage("Keeps the ${devices.size} device${if (devices.size == 1) "" else "s"} in the list now, to look at later in History > Snapshots.")
+ .setView(android.widget.FrameLayout(this).apply { setPadding(pad, 0, pad, 0); addView(input) })
+ .setPositiveButton("Save") { _, _ ->
+ val name = input.text.toString().trim().ifEmpty { com.rfsentinel.app.data.Snapshots.defaultName() }
+ val app = applicationContext
+ lifecycleScope.launch {
+ val id = runCatching { com.rfsentinel.app.data.Snapshots.save(app, name, devices) }.getOrNull()
+ if (id == null) {
+ android.widget.Toast.makeText(this@MainActivity, "Couldn't save the snapshot", android.widget.Toast.LENGTH_SHORT).show()
+ return@launch
+ }
+ com.google.android.material.snackbar.Snackbar.make(binding.root, "Snapshot saved", com.google.android.material.snackbar.Snackbar.LENGTH_LONG)
+ .setAction("View") {
+ startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.SnapshotActivity::class.java)
+ .putExtra(com.rfsentinel.app.ui.SnapshotActivity.EXTRA_TRIP_ID, id))
+ }
+ .show()
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_waze_now -> { com.rfsentinel.app.ui.WazeUi.checkNow(this); true }
@@ -1163,6 +1237,12 @@ class MainActivity : AppCompatActivity() {
R.id.action_probes -> { startActivity(Intent(this, com.rfsentinel.app.probes.ProbeListActivity::class.java)); true }
R.id.action_export -> { Exporter.showExportMenu(this); true }
R.id.action_traces -> { startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java)); true }
+ R.id.action_snapshots -> {
+ startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java)
+ .putExtra(com.rfsentinel.app.ui.TripsActivity.EXTRA_SECTION, com.rfsentinel.app.data.TripEntity.KIND_SNAPSHOT))
+ true
+ }
+ R.id.action_save_snapshot -> { saveSnapshot(); true }
R.id.action_history -> { startActivity(Intent(this, com.rfsentinel.app.ui.HistoryActivity::class.java)); true }
// Like a radar detector's mute: a tap snoozes for the set length; muted or snoozed, a tap brings the sound back.
R.id.action_mute -> {
diff --git a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt
index 49ac17d..82c3451 100644
--- a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt
@@ -12,7 +12,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase
DetectionEntity::class, WhitelistEntity::class, KnownDeviceEntity::class,
TripEntity::class, TripPointEntity::class, TripDeviceEntity::class
],
- version = 5,
+ version = 6,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
@@ -85,13 +85,20 @@ abstract class AppDatabase : RoomDatabase() {
}
}
+ /** v2.28: snapshots - device lists saved without a route, kept with the traces. */
+ val MIGRATION_5_6 = object : Migration(5, 6) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ db.execSQL("ALTER TABLE trips ADD COLUMN kind TEXT NOT NULL DEFAULT 'trace'")
+ }
+ }
+
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"rfsentinel.db"
- ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5).build().also { INSTANCE = it }
+ ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6).build().also { INSTANCE = it }
}
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/data/Snapshots.kt b/app/src/main/java/com/rfsentinel/app/data/Snapshots.kt
new file mode 100644
index 0000000..e106383
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/data/Snapshots.kt
@@ -0,0 +1,44 @@
+package com.rfsentinel.app.data
+
+import android.content.Context
+import com.rfsentinel.app.service.DeviceRegistry
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * Snapshots: the device list saved as it is at one moment, to look at again later without recording a trace.
+ * Kept with the traces (same tables, [TripEntity.KIND_SNAPSHOT], no route), so they open on the map and export
+ * the same way.
+ */
+object Snapshots {
+
+ fun defaultName(now: Long = System.currentTimeMillis()): String =
+ "Snapshot " + SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(now))
+
+ /** Saves [devices] under [name]; returns the new snapshot's id. */
+ suspend fun save(context: Context, name: String, devices: List<DeviceRegistry.Snapshot>): Long {
+ val now = System.currentTimeMillis()
+ val dao = AppDatabase.getInstance(context).tripDao()
+ val rows = devices.map { s ->
+ // Trusted (whitelisted) devices are saved unflagged, as a trace records them.
+ val best = s.best?.takeUnless { WhitelistCache.contains(s.mac) }
+ val place = s.place
+ TripDeviceEntity(
+ tripId = 0, mac = s.mac,
+ label = best?.label ?: s.name ?: s.deviceType.ifEmpty { s.mac },
+ name = s.name, vendor = s.vendor, deviceType = s.deviceType.ifEmpty { null },
+ source = s.source.name,
+ category = best?.category?.name, confidence = best?.confidence ?: 0, evidence = best?.evidence,
+ firstSeen = s.firstSeen, lastSeen = s.lastSeen, bestRssi = s.bestRssi,
+ lat = place?.lat, lon = place?.lon
+ )
+ }
+ val id = dao.insertTrip(TripEntity(
+ name = name, startTime = now, endTime = now,
+ deviceCount = rows.size, flaggedCount = rows.count { it.flagged }, kind = TripEntity.KIND_SNAPSHOT
+ ))
+ rows.map { it.copy(tripId = id) }.chunked(300).forEach { dao.upsertDevices(it) }
+ return id
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/data/Trips.kt b/app/src/main/java/com/rfsentinel/app/data/Trips.kt
index cb69302..c68979e 100644
--- a/app/src/main/java/com/rfsentinel/app/data/Trips.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/Trips.kt
@@ -1,5 +1,6 @@
package com.rfsentinel.app.data
+import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.ForeignKey
@@ -10,7 +11,7 @@ import androidx.room.Query
import androidx.room.Upsert
import kotlinx.coroutines.flow.Flow
-/** A recorded scan trace: your GPS path plus every device heard along it. */
+/** A recorded scan trace: your GPS path plus every device heard along it. Also a snapshot: a device list saved at one moment. */
@Entity(tableName = "trips")
data class TripEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@@ -20,9 +21,17 @@ data class TripEntity(
val distanceM: Double = 0.0,
val pointCount: Int = 0,
val deviceCount: Int = 0,
- val flaggedCount: Int = 0
+ val flaggedCount: Int = 0,
+ /** [KIND_TRACE] (a recorded route) or [KIND_SNAPSHOT] (the device list saved at one moment, no route). */
+ @ColumnInfo(defaultValue = KIND_TRACE) val kind: String = KIND_TRACE
) {
val recording: Boolean get() = endTime == null
+ val snapshot: Boolean get() = kind == KIND_SNAPSHOT
+
+ companion object {
+ const val KIND_TRACE = "trace"
+ const val KIND_SNAPSHOT = "snapshot"
+ }
}
@Entity(
diff --git a/app/src/main/java/com/rfsentinel/app/detect/VendorDb.kt b/app/src/main/java/com/rfsentinel/app/detect/VendorDb.kt
index 43ae7f5..63e4683 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/VendorDb.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/VendorDb.kt
@@ -71,6 +71,13 @@ object VendorDb {
return table[hex.take(9)] ?: table[hex.take(7)] ?: table[hex.take(6)]
}
+ /** Hex digits of the IEEE block a MAC is registered in (9, 7 or 6), or null when it's in none. */
+ fun blockDigits(mac: String): Int? {
+ val hex = mac.replace(":", "").uppercase()
+ val table = oui
+ return intArrayOf(9, 7, 6).firstOrNull { hex.length >= it && table[hex.take(it)] != null }
+ }
+
fun company(id: Int): String? = companies[id]
fun uuid16(short: Int): String? = uuids[short]
diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
index 2136a1c..c225584 100644
--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
@@ -29,7 +29,7 @@ object OuiWatchlist {
private val listType = object : TypeToken<List<OuiEntry>>() {}.type
private class State(
- /** Address entries keyed by hex digits: 12 = one device, 9/7/6 = IEEE block. */
+ /** Address entries keyed by hex digits: 12 = one device, 6 to 11 = a prefix (IEEE blocks are 9/7/6). */
val byHex: Map<String, OuiEntry>,
val nameRules: List<OuiEntry>,
/** Name / SSID prefix rules. */
@@ -183,24 +183,24 @@ object OuiWatchlist {
fun allEntries(): List<OuiEntry> = state.all
- /** Valid keys: IEEE block prefix (24/28/36-bit), full MAC, or a non-empty name:/starts:/vendor:/probe:/fp:/adv: rule. */
+ /** Valid keys: address prefix (24 to 44 bits), full MAC, or a non-empty name:/starts:/vendor:/probe:/fp:/adv: rule. */
fun isValidKey(prefix: String): Boolean {
val k = prefix.trim()
if (k.startsWith(OuiEntry.NAME, true) || k.startsWith(OuiEntry.STARTS, true) || k.startsWith(OuiEntry.VENDOR, true) ||
k.startsWith(OuiEntry.PROBE, true) || k.startsWith(OuiEntry.FINGERPRINT, true) || k.startsWith(OuiEntry.ADVERT, true)) {
return k.substringAfter(':').isNotBlank()
}
- return MacUtil.isValidBlock(k) || MacUtil.isValidMac(k)
+ return MacUtil.isValidPrefix(k) || MacUtil.isValidMac(k)
}
/**
* Returns the address-keyed entry for a MAC, or null. The most specific
- * entry wins: exact device, then 36-bit, 28-bit, 24-bit block.
+ * entry wins: exact device, then the longest prefix.
*/
fun match(mac: String): OuiEntry? {
val table = state.byHex
val hex = MacUtil.hex(mac)
- for (len in intArrayOf(12, 9, 7, 6)) {
+ for (len in 12 downTo 6) {
if (hex.length >= len) table[hex.take(len)]?.let { return it }
}
return null
@@ -213,7 +213,7 @@ object OuiWatchlist {
match(mac)?.let {
out += it.toHit(
if (MacUtil.hex(it.prefix).length == 12) "Exact address $mac is on the watchlist"
- else "Address is in the watchlisted block ${it.prefix}"
+ else "Address starts with the watchlisted prefix ${it.prefix}"
)
}
if (name != null) {
@@ -266,4 +266,10 @@ object OuiWatchlist {
/** The custom (user-added) entry keyed exactly by [prefix], if any. */
fun customEntry(prefix: String): OuiEntry? =
state.all.firstOrNull { it.prefix == normalizeKey(prefix) && it.isCustom }
+
+ /** The user's own entry for this address or the longest of their prefixes it starts with, or null. */
+ fun customAddressEntry(mac: String): OuiEntry? {
+ val hex = MacUtil.hex(mac)
+ return (12 downTo 6).firstNotNullOfOrNull { len -> state.byHex[hex.take(len)]?.takeIf { hex.length >= len && it.isCustom } }
+ }
}
diff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt
index 52319fd..9ee48cd 100644
--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt
@@ -73,7 +73,7 @@ class OuiListActivity : AppCompatActivity() {
val key = ruleType.keyPrefix + text
if (text.isEmpty() || !OuiWatchlist.isValidKey(key)) {
binding.prefixInput.error = when (ruleType) {
- RuleType.ADDRESS -> "Format: AA:BB:CC for a vendor, AA:BB:CC:DD:EE:FF for one device"
+ RuleType.ADDRESS -> "Format: AA:BB:CC up to AA:BB:CC:DD:EE:F for a prefix, AA:BB:CC:DD:EE:FF for one device"
else -> "Enter some text to match"
}
} else if (label.isEmpty()) {
diff --git a/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt b/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
index a36f155..0063890 100644
--- a/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
+++ b/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
@@ -6,14 +6,17 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
+import kotlinx.coroutines.launch
+import com.rfsentinel.app.RFSentinelApp
import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.service.TripRecorder
import com.rfsentinel.app.util.Permissions
import com.rfsentinel.app.util.Prefs
/**
- * Starts scanning when the phone connects to your car (its Bluetooth, chosen in
- * Settings, or Android Auto) and stops it when you leave - but only if it was
- * started this way, so a scan you started yourself is never cut off.
+ * Starts scanning (and, if chosen, a trace) when the phone connects to your car (its
+ * Bluetooth, chosen in Settings, or Android Auto) and stops it when you leave - but only
+ * if it was started this way, so a scan or trace you started yourself is never cut off.
*
* Android lets an app start a foreground service from the background for
* Bluetooth broadcasts that need BLUETOOTH_CONNECT, which is what makes this work.
@@ -23,18 +26,42 @@ object CarAutoStart {
private const val TAG = "CarAutoStart"
fun onCarConnected(context: Context, why: String) {
- if (!Prefs.carAutoStart(context) || ScanForegroundService.isRunning) return
+ val scan = Prefs.carAutoStart(context)
+ val record = Prefs.carAutoRecord(context)
+ if (!scan && !record) return
if (Permissions.missingRequired(context).isNotEmpty()) return
try {
- ScanForegroundService.start(context)
- Prefs.setStartedByCar(context, true)
- Log.i(TAG, "Scanning started: $why")
+ if (!ScanForegroundService.isRunning) {
+ ScanForegroundService.start(context)
+ Prefs.setStartedByCar(context, true)
+ Log.i(TAG, "Scanning started: $why")
+ }
} catch (e: Exception) {
Log.w(TAG, "Could not start scanning ($why)", e)
+ return
+ }
+ if (record && !TripRecorder.isRecording) {
+ val app = context.applicationContext as RFSentinelApp
+ app.appScope.launch {
+ runCatching { TripRecorder.start(app) }.onFailure { Log.w(TAG, "Could not start the trace ($why)", it) }.getOrNull() ?: return@launch
+ Prefs.setRecordingByCar(app, true)
+ Log.i(TAG, "Trace started: $why")
+ refreshLocation(app)
+ }
}
}
fun onCarDisconnected(context: Context, why: String) {
+ if (Prefs.recordingByCar(context)) {
+ Prefs.setRecordingByCar(context, false)
+ // Detached at once, so the scan stopping next can't end it a second time; written in the app's scope.
+ TripRecorder.detach()?.let { trip ->
+ val app = context.applicationContext as RFSentinelApp
+ app.appScope.launch { runCatching { TripRecorder.persist(app, trip) } }
+ Log.i(TAG, "Trace saved: $why")
+ if (!Prefs.startedByCar(context)) refreshLocation(app)
+ }
+ }
if (!Prefs.startedByCar(context)) return
Prefs.setStartedByCar(context, false)
if (ScanForegroundService.isRunning) {
@@ -42,6 +69,13 @@ object CarAutoStart {
Log.i(TAG, "Scanning stopped: $why")
}
}
+
+ /** The running scan switches its GPS rate for the trace starting or ending. */
+ private fun refreshLocation(context: Context) {
+ if (ScanForegroundService.isRunning) runCatching {
+ context.startService(Intent(context, ScanForegroundService::class.java).setAction(ScanForegroundService.ACTION_REFRESH_LOCATION))
+ }
+ }
}
/** Bluetooth connect / disconnect of one of the chosen car devices. */
diff --git a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
index 9dd1fcf..aa24398 100644
--- a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
@@ -34,9 +34,19 @@ class BleScanEngine(
@Volatile private var scanning = false
@Volatile private var filteredScanning = false
+ /** Last result from the unfiltered scan (the filtered one alone keeps alerts going but not the list). */
+ @Volatile var lastUnfilteredAt = 0L
+ private set
+
private val callback = object : ScanCallback() {
- override fun onScanResult(callbackType: Int, result: ScanResult) = onResult(result)
- override fun onBatchScanResults(results: MutableList<ScanResult>) = results.forEach(onResult)
+ override fun onScanResult(callbackType: Int, result: ScanResult) {
+ lastUnfilteredAt = System.currentTimeMillis()
+ onResult(result)
+ }
+ override fun onBatchScanResults(results: MutableList<ScanResult>) {
+ if (results.isNotEmpty()) lastUnfilteredAt = System.currentTimeMillis()
+ results.forEach(onResult)
+ }
override fun onScanFailed(errorCode: Int) {
Log.w(TAG, "Unfiltered BLE scan failed: $errorCode")
scanning = false
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 80b683a..ebd55a3 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -82,6 +82,8 @@ class ScanForegroundService : Service() {
private const val BLE_RESTART_INTERVAL_MS = 25 * 60 * 1000L
/** Watchdog: a scanner silent this long is restarted. */
private const val BLE_SILENCE_MS = 2 * 60_000L
+ /** After the screen comes on, the unfiltered BLE scan should be delivering again within this long. */
+ private const val SCREEN_ON_CHECK_MS = 10_000L
private const val WIFI_SILENCE_MS = 3 * 60_000L
private const val MAX_SILENCE_MS = 16 * 60_000L
@@ -986,6 +988,9 @@ class ScanForegroundService : Service() {
private val bleRate = BleRateWatch()
private var rateTickAt = 0L
private var wasInteractive = false
+ /** When the screen last came on, and whether the unfiltered scan was checked since. */
+ private var screenOnAt = 0L
+ private var screenOnChecked = true
/** Results came back after a restart: the scanner really was stuck, so say so. */
private fun onRecovered(which: String, restartAt: Long, now: Long) {
@@ -1021,14 +1026,26 @@ class ScanForegroundService : Service() {
val count = bleResults.getAndSet(0)
val span = now - rateTickAt
rateTickAt = now
- if (interactive && wasInteractive && adapterOn && Prefs.bleEnabled(this) && bleEngine.isScanning() &&
- bleWatchdogRestartAt != now // already restarted for silence
- ) {
+ val bleRunning = adapterOn && Prefs.bleEnabled(this) && bleEngine.isScanning()
+ var restarted = bleWatchdogRestartAt == now
+ if (interactive && wasInteractive && bleRunning && !restarted) {
if (bleRate.tick(count, span, now)) {
Log.w(TAG, "Watchdog: Bluetooth results down to %.1f/s - restarting the scan".format(count * 1000.0 / span))
android.os.Handler(Looper.getMainLooper()).post { bleEngine.stop(); startBle() }
+ restarted = true
+ }
+ } else if (!bleRunning || restarted) bleRate.reset()
+ // With the screen off the baseline learned with it on is kept, so a scan that doesn't come back is still spotted.
+ if (interactive && !wasInteractive) { screenOnAt = now; screenOnChecked = false }
+ // Screen back on: Android should resume the unfiltered scan by itself, but it can stay paused while the
+ // filtered one keeps running - alerts still come, the list stays empty. Nothing unfiltered since: restart once.
+ if (interactive && !screenOnChecked && now - screenOnAt >= SCREEN_ON_CHECK_MS) {
+ screenOnChecked = true
+ if (bleRunning && !restarted && bleEngine.lastUnfilteredAt < screenOnAt && now - bleStartedAt >= SCREEN_ON_CHECK_MS) {
+ Log.w(TAG, "Watchdog: no unfiltered Bluetooth results since the screen came on - restarting the scan")
+ android.os.Handler(Looper.getMainLooper()).post { bleEngine.stop(); startBle() }
}
- } else bleRate.reset()
+ }
wasInteractive = interactive
val wifiOn = runCatching { (applicationContext.getSystemService(WIFI_SERVICE) as android.net.wifi.WifiManager).isScanAlwaysAvailable ||
(applicationContext.getSystemService(WIFI_SERVICE) as android.net.wifi.WifiManager).isWifiEnabled }.getOrDefault(false)
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 d7d3527..e38a3f1 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -424,11 +424,14 @@ class SettingsActivity : AppCompatActivity() {
"Background scanning: lets the scan keep running with the screen off.\n\n" +
"Remove from the list: how long an ordinary device stays in the list and radar once it stops being heard (default 30 s Bluetooth, 60 s WiFi). Flagged devices follow these too; favourite and following devices stay 3 minutes. " +
"Hide trusted devices: whitelisted devices are left out of the list and radar (they stay in the history). " +
- "Both can go down to 5 s (WiFi only when Developer options are on and the WiFi interval is under 30 s)."),
+ "All can go down to 5 s (WiFi only when \"Wi-Fi scan throttling\" is off in Developer options). " +
+ "External hardware: devices heard only by an ESP32 board or a USB WiFi adapter."),
Section("autostart", binding.headerAutoStart, binding.sectionAutoStart,
"When the phone starts: begins scanning after a reboot.\n\n" +
"In the car: starts scanning when the phone connects to your car's Bluetooth and stops when you leave. " +
- "Android Auto also starts it when RF Sentinel opens on the car screen."),
+ "Android Auto also starts it when RF Sentinel opens on the car screen.\n\n" +
+ "Record a trace in the car: records a GPS trace from the moment the phone connects to your car until you leave, " +
+ "then saves it with your other traces."),
Section("detect", binding.headerDetect, binding.sectionDetect,
"Each type of equipment can be turned on or off. Network / home cameras are off by default (many false alarms).\n\n" +
"GPS / satellite checks cover every system the phone hears: GPS, GLONASS, Galileo, BeiDou, QZSS and NavIC.\n\n" +
@@ -787,6 +790,7 @@ class SettingsActivity : AppCompatActivity() {
withUnit(binding.intervalInput, "s")
info(binding.batteryButton, "Opens Android's battery settings: set RF Sentinel to Unrestricted so scanning keeps going with the screen off.")
info(binding.carAutoSwitch, "Starts scanning when the phone connects to your car's Bluetooth or Android Auto, and stops when you leave.")
+ info(binding.carRecordSwitch, "Records a GPS trace when the phone connects to your car's Bluetooth or Android Auto, and saves it when you leave. Starts scanning too if it isn't running. A trace you started yourself is never stopped.")
info(binding.presetLabel, PRESETS_INFO)
info(binding.thresholdLabel, "Weak: every match, more false alarms.\n\nProbable: recommended.\n\nStrong only: the fewest alerts.")
binding.thresholdMedium.text = tagged("Probable", "recommended")
@@ -1551,16 +1555,18 @@ class SettingsActivity : AppCompatActivity() {
}
private fun addLiveWindowSliders() {
- val texts = mutableListOf<android.widget.TextView>()
- fun slider(label: (Int) -> String, from: Int, to: Int, value: Int, save: (Int) -> Unit): com.google.android.material.slider.Slider {
+ fun slider(
+ label: (Int) -> String, from: Int, to: Int, value: Int,
+ info: String = "How long a device stays in the list and radar after it was last heard. " +
+ "Flagged, favourite and following devices always stay 3 minutes.",
+ save: (Int) -> Unit
+ ): Pair<com.google.android.material.slider.Slider, android.widget.TextView> {
val text = android.widget.TextView(this).apply {
textSize = 14f
setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)
this.text = label(value)
}
- texts += text
- binding.sectionScanning.addView(infoRow(text, "How long a device stays in the list and radar after it was last heard. " +
- "Flagged, favourite and following devices always stay 3 minutes.", "Out of range"))
+ binding.sectionScanning.addView(infoRow(text, info, "Out of range"))
val s = com.google.android.material.slider.Slider(this).apply {
valueFrom = from.toFloat(); valueTo = to.toFloat(); stepSize = 5f
this.value = (value - value % 5).coerceIn(from, to).toFloat()
@@ -1572,32 +1578,35 @@ class SettingsActivity : AppCompatActivity() {
}
}
binding.sectionScanning.addView(s)
- return s
+ return s to text
}
slider({ "Bluetooth: off the list after $it s" }, 5, 180, Prefs.liveBleSec(this)) {
Prefs.setLiveBleSec(this, it)
}
- // Below 30 s only with Developer options on and a WiFi scan interval under 30 s.
- val wifiLabel = { s: Int -> "WiFi: off the list after $s s" }
- val wifiSlider = slider(wifiLabel, Prefs.minLiveWifiSec(this), 180, Prefs.liveWifiSec(this)) {
+ // Below 30 s only with "Wi-Fi scan throttling" off in Developer options (see updateWifiSliderMin).
+ liveWifiSlider = slider(wifiLabel, Prefs.minLiveWifiSec(this), 180, Prefs.liveWifiSec(this)) {
Prefs.setLiveWifiSec(this, it)
}
- // Follow the WiFi interval as it's typed.
- binding.intervalInput.addTextChangedListener(object : android.text.TextWatcher {
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
- override fun afterTextChanged(s: android.text.Editable?) {
- val sec = s?.toString()?.toLongOrNull() ?: return
- val min = Prefs.minLiveWifiSec(this@SettingsActivity, sec.coerceAtLeast(5) * 1000L)
- if (wifiSlider.valueFrom.toInt() == min) return
- if (wifiSlider.value < min) {
- wifiSlider.value = min.toFloat()
- Prefs.setLiveWifiSec(this@SettingsActivity, min)
- texts.last().text = wifiLabel(min)
- }
- wifiSlider.valueFrom = min.toFloat()
- }
- })
+ slider({ "External hardware: off the list after $it s" }, 5, 180, Prefs.liveExternalSec(this),
+ "How long a device heard only by an ESP32 board or a USB WiFi adapter stays in the list and radar after it " +
+ "was last heard. Flagged, favourite and following devices always stay 3 minutes.") {
+ Prefs.setLiveExternalSec(this, it)
+ }
+ }
+
+ private val wifiLabel = { s: Int -> "WiFi: off the list after $s s" }
+ private var liveWifiSlider: Pair<com.google.android.material.slider.Slider, android.widget.TextView>? = null
+
+ /** The WiFi slider goes down to 5 s while scan throttling is off (the user may be back from Developer options). */
+ private fun updateWifiSliderMin() {
+ val (slider, text) = liveWifiSlider ?: return
+ val min = Prefs.minLiveWifiSec(this)
+ if (slider.valueFrom.toInt() == min) return
+ if (slider.value < min) slider.value = min.toFloat()
+ slider.valueFrom = min.toFloat()
+ // Back to the chosen value when throttling goes off again ([Prefs.liveWifiSec] keeps it).
+ slider.value = (Prefs.liveWifiSec(this).let { it - it % 5 }).coerceIn(min, 180).toFloat()
+ text.text = wifiLabel(slider.value.toInt())
}
/** Aircraft search radius (10-50 km) and the feed status, under the aircraft switch. */
@@ -2050,6 +2059,10 @@ class SettingsActivity : AppCompatActivity() {
binding.carAutoSwitch.setOnCheckedChangeListener { _, on ->
if (on && Prefs.carDevices(this).isEmpty()) chooseCarDevices()
}
+ binding.carRecordSwitch.isChecked = Prefs.carAutoRecord(this)
+ binding.carRecordSwitch.setOnCheckedChangeListener { _, on ->
+ if (on && Prefs.carDevices(this).isEmpty()) chooseCarDevices()
+ }
binding.carDevicesButton.setOnClickListener { chooseCarDevices() }
updateCarDevicesText()
binding.batteryButton.setOnClickListener {
@@ -2323,7 +2336,8 @@ class SettingsActivity : AppCompatActivity() {
}
private fun updateWifiThrottleHint() {
- val throttled = wifiScanThrottled()
+ updateWifiSliderMin()
+ val throttled = Prefs.wifiScanThrottled(this)
binding.wifiThrottleText.text = if (throttled)
"Android throttles WiFi scans: under 30 s is wasted unless you turn it off"
else
@@ -2366,13 +2380,6 @@ class SettingsActivity : AppCompatActivity() {
.show()
}
- /** Android's WiFi scan throttle (Developer options), on unless the user disabled it. */
- /** Android 11+ keeps the developer toggle in the WiFi service; older versions in a global setting. */
- private fun wifiScanThrottled(): Boolean =
- if (android.os.Build.VERSION.SDK_INT >= 30)
- runCatching { getSystemService(android.net.wifi.WifiManager::class.java).isScanThrottleEnabled }.getOrDefault(true)
- else runCatching { Settings.Global.getInt(contentResolver, "wifi_scan_throttle_enabled", 1) != 0 }.getOrDefault(true)
-
private fun confirm(title: String, message: String, action: () -> Unit) {
MaterialAlertDialogBuilder(this)
.setTitle(title)
@@ -2411,6 +2418,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setScanIntervalMs(this, intervalSec.coerceAtLeast(5) * 1000L)
Prefs.setAutoStartOnBoot(this, binding.bootSwitch.isChecked)
Prefs.setCarAutoStart(this, binding.carAutoSwitch.isChecked)
+ Prefs.setCarAutoRecord(this, binding.carRecordSwitch.isChecked)
categorySwitches.forEach { (c, sw) -> Prefs.setCategoryEnabled(this, c, sw.isChecked) }
airTagSwitch?.let { Prefs.setExcludeAirTags(this, it.isChecked) }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/ChipStyle.kt b/app/src/main/java/com/rfsentinel/app/ui/ChipStyle.kt
index b35302e..f1c1d56 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/ChipStyle.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/ChipStyle.kt
@@ -24,8 +24,11 @@ object ChipStyle {
fun onSurface(context: Context): Int =
attr(context, com.google.android.material.R.attr.colorOnSurface) ?: attr(context, android.R.attr.textColorPrimary) ?: 0xFF888888.toInt()
- /** [overMap]: unselected chips get a solid background so they read on any map. */
- fun apply(chip: Chip, overMap: Boolean = false) {
+ /**
+ * [overMap]: unselected chips get a solid background so they read on any map. [minTouchTarget]: the invisible
+ * 48 dp touch frame; switching it on and off again on a restyle can leave a chip taller than the others.
+ */
+ fun apply(chip: Chip, overMap: Boolean = false, minTouchTarget: Boolean = true) {
val ctx = chip.context
val (accent, onAccent) = accent(ctx)
val text = onSurface(ctx)
@@ -39,7 +42,7 @@ object ChipStyle {
chip.chipStrokeColor = ColorStateList(arrayOf(checked, none), intArrayOf(accent, (text and 0x00FFFFFF) or 0x66000000))
chip.chipStrokeWidth = 1.5f * ctx.resources.displayMetrics.density
chip.isCheckedIconVisible = false
- chip.setEnsureMinTouchTargetSize(true)
+ if (minTouchTarget) chip.setEnsureMinTouchTargetSize(true)
chip.typeface = android.graphics.Typeface.create(chip.typeface, android.graphics.Typeface.BOLD)
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
index a42a25d..5494fa4 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
@@ -56,7 +56,7 @@ object DeviceActions {
/** Long-press menu. */
fun showQuickActions(activity: AppCompatActivity, mac: String) {
val snap = DeviceRegistry.get(mac)
- val custom = OuiWatchlist.customEntry(mac) ?: OuiWatchlist.customEntry(MacUtil.oui(mac))
+ val custom = OuiWatchlist.customAddressEntry(mac)
val whitelisted = WhitelistCache.inTable(mac)
val ignoredTracker = com.rfsentinel.app.data.TrackerMutes.isMuted(mac)
// Trackers that change their address can't be whitelisted: offer ignoring instead.
@@ -111,11 +111,18 @@ object DeviceActions {
* as every network / device whose name starts the same way (an SSID prefix).
*/
fun addToWatchlist(activity: AppCompatActivity, mac: String, name: String?, wifi: Boolean = false) {
- val oui = MacUtil.oui(mac)
val randomized = MacUtil.isRandomized(mac)
val b = DialogAddWatchlistBinding.inflate(activity.layoutInflater)
b.scopeDevice.text = "Only this device ($mac)"
- b.scopePrefix.text = "Every device with prefix $oui"
+ // The prefix length: the vendor's own IEEE block to start with, longer to narrow it to one batch of devices.
+ var digits = com.rfsentinel.app.detect.VendorDb.blockDigits(mac) ?: 6
+ fun showPrefix() {
+ b.scopePrefix.text = "Every device whose address starts with ${MacUtil.prefix(mac, digits)} (${digits * 4} bits)"
+ }
+ showPrefix()
+ b.prefixBitsSlider.value = digits * 4f
+ b.prefixBitsSlider.setLabelFormatter { "${it.toInt()} bits" }
+ b.prefixBitsSlider.addOnChangeListener { _, v, _ -> digits = v.toInt() / 4; showPrefix() }
if (randomized) {
b.warningText.visibility = View.VISIBLE
b.warningText.text = "This is a randomized (private) address: it may change later, and its prefix " +
@@ -144,13 +151,14 @@ object DeviceActions {
b.scopeStarts.visibility = View.VISIBLE
b.scopeStarts.text = if (wifi) "Every network whose name (SSID) starts with:" else "Every device whose name starts with:"
b.startsInput.setText(named)
- b.scopeGroup.setOnCheckedChangeListener { _, id ->
- b.startsInput.visibility = if (id == b.scopeStarts.id) View.VISIBLE else View.GONE
- if (id == b.scopeStarts.id) b.startsInput.requestFocus()
- }
if (randomized && fp == null) b.warningText.text = "This is a randomized (private) address: it may change later, and its " +
"prefix is not a real vendor, so prefix matching is disabled. Tip: watch the start of its name instead."
}
+ b.scopeGroup.setOnCheckedChangeListener { _, id ->
+ b.prefixBitsSlider.visibility = if (id == b.scopePrefix.id) View.VISIBLE else View.GONE
+ b.startsInput.visibility = if (id == b.scopeStarts.id) View.VISIBLE else View.GONE
+ if (id == b.scopeStarts.id) b.startsInput.requestFocus()
+ }
b.labelInput.setText(name ?: "")
MaterialAlertDialogBuilder(activity)
.setTitle("Add to watchlist")
@@ -165,7 +173,7 @@ object DeviceActions {
val key = when {
byStart -> OuiEntry.STARTS + start
byShape -> OuiEntry.FINGERPRINT + shape; byFingerprint -> OuiEntry.FINGERPRINT + fp
- wholePrefix -> oui; else -> mac
+ wholePrefix -> MacUtil.prefix(mac, digits); else -> mac
}
// The label box holds the device's own full name: for a name prefix, say what is watched instead.
val typed = b.labelInput.text.toString().trim().takeUnless { byStart && it == named }.orEmpty()
@@ -173,7 +181,7 @@ object DeviceActions {
when {
byStart -> (if (wifi) "SSID starts with " else "Name starts with ") + start
byShape -> "Probe shape ${shape!!.removePrefix("shape-")}"; byFingerprint -> "Device type $fp"
- wholePrefix -> "Custom prefix $oui"; else -> "Custom device $mac"
+ wholePrefix -> "Custom prefix $key"; else -> "Custom device $mac"
}
}
OuiWatchlist.addCustomEntry(activity, OuiEntry(key, label, "user-added from live list", "custom"))
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 c446973..7a35809 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -246,7 +246,7 @@ class DeviceDetailActivity : AppCompatActivity() {
// Action labels
val fp = com.rfsentinel.app.usb.ProbeIntel.of(mac)?.fingerprint
- val custom = OuiWatchlist.customEntry(mac) ?: OuiWatchlist.customEntry(MacUtil.oui(mac))
+ val custom = OuiWatchlist.customAddressEntry(mac)
?: fp?.let { OuiWatchlist.customEntry(com.rfsentinel.app.oui.OuiEntry.FINGERPRINT + it) }
binding.actionWatchlist.text = if (custom != null) "Remove from watchlist" else "Add to watchlist"
radioHz?.let { hz ->
@@ -581,7 +581,7 @@ class DeviceDetailActivity : AppCompatActivity() {
// ---- Actions --------------------------------------------------------------
private fun onWatchlistAction() {
- val custom = OuiWatchlist.customEntry(mac) ?: OuiWatchlist.customEntry(MacUtil.oui(mac))
+ val custom = OuiWatchlist.customAddressEntry(mac)
if (custom != null) {
OuiWatchlist.removeCustomEntry(this, custom.prefix)
com.rfsentinel.app.util.Undo.show(this, "Removed ${custom.prefix} from the watchlist") {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
index dcf927d..0fa34ff 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
@@ -1,11 +1,12 @@
package com.rfsentinel.app.ui
import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.esp.HeardBy
import com.rfsentinel.app.service.DeviceRegistry
/**
* How long a device stays in the live list and radar after it was last heard (Settings >
- * Scanning, defaults 30 s Bluetooth / 60 s WiFi), flagged devices included - never shorter
+ * Scanning, defaults 30 s Bluetooth / 60 s WiFi / 60 s external hardware), flagged devices included - never shorter
* than while they still count as in range. Favourite and following devices stay for the
* registry's full 3 minutes.
*/
@@ -30,11 +31,19 @@ object LiveWindow {
fun alerting(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): Boolean =
s.best?.listOnly == false && !com.rfsentinel.app.data.WhitelistCache.contains(s.mac) && inRange(s, now)
- fun keep(s: DeviceRegistry.Snapshot, now: Long, bleMs: Long, wifiMs: Long): Boolean {
+ fun keep(s: DeviceRegistry.Snapshot, now: Long, bleMs: Long, wifiMs: Long, externalMs: Long = wifiMs): Boolean {
if (s.following || s.known?.favorite == true) return true
val wifi = Advert.Source.WIFI in s.sources || s.source == Advert.Source.WIFI
// A flagged device never leaves the list while it still alerts (bubble, banner, beeps).
if (s.best != null && inRange(s, now)) return true
- return now - s.lastSeen <= if (wifi) wifiMs else bleMs
+ val phoneMs = if (wifi) wifiMs else bleMs
+ // Heard by an ESP32 board or a USB adapter: its own time, or the longer one when the phone hears it too.
+ val external = HeardBy.esp.recent(s.mac, now) || HeardBy.usb.recent(s.mac, now)
+ val ms = when {
+ !external -> phoneMs
+ HeardBy.phone.recent(s.mac, now) -> maxOf(phoneMs, externalMs)
+ else -> externalMs
+ }
+ return now - s.lastSeen <= ms
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
index 0b7a2db..42b000b 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
@@ -1464,7 +1464,11 @@ class MapFragment : Fragment() {
r.drawPins(devices.filter { it.lat != null && (it.flagged || filter == DeviceFilter.ALL) }.map { it.toPin() })
}
val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000
- binding.statusText.text = String.format(
+ // A snapshot has no route: where its devices were, and how many.
+ binding.statusText.text = if (t.snapshot) String.format(
+ Locale.US, "%s\n%s · %s (%d flagged) · %d on the map",
+ t.name, dateFmt.format(Date(t.startTime)), devicesLabel(t.deviceCount), t.flaggedCount, devices.count { it.lat != null }
+ ) else String.format(
Locale.US, "%s\n%s · %d:%02d · %s · %s (%d flagged)",
t.name, dateFmt.format(Date(t.startTime)), mins / 60, mins % 60, com.rfsentinel.app.util.Units.trip(t.distanceM),
devicesLabel(t.deviceCount), t.flaggedCount
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt
new file mode 100644
index 0000000..b4c193c
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt
@@ -0,0 +1,181 @@
+package com.rfsentinel.app.ui
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.Menu
+import android.view.MenuItem
+import android.view.View
+import android.view.ViewGroup
+import android.widget.EditText
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.widget.doAfterTextChanged
+import androidx.lifecycle.lifecycleScope
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.chip.Chip
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rfsentinel.app.data.AppDatabase
+import com.rfsentinel.app.data.TripDeviceEntity
+import com.rfsentinel.app.data.TripEntity
+import com.rfsentinel.app.databinding.ActivityLogBinding
+import com.rfsentinel.app.databinding.ItemDetectionBinding
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Tier
+import com.rfsentinel.app.util.Exporter
+import com.rfsentinel.app.util.ProximityUtil
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.launch
+import java.text.DateFormat
+import java.util.Date
+
+/** One saved snapshot ([com.rfsentinel.app.data.Snapshots]): the device list as it was, searchable. */
+class SnapshotActivity : AppCompatActivity() {
+
+ companion object {
+ const val EXTRA_TRIP_ID = "trip_id"
+ }
+
+ private lateinit var binding: ActivityLogBinding
+ private var tripId = 0L
+ private var trip: TripEntity? = null
+ private var devices: List<TripDeviceEntity> = emptyList()
+ private var onlyFlagged = false
+ private val fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
+ private val timeFmt = DateFormat.getTimeInstance(DateFormat.SHORT)
+
+ private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
+ var items: List<TripDeviceEntity> = emptyList()
+
+ override fun getItemCount() = items.size
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
+ object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}
+
+ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
+ val d = items[position]
+ val b = ItemDetectionBinding.bind(holder.itemView)
+ val category = Category.parse(d.category)
+ b.labelText.text = d.label
+ b.labelText.setTextColor(
+ if (category != null) ThemeManager.ink(this@SnapshotActivity, category.colorArgb) else b.macText.currentTextColor
+ )
+ b.macText.text = d.mac + (d.vendor?.let { " · $it" } ?: "")
+ val parts = mutableListOf<String>()
+ category?.let { parts += it.shortTag }
+ if (d.confidence > 0) parts += "${Tier.of(d.confidence).label} ${d.confidence}%"
+ d.name?.takeIf { it != d.label }?.let { parts += it }
+ parts += "${if (d.source == "WIFI") "WiFi" else "Bluetooth"} ${ProximityUtil.band(d.bestRssi)} ${d.bestRssi} dBm"
+ parts += timeFmt.format(Date(d.firstSeen)) + "–" + timeFmt.format(Date(d.lastSeen))
+ b.metaText.text = parts.joinToString(" · ")
+ holder.itemView.setOnClickListener { DeviceActions.openDetails(this@SnapshotActivity, d.mac) }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ tripId = intent.getLongExtra(EXTRA_TRIP_ID, 0L)
+ binding = ActivityLogBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.root.applySystemBarInsets()
+ title = "Snapshot"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding.recyclerView.layoutManager = LinearLayoutManager(this)
+ binding.recyclerView.adapter = adapter
+ binding.searchInput.doAfterTextChanged { show() }
+ onlyFlagged = savedInstanceState?.getBoolean("only_flagged") ?: false
+ fun chip(label: String, flagged: Boolean) = binding.filterChips.addView(
+ Chip(this, null, com.google.android.material.R.attr.chipStyle).apply {
+ id = View.generateViewId(); text = label; isCheckable = true; isCheckedIconVisible = false
+ ChipStyle.apply(this)
+ isChecked = flagged == onlyFlagged
+ setOnClickListener { onlyFlagged = flagged; show() }
+ })
+ chip("All", false)
+ chip("Flagged", true)
+ load()
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putBoolean("only_flagged", onlyFlagged)
+ }
+
+ private fun load() = lifecycleScope.launch {
+ val dao = AppDatabase.getInstance(this@SnapshotActivity).tripDao()
+ val t = dao.get(tripId) ?: run { finish(); return@launch }
+ trip = t
+ devices = dao.devices(tripId)
+ title = t.name
+ show()
+ }
+
+ private fun show() {
+ val t = trip ?: return
+ val q = binding.searchInput.text?.toString()?.trim().orEmpty()
+ val list = devices.filter { d ->
+ (!onlyFlagged || d.flagged) && (q.isEmpty() ||
+ listOfNotNull(d.mac, d.label, d.name, d.vendor, d.deviceType, d.evidence).any { it.contains(q, ignoreCase = true) })
+ }
+ adapter.items = list
+ @Suppress("NotifyDataSetChanged") adapter.notifyDataSetChanged()
+ binding.emptyText.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
+ binding.emptyText.text = if (devices.isEmpty()) "This snapshot has no devices." else "Nothing matches."
+ supportActionBar?.subtitle = fmt.format(Date(t.startTime)) + " · " +
+ (if (list.size != devices.size) "${list.size} of " else "") + devicesLabel(devices.size)
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menu.add(0, 1, 0, "View on map")
+ menu.add(0, 2, 1, "Export...")
+ menu.add(0, 3, 2, "Rename")
+ menu.add(0, 4, 3, "Delete")
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
+ 1 -> { startActivity(Intent(this, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, tripId)); true }
+ 2 -> { Exporter.showTripExport(this, tripId, snapshot = true); true }
+ 3 -> { rename(); true }
+ 4 -> { delete(); true }
+ else -> super.onOptionsItemSelected(item)
+ }
+
+ private fun rename() {
+ val t = trip ?: return
+ val input = EditText(this).apply { setText(t.name); setSelection(text.length) }
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Rename snapshot")
+ .setView(input)
+ .setPositiveButton("Save") { _, _ ->
+ val name = input.text.toString().trim().ifEmpty { "Snapshot" }
+ lifecycleScope.launch {
+ AppDatabase.getInstance(this@SnapshotActivity).tripDao().rename(t.id, name)
+ trip = t.copy(name = name)
+ title = name
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ private fun delete() {
+ val t = trip ?: return
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Delete \"${t.name}\"?")
+ .setMessage("The saved device list is deleted from this phone.")
+ .setPositiveButton("Delete") { _, _ ->
+ lifecycleScope.launch {
+ AppDatabase.getInstance(this@SnapshotActivity).tripDao().delete(t.id)
+ finish()
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ override fun onSupportNavigateUp(): Boolean {
+ finish()
+ return true
+ }
+}
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 b631e6f..132a3b7 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
@@ -7,6 +7,7 @@ import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
+import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
@@ -25,11 +26,28 @@ import java.text.DateFormat
import java.util.Date
import java.util.Locale
-/** Recorded scan traces. Tap to view on the map; long-press to export, rename or delete. */
+/**
+ * Recorded scan traces and saved snapshots (the device list kept as it was, [com.rfsentinel.app.data.Snapshots]),
+ * one section each. Tap a trace to view it on the map, a snapshot to see its list; long-press to export, rename or delete.
+ */
class TripsActivity : AppCompatActivity() {
+ companion object {
+ /** Opens on this section: [TripEntity.KIND_TRACE] or [TripEntity.KIND_SNAPSHOT]. */
+ const val EXTRA_SECTION = "section"
+ }
+
private lateinit var binding: ActivityLogBinding
private val fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
+ private var section = TripEntity.KIND_TRACE
+ private var all: List<TripEntity> = emptyList()
+
+ private fun open(t: TripEntity) {
+ startActivity(
+ if (t.snapshot) Intent(this, SnapshotActivity::class.java).putExtra(SnapshotActivity.EXTRA_TRIP_ID, t.id)
+ else Intent(this, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id)
+ )
+ }
private val adapter = object : ListAdapter<TripEntity, RecyclerView.ViewHolder>(
object : DiffUtil.ItemCallback<TripEntity>() {
@@ -48,9 +66,7 @@ class TripsActivity : AppCompatActivity() {
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.setOnClickListener { open(t) }
holder.itemView.setOnLongClickListener { actions(t); true }
return
}
@@ -58,14 +74,19 @@ class TripsActivity : AppCompatActivity() {
val live = t.id == TripRecorder.activeTripId
b.labelText.text = (if (live) "● " else "") + t.name
b.labelText.setTextColor(if (live) 0xFFB3261E.toInt() else if (t.flaggedCount > 0) 0xFFC8431A.toInt() else b.macText.currentTextColor)
+ if (t.snapshot) {
+ b.macText.text = fmt.format(Date(t.startTime))
+ b.metaText.text = "${devicesLabel(t.deviceCount)} · ${t.flaggedCount} flagged"
+ holder.itemView.setOnClickListener { open(t) }
+ holder.itemView.setOnLongClickListener { actions(t); true }
+ return
+ }
val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000
b.macText.text = fmt.format(Date(t.startTime)) +
String.format(Locale.US, " · %d:%02d · %s", mins / 60, mins % 60, com.rfsentinel.app.util.Units.trip(t.distanceM))
b.metaText.text = (if (live) "Recording now · " else "") +
"${devicesLabel(t.deviceCount)} · ${t.flaggedCount} flagged · ${t.pointCount} GPS points"
- holder.itemView.setOnClickListener {
- startActivity(Intent(this@TripsActivity, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id))
- }
+ holder.itemView.setOnClickListener { open(t) }
holder.itemView.setOnLongClickListener { actions(t); true }
}
}
@@ -75,18 +96,48 @@ class TripsActivity : AppCompatActivity() {
binding = ActivityLogBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.root.applySystemBarInsets()
- title = "Recorded traces"
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
- binding.emptyText.text = "No recorded traces yet.\nOpen the map and tap Record trace."
+ section = savedInstanceState?.getString(EXTRA_SECTION) ?: intent.getStringExtra(EXTRA_SECTION) ?: TripEntity.KIND_TRACE
+ for ((kind, label) in listOf(TripEntity.KIND_TRACE to "Traces", TripEntity.KIND_SNAPSHOT to "Snapshots")) {
+ binding.filterChips.addView(com.google.android.material.chip.Chip(this, null, com.google.android.material.R.attr.chipStyle).apply {
+ id = View.generateViewId(); text = label; isCheckable = true; isCheckedIconVisible = false
+ ChipStyle.apply(this)
+ isChecked = kind == section
+ setOnClickListener { section = kind; show() }
+ })
+ }
+ binding.searchInput.doAfterTextChanged { show() }
lifecycleScope.launch {
AppDatabase.getInstance(this@TripsActivity).tripDao().allFlow().collect { list ->
- adapter.submitList(list)
- binding.emptyText.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
+ all = list
+ show()
}
}
+ show()
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putString(EXTRA_SECTION, section)
+ }
+
+ /** The picked section, narrowed by the search box (name). */
+ private fun show() {
+ val snapshots = section == TripEntity.KIND_SNAPSHOT
+ title = if (snapshots) "Snapshots" else "Recorded traces"
+ val q = binding.searchInput.text?.toString()?.trim().orEmpty()
+ val mine = all.filter { it.snapshot == snapshots }
+ val list = mine.filter { q.isEmpty() || it.name.contains(q, ignoreCase = true) }
+ adapter.submitList(list)
+ binding.emptyText.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
+ binding.emptyText.text = when {
+ mine.isNotEmpty() -> "Nothing matches."
+ snapshots -> "No snapshots yet.\nOn the main screen, open the menu and tap Save snapshot to keep the device list as it is."
+ else -> "No recorded traces yet.\nOpen the map and tap Record trace."
+ }
}
override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
@@ -128,8 +179,16 @@ class TripsActivity : AppCompatActivity() {
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()
+ // A snapshot has no route: just its numbers.
+ route.visibility = if (t.snapshot) View.GONE else View.VISIBLE
+ if (t.snapshot) {
+ stats.addView(VisualMode.chip(context, devicesLabel(t.deviceCount), accent))
+ stats.addView(VisualMode.chip(context, "${t.flaggedCount} flagged", if (t.flaggedCount > 0) 0xFFD0503C.toInt() else accent))
+ boundId = t.id
+ return
+ }
+ val mins = ((t.endTime ?: System.currentTimeMillis()) - t.startTime) / 60000
listOf(com.rfsentinel.app.util.Units.trip(t.distanceM), 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))
@@ -152,6 +211,21 @@ class TripsActivity : AppCompatActivity() {
}
private fun actions(t: TripEntity) {
+ if (t.snapshot) {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(t.name)
+ .setItems(arrayOf("View list", "View on map", "Export (GPX, KML, GeoJSON, CSV)...", "Rename", "Delete")) { _, which ->
+ when (which) {
+ 0 -> open(t)
+ 1 -> startActivity(Intent(this, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id))
+ 2 -> Exporter.showTripExport(this, t.id, snapshot = true)
+ 3 -> rename(t)
+ 4 -> delete(t)
+ }
+ }
+ .show()
+ return
+ }
MaterialAlertDialogBuilder(this)
.setTitle(t.name)
.setItems(arrayOf("View on map", "Export (GPX, KML, GeoJSON, CSV)...", "Rename", "Delete")) { _, which ->
@@ -168,11 +242,11 @@ class TripsActivity : AppCompatActivity() {
private fun rename(t: TripEntity) {
val input = EditText(this).apply { setText(t.name); setSelection(text.length) }
MaterialAlertDialogBuilder(this)
- .setTitle("Rename trace")
+ .setTitle(if (t.snapshot) "Rename snapshot" else "Rename trace")
.setView(input)
.setPositiveButton("Save") { _, _ ->
lifecycleScope.launch {
- AppDatabase.getInstance(this@TripsActivity).tripDao().rename(t.id, input.text.toString().trim().ifEmpty { "Trace" })
+ AppDatabase.getInstance(this@TripsActivity).tripDao().rename(t.id, input.text.toString().trim().ifEmpty { if (t.snapshot) "Snapshot" else "Trace" })
}
}
.setNegativeButton("Cancel", null)
@@ -187,7 +261,7 @@ class TripsActivity : AppCompatActivity() {
}
MaterialAlertDialogBuilder(this)
.setTitle("Delete \"${t.name}\"?")
- .setMessage("The route and its device list are deleted from this phone.")
+ .setMessage(if (t.snapshot) "The saved device list is deleted from this phone." else "The route and its device list are deleted from this phone.")
.setPositiveButton("Delete") { _, _ ->
lifecycleScope.launch { AppDatabase.getInstance(this@TripsActivity).tripDao().delete(t.id) }
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
index caff568..ecb4e06 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
@@ -199,16 +199,17 @@ object Exporter {
}
/** Export one recorded trace: pick a format, then whether to include every device. */
- fun showTripExport(activity: AppCompatActivity, tripId: Long) {
+ /** [snapshot]: a saved device list ([com.rfsentinel.app.data.Snapshots]) - no route, just the devices. */
+ fun showTripExport(activity: AppCompatActivity, tripId: Long, snapshot: Boolean = false) {
val formats = listOf("gpx", "kml", "geojson", "csv")
val labels = arrayOf(
- "GPX - track + device waypoints (GPS / map apps)",
+ if (snapshot) "GPX - device waypoints (GPS / map apps)" else "GPX - track + device waypoints (GPS / map apps)",
"KML - Google Earth / My Maps",
"GeoJSON - web maps, QGIS",
- "CSV - devices heard on this trace (spreadsheet)"
+ if (snapshot) "CSV - devices in this snapshot (spreadsheet)" else "CSV - devices heard on this trace (spreadsheet)"
)
MaterialAlertDialogBuilder(activity)
- .setTitle("Export trace")
+ .setTitle(if (snapshot) "Export snapshot" else "Export trace")
.setItems(labels) { _, which ->
val format = formats[which]
if (format == "csv") {
@@ -216,7 +217,7 @@ object Exporter {
} else {
MaterialAlertDialogBuilder(activity)
.setTitle("Which devices?")
- .setItems(arrayOf("All devices heard on the trace", "Flagged devices only")) { _, w ->
+ .setItems(arrayOf(if (snapshot) "All devices in the snapshot" else "All devices heard on the trace", "Flagged devices only")) { _, w ->
exportTrip(activity, tripId, format, onlyFlagged = w == 1)
}
.show()
@@ -237,7 +238,7 @@ object Exporter {
val points = dao.points(tripId)
val devices = dao.devices(tripId)
if (points.isEmpty() && devices.none { it.lat != null } && format != "csv") {
- toast(activity, "This trace has no GPS points yet")
+ toast(activity, if (trip.snapshot) "No device in this snapshot has a position" else "This trace has no GPS points yet")
return@launchExport
}
val (text, mime, ext) = withContext(Dispatchers.Default) {
diff --git a/app/src/main/java/com/rfsentinel/app/util/MacUtil.kt b/app/src/main/java/com/rfsentinel/app/util/MacUtil.kt
index d010b0c..f64c879 100644
--- a/app/src/main/java/com/rfsentinel/app/util/MacUtil.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/MacUtil.kt
@@ -19,6 +19,18 @@ object MacUtil {
*/
fun isValidBlock(prefix: String): Boolean = BLOCK.matches(normalize(prefix))
+ /**
+ * A watchlist address prefix of any length from 24 to 44 bits (6 to 11 hex digits), e.g. "AA:BB:CC",
+ * "AA:BB:CC:D" or "AA:BB:CC:DD:EE:F": the IEEE block sizes and anything in between.
+ */
+ fun isValidPrefix(prefix: String): Boolean {
+ val h = hex(prefix)
+ return h.length in 6..11 && h.all { it in '0'..'9' || it in 'A'..'F' } && prefix(h, h.length) == normalize(prefix)
+ }
+
+ /** The first [digits] hex digits of an address, written as a prefix: ("8C:1F:64:DF:00:11", 7) -> "8C:1F:64:D". */
+ fun prefix(mac: String, digits: Int): String = hex(mac).take(digits).chunked(2).joinToString(":")
+
/** Hex digits only, e.g. "8C:1F:64:DF:0" -> "8C1F64DF0". */
fun hex(macOrPrefix: String): String = normalize(macOrPrefix).replace(":", "")
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 596a136..fe39e88 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -223,20 +223,23 @@ object Prefs {
fun liveWifiSec(context: Context): Int = int(context, "live_wifi_sec", 60).coerceIn(minLiveWifiSec(context), 180)
/**
- * The WiFi list window can go below 30 s only when Developer options are on and the WiFi
- * scan interval is under 30 s (i.e. scan throttling turned off): otherwise devices would
- * drop out between two scans.
+ * The WiFi list window can go below 30 s only when "Wi-Fi scan throttling" is turned off in
+ * Developer options: otherwise Android scans about every 30 s and devices would drop out between two scans.
*/
- fun minLiveWifiSec(context: Context, intervalMs: Long = scanIntervalMs(context)): Int =
- if (fastWifiScans(context, intervalMs)) 5 else 30
-
- fun fastWifiScans(context: Context, intervalMs: Long = scanIntervalMs(context)): Boolean =
- intervalMs < 30_000L && runCatching {
- android.provider.Settings.Global.getInt(context.contentResolver,
- android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) == 1
- }.getOrDefault(false)
- // Stored as chosen (down to 5 s); [liveWifiSec] raises it to 30 s whenever fast WiFi scans are off.
+ fun minLiveWifiSec(context: Context): Int = minLiveWifiSec(wifiScanThrottled(context))
+ fun minLiveWifiSec(throttled: Boolean): Int = if (throttled) 30 else 5
+
+ /** Android's WiFi scan throttle (Developer options), on unless the user disabled it. */
+ /** Android 11+ keeps the developer toggle in the WiFi service; older versions in a global setting. */
+ fun wifiScanThrottled(context: Context): Boolean =
+ if (android.os.Build.VERSION.SDK_INT >= 30)
+ runCatching { context.getSystemService(android.net.wifi.WifiManager::class.java).isScanThrottleEnabled }.getOrDefault(true)
+ else runCatching { android.provider.Settings.Global.getInt(context.contentResolver, "wifi_scan_throttle_enabled", 1) != 0 }.getOrDefault(true)
+ // Stored as chosen (down to 5 s); [liveWifiSec] raises it to 30 s while WiFi scans are throttled.
fun setLiveWifiSec(context: Context, sec: Int) = setInt(context, "live_wifi_sec", sec.coerceIn(5, 180))
+ /** How long a device heard only by external hardware (ESP32 board, USB WiFi adapter) stays in the list and radar. */
+ fun liveExternalSec(context: Context): Int = int(context, "live_external_sec", 60).coerceIn(5, 180)
+ fun setLiveExternalSec(context: Context, sec: Int) = setInt(context, "live_external_sec", sec.coerceIn(5, 180))
/** Police aircraft from the online ADS-B feeds; off leaves only the RTL-SDR's own receiver (on by default). */
fun aircraftOnline(context: Context): Boolean = bool(context, "aircraft_online", true)
@@ -437,6 +440,12 @@ object Prefs {
/** True while the running scan was started by the car (so leaving the car may stop it). */
fun startedByCar(context: Context): Boolean = bool(context, "started_by_car", false)
fun setStartedByCar(context: Context, value: Boolean) = setBool(context, "started_by_car", value)
+ /** Record a trace while in the car (chosen Bluetooth devices, or Android Auto). */
+ fun carAutoRecord(context: Context): Boolean = bool(context, "car_auto_record", false)
+ fun setCarAutoRecord(context: Context, value: Boolean) = setBool(context, "car_auto_record", value)
+ /** True while the trace being recorded was started by the car (so leaving the car saves it). */
+ fun recordingByCar(context: Context): Boolean = bool(context, "recording_by_car", false)
+ fun setRecordingByCar(context: Context, value: Boolean) = setBool(context, "recording_by_car", value)
/** Floating threat bubble over other apps while scanning. */
/** Floating mini map with the devices around you, drawn over other apps while scanning. */
diff --git a/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt b/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt
index 054b0cc..f6ce533 100644
--- a/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt
@@ -39,7 +39,7 @@ object SettingsBackup {
private val parts = listOf(
Part("rf_sentinel_prefs", Section.SETTINGS, skip = setOf(
// Short-lived state and where you were.
- "alerts_snoozed_until", "tracker_follow_paused_until", "last_update_check", "map_center", "map_zoom", "deflock_updated", "started_by_car",
+ "alerts_snoozed_until", "tracker_follow_paused_until", "last_update_check", "map_center", "map_zoom", "deflock_updated", "started_by_car", "recording_by_car",
// Acknowledgements that must be given again, and folder access that does not carry over.
"waze_accepted", "waze_direct_accepted", "live_export", "live_export_tree")),
Part("nav_places", Section.PLACES, only = setOf("nav_home", "nav_work", "nav_favorites")),
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index e532b33..29cce52 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -174,6 +174,12 @@
android:layout_height="wrap_content"
android:text="In the car" />
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/carRecordSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Record a trace in the car" />
+
<TextView
android:id="@+id/carDevicesText"
style="@style/SettingsLabel"
diff --git a/app/src/main/res/layout/dialog_add_watchlist.xml b/app/src/main/res/layout/dialog_add_watchlist.xml
index 53ce26e..bf32fc0 100644
--- a/app/src/main/res/layout/dialog_add_watchlist.xml
+++ b/app/src/main/res/layout/dialog_add_watchlist.xml
@@ -23,6 +23,18 @@
android:layout_width="match_parent"
android:layout_height="wrap_content" />
+ <!-- Prefix length in bits, one hex digit (4 bits) per step: shown while the prefix is picked. -->
+ <com.google.android.material.slider.Slider
+ android:id="@+id/prefixBitsSlider"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="24dp"
+ android:contentDescription="Prefix length in bits"
+ android:stepSize="4"
+ android:valueFrom="24"
+ android:valueTo="44"
+ android:visibility="gone" />
+
<RadioButton
android:id="@+id/scopeFingerprint"
android:layout_width="wrap_content"
diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xml
index 7c90b4b..d47d0b0 100644
--- a/app/src/main/res/menu/menu_main.xml
+++ b/app/src/main/res/menu/menu_main.xml
@@ -25,10 +25,13 @@
<item android:id="@+id/action_device_history" android:title="Device history" />
<item android:id="@+id/action_match_log" android:title="Match history" />
<item android:id="@+id/action_traces" android:title="Recorded traces" />
+ <item android:id="@+id/action_snapshots" android:title="Snapshots" />
<item android:id="@+id/action_history" android:title="History map &amp; timeline" />
<item android:id="@+id/action_probes" android:title="Requested networks" />
</menu>
</item>
+ <!-- The device list as it is now, kept to look at later (History > Snapshots). -->
+ <item android:id="@+id/action_save_snapshot" android:title="Save snapshot" app:showAsAction="never" />
<item android:id="@+id/action_export" android:title="Export..." app:showAsAction="never" />
</menu>
diff --git a/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt b/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt
index 03472e5..4ec1571 100644
--- a/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/service/AlertRangeTest.kt
@@ -55,15 +55,15 @@ class AlertRangeTest {
}
@Test
- fun wifiListWindowBelow30sIsSavedOnlyUsedWithFastScans() {
+ fun wifiListWindowBelow30sIsSavedOnlyUsedWithoutScanThrottling() {
val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext<Application>()
- android.provider.Settings.Global.putInt(ctx.contentResolver, android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1)
- com.rfsentinel.app.util.Prefs.setScanIntervalMs(ctx, 10_000L)
+ // Throttled, Android scans about every 30 s: the list can't keep WiFi devices for less.
+ org.junit.Assert.assertEquals(30, com.rfsentinel.app.util.Prefs.minLiveWifiSec(throttled = true))
+ org.junit.Assert.assertEquals(5, com.rfsentinel.app.util.Prefs.minLiveWifiSec(throttled = false))
+ // The choice is saved as made and only raised while reading it.
com.rfsentinel.app.util.Prefs.setLiveWifiSec(ctx, 5)
- org.junit.Assert.assertEquals(5, com.rfsentinel.app.util.Prefs.liveWifiSec(ctx))
- // Back to a 30 s interval: the saved 5 s is raised to 30 s.
- com.rfsentinel.app.util.Prefs.setScanIntervalMs(ctx, 30_000L)
- org.junit.Assert.assertEquals(30, com.rfsentinel.app.util.Prefs.liveWifiSec(ctx))
+ val min = com.rfsentinel.app.util.Prefs.minLiveWifiSec(ctx)
+ org.junit.Assert.assertEquals(maxOf(5, min), com.rfsentinel.app.util.Prefs.liveWifiSec(ctx))
}
@Test
diff --git a/app/src/test/java/com/rfsentinel/app/util/MacUtilTest.kt b/app/src/test/java/com/rfsentinel/app/util/MacUtilTest.kt
index 47eede7..fd48801 100644
--- a/app/src/test/java/com/rfsentinel/app/util/MacUtilTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/util/MacUtilTest.kt
@@ -37,6 +37,19 @@ class MacUtilTest {
assertEquals("8C1F64DF0", MacUtil.hex("8c:1f:64:df:0"))
}
+ @Test
+ fun watchlistPrefixesOfAnyLength() {
+ assertTrue(MacUtil.isValidPrefix("00:25:DF")) // 24 bits
+ assertTrue(MacUtil.isValidPrefix("8C:1F:64:DF")) // 32 bits
+ assertTrue(MacUtil.isValidPrefix("8c-1f-64-df-00-1")) // 44 bits, any case/separator
+ assertFalse(MacUtil.isValidPrefix("00:25")) // shorter than a vendor block
+ assertFalse(MacUtil.isValidPrefix("00:25:DF:11:22:33")) // a whole address, not a prefix
+ assertFalse(MacUtil.isValidPrefix("00:25:D:F1")) // badly grouped
+ assertFalse(MacUtil.isValidPrefix("00:25:DG"))
+ assertEquals("8C:1F:64:D", MacUtil.prefix("8C:1F:64:DF:00:11", 7))
+ assertEquals("8C:1F:64:DF:00", MacUtil.prefix("8C:1F:64:DF:00:11", 10))
+ }
+
@Test
fun randomizedAddressDetection() {
assertFalse(MacUtil.isRandomized("00:25:DF:12:34:56")) // Axon, globally unique