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.

RTL-SDR radio activity detector; GNSS jamming / spoofing detection

CIS-C03eaf5086ae56
diff --git a/README.md b/README.md
index 152765d..090addd 100644
--- a/README.md
+++ b/README.md
@@ -395,6 +395,26 @@ compares both paths on the first seconds of traffic and moves 2.4 GHz reception
to the one with the antenna (about 30 dB better on the dongle we tested - more
than Realtek's own Windows driver gets from it).
+### RTL-SDR: two-way radio transmitting nearby
+
+Plug an RTL-SDR dongle (R820T / R820T2 / R860 tuner, e.g. RTL-SDR Blog V3, or the
+RTL-SDR Blog V4) into the phone with an OTG cable while scanning. RF Sentinel
+sweeps the North American public-safety radio bands - the 700 and 800 MHz bands
+where police, fire and EMS radios (not towers) transmit, and the shared VHF / UHF
+land-mobile bands - and measures only **how much energy each 12.5 kHz channel
+carries**. Nothing is demodulated, decoded, recorded or decrypted: it can't know
+what was said or who said it.
+
+It first learns which channels are busy all the time where you are (towers,
+repeaters, trunking control channels, pagers) and ignores them; a strong burst on
+a normally quiet channel means a radio is transmitting close by, and raises a
+**Two-way radio transmitting nearby** alert (category *RADIO*, can be switched off
+in Settings). On 700 / 800 MHz that's a probable sign of a public-safety radio; on
+VHF / UHF, which businesses, schools and transit share, only a very strong signal
+counts, and only as a weak sign. Consumer walkie-talkies (FRS / GMRS, MURS),
+marine, railroad, weather and paging channels are skipped. The dongle's log is in
+the exported USB adapter log.
+
**Requested networks** (Menu → *Requested networks*): phones and laptops ask by
name for networks they joined before. With an adapter or a Marauder board
plugged in, RF Sentinel can keep these names (off by default: they're other
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 29b14d7..b9b78b4 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -70,6 +70,7 @@
<activity android:name=".probes.ProbeListActivity" android:exported="false" />
<activity android:name=".ui.DetectionLogActivity" android:exported="false" />
<activity android:name=".ui.CellTowersActivity" android:exported="false" />
+ <activity android:name=".ui.GnssActivity" android:exported="false" />
<activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" />
<activity
android:name=".ui.SetupActivity"
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 1f4bd48..66c0065 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -111,10 +111,12 @@ class MainActivity : AppCompatActivity() {
menu.add(0, 1, 0, "Cell towers")
menu.add(0, 2, 1, "WiFi channels")
menu.add(0, 3, 2, "WiFi spectrum")
+ menu.add(0, 4, 3, "Satellites (GPS, Galileo, GLONASS, BeiDou)")
setOnMenuItemClickListener { item ->
when (item.itemId) {
1 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.CellTowersActivity::class.java))
2 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java))
+ 4 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.GnssActivity::class.java))
else -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WifiAnalyzerActivity::class.java)
.putExtra(com.rfsentinel.app.ui.WifiAnalyzerActivity.EXTRA_SPECTRUM, true))
}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/Category.kt b/app/src/main/java/com/rfsentinel/app/detect/Category.kt
index 82c4052..fff8a0f 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/Category.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/Category.kt
@@ -20,6 +20,8 @@ enum class Category(
GLASSES("Smart / recording glasses", "GLASSES", 0xFF00796B.toInt(), true),
NETWORK_CAMERA("Network / home security camera", "CAMERA", 0xFF5D6D7E.toInt(), false),
CELL_ANOMALY("Fake cell tower signs (IMSI catcher)", "CELL", 0xFF7B1FA2.toInt(), true),
+ GNSS("GPS / satellite jamming or spoofing signs", "GNSS", 0xFF00838F.toInt(), true),
+ RADIO("Two-way radio transmitting nearby (needs an RTL-SDR)", "RADIO", 0xFF0277BD.toInt(), true),
CUSTOM("Your watchlist", "WATCHLIST", 0xFFC8431A.toInt(), true);
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt b/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt
new file mode 100644
index 0000000..59f03b8
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/detect/GnssAnalyzer.kt
@@ -0,0 +1,190 @@
+package com.rfsentinel.app.detect
+
+import kotlin.math.abs
+import kotlin.math.sqrt
+
+/**
+ * Signs of GNSS jamming and spoofing, from what the phone's satellite receiver already
+ * reports for every system it tracks (GPS, GLONASS, Galileo, BeiDou, QZSS, NavIC, SBAS):
+ * each satellite's signal strength (C/N0) and height in the sky, the receiver's input
+ * gain (AGC), and its fixes. Passive: nothing is transmitted.
+ *
+ * - Jamming: the noise the receiver sees jumps (its AGC drops) while every satellite
+ * weakens together. A tunnel or a garage weakens the satellites too, but doesn't raise
+ * the noise, so it isn't mistaken for jamming. Without an AGC reading (some phones
+ * don't report one) a sudden total loss is only logged as a weak sign.
+ * - Spoofing: one fake transmitter makes every satellite equally strong whatever its
+ * height; its clock or position can jump; and cheap spoofers fake GPS only, so the other
+ * systems vanish while "GPS" stays strong.
+ * These are signs, not proof.
+ */
+class GnssAnalyzer {
+
+ enum class System(val label: String) {
+ GPS("GPS"), SBAS("SBAS"), GLONASS("GLONASS"), QZSS("QZSS"), BEIDOU("BeiDou"),
+ GALILEO("Galileo"), NAVIC("NavIC"), OTHER("Other");
+
+ companion object {
+ /** From android.location.GnssStatus.CONSTELLATION_* */
+ fun of(constellation: Int) = when (constellation) {
+ 1 -> GPS; 2 -> SBAS; 3 -> GLONASS; 4 -> QZSS; 5 -> BEIDOU; 6 -> GALILEO; 7 -> NAVIC; else -> OTHER
+ }
+ }
+ }
+
+ data class Sat(val system: System, val svid: Int, val cn0: Float, val elevation: Float, val usedInFix: Boolean,
+ val carrierMhz: Float? = null)
+
+ /** One receiver report: the satellites, and the input gain when the phone reports it. */
+ data class Snapshot(val time: Long, val sats: List<Sat>, val agcDb: Double? = null)
+
+ /** A GNSS fix with the phone's (network) clock when it arrived. */
+ data class Fix(val gnssTime: Long, val systemTime: Long, val lat: Double, val lon: Double, val accuracyM: Float)
+
+ data class Anomaly(val key: String, val title: String, val detail: String, val confidence: Int)
+
+ // Baselines learned while the sky is clear: strongest-4 average C/N0, AGC, systems tracked.
+ private var cn0Base: Double? = null
+ private var agcBase: Double? = null
+ private val systemsSeen = HashMap<System, Long>()
+ private var jamSince = 0L
+ private var lossSince = 0L
+ private var uniformSince = 0L
+ private var gpsOnlySince = 0L
+ private var lastFix: Fix? = null
+ private val lastAlert = HashMap<String, Long>()
+
+ /** The latest state in words, for the satellite screen. */
+ var verdict: String = "Waiting for satellites…"; private set
+
+ fun onSnapshot(s: Snapshot): List<Anomaly> {
+ val out = ArrayList<Anomaly>()
+ val tracked = s.sats.filter { it.cn0 > 0f }
+ val top4 = tracked.map { it.cn0.toDouble() }.sortedDescending().take(4)
+ val strength = if (top4.isEmpty()) 0.0 else top4.average()
+ val clearSky = tracked.count { it.cn0 >= 30f } >= 6
+
+ // ---- jamming ----
+ val agcDrop = if (s.agcDb != null && agcBase != null) agcBase!! - s.agcDb else null
+ val cn0Drop = cn0Base?.let { it - strength }
+ val jammed = agcDrop != null && agcDrop >= AGC_JAM_DB && (cn0Drop ?: 0.0) >= CN0_JAM_DB
+ if (jammed) {
+ if (jamSince == 0L) jamSince = s.time
+ if (s.time - jamSince >= SUSTAIN_MS) report(out, s.time, "jam",
+ "GNSS jamming signs",
+ "The satellite receiver's noise rose by ${fmt(agcDrop!!)} dB while every satellite weakened by ${fmt(cn0Drop!!)} dB " +
+ "(${systems(tracked)}). A jammer nearby, often a cheap \"GPS blocker\" in a vehicle, does this; a tunnel doesn't raise the noise.",
+ if (agcDrop >= 10) 75 else 60)
+ } else jamSince = 0L
+
+ // Total loss without an AGC reading: can't tell a jammer from a roof, so only a weak sign.
+ val lost = s.agcDb == null && cn0Base != null && cn0Base!! >= 35 && tracked.count { it.cn0 >= 20f } == 0
+ if (lost) {
+ if (lossSince == 0L) lossSince = s.time
+ if (s.time - lossSince >= SUSTAIN_MS) report(out, s.time, "loss", "All satellite signals lost at once",
+ "Every satellite system dropped out together after a clear sky. A jammer can do this, but so can a tunnel or a " +
+ "building; this phone doesn't report the receiver noise that would tell them apart.", 25)
+ } else lossSince = 0L
+
+ // ---- spoofing: every satellite the same strength whatever its height ----
+ val strong = tracked.filter { it.cn0 >= 25f }
+ if (strong.size >= 6) {
+ val cn = strong.map { it.cn0.toDouble() }
+ val mean = cn.average()
+ val sd = sqrt(cn.sumOf { (it - mean) * (it - mean) } / cn.size)
+ val corr = correlation(strong.map { it.elevation.toDouble() }, cn)
+ if (sd < UNIFORM_SD_DB && mean >= 38) {
+ if (uniformSince == 0L) uniformSince = s.time
+ if (s.time - uniformSince >= SUSTAIN_MS) report(out, s.time, "uniform", "GNSS spoofing signs",
+ "${strong.size} satellites all arrive at almost the same strength (${fmt(mean)} dB-Hz, spread ${fmt(sd)} dB) " +
+ "whatever their height in the sky. Real satellites near the horizon are weaker; one fake transmitter " +
+ "makes them all alike.", if (corr < 0.1) 65 else 50)
+ } else uniformSince = 0L
+ } else uniformSince = 0L
+
+ // ---- spoofing: GPS stays strong while the other systems vanish ----
+ val now = s.time
+ val present = tracked.filter { it.cn0 >= 20f }.map { it.system }.toSet()
+ for (sys in present) systemsSeen[sys] = now
+ val othersRecently = systemsSeen.filter { (sys, t) -> sys != System.GPS && sys != System.SBAS && sys != System.QZSS && now - t < 10 * 60_000L }.keys
+ val gpsStrong = tracked.count { it.system == System.GPS && it.cn0 >= 30f } >= 4
+ val othersGone = othersRecently.isNotEmpty() && othersRecently.none { it in present }
+ if (gpsStrong && othersGone && cn0Base != null) {
+ if (gpsOnlySince == 0L) gpsOnlySince = s.time
+ if (s.time - gpsOnlySince >= SUSTAIN_MS) report(out, s.time, "gpsonly", "GNSS spoofing signs",
+ "GPS is still strong, but ${othersRecently.joinToString { it.label }} - tracked a few minutes ago - vanished at once. " +
+ "Most spoofers fake GPS only.", 50)
+ } else gpsOnlySince = 0L
+
+ // ---- learn the baselines on a normal, clear sky ----
+ if (clearSky && !jammed && uniformSince == 0L) {
+ cn0Base = cn0Base?.let { it + (strength - it) * 0.05 } ?: strength
+ s.agcDb?.let { a -> agcBase = agcBase?.let { it + (a - it) * 0.05 } ?: a }
+ }
+
+ verdict = when {
+ out.isNotEmpty() -> out.first().title
+ jammed || lost || uniformSince != 0L || gpsOnlySince != 0L -> "Checking an unusual reading…"
+ tracked.isEmpty() -> "No satellites heard (indoors?)"
+ cn0Base == null -> "Learning this sky…"
+ else -> "No jamming or spoofing signs"
+ }
+ return out
+ }
+
+ /** Spoofing: GNSS time far from network time, or a jump no vehicle could make. */
+ fun onFix(f: Fix): List<Anomaly> {
+ val out = ArrayList<Anomaly>()
+ val skew = abs(f.gnssTime - f.systemTime) / 1000
+ if (skew >= TIME_SKEW_S) report(out, f.systemTime, "time", "GNSS spoofing signs",
+ "The satellite clock says ${skew} s ${if (f.gnssTime > f.systemTime) "ahead of" else "behind"} the network time. " +
+ "Spoofers often shift the time.", 55)
+ lastFix?.let { p ->
+ val dt = (f.gnssTime - p.gnssTime) / 1000.0
+ if (dt in 0.5..120.0) {
+ val d = distanceM(p.lat, p.lon, f.lat, f.lon) - p.accuracyM - f.accuracyM
+ if (d / dt > MAX_SPEED_MPS) report(out, f.systemTime, "jump", "GNSS spoofing signs",
+ "The position jumped ${fmt(d / 1000)} km in ${fmt(dt)} s (${(d / dt * 3.6).toInt()} km/h). " +
+ "No car or plane moves like that; a spoofer moving the fake position can.", 55)
+ }
+ }
+ lastFix = f
+ return out
+ }
+
+ private fun report(out: MutableList<Anomaly>, now: Long, key: String, title: String, detail: String, confidence: Int) {
+ if (now - (lastAlert[key] ?: Long.MIN_VALUE / 2) < REPEAT_MS) return
+ lastAlert[key] = now
+ out += Anomaly(key, title, detail, confidence)
+ }
+
+ private fun systems(sats: List<Sat>) = sats.map { it.system.label }.distinct().joinToString().ifEmpty { "no satellites left" }
+
+ companion object {
+ const val SUSTAIN_MS = 4_000L
+ private const val REPEAT_MS = 10 * 60_000L
+ private const val AGC_JAM_DB = 6.0
+ private const val CN0_JAM_DB = 8.0
+ private const val UNIFORM_SD_DB = 1.5
+ private const val TIME_SKEW_S = 20L
+ private const val MAX_SPEED_MPS = 340.0
+
+ private fun fmt(v: Double) = "%.1f".format(java.util.Locale.US, v)
+
+ fun correlation(x: List<Double>, y: List<Double>): Double {
+ if (x.size < 3) return 1.0
+ val mx = x.average(); val my = y.average()
+ var sxy = 0.0; var sxx = 0.0; var syy = 0.0
+ for (i in x.indices) { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) * (x[i] - mx); syy += (y[i] - my) * (y[i] - my) }
+ return if (sxx == 0.0 || syy == 0.0) 0.0 else sxy / sqrt(sxx * syy)
+ }
+
+ fun distanceM(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
+ val r = 6_371_000.0
+ val dLat = Math.toRadians(lat2 - lat1); val dLon = Math.toRadians(lon2 - lon1)
+ val a = kotlin.math.sin(dLat / 2).let { it * it } +
+ kotlin.math.cos(Math.toRadians(lat1)) * kotlin.math.cos(Math.toRadians(lat2)) * kotlin.math.sin(dLon / 2).let { it * it }
+ return 2 * r * kotlin.math.asin(sqrt(a))
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
new file mode 100644
index 0000000..aff7ba7
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
@@ -0,0 +1,200 @@
+package com.rfsentinel.app.sdr
+
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.log10
+import kotlin.math.roundToInt
+import kotlin.math.sin
+
+/**
+ * Two-way radio activity on the North American public-safety bands, from an RTL-SDR's
+ * power spectrum only: how much energy each 12.5 kHz channel carries. Nothing is
+ * demodulated, decoded, recorded or decrypted - it can't tell what is said or who says
+ * it, only that a radio is transmitting, and roughly how close.
+ *
+ * Towers, repeaters and trunking control channels are on the air all the time and
+ * everywhere; a handheld or car radio is only strong close by. So it learns which
+ * channels are busy most of the time and ignores them, and reports a strong burst on
+ * a quiet channel. The 700 / 800 MHz bands it watches are where public-safety radios
+ * (not towers) transmit; on the shared VHF / UHF bands businesses, schools and transit
+ * use the same kind of radios, so those count as weak signs unless very strong.
+ */
+class RadioWatch {
+
+ enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED }
+
+ data class Band(val label: String, val startHz: Long, val endHz: Long, val kind: Kind)
+
+ /** A strong transmission on a normally quiet channel. */
+ data class Event(val freqHz: Long, val snrDb: Int, val band: Band, val confidence: Int) {
+ val mhz: String get() = "%.4f".format(java.util.Locale.US, freqHz / 1e6)
+ }
+
+ private class Channel {
+ var visits = 0
+ /** The last 32 visits, 1 = energy on the channel. */
+ var recent = 0L
+ var lastEvent = Long.MIN_VALUE / 2 // never reported
+ fun busyRatio(): Double {
+ val n = minOf(visits, 32)
+ return if (n == 0) 0.0 else java.lang.Long.bitCount(recent and ((1L shl n) - 1)).toDouble() / n
+ }
+ }
+
+ private val channels = HashMap<Long, Channel>()
+ var sweeps = 0; private set
+
+ val learnedChannels: Int get() = channels.size
+ /** Channels busy most of the time (towers, control channels, pagers): never reported. */
+ val busyChannels: Int get() = channels.values.count { it.visits >= MIN_VISITS_BUSY && it.busyRatio() >= BUSY_RATIO }
+
+ fun sweepDone() { sweeps++ }
+
+ /**
+ * One tuned chunk: [psdDb] is the averaged power spectrum (FFT-shifted, DC in the middle)
+ * at [centerHz] and [sampleRate]. Returns the transmissions worth reporting.
+ */
+ fun analyze(centerHz: Long, psdDb: FloatArray, sampleRate: Int, now: Long): List<Event> {
+ val n = psdDb.size
+ val binHz = sampleRate.toDouble() / n
+ val usableBins = (USABLE_HZ / binHz).toInt()
+ val floor = median(FloatArray(2 * usableBins) { psdDb[(n / 2 - usableBins + it).coerceIn(0, n - 1)] })
+ val half = maxOf(1, (CHANNEL_HALF_HZ / binHz).roundToInt())
+ val found = ArrayList<Event>()
+ for (band in BANDS) {
+ var f = ((maxOf(band.startHz, centerHz - USABLE_HZ.toLong()) + STEP_HZ - 1) / STEP_HZ) * STEP_HZ
+ val last = minOf(band.endHz, centerHz + USABLE_HZ.toLong())
+ while (f <= last) {
+ val off = f - centerHz
+ if (kotlin.math.abs(off) > DC_GUARD_HZ && !excluded(f)) {
+ val mid = n / 2 + (off / binHz).roundToInt()
+ var p = -200f
+ for (k in mid - half..mid + half) if (k in 0 until n && psdDb[k] > p) p = psdDb[k]
+ val snr = (p - floor).roundToInt()
+ val ch = channels.getOrPut(f) { Channel() }
+ val active = snr >= ACTIVE_DB
+ ch.recent = (ch.recent shl 1) or (if (active) 1L else 0L)
+ ch.visits++
+ if (active) eventFor(f, snr, band, ch, now)?.let { found += it }
+ }
+ f += STEP_HZ
+ }
+ }
+ // A strong signal spills into the channels next to it: keep the strongest of a cluster.
+ val kept = found.sortedByDescending { it.snrDb }.fold(ArrayList<Event>()) { acc, e ->
+ if (acc.none { kotlin.math.abs(it.freqHz - e.freqHz) <= SPLATTER_HZ }) acc += e
+ acc
+ }
+ for (e in kept) channels[e.freqHz]?.lastEvent = now
+ return kept
+ }
+
+ private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long): Event? {
+ if (sweeps < LEARN_SWEEPS) return null // still learning what's always there
+ if (ch.visits >= MIN_VISITS_BUSY && ch.busyRatio() >= BUSY_RATIO) return null // tower / control channel / pager
+ if (now - ch.lastEvent < REPEAT_MS) return null
+ val confidence = when (band.kind) {
+ Kind.PUBLIC_SAFETY_MOBILE -> when { snr >= 40 -> 75; snr >= 30 -> 60; else -> return null }
+ Kind.SHARED -> when { snr >= 45 -> 55; snr >= 35 -> 35; else -> return null }
+ }
+ return Event(f, snr, band, confidence)
+ }
+
+ companion object {
+ const val STEP_HZ = 12_500L
+ 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
+ private const val ACTIVE_DB = 12
+ private const val SPLATTER_HZ = 37_500L
+ private const val BUSY_RATIO = 0.4
+ private const val MIN_VISITS_BUSY = 6
+ private const val LEARN_SWEEPS = 6 // = MIN_VISITS_BUSY: no alert before always-on channels are known
+ private const val REPEAT_MS = 120_000L
+
+ /** North American (FCC) public-safety land-mobile bands. */
+ val BANDS = listOf(
+ Band("700 MHz public-safety radio band", 799_000_000L, 805_000_000L, Kind.PUBLIC_SAFETY_MOBILE),
+ // 806-814 MHz: public-safety radios after the 800 MHz rebanding; LTE phones start at 814.
+ Band("800 MHz public-safety radio band", 806_000_000L, 813_900_000L, Kind.PUBLIC_SAFETY_MOBILE),
+ Band("VHF land-mobile band", 150_800_000L, 174_000_000L, Kind.SHARED),
+ Band("UHF land-mobile band", 450_000_000L, 470_000_000L, Kind.SHARED)
+ )
+
+ /** Consumer, marine, railroad, weather and paging channels - never police radios. */
+ private val EXCLUDED = listOf(
+ 151_815_000L..151_945_000L, 154_565_000L..154_605_000L, // MURS
+ 156_000_000L..157_450_000L, 160_600_000L..162_025_000L, // marine VHF
+ 159_810_000L..161_565_000L, // railroad
+ 162_400_000L..162_550_000L, // NOAA weather radio
+ 462_537_500L..462_737_500L, 467_537_500L..467_737_500L // FRS / GMRS walkie-talkies
+ ) + listOf(152_007_500L, 152_240_000L, 152_480_000L, 157_740_000L, 158_100_000L, 158_700_000L) // paging
+ .map { it - 6_250L..it + 6_250L }
+
+ fun excluded(hz: Long) = EXCLUDED.any { hz in it }
+
+ /** Tuning plan: chunk centres covering every band with the usable middle of the spectrum. */
+ fun plan(): List<Long> = BANDS.flatMap { b ->
+ val step = (2 * USABLE_HZ).toLong()
+ generateSequence(b.startHz + step / 2) { it + step }.takeWhile { it - step / 2 < b.endHz }.toList()
+ }
+
+ private fun median(a: FloatArray): Float { a.sort(); return if (a.isEmpty()) 0f else a[a.size / 2] }
+
+ /**
+ * Averaged power spectrum in dB of [count] unsigned 8-bit I/Q pairs from [iq], in
+ * [n]-point Hann-windowed FFTs, FFT-shifted so DC sits at index n/2.
+ */
+ fun powerSpectrum(iq: ByteArray, count: Int, n: Int = 1024): FloatArray {
+ val acc = DoubleArray(n)
+ val re = DoubleArray(n); val im = DoubleArray(n)
+ val win = DoubleArray(n) { 0.5 - 0.5 * cos(2 * PI * it / (n - 1)) }
+ var frames = 0
+ var s = 0
+ while (s + n <= count) {
+ for (k in 0 until n) {
+ re[k] = ((iq[2 * (s + k)].toInt() and 0xff) - 127.5) / 127.5 * win[k]
+ im[k] = ((iq[2 * (s + k) + 1].toInt() and 0xff) - 127.5) / 127.5 * win[k]
+ }
+ fft(re, im)
+ for (k in 0 until n) acc[k] += re[k] * re[k] + im[k] * im[k]
+ frames++; s += n
+ }
+ return FloatArray(n) { k ->
+ val v = acc[(k + n / 2) % n] / maxOf(1, frames)
+ (10 * log10(v + 1e-20)).toFloat()
+ }
+ }
+
+ /** In-place iterative radix-2 FFT. */
+ private fun fft(re: DoubleArray, im: DoubleArray) {
+ val n = re.size
+ var j = 0
+ for (i in 1 until n) {
+ var bit = n shr 1
+ while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
+ j = j xor bit
+ if (i < j) { var t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t }
+ }
+ var len = 2
+ while (len <= n) {
+ val ang = -2 * PI / len
+ val wr = cos(ang); val wi = sin(ang)
+ var i = 0
+ while (i < n) {
+ var cr = 1.0; var ci = 0.0
+ for (k in 0 until len / 2) {
+ val ar = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci
+ val ai = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr
+ re[i + k + len / 2] = re[i + k] - ar; im[i + k + len / 2] = im[i + k] - ai
+ re[i + k] += ar; im[i + k] += ai
+ val t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t
+ }
+ i += len
+ }
+ len = len shl 1
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt
new file mode 100644
index 0000000..85e242f
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt
@@ -0,0 +1,475 @@
+package com.rfsentinel.app.sdr
+
+/*
+ * Userspace driver for RTL2832U "RTL-SDR" dongles with a Rafael Micro R820T / R820T2 /
+ * R860 or R828D tuner (RTL-SDR Blog V3 / V4, Nooelec NESDR and most generic DVB-T
+ * sticks), over Android's USB host API - no root. Receive only: it tunes, sets the gain
+ * and reads raw I/Q samples, which RF Sentinel only turns into a power spectrum
+ * (nothing is demodulated, decoded or recorded).
+ *
+ * Ported from librtlsdr (osmocom rtl-sdr: Steve Markgraf, Dimitri Stolnikov and others;
+ * R82xx tuner code by Mauro Carvalho Chehab and Steve Markgraf; RTL-SDR Blog V4 support
+ * by RTL-SDR Blog), GPL-2.0-or-later, used under the GNU GPL v3.
+ */
+
+import android.hardware.usb.UsbDevice
+import android.hardware.usb.UsbDeviceConnection
+import android.hardware.usb.UsbEndpoint
+
+class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevice, private val log: (String) -> Unit) {
+
+ enum class Tuner { R820T, R828D }
+
+ var tuner: Tuner? = null; private set
+ /** RTL-SDR Blog V4: R828D with a 28.8 MHz crystal, its own band inputs and notch filters. */
+ var blogV4 = false; private set
+ var sampleRate = 0; private set
+ var ctlErrors = 0; private set
+ private var centerHz = 0L
+ private lateinit var rx: UsbEndpoint
+
+ // ---- R82xx tuner state ----
+ private var i2cAddr = R820T_I2C_ADDR
+ private var tunerXtal = RTL_XTAL
+ private val regs = IntArray(NUM_REGS)
+ private var intFreq = 3_570_000
+ private var hasLock = false
+ private var input = -1
+
+ /** Opens the dongle: baseband, tuner detection and init. False when no supported tuner answers. */
+ fun open(): Boolean {
+ val intf = device.getInterface(0)
+ if (!conn.claimInterface(intf, true)) log("RTL-SDR: couldn't claim the USB interface (continuing)")
+ rx = (0 until intf.endpointCount).map { intf.getEndpoint(it) }.firstOrNull { it.address == 0x81 }
+ ?: run { log("RTL-SDR: no bulk-IN endpoint 0x81"); return false }
+ // A dummy write first, as librtlsdr does.
+ writeReg(USBB, USB_SYSCTL, 0x09, 1)
+ initBaseband()
+ val maker = runCatching { device.manufacturerName }.getOrNull().orEmpty()
+ val product = runCatching { device.productName }.getOrNull().orEmpty()
+ setI2cRepeater(true)
+ tuner = when {
+ i2cReadReg(R820T_I2C_ADDR, 0x00) == R82XX_CHECK_VAL -> Tuner.R820T
+ i2cReadReg(R828D_I2C_ADDR, 0x00) == R82XX_CHECK_VAL -> Tuner.R828D
+ else -> null
+ }
+ blogV4 = tuner == Tuner.R828D && maker == "RTLSDRBlog" && product == "Blog V4"
+ log("RTL-SDR: \"$maker $product\", tuner ${tuner ?: "not supported (E4000 / FC001x / FC2580?)"}${if (blogV4) " (RTL-SDR Blog V4)" else ""}")
+ if (tuner == null) { setI2cRepeater(false); return false }
+ if (tuner == Tuner.R828D) { i2cAddr = R828D_I2C_ADDR; if (!blogV4) tunerXtal = R828D_XTAL }
+ // R82xx: low IF, not zero-IF; only the in-phase ADC; spectrum inversion
+ demodWrite(1, 0xb1, 0x1a, 1)
+ demodWrite(0, 0x08, 0x4d, 1)
+ setIfFreq(R82XX_IF_FREQ)
+ demodWrite(1, 0x15, 0x01, 1)
+ val ok = r82xxInit()
+ setI2cRepeater(false)
+ if (!ok) log("RTL-SDR: tuner init failed")
+ return ok
+ }
+
+ fun close() {
+ runCatching {
+ setI2cRepeater(true); r82xxStandby(); setI2cRepeater(false)
+ writeReg(SYSB, DEMOD_CTL, 0x20, 1) // power off the demodulator and ADCs
+ }
+ }
+
+ // ---- RTL2832U ----
+
+ private fun initBaseband() {
+ writeReg(USBB, USB_SYSCTL, 0x09, 1)
+ writeReg(USBB, USB_EPA_MAXPKT, 0x0002, 2)
+ writeReg(USBB, USB_EPA_CTL, 0x1002, 2)
+ writeReg(SYSB, DEMOD_CTL_1, 0x22, 1)
+ writeReg(SYSB, DEMOD_CTL, 0xe8, 1)
+ demodWrite(1, 0x01, 0x14, 1); demodWrite(1, 0x01, 0x10, 1) // soft reset
+ demodWrite(1, 0x15, 0x00, 1); demodWrite(1, 0x16, 0x0000, 2)
+ for (i in 0 until 6) demodWrite(1, 0x16 + i, 0x00, 1)
+ setFir()
+ demodWrite(0, 0x19, 0x05, 1) // SDR mode, no DAGC
+ demodWrite(1, 0x93, 0xf0, 1); demodWrite(1, 0x94, 0x0f, 1)
+ demodWrite(1, 0x11, 0x00, 1) // no AGC
+ demodWrite(1, 0x04, 0x00, 1) // no RF / IF AGC loop
+ demodWrite(0, 0x61, 0x60, 1) // no PID filter
+ demodWrite(0, 0x06, 0x80, 1)
+ demodWrite(1, 0xb1, 0x1b, 1) // zero-IF, DC and IQ correction
+ demodWrite(0, 0x0d, 0x83, 1) // no 4.096 MHz clock output
+ }
+
+ private fun setFir() {
+ val fir = IntArray(20)
+ for (i in 0 until 8) fir[i] = FIR_DEFAULT[i] and 0xff
+ var i = 0
+ while (i < 8) {
+ val v0 = FIR_DEFAULT[8 + i]; val v1 = FIR_DEFAULT[8 + i + 1]
+ fir[8 + i * 3 / 2] = (v0 shr 4) and 0xff
+ fir[8 + i * 3 / 2 + 1] = ((v0 shl 4) or ((v1 shr 8) and 0x0f)) and 0xff
+ fir[8 + i * 3 / 2 + 2] = v1 and 0xff
+ i += 2
+ }
+ for (k in fir.indices) demodWrite(1, 0x1c + k, fir[k], 1)
+ }
+
+ private fun setIfFreq(freq: Int) {
+ val ifFreq = -((freq.toLong() * (1L shl 22)) / RTL_XTAL).toInt()
+ demodWrite(1, 0x19, (ifFreq shr 16) and 0x3f, 1)
+ demodWrite(1, 0x1a, (ifFreq shr 8) and 0xff, 1)
+ demodWrite(1, 0x1b, ifFreq and 0xff, 1)
+ }
+
+ /** Sample rate in Hz (0.9 - 3.2 MS/s), with the tuner's IF filter set to match. */
+ fun setSampleRate(rate: Int) {
+ var ratio = ((RTL_XTAL.toLong() * (1L shl 22)) / rate).toInt() and 0x0ffffffc
+ val real = (ratio.toLong() or ((ratio.toLong() and 0x08000000L) shl 1))
+ sampleRate = ((RTL_XTAL.toLong() * (1L shl 22)) / real).toInt()
+ setI2cRepeater(true)
+ val ifHz = r82xxSetBandwidth(sampleRate)
+ setIfFreq(ifHz)
+ setI2cRepeater(false)
+ demodWrite(1, 0x9f, (ratio shr 16) and 0xffff, 2)
+ demodWrite(1, 0xa1, ratio and 0xffff, 2)
+ demodWrite(1, 0x3f, 0, 1); demodWrite(1, 0x3e, 0, 1) // no ppm correction
+ demodWrite(1, 0x01, 0x14, 1); demodWrite(1, 0x01, 0x10, 1)
+ if (centerHz > 0) tune(centerHz)
+ }
+
+ /** Tunes to [hz]; false when the tuner's PLL doesn't lock. */
+ fun tune(hz: Long): Boolean {
+ setI2cRepeater(true)
+ val ok = r82xxSetFreq(hz)
+ setI2cRepeater(false)
+ if (ok) centerHz = hz
+ return ok
+ }
+
+ /** Fixed tuner gain in tenths of a dB (e.g. 297 = 29.7 dB): a steady scale for comparing channels over time. */
+ fun setGain(tenthsDb: Int) {
+ setI2cRepeater(true); r82xxSetGain(tenthsDb); setI2cRepeater(false)
+ }
+
+ fun resetBuffer() {
+ writeReg(USBB, USB_EPA_CTL, 0x1002, 2)
+ writeReg(USBB, USB_EPA_CTL, 0x0000, 2)
+ }
+
+ /** Reads raw 8-bit I/Q samples; bytes read, or a negative value on error. */
+ fun read(buf: ByteArray, len: Int = buf.size): Int = conn.bulkTransfer(rx, buf, len, 1000)
+
+ // ---- register access ----
+
+ private fun writeArray(block: Int, addr: Int, data: ByteArray, len: Int = data.size): Int =
+ conn.controlTransfer(0x40, 0, addr, (block shl 8) or 0x10, data, len, 300).also { if (it < 0) ctlErrors++ }
+ private fun readArray(block: Int, addr: Int, data: ByteArray, len: Int = data.size): Int =
+ conn.controlTransfer(0xC0, 0, addr, block shl 8, data, len, 300).also { if (it < 0) ctlErrors++ }
+
+ private fun writeReg(block: Int, addr: Int, v: Int, len: Int) {
+ val d = if (len == 1) byteArrayOf(v.toByte(), v.toByte()) else byteArrayOf((v shr 8).toByte(), v.toByte())
+ writeArray(block, addr, d, len)
+ }
+ private fun readReg(block: Int, addr: Int, len: Int): Int {
+ val d = ByteArray(2); readArray(block, addr, d, len)
+ return ((d[1].toInt() and 0xff) shl 8) or (d[0].toInt() and 0xff)
+ }
+
+ private fun demodWrite(page: Int, addr: Int, v: Int, len: Int) {
+ val d = if (len == 1) byteArrayOf(v.toByte(), v.toByte()) else byteArrayOf((v shr 8).toByte(), v.toByte())
+ if (conn.controlTransfer(0x40, 0, (addr shl 8) or 0x20, 0x10 or page, d, len, 300) < 0) ctlErrors++
+ demodRead(0x0a, 0x01, 1)
+ }
+ private fun demodRead(page: Int, addr: Int, len: Int): Int {
+ val d = ByteArray(2)
+ if (conn.controlTransfer(0xC0, 0, (addr shl 8) or 0x20, page, d, len, 300) < 0) ctlErrors++
+ return ((d[1].toInt() and 0xff) shl 8) or (d[0].toInt() and 0xff)
+ }
+
+ private fun setI2cRepeater(on: Boolean) = demodWrite(1, 0x01, if (on) 0x18 else 0x10, 1)
+
+ private fun i2cReadReg(addr: Int, reg: Int): Int {
+ writeArray(IICB, addr, byteArrayOf(reg.toByte()))
+ val d = ByteArray(1); readArray(IICB, addr, d)
+ return d[0].toInt() and 0xff
+ }
+
+ private fun setGpioOutput(gpio: Int) {
+ val bit = 1 shl gpio
+ writeReg(SYSB, GPD, readReg(SYSB, GPD, 1) and bit.inv(), 1)
+ writeReg(SYSB, GPOE, readReg(SYSB, GPOE, 1) or bit, 1)
+ }
+ private fun setGpioBit(gpio: Int, on: Boolean) {
+ val bit = 1 shl gpio; val r = readReg(SYSB, GPO, 1)
+ writeReg(SYSB, GPO, if (on) r or bit else r and bit.inv(), 1)
+ }
+
+ // ---- R82xx (tuner_r82xx.c) ----
+
+ private fun r82xxWrite(reg: Int, vals: IntArray) {
+ // skip writes the shadow registers already hold (I2C is slow)
+ val r0 = reg - REG_SHADOW_START
+ if (r0 >= 0 && r0 + vals.size <= NUM_REGS && (vals.indices).all { regs[r0 + it] == vals[it] }) return
+ for (i in vals.indices) { val r = r0 + i; if (r in 0 until NUM_REGS) regs[r] = vals[i] }
+ var pos = 0; var addr = reg
+ while (pos < vals.size) {
+ val size = minOf(MAX_I2C_MSG - 1, vals.size - pos)
+ val buf = ByteArray(size + 1)
+ buf[0] = addr.toByte()
+ for (k in 0 until size) buf[1 + k] = vals[pos + k].toByte()
+ if (writeArray(IICB, i2cAddr, buf) != size + 1) log("RTL-SDR: tuner write failed at reg 0x%02x".format(addr))
+ addr += size; pos += size
+ }
+ }
+ private fun r82xxWriteReg(reg: Int, v: Int) = r82xxWrite(reg, intArrayOf(v and 0xff))
+ private fun r82xxWriteMask(reg: Int, v: Int, mask: Int) {
+ val cur = regs.getOrElse(reg - REG_SHADOW_START) { 0 }
+ r82xxWriteReg(reg, (cur and mask.inv()) or (v and mask))
+ }
+ private fun r82xxRead(len: Int): IntArray {
+ writeArray(IICB, i2cAddr, byteArrayOf(0))
+ val d = ByteArray(len); readArray(IICB, i2cAddr, d)
+ return IntArray(len) { bitrev(d[it].toInt() and 0xff) }
+ }
+ private fun bitrev(b: Int): Int {
+ val lut = intArrayOf(0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf)
+ return (lut[b and 0xf] shl 4) or lut[b shr 4]
+ }
+
+ private fun r82xxInit(): Boolean {
+ regs.fill(0)
+ r82xxWrite(0x05, INIT_ARRAY)
+ if (!setTvStandard()) return false
+ sysfreqSel()
+ return true
+ }
+
+ private fun r82xxStandby() {
+ for ((r, v) in listOf(0x06 to 0xb1, 0x05 to 0xa0, 0x07 to 0x3a, 0x08 to 0x40, 0x09 to 0xc0, 0x0a to 0x36,
+ 0x0c to 0x35, 0x0f to 0x68, 0x11 to 0x03, 0x17 to 0xf4, 0x19 to 0x0c)) r82xxWriteReg(r, v)
+ }
+
+ /** r82xx_set_tv_standard for the 6 MHz digital mode librtlsdr uses, including the IF filter calibration. */
+ private fun setTvStandard(): Boolean {
+ INIT_ARRAY.copyInto(regs)
+ r82xxWriteMask(0x0c, 0x00, 0x0f)
+ r82xxWriteMask(0x13, VER_NUM, 0x3f)
+ r82xxWriteMask(0x1d, 0x00, 0x38)
+ intFreq = 3_570_000
+ var filCal = 0
+ for (i in 0 until 2) {
+ r82xxWriteMask(0x0b, 0x6b, 0x60)
+ r82xxWriteMask(0x0f, 0x04, 0x04)
+ r82xxWriteMask(0x10, 0x00, 0x03)
+ setPll(56_000_000L)
+ if (!hasLock) { log("RTL-SDR: tuner PLL didn't lock for the filter calibration (continuing, as librtlsdr does)"); return true }
+ r82xxWriteMask(0x0b, 0x10, 0x10)
+ r82xxWriteMask(0x0b, 0x00, 0x10)
+ r82xxWriteMask(0x0f, 0x00, 0x04)
+ filCal = r82xxRead(5)[4] and 0x0f
+ if (filCal != 0 && filCal != 0x0f) break
+ }
+ if (filCal == 0x0f) filCal = 0
+ r82xxWriteMask(0x0a, 0x10 or filCal, 0x1f)
+ r82xxWriteMask(0x0b, 0x6b, 0xef)
+ r82xxWriteMask(0x07, 0x00, 0x80)
+ r82xxWriteMask(0x06, 0x10, 0x30)
+ r82xxWriteMask(0x1e, 0x60, 0x60)
+ r82xxWriteMask(0x05, 0x01, 0x80)
+ r82xxWriteMask(0x1f, 0x00, 0x80)
+ r82xxWriteMask(0x0f, 0x00, 0x80)
+ r82xxWriteMask(0x19, 0x60, 0x60)
+ return true
+ }
+
+ /** r82xx_sysfreq_sel for digital TV / SDR use. */
+ private fun sysfreqSel() {
+ val mixerTop = 0x24; val lnaTop = 0xe5
+ r82xxWriteMask(0x1d, lnaTop, 0xc7)
+ r82xxWriteMask(0x1c, mixerTop, 0xf8)
+ r82xxWriteReg(0x0d, 0x53)
+ r82xxWriteReg(0x0e, 0x75)
+ input = 0x00
+ r82xxWriteMask(0x05, 0x00, 0x60)
+ r82xxWriteMask(0x06, 0x00, 0x08)
+ r82xxWriteMask(0x11, 0x38, 0x38)
+ r82xxWriteMask(0x17, 0x30, 0x30)
+ r82xxWriteMask(0x0a, 0x40, 0x60)
+ r82xxWriteMask(0x1d, 0, 0x38)
+ r82xxWriteMask(0x1c, 0, 0x04)
+ r82xxWriteMask(0x06, 0, 0x40)
+ r82xxWriteMask(0x1a, 0x30, 0x30)
+ r82xxWriteMask(0x1d, 0x18, 0x38)
+ r82xxWriteMask(0x1c, mixerTop, 0x04)
+ r82xxWriteMask(0x1e, 14, 0x1f)
+ r82xxWriteMask(0x1a, 0x20, 0x30)
+ }
+
+ private fun setMux(loHz: Long) {
+ val mhz = (loHz / 1_000_000).toInt()
+ var i = 0
+ while (i < FREQ_RANGES.size - 1 && mhz >= FREQ_RANGES[i + 1][0]) i++
+ val r = FREQ_RANGES[i]
+ r82xxWriteMask(0x17, r[1], 0x08)
+ r82xxWriteMask(0x1a, r[2], 0xc3)
+ r82xxWriteReg(0x1b, r[3])
+ r82xxWriteMask(0x10, r[6] or 0x00, 0x0b) // XTAL_HIGH_CAP_0P, as r82xx_init selects
+ r82xxWriteMask(0x08, 0x00, 0x3f)
+ r82xxWriteMask(0x09, 0x00, 0x3f)
+ }
+
+ private fun setPll(freqHz: Long) {
+ val freqKhz = (freqHz + 500) / 1000
+ val vcoMin = 1_770_000L; val vcoMax = vcoMin * 2
+ r82xxWriteMask(0x1a, 0x00, 0x0c)
+ val p = IntArray(7) { regs[0x10 - REG_SHADOW_START + it] }
+ p[0] = (p[0] and 0x10.inv()) // refdiv2 = 0
+ p[2] = (p[2] and 0xe0.inv()) or 0x80
+ var mixDiv = 2; var divNum = 0
+ while (mixDiv <= 64) {
+ if (freqKhz * mixDiv in vcoMin until vcoMax) {
+ var divBuf = mixDiv
+ while (divBuf > 2) { divBuf = divBuf shr 1; divNum++ }
+ break
+ }
+ mixDiv = mixDiv shl 1
+ }
+ val data = r82xxRead(5)
+ val vcoPowerRef = if (tuner == Tuner.R828D) 1 else 2
+ val vcoFineTune = (data[4] and 0x30) shr 4
+ if (vcoFineTune > vcoPowerRef) divNum-- else if (vcoFineTune < vcoPowerRef) divNum++
+ p[0] = (p[0] and 0xe0.inv()) or ((divNum shl 5) and 0xe0)
+ val vcoFreq = freqHz * mixDiv
+ val vcoDiv = (tunerXtal + 65536L * vcoFreq) / (2L * tunerXtal)
+ val nint = (vcoDiv / 65536).toInt(); val sdm = (vcoDiv % 65536).toInt()
+ if (nint > 128 / vcoPowerRef - 1) { log("RTL-SDR: no PLL values for $freqHz Hz"); hasLock = false; return }
+ val ni = (nint - 13) / 4; val si = nint - 4 * ni - 13
+ p[4] = (ni + (si shl 6)) and 0xff
+ p[2] = (p[2] and 0x08.inv()) or (if (sdm == 0) 0x08 else 0x00)
+ p[5] = sdm and 0xff; p[6] = sdm shr 8
+ r82xxWrite(0x10, p)
+ var lock = false
+ for (i in 0 until 2) {
+ if (r82xxRead(3)[2] and 0x40 != 0) { lock = true; break }
+ if (i == 0) r82xxWriteMask(0x12, 0x60, 0xe0)
+ }
+ hasLock = lock
+ if (lock) r82xxWriteMask(0x1a, 0x08, 0x08)
+ }
+
+ private fun r82xxSetFreq(hz: Long): Boolean {
+ val lo = hz + intFreq // VHF / UHF only here: no HF upconversion
+ setMux(lo)
+ setPll(lo)
+ if (!hasLock) return false
+ if (blogV4) {
+ // notch filters off inside the FM / DAB bands, on elsewhere; VHF or UHF input
+ val openD = if (hz in 85_000_000L..112_000_000L || hz in 172_000_000L..242_000_000L) 0x00 else 0x08
+ r82xxWriteMask(0x17, openD, 0x08)
+ val band = if (hz < 250_000_000L) VHF else UHF
+ if (band != input) {
+ input = band
+ r82xxWriteMask(0x06, 0x00, 0x08) // cable 2 (HF) off
+ setGpioOutput(5); setGpioBit(5, true) // upconverter switch: not HF
+ r82xxWriteMask(0x05, if (band == VHF) 0x40 else 0x00, 0x40)
+ r82xxWriteMask(0x05, if (band == UHF) 0x00 else 0x20, 0x20)
+ }
+ } else if (tuner == Tuner.R828D) {
+ val airCable1 = if (hz > 345_000_000L) 0x00 else 0x60
+ if (airCable1 != input) { input = airCable1; r82xxWriteMask(0x05, airCable1, 0x60) }
+ }
+ return true
+ }
+
+ private fun r82xxSetGain(gain: Int) {
+ r82xxWriteMask(0x05, 0x10, 0x10) // LNA auto off
+ r82xxWriteMask(0x07, 0x00, 0x10) // mixer auto off
+ r82xxRead(4)
+ r82xxWriteMask(0x0c, 0x08, 0x9f) // fixed VGA gain (16.3 dB)
+ var total = 0; var lna = 0; var mix = 0
+ for (i in 0 until 15) {
+ if (total >= gain) break
+ total += LNA_STEPS[++lna]
+ if (total >= gain) break
+ total += MIXER_STEPS[++mix]
+ }
+ r82xxWriteMask(0x05, lna, 0x0f)
+ r82xxWriteMask(0x07, mix, 0x0f)
+ }
+
+ /** r82xx_set_bandwidth; returns the IF frequency to program in the RTL2832U. */
+ private fun r82xxSetBandwidth(bwIn: Int): Int {
+ var bw = bwIn
+ val reg0a: Int; var reg0b: Int
+ if (bw > 7_000_000) { reg0a = 0x10; reg0b = 0x0b; intFreq = 4_570_000 }
+ else if (bw > 6_000_000) { reg0a = 0x10; reg0b = 0x2a; intFreq = 4_570_000 }
+ else if (bw > LPF_BW[0] + HP_BW1 + HP_BW2) { reg0a = 0x10; reg0b = 0x6b; intFreq = 3_570_000 }
+ else {
+ reg0a = 0x00; reg0b = 0x80; intFreq = 2_300_000
+ var realBw = 0
+ if (bw > LPF_BW[0] + HP_BW1) { bw -= HP_BW2; intFreq += HP_BW2; realBw += HP_BW2 } else reg0b = reg0b or 0x20
+ if (bw > LPF_BW[0]) { bw -= HP_BW1; intFreq += HP_BW1; realBw += HP_BW1 } else reg0b = reg0b or 0x40
+ var i = 0
+ while (i < LPF_BW.size && bw <= LPF_BW[i]) i++
+ i--
+ if (i < 0) i = 0
+ reg0b = reg0b or (15 - i)
+ realBw += LPF_BW[i]
+ intFreq -= realBw / 2
+ }
+ r82xxWriteMask(0x0a, reg0a, 0x10)
+ r82xxWriteMask(0x0b, reg0b, 0xef)
+ return intFreq
+ }
+
+ companion object {
+ /** RTL2832U dongles librtlsdr knows (the common ones; DVB-T sticks with other tuners are declined at open). */
+ private val IDS = setOf(0x0bda to 0x2832, 0x0bda to 0x2838, 0x0413 to 0x6680, 0x0413 to 0x6f0f, 0x0458 to 0x707f,
+ 0x0ccd to 0x00a9, 0x0ccd to 0x00b3, 0x0ccd to 0x00d3, 0x0ccd to 0x00d7, 0x0ccd to 0x00e0, 0x1554 to 0x5020,
+ 0x15f4 to 0x0131, 0x15f4 to 0x0133, 0x185b to 0x0620, 0x185b to 0x0650, 0x185b to 0x0680, 0x1b80 to 0xd393,
+ 0x1b80 to 0xd394, 0x1b80 to 0xd395, 0x1b80 to 0xd397, 0x1b80 to 0xd398, 0x1b80 to 0xd39d, 0x1b80 to 0xd3a4,
+ 0x1b80 to 0xd3a8, 0x1b80 to 0xd3af, 0x1b80 to 0xd3b0, 0x1d19 to 0x1101, 0x1d19 to 0x1102, 0x1d19 to 0x1103,
+ 0x1d19 to 0x1104, 0x1f4d to 0xa803, 0x1f4d to 0xb803, 0x1f4d to 0xc803, 0x1f4d to 0xd286, 0x1f4d to 0xd803)
+
+ fun isRtlSdr(vid: Int, pid: Int) = (vid to pid) in IDS
+
+ private const val RTL_XTAL = 28_800_000
+ private const val R828D_XTAL = 16_000_000
+ private const val R820T_I2C_ADDR = 0x34
+ private const val R828D_I2C_ADDR = 0x74
+ private const val R82XX_CHECK_VAL = 0x69
+ private const val R82XX_IF_FREQ = 3_570_000
+ private const val REG_SHADOW_START = 5
+ private const val NUM_REGS = 30
+ private const val VER_NUM = 49
+ private const val MAX_I2C_MSG = 8
+ private const val VHF = 2; private const val UHF = 3
+ private const val HP_BW1 = 350_000; private const val HP_BW2 = 380_000
+
+ private const val USBB = 1; private const val SYSB = 2; private const val IICB = 6
+ private const val USB_SYSCTL = 0x2000; private const val USB_EPA_CTL = 0x2148; private const val USB_EPA_MAXPKT = 0x2158
+ private const val DEMOD_CTL = 0x3000; private const val GPO = 0x3001; private const val GPOE = 0x3003
+ private const val GPD = 0x3004; private const val DEMOD_CTL_1 = 0x300b
+
+ private val FIR_DEFAULT = intArrayOf(-54, -36, -41, -40, -32, -14, 14, 53, 101, 156, 215, 273, 327, 372, 404, 421)
+
+ private val INIT_ARRAY = intArrayOf(
+ 0x83, 0x32, 0x75, 0xc0, 0x40, 0xd6, 0x6c, 0xf5, 0x63, 0x75, 0x68, 0x6c, 0x83, 0x80, 0x00,
+ 0x0f, 0x00, 0xc0, 0x30, 0x48, 0xcc, 0x60, 0x00, 0x54, 0xae, 0x4a, 0xc0, 0x00, 0x00, 0x00) // 0x05-0x1f, then 0x20-0x22 = 0
+
+ /** freq_ranges: start MHz, open_d, rf_mux_ploy, tf_c, xtal_cap20p, xtal_cap10p, xtal_cap0p. */
+ private val FREQ_RANGES = arrayOf(
+ intArrayOf(0, 0x08, 0x02, 0xdf, 0x02, 0x01, 0x00), intArrayOf(50, 0x08, 0x02, 0xbe, 0x02, 0x01, 0x00),
+ intArrayOf(55, 0x08, 0x02, 0x8b, 0x02, 0x01, 0x00), intArrayOf(60, 0x08, 0x02, 0x7b, 0x02, 0x01, 0x00),
+ intArrayOf(65, 0x08, 0x02, 0x69, 0x02, 0x01, 0x00), intArrayOf(70, 0x08, 0x02, 0x58, 0x02, 0x01, 0x00),
+ intArrayOf(75, 0x00, 0x02, 0x44, 0x02, 0x01, 0x00), intArrayOf(80, 0x00, 0x02, 0x44, 0x02, 0x01, 0x00),
+ intArrayOf(90, 0x00, 0x02, 0x34, 0x01, 0x01, 0x00), intArrayOf(100, 0x00, 0x02, 0x34, 0x01, 0x01, 0x00),
+ intArrayOf(110, 0x00, 0x02, 0x24, 0x01, 0x01, 0x00), intArrayOf(120, 0x00, 0x02, 0x24, 0x01, 0x01, 0x00),
+ intArrayOf(140, 0x00, 0x02, 0x14, 0x01, 0x01, 0x00), intArrayOf(180, 0x00, 0x02, 0x13, 0x00, 0x00, 0x00),
+ intArrayOf(220, 0x00, 0x02, 0x13, 0x00, 0x00, 0x00), intArrayOf(250, 0x00, 0x02, 0x11, 0x00, 0x00, 0x00),
+ intArrayOf(280, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00), intArrayOf(310, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00),
+ intArrayOf(450, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00), intArrayOf(588, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00),
+ intArrayOf(650, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00))
+
+ private val LNA_STEPS = intArrayOf(0, 9, 13, 40, 38, 13, 31, 22, 26, 31, 26, 14, 19, 5, 35, 13)
+ private val MIXER_STEPS = intArrayOf(0, 5, 10, 10, 19, 9, 10, 25, 17, 10, 8, 16, 13, 6, 3, -8)
+ private val LPF_BW = intArrayOf(1700000, 1600000, 1550000, 1450000, 1200000, 900000, 700000, 550000, 450000, 350000)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
new file mode 100644
index 0000000..6baa2f8
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -0,0 +1,152 @@
+package com.rfsentinel.app.sdr
+
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.hardware.usb.UsbDevice
+import android.hardware.usb.UsbManager
+import androidx.core.content.ContextCompat
+import com.rfsentinel.app.usb.UsbWifi
+
+/**
+ * An RTL-SDR dongle on an OTG cable, used while scanning as a receive-only radio-activity
+ * detector ([RadioWatch]): it sweeps the public-safety bands and reports strong
+ * transmissions nearby. Only signal strength per channel is measured. Its log goes into
+ * the USB adapter log (Settings → Export USB WiFi adapter log).
+ */
+object SdrRadio {
+
+ private const val ACTION_PERMISSION = "com.rfsentinel.app.SDR_PERMISSION"
+ private const val SAMPLE_RATE = 2_048_000
+ private const val GAIN_TENTHS_DB = 297
+ private const val XFER = 16_384 // bytes per USB read (8192 samples)
+ private const val READS_PER_CHUNK = 8 // ~32 ms of samples per tuned chunk
+ private const val SETTLE_READS = 2 // samples after a retune are discarded
+
+ @Volatile var status: String = ""; private set
+ private var receiver: BroadcastReceiver? = null
+ private var onEvent: ((RadioWatch.Event) -> Unit)? = null
+ @Volatile private var runningDevice: String? = null
+ @Volatile private var stop = false
+
+ fun isSdr(d: UsbDevice) = RtlSdr.isRtlSdr(d.vendorId, d.productId)
+
+ @Synchronized
+ fun start(context: Context, events: (RadioWatch.Event) -> Unit) {
+ val app = context.applicationContext
+ onEvent = events
+ if (receiver == null) {
+ val r = object : BroadcastReceiver() {
+ override fun onReceive(c: Context, intent: Intent) {
+ when (intent.action) {
+ UsbManager.ACTION_USB_DEVICE_ATTACHED, ACTION_PERMISSION -> connect(app)
+ UsbManager.ACTION_USB_DEVICE_DETACHED -> {
+ val d = deviceOf(intent)
+ if (d != null && d.deviceName == runningDevice) halt("RTL-SDR unplugged")
+ }
+ }
+ }
+ }
+ ContextCompat.registerReceiver(app, r, IntentFilter().apply {
+ addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
+ addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
+ addAction(ACTION_PERMISSION)
+ }, ContextCompat.RECEIVER_NOT_EXPORTED)
+ receiver = r
+ }
+ connect(app)
+ }
+
+ @Synchronized
+ fun stop(context: Context) {
+ receiver?.let { runCatching { context.applicationContext.unregisterReceiver(it) } }
+ receiver = null
+ halt("")
+ onEvent = null
+ }
+
+ @Synchronized
+ private fun halt(newStatus: String) {
+ stop = true
+ runningDevice = null
+ status = newStatus
+ }
+
+ private fun deviceOf(intent: Intent): UsbDevice? =
+ if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
+ else @Suppress("DEPRECATION") intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
+
+ @Synchronized
+ private fun connect(context: Context) {
+ if (runningDevice != null) return
+ val mgr = context.getSystemService(UsbManager::class.java) ?: return
+ val d = runCatching { mgr.deviceList.values.firstOrNull { isSdr(it) } }.getOrNull() ?: return
+ if (!mgr.hasPermission(d)) {
+ UsbWifi.log("%04x:%04x (RTL-SDR) plugged in - asking for USB access".format(d.vendorId, d.productId))
+ status = "RTL-SDR found - allow USB access on the prompt"
+ val pi = PendingIntent.getBroadcast(context, 2, Intent(ACTION_PERMISSION).setPackage(context.packageName), PendingIntent.FLAG_MUTABLE)
+ runCatching { mgr.requestPermission(d, pi) }
+ return
+ }
+ val conn = mgr.openDevice(d) ?: run { status = "RTL-SDR: couldn't open it"; return }
+ runningDevice = d.deviceName
+ stop = false
+ status = "RTL-SDR · starting…"
+ Thread({
+ runCatching { run(RtlSdr(conn, d, UsbWifi::log), d) }
+ .onFailure { UsbWifi.log("RTL-SDR stopped: ${UsbWifi.describe(it)}"); status = "RTL-SDR error: ${it.message}" }
+ runCatching { conn.close() }
+ synchronized(this) { if (runningDevice == d.deviceName) runningDevice = null }
+ }, "rtl-sdr").start()
+ }
+
+ private fun run(sdr: RtlSdr, d: UsbDevice) {
+ UsbWifi.log("=== RTL-SDR radio activity watch (%04x:%04x) ===".format(d.vendorId, d.productId))
+ if (!sdr.open()) { status = "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"; return }
+ sdr.setSampleRate(SAMPLE_RATE)
+ sdr.setGain(GAIN_TENTHS_DB)
+ sdr.resetBuffer()
+ val plan = RadioWatch.plan()
+ val watch = RadioWatch()
+ UsbWifi.log("RTL-SDR: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " +
+ RadioWatch.BANDS.joinToString { "%.1f-%.1f MHz".format(it.startHz / 1e6, it.endHz / 1e6) } + ", USB errors ${sdr.ctlErrors}")
+ val buf = ByteArray(XFER)
+ val iq = ByteArray(XFER * READS_PER_CHUNK)
+ var lastLog = 0L; var sweepStart = System.currentTimeMillis(); var sweepMs = 0L
+ var events = 0; var unlocked = 0; var readErrors = 0
+ while (!stop) {
+ for (center in plan) {
+ if (stop) break
+ if (!sdr.tune(center)) { unlocked++; continue }
+ repeat(SETTLE_READS) { sdr.read(buf) }
+ var got = 0
+ for (i in 0 until READS_PER_CHUNK) {
+ val n = sdr.read(buf)
+ if (n <= 0) { readErrors++; break }
+ System.arraycopy(buf, 0, iq, got, n); got += n
+ }
+ if (got < 2 * 1024) continue
+ val psd = RadioWatch.powerSpectrum(iq, got / 2)
+ for (e in watch.analyze(center, psd, sdr.sampleRate, System.currentTimeMillis())) {
+ events++
+ UsbWifi.log("RTL-SDR: transmission ${e.mhz} MHz, ${e.snrDb} dB above the noise (${e.band.label})")
+ onEvent?.invoke(e)
+ }
+ }
+ watch.sweepDone()
+ val now = System.currentTimeMillis()
+ sweepMs = now - sweepStart; sweepStart = now
+ status = if (watch.sweeps < 6) "RTL-SDR · learning the radio bands here…"
+ else "RTL-SDR · watching police radio bands · $events transmissions nearby so far"
+ if (now - lastLog > (if (watch.sweeps < 20) 10_000 else 60_000)) {
+ lastLog = now
+ UsbWifi.log("RTL-SDR: sweep ${watch.sweeps} in $sweepMs ms, ${watch.learnedChannels} channels, ${watch.busyChannels} always busy, " +
+ "$events reported, PLL unlocked $unlocked, read errors $readErrors, USB errors ${sdr.ctlErrors}")
+ }
+ }
+ sdr.close()
+ UsbWifi.log("RTL-SDR: stopped after ${watch.sweeps} sweeps")
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
new file mode 100644
index 0000000..dd67398
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/service/GnssWatch.kt
@@ -0,0 +1,106 @@
+package com.rfsentinel.app.service
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.location.GnssMeasurementsEvent
+import android.location.GnssStatus
+import android.location.Location
+import android.location.LocationListener
+import android.location.LocationManager
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import com.rfsentinel.app.detect.GnssAnalyzer
+
+/**
+ * Listens to the phone's satellite receiver (every system: GPS, GLONASS, Galileo, BeiDou,
+ * QZSS, NavIC, SBAS) for [GnssAnalyzer]. It doesn't turn the GPS on by itself: it hears
+ * the satellites whenever something else uses GPS (the map, a trace, camera warnings, or
+ * the satellite screen, which asks for GPS while it's open). Users are counted, so the
+ * scanner and the screen can share it.
+ */
+object GnssWatch {
+
+ @Volatile var latest: GnssAnalyzer.Snapshot? = null; private set
+ @Volatile var latestAt = 0L; private set
+ /** True when the phone reports its receiver gain (needed to tell jamming from a tunnel). */
+ @Volatile var hasAgc = false; private set
+ val analyzer = GnssAnalyzer()
+
+ private val listeners = LinkedHashSet<(GnssAnalyzer.Anomaly) -> Unit>()
+ private var users = 0
+ private var agcDb: Double? = null
+ private var agcAt = 0L
+ private val handler by lazy { Handler(Looper.getMainLooper()) }
+
+ private val statusCallback = object : GnssStatus.Callback() {
+ override fun onSatelliteStatusChanged(status: GnssStatus) {
+ val now = System.currentTimeMillis()
+ val sats = (0 until status.satelliteCount).map { i ->
+ GnssAnalyzer.Sat(
+ GnssAnalyzer.System.of(status.getConstellationType(i)), status.getSvid(i), status.getCn0DbHz(i),
+ status.getElevationDegrees(i), status.usedInFix(i),
+ if (status.hasCarrierFrequencyHz(i)) status.getCarrierFrequencyHz(i) / 1e6f else null
+ )
+ }
+ val snap = GnssAnalyzer.Snapshot(now, sats, agcDb?.takeIf { now - agcAt < 5_000L })
+ latest = snap; latestAt = now
+ emit(analyzer.onSnapshot(snap))
+ }
+ }
+
+ private val measurementsCallback = object : GnssMeasurementsEvent.Callback() {
+ override fun onGnssMeasurementsReceived(event: GnssMeasurementsEvent) {
+ // Receiver gain on the L1 / E1 / B1 / G1 band (the one jammers usually hit).
+ val values = ArrayList<Double>()
+ if (Build.VERSION.SDK_INT >= 33) {
+ event.gnssAutomaticGainControls.filter { it.carrierFrequencyHz > 1_500_000_000L }.forEach { values += it.levelDb }
+ }
+ if (values.isEmpty()) @Suppress("DEPRECATION") event.measurements.forEach { m ->
+ if (m.hasAutomaticGainControlLevelDb() && (!m.hasCarrierFrequencyHz() || m.carrierFrequencyHz > 1.5e9f))
+ values += m.automaticGainControlLevelDb
+ }
+ if (values.isNotEmpty()) {
+ values.sort()
+ agcDb = values[values.size / 2]; agcAt = System.currentTimeMillis(); hasAgc = true
+ }
+ }
+ }
+
+ private val fixListener = LocationListener { loc: Location ->
+ if (loc.provider == LocationManager.GPS_PROVIDER)
+ emit(analyzer.onFix(GnssAnalyzer.Fix(loc.time, System.currentTimeMillis(), loc.latitude, loc.longitude, loc.accuracy)))
+ }
+
+ private fun emit(list: List<GnssAnalyzer.Anomaly>) {
+ if (list.isEmpty()) return
+ val ls = synchronized(this) { listeners.toList() }
+ for (a in list) ls.forEach { it(a) }
+ }
+
+ /** Starts listening (needs the fine location permission); [onAnomaly] gets jamming / spoofing signs. */
+ @SuppressLint("MissingPermission")
+ @Synchronized
+ fun start(context: Context, onAnomaly: ((GnssAnalyzer.Anomaly) -> Unit)? = null) {
+ onAnomaly?.let { listeners += it }
+ users++
+ if (users > 1) return
+ val lm = context.applicationContext.getSystemService(LocationManager::class.java) ?: return
+ runCatching { lm.registerGnssStatusCallback(statusCallback, handler) }
+ runCatching { lm.registerGnssMeasurementsCallback(measurementsCallback, handler) }
+ // Fixes other parts of the app (or other apps) ask for; costs nothing extra.
+ runCatching { lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 1_000L, 0f, fixListener, Looper.getMainLooper()) }
+ }
+
+ @Synchronized
+ fun stop(context: Context, onAnomaly: ((GnssAnalyzer.Anomaly) -> Unit)? = null) {
+ onAnomaly?.let { listeners -= it }
+ if (users == 0) return
+ users--
+ if (users > 0) return
+ val lm = context.applicationContext.getSystemService(LocationManager::class.java) ?: return
+ runCatching { lm.unregisterGnssStatusCallback(statusCallback) }
+ runCatching { lm.unregisterGnssMeasurementsCallback(measurementsCallback) }
+ runCatching { lm.removeUpdates(fixListener) }
+ }
+}
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 e8c800f..3c149ee 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -261,6 +261,9 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.esp.EspBoards.start(this) { list -> pipeline.post { list.forEach(::processEsp) } }
// A USB WiFi adapter in monitor mode (e.g. AWUS036ACS): access points and client devices.
com.rfsentinel.app.usb.UsbWifi.start(this) { list -> pipeline.post { list.forEach(::processUsbWifi) } }
+ // An RTL-SDR dongle: strong two-way radio transmissions nearby (signal strength only).
+ if (Prefs.categoryEnabled(this, Category.RADIO)) com.rfsentinel.app.sdr.SdrRadio.start(this) { e -> pipeline.post { onRadio(e) } }
+ else com.rfsentinel.app.sdr.SdrRadio.stop(this)
// An OUI-SPY board paired over Bluetooth (App-Controlled firmware).
Prefs.ouiSpyBoard(this)?.let { addr ->
com.rfsentinel.app.esp.OuiSpyBle.start(this, addr, Prefs.ouiSpyRelayAll(this)) { list -> pipeline.post { list.forEach(::processEsp) } }
@@ -268,6 +271,7 @@ class ScanForegroundService : Service() {
updateLocationUpdates()
startHousekeeping()
startCellChecks()
+ startGnssChecks()
startBubble()
isRunning = true
@@ -844,6 +848,73 @@ class ScanForegroundService : Service() {
}
}
+ /**
+ * A strong two-way radio transmission on a normally quiet public-safety channel, from
+ * an RTL-SDR ([com.rfsentinel.app.sdr.RadioWatch]): logged, and an alert when it clears
+ * the alert threshold. Only signal strength is known - nothing that was said.
+ */
+ private fun onRadio(e: com.rfsentinel.app.sdr.RadioWatch.Event) {
+ if (!Prefs.categoryEnabled(this, Category.RADIO)) return
+ val now = System.currentTimeMillis()
+ val near = when { e.snrDb >= 40 -> "very close"; e.snrDb >= 30 -> "close" else -> "nearby" }
+ val detail = "A radio transmitted on ${e.mhz} MHz (${e.band.label}), ${e.snrDb} dB above the noise - $near. " +
+ if (e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.PUBLIC_SAFETY_MOBILE)
+ "Public-safety radios (police, fire, EMS) transmit on this band; not proof of who it is."
+ else "Police use this band, but so do businesses, schools and transit; a weak sign on its own."
+ val hit = Hit(Category.RADIO, "Two-way radio transmitting nearby", e.confidence, detail, "RTL-SDR signal strength (no decoding)")
+ val loc = lastLocation
+ val tag = Prefs.gpsTaggingEnabled(this)
+ serviceScope.launch {
+ AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
+ DetectionEntity(
+ mac = "RADIO " + e.mhz + " MHz", label = hit.label, source = "SDR", rssi = e.snrDb,
+ timestamp = now,
+ latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
+ category = Category.RADIO.name, confidence = e.confidence, evidence = detail
+ )
+ )
+ }
+ if (e.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {
+ NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)
+ AlertPlayer.play(this, hit.tier, "Radio transmitting nearby")
+ }
+ }
+
+ private var gnssWatching = false
+ private val gnssListener: (com.rfsentinel.app.detect.GnssAnalyzer.Anomaly) -> Unit = { a -> pipeline.post { onGnssAnomaly(a) } }
+
+ /**
+ * GPS / Galileo / GLONASS / BeiDou jamming and spoofing signs ([GnssWatch]): heard
+ * whenever GPS is on (map, traces, camera warnings); it doesn't turn GPS on itself.
+ */
+ private fun startGnssChecks() {
+ val want = Prefs.categoryEnabled(this, Category.GNSS) && hasFineLocation()
+ if (want && !gnssWatching) { GnssWatch.start(this, gnssListener); gnssWatching = true }
+ else if (!want && gnssWatching) { GnssWatch.stop(this, gnssListener); gnssWatching = false }
+ }
+
+ private fun onGnssAnomaly(a: com.rfsentinel.app.detect.GnssAnalyzer.Anomaly) {
+ if (!Prefs.categoryEnabled(this, Category.GNSS)) return
+ val now = System.currentTimeMillis()
+ val hit = Hit(Category.GNSS, a.title, a.confidence, a.detail, "Phone satellite receiver (heuristic, not proof)")
+ val loc = lastLocation
+ val tag = Prefs.gpsTaggingEnabled(this)
+ serviceScope.launch {
+ AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
+ DetectionEntity(
+ mac = "GNSS " + a.key, label = a.title, source = "GNSS", rssi = 0,
+ timestamp = now,
+ latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
+ category = Category.GNSS.name, confidence = a.confidence, evidence = a.detail
+ )
+ )
+ }
+ if (a.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {
+ NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java)
+ AlertPlayer.play(this, hit.tier, a.title)
+ }
+ }
+
private fun onCellAnomaly(a: com.rfsentinel.app.detect.CellAnalyzer.Anomaly) {
val now = System.currentTimeMillis()
if (now - (lastCellAlert[a.key] ?: 0L) < CELL_REPEAT_MS) return
@@ -933,6 +1004,8 @@ class ScanForegroundService : Service() {
override fun onDestroy() {
com.rfsentinel.app.esp.EspBoards.stop(this)
com.rfsentinel.app.usb.UsbWifi.stop(this)
+ com.rfsentinel.app.sdr.SdrRadio.stop(this)
+ if (gnssWatching) { GnssWatch.stop(this, gnssListener); gnssWatching = false }
com.rfsentinel.app.esp.OuiSpyBle.stop()
// External hardware is gone with the scan: its "heard by" marks (External filter, badges) go too.
com.rfsentinel.app.esp.HeardBy.esp.clear()
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 f33cbe0..d1be310 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -211,7 +211,9 @@ class SettingsActivity : AppCompatActivity() {
s.ifBlank { "plug one in with an OTG cable while scanning to add its detections" }
binding.usbWifiText.text = "USB WiFi adapter in monitor mode (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, RTL8812BU / 8822BU, " +
"RTL8814AU (AWUS1900), MT7612U (AWUS036ACM), RTL8187 (AWUS036H), RT3070 (AWUS036NH / NEH) or, experimental, AR9271 (AWUS036NHA)): " +
- com.rfsentinel.app.usb.UsbWifi.status.ifBlank { "plug one in with an OTG cable while scanning - longer range, and it hears devices connected to networks" }
+ com.rfsentinel.app.usb.UsbWifi.status.ifBlank { "plug one in with an OTG cable while scanning - longer range, and it hears devices connected to networks" } +
+ "\nRTL-SDR dongle (two-way radio transmitting nearby, signal strength only): " +
+ com.rfsentinel.app.sdr.SdrRadio.status.ifBlank { "plug one in while scanning" }
val board = Prefs.ouiSpyBoard(this)
binding.ouiSpyText.text = if (board == null)
"OUI-SPY over Bluetooth (App-Controlled firmware): not paired"
diff --git a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
new file mode 100644
index 0000000..6731f8f
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
@@ -0,0 +1,155 @@
+package com.rfsentinel.app.ui
+
+import android.annotation.SuppressLint
+import android.graphics.Typeface
+import android.location.LocationListener
+import android.location.LocationManager
+import android.os.Bundle
+import android.os.Looper
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.rfsentinel.app.databinding.ActivityLogBinding
+import com.rfsentinel.app.databinding.ItemDetectionBinding
+import com.rfsentinel.app.detect.GnssAnalyzer
+import com.rfsentinel.app.service.GnssWatch
+import com.rfsentinel.app.util.Permissions
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/**
+ * The satellites the phone hears, for every system (GPS, GLONASS, Galileo, BeiDou, QZSS,
+ * NavIC, SBAS): signal strength, height in the sky, whether the fix uses it, and the
+ * jamming / spoofing check. GPS is switched on while this screen is open.
+ */
+class GnssActivity : AppCompatActivity() {
+
+ private lateinit var binding: ActivityLogBinding
+
+ private sealed interface Row {
+ data class Header(val text: String) : Row
+ data class Line(val title: String, val sub: String, val meta: String, val highlight: Boolean = false) : Row
+ }
+
+ private var rows: List<Row> = emptyList()
+ private val gpsOn = LocationListener { }
+
+ private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
+ override fun getItemCount() = rows.size
+ override fun getItemViewType(position: Int) = if (rows[position] is Row.Header) 0 else 1
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
+ val v = if (viewType == 0) TextView(parent.context).apply {
+ setTypeface(typeface, Typeface.BOLD)
+ textSize = 15f
+ setPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())
+ } else ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root
+ return object : RecyclerView.ViewHolder(v) {}
+ }
+ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
+ when (val r = rows[position]) {
+ is Row.Header -> (holder.itemView as TextView).text = r.text
+ is Row.Line -> ItemDetectionBinding.bind(holder.itemView).apply {
+ labelText.text = r.title
+ labelText.setTextColor(if (r.highlight) ThemeManager.ink(this@GnssActivity, 0xFF0B7A3E.toInt()) else macText.currentTextColor)
+ macText.text = r.sub
+ metaText.text = r.meta
+ }
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityLogBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.root.applySystemBarInsets()
+ title = "Satellites"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding.recyclerView.layoutManager = LinearLayoutManager(this)
+ binding.recyclerView.adapter = adapter
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(1_000) }
+ }
+ }
+ }
+
+ @SuppressLint("MissingPermission")
+ override fun onStart() {
+ super.onStart()
+ if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) return
+ GnssWatch.start(this)
+ runCatching {
+ getSystemService(LocationManager::class.java)
+ .requestLocationUpdates(LocationManager.GPS_PROVIDER, 1_000L, 0f, gpsOn, Looper.getMainLooper())
+ }
+ }
+
+ override fun onStop() {
+ runCatching { getSystemService(LocationManager::class.java).removeUpdates(gpsOn) }
+ if (Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) GnssWatch.stop(this)
+ super.onStop()
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ @SuppressLint("NotifyDataSetChanged")
+ private fun refresh() {
+ if (!Permissions.granted(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
+ show(emptyList(), "The satellite view needs the location permission.\nStart a scan once to grant it."); return
+ }
+ val snap = GnssWatch.latest?.takeIf { System.currentTimeMillis() - GnssWatch.latestAt < 10_000L }
+ if (snap == null) {
+ show(emptyList(), "Listening for satellites…\nIt can take up to a minute; outdoors or near a window works best."); return
+ }
+ val tracked = snap.sats.filter { it.cn0 > 0f }
+ val out = ArrayList<Row>()
+ out += Row.Header("Check")
+ out += Row.Line(GnssWatch.analyzer.verdict,
+ "${tracked.size} satellites heard, ${snap.sats.count { it.usedInFix }} used for the position",
+ if (GnssWatch.hasAgc) "Receiver noise (AGC) ${snap.agcDb?.let { "%.1f dB".format(it) } ?: "-"} · jamming check on"
+ else "This phone doesn't report receiver noise: jamming is only suspected on a total loss",
+ highlight = GnssWatch.analyzer.verdict.startsWith("No "))
+ out += Row.Header("Systems")
+ snap.sats.groupBy { it.system }.toSortedMap(compareBy { it.ordinal }).forEach { (sys, list) ->
+ val heard = list.filter { it.cn0 > 0f }
+ out += Row.Line(sys.label, "${heard.size} heard · ${list.count { it.usedInFix }} used",
+ if (heard.isEmpty()) "no signal" else "strongest %.0f dB-Hz · average %.0f dB-Hz".format(heard.maxOf { it.cn0 }, heard.map { it.cn0 }.average()))
+ }
+ out += Row.Header("Satellites")
+ snap.sats.sortedWith(compareBy<GnssAnalyzer.Sat> { it.system.ordinal }.thenByDescending { it.cn0 }).forEach { s ->
+ out += Row.Line("${s.system.label} ${s.svid}${band(s)}" + if (s.usedInFix) " · used" else "",
+ if (s.cn0 > 0f) "${bars(s.cn0)} %.0f dB-Hz".format(s.cn0) else "not heard",
+ "%.0f° above the horizon".format(s.elevation), highlight = s.usedInFix)
+ }
+ show(out, null)
+ }
+
+ private fun band(s: GnssAnalyzer.Sat): String {
+ val f = s.carrierMhz ?: return ""
+ return when {
+ f > 1500f -> when (s.system) { GnssAnalyzer.System.GALILEO -> " E1"; GnssAnalyzer.System.BEIDOU -> " B1"; GnssAnalyzer.System.GLONASS -> " G1"; else -> " L1" }
+ f > 1250f -> " (L6 / E6 / B3)"
+ f > 1200f -> " (L2 / B2)"
+ else -> when (s.system) { GnssAnalyzer.System.GALILEO -> " E5a"; GnssAnalyzer.System.BEIDOU -> " B2a"; else -> " L5" }
+ }
+ }
+
+ private fun bars(cn0: Float): String { val n = ((cn0 - 15) / 7).toInt().coerceIn(0, 5); return "▮".repeat(n) + "▯".repeat(5 - n) }
+
+ @SuppressLint("NotifyDataSetChanged")
+ private fun show(list: List<Row>, emptyText: String?) {
+ rows = list
+ adapter.notifyDataSetChanged()
+ binding.emptyText.text = emptyText.orEmpty()
+ binding.emptyText.visibility = if (emptyText != null) View.VISIBLE else View.GONE
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
index d81f834..f57a513 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
@@ -259,7 +259,7 @@ class SetupActivity : AppCompatActivity() {
Prefs.setCellChangeAlerts(this, it)
}
para("Extra hardware works on its own once plugged in while scanning: ESP32 boards (OUI-Spy, GhostESP, Marauder - also ESP32-C5 boards for 5 GHz, and a Flipper Zero with its ESP32 board) " +
- "and USB WiFi adapters (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070 or, experimental, AR9271 - ALFA AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA). An OUI-SPY board over Bluetooth is paired in Settings.", small = true)
+ "and USB WiFi adapters (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, RTL8812BU / 8822BU, RTL8814AU, MT7612U, RTL8187, RT3070 or, experimental, AR9271 - ALFA AWUS1900, AWUS036ACM, AWUS036H, AWUS036NH / NEH, AWUS036NHA), and an RTL-SDR dongle to hear two-way radios transmitting nearby (signal strength only, nothing decoded). An OUI-SPY board over Bluetooth is paired in Settings.", small = true)
}
private fun permissions() {
diff --git a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
index 7b0effa..e730e41 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
+++ b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
@@ -27,6 +27,7 @@ These drivers run USB WiFi adapters in receive-only monitor mode from userspace.
| AR9271 register tables | Linux `ath9k` (`ar9002_initvals.h`), as used by Wardrive Go | ISC |
| MT7612U firmware `mt7662.bin` and ROM patch `mt7662_rom_patch.bin` (unmodified, from linux-firmware) | Ralink, a MediaTek company | Redistributable binary, see `assets/usbwifi/LICENCE.ralink_a_mediatek_company_firmware` |
| AR9271 firmware `htc_9271-1.4.0.fw` (unmodified, from linux-firmware; Wardrive Go ships a build that differs in 10 bytes) | [open-ath9k-htc-firmware](https://github.com/qca/open-ath9k-htc-firmware), Qualcomm Atheros and others | Free software, see `assets/usbwifi/LICENCE.open-ath9k-htc-firmware` |
+| RTL-SDR driver (`sdr/RtlSdr.kt`: RTL2832U baseband, R820T / R828D tuner, RTL-SDR Blog V4 band switching) | [librtlsdr](https://github.com/osmocom/rtl-sdr) (osmocom: Steve Markgraf, Dimitri Stolnikov and others; R82xx code by Mauro Carvalho Chehab and Steve Markgraf; Blog V4 support by RTL-SDR Blog) | GPL-2.0-or-later |
| Integration into RF Sentinel; removal of handshake / PMKID capture (8821AU, RT3070) and of every transmit, beamforming and calibration-for-TX path (8822BU, RTL8187); RT3070 fixes checked against the kernel (eFuse addressing, EEPROM reads, DMA / frame-length setup, receive gain, external LNA, EEPROM BBP overrides); MT7612U: bad-checksum frames dropped, auto-responder off, kernel ROM-patch rule; AR9271: signal relative to the noise floor, FCS removed, packets spanning transfers reassembled, WMI answers matched, running firmware reused | RF Sentinel (CIS-C0) | GPL-3.0 |
RF Sentinel is distributed under the GNU GPL v3.0 (see `LICENSE`). The register
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 d1bd8ad..ab13695 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -189,7 +189,8 @@ object UsbWifi {
private fun describe(mgr: UsbManager?, d: UsbDevice): String {
val sb = StringBuilder()
val what = chipOf(d)?.let { "supported (${it.name})" }
- ?: knownOnly(d)?.let { "$it, not supported yet" } ?: "not a supported WiFi adapter"
+ ?: knownOnly(d)?.let { "$it, not supported yet" }
+ ?: if (com.rfsentinel.app.sdr.RtlSdr.isRtlSdr(d.vendorId, d.productId)) "RTL-SDR (radio activity detector)" else "not a supported WiFi adapter"
val allowed = runCatching { mgr?.hasPermission(d) }.getOrNull() == true
// Names are only readable once USB access is allowed.
val name = listOfNotNull(runCatching { d.manufacturerName }.getOrNull(), runCatching { d.productName }.getOrNull())
diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
index 5b3a42e..049e5ab 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
@@ -38,6 +38,8 @@ object Spoken {
Category.GLASSES -> "Camera glasses"
Category.NETWORK_CAMERA -> "Camera"
Category.CELL_ANOMALY -> "Cell warning"
+ Category.RADIO -> "Radio nearby"
+ Category.GNSS -> "GPS warning"
Category.CUSTOM -> "Watchlist"
}
}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt b/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt
new file mode 100644
index 0000000..4cc0ba4
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/detect/GnssAnalyzerTest.kt
@@ -0,0 +1,77 @@
+package com.rfsentinel.app.detect
+
+import com.rfsentinel.app.detect.GnssAnalyzer.Sat
+import com.rfsentinel.app.detect.GnssAnalyzer.Snapshot
+import com.rfsentinel.app.detect.GnssAnalyzer.System
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class GnssAnalyzerTest {
+
+ /** A normal sky: strength rises with elevation, four systems. */
+ private fun sky(shift: Float = 0f, systems: Set<System> = setOf(System.GPS, System.GALILEO, System.GLONASS, System.BEIDOU)): List<Sat> =
+ systems.flatMap { sys -> (1..4).map { i -> val el = i * 20f; Sat(sys, i, 25f + el / 3 + shift, el, true) } }
+
+ private fun feed(a: GnssAnalyzer, from: Long, seconds: Int, sats: List<Sat>, agc: Double?) =
+ (0 until seconds).flatMap { a.onSnapshot(Snapshot(from + it * 1000L, sats, agc)) }
+
+ @Test
+ fun normalSkyIsQuiet() {
+ val a = GnssAnalyzer()
+ assertTrue(feed(a, 0, 60, sky(), 30.0).isEmpty())
+ assertEquals("No jamming or spoofing signs", a.verdict)
+ }
+
+ @Test
+ fun noiseRiseWithWeakerSatellitesIsJamming() {
+ val a = GnssAnalyzer()
+ feed(a, 0, 60, sky(), 30.0)
+ val out = feed(a, 60_000, 10, sky(shift = -12f), 18.0)
+ assertEquals("jam", out.single().key)
+ assertEquals(75, out.single().confidence)
+ }
+
+ @Test
+ fun aTunnelIsNotJamming() {
+ val a = GnssAnalyzer()
+ feed(a, 0, 60, sky(), 30.0)
+ assertTrue(feed(a, 60_000, 20, sky(shift = -15f), 30.0).isEmpty()) // weaker, but no noise rise
+ }
+
+ @Test
+ fun totalLossWithoutAgcIsOnlyAWeakSign() {
+ val a = GnssAnalyzer()
+ feed(a, 0, 60, sky(), null)
+ val out = feed(a, 60_000, 10, emptyList(), null)
+ assertEquals("loss", out.single().key)
+ assertTrue(out.single().confidence < 50)
+ }
+
+ @Test
+ fun equallyStrongSatellitesLookSpoofed() {
+ val a = GnssAnalyzer()
+ feed(a, 0, 30, sky(), 30.0)
+ val fake = (1..8).map { Sat(System.GPS, it, 45f + (it % 2) * 0.5f, (it * 10).toFloat(), true) }
+ val out = feed(a, 30_000, 10, fake, 30.0)
+ assertTrue(out.any { it.key == "uniform" })
+ }
+
+ @Test
+ fun otherSystemsVanishingWhileGpsStaysStrong() {
+ val a = GnssAnalyzer()
+ feed(a, 0, 60, sky(shift = 10f), 30.0)
+ val out = feed(a, 60_000, 10, sky(shift = 10f, systems = setOf(System.GPS)), 30.0)
+ assertTrue(out.any { it.key == "gpsonly" })
+ }
+
+ @Test
+ fun clockSkewAndImpossibleJumps() {
+ val a = GnssAnalyzer()
+ assertTrue(a.onFix(GnssAnalyzer.Fix(1_000_000, 1_000_000, 45.0, -73.0, 5f)).isEmpty())
+ val jump = a.onFix(GnssAnalyzer.Fix(1_002_000, 1_002_000, 46.0, -73.0, 5f)) // ~111 km in 2 s
+ assertEquals("jump", jump.single().key)
+ val skew = a.onFix(GnssAnalyzer.Fix(1_004_000 + 3_600_000, 1_004_000, 46.0, -73.0, 5f))
+ assertTrue(skew.any { it.key == "time" })
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt
new file mode 100644
index 0000000..124a792
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt
@@ -0,0 +1,111 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.roundToInt
+import kotlin.math.sin
+
+class RadioWatchTest {
+
+ private val rate = 2_048_000
+ private val n = 1024
+ private val binHz = rate.toDouble() / n
+
+ /** A flat -60 dB spectrum with a signal [snr] dB up at each frequency of [signals]. */
+ private fun psd(center: Long, vararg signals: Pair<Long, Int>): FloatArray {
+ val p = FloatArray(n) { -60f }
+ for ((f, snr) in signals) {
+ val mid = n / 2 + ((f - center) / binHz).roundToInt()
+ for (k in mid - 2..mid + 2) if (k in 0 until n) p[k] = -60f + snr
+ }
+ return p
+ }
+
+ private val center = 807_000_000L // a chunk in the 800 MHz public-safety band
+ private val tower = 806_500_000L // always on
+ private val radio = 807_312_500L // a handheld keying up
+
+ private fun learn(w: RadioWatch, sweeps: Int, t0: Long = 0L): Long {
+ var t = t0
+ repeat(sweeps) { w.analyze(center, psd(center, tower to 40), rate, t); w.sweepDone(); t += 2_500 }
+ return t
+ }
+
+ @Test
+ fun alwaysOnChannelsAreLearnedAndIgnored() {
+ val w = RadioWatch()
+ val t = learn(w, 10)
+ assertTrue(w.busyChannels >= 1)
+ assertTrue(w.analyze(center, psd(center, tower to 45), rate, t).isEmpty())
+ }
+
+ @Test
+ fun aStrongBurstOnAQuietChannelIsReported() {
+ val w = RadioWatch()
+ val t = learn(w, 8)
+ val ev = w.analyze(center, psd(center, tower to 40, radio to 42), rate, t)
+ assertEquals(1, ev.size)
+ assertEquals(radio, ev[0].freqHz)
+ assertEquals(75, ev[0].confidence)
+ assertEquals(RadioWatch.Kind.PUBLIC_SAFETY_MOBILE, ev[0].band.kind)
+ // the same channel isn't reported again right away
+ assertTrue(w.analyze(center, psd(center, radio to 42), rate, t + 2_500).isEmpty())
+ }
+
+ @Test
+ fun nothingIsReportedWhileLearning() {
+ val w = RadioWatch()
+ learn(w, 2)
+ assertTrue(w.analyze(center, psd(center, radio to 45), rate, 10_000).isEmpty())
+ }
+
+ @Test
+ fun weakSignalsAndSplatterAreNotReportedTwice() {
+ val w = RadioWatch()
+ val t = learn(w, 8)
+ assertTrue(w.analyze(center, psd(center, radio to 20), rate, t).isEmpty()) // too weak for an alert
+ val ev = w.analyze(center, psd(center, radio to 42, radio + 12_500 to 35), rate, t + 200_000)
+ assertEquals(1, ev.size)
+ }
+
+ @Test
+ fun sharedBandsNeedAStrongerSignalAndSkipConsumerRadios() {
+ val c = 462_600_000L
+ val w = RadioWatch()
+ var t = 0L
+ repeat(8) { w.analyze(c, psd(c), rate, t); w.sweepDone(); t += 2_500 }
+ assertTrue(RadioWatch.excluded(462_625_000L)) // FRS / GMRS
+ assertTrue(w.analyze(c, psd(c, 462_625_000L to 50), rate, t).isEmpty())
+ val ev = w.analyze(c, psd(c, 462_900_000L to 50), rate, t + 1)
+ assertEquals(1, ev.size)
+ assertEquals(55, ev[0].confidence)
+ assertTrue(w.analyze(c, psd(c, 463_100_000L to 36), rate, t + 2).single().confidence == 35)
+ }
+
+ @Test
+ fun planCoversEveryBandWithoutLteUplink() {
+ val plan = RadioWatch.plan()
+ assertEquals(37, plan.size)
+ for (b in RadioWatch.BANDS) assertTrue(plan.any { it - RadioWatch.USABLE_HZ <= b.startHz })
+ assertFalse(RadioWatch.BANDS.any { it.endHz > 814_000_000L && it.startHz < 849_000_000L && it.startHz > 806_000_000L })
+ }
+
+ @Test
+ fun powerSpectrumPutsAToneInItsBin() {
+ val count = 8192
+ val iq = ByteArray(2 * count)
+ val tone = 200_000.0
+ for (i in 0 until count) {
+ val ph = 2 * PI * tone * i / rate
+ iq[2 * i] = (127.5 + 60 * cos(ph)).roundToInt().toByte()
+ iq[2 * i + 1] = (127.5 + 60 * sin(ph)).roundToInt().toByte()
+ }
+ val p = RadioWatch.powerSpectrum(iq, count, n)
+ val peak = p.indices.maxByOrNull { p[it] }!!
+ assertEquals(n / 2 + (tone / binHz).roundToInt(), peak)
+ }
+}