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.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
P25: listen on a call's input frequency to tell a radio keying up nearby (off by default)
CIS-C0d4bedffeb56f
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.ktindex f1f8d69..e386a79 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt@@ -117,9 +117,10 @@ class P25Hunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}/*** Stays on [lock], handing each message to [onMsg]: false when [stop] said so, true when the channel- * went quiet for [LOST_S] (hunt again). Logs what it decoded every [LOG_S].+ * went quiet for [LOST_S] (hunt again). Logs what it decoded every [LOG_S]. [detour] true: it tuned away for a+ * moment (an input check), so the control channel is tuned again.*/- fun listen(lock: Lock, stop: () -> Boolean, onMsg: (P25Tsbk.Msg) -> Unit): Boolean {+ fun listen(lock: Lock, stop: () -> Boolean, detour: () -> Boolean = { false }, onMsg: (P25Tsbk.Msg) -> Unit): Boolean {sdr.setSampleRate(P25Demod.SAMPLE_RATE)if (!sdr.tune(lock.hz - OFFSET_HZ)) { log("P25 listen: the tuner didn't lock"); return true }sdr.resetBuffer()@@ -141,6 +142,13 @@ class P25Hunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}st = Stats(); kinds.clear()}while (!stop()) {+ if (detour()) {+ if (!sdr.tune(lock.hz - OFFSET_HZ)) { log("P25 listen: the tuner didn't lock after an input check"); return true }+ sdr.resetBuffer()+ repeat(sdr.settleReads) { sdr.read(buf) }+ lastGood = samples // the time away doesn't count as the channel going quiet+ continue+ }val n = sdr.read(buf)if (n <= 0) { st.stalls++; if (++fails % STALL_READS == 0) sdr.resetBuffer(); continue }fails = 0diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.ktindex 3606c2f..8083d16 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt@@ -70,6 +70,9 @@ class P25Log {@Synchronized fun summary() = Summary(site, messages, registrations, since)+ /** Where the radios transmit on [channel], or null while unknown. */+ @Synchronized fun inputHz(channel: Int): Long? = channels.inputHz(channel)+/** The calls started since the last time this was asked, oldest first. */@Synchronized fun takeCalls(): List<P25History.Call> = started.toList().also { started.clear() }diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.ktindex 2f85443..22d09e4 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt@@ -17,8 +17,9 @@ object P25Tsbk {data class GrantUpdate(val calls: List<Pair<Int, Int>>) : Msg()data class Affiliation(val radio: Int, val tg: Int) : Msg()data class Registration(val radio: Int, val accepted: Boolean) : Msg()- /** Channel table [id]: channel n is [baseHz] + n × [spacingHz], or n / [slots] on a TDMA (Phase 2) carrier. */- data class Iden(val id: Int, val baseHz: Long, val spacingHz: Int, val slots: Int) : Msg()+ /** Channel table [id]: channel n is [baseHz] + n × [spacingHz], or n / [slots] on a TDMA (Phase 2) carrier.+ * [txOffsetHz]: where the radios transmit, from the base station's frequency (0: not given). */+ data class Iden(val id: Int, val baseHz: Long, val spacingHz: Int, val slots: Int, val txOffsetHz: Long = 0) : Msg()/** This site: [wacn] and [sysId] the system, [rfss] / [site] where, [channel] its control channel. */data class Site(val wacn: Int?, val sysId: Int, val rfss: Int?, val site: Int?, val channel: Int) : Msg()/** A neighbouring site's control channel. */@@ -35,9 +36,9 @@ object P25Tsbk {0x04, 0x06 -> Grant(f(64, 16), null, f(40, 24), f(16, 24), false, false)0x28 -> Affiliation(f(16, 24), f(40, 16))0x2C -> Registration(f(16, 24), f(76, 2) == 0)- 0x3D -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, 1)- 0x34 -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, 1)- 0x33 -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, SLOTS[f(72, 4)])+ 0x3D -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, 1, offset(f(58, 9), 8, 250_000L))+ 0x34 -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, 1, offset(f(58, 14), 13, f(48, 10) * 125L))+ 0x33 -> Iden(f(76, 4), f(16, 32) * 5L, f(48, 10) * 125, SLOTS[f(72, 4)], offset(f(58, 14), 13, f(48, 10) * 125L))0x3A -> Site(null, f(56, 12), f(48, 8), f(40, 8), f(24, 16))0x3B -> Site(f(52, 20), f(40, 12), null, null, f(24, 16))0x3C -> Neighbor(f(48, 8), f(40, 8), f(24, 16))@@ -45,6 +46,10 @@ object P25Tsbk {}}+ /** A transmit offset: the bits below sign bit [sign] (set: the radios transmit above the base station) times [step]. */+ private fun offset(v: Int, sign: Int, step: Long): Long =+ (v and ((1 shl sign) - 1)) * step * (if (v shr sign and 1 == 1) 1 else -1)+/** Bytes 2-9: the 64 argument bits (bit 0 of the result is bit 16 of the 96-bit block). */private fun args(b: ByteArray): Long {var v = 0L@@ -66,6 +71,11 @@ object P25Tsbk {val t = tables[channel shr 12 and 0xf] ?: return nullreturn t.baseHz + t.spacingHz.toLong() * ((channel and 0xfff) / t.slots)}+ /** Where the radios transmit on [channel] (the site's input), or null until its table, with an offset, is heard. */+ fun inputHz(channel: Int): Long? {+ val t = tables[channel shr 12 and 0xf]?.takeIf { it.txOffsetHz != 0L } ?: return null+ return hz(channel)?.plus(t.txOffsetHz)+ }}/** "1-0123" style: the table and the channel number, for a channel whose frequency isn't known yet. */diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.ktindex 588eae0..25f3c26 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt@@ -336,6 +336,16 @@ class RadioWatch {private fun median(a: FloatArray): Float { a.sort(); return if (a.isEmpty()) 0f else a[a.size / 2] }+ /** dB above the noise (the spectrum's median) of the strongest bin within [widthHz] around [offsetHz] from the centre. */+ fun channelSnrDb(psd: FloatArray, sampleRate: Int, offsetHz: Long, widthHz: Long = STEP_HZ): Int {+ val binHz = sampleRate.toDouble() / psd.size+ val mid = psd.size / 2 + (offsetHz / binHz).roundToInt()+ val half = maxOf(1, (widthHz / 2 / binHz).roundToInt())+ val peak = (mid - half..mid + half).filter { it in psd.indices }.maxOfOrNull { psd[it] } ?: return 0+ val noise = psd.sorted()[psd.size / 2]+ return (peak - noise).roundToInt()+ }+/*** 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.diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex 7670e85..6656534 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -37,6 +37,10 @@ object SdrRadio {private const val TUNED_READS = 4 // ~16 ms of samples per waterfall rowprivate const val TUNED_ROW_MS = 40L // at most ~25 rows a secondprivate const val P25_RETRY_MS = 30_000L // no control channel found: look again after this+ private const val INPUT_DELAY_MS = 400L // after a grant: the radio is on the air by then+ private const val INPUT_GAP_MS = 5_000L // at most one input check this often: each costs ~0.2 s of control channel+ private const val INPUT_READS = 16 // ~70 ms of the input+ private const val INPUT_OFFSET_HZ = 250_000L // the input this far above the tuned centre, clear of the DC spike@Volatile var status: String = ""; private set/** ADS-B messages decoded since the app started, for the main screen's messages-per-second line. */@@ -84,6 +88,10 @@ object SdrRadio {val p25Log = P25Log()/** A call started on this talkgroup (the service alerts on watched ones). */@Volatile var onP25Call: ((Int) -> Unit)? = null+ /** Settings › RTL-SDR radio: after a call starts, briefly listen where its radio transmits (the site's input). */+ @Volatile var p25Inputs = false+ /** A call's radio heard on the input: [snrDb] above the noise, so close to you (the call, its input frequency). */+ @Volatile var onP25Input: ((P25History.Call, Long, Int) -> Unit)? = null/*** 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.@@ -424,17 +432,52 @@ object SdrRadio {val where = "%.3f MHz · NAC %03X".format(java.util.Locale.US, lock.hz / 1e6, lock.nac)status = "$deviceLabel · P25 · control channel $where" + turnNote()var messages = 0; var lastStatus = 0L- val lost = hunt.listen(lock, stop) {+ var pending: Pair<P25History.Call, Long>? = null; var lastInput = 0L; var inputs = 0; var heard = 0+ // A call's input: once it's on the air, tune there for a moment and measure it (the control channel comes back after).+ val detour = detour@{+ val (call, hz) = pending ?: return@detour false+ if (System.currentTimeMillis() - call.time < INPUT_DELAY_MS) return@detour false+ pending = null+ val snr = measureInput(sdr, hz) ?: return@detour true+ inputs+++ if (snr >= RadioWatch.activeDb(config.minSnrDb)) { heard++; onP25Input?.invoke(call, hz, snr) }+ true+ }+ val lost = hunt.listen(lock, stop, detour) {messages++; p25Messages++val now = System.currentTimeMillis()for (tg in p25Log.add(it, now)) onP25Call?.invoke(tg)- appContext?.let { c -> P25History.append(c, p25Log.takeCalls()) }+ val calls = p25Log.takeCalls()+ appContext?.let { c -> P25History.append(c, calls) }+ if (p25Inputs && pending == null && now - lastInput >= INPUT_GAP_MS) {+ calls.lastOrNull { it.source != null && it.channel != null }?.let { c ->+ p25Log.inputHz(c.channel!!)?.let { hz -> pending = c to hz; lastInput = now }+ }+ }if (now - lastStatus >= 2_000L && !halted) { lastStatus = now; status = "$deviceLabel · P25 · control channel $where · $messages messages" + turnNote() }}if (lost) p25Lock = nullUsbWifi.log("$deviceLabel: P25 ${if (lost) "control channel went quiet" else "turn over or stopped"} after $messages messages (${hunt.blocks} blocks in all), " +- p25Log.rows().let { r -> "${r.size} talkgroups / private calls, ${r.sumOf { it.calls }} calls" })+ p25Log.rows().let { r -> "${r.size} talkgroups / private calls, ${r.sumOf { it.calls }} calls" } ++ (if (inputs > 0) ", $inputs input checks, $heard radios heard nearby" else ""))+ }+ }++ /** A call's input level in dB above the noise, or null when the tuner didn't get there. Frequency kept off the log. */+ private fun measureInput(sdr: SdrDevice, hz: Long): Int? {+ if (!sdr.tune(hz - INPUT_OFFSET_HZ)) return null+ sdr.resetBuffer()+ val buf = ByteArray(XFER)+ repeat(sdr.settleReads) { sdr.read(buf) }+ val iq = ByteArray(XFER * INPUT_READS)+ var got = 0+ for (i in 0 until INPUT_READS) {+ val n = sdr.read(buf)+ if (n <= 0) break+ System.arraycopy(buf, 0, iq, got, n); got += n}+ if (got < 2 * 1024) return null+ return RadioWatch.channelSnrDb(RadioWatch.powerSpectrum(iq, got / 2), sdr.sampleRate, INPUT_OFFSET_HZ)}/** Holds [tuneHz] for the waterfall screen: a row of the ~2 MHz around it every few tens of ms. */diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 67fd503..d31ed21 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -424,6 +424,8 @@ class ScanForegroundService : Service() {com.rfsentinel.app.sdr.SdrRadio.modes = sdrModescom.rfsentinel.app.sdr.SdrRadio.turnMs = Prefs.sdrTurnS(this) * 1000Lcom.rfsentinel.app.sdr.SdrRadio.onP25Call = { tg -> pipeline.post { onP25Call(tg) } }+ com.rfsentinel.app.sdr.SdrRadio.p25Inputs = Prefs.p25Inputs(this)+ com.rfsentinel.app.sdr.SdrRadio.onP25Input = { call, hz, snr -> pipeline.post { onP25Input(call, hz, snr) } }com.rfsentinel.app.sdr.SdrRadio.location = { (lastLocation ?: lastFix)?.let { it.latitude to it.longitude } }com.rfsentinel.app.sdr.SdrRadio.onAircraft = { planes, unlocated -> onlineWatch.localAircraft(planes, unlocated) }if (sdrModes.isNotEmpty() || radioOn) {@@ -1556,6 +1558,25 @@ class ScanForegroundService : Service() {P25_CONFIDENCE >= Prefs.alertThreshold(this, Category.RADIO))}+ /** A call's radio heard strongly on the site's input: it is keying up close to you. */+ private fun onP25Input(call: com.rfsentinel.app.sdr.P25History.Call, hz: Long, snr: Int) {+ if (!Prefs.categoryEnabled(this, Category.RADIO)) return+ val now = System.currentTimeMillis()+ val min = Prefs.radioMinSnr(this)+ val confidence = if (snr >= min + 10) 75 else 60+ val name = call.tg?.let { com.rfsentinel.app.sdr.P25Log.watched(Prefs.p25Talkgroups(this))[it]?.ifEmpty { null } }+ val called = name ?: call.tg?.let { "talkgroup $it" } ?: "a private call"+ val near = when { snr >= 40 -> "very close"; snr >= 30 -> "close"; else -> "nearby" }+ val mhz = "%.4f".format(java.util.Locale.US, hz / 1e6)+ val detail = "Radio ${call.source} keyed up on $called and was heard on the site's input ($mhz MHz), $snr dB above the " ++ "noise - $near. On the input only radios transmit, so this one is near you, not just somewhere the site covers." ++ (if (call.emergency) " Marked as an emergency call." else "") + (if (call.encrypted) " Encrypted." else "")+ val hit = Hit(Category.RADIO, "P25 radio keyed up $near: $called", confidence, detail,+ "P25 control channel grant + SDR signal strength on the input (no voice)")+ radioDetection(hit, "P25 radio ${call.source}", snr, detail, now, "p25in:${call.tg ?: call.target}",+ "Radio keyed up $near, $called", confidence >= Prefs.alertThreshold(this, Category.RADIO))+ }+private var p25UnusualAt = 0Lprivate val p25UnusualAlerted = HashMap<Int, Long>()diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex dab3ec8..5b81018 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -1390,7 +1390,13 @@ class SettingsActivity : AppCompatActivity() {"Compares each talkgroup's calls in the last hour with the same hour on the days before, from the call log. Alerts when " +"one is at least three times busier than usual, or busy for the first time. Starts after the log has " +"${com.rfsentinel.app.sdr.P25History.BASELINE_DAYS} days in it, and needs the call log kept.") { Prefs.setP25Unusual(this, it) }- val talkgroupViews = (box.childCount - 5 until box.childCount).map { box.getChildAt(it) }+ scan("Listen for radios keying up nearby", Prefs.p25Inputs(this),+ "When a call starts, the SDR leaves the control channel for a fraction of a second and listens where that call's radio " ++ "transmits. A strong signal there means the radio talking is close to you, not just somewhere the site covers. At most " ++ "once every few seconds; the control channel misses a few messages each time. Uses the radio sweep's sensitivity.") {+ Prefs.setP25Inputs(this, it)+ }+ val talkgroupViews = (box.childCount - 6 until box.childCount).map { box.getChildAt(it) }var sweepViews = emptyList<View>() // the sweep's own settings, belowshowSdrOptions = {val ticked = listOf(sweepBox, adsbBox, p25Box).count { it.isChecked }diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 578a59b..cf64949 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -654,6 +654,9 @@ object Prefs {/** Alert when a talkgroup is much busier than usual for the hour ([com.rfsentinel.app.sdr.P25History.unusual]). Off by default. */fun p25Unusual(context: Context): Boolean = bool(context, "p25_unusual", false)fun setP25Unusual(context: Context, v: Boolean) = setBool(context, "p25_unusual", v)+ /** After a call starts, listen for a moment where its radio transmits: strong there, the radio is near you. Off by default. */+ fun p25Inputs(context: Context): Boolean = bool(context, "p25_inputs", false)+ fun setP25Inputs(context: Context, v: Boolean) = setBool(context, "p25_inputs", v)/** Seconds the SDR gives each ticked scan in turn, 30-300: a first P25 search takes up to about 15 s. */fun sdrTurnS(context: Context): Int = int(context, "sdr_turn_s", 60).coerceIn(30, 300)fun setSdrTurnS(context: Context, v: Int) = setInt(context, "sdr_turn_s", v.coerceIn(30, 300))diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.ktindex 82c2a35..bd663e8 100644--- a/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt@@ -39,6 +39,20 @@ class P25TsbkTest {assertNull(ch.hz(0x3001))}+ @Test+ fun channelTableGivesTheRadiosInput() {+ // 800 MHz: radios 45 MHz below (sign clear, 180 × 250 kHz). 700 MHz TDMA: 30 MHz above (sign set, 2400 × 12.5 kHz).+ val low = P25Tsbk.parse(tsbk(0x3D, (1L shl 60) or (180L shl 42) or (50L shl 32) or (851_006_250L / 5))) as P25Tsbk.Iden+ assertEquals(-45_000_000L, low.txOffsetHz)+ val high = P25Tsbk.parse(tsbk(0x33, (2L shl 60) or (3L shl 56) or (((1L shl 13) or 2400L) shl 42) or (100L shl 32) or+ (769_006_250L / 5))) as P25Tsbk.Iden+ assertEquals(30_000_000L, high.txOffsetHz)+ val ch = P25Tsbk.Channels().apply { learn(low); learn(high) }+ assertEquals(851_006_250L + 10 * 6_250 - 45_000_000L, ch.inputHz(0x100A))+ assertEquals(769_006_250L + 2 * 12_500 + 30_000_000L, ch.inputHz(0x2005))+ assertNull(P25Tsbk.Channels().apply { learn(P25Tsbk.Iden(1, 851_006_250L, 6_250, 1)) }.inputHz(0x100A)) // no offset given+ }+@Testfun siteBroadcasts() {// WACN 0xBEE00, system 0x3A1, control channel 0x1040.diff --git a/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.ktindex c7f8ae8..b756034 100644--- a/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt+++ b/app/src/test/java/com/rfsentinel/app/sdr/RadioWatchTest.kt@@ -111,6 +111,15 @@ class RadioWatchTest {assertEquals(n / 2 + (tone / binHz).roundToInt(), peak)}+ @Test+ fun channelSnrIsTheChannelAboveTheNoise() {+ // A P25 input check: a radio 30 dB up on the channel 250 kHz above the centre, nothing 400 kHz up.+ val psd = FloatArray(n) { -100f }+ psd[n / 2 + (250_000 / binHz).roundToInt() + 1] = -70f+ assertEquals(30, RadioWatch.channelSnrDb(psd, rate, 250_000L))+ assertEquals(0, RadioWatch.channelSnrDb(psd, rate, 400_000L))+ }+// ---- Settings > RTL-SDR radio ----@Test