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
Pager messages: POCSAG and FLEX decoding on the SDR (experimental, off by default), kept in memory only; decoders follow multimon-ng
CIS-C043acb7631565
diff --git a/README.md b/README.mdindex 8db01f5..c1aa38b 100644--- a/README.md+++ b/README.md@@ -275,6 +275,7 @@ Everything the app does, grouped by area.- The ALFA AWUS036ACS's light blinks with received traffic (Settings → External hardware switches it off, for the adapters whose light the app can control)- RTL-SDR and HackRF transmissions show on the **radar** too, for a minute after they were last heard- **P25 control channel** (experimental, RTL-SDR): finds the trunked-radio control channel and lists which talkgroups get a channel and when (Tools → P25 talkgroups), with alerts for talkgroups you watch. Signalling only, voice is never decoded. With more than one SDR scan ticked (radio sweep, ADS-B, P25) the dongle takes turns+- **Pager messages** (experimental, RTL-SDR or HackRF, off by default): decodes POCSAG and FLEX pages (Tools → Pager messages), kept in memory only- **More from every frame:** WPS maker / model / device name, a **probe fingerprint** that survives MAC randomization (watchable: "every device of this type"), and the real name of **hidden networks** when a device joins them</details>@@ -770,9 +771,17 @@ talkgroups with their calls, last channel and radio, and emergency / encrypted fand *Watch these talkgroups* alerts when a call starts on one. Voice is neverdecoded, and the frequency and network code stay out of the logs. Receiving radiosignalling is legal in many places but not all: check the law where you are. With-more than one SDR scan ticked (radio sweep, ADS-B, P25), the dongle takes turns of+more than one SDR scan ticked (radio sweep, ADS-B, P25, pagers), the dongle takes turns ofthe length you set.+**Pager messages** (experimental, Settings → *RTL-SDR radio*, off by default): finds+paging channels and decodes POCSAG (512 / 1200 / 2400 baud) and FLEX pages into+**Tools → Pager messages**. Pages can hold private or medical details, so they stay in+the phone's memory: never saved, exported or sent, kept out of the logs, and gone when the+app closes or you untick the setting. Canada, the United States and many other places+restrict using or passing on messages you intercept, and some forbid listening at all:+check the law where you are.+<details><summary><b>How a nearby transmitter is told apart, settings and requested networks</b></summary>@@ -1230,7 +1239,9 @@ shape is [FlipDeFlock](https://github.com/ReconGrunt/FlipDeFlock)'s IE skeletonso its values match, with its candidate and generic shape lists (GPL-3.0). The ADS-B decoderis written from the published format and Junzi Sun's *The 1090 MHz Riddle*, with[SkyPulse](https://github.com/MrJohn6774/SkyPulse) (GPL-3.0) and-[dump1090](https://github.com/antirez/dump1090) (BSD-3-Clause) as references. Two fake-cell+[dump1090](https://github.com/antirez/dump1090) (BSD-3-Clause) as references. The POCSAG and+FLEX pager decoders follow [multimon-ng](https://github.com/EliasOenal/multimon-ng) (GPL; see+`sdr/NOTICE.md`). Two fake-cellchecks follow [AIMSICD](https://github.com/CellularPrivacy/Android-IMSI-Catcher-Detector) and[SnoopSnitch](https://github.com/srlabs/snoopsnitch) (GPL-3.0; ideas only). European V2X (ITS-G5) frames are read the way[V2X2MAP](https://github.com/pit711/V2X2MAP) by Peter Holzhauser does (MIT; seediff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex cf3e957..13930c9 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -120,6 +120,7 @@<activity android:name=".ui.AntennaCheckActivity" android:exported="false" /><activity android:name=".ui.AircraftActivity" android:exported="false" /><activity android:name=".ui.P25Activity" android:exported="false" />+ <activity android:name=".ui.PagerActivity" android:exported="false" /><activity android:name=".ui.WaterfallActivity" android:exported="false"android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize" /><activitydiff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex f21ddad..5c5517d 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -231,10 +231,12 @@ class MainActivity : AppCompatActivity() {menu.add(0, 6, 5, "Aircraft")menu.add(0, 7, 6, "Radio waterfall")menu.add(0, 8, 7, "P25 talkgroups")+ menu.add(0, 9, 8, "Pager messages")setOnMenuItemClickListener { item ->when (item.itemId) {7 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.WaterfallActivity::class.java))8 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.P25Activity::class.java))+ 9 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.PagerActivity::class.java))6 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AircraftActivity::class.java).putExtra("demo", demoMode))5 -> startActivity(Intent(this@MainActivity, com.rfsentinel.app.ui.AntennaCheckActivity::class.java)@@ -521,6 +523,7 @@ class MainActivity : AppCompatActivity() {when (com.rfsentinel.app.sdr.SdrRadio.mode) {com.rfsentinel.app.sdr.SdrRadio.Mode.ADSB -> ({ com.rfsentinel.app.sdr.SdrRadio.adsbMessages })com.rfsentinel.app.sdr.SdrRadio.Mode.P25 -> ({ com.rfsentinel.app.sdr.SdrRadio.p25Messages })+ com.rfsentinel.app.sdr.SdrRadio.Mode.PAGER -> ({ com.rfsentinel.app.sdr.SdrRadio.pagerLog.total })else -> null}, " msg/s")},diff --git a/app/src/main/java/com/rfsentinel/app/sdr/Flex.kt b/app/src/main/java/com/rfsentinel/app/sdr/Flex.ktnew file mode 100644index 0000000..6e948a0--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/Flex.kt@@ -0,0 +1,283 @@+package com.rfsentinel.app.sdr++import java.lang.Integer.bitCount+import java.lang.Integer.reverse+import kotlin.math.abs++/** Follows a stream's symbol edges by its zero crossings. */+internal class SymbolClock(private val sampleRate: Int, var baud: Int) {+ private var phase = 0.0 // through the symbol, 0 to 1+ private var last = 0.0+ /** In the middle of a symbol, clear of its edges. */+ val mid get() = phase > 0.1 && phase < 0.9++ /** [x] crossed zero: pulls the edge towards it by [rate]. */+ fun crossed(x: Double, rate: Double): Boolean {+ val crossed = (last < 0 && x >= 0) || (last >= 0 && x < 0)+ last = x+ if (crossed) phase -= (if (phase < 0.5) phase else phase - 1) * rate+ return crossed+ }++ /** One sample on: true when that ends a symbol. */+ fun advance(): Boolean {+ phase += baud.toDouble() / sampleRate+ if (phase <= 1) return false+ phase -= 1+ return true+ }+}++/**+ * FLEX pager messages from the FM-demodulated signal (any scale), a port of multimon-ng's demod_flex.c (see NOTICE.md).+ * A frame is 1.875 s: a 1600 baud two-level header (sync with the speed in it, then the frame information word), and+ * 1.76 s of data at 1600 or 3200 baud, two or four levels, carrying one to four interleaved phases of 88 words.+ * Each phase is a block information word, addresses, a vector per address, and the messages they point to.+ *+ * shortcut: group messages show under the group's address, fragments of a long page as separate partial rows, binary pages+ * and the digits in tone pages are dropped, long addresses read as short ones (as upstream); upgrade if real pages need them.+ * Pure (no Android): unit-tested.+ */+class Flex(sampleRate: Int, private val onPage: (PagerLog.Page) -> Unit) {++ private enum class State { SYNC1, FIW, SYNC2, DATA }++ /** Frame headers that passed their checks: a real FLEX signal, even with no page in it. */+ var frames = 0; private set++ private val clock = SymbolClock(sampleRate, HEADER_BAUD)+ private val zeroSamples = sampleRate * ZERO_S+ private var zero = 0.0+ private var envelope = 0.0; private var envelopeSum = 0.0; private var envelopeN = 0+ private var locked = false+ private var lockBuf = 0L+ private val symbols = IntArray(4)+ private var timeout = 0+ private var nonConsecutive = 0++ private var state = State.SYNC1+ private var syncBuf = 0L+ private var inverted = false+ private var baud = HEADER_BAUD+ private var levels = 2+ private var fiw = 0; private var fiwCount = 0+ private var sync2Count = 0+ private var dataCount = 0+ private val phases = Array(4) { IntArray(WORDS) }+ private var toggle = false+ private var dataBits = 0++ fun sample(raw: Double) {+ if (state == State.SYNC1) zero = (zero * zeroSamples + raw) / (zeroSamples + 1)+ val x = raw - zero+ if (locked) {+ if (state == State.SYNC1) { envelopeSum += abs(x); envelope = envelopeSum / ++envelopeN }+ } else {+ envelope = 0.0; envelopeSum = 0.0; envelopeN = 0+ clock.baud = HEADER_BAUD; timeout = 0; nonConsecutive = 0+ state = State.SYNC1+ }+ val mid = clock.mid+ if (mid) symbols[if (x > 0) (if (x > envelope * SLICE) 3 else 2) else (if (x < -envelope * SLICE) 0 else 1)]+++ if (clock.crossed(x, if (locked) LOCKED_RATE else UNLOCKED_RATE)) {+ // Crossings in mid-symbol: the clock isn't on this signal any more.+ if (!mid) nonConsecutive = 0 else if (++nonConsecutive > MAX_NON_CONSECUTIVE) locked = false+ timeout = 0+ }+ if (clock.advance()) symbolEnd()+ }++ private fun symbolEnd() {+ nonConsecutive = 0+ var modal = 0+ for (j in 1..3) if (symbols[j] > symbols[modal]) modal = j+ symbols.fill(0)+ if (locked) symbol(modal)+ else {+ // The bit sync: outer levels, alternating.+ lockBuf = lockBuf shl 2 or (modal xor 1).toLong()+ val pattern = lockBuf xor LOCK_PATTERN+ if (pattern and LOCK_MASK == 0L || pattern.inv() and LOCK_MASK == 0L) { locked = true; lockBuf = 0 }+ }+ if (++timeout > MAX_TIMEOUT) locked = false+ }++ private fun symbol(raw: Int) {+ val sym = if (inverted) 3 - raw else raw+ when (state) {+ State.SYNC1 -> {+ val code = sync(raw)+ if (code != 0 && mode(code)) state = State.FIW+ fiwCount = 0; fiw = 0+ }+ State.FIW -> {+ // 16 bits of dotting, then the frame information word.+ if (++fiwCount >= 16) fiw = (fiw ushr 1) or (if (sym > 1) Int.MIN_VALUE else 0)+ if (fiwCount == 48) {+ if (fiwGood()) { frames++; sync2Count = 0; clock.baud = baud; state = State.SYNC2 }+ else state = State.SYNC1+ }+ }+ State.SYNC2 -> if (++sync2Count == baud * 25 / 1000) {+ dataCount = 0; toggle = false; dataBits = 0+ phases.forEach { it.fill(0) }+ state = State.DATA+ }+ State.DATA -> {+ readData(sym)+ if (++dataCount == baud * 1760 / 1000) {+ decodeData()+ clock.baud = HEADER_BAUD+ state = State.SYNC1+ }+ }+ }+ }++ /** The sync's speed code, either polarity; 0 until one is complete. */+ private fun sync(raw: Int): Int {+ syncBuf = syncBuf shl 1 or (if (raw < 2) 1L else 0L)+ val code = syncCode(syncBuf)+ if (code != 0) { inverted = false; return code }+ return syncCode(syncBuf.inv()).also { if (it != 0) inverted = true }+ }++ /** AAAA:A6C6AAAA:~AAAA, a few bits off allowed in each part. */+ private fun syncCode(buf: Long): Int {+ val marker = (buf ushr 16).toInt()+ val high = (buf ushr 48).toInt() and 0xFFFF+ val low = buf.toInt().inv() and 0xFFFF+ return if (bitCount(marker xor MARKER) < 4 && bitCount(low xor high) < 4) high else 0+ }++ private fun mode(code: Int): Boolean {+ val m = MODES.firstOrNull { bitCount(it[0] xor code) < 4 } ?: return false+ baud = m[1]; levels = m[2]+ return true+ }++ private fun fix(word: Int): Int? = Bch3121.correct(reverse(word))?.let { reverse(it) }++ private fun fiwGood(): Boolean {+ val w = fix(fiw) ?: return false+ val sum = (w and 0xF) + ((w ushr 4) and 0xF) + ((w ushr 8) and 0xF) + ((w ushr 12) and 0xF) + ((w ushr 16) and 0xF) + ((w ushr 20) and 1)+ return sum and 0xF == 0xF+ }++ private fun readData(sym: Int) {+ val a = sym > 1+ val b = levels == 4 && (sym == 1 || sym == 2)+ if (baud == HEADER_BAUD) toggle = false+ // Deinterleaves: bits of eight words at a time, one bit of each in turn.+ val word = ((dataBits ushr 5) and 0xFFF8) or (dataBits and 7)+ val first = if (toggle) 2 else 0+ phases[first][word] = (phases[first][word] ushr 1) or (if (a) Int.MIN_VALUE else 0)+ phases[first + 1][word] = (phases[first + 1][word] ushr 1) or (if (b) Int.MIN_VALUE else 0)+ toggle = !toggle+ if (baud == HEADER_BAUD || !toggle) dataBits+++ }++ private fun decodeData() {+ decodePhase(phases[0])+ if (levels == 4) decodePhase(phases[1])+ if (baud != HEADER_BAUD) {+ decodePhase(phases[2])+ if (levels == 4) decodePhase(phases[3])+ }+ }++ private fun decodePhase(p: IntArray) {+ for (i in p.indices) p[i] = (fix(p[i]) ?: return) and DATA_MASK+ val biw = p[0]+ if (biw == 0 || biw == DATA_MASK) return+ val vectors = (biw ushr 10) and 0x3f+ val addresses = ((biw ushr 8) and 3) + 1+ if (vectors < addresses || vectors + (vectors - addresses) > WORDS) return+ for (i in addresses until vectors) {+ val address = p[i]+ if (address == 0 || address == DATA_MASK) continue+ val capcode = address - 0x8000L+ if (capcode < 0) continue+ val long = address < 0x8001 || address > 0x1E0000+ val j = vectors + i - addresses+ val vector = p[j]+ val type = (vector ushr 4) and 7+ val start = (vector ushr 7) and 0x7f+ val end = start + ((vector ushr 14) and 0x7f) - 1+ if (type == TYPE_SHORT_INSTRUCTION || (start == 0 && end == 0)) continue+ val protocol = "FLEX $baud/$levels"+ when (type) {+ TYPE_SECURE, TYPE_ALPHA -> if (start < WORDS && end < WORDS) alpha(p, start, end, protocol, capcode)+ TYPE_NUMERIC, TYPE_SPECIAL_NUMERIC, TYPE_NUMBERED_NUMERIC ->+ numeric(p, j, type, long)?.let { onPage(PagerLog.Page(protocol, capcode, PagerLog.Kind.NUMERIC, it)) }+ TYPE_TONE -> onPage(PagerLog.Page(protocol, capcode, PagerLog.Kind.TONE, ""))+ }+ }+ }++ /** Three 7-bit characters a word after a header word; a whole page's first character is a signature, not text. */+ private fun alpha(p: IntArray, start: Int, end: Int, protocol: String, capcode: Long) {+ val fragment = (p[start] ushr 11) and 3+ val continued = (p[start] ushr 10) and 1 == 1+ val codes = ArrayList<Int>()+ for (i in start + 1..end) {+ if (i > start + 1 || fragment != 3) codes += p[i] and 0x7F+ codes += (p[i] ushr 7) and 0x7F+ codes += (p[i] ushr 14) and 0x7F+ }+ onPage(PagerLog.Page(protocol, capcode, PagerLog.Kind.ALPHA, pageText(codes), continued || fragment != 3))+ }++ /** Digits run through 21-bit words, after a few header bits; null when the vector points outside the phase. */+ private fun numeric(p: IntArray, j: Int, type: Int, long: Boolean): String? {+ var first = (p[j] ushr 7) and 0x7f+ var last = ((p[j] ushr 14) and 7) + first+ if (first >= WORDS || last >= WORDS || (long && j + 1 >= WORDS)) return null+ // A long address has its first digits in the second vector word.+ var dw = if (long) p[j + 1] else p[first++].also { last++ }+ var digit = 0+ var count = if (type == TYPE_NUMBERED_NUMERIC) 14 else 6+ return buildString {+ for (i in first..last) {+ repeat(21) {+ digit = (digit ushr 1) or ((dw and 1) shl 3)+ dw = dw ushr 1+ if (--count == 0) {+ if (digit != FILL) append(BCD[digit])+ count = 4+ }+ }+ if (i < last) dw = p[i]+ }+ }+ }++ companion object {+ private const val HEADER_BAUD = 1600+ private const val WORDS = 88+ private const val DATA_MASK = 0x1FFFFF+ private const val MARKER = 0xA6C6AAAA.toInt()+ private const val SLICE = 0.667 // four levels: the outer ones are three times the inner+ private const val ZERO_S = 0.010+ private const val LOCKED_RATE = 0.045+ private const val UNLOCKED_RATE = 0.050+ private const val LOCK_PATTERN = 0x6666666666666666L+ private const val LOCK_MASK = (1L shl 48) - 1 // 24 symbols+ private const val MAX_TIMEOUT = 100 // symbols with no zero crossing+ private const val MAX_NON_CONSECUTIVE = 20+ private const val FILL = 0xC+ private const val BCD = "0123456789 U -]["+ private const val TYPE_SECURE = 0+ private const val TYPE_SHORT_INSTRUCTION = 1+ private const val TYPE_TONE = 2+ private const val TYPE_NUMERIC = 3+ private const val TYPE_SPECIAL_NUMERIC = 4+ private const val TYPE_ALPHA = 5+ private const val TYPE_NUMBERED_NUMERIC = 7+ /** Speed code, baud, levels. */+ private val MODES = listOf(+ intArrayOf(0x870C, 1600, 2), intArrayOf(0xB068, 1600, 4),+ intArrayOf(0x7B18, 3200, 2), intArrayOf(0xDEA0, 3200, 4), intArrayOf(0x4C7C, 3200, 4)+ )+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/NOTICE.md b/app/src/main/java/com/rfsentinel/app/sdr/NOTICE.mdindex 99ed495..f181cdd 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/NOTICE.md+++ b/app/src/main/java/com/rfsentinel/app/sdr/NOTICE.md@@ -23,3 +23,14 @@ The ISC license of DSD and mbelib:> PERFORMANCE OF THIS SOFTWARE.IMBE is a voice coding method of Digital Voice Systems, Inc. (DVSI); the P25 standard (TIA-102.BABA) describes it.++# Pager messages: sources and licenses++- `Flex.kt` is a Kotlin port of multimon-ng's FLEX decoder: symbol recovery, frame state machine, phase, address and message parsing.+- `Pocsag.kt` follows multimon-ng's POCSAG decoder and its BCH(31,21) error correction, rewritten for one table shared with FLEX.++| Part | Origin | License |+|---|---|---|+| FLEX decoder (`demod_flex.c`) | [multimon-ng](https://github.com/EliasOenal/multimon-ng), adapted from GNU Radio: Copyright 2004, 2006, 2010 Free Software Foundation, Inc.; (C) 2015 Craig Shelley; (C) 2024 Jason Lingohr | GPL-3.0-or-later |+| POCSAG decoder (`pocsag.c`) | [multimon-ng](https://github.com/EliasOenal/multimon-ng): (C) 1996 Thomas Sailer; (C) 2012-2014 Elias Oenal and others | GPL-2.0-or-later |+| BCH(31,21) correction (`bch.c`) | [multimon-ng](https://github.com/EliasOenal/multimon-ng) | Public domain (Unlicense) |diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.ktindex 7f765ee..9e2f3bf 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt@@ -176,15 +176,16 @@ class P25Demod(offsetHz: Double, private val frameDibits: Int = FRAME_DIBITS, prelse -> 3}- /** Channel low-pass at 48 kS/s: windowed sinc, cut at 6.25 kHz. */- private val TAPS: DoubleArray = run {- val len = 31; val fc = 6_250.0 / CHANNEL_RATE+ /** Channel low-pass at 48 kS/s: windowed sinc, cut at [cutHz]. */+ internal fun lowPass(cutHz: Double): DoubleArray {+ val len = 31; val fc = cutHz / CHANNEL_RATEval t = DoubleArray(len) { k ->val x = k - (len - 1) / 2.0val sinc = if (x == 0.0) 2 * fc else sin(2 * PI * fc * x) / (PI * x)sinc * (0.54 - 0.46 * cos(2 * PI * k / (len - 1)))}- val sum = t.sum(); DoubleArray(len) { t[it] / sum }+ val sum = t.sum(); return DoubleArray(len) { t[it] / sum }}+ private val TAPS = lowPass(6_250.0)}}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.ktindex e386a79..81186a6 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt@@ -53,26 +53,12 @@ class P25Hunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}/** The control channel heard best here, or null (none on the air, or [stop]). */fun hunt(stop: () -> Boolean): Lock? {sdr.setSampleRate(P25Demod.SAMPLE_RATE)- val found = ArrayList<Candidate>()- val iq = ByteArray(XFER * SCAN_READS)val plan = plan()- var unlocked = 0; var short = 0- for (center in plan) {- if (stop()) return null- if (!sdr.tune(center)) { unlocked++; continue }- repeat(sdr.settleReads) { sdr.read(buf) }- var got = 0- for (i in 0 until SCAN_READS) {- val n = sdr.read(buf)- if (n <= 0) break- System.arraycopy(buf, 0, iq, got, n); got += n- }- if (got >= 2 * 1024) found += candidates(center, RadioWatch.powerSpectrum(iq, got / 2), sdr.sampleRate) else short++- }- val ranked = strongest(found)+ val scan = scan(sdr, plan, stop) ?: return null+ val ranked = strongest(scan.found)val tries = ranked.take(MAX_TRIES)// Frequencies and network codes stay off the log (they name the local system); bands and levels say enough.- log("P25 scan: ${plan.size} steps, tuner didn't lock $unlocked, no samples $short, ${ranked.size} channels " ++ log("P25 scan: ${plan.size} steps, tuner didn't lock ${scan.unlocked}, no samples ${scan.short}, ${ranked.size} channels " +"${MIN_SNR_DB.toInt()} dB or more above the noise (700 MHz ${ranked.count { it.hz < 800_000_000L }}, " +"800 MHz ${ranked.count { it.hz >= 800_000_000L }}), strongest ${tries.joinToString { "%.0f".format(it.snrDb) }} dB")tried = 0@@ -185,8 +171,31 @@ class P25Hunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}/** Tuned centres a little closer than the usable width: every channel is seen twice, once well away from DC. */private const val STEP_HZ = 750_000L- internal fun plan(): List<Long> =- BANDS.flatMap { b -> generateSequence(b.first - STEP_HZ / 2) { it + STEP_HZ }.takeWhile { it <= b.last + STEP_HZ / 2 }.toList() }+ internal fun plan(bands: List<LongRange> = BANDS): List<Long> =+ bands.flatMap { b -> generateSequence(b.first - STEP_HZ / 2) { it + STEP_HZ }.takeWhile { it <= b.last + STEP_HZ / 2 }.toList() }++ internal class Scan(val found: List<Candidate>, val unlocked: Int, val short: Int)++ /** Looks at each tuned centre of [plan] for channels that are on; null when [stop] said so. */+ internal fun scan(sdr: SdrDevice, plan: List<Long>, stop: () -> Boolean): Scan? {+ val buf = ByteArray(XFER)+ val found = ArrayList<Candidate>()+ val iq = ByteArray(XFER * SCAN_READS)+ var unlocked = 0; var short = 0+ for (center in plan) {+ if (stop()) return null+ if (!sdr.tune(center)) { unlocked++; continue }+ repeat(sdr.settleReads) { sdr.read(buf) }+ var got = 0+ for (i in 0 until SCAN_READS) {+ val n = sdr.read(buf)+ if (n <= 0) break+ System.arraycopy(buf, 0, iq, got, n); got += n+ }+ if (got >= 2 * 1024) found += candidates(center, RadioWatch.powerSpectrum(iq, got / 2), sdr.sampleRate) else short+++ }+ return Scan(found, unlocked, short)+ }/** Channel-wide peaks [MIN_SNR_DB] above the noise in one tuned chunk, at their power-weighted centre. */internal fun candidates(center: Long, psd: FloatArray, sampleRate: Int): List<Candidate> {diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Record.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Record.ktindex 2d31206..0f9ceeb 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/P25Record.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Record.kt@@ -25,8 +25,8 @@ object P25Record {/** 8-bit samples summed [P25Demod.DECIM] at a time reach ±5100: this fills 16 bits without clipping. */private const val SCALE = 6.0- /** Mixes [offsetHz] down to 0 and integrates-and-dumps to [RATE], collecting 16-bit I/Q pairs. */- class Baseband(val offsetHz: Long, sampleRate: Int = P25Demod.SAMPLE_RATE) {+ /** Mixes [offsetHz] down to 0 and integrates-and-dumps to [RATE], collecting 16-bit I/Q pairs, or handing each to [onSample]. */+ class Baseband(val offsetHz: Long, sampleRate: Int = P25Demod.SAMPLE_RATE, private val onSample: ((Double, Double) -> Unit)? = null) {private val decim = sampleRate / RATEprivate val stepR: Double; private val stepI: Doubleinit { val w = -2 * PI * offsetHz / sampleRate; stepR = cos(w); stepI = sin(w) }@@ -47,7 +47,8 @@ object P25Record {val nr = pr * stepR - pi * stepIpi = pr * stepI + pi * stepR; pr = nrif (++accN == decim) {- short(accR); short(accI); samples+++ if (onSample != null) onSample.invoke(accR, accI) else { short(accR); short(accI) }+ samples++accN = 0; accR = 0.0; accI = 0.0val m = 1.5 - 0.5 * (pr * pr + pi * pi); pr *= m; pi *= m // keeps the phasor on the unit circle}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/PagerDemod.kt b/app/src/main/java/com/rfsentinel/app/sdr/PagerDemod.ktnew file mode 100644index 0000000..398a3fb--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/PagerDemod.kt@@ -0,0 +1,63 @@+package com.rfsentinel.app.sdr++import kotlin.math.PI+import kotlin.math.atan2++/**+ * Pager messages, first stage: the SDR's raw I/Q to pages. Picks the channel [offsetHz] from the tuned centre (mixed and+ * cut to 48 kS/s as for P25), FM-demodulates it and hands it to POCSAG at its three speeds and to FLEX at once: a+ * channel doesn't say which it is. Pure (no Android): unit-tested on a synthetic signal.+ */+class PagerDemod(offsetHz: Long, onPage: (PagerLog.Page) -> Unit) {++ private class PocsagRx(baud: Int, onPage: (PagerLog.Page) -> Unit) {+ val decoder = Pocsag(baud, onPage)+ private val clock = SymbolClock(RATE, baud)+ private var sum = 0.0+ fun sample(x: Double) {+ if (clock.mid) sum += x+ clock.crossed(x, CLOCK_RATE)+ if (clock.advance()) { decoder.bit(sum > 0); sum = 0.0 }+ }+ }++ private val pocsag = listOf(512, 1200, 2400).map { PocsagRx(it, onPage) }+ private val flex = Flex(RATE, onPage)+ private val baseband = P25Record.Baseband(offsetHz, onSample = ::channelSample)++ /** POCSAG batches and FLEX frames that checked out: the channel really carries pages. */+ val frames get() = flex.frames + pocsag.sumOf { it.decoder.batches }++ private val firR = DoubleArray(TAPS.size); private val firI = DoubleArray(TAPS.size); private var firAt = 0+ private var lastR = 0.0; private var lastI = 0.0+ private val box = DoubleArray(BOX); private var boxAt = 0; private var boxSum = 0.0+ private var dc = 0.0++ /** Unsigned 8-bit I/Q as the dongle delivers it: [count] complex samples from [buf]. */+ fun feed(buf: ByteArray, count: Int) = baseband.feed(buf, count)++ private fun channelSample(r: Double, i: Double) {+ firR[firAt] = r; firI[firAt] = i+ var yr = 0.0; var yi = 0.0; var j = firAt+ for (t in TAPS) { yr += t * firR[j]; yi += t * firI[j]; if (--j < 0) j = TAPS.size - 1 }+ if (++firAt == TAPS.size) firAt = 0+ val hz = atan2(yi * lastR - yr * lastI, yr * lastR + yi * lastI) * RATE / (2 * PI)+ lastR = yr; lastI = yi+ // Smoothed, or noise on the discriminator makes false zero crossings for the symbol clocks.+ boxSum += hz - box[boxAt]; box[boxAt] = hz; if (++boxAt == BOX) boxAt = 0+ val x = boxSum / BOX+ // The carrier is only about on the channel's centre (crystal error): the slow average is where zero is.+ dc += (x - dc) / DC_SAMPLES+ for (p in pocsag) p.sample(x - dc)+ flex.sample(x)+ }++ companion object {+ private const val RATE = P25Demod.CHANNEL_RATE+ private const val CLOCK_RATE = 0.05+ private const val BOX = 6+ private const val DC_SAMPLES = 2_400.0 // 50 ms+ /** Up to ±4.8 kHz deviation, plus the signal's own width. */+ private val TAPS = P25Demod.lowPass(8_000.0)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/PagerHunt.kt b/app/src/main/java/com/rfsentinel/app/sdr/PagerHunt.ktnew file mode 100644index 0000000..8f345f6--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/PagerHunt.kt@@ -0,0 +1,76 @@+package com.rfsentinel.app.sdr++/**+ * Pager messages, second stage: finds a paging channel and stays on it. [hunt] looks over the paging bands the way+ * [P25Hunt] does and listens to the strongest carriers in turn; the first that decodes is the channel. [listen] then+ * stays until nothing has decoded for [QUIET_S]. Paging transmitters can be silent between pages, so a channel missed now+ * shows up on a later look. Frequencies, capcodes and text stay off the log: counts and levels only.+ */+class PagerHunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}) {++ /** Channels listened to in the last hunt, for the log. */+ var tried = 0; private set++ private val buf = ByteArray(XFER)++ /** The first paging channel that decodes, strongest first, or null. Pages heard on the way go to [onPage]. */+ fun hunt(stop: () -> Boolean, onPage: (PagerLog.Page, Long) -> Unit): Long? {+ sdr.setSampleRate(P25Demod.SAMPLE_RATE)+ val plan = P25Hunt.plan(BANDS)+ val scan = P25Hunt.scan(sdr, plan, stop) ?: return null+ val ranked = P25Hunt.strongest(scan.found)+ val tries = ranked.take(MAX_TRIES)+ log("Pager scan: ${plan.size} steps, tuner didn't lock ${scan.unlocked}, no samples ${scan.short}, ${ranked.size} carriers, " ++ "strongest ${tries.joinToString { "%.0f".format(it.snrDb) }} dB")+ tried = 0+ for (c in tries) {+ if (stop()) return null+ tried+++ val heard = receive(c.hz, TRIAL_S, true, stop, onPage)+ log("Pager try $tried/${tries.size}: %.0f dB: ${if (heard) "paging channel" else "nothing decoded"}".format(c.snrDb))+ if (heard) return c.hz+ }+ return null+ }++ /** Stays on [hz], pages to [onPage]: false when [stop] said so, true when it went quiet (hunt again). */+ fun listen(hz: Long, stop: () -> Boolean, onPage: (PagerLog.Page, Long) -> Unit): Boolean {+ sdr.setSampleRate(P25Demod.SAMPLE_RATE)+ receive(hz, QUIET_S, false, stop, onPage)+ return !stop()+ }++ /** Decodes [hz] until [stop] or [quietS] without a good frame ([once]: or the first one). True when a frame was heard. */+ private fun receive(hz: Long, quietS: Double, once: Boolean, stop: () -> Boolean, onPage: (PagerLog.Page, Long) -> Unit): Boolean {+ if (!sdr.tune(hz - OFFSET_HZ)) { log("Pager: the tuner didn't lock"); return false }+ sdr.resetBuffer()+ repeat(sdr.settleReads) { sdr.read(buf) }+ val demod = PagerDemod(OFFSET_HZ) { onPage(it, hz) }+ var samples = 0L; var lastGood = 0L; var seen = 0; var fails = 0+ while (!stop()) {+ val n = sdr.read(buf)+ if (n <= 0) { if (++fails % STALL_READS == 0) sdr.resetBuffer(); continue }+ fails = 0+ demod.feed(buf, n / 2); samples += n / 2+ if (demod.frames > seen) {+ seen = demod.frames; lastGood = samples+ if (once) break+ }+ if (samples - lastGood > quietS * P25Demod.SAMPLE_RATE) break+ }+ return seen > 0+ }++ companion object {+ /** Paging channels around the world, base-station side. */+ val BANDS = listOf(152_000_000L..153_000_000L, 157_400_000L..158_700_000L, 169_400_000L..169_800_000L,+ 465_900_000L..466_300_000L, 929_000_000L..932_000_000L)+ private const val XFER = 16_384+ private const val OFFSET_HZ = 250_000L // clear of the receiver's DC spike+ private const val MAX_TRIES = 6+ private const val TRIAL_S = 3.0 // a FLEX frame is 1.875 s; a busy POCSAG channel sends within this+ /** Under the shortest turn: a channel gone silent must be noticed within a turn, not start over each time. */+ const val QUIET_S = 25.0+ private const val STALL_READS = 8+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/PagerLog.kt b/app/src/main/java/com/rfsentinel/app/sdr/PagerLog.ktnew file mode 100644index 0000000..4bfee79--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/PagerLog.kt@@ -0,0 +1,29 @@+package com.rfsentinel.app.sdr++/**+ * Pages heard this session (the Pager messages screen). In memory only, on purpose: pages can hold private or medical+ * details, so they are never saved, exported or sent, and go when the app closes or the setting is turned off.+ */+class PagerLog {++ enum class Kind { NUMERIC, ALPHA, TONE }+ /** [partial]: part of the page is missing (a garbled word, or a FLEX fragment). */+ data class Page(val protocol: String, val capcode: Long, val kind: Kind, val text: String, val partial: Boolean = false)+ data class Row(val page: Page, val hz: Long, val at: Long)++ private val rows = ArrayDeque<Row>()+ /** Pages heard since the app started, for the main screen's messages-per-second line. */+ @Volatile var total = 0L; private set++ @Synchronized fun add(page: Page, hz: Long, at: Long) {+ rows.addFirst(Row(page, hz, at))+ if (rows.size > MAX) rows.removeLast()+ total+++ }++ /** Newest first. */+ @Synchronized fun rows(): List<Row> = rows.toList()+ @Synchronized fun clear() = rows.clear()++ companion object { const val MAX = 500 }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/Pocsag.kt b/app/src/main/java/com/rfsentinel/app/sdr/Pocsag.ktnew file mode 100644index 0000000..77eb98a--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/sdr/Pocsag.kt@@ -0,0 +1,158 @@+package com.rfsentinel.app.sdr++import java.lang.Integer.bitCount++/**+ * The BCH(31,21) code of POCSAG and FLEX, generator 0x769, plus even parity. Works on POCSAG's word layout: codeword in+ * bits 31..1, first bit sent highest, parity in bit 0. A FLEX word is the same layout bit-reversed.+ */+internal object Bch3121 {+ private const val POLY = 0x769++ /** Remainder of the codeword by the generator: 0 when it is clean. */+ fun syndrome(word: Int): Int {+ var r = word ushr 1+ for (i in 20 downTo 0) if ((r ushr (i + 10)) and 1 != 0) r = r xor (POLY shl i)+ return r+ }++ /** Syndrome to the one or two codeword bits that cause it; 0 when no such error does. */+ private val ERRORS = IntArray(1024).also { t ->+ for (i in 1..31) t[syndrome(1 shl i)] = 1 shl i+ for (i in 1..31) for (j in i + 1..31) {+ val s = syndrome(1 shl i) xor syndrome(1 shl j)+ if (t[s] == 0) t[s] = (1 shl i) or (1 shl j)+ }+ }++ /**+ * [word] with up to two bit errors in the codeword fixed, or null. The parity bit rejects a fix that three or more errors+ * made look valid: without it about half of random words would pass.+ */+ fun correct(word: Int): Int? {+ val s = syndrome(word)+ if (s == 0) return if (bitCount(word) and 1 == 0) word else word xor 1+ val error = ERRORS[s]+ if (error == 0) return null+ return (word xor error).takeIf { bitCount(it) and 1 == 0 }+ }+}++/** Text from 7-bit characters: printable ones kept, line breaks as spaces, other control codes dropped. */+internal fun pageText(codes: List<Int>): String = buildString {+ for (c in codes) when (c) {+ in 0x20..0x7e -> append(c.toChar())+ 0x0a, 0x0d -> append(' ')+ }+}.trim()++/**+ * POCSAG pager messages from a stream of bits, at one speed ([baud]): frame sync (either polarity, so it doesn't matter+ * which way up the receiver has the signal), then batches of 16 codewords with the sync between them. An address word+ * starts a page, message words add to it, and an idle word or the next address ends it. A page's frame in the batch is+ * the low three bits of its capcode.+ *+ * Pages wait for the end of their batch: a false sync on noise gets past the error correction often enough to+ * make up a page, but not for a whole batch. Pure (no Android): unit-tested. Follows multimon-ng's pocsag.c (see NOTICE.md).+ */+class Pocsag(private val baud: Int, private val onPage: (PagerLog.Page) -> Unit) {++ /** Batches that ended in a sync: a real POCSAG signal, even with no page in them. */+ var batches = 0; private set++ private var reg = 0+ private var synced = false+ private var inverted = false+ private var bits = 0+ private var at = 0 // next codeword in the batch; BATCH: the sync is next+ private var bad = 0 // words past correcting in this batch+ private var capcode = -1L // the page being read+ private var function = 0+ private val words = ArrayList<Int>()+ private val pending = ArrayList<PagerLog.Page>()++ fun bit(one: Boolean) {+ reg = reg shl 1 or (if (one) 1 else 0)+ if (!synced) {+ val d = bitCount(reg xor SYNC)+ if (d <= SYNC_ERRORS || d >= 32 - SYNC_ERRORS) {+ synced = true; inverted = d > SYNC_ERRORS+ bits = 0; at = 0; bad = 0+ }+ return+ }+ if (++bits < 32) return+ bits = 0+ word(if (inverted) reg.inv() else reg)+ }++ private fun word(w: Int) {+ if (at == BATCH) {+ if (bitCount(w xor SYNC) <= SYNC_ERRORS) { batches++; at = 0; bad = 0 }+ else { end(false); synced = false }+ pending.forEach(onPage); pending.clear()+ return+ }+ val index = at+++ val c = Bch3121.correct(w)+ when {+ c == null -> {+ end(true)+ // Noise, or the signal is gone: nothing from this batch can be trusted.+ if (++bad >= MAX_BAD) { pending.clear(); synced = false }+ }+ c == IDLE -> end(false)+ c >= 0 -> {+ end(false)+ capcode = (((c ushr 13) and 0x3FFFF).toLong() shl 3) or (index / 2).toLong()+ function = (c ushr 11) and 3+ }+ capcode >= 0 && words.size < MAX_WORDS -> words += (c ushr 11) and 0xFFFFF+ }+ }++ /** The page being read is complete, or cut off ([partial]). */+ private fun end(partial: Boolean) {+ if (capcode >= 0) {+ val (kind, text) = decode(function, words)+ pending += PagerLog.Page("POCSAG $baud", capcode, kind, text, partial)+ }+ capcode = -1; words.clear()+ }++ companion object {+ internal const val SYNC = 0x7CD215D8+ internal const val IDLE = 0x7A89C197+ internal const val BATCH = 16+ private const val SYNC_ERRORS = 2+ private const val MAX_BAD = 6+ private const val MAX_WORDS = 256+ private const val NUMERIC = "0123456789*U -)("+ private const val DIGITS = "0123456789 -"++ /** Function 3 is text by convention. The rest is up to the network: numbers unless they read as noise. */+ internal fun decode(function: Int, words: List<Int>): Pair<PagerLog.Kind, String> {+ if (words.isEmpty()) return PagerLog.Kind.TONE to ""+ val digits = numeric(words)+ val isNumeric = function != 3 && digits.count { it !in DIGITS } * 4 <= digits.length+ return if (isNumeric) PagerLog.Kind.NUMERIC to digits else PagerLog.Kind.ALPHA to alpha(words)+ }++ /** Five digits a word, each sent lowest bit first. */+ private fun numeric(words: List<Int>) = buildString {+ for (w in words) for (shift in 16 downTo 0 step 4)+ append(NUMERIC[Integer.reverse((w ushr shift) and 0xF) ushr 28])+ }.trim()++ /** 7-bit characters running across the 20-bit words, each sent lowest bit first. */+ private fun alpha(words: List<Int>): String {+ val codes = ArrayList<Int>()+ var c = 0; var n = 0+ for (w in words) for (b in 19 downTo 0) {+ c = c or (((w ushr b) and 1) shl n)+ if (++n == 7) { codes += c; c = 0; n = 0 }+ }+ return pageText(codes)+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.ktindex 8ede521..03a7d50 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt@@ -4,8 +4,7 @@ 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 / V4L, 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).+ * and reads raw I/Q samples for the scans in [SdrRadio].** 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 supportdiff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.ktindex a46940f..58edea8 100644--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt@@ -18,7 +18,8 @@ import com.rfsentinel.app.usb.UsbWifi** Or an ADS-B receiver on 1090 MHz ([ModeS], [AdsbTracker]): aircraft heard directly, no internet* needed, handed to [onAircraft] every few seconds. Or it finds and follows a P25 trunked-radio- * control channel ([P25Hunt]). Any mix of the three ([modes]): it takes turns, each of its own [turnMs].+ * control channel ([P25Hunt]). Or it decodes pager messages ([PagerHunt], [PagerLog]). Any mix of them ([modes]): it takes+ * turns, each of its own [turnMs].** The radio waterfall screen ([SdrWaterfall]) gets a row per sweep, or, zoomed in with [tuneHz],* holds one frequency for a fast live view (the sweep and ADS-B pause meanwhile).@@ -39,6 +40,7 @@ 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 PAGER_RETRY_MS = 5_000L // no paging channel decoded: look again after this (they can be silent between pages)private const val INPUT_DELAY_MS = 400L // after a grant: the radio is on the air by thenprivate const val INPUT_GAP_MS = 5_000L // at most one input check this often: each costs ~0.2 s of control channelprivate const val INPUT_READS = 16 // ~70 ms of the input@@ -67,7 +69,7 @@ object SdrRadio {private val UNPLUGGED get() = "$deviceLabel unplugged"/** For the reading thread: stop now (scan stopped, unplugged, or a newer thread took over). */private val halted get() = stop || Thread.currentThread() !== worker- enum class Mode(val label: String) { SWEEP("radio sweep"), ADSB("ADS-B"), P25("P25") }+ enum class Mode(val label: String) { SWEEP("radio sweep"), ADSB("ADS-B"), P25("P25"), PAGER("pagers") }/** What the SDR does (Settings > RTL-SDR radio); with more than one it takes turns ([turnMs]). */@Volatile var modes: Set<Mode> = setOf(Mode.SWEEP)/** How long each scan's turn lasts (Settings › RTL-SDR radio); 60 s when not set. */@@ -96,6 +98,10 @@ object SdrRadio {@Volatile var p25Messages = 0L; private set/** Talkgroups and calls heard on the current control channel (the P25 screen). */val p25Log = P25Log()+ /** Pages heard, in memory only (the Pager messages screen). */+ val pagerLog = PagerLog()+ /** The paging channel to go back to on its next turn. */+ private var pagerHz: Long? = null/** 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). */@@ -306,7 +312,7 @@ object SdrRadio {else "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"return false}- sweepWatch = null; p25Hunt = null; p25Lock = null+ sweepWatch = null; p25Hunt = null; p25Lock = null; pagerHz = nullvar tuned = falsewhile (!halted && !sdr.lost && !gone(name)) {if (tuneHz != null) { runTuned(sdr, name); tuned = true; continue }@@ -325,6 +331,7 @@ object SdrRadio {Mode.SWEEP -> runSweep(sdr, name)Mode.ADSB -> runAdsb(sdr, name)Mode.P25 -> runP25(sdr, name)+ Mode.PAGER -> runPager(sdr, name)}}if (sdr.lost) UsbWifi.log("$deviceLabel: the dongle stopped answering (unplugged?)")@@ -653,6 +660,39 @@ object SdrRadio {return RadioWatch.channelSnrDb(RadioWatch.powerSpectrum(iq, got / 2), sdr.sampleRate, INPUT_OFFSET_HZ)}+ /** Finds a paging channel and decodes it; looks again when it goes quiet or none decoded. */+ private fun runPager(sdr: SdrDevice, name: String) {+ sdr.setGain(GAIN_TENTHS_DB)+ sdr.resetBuffer()+ val hunt = PagerHunt(sdr) { UsbWifi.log("$deviceLabel: $it") }+ var lastCheck = System.currentTimeMillis(); var away = false+ val stop = {+ val now = System.currentTimeMillis()+ if (now - lastCheck >= 2_000L) { lastCheck = now; away = gone(name) }+ halted || sdr.lost || away || !keeps(Mode.PAGER)+ }+ val onPage = { page: PagerLog.Page, hz: Long -> pagerLog.add(page, hz, System.currentTimeMillis()) }+ while (!stop()) {+ val known = pagerHz+ if (known == null) status = "$deviceLabel · pagers · looking for a paging channel…" + turnNote()+ val hz = known ?: hunt.hunt(stop, onPage)+ if (hz == null) {+ if (stop()) break+ status = "$deviceLabel · pagers · nothing decoding here · looking again shortly" + turnNote()+ val until = System.currentTimeMillis() + PAGER_RETRY_MS+ while (!stop() && System.currentTimeMillis() < until) Thread.sleep(200)+ continue+ }+ pagerHz = hz+ status = "$deviceLabel · pagers · listening on %.4f MHz".format(java.util.Locale.US, hz / 1e6) + turnNote()+ val before = pagerLog.total+ val quiet = hunt.listen(hz, stop, onPage)+ if (quiet) pagerHz = null+ // A count only: frequency, capcodes and text stay off the log.+ UsbWifi.log("$deviceLabel: pagers ${if (quiet) "channel went quiet" else "turn over or stopped"} after ${pagerLog.total - before} pages")+ }+ }+/** Holds [tuneHz] for the waterfall screen: a row of the ~2 MHz around it every few tens of ms. */private fun runTuned(sdr: SdrDevice, name: String) {val hz = tuneHz ?: returndiff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex af84a87..f5de28c 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -438,7 +438,8 @@ class ScanForegroundService : Service() {val sdrModes = listOfNotNull(com.rfsentinel.app.sdr.SdrRadio.Mode.SWEEP.takeIf { radioOn && Prefs.sdrSweep(this) },com.rfsentinel.app.sdr.SdrRadio.Mode.ADSB.takeIf { Prefs.sdrAdsb(this) && Prefs.categoryEnabled(this, Category.AIRCRAFT) },- com.rfsentinel.app.sdr.SdrRadio.Mode.P25.takeIf { radioOn && Prefs.sdrP25(this) }+ com.rfsentinel.app.sdr.SdrRadio.Mode.P25.takeIf { radioOn && Prefs.sdrP25(this) },+ com.rfsentinel.app.sdr.SdrRadio.Mode.PAGER.takeIf { radioOn && Prefs.sdrPager(this) }).toSet()com.rfsentinel.app.sdr.SdrRadio.modes = sdrModescom.rfsentinel.app.sdr.SdrRadio.turnMs = com.rfsentinel.app.sdr.SdrRadio.Mode.entries.associateWith { Prefs.sdrTurnS(this, it) * 1000L }diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 030376c..49df330 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -1490,9 +1490,18 @@ class SettingsActivity : AppCompatActivity() {"Needs Two-way radio turned on. On by default when your region is the United States or Canada. Receiving radio " +"signalling is legal in many places but not all, and some forbid it in a vehicle or passing on what you hear: " +"check the law where you are.") { Prefs.setSdrP25(this, it) }+ val pagerBox = scan("Pager messages", Prefs.sdrPager(this),+ "Experimental. Finds paging channels and decodes POCSAG and FLEX pages (Tools › Pager messages). Pages stay in the " ++ "phone's memory: never saved, exported or sent, and gone when the app closes or you untick this. Pages can hold " ++ "private or medical details. Canada, the United States and many other places restrict using or passing on " ++ "messages you intercept, and some forbid listening at all: check the law where you are. " ++ "Needs Two-way radio turned on.") {+ Prefs.setSdrPager(this, it)+ if (!it) com.rfsentinel.app.sdr.SdrRadio.pagerLog.clear()+ }// Each ticked scan's own turn length, shown while it shares the SDR.val turnViews = listOf(sweepBox to com.rfsentinel.app.sdr.SdrRadio.Mode.SWEEP, adsbBox to com.rfsentinel.app.sdr.SdrRadio.Mode.ADSB,- p25Box to com.rfsentinel.app.sdr.SdrRadio.Mode.P25).map { (ticked, m) ->+ p25Box to com.rfsentinel.app.sdr.SdrRadio.Mode.P25, pagerBox to com.rfsentinel.app.sdr.SdrRadio.Mode.PAGER).map { (ticked, m) ->slider(30, 300, Prefs.sdrTurnS(this, m), { "Time for ${m.label}: $it s" }) { Prefs.setSdrTurnS(this, m, it) }info(box.getChildAt(box.childCount - 2), "With more than one scan ticked, the SDR gives ${m.label} this long before the next scan takes " +"its turn. Longer misses less of it; shorter comes back to the other scans sooner.",diff --git a/app/src/main/java/com/rfsentinel/app/ui/PagerActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/PagerActivity.ktnew file mode 100644index 0000000..a5c3310--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/PagerActivity.kt@@ -0,0 +1,68 @@+package com.rfsentinel.app.ui++import android.annotation.SuppressLint+import android.os.Bundle+import android.text.format.DateUtils+import android.view.View+import android.widget.TextView+import androidx.appcompat.app.AppCompatActivity+import androidx.core.widget.doAfterTextChanged+import com.rfsentinel.app.databinding.ActivityLogBinding+import com.rfsentinel.app.sdr.PagerLog+import com.rfsentinel.app.sdr.SdrRadio+import java.util.Locale++/**+ * Pages the SDR decoded this session (Settings › RTL-SDR radio › Pager messages), newest first. No export or history,+ * on purpose: pages can hold private details, so they stay in memory ([PagerLog]).+ */+class PagerActivity : AppCompatActivity() {++ private lateinit var binding: ActivityLogBinding+ private var rows: List<PagerLog.Row> = emptyList()+ private val header by lazy {+ TextView(this).apply {+ textSize = 12f; alpha = 0.8f+ val p = (8 * resources.displayMetrics.density).toInt(); setPadding(0, p, 0, p)+ }+ }++ private val adapter = DetectionRows({ rows }) { r ->+ labelText.text = "Capcode ${r.page.capcode} · ${r.page.protocol}"+ macText.text = r.page.text.ifEmpty { "Tone only: no message" }+ metaText.text = listOfNotNull(+ String.format(Locale.US, "%.4f MHz", r.hz / 1e6),+ "cut off".takeIf { r.page.partial },+ DateUtils.getRelativeTimeSpanString(r.at, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)+ ).joinToString(" · ")+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ binding = logScreen("Pager messages", adapter)+ binding.searchInput.doAfterTextChanged { refresh() }+ binding.root.addView(header, 2)+ refreshWhileStarted(1_000) { refresh() }+ }++ override fun onSupportNavigateUp(): Boolean { finish(); return true }++ @SuppressLint("NotifyDataSetChanged")+ private fun refresh() {+ val q = binding.searchInput.text?.toString()?.trim().orEmpty()+ rows = SdrRadio.pagerLog.rows().filter { r ->+ q.isEmpty() || r.page.text.contains(q, ignoreCase = true) || r.page.capcode.toString().contains(q)+ }+ header.text = SdrRadio.status.ifBlank { "No SDR running" } + "\nKept in memory only, until the app closes: at most ${PagerLog.MAX} pages."+ adapter.notifyDataSetChanged()+ val empty = when {+ rows.isNotEmpty() -> null+ q.isNotEmpty() -> "Nothing matches."+ SdrRadio.Mode.PAGER !in SdrRadio.modes -> "Pager messages is off.\nTick it in Settings › RTL-SDR radio. It runs while scanning, with an RTL-SDR or HackRF plugged in."+ else -> "No pages heard yet.\nThey show up here as a paging channel is decoded."+ }+ binding.recyclerView.visibility = if (empty == null) View.VISIBLE else View.GONE+ binding.emptyText.text = empty.orEmpty()+ binding.emptyText.visibility = if (empty != null) View.VISIBLE else View.GONE+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.ktindex d5505a2..d775ba1 100644--- a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt@@ -116,6 +116,7 @@ class WaterfallActivity : AppCompatActivity() {tuned != null -> "Zoomed in on about 2 MHz. Radio detection is paused until you go back to the sweep. Tap to move."SdrRadio.mode == SdrRadio.Mode.ADSB -> "The SDR is receiving ADS-B. Tune to look at a frequency."SdrRadio.mode == SdrRadio.Mode.P25 -> "The SDR is following a P25 control channel. Tune to look at a frequency."+ SdrRadio.mode == SdrRadio.Mode.PAGER -> "The SDR is decoding pagers. Tune to look at a frequency."else -> "One row per sweep of your watched bands, newest at the top. Tap a signal to zoom in."}binding.sweepButton.visibility = if (tuned != null) View.VISIBLE else View.GONEdiff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex 71fa9d9..8762f91 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -664,6 +664,9 @@ object Prefs {fun sdrP25(context: Context): Boolean = bool(context, "sdr_p25",com.rfsentinel.app.oui.OuiWatchlist.getEnabledPresets(context).any { it == "us" || it == "canada" })fun setSdrP25(context: Context, v: Boolean) { keepSdrSweep(context); setBool(context, "sdr_p25", v) }+ /** The SDR decodes pager messages (off by default); they stay in memory ([com.rfsentinel.app.sdr.PagerLog]). */+ fun sdrPager(context: Context): Boolean = bool(context, "sdr_pager", false)+ fun setSdrPager(context: Context, v: Boolean) { keepSdrSweep(context); setBool(context, "sdr_pager", v) }/** The sweep's default follows the ADS-B and P25 settings: store it before they change, or ticking one would untick it. */private fun keepSdrSweep(context: Context) { if (!sp(context).contains("sdr_sweep")) setSdrSweep(context, sdrSweep(context)) }/** P25 talkgroups to alert on, "1234 Name" a line ([com.rfsentinel.app.sdr.P25Log.watched]). */diff --git a/app/src/test/java/com/rfsentinel/app/sdr/PagerTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/PagerTest.ktnew file mode 100644index 0000000..eacdb81--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/sdr/PagerTest.kt@@ -0,0 +1,325 @@+package com.rfsentinel.app.sdr++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.roundToInt+import kotlin.math.sin++class PagerTest {++ private companion object {+ const val RATE = P25Demod.SAMPLE_RATE+ const val OFFSET = 250_000L+ /** The receiver's crystal: the carrier is this far from where the hunt thinks it is. */+ const val CARRIER_ERROR_HZ = 700.0+ }++ /** A POCSAG or FLEX transmitter as a list of (frequency deviation, symbol rate) runs. */+ private class Fsk {+ val hz = ArrayList<Double>()+ val perSymbol = ArrayList<Double>()+ fun add(deviation: Double, baud: Int) { hz += deviation; perSymbol += RATE.toDouble() / baud }+ val samples get() = perSymbol.sum().toInt()++ /** The signal as the dongle delivers it at [carrierHz] from the tuned centre, in noise. */+ fun iq(carrierHz: Double, amp: Double = 60.0, noise: Double = 3.0): ByteArray {+ val out = ByteArray(2 * samples)+ val rnd = java.util.Random(7)+ var phase = 0.0; var k = 0; var edge = 0.0; var t = 0+ for (s in hz.indices) {+ edge += perSymbol[s]+ val step = 2 * PI * (carrierHz + hz[s]) / RATE+ while (t < edge && k < out.size) {+ phase += step; t+++ out[k++] = (127.5 + amp * cos(phase) + rnd.nextGaussian() * noise).roundToInt().coerceIn(0, 255).toByte()+ out[k++] = (127.5 + amp * sin(phase) + rnd.nextGaussian() * noise).roundToInt().coerceIn(0, 255).toByte()+ }+ }+ return out+ }+ }++ private fun decode(iq: ByteArray): Pair<List<PagerLog.Page>, Int> {+ val pages = ArrayList<PagerLog.Page>()+ val d = PagerDemod(OFFSET) { pages += it }+ val chunk = 16_384+ var at = 0+ while (at < iq.size) {+ val n = minOf(chunk, iq.size - at)+ d.feed(iq.copyOfRange(at, at + n), n / 2)+ at += n+ }+ return pages to d.frames+ }++ // POCSAG, as the standard lays it out.++ private fun pocsagWord(data21: Int): Int {+ val w = data21 shl 11+ val c = w or (Bch3121.syndrome(w) shl 1)+ return c or (Integer.bitCount(c) and 1)+ }++ private fun address(capcode: Int, function: Int) = pocsagWord(((capcode ushr 3) shl 2) or function)+ private fun message(bits20: Int) = pocsagWord((1 shl 20) or bits20)++ /** Message words from a bit list, padded out with [pad]. */+ private fun messageWords(bits: List<Int>, pad: Int = 0) = bits.chunked(20).map { c ->+ message((c + List(20 - c.size) { pad }).fold(0) { a, b -> a shl 1 or b })+ }++ private fun alphaBits(text: String) = (text + "\u0004").flatMap { ch -> List(7) { (ch.code ushr it) and 1 } }++ private fun numericBits(text: String) = text.flatMap { ch ->+ val v = "0123456789*U -)(".indexOf(ch)+ List(4) { (v ushr it) and 1 }+ }.let { b -> b + List((20 - b.size % 20) % 20) { i -> listOf(0, 0, 1, 1)[i % 4] } } // padded with spaces++ /** Preamble and sync, then [pages] (capcode, its words) each in its frame, in as many batches as they need. */+ private fun pocsag(pages: List<Pair<Int, List<Int>>>): List<Int> {+ val words = ArrayList<Int>()+ for ((capcode, msg) in pages) {+ while (words.size % 16 / 2 != capcode and 7 ) words += Pocsag.IDLE+ words += msg+ words += Pocsag.IDLE+ }+ while (words.size % 16 != 0) words += Pocsag.IDLE+ repeat(16) { words += Pocsag.IDLE }+ val out = ArrayList<Int>()+ words.forEachIndexed { i, w -> if (i % 16 == 0) out += Pocsag.SYNC; out += w }+ return out+ }++ private fun pocsagSignal(baud: Int, words: List<Int>, inverted: Boolean = false) = Fsk().apply {+ val high = if (inverted) -4500.0 else 4500.0+ repeat(576) { add(if (it % 2 == 0) high else -high, baud) }+ for (w in words) for (b in 31 downTo 0) add(if ((w ushr b) and 1 == 1) high else -high, baud)+ repeat(40) { add(0.0, baud) }+ }++ @Test fun `the standard's sync and idle words are clean codewords`() {+ assertEquals(0, Bch3121.syndrome(Pocsag.SYNC))+ assertEquals(0, Bch3121.syndrome(Pocsag.IDLE))+ assertEquals(Pocsag.IDLE, Bch3121.correct(Pocsag.IDLE))+ }++ @Test fun `up to two bit errors in the codeword are fixed and three are not passed off as good`() {+ val word = message(0x5A5A5)+ assertEquals(word, Bch3121.correct(word xor 1))+ for (i in 1..31) {+ assertEquals(word, Bch3121.correct(word xor (1 shl i)))+ for (j in i + 1..31) assertEquals("$i $j", word, Bch3121.correct(word xor (1 shl i) xor (1 shl j)))+ }+ // Odd error counts leave the parity wrong: never a word with a different message.+ for (i in 1..29) assertNull(Bch3121.correct(word xor (7 shl i)))+ }++ @Test fun `alpha and numeric pages at all three speeds, either polarity`() {+ val text = "Test message 42"+ for (baud in listOf(512, 1200, 2400)) for (inverted in listOf(false, true)) {+ val words = pocsag(listOf(+ 1234567 to (listOf(address(1234567, 3)) + messageWords(alphaBits(text))),+ 2000002 to (listOf(address(2000002, 0)) + messageWords(numericBits("555 1234"))),+ 300004 to listOf(address(300004, 1))+ ))+ val (pages, frames) = decode(pocsagSignal(baud, words, inverted).iq(OFFSET + CARRIER_ERROR_HZ))+ assertEquals("$baud $inverted", listOf(+ PagerLog.Page("POCSAG $baud", 1234567, PagerLog.Kind.ALPHA, text),+ PagerLog.Page("POCSAG $baud", 2000002, PagerLog.Kind.NUMERIC, "555 1234"),+ PagerLog.Page("POCSAG $baud", 300004, PagerLog.Kind.TONE, "")+ ), pages)+ assertTrue(frames > 0)+ }+ }++ @Test fun `bit errors in the words are corrected and a word past fixing cuts the page off`() {+ val words = pocsag(listOf(1234560 to (listOf(address(1234560, 3)) + messageWords(alphaBits("Hello there, a longer page")))))+ val at = words.indexOfFirst { it == address(1234560, 3) }+ val hit = words.toMutableList()+ hit[at] = hit[at] xor 0x00100400+ hit[at + 1] = hit[at + 1] xor 0x40000002+ assertEquals("Hello there, a longer page", decode(pocsagSignal(1200, hit).iq(OFFSET.toDouble())).first.single().text)+ hit[at + 3] = hit[at + 3] xor 0x00015000+ val page = decode(pocsagSignal(1200, hit).iq(OFFSET.toDouble())).first.single()+ assertTrue(page.partial)+ assertTrue(page.text, page.text.startsWith("Hello"))+ }++ @Test fun `alpha sent on function 0 is still read as text`() {+ val (kind, text) = Pocsag.decode(0, messageWords(alphaBits("Call the office now")).map { (it ushr 11) and 0xFFFFF })+ assertEquals(PagerLog.Kind.ALPHA, kind)+ assertEquals("Call the office now", text)+ }++ @Test fun `noise makes no pages`() {+ val rnd = java.util.Random(3)+ val noise = ByteArray(2 * RATE * 8) { (127.5 + rnd.nextGaussian() * 20).roundToInt().coerceIn(0, 255).toByte() }+ val (pages, frames) = decode(noise)+ assertTrue(pages.toString(), pages.isEmpty())+ assertEquals(0, frames)+ }++ // FLEX, as demod_flex.c reads it.++ private fun flexWord(data21: Int) = Integer.reverse(pocsagWord(Integer.reverse(data21) ushr 11))++ private fun flexFiw(cycle: Int, frame: Int): Int {+ val rest = (cycle shl 4) or (frame shl 8)+ val sum = (rest ushr 4 and 0xF) + (rest ushr 8 and 0xF) + (rest ushr 12 and 0xF) + (rest ushr 16 and 0xF)+ return flexWord(rest or ((0xF - sum) and 0xF))+ }++ private fun flexAlpha(text: String): List<Int> {+ val codes = listOf(0x41) + text.map { it.code } // a signature character first+ val header = 3 shl 11 // a whole page+ return listOf(header) + codes.chunked(3).map { c -> (c + List(3 - c.size) { 3 }).let { it[0] or (it[1] shl 7) or (it[2] shl 14) } }+ }++ /** Digits after two header bits; fill to the end of the word. */+ private fun flexNumeric(digits: String): List<Int> {+ val nibbles = digits.map { "0123456789 U -][".indexOf(it) }+ val bits = listOf(0, 0) + nibbles.flatMap { n -> List(4) { (n ushr it) and 1 } }+ val filled = bits + generateSequence(0) { (it + 1) % 4 }.map { (0xC ushr it) and 1 }.take((21 - bits.size % 21) % 21).toList()+ return filled.chunked(21).map { w -> w.foldIndexed(0) { i, a, b -> a or (b shl i) } }+ }++ /** Unused words: all-same fill would leave the signal with no zero crossings for 100 symbols, and the clock gives up. */+ private fun flexFill(i: Int) = if (i % 2 == 0) 0x1FFFFF else 0++ /** A phase: BIW, addresses, vectors, messages. Each page: capcode, type, words. */+ private fun flexPhase(pages: List<Triple<Long, Int, List<Int>>>): IntArray {+ val data = IntArray(88, ::flexFill)+ val vectors = 1 + pages.size+ data[0] = (vectors shl 10) // addresses at 1+ var at = vectors + pages.size+ pages.forEachIndexed { i, (capcode, type, words) ->+ data[1 + i] = (capcode + 0x8000).toInt()+ val len = if (type == 3) words.size - 1 else words.size+ data[vectors + i] = (type shl 4) or (at shl 7) or (len shl 14)+ words.forEach { data[at++] = it }+ }+ return IntArray(88) { flexWord(data[it]) }+ }++ /** One FLEX frame. Sync bits go out inverted relative to data bits, as the decoder reads them. */+ private fun flex(code: Int, baud: Int, levels: Int, phases: List<IntArray>, inverted: Boolean = false) = Fsk().apply {+ val sign = if (inverted) -1 else 1+ fun level(sym: Int) = sign * listOf(-4800.0, -1600.0, 1600.0, 4800.0)[sym]+ repeat(200) { add(level(if (it % 2 == 0) 0 else 3), 1600) }+ val sync = (code.toLong() shl 48) or (0xA6C6AAAAL shl 16) or (code.inv().toLong() and 0xFFFF)+ for (b in 63 downTo 0) add(level(if ((sync ushr b) and 1L == 1L) 0 else 3), 1600)+ repeat(16) { add(level(if (it % 2 == 0) 3 else 0), 1600) }+ val fiw = flexFiw(3, 42)+ for (b in 0..31) add(level(if ((fiw ushr b) and 1 == 1) 3 else 0), 1600)+ repeat(baud * 25 / 1000) { add(level(if (it % 2 == 0) 0 else 3), baud) }+ fun sym(a: Int, b: Int) = if (levels == 2) (if (a == 1) 3 else 0) else when { a == 1 && b == 1 -> 2; a == 1 -> 3; b == 1 -> 1; else -> 0 }+ fun bit(p: IntArray, c: Int) = (p[((c ushr 5) and 0xFFF8) or (c and 7)] ushr ((c ushr 3) and 31)) and 1+ for (c in 0 until 2816) {+ add(level(sym(bit(phases[0], c), bit(phases[1], c))), baud)+ if (baud == 3200) add(level(sym(bit(phases[2], c), bit(phases[3], c))), baud)+ }+ repeat(64) { add(level(if (it % 2 == 0) 0 else 3), 1600) }+ }++ @Test fun `flex frames at every speed, with alpha, numeric and tone pages`() {+ val idle = IntArray(88) { flexWord(flexFill(it)) }+ for ((code, baud, levels) in listOf(Triple(0x870C, 1600, 2), Triple(0xB068, 1600, 4), Triple(0x7B18, 3200, 2), Triple(0xDEA0, 3200, 4))) {+ val first = flexPhase(listOf(+ Triple(1234567L, 5, flexAlpha("FLEX test page")),+ Triple(1345678L, 3, flexNumeric("5551234")),+ Triple(345678L, 2, listOf(0))+ ))+ val second = if (levels == 4) flexPhase(listOf(Triple(777777L, 5, flexAlpha("Second phase")))) else idle+ val phases = listOf(first, second, idle, idle)+ for (inverted in listOf(false, true)) {+ val (pages, frames) = decode(flex(code, baud, levels, phases, inverted).iq(OFFSET + CARRIER_ERROR_HZ))+ val name = "FLEX $baud/$levels"+ assertEquals("$name $inverted", listOfNotNull(+ PagerLog.Page(name, 1234567, PagerLog.Kind.ALPHA, "FLEX test page"),+ PagerLog.Page(name, 1345678, PagerLog.Kind.NUMERIC, "5551234"),+ PagerLog.Page(name, 345678, PagerLog.Kind.TONE, ""),+ PagerLog.Page(name, 777777, PagerLog.Kind.ALPHA, "Second phase").takeIf { levels == 4 }+ ), pages)+ assertEquals(1, frames)+ }+ }+ }++ @Test fun `flex at 3200 reads the interleaved phase too`() {+ val idle = IntArray(88) { flexWord(flexFill(it)) }+ val a = flexPhase(listOf(Triple(1000L, 5, flexAlpha("Phase A"))))+ val c = flexPhase(listOf(Triple(2000L, 5, flexAlpha("Phase C"))))+ val pages = decode(flex(0x7B18, 3200, 2, listOf(a, idle, c, idle)).iq(OFFSET.toDouble())).first+ assertEquals(listOf("Phase A", "Phase C"), pages.map { it.text })+ }++ // The hunt.++ /** A dongle that hears [signal] on repeat at [carrierHz], plus noise. */+ private class FakeDongle(val carrierHz: Long, val signal: Fsk) : SdrDevice {+ override val label = "fake"+ override val sampleRate = RATE+ override val ctlErrors = 0+ override val lost = false+ override val tunerWriteFails = 0+ override val settleReads = 1+ var reads = 0+ private var tuned = 0L+ private var iq = ByteArray(0)+ private var at = 0+ private val rnd = java.util.Random(9)+ override fun open() = true+ override fun close() {}+ override fun setSampleRate(rate: Int) {}+ override fun tune(hz: Long): Boolean {+ tuned = hz+ val off = carrierHz - hz+ iq = if (abs(off) < 900_000) signal.iq(off.toDouble()) else ByteArray(0)+ at = 0+ return true+ }+ override fun setGain(tenthsDb: Int) {}+ override fun resetBuffer() {}+ override fun read(buf: ByteArray, len: Int): Int {+ reads+++ for (k in 0 until len) {+ buf[k] = if (iq.isEmpty()) (127.5 + rnd.nextGaussian() * 3).roundToInt().coerceIn(0, 255).toByte() else iq[at]+ if (iq.isNotEmpty()) at = (at + 1) % iq.size+ }+ return len+ }+ }++ @Test fun `the hunt finds the paging channel in its band and listen stops when told`() {+ val words = pocsag(listOf(1234567 to (listOf(address(1234567, 3)) + messageWords(alphaBits("Found you")))))+ val dongle = FakeDongle(929_612_500L, pocsagSignal(1200, words))+ val pages = ArrayList<PagerLog.Page>()+ val hunt = PagerHunt(dongle)+ val hz = hunt.hunt({ false }) { p, _ -> pages += p }+ assertNotNull(hz)+ assertTrue("$hz", abs(hz!! - 929_612_500L) < 3_000)+ val until = dongle.reads + 1_000+ assertEquals(false, hunt.listen(hz, { dongle.reads > until }) { p, _ -> pages += p })+ assertTrue(pages.any { it.text == "Found you" })+ }++ @Test fun `nothing on the air means the hunt gives up`() {+ val dongle = FakeDongle(100_000_000L, Fsk())+ assertNull(PagerHunt(dongle).hunt({ false }) { _, _ -> })+ }++ @Test fun `the log keeps the newest pages and clears`() {+ val log = PagerLog()+ repeat(PagerLog.MAX + 5) { log.add(PagerLog.Page("POCSAG 1200", it.toLong(), PagerLog.Kind.TONE, ""), 1L, it.toLong()) }+ assertEquals(PagerLog.MAX, log.rows().size)+ assertEquals((PagerLog.MAX + 4).toLong(), log.rows().first().page.capcode)+ log.clear()+ assertTrue(log.rows().isEmpty())+ }+}