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.

Add I saw it learning, probe-rate behaviour clue and live SDR waterfall

CIS-C0322c8c3d6589
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 52dcd7f..6873129 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -87,6 +87,7 @@
<activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" />
<activity android:name=".ui.AntennaCheckActivity" android:exported="false" />
<activity android:name=".ui.AircraftActivity" android:exported="false" />
+ <activity android:name=".ui.WaterfallActivity" android:exported="false" />
<activity
android:name=".ui.SetupActivity"
android:exported="false" />
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 4cb6513..9878ecc 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -181,8 +181,10 @@ class MainActivity : AppCompatActivity() {
menu.add(0, 4, 3, "Satellites")
menu.add(0, 5, 4, "Antenna check")
menu.add(0, 6, 5, "Aircraft")
+ menu.add(0, 7, 6, "Radio waterfall")
setOnMenuItemClickListener { item ->
when (item.itemId) {
+ 7 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WaterfallActivity::class.java))
6 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AircraftActivity::class.java)
.putExtra("demo", demoMode))
5 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AntennaCheckActivity::class.java)
diff --git a/app/src/main/java/com/rfsentinel/app/detect/Advert.kt b/app/src/main/java/com/rfsentinel/app/detect/Advert.kt
index 8053dd0..6ba8736 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/Advert.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/Advert.kt
@@ -47,7 +47,9 @@ class Advert(
/** Its probe request carried the Wi-Fi Alliance element 50:6F:9A:16 03 01 03 Flock cameras send. */
val flockProbeIe: Boolean = false,
/** FlipDeFlock's probe skeleton hash of a client's probe requests (USB adapter). */
- val probeSkeleton: Long? = null
+ val probeSkeleton: Long? = null,
+ /** Its latest run of wildcard probes (USB adapter): how steadily it probes ([ProbeBehaviour]). */
+ val probeRun: ProbeBehaviour.Run? = null
)
val isBle get() = source == Source.BLE
diff --git a/app/src/main/java/com/rfsentinel/app/detect/AdvertFingerprint.kt b/app/src/main/java/com/rfsentinel/app/detect/AdvertFingerprint.kt
index dba85c0..9ab5f1e 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/AdvertFingerprint.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/AdvertFingerprint.kt
@@ -30,6 +30,16 @@ object AdvertFingerprint {
}
}
+ /**
+ * [of] as a short key for the watchlist ("adv:" rules): 8 hex digits (FNV-1a), the same
+ * for every advert the device sends, whatever its address. Null when [of] is.
+ */
+ fun key(a: Advert): String? = of(a)?.let { fp ->
+ var h = 0x811C9DC5.toInt()
+ for (byte in fp.toByteArray(Charsets.UTF_8)) { h = h xor (byte.toInt() and 0xff); h *= 0x01000193 }
+ "%08x".format(h)
+ }
+
/** True when the address type means it's expected to rotate (or unknown on Android < 15). */
fun mayRotate(a: Advert): Boolean = a.isBle && a.addressType != AddressType.PUBLIC &&
a.addressType != AddressType.RANDOM_STATIC
diff --git a/app/src/main/java/com/rfsentinel/app/detect/ProbeBehaviour.kt b/app/src/main/java/com/rfsentinel/app/detect/ProbeBehaviour.kt
new file mode 100644
index 0000000..c0f9c2d
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/detect/ProbeBehaviour.kt
@@ -0,0 +1,80 @@
+package com.rfsentinel.app.detect
+
+import com.rfsentinel.app.util.MacUtil
+import java.util.Locale
+
+/**
+ * How steadily a WiFi client sends wildcard probe requests, heard by a USB adapter (FlipDeFlock's
+ * observation): a camera on a pole runs on mains power and probes without pause, from the same
+ * address, while a phone probes in short bursts to save its battery. The adapter hops channels and
+ * misses some probes, so this counts the 8 s windows that held at least one, not single frames.
+ */
+object ProbeBehaviour {
+ const val WINDOW_MS = 8_000L
+ /** A silence this long ends a run. */
+ const val BREAK_MS = 45_000L
+ /** A run counts as non-stop once it lasts this long with probes in at least [MIN_COVERAGE] of its windows. */
+ const val MIN_SPAN_MS = 120_000L
+ const val MIN_COVERAGE = 0.5
+ const val CONFIDENCE = 55
+ const val SOURCE = "FlipDeFlock (probe-rate behaviour)"
+ private const val LABEL = "Probes non-stop like a fixed camera"
+
+ /** Kinds of device that sit in one place on mains power, where non-stop probing fits. */
+ private val FIXED = setOf(Category.ALPR, Category.PUBLIC_SAFETY, Category.BODY_CAM, Category.AUDIO_SENSOR)
+
+ /** One unbroken run of wildcard probes from a device. */
+ data class Run(val probes: Int, val firstAt: Long, val lastAt: Long, val windows: Int) {
+ val spanMs: Long get() = lastAt - firstAt
+ /** Share of the 8 s windows from first to last probe that held a probe. */
+ val coverage: Double get() = windows.toDouble() / (lastAt / WINDOW_MS - firstAt / WINDOW_MS + 1)
+ val nonStop: Boolean get() = spanMs >= MIN_SPAN_MS && coverage >= MIN_COVERAGE
+ /** Probes heard per 8 s window that held any. */
+ val perWindow: Double get() = probes.toDouble() / windows.coerceAtLeast(1)
+
+ /** "3.2 per 8 s, in 90% of windows for 4 min". */
+ fun describe(): String = String.format(Locale.US, "%.1f per 8 s, in %d%% of windows for %s",
+ perWindow, (coverage * 100).toInt().coerceAtMost(100), duration(spanMs))
+ }
+
+ /** Kept per device by the frame parser; not thread-safe (like MonitorFrames). */
+ class Counter {
+ private var probes = 0; private var windows = 0
+ private var firstAt = 0L; private var lastAt = 0L; private var window = -1L
+
+ fun probe(now: Long) {
+ if (probes == 0 || now - lastAt > BREAK_MS || now < lastAt) {
+ probes = 0; windows = 0; window = -1L; firstAt = now
+ }
+ probes++; lastAt = now
+ val w = now / WINDOW_MS
+ if (w != window) { window = w; windows++ }
+ }
+
+ fun run(): Run? = if (probes == 0) null else Run(probes, firstAt, lastAt, windows)
+ }
+
+ /**
+ * A supporting match for a device that already matches a fixed surveillance device and has
+ * been probing non-stop from its maker's own (not randomized) address. Never a match alone:
+ * a phone left on its WiFi settings page probes non-stop too.
+ */
+ fun supportHit(a: Advert, hits: List<Hit>): Hit? {
+ val w = a.wifi ?: return null
+ val run = w.probeRun ?: return null
+ if (!w.client || !run.nonStop || a.timestamp - run.lastAt > BREAK_MS || MacUtil.isRandomized(a.mac)) return null
+ val top = hits.filter { it.category in FIXED && it.source != SOURCE }.maxByOrNull { it.confidence } ?: return null
+ return Hit(top.category, LABEL, CONFIDENCE,
+ "Sends wildcard probe requests non-stop (${run.describe()}) from a fixed address: " +
+ "a mains-powered device such as a pole camera, not a battery phone", SOURCE)
+ }
+
+ private fun duration(ms: Long): String {
+ val s = ms / 1000
+ return when {
+ s < 120 -> "$s s"
+ s < 7200 -> "${s / 60} min"
+ else -> "${s / 3600} h"
+ }
+ }
+}
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 1398495..c1d015c 100644
--- a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt
+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt
@@ -15,6 +15,8 @@ data class OuiEntry(
* - "probe:<ssid>" a device asks for this exact WiFi network name (probe request,
* heard by a USB WiFi adapter or an ESP32 Marauder board)
* - "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
*/
val prefix: String,
val label: String,
@@ -34,6 +36,7 @@ data class OuiEntry(
val isVendorRule get() = prefix.startsWith(VENDOR, ignoreCase = true)
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 ruleText get() = prefix.substringAfter(':').trim()
val effectiveScore: Int
@@ -60,5 +63,8 @@ data class OuiEntry(
const val VENDOR = "vendor:"
const val PROBE = "probe:"
const val FINGERPRINT = "fp:"
+ const val ADVERT = "adv:"
+ /** The source of entries made with "I saw it" ([com.rfsentinel.app.ui.DeviceActions.learn]). */
+ const val LEARNED = "learned from I saw it"
}
}
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 ec4c9b2..2136a1c 100644
--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt
@@ -38,6 +38,8 @@ object OuiWatchlist {
/** Requested-network rules keyed by the lower-cased network name. */
val probeRules: Map<String, OuiEntry>,
val fingerprintRules: Map<String, OuiEntry>,
+ /** Bluetooth advert-pattern rules keyed by [com.rfsentinel.app.detect.AdvertFingerprint.key]. */
+ val advertRules: Map<String, OuiEntry>,
val all: List<OuiEntry>
)
@@ -55,7 +57,7 @@ object OuiWatchlist {
private set
@Volatile
- private var state = State(emptyMap(), emptyList(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyList())
+ private var state = State(emptyMap(), emptyList(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyMap(), 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")
@@ -74,13 +76,14 @@ 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 }
+ byHex = all.filter { !it.isNameRule && !it.isStartsRule && !it.isVendorRule && !it.isProbeRule && !it.isFingerprintRule && !it.isAdvertRule }
.associateBy { MacUtil.hex(it.prefix) },
nameRules = all.filter { it.isNameRule && it.ruleText.isNotEmpty() },
startsRules = all.filter { it.isStartsRule && it.ruleText.isNotEmpty() },
vendorRules = all.filter { it.isVendorRule && it.ruleText.isNotEmpty() },
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() },
all = all
)
version++
@@ -117,6 +120,7 @@ object OuiWatchlist {
k.startsWith(OuiEntry.VENDOR, ignoreCase = true) -> OuiEntry.VENDOR + k.substringAfter(':').trim()
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()
else -> MacUtil.normalize(k)
}
}
@@ -179,11 +183,11 @@ 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: rule. */
+ /** Valid keys: IEEE block prefix (24/28/36-bit), 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.PROBE, true) || k.startsWith(OuiEntry.FINGERPRINT, true) || k.startsWith(OuiEntry.ADVERT, true)) {
return k.substringAfter(':').isNotBlank()
}
return MacUtil.isValidBlock(k) || MacUtil.isValidMac(k)
@@ -236,6 +240,15 @@ object OuiWatchlist {
fun isFingerprintWatched(fp: String): Boolean = fp.lowercase() in state.fingerprintRules
+ /** Hits for a Bluetooth device whose adverts have a watched pattern ("adv:" rules), whatever its address. */
+ fun advertHits(a: com.rfsentinel.app.detect.Advert): List<Hit> {
+ if (state.advertRules.isEmpty()) return emptyList()
+ val key = com.rfsentinel.app.detect.AdvertFingerprint.key(a) ?: return emptyList()
+ return listOfNotNull(state.advertRules[key]?.toHit("Its Bluetooth adverts match the watched pattern $key"))
+ }
+
+ fun isAdvertWatched(key: String): Boolean = key.lowercase() in state.advertRules
+
/** 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 8ba5e40..c69aee0 100644
--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt
@@ -33,13 +33,14 @@ class OuiAdapter(
item.isVendorRule -> "Maker contains \"${item.ruleText}\""
item.isProbeRule -> "Asks for network \"${item.ruleText}\""
item.isFingerprintRule -> "Probe fingerprint ${item.ruleText}"
+ item.isAdvertRule -> "Bluetooth advert pattern ${item.ruleText}"
else -> item.prefix
}
holder.binding.labelText.text = item.label
holder.binding.confidenceText.text = buildString {
append(if (item.isCustom) "Your entry" else "Preset")
append(" · ${item.effectiveCategory.shortTag} · ${Tier.of(item.effectiveScore).label} ${item.effectiveScore}%")
- if (!item.isCustom && item.source.isNotEmpty()) append("\n${item.source}")
+ if ((!item.isCustom || item.source == com.rfsentinel.app.oui.OuiEntry.LEARNED) && item.source.isNotEmpty()) append("\n${item.source}")
}
// Only user-added entries can be removed; bundled preset entries are read-only here
// (deselect the whole preset in Settings instead).
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
index a390167..178d353 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
@@ -222,7 +222,8 @@ class RadioWatch {
private const val CHANNEL_HALF_HZ = 5_000.0
/** Only the flat middle of the spectrum is used; the edges roll off. */
const val USABLE_HZ = 800_000.0
- private const val DC_GUARD_HZ = 15_000L
+ /** Around a chunk's centre the receiver's own DC spike hides everything. */
+ const val DC_GUARD_HZ = 15_000L
private const val ACTIVE_DB = 12
private const val SPLATTER_HZ = 37_500L
private const val BUSY_RATIO = 0.4
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
index 02d7da5..2b1e09a 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -18,6 +18,9 @@ import com.rfsentinel.app.usb.UsbWifi
*
* Or, with [adsb] on, it stays on 1090 MHz as an ADS-B receiver ([ModeS], [AdsbTracker]):
* aircraft heard directly, no internet needed, handed to [onAircraft] every few seconds.
+ *
+ * The radio waterfall screen ([SdrWaterfall]) gets a row per sweep, or, zoomed in with [tuneHz],
+ * holds one frequency for a fast live view (the sweep and ADS-B pause meanwhile).
*/
object SdrRadio {
@@ -30,6 +33,8 @@ object SdrRadio {
private const val STALL_CHUNKS = 8 // chunks in a row without samples before the stream is restarted
private const val ADSB_GAIN_TENTHS_DB = 496 // the tuner's most: aircraft are far and faint
private const val ADSB_PUSH_MS = 2_000L
+ private const val TUNED_READS = 4 // ~16 ms of samples per waterfall row
+ private const val TUNED_ROW_MS = 40L // at most ~25 rows a second
@Volatile var status: String = ""; private set
/** ADS-B messages decoded since the app started, for the main screen's messages-per-second line. */
@@ -52,6 +57,15 @@ object SdrRadio {
private val halted get() = stop || Thread.currentThread() !== worker
/** Receive ADS-B on 1090 MHz instead of sweeping the radio bands; switches at the next sweep. */
@Volatile var adsb = false
+ /**
+ * The waterfall screen zoomed in: hold this frequency instead of sweeping (or receiving ADS-B),
+ * until set back to null. Picked up within a chunk.
+ */
+ @Volatile var tuneHz: Long? = null
+ /** Learned channels for the sweep, kept while the waterfall zooms in and out (new per device). */
+ private var sweepWatch: RadioWatch? = null
+ /** An SDR is plugged in and being read. */
+ val running: Boolean get() = runningDevice != null
/** Where you are (latitude, longitude), to drop impossible aircraft positions. */
@Volatile var location: (() -> Pair<Double, Double>?)? = null
/** Aircraft with a position, and addresses heard without one, every couple of seconds in ADS-B mode. */
@@ -93,6 +107,7 @@ object SdrRadio {
receiver = null
halt("")
onEvent = null
+ tuneHz = null
}
@Synchronized
@@ -172,7 +187,12 @@ object SdrRadio {
else "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"
return false
}
- while (!halted && !sdr.lost && !gone(d.deviceName)) if (adsb) runAdsb(sdr, d.deviceName) else runSweep(sdr, d.deviceName)
+ sweepWatch = null
+ while (!halted && !sdr.lost && !gone(d.deviceName)) when {
+ tuneHz != null -> runTuned(sdr, d.deviceName)
+ adsb -> runAdsb(sdr, d.deviceName)
+ else -> runSweep(sdr, d.deviceName)
+ }
if (sdr.lost) UsbWifi.log("$deviceLabel: the dongle stopped answering (unplugged?)")
val away = sdr.lost || gone(d.deviceName)
if (!away) sdr.close()
@@ -202,7 +222,7 @@ object SdrRadio {
val frames = ArrayList<ModeS.Frame>()
var lastPush = 0L; var lastLog = System.currentTimeMillis(); var fails = 0; var messages = 0L; var logged = 0L
var lastCheck = System.currentTimeMillis()
- while (!halted && !sdr.lost && adsb) {
+ while (!halted && !sdr.lost && adsb && tuneHz == null) {
val n = sdr.read(buf)
// Every couple of seconds: still plugged in? (Reads alone can fail quietly for a long time.)
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
@@ -250,7 +270,7 @@ object SdrRadio {
sdr.resetBuffer()
var cfg = config
var plan = RadioWatch.plan(cfg)
- val watch = RadioWatch()
+ val watch = sweepWatch ?: RadioWatch().also { sweepWatch = it }
watch.config = cfg
fun logPlan() = UsbWifi.log("$deviceLabel: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " +
cfg.bands.joinToString { "%.1f-%.1f MHz".format(it.startHz / 1e6, it.endHz / 1e6) } +
@@ -262,11 +282,13 @@ object SdrRadio {
var lastLog = 0L; var sweepStart = System.currentTimeMillis(); var sweepMs = 0L
var events = 0; var unlocked = 0; var readErrors = 0; var failedChunks = 0
var lastCheck = System.currentTimeMillis()
- while (!halted && !sdr.lost && !adsb) {
+ // The waterfall's row for this sweep, while it is on screen.
+ var row = ArrayList<SdrWaterfall.Segment>()
+ while (!halted && !sdr.lost && !adsb && tuneHz == null) {
// Settings changed: the new bands / targets / sensitivity from this sweep on.
if (config != cfg) { cfg = config; plan = RadioWatch.plan(cfg); watch.config = cfg; logPlan() }
for (center in plan) {
- if (halted || sdr.lost || adsb) break
+ if (halted || sdr.lost || adsb || tuneHz != null) break
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
if (!sdr.tune(center)) { unlocked++; continue }
repeat(sdr.settleReads) { sdr.read(buf) }
@@ -289,6 +311,8 @@ object SdrRadio {
failedChunks = 0
val bursts = if (tetra) RadioWatch.burstSpectrum(iq, got / 2, sdr.sampleRate) else null
val psd = bursts?.psd ?: RadioWatch.powerSpectrum(iq, got / 2)
+ if (SdrWaterfall.listening) row += SdrWaterfall.segment(center, psd, sdr.sampleRate, RadioWatch.USABLE_HZ,
+ cfg.bands.firstOrNull { RadioWatch.covers(it, center) }?.label)
for (e in watch.analyze(center, psd, sdr.sampleRate, System.currentTimeMillis(), bursts)) {
if (!e.repeat) {
events++
@@ -298,8 +322,13 @@ object SdrRadio {
onEvent?.invoke(e)
}
}
+ if (tuneHz != null || adsb) break // cut short: not a whole sweep
watch.sweepDone()
val now = System.currentTimeMillis()
+ if (row.isNotEmpty()) {
+ SdrWaterfall.listener?.invoke(SdrWaterfall.Row(row.sortedBy { it.startHz }, tuned = false, at = now))
+ row = ArrayList()
+ }
sweepMs = now - sweepStart; sweepStart = now
if (gone(name)) break
if (!halted) status = if (watch.sweeps < 6) "$deviceLabel · learning the radio bands here…"
@@ -312,4 +341,47 @@ object SdrRadio {
}
UsbWifi.log("$deviceLabel: radio sweep stopped after ${watch.sweeps} sweeps")
}
+
+ /** Holds [tuneHz] for the waterfall screen: a row of the ~2 MHz around it every few tens of ms. */
+ private fun runTuned(sdr: SdrDevice, name: String) {
+ val hz = tuneHz ?: return
+ sdr.setSampleRate(SAMPLE_RATE)
+ sdr.setGain(GAIN_TENTHS_DB)
+ val mhz = "%.3f MHz".format(java.util.Locale.US, hz / 1e6)
+ if (!sdr.tune(hz)) {
+ UsbWifi.log("$deviceLabel: the tuner didn't lock on $mhz")
+ status = "$deviceLabel · waterfall: the tuner can't tune to $mhz"
+ while (!halted && !sdr.lost && tuneHz == hz) Thread.sleep(100)
+ return
+ }
+ sdr.resetBuffer()
+ UsbWifi.log("$deviceLabel: waterfall on $mhz (radio watch paused)")
+ status = "$deviceLabel · waterfall on $mhz · radio watch paused"
+ val buf = ByteArray(XFER)
+ val iq = ByteArray(XFER * TUNED_READS)
+ var lastRow = 0L; var lastCheck = System.currentTimeMillis(); var fails = 0
+ repeat(sdr.settleReads) { sdr.read(buf) }
+ while (!halted && !sdr.lost && tuneHz == hz) {
+ if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
+ var got = 0
+ for (i in 0 until TUNED_READS) {
+ val n = sdr.read(buf)
+ if (n <= 0) break
+ System.arraycopy(buf, 0, iq, got, n); got += n
+ }
+ if (got < 2 * 1024) {
+ if (++fails % STALL_CHUNKS == 0) sdr.resetBuffer()
+ continue
+ }
+ fails = 0
+ val now = System.currentTimeMillis()
+ val listener = SdrWaterfall.listener
+ if (listener == null || now - lastRow < TUNED_ROW_MS) continue
+ lastRow = now
+ val psd = RadioWatch.powerSpectrum(iq, got / 2)
+ // The outer tenth on each side rolls off in the receiver's filter: left out.
+ listener(SdrWaterfall.Row(listOf(SdrWaterfall.segment(hz, psd, sdr.sampleRate, sdr.sampleRate * 0.45, null)), tuned = true, at = now))
+ }
+ UsbWifi.log("$deviceLabel: waterfall left $mhz")
+ }
}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt
new file mode 100644
index 0000000..370f76e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt
@@ -0,0 +1,36 @@
+package com.rfsentinel.app.sdr
+
+/**
+ * Live rows for the radio waterfall screen, handed over from the SDR thread, and built only while
+ * that screen listens. Sweeping, a row is one sweep of every watched band (the usable middle of each
+ * tuned chunk, side by side); zoomed in ([SdrRadio.tuneHz]), a row is a few milliseconds of the
+ * ~2 MHz around one frequency.
+ */
+object SdrWaterfall {
+
+ /** A stretch of spectrum: [db] evenly spaced from [startHz] to [endHz], in the band named [band]. */
+ class Segment(val startHz: Long, val endHz: Long, val db: FloatArray, val band: String?)
+
+ /** One line of the waterfall, segments in frequency order. [tuned]: the fast single-frequency view. */
+ class Row(val segments: List<Segment>, val tuned: Boolean, val at: Long)
+
+ /** Called on the SDR thread with each new row; null while no screen shows it. */
+ @Volatile var listener: ((Row) -> Unit)? = null
+ val listening: Boolean get() = listener != null
+
+ /**
+ * The middle [halfSpanHz] either side of [centerHz] from one chunk's spectrum [psd] (FFT-shifted,
+ * DC at n/2), with the receiver's own spike at the centre levelled to the noise beside it.
+ */
+ fun segment(centerHz: Long, psd: FloatArray, sampleRate: Int, halfSpanHz: Double, band: String?): Segment {
+ val n = psd.size
+ val binHz = sampleRate.toDouble() / n
+ val half = (halfSpanHz / binHz).toInt().coerceIn(1, n / 2 - 1)
+ val out = psd.copyOfRange(n / 2 - half, n / 2 + half + 1)
+ val guard = maxOf(1, (RadioWatch.DC_GUARD_HZ / binHz).toInt()).coerceAtMost(half - 1)
+ val level = minOf(out[half - guard - 1], out[half + guard + 1])
+ for (k in half - guard..half + guard) out[k] = level
+ val edge = (half * binHz).toLong()
+ return Segment(centerHz - edge, centerHz + edge, out, band)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
index e48012c..70e092d 100644
--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt
@@ -362,6 +362,13 @@ object DeviceRegistry {
}
/** Full snapshot (history, path, raw advert) for the detail screen. */
+ /**
+ * Addresses heard in the last [withinMs] whose adverts have the fingerprint [fp]
+ * ([AdvertFingerprint.of]): other devices of the same model nearby, or one device changing address.
+ */
+ fun sharingFingerprint(fp: String, now: Long = System.currentTimeMillis(), withinMs: Long = 10 * 60_000L): Int =
+ tracks.values.count { t -> synchronized(t) { t.fingerprint == fp && now - t.lastSeen <= withinMs } }
+
/** The last advert of every device in this session (to re-check them after the watchlist changes). */
fun lastAdverts(): List<Advert> = tracks.values.mapNotNull { t -> synchronized(t) { t.advert } }
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 dc5efd4..09fdd8a 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -691,7 +691,8 @@ class ScanForegroundService : Service() {
mac = mac, source = Advert.Source.WIFI, rssi = m.rssi, name = m.ssid ?: m.wps?.label,
addressType = com.rfsentinel.app.detect.AddressType.ofWifi(mac),
wifi = Advert.WifiInfo(m.frequencyMhz, "", null, emptyList(), client = !m.isAccessPoint,
- wildcardProbe = m.wildcardProbe, flockProbeIe = m.flockProbeIe, probeSkeleton = m.probeSkeleton),
+ wildcardProbe = m.wildcardProbe, flockProbeIe = m.flockProbeIe, probeSkeleton = m.probeSkeleton,
+ probeRun = m.probeRun),
timestamp = now
), null)
}
@@ -743,13 +744,16 @@ class ScanForegroundService : Service() {
// patrol-vehicle cluster, then fused into one calibrated score.
val raw = SignatureEngine.classify(a) +
OuiWatchlist.hits(a.mac, a.name, listOfNotNull(macVendor) + companyVendors) +
+ OuiWatchlist.advertHits(a) +
DeviceRegistry.inheritedHits(a.mac) +
listOfNotNull(DeviceRegistry.clusterHit(a.mac, now)) +
espHits[a.mac]?.takeIf { now - it.first < ESP_HIT_TTL_MS }?.second.orEmpty() +
probeHits[a.mac]?.takeIf { now - it.first < ESP_HIT_TTL_MS }?.second.orEmpty() +
extra
val noAirTags = Prefs.excludeAirTags(this)
- val sifted = DeviceIntel.dropTrainRouter(com.rfsentinel.app.detect.FlockNoise.filter(raw, a.name, OuiWatchlist.flockRegion), a)
+ val kept = DeviceIntel.dropTrainRouter(com.rfsentinel.app.detect.FlockNoise.filter(raw, a.name, OuiWatchlist.flockRegion), a)
+ // Non-stop probing backs up a fixed-camera match that survived the noise filters (never alone).
+ val sifted = kept + listOfNotNull(com.rfsentinel.app.detect.ProbeBehaviour.supportHit(a, kept))
val hits = EvidenceFusion.fuse(sifted.filter {
Prefs.categoryEnabled(this, it.category) && !(noAirTags && SignatureEngine.isAppleFindMy(it))
})
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt b/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
index 984329c..4879ed9 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DemoData.kt
@@ -149,7 +149,7 @@ object DemoData {
val a = make(base + wobble.toInt(), t)
val vendor = VendorDb.macVendor(a.mac) ?: a.manufacturerData.keys.firstNotNullOfOrNull { VendorDb.company(it) }
val raw = SignatureEngine.classify(a) +
- OuiWatchlist.hits(a.mac, a.name, listOfNotNull(vendor)) +
+ OuiWatchlist.hits(a.mac, a.name, listOfNotNull(vendor)) + OuiWatchlist.advertHits(a) +
listOfNotNull(DeviceRegistry.clusterHit(a.mac, t))
val rid = if (a.mac == DEMO_DRONE && anchor != null) demoRemoteId(anchor, s) else null
// Made-up spots around you within real Bluetooth / WiFi range (5-60 m),
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 7a4986f..f9970bc 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
@@ -90,6 +90,7 @@ object DeviceActions {
toast(activity, if (favorite) "Removed from favorites" else "Added to favorites")
}
}
+ items += "I saw it: learn this device..." to { learn(activity, mac) }
if (snap?.advert != null && snap.best == null) {
items += "Report unknown device..." to { reportUnknown(activity, mac) }
}
@@ -179,6 +180,91 @@ object DeviceActions {
.show()
}
+ /**
+ * "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
+ * address: its address when that is fixed, its Bluetooth advert pattern, its WiFi probe fingerprint.
+ * A pattern many devices nearby share (one phone model) is refused, and patterns learned this way
+ * stay probable matches ([LEARNED_SCORE]), never strong ones: only the exact address is certain.
+ */
+ fun learn(activity: AppCompatActivity, mac: String) {
+ val snap = DeviceRegistry.get(mac)
+ val advert = snap?.advert
+ val randomized = MacUtil.isRandomized(mac)
+ 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 = "Tell RF Sentinel what this is, so it knows it next time, even under a new address."
+ })
+ val label = EditText(activity).apply {
+ hint = "What it is, e.g. pole camera on the bridge"
+ setSingleLine(true)
+ setText(snap?.best?.label ?: snap?.name ?: "")
+ }
+ box.addView(label)
+
+ // Each stable identity: key, what it is, how sure a later match is, and why it can't be used.
+ class Option(val key: String, val text: String, val score: Int?, val refused: String?)
+ val options = mutableListOf<Option>()
+ if (!randomized) options += Option(mac, "This exact address ($mac)", null, null)
+ if (advert != null) com.rfsentinel.app.detect.AdvertFingerprint.of(advert)?.let { fp ->
+ val key = com.rfsentinel.app.detect.AdvertFingerprint.key(advert)!!
+ val shared = DeviceRegistry.sharingFingerprint(fp)
+ options += Option(OuiEntry.ADVERT + key, "Its Bluetooth advert pattern ($key)", LEARNED_SCORE,
+ if (shared >= MAX_SHARED) "$shared devices nearby send the same pattern" else null)
+ }
+ com.rfsentinel.app.usb.ProbeIntel.of(mac)?.fingerprint?.let { fp ->
+ val shared = com.rfsentinel.app.usb.ProbeIntel.sharing(fp)
+ options += Option(OuiEntry.FINGERPRINT + fp, "Its WiFi probe fingerprint ($fp)", LEARNED_SCORE,
+ if (shared >= MAX_SHARED) "$shared addresses heard today share it" else null)
+ }
+ val boxes = options.map { o ->
+ android.widget.CheckBox(activity).apply {
+ val watched = OuiWatchlist.customEntry(o.key) != null
+ text = o.text + when {
+ watched -> "\nAlready on your watchlist"
+ o.refused != null -> "\nNot usable: ${o.refused}, so it would match them too"
+ o.score != null -> "\nMatches as probable (${o.score}%): similar devices can share it"
+ else -> ""
+ }
+ isEnabled = o.refused == null && !watched
+ isChecked = isEnabled
+ }.also { box.addView(it) }
+ }
+ if (boxes.none { it.isEnabled }) box.addView(TextView(activity).apply {
+ setPadding(0, (8 * d).toInt(), 0, 0)
+ text = if (options.isEmpty()) "Nothing stable to learn: its address is private and changes, and it sends nothing " +
+ "that marks it apart from similar devices. Tip: add a name rule under Watchlist & rules."
+ else "Nothing new to learn from it."
+ })
+ val category = snap?.best?.category?.takeIf { it != com.rfsentinel.app.detect.Category.CUSTOM }
+ MaterialAlertDialogBuilder(activity)
+ .setTitle("I saw it")
+ .setView(ScrollView(activity).apply { addView(box) })
+ .setPositiveButton("Learn") { _, _ ->
+ val chosen = options.filterIndexed { i, _ -> boxes[i].isEnabled && boxes[i].isChecked }
+ if (chosen.isEmpty()) { toast(activity, "Nothing learned"); return@setPositiveButton }
+ val name = label.text.toString().trim().ifEmpty { "Seen device" }
+ val entries = chosen.map { OuiEntry(it.key, name, OuiEntry.LEARNED, "custom", it.score, category?.name) }
+ entries.forEach { OuiWatchlist.addCustomEntry(activity, it) }
+ com.rfsentinel.app.util.Undo.show(activity, "Learned $name (${entries.size} " +
+ (if (entries.size == 1) "rule" else "rules") + ")") {
+ entries.forEach { OuiWatchlist.removeCustomEntry(activity, it.prefix) }
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ /** How sure a later match on a learned pattern (not an exact address) is: probable, never strong. */
+ const val LEARNED_SCORE = 60
+ /** A pattern this many devices share is refused: it would match them all. */
+ const val MAX_SHARED = 4
+
/**
* Shares a signature report (see [SignatureReport]) so a device RF Sentinel
* doesn't know can be added. The user sees exactly what is shared first.
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 09a5d4f..bc793aa 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -109,6 +109,7 @@ class DeviceDetailActivity : AppCompatActivity() {
binding.noteText.setOnClickListener { editNote() }
binding.actionCopy.setOnClickListener { DeviceActions.copy(this, mac) }
binding.actionShare.setOnClickListener { share() }
+ binding.actionLearn.setOnClickListener { DeviceActions.learn(this, mac) }
lifecycleScope.launch {
val db = AppDatabase.getInstance(this@DeviceDetailActivity)
@@ -306,6 +307,10 @@ class DeviceDetailActivity : AppCompatActivity() {
}
if (r.probed.isNotEmpty()) id += "Networks it asked for" to r.probed.reversed().joinToString(", ")
}
+ a?.wifi?.probeRun?.let { run ->
+ id += "Wildcard probes" to run.describe() +
+ if (run.nonStop) " · non-stop, like a mains-powered fixed device" else ""
+ }
if (id.isNotEmpty()) out += "Identity" to id
// Drone Remote ID
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
new file mode 100644
index 0000000..b9cc445
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
@@ -0,0 +1,137 @@
+package com.rfsentinel.app.ui
+
+import android.os.Bundle
+import android.text.InputType
+import android.view.View
+import android.widget.EditText
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rfsentinel.app.databinding.ActivityWaterfallBinding
+import com.rfsentinel.app.sdr.FreqNames
+import com.rfsentinel.app.sdr.RadioWatch
+import com.rfsentinel.app.sdr.SdrRadio
+import com.rfsentinel.app.sdr.SdrWaterfall
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import java.util.Locale
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * The SDR's live radio waterfall. It opens on the band sweep (a row per sweep of the watched bands,
+ * radio detection carries on); tapping a frequency or Tune zooms in: the SDR holds those ~2 MHz for a
+ * fast live view, and detection pauses until Back to sweep or leaving the screen. Receive-only.
+ */
+class WaterfallActivity : AppCompatActivity() {
+
+ private lateinit var binding: ActivityWaterfallBinding
+ private val queue = ConcurrentLinkedQueue<SdrWaterfall.Row>()
+ private val posted = AtomicBoolean(false)
+ private val drain = Runnable {
+ posted.set(false)
+ var any = false
+ while (true) { val row = queue.poll() ?: break; binding.waterfall.add(row); any = true }
+ if (any) binding.waterfall.invalidate()
+ }
+ /** Rows show the zoomed-in view (vs the sweep), to clear the view once when it switches. */
+ private var showingTuned: Boolean? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityWaterfallBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.root.applySystemBarInsets()
+ title = "Radio waterfall"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding.waterfall.onTap = { hz -> zoom(hz) }
+ binding.tuneButton.setOnClickListener { askFrequency() }
+ binding.sweepButton.setOnClickListener { SdrRadio.tuneHz = null; refresh() }
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(1000) }
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ SdrWaterfall.listener = { row ->
+ queue.add(row)
+ while (queue.size > MAX_QUEUED) queue.poll()
+ if (posted.compareAndSet(false, true)) binding.waterfall.post(drain)
+ }
+ }
+
+ override fun onStop() {
+ super.onStop()
+ SdrWaterfall.listener = null
+ queue.clear()
+ // Radio detection never stays paused behind a closed screen.
+ SdrRadio.tuneHz = null
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ private fun zoom(hz: Long) {
+ if (!SdrRadio.running) return
+ SdrRadio.tuneHz = (hz + RadioWatch.STEP_HZ / 2) / RadioWatch.STEP_HZ * RadioWatch.STEP_HZ
+ refresh()
+ }
+
+ private fun askFrequency() {
+ if (!SdrRadio.running) { Toast.makeText(this, "No SDR running", Toast.LENGTH_SHORT).show(); return }
+ val input = EditText(this).apply {
+ hint = "Frequency in MHz, e.g. 155.475"
+ inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
+ SdrRadio.tuneHz?.let { setText(String.format(Locale.US, "%.4f", it / 1e6)) }
+ }
+ val pad = (20 * resources.displayMetrics.density).toInt()
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Tune to")
+ .setView(android.widget.FrameLayout(this).apply { setPadding(pad, 0, pad, 0); addView(input) })
+ .setPositiveButton("Tune") { _, _ ->
+ val mhz = input.text.toString().replace(',', '.').toDoubleOrNull()
+ if (mhz == null || mhz < MIN_MHZ || mhz > MAX_MHZ) {
+ Toast.makeText(this, "Enter a frequency from $MIN_MHZ to $MAX_MHZ MHz", Toast.LENGTH_SHORT).show()
+ } else zoom((mhz * 1e6).toLong())
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ private fun refresh() {
+ val tuned = SdrRadio.tuneHz
+ if (showingTuned != (tuned != null)) {
+ showingTuned = tuned != null
+ queue.clear()
+ binding.waterfall.clear()
+ }
+ val running = SdrRadio.running
+ binding.statusText.text = when {
+ !running -> SdrRadio.status.ifBlank { "No SDR running" }
+ tuned != null -> String.format(Locale.US, "%.4f MHz", tuned / 1e6) +
+ (FreqNames.lookup(tuned, RadioWatch.STEP_HZ)?.let { " · ${it.name}" } ?: "") + "\n" + SdrRadio.status
+ else -> SdrRadio.status
+ }
+ binding.hintText.text = when {
+ !running -> "Plug in an RTL-SDR or HackRF and start scanning to see the radio bands live."
+ tuned != null -> "Zoomed in on about 2 MHz. Radio detection is paused until you go back to the sweep. Tap to move."
+ SdrRadio.adsb -> "The SDR is receiving ADS-B. Tune to look at a frequency."
+ else -> "One row per sweep of your watched bands, newest at the top. Tap a signal to zoom in."
+ }
+ binding.sweepButton.visibility = if (tuned != null) View.VISIBLE else View.GONE
+ binding.tuneButton.isEnabled = running
+ }
+
+ private companion object {
+ /** Rows waiting for the screen; older ones are dropped if it falls behind. */
+ const val MAX_QUEUED = 64
+ const val MIN_MHZ = 1.0
+ const val MAX_MHZ = 6000.0
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt
new file mode 100644
index 0000000..49c2972
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt
@@ -0,0 +1,210 @@
+package com.rfsentinel.app.ui
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.Rect
+import android.util.AttributeSet
+import android.util.TypedValue
+import android.view.MotionEvent
+import android.view.View
+import com.rfsentinel.app.sdr.SdrWaterfall
+import java.util.Locale
+import kotlin.math.abs
+
+/**
+ * The radio waterfall: the latest spectrum as a line on top, and below it every row so far, newest at
+ * the top, from dark (noise) to bright (a strong signal). The colour scale follows the noise floor, so
+ * it reads the same with any antenna. Tap to pick a frequency ([onTap]).
+ */
+class WaterfallView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
+
+ /** A frequency tapped on the waterfall or the spectrum. */
+ var onTap: ((Long) -> Unit)? = null
+
+ private val density = resources.displayMetrics.density
+ private val textColor = TypedValue().let { tv ->
+ context.theme.resolveAttribute(android.R.attr.textColorSecondary, tv, true)
+ if (tv.resourceId != 0) context.getColor(tv.resourceId) else tv.data
+ }
+ private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = textColor
+ textSize = resources.getDimension(com.rfsentinel.app.R.dimen.text_caption)
+ }
+ private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = textColor; strokeWidth = 1.5f * density; style = Paint.Style.STROKE }
+ private val peakPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = textColor; alpha = 90; strokeWidth = 1f * density; style = Paint.Style.STROKE }
+ private val gapPaint = Paint().apply { color = textColor; alpha = 140; strokeWidth = 1f * density }
+ private val bitmapPaint = Paint().apply { isFilterBitmap = false }
+ private val blackPaint = Paint().apply { color = Color.BLACK }
+
+ // Where each pixel column comes from in the current rows' layout.
+ private var layoutKey = ""
+ private var colSeg = IntArray(0); private var colFrom = IntArray(0); private var colTo = IntArray(0)
+ private var colHz = LongArray(0)
+ /** Columns where one band stops and another starts (not side by side in frequency). */
+ private var gaps = IntArray(0)
+ private var tuned = false
+
+ private var bitmap: Bitmap? = null
+ /** Bitmap row holding the newest line; the ones after it are older. */
+ private var newest = 0
+ private var rows = 0
+ private var pixels = IntArray(0)
+ private var spectrum: FloatArray? = null
+ private var peak: FloatArray? = null
+ /** Noise floor (dB), followed slowly so the colours stay steady. */
+ private var floor = Float.NaN
+
+ private val spectrumH get() = (height * 0.28f).coerceAtLeast(64 * density)
+ private val labelH get() = textPaint.textSize + 6 * density
+ private val waterTop get() = spectrumH + labelH
+
+ /** Forgets every row (the view switched between the sweep and a single frequency). */
+ fun clear() {
+ layoutKey = ""; rows = 0; spectrum = null; peak = null; floor = Float.NaN
+ bitmap?.eraseColor(Color.BLACK)
+ invalidate()
+ }
+
+ /** Adds the newest row; call on the main thread, then [invalidate]. */
+ fun add(row: SdrWaterfall.Row) {
+ val w = width; if (w <= 0 || height <= waterTop + 8 * density) return
+ val key = row.tuned.toString() + w + row.segments.joinToString { "${it.startHz}-${it.endHz}" }
+ if (key != layoutKey) relayout(row, w, key)
+ // One value per column: the strongest bin under it, so a narrow signal never falls between pixels.
+ val values = FloatArray(w) { x ->
+ val d = row.segments[colSeg[x]].db
+ var m = -200f
+ for (k in colFrom[x]..colTo[x]) if (d[k] > m) m = d[k]
+ m
+ }
+ val median = values.copyOf().also { it.sort() }[w / 2]
+ floor = if (floor.isNaN()) median else floor + (median - floor) * (if (row.tuned) 0.05f else 0.3f)
+ spectrum = values
+ peak = peak?.let { p -> FloatArray(w) { maxOf(values[it], p[it] - (if (row.tuned) 0.15f else 1.5f)) } } ?: values.copyOf()
+ val bmp = bitmap ?: return
+ for (x in 0 until w) pixels[x] = PALETTE[(((values[x] - floor + 3f) / RANGE_DB) * 255).toInt().coerceIn(0, 255)]
+ newest = (newest - 1 + bmp.height) % bmp.height
+ bmp.setPixels(pixels, 0, w, 0, newest, w, 1)
+ rows = minOf(rows + 1, bmp.height)
+ }
+
+ private fun relayout(row: SdrWaterfall.Row, w: Int, key: String) {
+ layoutKey = key; tuned = row.tuned
+ val segs = row.segments
+ val total = segs.sumOf { it.endHz - it.startHz }.coerceAtLeast(1)
+ colSeg = IntArray(w); colFrom = IntArray(w); colTo = IntArray(w); colHz = LongArray(w)
+ val gapList = ArrayList<Int>()
+ var x0 = 0; var acc = 0L
+ segs.forEachIndexed { i, s ->
+ acc += s.endHz - s.startHz
+ val x1 = if (i == segs.lastIndex) w else (acc * w / total).toInt()
+ if (i > 0 && s.startHz > segs[i - 1].endHz + (s.endHz - s.startHz) / 20) gapList += x0
+ val bins = s.db.size
+ for (x in x0 until x1) {
+ val f0 = (x - x0).toDouble() / (x1 - x0); val f1 = (x + 1 - x0).toDouble() / (x1 - x0)
+ colSeg[x] = i
+ colFrom[x] = (f0 * bins).toInt().coerceIn(0, bins - 1)
+ colTo[x] = ((f1 * bins).toInt() - 1).coerceIn(colFrom[x], bins - 1)
+ colHz[x] = s.startHz + ((s.endHz - s.startHz) * (f0 + f1) / 2).toLong()
+ }
+ x0 = x1
+ }
+ gaps = gapList.toIntArray()
+ // The sweep gives a row every second or two: taller rows, so the history isn't a thin strip.
+ val rowPx = if (row.tuned) 1f else 4 * density
+ val h = ((height - waterTop) / rowPx).toInt().coerceAtLeast(1)
+ bitmap?.recycle()
+ bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLACK) }
+ pixels = IntArray(w); newest = 0; rows = 0; spectrum = null; peak = null; floor = Float.NaN
+ }
+
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
+ if (w != oldw || h != oldh) { layoutKey = ""; bitmap?.recycle(); bitmap = null }
+ }
+
+ override fun onDetachedFromWindow() {
+ super.onDetachedFromWindow()
+ bitmap?.recycle(); bitmap = null; layoutKey = ""
+ }
+
+ override fun onDraw(canvas: Canvas) {
+ val w = width.toFloat()
+ val top = waterTop
+ canvas.drawRect(0f, top, w, height.toFloat(), blackPaint)
+ val bmp = bitmap
+ if (bmp != null && rows > 0) {
+ // Newest row at the top: the bitmap from [newest] down, then its start.
+ val scale = (height - top) / bmp.height
+ val firstRows = minOf(rows, bmp.height - newest)
+ canvas.drawBitmap(bmp, Rect(0, newest, bmp.width, newest + firstRows),
+ android.graphics.RectF(0f, top, w, top + firstRows * scale), bitmapPaint)
+ val rest = rows - firstRows
+ if (rest > 0) canvas.drawBitmap(bmp, Rect(0, 0, bmp.width, rest),
+ android.graphics.RectF(0f, top + firstRows * scale, w, top + rows * scale), bitmapPaint)
+ }
+ for (g in gaps) canvas.drawLine(g.toFloat(), 0f, g.toFloat(), height.toFloat(), gapPaint)
+ val s = spectrum
+ if (s != null && !floor.isNaN()) {
+ val h = spectrumH - 4 * density
+ fun y(v: Float) = 2 * density + h * (1f - ((v - floor + 3f) / (RANGE_DB + 10f)).coerceIn(0f, 1f))
+ peak?.let { p -> canvas.drawPath(Path().apply { p.forEachIndexed { x, v -> if (x == 0) moveTo(0f, y(v)) else lineTo(x.toFloat(), y(v)) } }, peakPaint) }
+ canvas.drawPath(Path().apply { s.forEachIndexed { x, v -> if (x == 0) moveTo(0f, y(v)) else lineTo(x.toFloat(), y(v)) } }, linePaint)
+ }
+ drawLabels(canvas)
+ }
+
+ /** Frequencies under the spectrum: each band's start, and the right-hand end. */
+ private fun drawLabels(canvas: Canvas) {
+ if (colHz.isEmpty()) return
+ val y = spectrumH + textPaint.textSize
+ val marks = if (tuned) listOf(0, colHz.size / 2, colHz.size - 1) else (listOf(0) + gaps.toList() + (colHz.size - 1)).distinct()
+ var lastEnd = -1f
+ for ((i, x) in marks.withIndex()) {
+ val t = mhz(colHz[x])
+ val tw = textPaint.measureText(t)
+ val left = when (i) { 0 -> 0f; marks.lastIndex -> width - tw; else -> (x - tw / 2).coerceIn(0f, width - tw) }
+ if (left < lastEnd + 8 * density) continue
+ canvas.drawText(t, left, y, textPaint)
+ lastEnd = left + tw
+ }
+ }
+
+ private fun mhz(hz: Long) = String.format(Locale.US, if (tuned) "%.3f" else "%.1f", hz / 1e6)
+
+ private var downX = 0f; private var downY = 0f
+
+ @SuppressLint("ClickableViewAccessibility")
+ override fun onTouchEvent(e: MotionEvent): Boolean {
+ when (e.actionMasked) {
+ MotionEvent.ACTION_DOWN -> { downX = e.x; downY = e.y; return true }
+ MotionEvent.ACTION_UP -> if (abs(e.x - downX) < 16 * density && abs(e.y - downY) < 16 * density) {
+ val x = e.x.toInt()
+ if (x in colHz.indices) { onTap?.invoke(colHz[x]); performClick() }
+ return true
+ }
+ }
+ return super.onTouchEvent(e)
+ }
+
+ override fun performClick(): Boolean = super.performClick()
+
+ companion object {
+ /** dB above the noise floor that reach the top of the colour scale. */
+ private const val RANGE_DB = 40f
+
+ /** Black, deep blue, cyan, yellow, red, white: the usual waterfall scale. */
+ private val PALETTE = IntArray(256) { i ->
+ val stops = intArrayOf(0xFF000000.toInt(), 0xFF0A1A6E.toInt(), 0xFF0096C8.toInt(), 0xFFF0E000.toInt(), 0xFFE02000.toInt(), 0xFFFFFFFF.toInt())
+ val p = i / 255f * (stops.size - 1)
+ val k = p.toInt().coerceAtMost(stops.size - 2); val f = p - k
+ val a = stops[k]; val b = stops[k + 1]
+ fun mix(sh: Int) = (((a shr sh) and 0xff) * (1 - f) + ((b shr sh) and 0xff) * f).toInt()
+ Color.rgb(mix(16), mix(8), mix(0))
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
index aae51a6..ee37470 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
@@ -25,6 +25,8 @@ class MonitorFrames {
var hidden = false
/** A client that sent wildcard probe requests; with the Flock-camera Wi-Fi Alliance element. */
var wildcard = false; var flockIe = false
+ /** How steadily it sends wildcard probes ([com.rfsentinel.app.detect.ProbeBehaviour]). */
+ var probeRate: com.rfsentinel.app.detect.ProbeBehaviour.Counter? = null
// Per-window counters for driver diagnostics (debug builds).
var winHits = 0; var winMeasured = 0; var winMax = -128; var winSum = 0L
var winOfdm = 0; var winA = -128; var winB = -128
@@ -103,7 +105,10 @@ class MonitorFrames {
4 -> if (captureClients && !isScannerProbe(b, d, end)) touch(a2, ap = false)?.let { s ->
val ies = Ies.read(b, d + 24, end)
ies.wps?.let { s.wps = it }
- if (ies.wildcard) s.wildcard = true
+ if (ies.wildcard) {
+ s.wildcard = true
+ (s.probeRate ?: com.rfsentinel.app.detect.ProbeBehaviour.Counter().also { s.probeRate = it }).probe(now)
+ }
if (ies.flockIe) s.flockIe = true
ProbeIntel.fingerprint(b, d + 24, end)?.let { s.fingerprint = it }
ProbeIntel.skeletonHash(b, d + 24, ProbeIntel.withoutFcs(b, d, end))?.let { s.skeleton = it }
@@ -177,7 +182,8 @@ class MonitorFrames {
probeSkeleton = s.skeleton,
hiddenNetwork = s.hidden,
wildcardProbe = s.wildcard,
- flockProbeIe = s.flockIe
+ flockProbeIe = s.flockIe,
+ probeRun = s.probeRate?.run()
)
}
sightings.entries.removeAll { now - it.value.lastSeen > pruneMs }
diff --git a/app/src/main/java/com/rfsentinel/app/usb/ProbeIntel.kt b/app/src/main/java/com/rfsentinel/app/usb/ProbeIntel.kt
index f45b6eb..a8121d0 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/ProbeIntel.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/ProbeIntel.kt
@@ -132,5 +132,8 @@ object ProbeIntel {
fun of(mac: String): Record? = byMac[mac.uppercase()]
+ /** Addresses heard this session whose probe requests have the fingerprint [fp]. */
+ fun sharing(fp: String): Int = byMac.values.count { it.fingerprint == fp }
+
fun clear() = byMac.clear()
}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
index 6598eee..046164f 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -34,7 +34,9 @@ data class MonitorSighting(
/** A client that sent wildcard probe requests (no network name). */
val wildcardProbe: Boolean = false,
/** Its probe requests carried the Wi-Fi Alliance element Flock cameras send ([MonitorFrames.Ies.flockIe]). */
- val flockProbeIe: Boolean = false
+ val flockProbeIe: Boolean = false,
+ /** Its latest run of wildcard probes: how steadily it probes ([com.rfsentinel.app.detect.ProbeBehaviour]). */
+ val probeRun: com.rfsentinel.app.detect.ProbeBehaviour.Run? = null
)
/**
diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xml
index c08f77b..3d76a6f 100644
--- a/app/src/main/res/layout/activity_device_detail.xml
+++ b/app/src/main/res/layout/activity_device_detail.xml
@@ -147,6 +147,12 @@
android:layout_height="wrap_content"
android:layout_marginTop="4dp">
+ <com.google.android.material.chip.Chip
+ android:id="@+id/actionLearn"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="I saw it" />
+
<com.google.android.material.chip.Chip
android:id="@+id/actionWhitelist"
android:layout_width="wrap_content"
diff --git a/app/src/main/res/layout/activity_waterfall.xml b/app/src/main/res/layout/activity_waterfall.xml
new file mode 100644
index 0000000..eb9463c
--- /dev/null
+++ b/app/src/main/res/layout/activity_waterfall.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:padding="16dp">
+
+ <TextView
+ android:id="@+id/statusText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:textSize="@dimen/text_body" />
+
+ <TextView
+ android:id="@+id/hintText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="2dp"
+ android:layout_marginBottom="8dp"
+ android:textColor="?android:attr/textColorSecondary"
+ android:textSize="@dimen/text_caption" />
+
+ <com.rfsentinel.app.ui.WaterfallView
+ android:id="@+id/waterfall"
+ android:layout_width="match_parent"
+ android:layout_height="0dp"
+ android:layout_weight="1"
+ android:contentDescription="Radio waterfall: tap to zoom in on a frequency" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:orientation="horizontal">
+
+ <com.google.android.material.button.MaterialButton
+ android:id="@+id/tuneButton"
+ style="?attr/materialButtonOutlinedStyle"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="Tune" />
+
+ <com.google.android.material.button.MaterialButton
+ android:id="@+id/sweepButton"
+ android:layout_width="0dp"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="8dp"
+ android:layout_weight="1"
+ android:text="Back to sweep" />
+ </LinearLayout>
+</LinearLayout>
diff --git a/app/src/test/java/com/rfsentinel/app/detect/ProbeBehaviourTest.kt b/app/src/test/java/com/rfsentinel/app/detect/ProbeBehaviourTest.kt
new file mode 100644
index 0000000..89bfe4a
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/detect/ProbeBehaviourTest.kt
@@ -0,0 +1,86 @@
+package com.rfsentinel.app.detect
+
+import com.rfsentinel.app.usb.MonitorFrames
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Non-stop wildcard probing (FlipDeFlock): a supporting clue for a fixed camera, never a match alone. */
+class ProbeBehaviourTest {
+
+ private fun counted(vararg at: Long) = ProbeBehaviour.Counter().apply { at.forEach { probe(it) } }.run()!!
+
+ @Test
+ fun countsTheWindowsThatHeldAProbe() {
+ // Probes every 5 s for 3 minutes, as a pole camera does; a few missed while the adapter hopped.
+ val times = (0L..180_000L step 5_000L).filter { it % 35_000L != 0L }
+ val run = counted(*times.toLongArray())
+ assertEquals(times.size, run.probes)
+ assertTrue(run.coverage.toString(), run.coverage > 0.8)
+ assertTrue(run.nonStop)
+ assertTrue(run.describe(), run.describe().contains("per 8 s") && run.describe().contains("2 min"))
+ }
+
+ @Test
+ fun aPhoneThatProbesInBurstsIsNotNonStop() {
+ // A burst every 40 s: the run goes on, but most 8 s windows stay empty.
+ val times = (0L..240_000L step 40_000L).flatMap { listOf(it, it + 200, it + 400) }
+ val run = counted(*times.toLongArray())
+ assertFalse(run.coverage.toString(), run.nonStop)
+ }
+
+ @Test
+ fun aLongSilenceStartsANewRun() {
+ val run = counted(0L, 5_000L, 10_000L, 10_000L + ProbeBehaviour.BREAK_MS + 1, 10_000L + ProbeBehaviour.BREAK_MS + 2_000)
+ assertEquals(2, run.probes)
+ assertFalse("a short run is never non-stop", run.nonStop)
+ }
+
+ private fun camera(mac: String, run: ProbeBehaviour.Run?, at: Long) = Advert(mac = mac, source = Advert.Source.WIFI, rssi = -70,
+ wifi = Advert.WifiInfo(2437, "", null, emptyList(), client = true, wildcardProbe = true, probeRun = run), timestamp = at)
+
+ private val flock = Hit(Category.ALPR, "Possible Flock camera (probe request)", 60, "module", "test")
+ private val steady = ProbeBehaviour.Run(probes = 60, firstAt = 0L, lastAt = 180_000L, windows = 22)
+
+ @Test
+ fun nonStopProbingBacksUpAFixedCameraMatch() {
+ val a = camera("24:B2:B9:33:44:55", steady, 181_000L)
+ val support = ProbeBehaviour.supportHit(a, listOf(flock))
+ assertNotNull(support)
+ assertEquals(Category.ALPR, support!!.category)
+ assertEquals(ProbeBehaviour.CONFIDENCE, support.confidence)
+ val fused = EvidenceFusion.fuse(listOf(flock, support)).first()
+ assertTrue("${fused.confidence}", fused.confidence > flock.confidence)
+ }
+
+ @Test
+ fun itIsNeverAMatchAlone() {
+ val a = camera("24:B2:B9:33:44:55", steady, 181_000L)
+ assertNull("no camera match to back up", ProbeBehaviour.supportHit(a, emptyList()))
+ assertNull("a tracker isn't a fixed device", ProbeBehaviour.supportHit(a, listOf(flock.copy(category = Category.TRACKER))))
+ assertNull("random addresses: a phone", ProbeBehaviour.supportHit(camera("DA:11:22:33:44:55", steady, 181_000L), listOf(flock)))
+ assertNull("the run ended long ago", ProbeBehaviour.supportHit(camera("24:B2:B9:33:44:55", steady, 600_000L), listOf(flock)))
+ assertNull("not steady", ProbeBehaviour.supportHit(camera("24:B2:B9:33:44:55", steady.copy(windows = 4), 181_000L), listOf(flock)))
+ }
+
+ @Test
+ fun theAdapterReportsHowSteadilyAClientProbes() {
+ val f = MonitorFrames()
+ // A wildcard probe request with extended rates and a vendor element (not a bare scanner probe).
+ val ies = byteArrayOf(0, 0, 1, 4, 0x82.toByte(), 0x84.toByte(), 0x8B.toByte(), 0x96.toByte(),
+ 0x32, 4, 0x0C, 0x12, 0x18, 0x60, 0xDD.toByte(), 7, 0x50, 0x6F, 0x9A.toByte(), 0x16, 3, 1, 3)
+ val frame = ByteArray(24).also {
+ it[0] = 0x40
+ byteArrayOf(0x24, 0xB2.toByte(), 0xB9.toByte(), 0x33, 0x44, 0x55).copyInto(it, 10)
+ } + ies
+ for (t in 0L..150_000L step 4_000L) f.frame(frame, 0, frame.size, 6, -60, now = t)
+ val s = f.drain(150_000L, 10_000L).single()
+ val run = s.probeRun!!
+ assertTrue(s.wildcardProbe)
+ assertEquals(38, run.probes)
+ assertTrue(run.nonStop)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/oui/AdvertRuleTest.kt b/app/src/test/java/com/rfsentinel/app/oui/AdvertRuleTest.kt
new file mode 100644
index 0000000..23e80e0
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/oui/AdvertRuleTest.kt
@@ -0,0 +1,48 @@
+package com.rfsentinel.app.oui
+
+import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.detect.AdvertFingerprint
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** "adv:" rules: a Bluetooth device's advert pattern, learned with "I saw it", whatever its address. */
+class AdvertRuleTest {
+
+ private fun ble(mac: String, name: String? = "BWC-1234", mfg: Map<Int, ByteArray> = mapOf(0x0A1B to ByteArray(6))) =
+ Advert(mac = mac, source = Advert.Source.BLE, rssi = -60, name = name, manufacturerData = mfg)
+
+ @Test
+ fun advertRulesAreValidKeys() {
+ assertTrue(OuiWatchlist.isValidKey("adv:1a2b3c4d"))
+ assertTrue(!OuiWatchlist.isValidKey("adv: "))
+ assertEquals("adv:1a2b3c4d", OuiWatchlist.normalizeKey("ADV: 1A2B3C4D "))
+ assertTrue(OuiEntry("adv:1a2b3c4d", "x").isAdvertRule)
+ assertTrue(!OuiEntry("adv:1a2b3c4d", "x").isFingerprintRule)
+ }
+
+ @Test
+ fun theKeyStaysTheSameWhenTheAddressChanges() {
+ val k = AdvertFingerprint.key(ble("C1:11:22:33:44:55"))!!
+ assertTrue(k, Regex("[0-9a-f]{8}").matches(k))
+ assertEquals(k, AdvertFingerprint.key(ble("D2:66:77:88:99:AA")))
+ assertNotEquals(k, AdvertFingerprint.key(ble("C1:11:22:33:44:55", name = "Other")))
+ }
+
+ @Test
+ fun anAdvertThatSaysNothingHasNoKey() {
+ assertNull("Apple-only adverts: every iPhone looks alike", AdvertFingerprint.key(ble("C1:11:22:33:44:55", null, mapOf(0x004C to ByteArray(10)))))
+ assertNull("WiFi has none", AdvertFingerprint.key(Advert(mac = "C1:11:22:33:44:55", source = Advert.Source.WIFI, rssi = -60, name = "x")))
+ }
+
+ @Test
+ fun aLearnedPatternIsAProbableMatchNotAStrongOne() {
+ val e = OuiEntry("adv:1a2b3c4d", "Pole camera", OuiEntry.LEARNED, "custom", com.rfsentinel.app.ui.DeviceActions.LEARNED_SCORE, "ALPR")
+ val hit = e.toHit("x")
+ assertEquals(60, hit.confidence)
+ assertEquals(com.rfsentinel.app.detect.Category.ALPR, hit.category)
+ assertEquals("an exact address stays certain", 100, OuiEntry("AA:BB:CC:DD:EE:FF", "Pole camera", OuiEntry.LEARNED, "custom").effectiveScore)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt
new file mode 100644
index 0000000..04bb802
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt
@@ -0,0 +1,27 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The waterfall's rows: the usable middle of a chunk, with the receiver's own centre spike levelled. */
+class SdrWaterfallTest {
+
+ @Test
+ fun aSegmentIsTheMiddleOfTheChunkWithoutTheCentreSpike() {
+ val n = 1024; val rate = 2_048_000 // 2 kHz per bin
+ val psd = FloatArray(n) { -60f }
+ psd[n / 2] = 0f; psd[n / 2 + 3] = -10f // DC spike, and its skirt inside the guard
+ psd[n / 2 + 200] = -20f // a real signal 400 kHz up
+ val s = SdrWaterfall.segment(155_000_000L, psd, rate, RadioWatch.USABLE_HZ, "VHF")
+ assertEquals(155_000_000L - 800_000L, s.startHz)
+ assertEquals(155_000_000L + 800_000L, s.endHz)
+ assertEquals(801, s.db.size)
+ val mid = s.db.size / 2
+ assertEquals("spike levelled to the noise beside it", -60f, s.db[mid], 0f)
+ assertEquals(-60f, s.db[mid + 3], 0f)
+ assertEquals("a real signal stays", -20f, s.db[mid + 200], 0f)
+ assertEquals("VHF", s.band)
+ assertTrue("the input is left alone", psd[n / 2] == 0f)
+ }
+}