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.

Watchlist: custom rules of several conditions, add a device another way, History keeps which radio heard each match

CIS-C00e3e2bd98031
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
index d08f5ad..c4fd6d1 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
@@ -95,15 +95,7 @@ object CarUi {
}
/** Which radio heard it: an ESP32 board, a USB WiFi or Bluetooth adapter, a linked Sentinel, or the phone (Bluetooth / WiFi). */
- fun sourceTag(s: DeviceRegistry.Snapshot): String = when {
- com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac) -> "USB WiFi"
- com.rfsentinel.app.esp.HeardBy.usbBt.recent(s.mac) -> "USB Bluetooth"
- com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) -> "ESP32"
- !com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac) && com.rfsentinel.app.esp.HeardBy.peer.recent(s.mac) ->
- "via " + com.rfsentinel.app.esp.HeardBy.peer.via(s.mac)
- s.source == com.rfsentinel.app.detect.Advert.Source.WIFI -> "WiFi"
- else -> "Bluetooth"
- }
+ fun sourceTag(s: DeviceRegistry.Snapshot): String = com.rfsentinel.app.esp.HeardBy.tag(s.mac, s.source)
/** Which radio heard it first (the line above can be cut off), then signal, distance and age. */
fun signalLine(s: DeviceRegistry.Snapshot, now: Long = System.currentTimeMillis()): String =
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 ae89228..ffb46a1 100644
--- a/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/AppDatabase.kt
@@ -13,7 +13,7 @@ import androidx.sqlite.db.SupportSQLiteDatabase
TripEntity::class, TripPointEntity::class, TripDeviceEntity::class, DeviceDetailsEntity::class,
TripPingEntity::class
],
- version = 9,
+ version = 10,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
@@ -118,13 +118,20 @@ abstract class AppDatabase : RoomDatabase() {
}
}
+ /** v2.34: which radio heard each match (a USB adapter, an ESP32, a linked Sentinel...). */
+ val MIGRATION_9_10 = object : Migration(9, 10) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ db.execSQL("ALTER TABLE detections ADD COLUMN heardBy TEXT")
+ }
+ }
+
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"rfsentinel.db"
- ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9).build().also { INSTANCE = it }
+ ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10).build().also { INSTANCE = it }
}
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/data/DetectionEntity.kt b/app/src/main/java/com/rfsentinel/app/data/DetectionEntity.kt
index f75f335..6bcb6fc 100644
--- a/app/src/main/java/com/rfsentinel/app/data/DetectionEntity.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/DetectionEntity.kt
@@ -23,5 +23,7 @@ data class DetectionEntity(
val vendor: String? = null,
val deviceName: String? = null,
/** The radio side in words ("5 GHz · channel 36 · WPA2"), from v2.30 ([com.rfsentinel.app.detect.DeviceIntel.radioSummary]). */
- val radio: String? = null
+ val radio: String? = null,
+ /** Which radio heard it ("USB WiFi", "ESP32", "Bluetooth", "via Pixel 7"), from v2.34 ([com.rfsentinel.app.esp.HeardBy.tag]). */
+ val heardBy: String? = null
)
diff --git a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
index 8031d19..2f8b8af 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
@@ -67,4 +67,20 @@ object HeardBy {
val phone = RecentMacs()
/** Another Sentinel (Sentinel Link). */
val peer = PeerMacs()
+
+ /** This phone or its own hardware heard [mac] recently. */
+ fun ownRecent(mac: String) = phone.recent(mac) || esp.recent(mac) || usb.recent(mac) || usbBt.recent(mac)
+
+ /** Which of this phone's own radios heard [mac]: a USB adapter, an ESP32 board, or the phone itself. */
+ fun own(mac: String, source: com.rfsentinel.app.detect.Advert.Source): String = when {
+ usb.recent(mac) -> "USB WiFi"
+ usbBt.recent(mac) -> "USB Bluetooth"
+ esp.recent(mac) -> "ESP32"
+ source == com.rfsentinel.app.detect.Advert.Source.WIFI -> "WiFi"
+ else -> "Bluetooth"
+ }
+
+ /** Which radio heard [mac]: one of this phone's own, else the linked Sentinel ("via Pixel 7"). The list, the car and History share it. */
+ fun tag(mac: String, source: com.rfsentinel.app.detect.Advert.Source): String =
+ peer.via(mac)?.takeIf { !ownRecent(mac) }?.let { "via $it" } ?: own(mac, source)
}
diff --git a/app/src/main/java/com/rfsentinel/app/oui/ComboRule.kt b/app/src/main/java/com/rfsentinel/app/oui/ComboRule.kt
new file mode 100644
index 0000000..500033c
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/oui/ComboRule.kt
@@ -0,0 +1,115 @@
+package com.rfsentinel.app.oui
+
+/**
+ * A watchlist rule that matches only when every one of its conditions holds, e.g. a maker with no network name
+ * on 5 GHz. Kept as an [OuiEntry] key, "all:" + the conditions joined by " & ":
+ * - "vendor~text" the manufacturer contains text
+ * - "name^text" the name / SSID starts with text
+ * - "name~text" the name / SSID contains text
+ * - "noname" no name / hidden SSID
+ * - "band=2.4|5|6|bt"
+ * - "probe=key" its probe fingerprint or probe shape ("shape-...") is this
+ * - "type~text" the device type contains text ("Laptop", "WiFi access point")
+ * - "rssi>=-70" heard at least this strong (dBm)
+ */
+data class ComboRule(val conditions: List<Cond>) {
+
+ sealed class Cond {
+ data class Vendor(val text: String) : Cond()
+ data class NameStarts(val text: String) : Cond()
+ data class NameHas(val text: String) : Cond()
+ object NoName : Cond()
+ data class Band(val band: String) : Cond()
+ data class Probe(val key: String) : Cond()
+ data class Type(val text: String) : Cond()
+ data class Rssi(val min: Int) : Cond()
+ }
+
+ /** What is known about one device when it's classified. */
+ data class Facts(
+ val name: String?,
+ val vendors: List<String>,
+ /** "2.4", "5", "6" or "bt". */
+ val band: String?,
+ /** Its probe fingerprint and probe shape key, when a USB adapter / ESP32 heard its probes. */
+ val probeKeys: Set<String>,
+ val type: String?,
+ val rssi: Int
+ )
+
+ fun matches(f: Facts): Boolean = conditions.isNotEmpty() && conditions.all { c ->
+ when (c) {
+ is Cond.Vendor -> f.vendors.any { it.contains(c.text, ignoreCase = true) }
+ is Cond.NameStarts -> f.name?.trimStart()?.startsWith(c.text, ignoreCase = true) == true
+ is Cond.NameHas -> f.name?.contains(c.text, ignoreCase = true) == true
+ Cond.NoName -> f.name.isNullOrBlank()
+ is Cond.Band -> f.band == c.band
+ is Cond.Probe -> c.key in f.probeKeys
+ is Cond.Type -> f.type?.contains(c.text, ignoreCase = true) == true
+ is Cond.Rssi -> f.rssi >= c.min
+ }
+ }
+
+ val key: String get() = PREFIX + conditions.joinToString(SEP) { c ->
+ when (c) {
+ is Cond.Vendor -> "vendor~${c.text}"
+ is Cond.NameStarts -> "name^${c.text}"
+ is Cond.NameHas -> "name~${c.text}"
+ Cond.NoName -> "noname"
+ is Cond.Band -> "band=${c.band}"
+ is Cond.Probe -> "probe=${c.key}"
+ is Cond.Type -> "type~${c.text}"
+ is Cond.Rssi -> "rssi>=${c.min}"
+ }
+ }
+
+ /** In words, for the watchlist and the match's evidence: "Maker contains "Panasonic" · no name · 5 GHz". */
+ fun describe(): String = conditions.joinToString(" · ") { c ->
+ when (c) {
+ is Cond.Vendor -> "maker contains \"${c.text}\""
+ is Cond.NameStarts -> "name starts with \"${c.text}\""
+ is Cond.NameHas -> "name contains \"${c.text}\""
+ Cond.NoName -> "no name"
+ is Cond.Band -> BANDS[c.band] ?: c.band
+ is Cond.Probe -> if (c.key.startsWith("shape-")) "probe shape ${c.key.removePrefix("shape-")}" else "probe fingerprint ${c.key}"
+ is Cond.Type -> "type contains \"${c.text}\""
+ is Cond.Rssi -> "signal ${c.min} dBm or stronger"
+ }
+ }.replaceFirstChar { it.uppercase() }
+
+ companion object {
+ const val PREFIX = "all:"
+ const val SEP = " & "
+ val BANDS = linkedMapOf("2.4" to "2.4 GHz", "5" to "5 GHz", "6" to "6 GHz", "bt" to "Bluetooth")
+
+ /** The band of a WiFi channel ([mhz]) or Bluetooth. */
+ fun band(bluetooth: Boolean, mhz: Int?): String? = when {
+ bluetooth -> "bt"
+ mhz == null || mhz <= 0 -> null
+ mhz < 3000 -> "2.4"
+ mhz < 5925 -> "5"
+ else -> "6"
+ }
+
+ /** The rule in [key], or null when it isn't one or a condition can't be read. */
+ fun parse(key: String): ComboRule? {
+ if (!key.startsWith(PREFIX, ignoreCase = true)) return null
+ val parts = key.substring(PREFIX.length).split("&").map { it.trim() }.filter { it.isNotEmpty() }
+ val conds = parts.map { p ->
+ fun after(op: String) = p.substringAfter(op).trim().takeIf { it.isNotEmpty() }
+ when {
+ p.equals("noname", true) -> Cond.NoName
+ p.startsWith("vendor~", true) -> after("~")?.let { Cond.Vendor(it) }
+ p.startsWith("name^", true) -> after("^")?.let { Cond.NameStarts(it) }
+ p.startsWith("name~", true) -> after("~")?.let { Cond.NameHas(it) }
+ p.startsWith("band=", true) -> after("=")?.lowercase()?.takeIf { it in BANDS }?.let { Cond.Band(it) }
+ p.startsWith("probe=", true) -> after("=")?.lowercase()?.let { Cond.Probe(it) }
+ p.startsWith("type~", true) -> after("~")?.let { Cond.Type(it) }
+ p.startsWith("rssi>=", true) -> after(">=")?.toIntOrNull()?.takeIf { it in -120..0 }?.let { Cond.Rssi(it) }
+ else -> null
+ } ?: return null
+ }
+ return if (conds.isEmpty()) null else ComboRule(conds)
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt
index f1b379d..12cf272 100644
--- a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt
+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt
@@ -18,6 +18,7 @@ data class OuiEntry(
* - "fp:<8 hex>" a device whose probe requests have this fingerprint (same model / OS)
* - "adv:<8 hex>" a Bluetooth device whose adverts have this pattern ([com.rfsentinel.app.detect.AdvertFingerprint.key]),
* whatever its address
+ * - "all:<conditions>" every one of several conditions at once ([ComboRule])
*/
val prefix: String,
val label: String,
@@ -42,6 +43,7 @@ data class OuiEntry(
val isProbeRule get() = prefix.startsWith(PROBE, ignoreCase = true)
val isFingerprintRule get() = prefix.startsWith(FINGERPRINT, ignoreCase = true)
val isAdvertRule get() = prefix.startsWith(ADVERT, ignoreCase = true)
+ val isComboRule get() = prefix.startsWith(ComboRule.PREFIX, ignoreCase = true)
val ruleText get() = prefix.substringAfter(':').trim()
val effectiveScore: Int
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 e5f260f..cc01e89 100644
--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
@@ -41,6 +41,8 @@ object OuiWatchlist {
val fingerprintRules: Map<String, OuiEntry>,
/** Bluetooth advert-pattern rules keyed by [com.rfsentinel.app.detect.AdvertFingerprint.key]. */
val advertRules: Map<String, OuiEntry>,
+ /** Rules of several conditions at once ([ComboRule]). */
+ val comboRules: List<Pair<ComboRule, OuiEntry>>,
val all: List<OuiEntry>
)
@@ -58,7 +60,7 @@ object OuiWatchlist {
private set
@Volatile
- private var state = State(emptyMap(), emptyList(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyMap(), emptyList())
+ private var state = State(emptyMap(), emptyList(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyMap(), emptyList(), emptyList())
/** Load order: regional presets after "global", so their labels win for shared prefixes. */
val availablePresets = listOf("global", "canada", "us", "france", "uk", "portugal", "germany", "spain", "italy")
@@ -77,7 +79,7 @@ object OuiWatchlist {
readCustom(context).forEach { byKey[it.prefix] = it }
val all = byKey.values.toList()
state = State(
- byHex = all.filter { !it.isNameRule && !it.isStartsRule && !it.isVendorRule && !it.isProbeRule && !it.isFingerprintRule && !it.isAdvertRule }
+ byHex = all.filter { !it.isNameRule && !it.isStartsRule && !it.isVendorRule && !it.isProbeRule && !it.isFingerprintRule && !it.isAdvertRule && !it.isComboRule }
.associateBy { MacUtil.hex(it.prefix) },
nameRules = all.filter { it.isNameRule && it.ruleText.isNotEmpty() },
startsRules = all.filter { it.isStartsRule && it.ruleText.isNotEmpty() },
@@ -85,6 +87,7 @@ object OuiWatchlist {
probeRules = all.filter { it.isProbeRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },
fingerprintRules = all.filter { it.isFingerprintRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },
advertRules = all.filter { it.isAdvertRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },
+ comboRules = all.mapNotNull { e -> if (e.isComboRule) ComboRule.parse(e.prefix)?.let { it to e } else null },
all = all
)
version++
@@ -122,6 +125,7 @@ object OuiWatchlist {
k.startsWith(OuiEntry.PROBE, ignoreCase = true) -> OuiEntry.PROBE + k.substringAfter(':').trim()
k.startsWith(OuiEntry.FINGERPRINT, ignoreCase = true) -> OuiEntry.FINGERPRINT + k.substringAfter(':').trim().lowercase()
k.startsWith(OuiEntry.ADVERT, ignoreCase = true) -> OuiEntry.ADVERT + k.substringAfter(':').trim().lowercase()
+ k.startsWith(ComboRule.PREFIX, ignoreCase = true) -> ComboRule.parse(k)?.key ?: k
else -> MacUtil.normalize(k)
}
}
@@ -187,6 +191,7 @@ object OuiWatchlist {
/** 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(ComboRule.PREFIX, true)) return ComboRule.parse(k) != null
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()
@@ -250,6 +255,10 @@ object OuiWatchlist {
fun isAdvertWatched(key: String): Boolean = key.lowercase() in state.advertRules
+ /** Hits for your rules of several conditions ([ComboRule]) that all hold for a device. */
+ fun comboHits(f: ComboRule.Facts): List<Hit> =
+ state.comboRules.filter { it.first.matches(f) }.map { (rule, e) -> e.toHit("Matches every condition: ${rule.describe()}") }
+
/** Watchlist name / maker rules against what a device's WPS block names. */
fun wpsHits(wps: com.rfsentinel.app.usb.ProbeIntel.Wps?): List<Hit> =
if (wps == null) emptyList() else hits("", wps.text.ifEmpty { null }, listOfNotNull(wps.manufacturer))
diff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt
index 53fee6e..6e4eace 100644
--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt
@@ -39,6 +39,7 @@ class OuiAdapter(
item.isProbeRule -> "Asks for network \"${item.ruleText}\""
item.isFingerprintRule -> "Probe fingerprint ${item.ruleText}"
item.isAdvertRule -> "Bluetooth advert pattern ${item.ruleText}"
+ item.isComboRule -> com.rfsentinel.app.oui.ComboRule.parse(item.prefix)?.describe() ?: item.prefix
else -> item.prefix
}
holder.binding.labelText.text = item.label
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 db1abaf..58b5d58 100644
--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt
@@ -94,6 +94,8 @@ class OuiListActivity : AppCompatActivity() {
}
}
+ binding.comboButton.setOnClickListener { com.rfsentinel.app.ui.ComboRuleDialog.show(this) { refresh() } }
+
refresh()
}
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 d08e5c3..389a825 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -775,7 +775,7 @@ class ScanForegroundService : Service() {
if (WhitelistCache.contains(mac)) return
if (!com.rfsentinel.app.detect.FixedRouter.quiet(mac, c.hits, Prefs.alertThreshold(this, best.category))) noteLocating(mac)
- maybeLog(a, best, c.vendor, loc, now)
+ maybeLog(a, best, c.vendor, loc, now, via)
maybeAlert(a, best, c.hits, now, via)
// Following is about this phone: a device near another Sentinel isn't following it.
if (via != null) return
@@ -1057,6 +1057,10 @@ class ScanForegroundService : Service() {
val raw = if (ignored) emptyList() else SignatureEngine.classify(a) +
OuiWatchlist.hits(a.mac, a.name, listOfNotNull(macVendor) + companyVendors) +
OuiWatchlist.advertHits(a) +
+ OuiWatchlist.comboHits(com.rfsentinel.app.oui.ComboRule.Facts(a.name, listOfNotNull(macVendor) + companyVendors,
+ com.rfsentinel.app.oui.ComboRule.band(a.isBle, a.wifi?.frequencyMhz),
+ com.rfsentinel.app.usb.ProbeIntel.of(a.mac)?.let { p -> setOfNotNull(p.fingerprint, p.skeleton?.let { com.rfsentinel.app.usb.ProbeIntel.shapeKey(it) }) }.orEmpty(),
+ identity.type, a.rssi)) +
DeviceRegistry.inheritedHits(a.mac) +
listOfNotNull(DeviceRegistry.clusterHit(a.mac, now), com.rfsentinel.app.sdr.P25Link.hitFor(a.mac)) +
espHits[a.mac]?.takeIf { now - it.first < ESP_HIT_TTL_MS }?.second.orEmpty() +
@@ -1076,7 +1080,8 @@ class ScanForegroundService : Service() {
return Classified(now, hits, named, vendor)
}
- private fun maybeLog(a: Advert, best: Hit, vendor: String?, loc: Location?, now: Long) {
+ private fun maybeLog(a: Advert, best: Hit, vendor: String?, loc: Location?, now: Long, via: String? = null) {
+ if (via != null && !Prefs.saveLinked(this)) return
val prevLogged = lastLogged[a.mac] ?: 0L
if (now - prevLogged < LOG_THROTTLE_MS) return
lastLogged[a.mac] = now
@@ -1096,7 +1101,8 @@ class ScanForegroundService : Service() {
evidence = best.evidence,
vendor = vendor,
deviceName = a.name,
- radio = com.rfsentinel.app.detect.DeviceIntel.radioSummary(a)
+ radio = com.rfsentinel.app.detect.DeviceIntel.radioSummary(a),
+ heardBy = via?.let { "via $it" } ?: com.rfsentinel.app.esp.HeardBy.own(a.mac, a.source)
)
)
}
@@ -1219,7 +1225,11 @@ class ScanForegroundService : Service() {
lastHistoryFlush = now
// Forget long-unsaved devices (rotating addresses): one heard again is just saved again.
detailsSaved.values.removeIf { now - it.first > 2 * DETAILS_SAVE_MS }
- val seen = DeviceRegistry.summaries(since)
+ // Settings › Sentinel Link: devices only a linked Sentinel heard are saved only when that's on.
+ val saveLinked = Prefs.saveLinked(this)
+ val seen = DeviceRegistry.summaries(since).filter {
+ saveLinked || !com.rfsentinel.app.esp.HeardBy.peer.recent(it.mac) || com.rfsentinel.app.esp.HeardBy.ownRecent(it.mac)
+ }
if (seen.isEmpty()) return null
// A page is saved when first heard, when its matches change, and otherwise every few minutes.
val details = seen.mapNotNull { sum ->
@@ -1523,20 +1533,22 @@ class ScanForegroundService : Service() {
e.tdma -> "TETRA radio nearby"
else -> "Radio transmitting nearby"
} + (via?.let { ", via $it" } ?: "")
- radioDetection(hit, "RADIO " + e.mhz + " MHz", e.snrDb, detail, now, "radio:" + e.freqHz, spoken, e.confidence >= threshold)
+ radioDetection(hit, "RADIO " + e.mhz + " MHz", e.snrDb, detail, now, "radio:" + e.freqHz, spoken, e.confidence >= threshold, via)
}
/** A radio [hit] into the detection history (tagged with where you are), and alerted when [alert]. */
- private fun radioDetection(hit: Hit, mac: String, rssi: Int, evidence: String, now: Long, key: String, spoken: String, alert: Boolean) {
+ private fun radioDetection(hit: Hit, mac: String, rssi: Int, evidence: String, now: Long, key: String, spoken: String, alert: Boolean,
+ via: String? = null) {
val loc = lastLocation
val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
+ if (via == null || Prefs.saveLinked(this)) serviceScope.launch {
AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
DetectionEntity(
mac = mac, label = hit.label, source = "SDR", rssi = rssi,
timestamp = now,
latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = hit.category.name, confidence = hit.confidence, evidence = evidence
+ category = hit.category.name, confidence = hit.confidence, evidence = evidence,
+ heardBy = via?.let { "via $it" }
)
)
}
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 69b3617..c0c0348 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -1068,6 +1068,9 @@ class SettingsActivity : AppCompatActivity() {
"a Bluetooth dongle, or a combo adapter with WiFi and Bluetooth (MT7921AU, Realtek). It only listens for " +
"advertisements, never connects. On a combo adapter WiFi and Bluetooth share the antennas. Off: only the phone's " +
"Bluetooth scans.")
+ info(binding.linkSaveSwitch, "On: what a linked Sentinel hears is saved in this phone's History too, where that " +
+ "Sentinel was, tagged \"via\" and its name. Off: it still shows live here, but only the Sentinel that heard it keeps it. " +
+ "Either way each phone keeps its own History: nothing is merged later.")
info(binding.rtl5gSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS. Experimental.")
info(binding.usbLightSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS: the light blinks with received traffic.")
info(binding.traceEveryPingSwitch, "A trace normally places each device once, where its signal was strongest. On: it also " +
@@ -2717,6 +2720,8 @@ class SettingsActivity : AppCompatActivity() {
binding.ouiSpyButton.setOnClickListener { pairOuiSpy() }
binding.ouiSpyEnginesButton.setOnClickListener { chooseOuiSpyEngines() }
binding.linkButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ui.SentinelLinkActivity::class.java)) }
+ binding.linkSaveSwitch.isChecked = Prefs.saveLinked(this)
+ binding.linkSaveSwitch.setOnCheckedChangeListener { _, on -> Prefs.setSaveLinked(this, on) }
binding.usbWifiLogButton.setOnClickListener { exportUsbWifiLog() }
// FOSS build: an adapter waiting for its chip firmware asks to download it.
binding.usbWifiText.setOnClickListener { com.rfsentinel.app.usb.FirmwarePrompt.show(this) { updateEspStatus() } }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/ComboRuleDialog.kt b/app/src/main/java/com/rfsentinel/app/ui/ComboRuleDialog.kt
new file mode 100644
index 0000000..bc445c5
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/ComboRuleDialog.kt
@@ -0,0 +1,116 @@
+package com.rfsentinel.app.ui
+
+import android.text.InputType
+import android.view.View
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.RadioButton
+import android.widget.RadioGroup
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rfsentinel.app.oui.ComboRule
+import com.rfsentinel.app.oui.OuiEntry
+import com.rfsentinel.app.oui.OuiWatchlist
+
+/** Watchlist & rules › Custom rule, and the device page's "Custom rule from this device": several conditions that must all hold. */
+object ComboRuleDialog {
+
+ /** [from]: a device's own values, filled in (the usual ones ticked); null starts empty. */
+ fun show(activity: AppCompatActivity, from: ComboRule.Facts? = null, label: String? = null, done: () -> Unit = {}) {
+ val d = activity.resources.displayMetrics.density
+ val pad = (20 * d).toInt()
+ val box = LinearLayout(activity).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad, (8 * d).toInt(), pad, 0)
+ }
+ box.addView(TextView(activity).apply { text = "Tick the conditions. A device matches only when every ticked one holds." })
+ val name = EditText(activity).apply {
+ hint = "Label: what it is"; setSingleLine(true); setText(label.orEmpty())
+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO
+ }
+ box.addView(name)
+
+ /** A condition with a text box, shown while it is ticked. */
+ fun text(title: String, hint: String, value: String?, ticked: Boolean, number: Boolean = false): Pair<CheckBox, EditText> {
+ val input = EditText(activity).apply {
+ this.hint = hint; setSingleLine(true); setText(value.orEmpty())
+ inputType = if (number) InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED
+ else InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
+ importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO
+ visibility = if (ticked) View.VISIBLE else View.GONE
+ }
+ val check = CheckBox(activity).apply {
+ text = title; isChecked = ticked
+ setOnCheckedChangeListener { _, on -> input.visibility = if (on) View.VISIBLE else View.GONE }
+ }
+ box.addView(check); box.addView(input)
+ return check to input
+ }
+ val unnamed = from != null && from.name.isNullOrBlank()
+ val vendor = text("Maker contains", "e.g. Panasonic", from?.vendors?.firstOrNull(), from?.vendors?.isNotEmpty() == true)
+ val starts = text("Name starts with", "Start of the name or SSID, e.g. Flock-", from?.name?.trim(), from != null && !unnamed)
+ val has = text("Name contains", "Text in the name or SSID", null, false)
+ val noName = CheckBox(activity).apply { text = "No name or hidden network"; isChecked = unnamed }.also { box.addView(it) }
+ val bands = ComboRule.BANDS.entries.toList()
+ val bandGroup = RadioGroup(activity).apply { orientation = RadioGroup.HORIZONTAL }
+ val bandButtons = bands.map { (key, words) ->
+ RadioButton(activity).apply { text = words; id = View.generateViewId(); isChecked = key == (from?.band ?: "2.4") }
+ .also { bandGroup.addView(it) }
+ }
+ // Scrolls sideways on a narrow screen instead of cutting a band off.
+ val bandRow = android.widget.HorizontalScrollView(activity).apply { addView(bandGroup) }
+ val band = CheckBox(activity).apply {
+ text = "Band"; isChecked = from?.band != null
+ setOnCheckedChangeListener { _, on -> bandRow.visibility = if (on) View.VISIBLE else View.GONE }
+ }
+ bandRow.visibility = if (band.isChecked) View.VISIBLE else View.GONE
+ box.addView(band); box.addView(bandRow)
+ val shape = from?.probeKeys?.firstOrNull { it.startsWith("shape-") }
+ val probe = shape?.let { s ->
+ CheckBox(activity).apply { text = "Probe shape ${s.removePrefix("shape-")}"; isChecked = false }.also { box.addView(it) }
+ }
+ val type = text("Device type contains", "e.g. Laptop", from?.type, from?.type != null)
+ val rssi = text("Signal at least, dBm", "e.g. -70", from?.rssi?.let { (it / 5 * 5).toString() }, false, number = true)
+
+ MaterialAlertDialogBuilder(activity)
+ .setTitle("Custom rule")
+ .setView(ScrollView(activity).apply { addView(box) })
+ .setPositiveButton("Add") { _, _ ->
+ fun value(p: Pair<CheckBox, EditText>) = p.second.text.toString().trim().takeIf { p.first.isChecked }
+ val conds = mutableListOf<ComboRule.Cond>()
+ val texts = listOfNotNull(value(vendor), value(starts), value(has), value(type))
+ if (texts.any { it.isEmpty() || '&' in it }) {
+ toast(activity, "Not added: fill in every ticked condition (no & in the text)"); return@setPositiveButton
+ }
+ value(vendor)?.let { conds += ComboRule.Cond.Vendor(it) }
+ value(starts)?.let { conds += ComboRule.Cond.NameStarts(it) }
+ value(has)?.let { conds += ComboRule.Cond.NameHas(it) }
+ if (noName.isChecked) conds += ComboRule.Cond.NoName
+ if (band.isChecked) conds += ComboRule.Cond.Band(bands[bandButtons.indexOfFirst { it.isChecked }.coerceAtLeast(0)].key)
+ if (probe?.isChecked == true) conds += ComboRule.Cond.Probe(shape)
+ value(type)?.let { conds += ComboRule.Cond.Type(it) }
+ value(rssi)?.let { v ->
+ val dbm = v.toIntOrNull()?.let { if (it > 0) -it else it }?.takeIf { it in -120..0 }
+ ?: run { toast(activity, "Not added: the signal is a number of dBm, e.g. -70"); return@setPositiveButton }
+ conds += ComboRule.Cond.Rssi(dbm)
+ }
+ if (conds.isEmpty()) { toast(activity, "Not added: tick at least one condition"); return@setPositiveButton }
+ val rule = ComboRule(conds)
+ if (OuiWatchlist.customEntry(rule.key) != null) { toast(activity, "Already on your watchlist"); return@setPositiveButton }
+ val entry = OuiEntry(rule.key, name.text.toString().trim().ifEmpty { rule.describe() }, "user-added custom rule", "custom")
+ OuiWatchlist.addCustomEntry(activity, entry)
+ done()
+ com.rfsentinel.app.util.Undo.show(activity, "Watching ${entry.label}") {
+ OuiWatchlist.removeCustomEntry(activity, entry.prefix); done()
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ private fun toast(activity: AppCompatActivity, msg: String) = Toast.makeText(activity, msg, Toast.LENGTH_LONG).show()
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
index 1bc4883..2398546 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
@@ -60,7 +60,7 @@ class DetectionAdapter(
val parts = mutableListOf<String>()
category?.let { parts += it.shortTag }
if (item.confidence > 0) parts += "${Tier.of(item.confidence).label} ${item.confidence}%"
- parts += "${item.source} ${ProximityUtil.band(item.rssi)} ${item.rssi} dBm"
+ parts += "${item.heardBy ?: item.source} ${ProximityUtil.band(item.rssi)} ${item.rssi} dBm"
item.radio?.let { parts += it }
parts += fmt.format(Date(item.timestamp))
if (item.latitude != null) parts += String.format(Locale.US, "📍 %.4f, %.4f", item.latitude, item.longitude)
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 3b36a35..78dd146 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
@@ -54,22 +54,48 @@ object DeviceActions {
}
/**
- * Your own watchlist entry this device is on: its address, else its WPS UUID, probe fingerprint or probe shape.
- * The device page's button label, its click and the long-press menu all use this, so they agree.
+ * Your own watchlist entries this device is on: its address, its WPS UUID, probe fingerprint or probe shape,
+ * and a name-start rule its [name] matches. The device page's button, its click and the long-press menu all
+ * use this, so they agree.
*/
- fun watchEntry(mac: String): OuiEntry? {
+ fun watchEntries(mac: String, name: String?): List<OuiEntry> {
val probe = com.rfsentinel.app.usb.ProbeIntel.of(mac)
- return OuiWatchlist.customAddressEntry(mac) ?: listOfNotNull(
+ val named = name?.trimStart().orEmpty()
+ return listOfNotNull(OuiWatchlist.customAddressEntry(mac)) + listOfNotNull(
probe?.wps?.uuid?.let { com.rfsentinel.app.usb.ProbeIntel.uuidKey(it) },
probe?.fingerprint,
probe?.skeleton?.let { com.rfsentinel.app.usb.ProbeIntel.shapeKey(it) }
- ).firstNotNullOfOrNull { OuiWatchlist.customEntry(OuiEntry.FINGERPRINT + it) }
+ ).mapNotNull { OuiWatchlist.customEntry(OuiEntry.FINGERPRINT + it) } +
+ if (named.isEmpty()) emptyList() else OuiWatchlist.allEntries().filter {
+ it.isCustom && it.isStartsRule && named.startsWith(it.ruleText, ignoreCase = true)
+ }
+ }
+
+ /** Takes [entry] off the watchlist, with Undo. */
+ fun removeWatch(activity: AppCompatActivity, entry: OuiEntry) {
+ OuiWatchlist.removeCustomEntry(activity, entry.prefix)
+ com.rfsentinel.app.util.Undo.show(activity, "Removed ${entry.prefix} from the watchlist") {
+ OuiWatchlist.addCustomEntry(activity, entry)
+ }
+ }
+
+ /** A device already on the watchlist: take it off one of the ways it is on, or add another way. */
+ fun watchlistMenu(activity: AppCompatActivity, mac: String, name: String?, wifi: Boolean, done: () -> Unit = {}) {
+ val entries = watchEntries(mac, name)
+ if (entries.isEmpty()) { addToWatchlist(activity, mac, name, wifi); return }
+ val items = entries.map { "Remove: ${it.label} (${it.prefix})" } + "Add another way..."
+ MaterialAlertDialogBuilder(activity)
+ .setTitle("Watchlist")
+ .setItems(items.toTypedArray()) { _, which ->
+ if (which < entries.size) { removeWatch(activity, entries[which]); done() } else addToWatchlist(activity, mac, name, wifi)
+ }
+ .show()
}
/** Long-press menu. */
fun showQuickActions(activity: AppCompatActivity, mac: String) {
val snap = DeviceRegistry.get(mac)
- val custom = watchEntry(mac)
+ val watched = watchEntries(mac, snap?.name)
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.
@@ -78,15 +104,9 @@ object DeviceActions {
val favorite = Favorites.contains(mac)
val items = mutableListOf<Pair<String, () -> Unit>>()
items += "Show details" to { openDetails(activity, mac) }
- if (custom != null) {
- items += "Remove from watchlist (${custom.prefix})" to {
- OuiWatchlist.removeCustomEntry(activity, custom.prefix)
- com.rfsentinel.app.util.Undo.show(activity, "Removed from watchlist") {
- OuiWatchlist.addCustomEntry(activity, custom)
- }
- }
- } else {
- items += "Add to watchlist..." to { addToWatchlist(activity, mac, snap?.name, snap?.advert?.isWifi == true) }
+ watched.forEach { e -> items += "Remove from watchlist (${e.prefix})" to { removeWatch(activity, e) } }
+ items += (if (watched.isEmpty()) "Add to watchlist..." else "Add to watchlist another way...") to {
+ addToWatchlist(activity, mac, snap?.name, snap?.advert?.isWifi == true)
}
val trustedName = !whitelisted && TrustedNetworks.contains(mac)
when {
@@ -222,6 +242,15 @@ object DeviceActions {
b.startsInput.visibility = if (id == b.scopeStarts.id) View.VISIBLE else View.GONE
if (id == b.scopeStarts.id) b.startsInput.requestFocus()
}
+ // Ways it is already watched can't be added twice: greyed out, and the first free way is picked.
+ listOfNotNull(b.scopeDevice to mac, uuid?.let { b.scopeUuid to OuiEntry.FINGERPRINT + it },
+ shape?.let { b.scopeShape to OuiEntry.FINGERPRINT + it }, fp?.let { b.scopeFingerprint to OuiEntry.FINGERPRINT + it })
+ .filter { (_, key) -> OuiWatchlist.customEntry(key) != null }
+ .forEach { (button, _) -> button.isEnabled = false; button.isChecked = false; button.text = "${button.text}\nAlready on your watchlist" }
+ if (b.scopeGroup.checkedRadioButtonId == View.NO_ID) {
+ listOf(b.scopeUuid, b.scopeFingerprint, b.scopeShape, b.scopeStarts, b.scopePrefix)
+ .firstOrNull { it.isEnabled && it.visibility == View.VISIBLE }?.let { b.scopeGroup.check(it.id) }
+ }
b.labelInput.setText(name ?: "")
MaterialAlertDialogBuilder(activity)
.setTitle("Add to watchlist")
@@ -240,6 +269,9 @@ object DeviceActions {
byShape -> OuiEntry.FINGERPRINT + shape; byFingerprint -> OuiEntry.FINGERPRINT + fp
wholePrefix -> MacUtil.prefix(mac, digits); else -> mac
}
+ if (b.scopeGroup.checkedRadioButtonId == View.NO_ID || OuiWatchlist.customEntry(key) != null) {
+ toast(activity, "Already on your watchlist: $key"); return@setPositiveButton
+ }
// 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()
val label = typed.ifEmpty {
@@ -254,9 +286,19 @@ object DeviceActions {
toast(activity, "Added $key to the watchlist")
}
.setNegativeButton("Cancel", null)
+ .setNeutralButton("Custom rule...") { _, _ -> ComboRuleDialog.show(activity, facts(mac), name) }
.show()
}
+ /** This device's values for a custom rule ([ComboRuleDialog]). */
+ private fun facts(mac: String): com.rfsentinel.app.oui.ComboRule.Facts? {
+ val s = DeviceRegistry.get(mac) ?: return null
+ val probe = com.rfsentinel.app.usb.ProbeIntel.of(mac)
+ return com.rfsentinel.app.oui.ComboRule.Facts(s.name, listOfNotNull(s.vendor),
+ com.rfsentinel.app.oui.ComboRule.band(s.source == com.rfsentinel.app.detect.Advert.Source.BLE, s.advert?.wifi?.frequencyMhz),
+ setOfNotNull(probe?.fingerprint, probe?.skeleton?.let { com.rfsentinel.app.usb.ProbeIntel.shapeKey(it) }), s.deviceType, s.rssi)
+ }
+
/**
* "I saw it": the user confirmed what this device is (a camera on a pole, a patrol car...), so RF
* Sentinel learns every stable thing that identifies it, to know it again next time, even under a new
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 79bc357..a34b37b 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -255,8 +255,8 @@ class DeviceDetailActivity : AppCompatActivity() {
}
// Action labels
- val custom = DeviceActions.watchEntry(mac)
- binding.actionWatchlist.text = if (custom != null) "Remove from watchlist" else "Add to watchlist"
+ val watched = DeviceActions.watchEntries(mac, s?.name ?: known?.name).isNotEmpty()
+ binding.actionWatchlist.text = if (watched) "Watchlist..." else "Add to watchlist"
radioHz?.let { hz ->
// A radio transmission (RTL-SDR / HackRF): found with the waterfall, watched as a frequency.
binding.locateButton.isEnabled = true // without an SDR it says what it needs
@@ -476,16 +476,8 @@ class DeviceDetailActivity : AppCompatActivity() {
// ---- Actions --------------------------------------------------------------
private fun onWatchlistAction() {
- val custom = DeviceActions.watchEntry(mac)
- if (custom != null) {
- OuiWatchlist.removeCustomEntry(this, custom.prefix)
- com.rfsentinel.app.util.Undo.show(this, "Removed ${custom.prefix} from the watchlist") {
- OuiWatchlist.addCustomEntry(this, custom)
- }
- } else {
- DeviceActions.addToWatchlist(this, mac, DeviceRegistry.get(mac)?.name ?: known?.name,
- DeviceRegistry.get(mac)?.advert?.isWifi == true)
- }
+ DeviceActions.watchlistMenu(this, mac, DeviceRegistry.get(mac)?.name ?: known?.name,
+ DeviceRegistry.get(mac)?.advert?.isWifi == true) { refresh() }
}
private fun share() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt
index 78814b1..995ccac 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceSections.kt
@@ -79,12 +79,14 @@ object DeviceSections {
if (s == null) pastMatches.firstOrNull { it.source == "BLE" || it.source == "WIFI" }?.let { m ->
// The radio side as saved with its last match.
id += "Radio" to (if (m.source == "BLE") "Bluetooth LE" else "WiFi") + (m.radio?.let { " · $it" } ?: "")
+ m.heardBy?.let { id += "Heard by" to it }
}
if (s != null) {
id += "Address type" to s.addressType.label
id += "Trackability" to s.addressType.trackability(known?.firstSeen, known?.lastSeen, known?.sessions ?: 0,
DeviceRegistry.linkedFrom(mac) != null)
id += "Radio" to s.sources.joinToString(" + ") { if (it == Advert.Source.BLE) "Bluetooth LE" else "WiFi" }
+ id += "Heard by" to com.rfsentinel.app.esp.HeardBy.tag(mac, s.source)
}
a?.connectable?.let { id += "Connectable" to if (it) "Yes (accepts connections)" else "No (broadcast only)" }
a?.phy?.let { id += "PHY" to it }
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 3a75aad..2f39013 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -622,6 +622,9 @@ object Prefs {
fun networkSdr(context: Context) = str(context, "network_sdr")
fun setNetworkSdr(context: Context, v: String) = setStr(context, "network_sdr", v)
/** The user's own bands, one "start-end MHz label" per line. */
+ /** Sentinel Link: what linked Sentinels hear is saved in this phone's History too. */
+ fun saveLinked(context: Context) = bool(context, "save_linked", true)
+ fun setSaveLinked(context: Context, v: Boolean) = setBool(context, "save_linked", v)
fun radioCustomBands(context: Context) = str(context, "radio_custom_bands")
fun setRadioCustomBands(context: Context, v: String) = setStr(context, "radio_custom_bands", v)
/** Ranges never to report, one "start-end MHz" per line (e.g. a business band). */
diff --git a/app/src/main/res/layout/activity_oui_list.xml b/app/src/main/res/layout/activity_oui_list.xml
index ab20de3..fc9e12c 100644
--- a/app/src/main/res/layout/activity_oui_list.xml
+++ b/app/src/main/res/layout/activity_oui_list.xml
@@ -45,6 +45,13 @@
android:layout_height="wrap_content"
android:text="Add to watchlist" />
+ <Button
+ android:id="@+id/comboButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Custom rule: several conditions" />
+
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 8ba3ed8..68e16fb 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -885,6 +885,12 @@
style="@style/SettingsLabel"
android:paddingTop="6dp" />
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/linkSaveSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Save what linked Sentinels hear" />
+
<Button
android:id="@+id/linkButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
diff --git a/app/src/test/java/com/rfsentinel/app/oui/ComboRuleTest.kt b/app/src/test/java/com/rfsentinel/app/oui/ComboRuleTest.kt
new file mode 100644
index 0000000..85ab297
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/oui/ComboRuleTest.kt
@@ -0,0 +1,55 @@
+package com.rfsentinel.app.oui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ComboRuleTest {
+
+ private fun facts(name: String? = null, vendor: String = "Panasonic Connect", band: String? = "5", rssi: Int = -60) =
+ ComboRule.Facts(name, listOf(vendor), band, setOf("shape-0a1b2c3d"), "Laptop", rssi)
+
+ @Test
+ fun keyRoundTripsAndEveryConditionMustHold() {
+ val rule = ComboRule.parse("all:vendor~panasonic & noname & band=5 & probe=shape-0A1B2C3D & type~lap & rssi>=-70")!!
+ assertEquals(rule, ComboRule.parse(rule.key))
+ assertTrue(rule.matches(facts()))
+ assertFalse(rule.matches(facts(name = "CORP-WIFI"))) // has a name
+ assertFalse(rule.matches(facts(band = "2.4"))) // other band
+ assertFalse(rule.matches(facts(vendor = "Apple"))) // other maker
+ assertFalse(rule.matches(facts(rssi = -80))) // too weak
+ assertEquals("Maker contains \"panasonic\" · no name · 5 GHz · probe shape 0a1b2c3d · type contains \"lap\" · signal -70 dBm or stronger",
+ rule.describe())
+ }
+
+ @Test
+ fun nameConditions() {
+ val rule = ComboRule.parse("all:name^Flock & vendor~panasonic")!!
+ assertTrue(rule.matches(facts(name = "Flock-12AB")))
+ assertFalse(rule.matches(facts(name = "My Flock")))
+ assertTrue(ComboRule.parse("all:name~flock")!!.matches(facts(name = "My Flock")))
+ }
+
+ @Test
+ fun badRulesAreRefused() {
+ assertNull(ComboRule.parse("all:"))
+ assertNull(ComboRule.parse("all:vendor~"))
+ assertNull(ComboRule.parse("all:band=9"))
+ assertNull(ComboRule.parse("all:rssi>=loud"))
+ assertNull(ComboRule.parse("all:colour=red"))
+ assertNull(ComboRule.parse("name:Flock"))
+ assertTrue(OuiWatchlist.isValidKey("all:noname & band=bt"))
+ assertFalse(OuiWatchlist.isValidKey("all:nonsense"))
+ }
+
+ @Test
+ fun bands() {
+ assertEquals("bt", ComboRule.band(true, null))
+ assertEquals("2.4", ComboRule.band(false, 2437))
+ assertEquals("5", ComboRule.band(false, 5180))
+ assertEquals("6", ComboRule.band(false, 5955))
+ assertNull(ComboRule.band(false, null))
+ }
+}