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.

P25 control channel decoder and talkgroups screen; SDR scan checkboxes that take turns; WiFi band choice for USB monitors; fixed-router detection; mute for Waze reports; menu shortcuts to watchlist and whitelist

CIS-C0b67355573a91
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 1cbcf67..9d01d85 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -49,6 +49,13 @@
<!-- Optional floating threat bubble over other apps (the user grants it in Settings). -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+ <!-- Android 11+ hides other apps: without this, speech engines other than the built-in one can't be found (GrapheneOS, a Play Store Google TTS). -->
+ <queries>
+ <intent>
+ <action android:name="android.intent.action.TTS_SERVICE" />
+ </intent>
+ </queries>
+
<application
android:name=".RFSentinelApp"
android:allowBackup="true"
@@ -105,6 +112,7 @@
<activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" />
<activity android:name=".ui.AntennaCheckActivity" android:exported="false" />
<activity android:name=".ui.AircraftActivity" android:exported="false" />
+ <activity android:name=".ui.P25Activity" android:exported="false" />
<activity android:name=".ui.WaterfallActivity" android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize" />
<activity
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 11cbb56..e7446bd 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -210,9 +210,11 @@ class MainActivity : AppCompatActivity() {
menu.add(0, 5, 4, "Antenna check")
menu.add(0, 6, 5, "Aircraft")
menu.add(0, 7, 6, "Radio waterfall")
+ menu.add(0, 8, 7, "P25 talkgroups")
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))
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)
@@ -496,7 +498,11 @@ class MainActivity : AppCompatActivity() {
},
com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let {
com.rfsentinel.app.ui.StatusPanel.Hardware(it,
- if (it.contains("ADS-B")) ({ com.rfsentinel.app.sdr.SdrRadio.adsbMessages }) else null, " msg/s")
+ 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 })
+ else -> null
+ }, " msg/s")
},
com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }
?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) },
@@ -504,7 +510,7 @@ class MainActivity : AppCompatActivity() {
com.rfsentinel.app.link.MeshNode.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) }
)
statusPanel.update(running, warning, hardware, if (locationOff) ::openLocationSettings else null,
- if (running && !locationOff) com.rfsentinel.app.ui.GpsDot.text(this, demoMode) else null)
+ gpsInTitleBar(if (running && !locationOff) com.rfsentinel.app.ui.GpsDot.text(this, demoMode) else null))
return
}
val locationOff = running && !locationOn() && !demoMode
@@ -533,8 +539,19 @@ class MainActivity : AppCompatActivity() {
com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +
com.rfsentinel.app.link.MeshNode.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty()
}
- binding.statusText.text = if (running && !locationOff)
- android.text.SpannableStringBuilder(com.rfsentinel.app.ui.GpsDot.text(this, demoMode)).append(" · ").append(line) else line
+ val gps = gpsInTitleBar(if (running && !locationOff) com.rfsentinel.app.ui.GpsDot.text(this, demoMode) else null)
+ binding.statusText.text = if (gps != null) android.text.SpannableStringBuilder(gps).append(" · ").append(line) else line
+ }
+
+ /**
+ * The GPS dot goes in the title bar under the app's name, so it takes no row of its own. A styled header hides
+ * that title: then it's returned, for the status.
+ */
+ private fun gpsInTitleBar(line: CharSequence?): CharSequence? {
+ val bar = supportActionBar
+ val titled = bar != null && bar.displayOptions and androidx.appcompat.app.ActionBar.DISPLAY_SHOW_TITLE != 0
+ bar?.subtitle = if (titled) line else null
+ return if (titled) null else line
}
/**
@@ -727,13 +744,17 @@ class MainActivity : AppCompatActivity() {
if (panes.radarShown) {
val radio = radioBlips(now, threshold)
radioBlips = radio.size
+ val fix = if (demoMode) com.rfsentinel.app.ui.DemoData.fakeLocation else ScanForegroundService.lastFix
+ // Heading-up while moving (the GPS course is steady from walking speed up), north-up otherwise.
+ binding.radarView.heading = fix?.takeIf { it.hasBearing() && it.speed >= 1.5f }?.bearing
binding.radarView.setBlips(visible.take(200).map { s ->
val alert = com.rfsentinel.app.ui.LiveWindow.alerting(s, now)
RadarView.Blip(
s.mac, s.rssi,
if (alert) colorFor(s) else binding.radarView.ordinaryColor(),
alert,
- if (alert) s.best?.label else null
+ if (alert) s.best?.label else null,
+ if (alert && fix != null) blipBearing(s, fix.latitude, fix.longitude) else null
)
} + radio)
}
@@ -747,8 +768,12 @@ class MainActivity : AppCompatActivity() {
val (urgent, quiet) = waze.partition { it.flashing }
val (radioLive, radioOld) = radio.partition { it.flashing }
val (airUrgent, airQuiet) = air.partition { it.flashing }
+ // Alerting devices from your own watchlist entries go above all of them.
+ fun mine(s: DeviceRegistry.Snapshot) = com.rfsentinel.app.ui.LiveWindow.alerting(s, now) &&
+ s.hits.any { it.source == com.rfsentinel.app.oui.OuiEntry.YOURS }
if (com.rfsentinel.app.ui.DeviceOrder.group(this) == com.rfsentinel.app.ui.DeviceOrder.Group.NONE) {
- submitRows(airUrgent + radioLive + urgent + sections.flatMap { it.items }.map { toRow(it, now, threshold) } +
+ val (yours, devices) = sections.flatMap { it.items }.partition(::mine)
+ submitRows(yours.map { toRow(it, now, threshold) } + airUrgent + radioLive + urgent + devices.map { toRow(it, now, threshold) } +
airQuiet + radioOld + cells + quiet)
} else {
// Grouped: everything the list shows has a group, not only Bluetooth and WiFi devices. What's
@@ -756,9 +781,10 @@ class MainActivity : AppCompatActivity() {
fun block(key: String, label: String, rows: List<DeviceRow>) =
if (rows.isEmpty()) emptyList() else listOf(DeviceRow.header(key, "$label · ${rows.size}")) + rows
val alerts = com.rfsentinel.app.ui.DeviceOrder.ALERTS
+ val (yours, flagged) = sections.filter { it.header == alerts }.flatMap { it.items }.partition(::mine)
submitRows(
- block(alerts, alerts, airUrgent + radioLive + urgent +
- sections.filter { it.header == alerts }.flatMap { it.items }.map { toRow(it, now, threshold) }) +
+ block(alerts, alerts, yours.map { toRow(it, now, threshold) } + airUrgent + radioLive + urgent +
+ flagged.map { toRow(it, now, threshold) }) +
sections.filter { it.header != alerts }.flatMap { sec -> block(sec.header.orEmpty(), sec.header.orEmpty(), sec.items.map { toRow(it, now, threshold) }) } +
block("x:aircraft", "Aircraft", airQuiet) + block("x:radio", "Radio transmissions", radioOld) +
block("x:waze", "Waze reports", quiet) + block("x:cells", "Cell towers", cells)
@@ -828,8 +854,9 @@ class MainActivity : AppCompatActivity() {
.filter { query.isBlank() || it.hit.label.contains(query.trim(), ignoreCase = true) }
.map { w ->
val off = aheadOnly && !w.onMyWay // behind you, another street, off your route
+ val muted = com.rfsentinel.app.data.AlertMutes.isMuted(this, WAZE_ROW + w.report.id, now)
val urgent = w.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&
- w.hit.confidence >= threshold && !off
+ w.hit.confidence >= threshold && !off && !muted
val ago = w.report.publishedMs?.let { "${((now - it) / 60_000).coerceAtLeast(0)} min ago" } ?: "just now"
DeviceRow(
mac = WAZE_ROW + w.report.id,
@@ -842,7 +869,9 @@ class MainActivity : AppCompatActivity() {
highlight = if (urgent) w.report.type.color else null,
flashing = urgent,
bold = urgent,
- confidence = w.hit.confidence
+ confidence = w.hit.confidence,
+ canMute = true,
+ muted = muted
)
}
}
@@ -887,6 +916,17 @@ class MainActivity : AppCompatActivity() {
* RTL-SDR / HackRF transmissions of the last minute on the radar, under the All and Radio filters: closer to the
* centre the stronger the signal. One on the air right now at or above the alert threshold pulses, with its frequency.
*/
+ /**
+ * Compass bearing from you to an alerting device whose position is known: its own broadcast, or a
+ * located estimate you are outside of (inside its circle every direction fits). Null otherwise.
+ */
+ private fun blipBearing(s: DeviceRegistry.Snapshot, lat: Double, lon: Double): Float? {
+ val at = s.broadcast?.let { it.lat to it.lon }
+ ?: s.located?.takeIf { DeviceRegistry.metersBetween(lat, lon, it.lat, it.lon) > it.radiusM }?.let { it.lat to it.lon }
+ ?: return null
+ return com.rfsentinel.app.alpr.KnownCameras.bearingTo(lat, lon, at.first, at.second).toFloat()
+ }
+
private fun radioBlips(now: Long, threshold: Int): List<RadarView.Blip> {
if ((filter != com.rfsentinel.app.ui.DeviceFilter.ALL && filter != com.rfsentinel.app.ui.DeviceFilter.RADIO) ||
!ScanForegroundService.isRunning) return emptyList()
@@ -1309,6 +1349,8 @@ class MainActivity : AppCompatActivity() {
R.id.action_device_history -> { startActivity(Intent(this, com.rfsentinel.app.ui.DeviceHistoryActivity::class.java)); true }
R.id.action_match_log -> { startActivity(Intent(this, DetectionLogActivity::class.java)); true }
R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)); true }
+ R.id.action_watchlist -> { startActivity(Intent(this, com.rfsentinel.app.ouilist.OuiListActivity::class.java)); true }
+ R.id.action_whitelist -> { startActivity(Intent(this, com.rfsentinel.app.whitelist.WhitelistActivity::class.java)); true }
R.id.action_probes -> { startActivity(Intent(this, com.rfsentinel.app.probes.ProbeListActivity::class.java)); true }
R.id.action_export -> { Exporter.showExportMenu(this); true }
R.id.action_traces -> { startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java)); true }
diff --git a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
index 6ec1016..c535c68 100644
--- a/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
+++ b/app/src/main/java/com/rfsentinel/app/data/KnownDeviceEntity.kt
@@ -56,6 +56,11 @@ interface KnownDeviceDao {
@Query("UPDATE known_devices SET favorite = :favorite WHERE mac = :mac")
suspend fun setFavorite(mac: String, favorite: Boolean)
+ /** Router makers' devices heard in [minSessions] sessions or more, the first before [before] ([com.rfsentinel.app.detect.FixedRouter]). */
+ @Query("""SELECT mac FROM known_devices WHERE sessions >= :minSessions AND firstSeen < :before AND
+ (vendor LIKE '%cradlepoint%' OR vendor LIKE '%sierra wireless%' OR vendor LIKE '%peplink%' OR vendor LIKE '%inseego%')""")
+ suspend fun familiarRouters(minSessions: Int, before: Long): List<String>
+
@Query("SELECT mac FROM known_devices WHERE favorite = 1")
suspend fun favorites(): List<String>
diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
index 98c0135..404053b 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
@@ -671,6 +671,8 @@ object DeviceIntel {
.trim().trimEnd(',', '.').ifEmpty { v }
fun security(caps: String): String = when {
+ // Android's own scan always has at least "[ESS]": blank is a USB monitor-mode sighting, which reads no security.
+ caps.isBlank() -> "Unknown (not read in monitor mode)"
caps.contains("SAE") -> "WPA3"
caps.contains("WPA2") || caps.contains("RSN") -> "WPA2"
caps.contains("WPA") -> "WPA"
diff --git a/app/src/main/java/com/rfsentinel/app/detect/FixedRouter.kt b/app/src/main/java/com/rfsentinel/app/detect/FixedRouter.kt
new file mode 100644
index 0000000..6cf5821
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/detect/FixedRouter.kt
@@ -0,0 +1,31 @@
+package com.rfsentinel.app.detect
+
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * Vehicle / cellular routers (Cradlepoint, Sierra Wireless...) ride in police cars, but the same routers sit in
+ * shops, kiosks and traffic-signal cabinets. A router address you keep hearing, scan after scan and day after day,
+ * is bolted down somewhere on your way: it's listed, not alerted - unless something else backs it (an Axon
+ * network, a patrol cluster, your watchlist).
+ */
+object FixedRouter {
+
+ private val ROUTER = Regex("cradlepoint|sierra wireless|peplink|inseego|cellular router", RegexOption.IGNORE_CASE)
+ /** Heard in this many scanning sessions, the first on an earlier day: a fixed router. */
+ const val MIN_SESSIONS = 3
+
+ /** Router addresses heard often enough, loaded as a scan starts. */
+ private val familiar = ConcurrentHashMap.newKeySet<String>()
+
+ /** Every match is only "it's a vehicle router": nothing else backs it. */
+ fun routerOnly(hits: List<Hit>) = hits.isNotEmpty() && hits.all { ROUTER.containsMatchIn(it.label) }
+
+ /** True for a router-only device ([hits]) that is one of the [familiar] ones. Never on the Weak threshold (0): it alerts on every match. */
+ fun quiet(mac: String, hits: List<Hit>, threshold: Int) = threshold > 0 && mac.uppercase() in familiar && routerOnly(hits)
+
+ /** [macs]: the router makers' addresses heard in [MIN_SESSIONS] sessions or more, the first before today. */
+ fun load(macs: Collection<String>) {
+ familiar.clear()
+ macs.mapTo(familiar) { it.uppercase() }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
index aebee0a..108e653 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/SignatureEngine.kt
@@ -442,9 +442,19 @@ object SignatureEngine {
CRADLEPOINT_VEHICLE_SSID.matches(ssid) -> Hit(Category.PUBLIC_SAFETY, "Cradlepoint vehicle router (default network name)", 40,
"WiFi network \"$ssid\" is a Cradlepoint in-vehicle router's default name (model + last 3 address digits). " +
"Police cars, but also ambulances, buses, utility fleets and traffic-signal cabinets", "Cradlepoint default SSID (product label); $IEEE")
+ // Weak alone; on a vehicle router it backs the router match, so a familiar one still alerts (FixedRouter).
+ ssid.lowercase().split(NON_ALNUM).any { w -> w in EMERGENCY_WORDS || w.split(LETTER_DIGIT).any { it in EMERGENCY_WORDS } } -> Hit(Category.PUBLIC_SAFETY,
+ "Police / fire / EMS network name", 45, "WiFi network \"$ssid\" names an emergency service. Stronger on a " +
+ "Cradlepoint or Sierra Wireless router", "Network-name keywords, after Wardrive Go's emergency-router filter")
else -> null
}
+ /** Words an agency puts in its vehicles' network names, matched as whole words ("SHERIFF-12", "Medic 7"). */
+ private val EMERGENCY_WORDS = setOf("police", "pd", "sheriff", "trooper", "patrol", "k9", "mdt", "fire", "fd",
+ "ems", "medic", "ambulance", "rescue", "dispatch")
+ private val NON_ALNUM = Regex("[^a-z0-9]+")
+ private val LETTER_DIGIT = Regex("(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])")
+
/** The network an Axon body camera or device opens while pairing ("AB3-...", "AXON-..."). */
internal fun axonPairingSsid(ssid: String): Hit? {
if (AXON_FLEET_SSID.matches(ssid)) return null // an in-car network: policeVehicleSsid
diff --git a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
index 9660451..137b3d2 100644
--- a/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/WazeWatch.kt
@@ -298,6 +298,8 @@ class WazeWatch(
val first = id !in seen
if (first) seen[id] = now
+ // Dismissed from the list (its mute button): no alert, no call-outs.
+ if (com.rfsentinel.app.data.AlertMutes.isMuted(context, "waze:$id", now)) continue
val eligible = s.hit.confidence >= threshold
if (first || (eligible && id !in alerted)) {
if (eligible) alerted += id
@@ -323,7 +325,8 @@ class WazeWatch(
heldSince.keys.retainAll(known.keys)
// The threat headline: the strongest report that counts and is allowed to be loud enough to matter.
- val headline = shown.filter { counts(it) && it.level != WazePolice.Level.LOG }.maxByOrNull { it.hit.confidence }
+ val headline = shown.filter { counts(it) && it.level != WazePolice.Level.LOG &&
+ !com.rfsentinel.app.data.AlertMutes.isMuted(context, "waze:${it.report.id}", now) }.maxByOrNull { it.hit.confidence }
AmbientThreats.waze = headline?.let { now to AmbientThreats.Threat(it.hit.confidence, it.hit.label, Category.POLICE_REPORT) }
AmbientThreats.wazeTtlMs = 20_000L // refreshed every second while the checks run
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt
new file mode 100644
index 0000000..6b9bb14
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Demod.kt
@@ -0,0 +1,186 @@
+package com.rfsentinel.app.sdr
+
+import kotlin.math.PI
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+/**
+ * P25 Phase 1 control channel, first stage: the RTL-SDR's raw I/Q to C4FM dibits.
+ *
+ * Picks the 12.5 kHz channel [offsetHz] from the tuned centre (mix, integrate-and-dump to 48 kS/s,
+ * low-pass), FM-demodulates it and finds each frame sync (0x5575F5FF77FF, 24 symbols of ±3). The sync
+ * gives the symbol timing, the level of ±3 and the DC offset, and the [FRAME_DIBITS] dibits after it are
+ * sliced and handed to [onFrame] (status symbols still in: the frame decoder takes them out).
+ * A slow frequency loop keeps the channel centred while the dongle's crystal drifts.
+ *
+ * Signalling only: it never demodulates voice. Pure (no Android): unit-tested on a synthetic signal.
+ */
+class P25Demod(offsetHz: Double, private val onFrame: (IntArray) -> Unit) {
+
+ /** Where the channel is, from the tuned centre; the frequency loop moves it while it tracks. */
+ var offsetHz = offsetHz; private set
+ /** Frame syncs found so far. */
+ var syncs = 0; private set
+
+ // Mixer: a phasor turned each input sample.
+ private var pr = 1.0; private var pi = 0.0
+ private var stepR = 1.0; private var stepI = 0.0
+ private fun setStep() { val w = -2 * PI * offsetHz / SAMPLE_RATE; stepR = cos(w); stepI = sin(w) }
+ init { setStep() }
+
+ // Integrate-and-dump to 48 kS/s.
+ private var accR = 0.0; private var accI = 0.0; private var accN = 0
+
+ // Channel low-pass at 48 kS/s.
+ private val firR = DoubleArray(TAPS.size); private val firI = DoubleArray(TAPS.size); private var firAt = 0
+
+ // Discriminator.
+ private var lastR = 0.0; private var lastI = 0.0
+ private var afcSum = 0.0; private var afcN = 0
+
+ // Symbol filter (a symbol-long moving average) and the history the sync search looks back over.
+ private val box = DoubleArray(SPS); private var boxAt = 0; private var boxSum = 0.0
+ private val hist = DoubleArray(HIST); private var n = 0L
+
+ private class Collect(val start: Long, val dc: Double, val level: Double) {
+ val dibits = IntArray(FRAME_DIBITS); var got = 0
+ }
+ private val collecting = ArrayList<Collect>()
+ private var lastSync = Long.MIN_VALUE / 2
+ private var best = 0.0; private var bestAt = -1L
+
+ /** Unsigned 8-bit I/Q as the dongle delivers it: [count] complex samples from [buf]. */
+ fun feed(buf: ByteArray, count: Int) {
+ var k = 0
+ for (s in 0 until count) {
+ val i = (buf[k++].toInt() and 0xff) - 127.5
+ val q = (buf[k++].toInt() and 0xff) - 127.5
+ accR += i * pr - q * pi
+ accI += i * pi + q * pr
+ val nr = pr * stepR - pi * stepI
+ pi = pr * stepI + pi * stepR; pr = nr
+ if (++accN == DECIM) {
+ accN = 0
+ channelSample(accR, accI)
+ accR = 0.0; accI = 0.0
+ // Keeps the phasor on the unit circle (rounding drifts it).
+ val m = 1.5 - 0.5 * (pr * pr + pi * pi); pr *= m; pi *= m
+ }
+ }
+ }
+
+ 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
+ // FM discriminator: the phase step between samples, in Hz.
+ val hz = atan2(yi * lastR - yr * lastI, yr * lastR + yi * lastI) * CHANNEL_RATE / (2 * PI)
+ lastR = yr; lastI = yi
+ afc(hz)
+ boxSum += hz - box[boxAt]; box[boxAt] = hz; if (++boxAt == SPS) boxAt = 0
+ symbolSample(boxSum / SPS)
+ }
+
+ /** C4FM averages to zero over random data: what's left is the channel being off centre. */
+ private fun afc(hz: Double) {
+ afcSum += hz.coerceIn(-3000.0, 3000.0)
+ if (++afcN < AFC_SAMPLES) return
+ offsetHz += AFC_GAIN * afcSum / afcN
+ afcSum = 0.0; afcN = 0
+ setStep()
+ }
+
+ private fun at(back: Int) = hist[((n - back) % HIST).toInt().let { if (it < 0) it + HIST else it }]
+
+ private fun symbolSample(v: Double) {
+ hist[(n % HIST).toInt()] = v
+ // Dibits for the frames being collected: one every SPS samples after their sync.
+ if (collecting.isNotEmpty()) {
+ val it = collecting.iterator()
+ while (it.hasNext()) {
+ val c = it.next()
+ if ((n - c.start) % SPS != 0L) continue
+ c.dibits[c.got++] = slice((v - c.dc) / c.level)
+ if (c.got == FRAME_DIBITS) { it.remove(); onFrame(c.dibits) }
+ }
+ }
+ // Sync search: the last 24 symbols against the pattern, normalized.
+ if (n >= SYNC.size * SPS) {
+ var dot = 0.0; var energy = 0.0
+ for (s in SYNC.indices) {
+ val x = at((SYNC.size - 1 - s) * SPS)
+ dot += x * SYNC[s]; energy += x * x
+ }
+ val corr = if (energy > 0) dot / sqrt(energy * SYNC_ENERGY) else 0.0
+ if (corr > SYNC_CORR && corr > best) { best = corr; bestAt = n }
+ // The peak is past: that sample is the sync's last symbol.
+ if (bestAt >= 0 && n - bestAt >= SPS / 2) {
+ if (bestAt - lastSync > SYNC.size * SPS) found(bestAt)
+ best = 0.0; bestAt = -1
+ }
+ }
+ n++
+ }
+
+ private fun found(end: Long) {
+ lastSync = end
+ var plus = 0.0; var minus = 0.0; var np = 0; var nm = 0
+ for (s in SYNC.indices) {
+ val x = at((n - end).toInt() + (SYNC.size - 1 - s) * SPS)
+ if (SYNC[s] > 0) { plus += x; np++ } else { minus += x; nm++ }
+ }
+ val hi = plus / np; val lo = minus / nm
+ val level = (hi - lo) / 2
+ if (level <= 0) return
+ syncs++
+ val c = Collect(end, (hi + lo) / 2, level)
+ // Samples already past since the sync's end: catch up those dibits from the history.
+ var t = end + SPS
+ while (t <= n && c.got < FRAME_DIBITS) { c.dibits[c.got++] = slice((at((n - t).toInt()) - c.dc) / c.level); t += SPS }
+ collecting += c
+ }
+
+ companion object {
+ /** RTL-SDR sample rate for P25: 40 × 48 kS/s, so 10 samples a symbol after decimation. */
+ const val SAMPLE_RATE = 1_920_000
+ const val DECIM = 40
+ const val CHANNEL_RATE = SAMPLE_RATE / DECIM
+ const val SYMBOL_RATE = 4_800
+ const val SPS = CHANNEL_RATE / SYMBOL_RATE
+ /** Dibits kept after a sync: NID and up to three trellis blocks, status symbols included. */
+ const val FRAME_DIBITS = 340
+ private const val HIST = 1024
+ private const val SYNC_CORR = 0.85
+ private const val AFC_SAMPLES = 4_800 // 0.1 s
+ private const val AFC_GAIN = 0.3
+
+ /** Frame sync 0x5575F5FF77FF as symbols: dibit 01 is +3, 11 is -3. */
+ val SYNC: IntArray = run {
+ val bits = 0x5575F5FF77FFL
+ IntArray(24) { k -> if (((bits shr (46 - 2 * k)) and 3L) == 1L) 3 else -3 }
+ }
+ private val SYNC_ENERGY = SYNC.sumOf { it * it }.toDouble()
+
+ /** Symbol (scaled so ±3 is ±1) to dibit: +3 → 01, +1 → 00, -1 → 10, -3 → 11. */
+ fun slice(x: Double): Int = when {
+ x >= 2.0 / 3 -> 1
+ x >= 0 -> 0
+ x >= -2.0 / 3 -> 2
+ else -> 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
+ val t = DoubleArray(len) { k ->
+ val x = k - (len - 1) / 2.0
+ val 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 }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Frame.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Frame.kt
new file mode 100644
index 0000000..6d83504
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Frame.kt
@@ -0,0 +1,136 @@
+package com.rfsentinel.app.sdr
+
+/**
+ * P25 Phase 1 frames, second stage: the dibits after a frame sync ([P25Demod]) to the network ID and
+ * the control channel's trunking blocks (TSBKs). Status symbols out, the NID's BCH(63,16) code corrected,
+ * then each 98-dibit block de-interleaved, rate-1/2 trellis decoded (Viterbi) and CRC checked.
+ * Constants from TIA-102.BAAA (the trellis table, interleave and CRC as OP25 implements them).
+ * Pure: unit-tested.
+ */
+object P25Frame {
+
+ /** Trunking signalling data unit: the control channel's frames. */
+ const val DUID_TSDU = 0x7
+
+ /** [nac] network access code, [duid] what kind of frame, [errors] bits the BCH code corrected. */
+ data class Nid(val nac: Int, val duid: Int, val errors: Int)
+
+ /** One error-free trunking block: [bytes] its 10 bytes (CRC off), [last] the frame's last block. */
+ class Tsbk(val bytes: ByteArray) {
+ val last get() = bytes[0].toInt() and 0x80 != 0
+ val protected get() = bytes[0].toInt() and 0x40 != 0
+ val opcode get() = bytes[0].toInt() and 0x3f
+ val mfid get() = bytes[1].toInt() and 0xff
+ }
+
+ /** What a frame held: its NID (null when uncorrectable) and the blocks that passed their CRC. */
+ class Decoded(val nid: Nid?, val tsbks: List<Tsbk>, val badBlocks: Int)
+
+ fun decode(frame: IntArray): Decoded {
+ val d = stripStatus(frame)
+ val nid = nid(d) ?: return Decoded(null, emptyList(), 0)
+ if (nid.duid != DUID_TSDU) return Decoded(nid, emptyList(), 0)
+ val out = ArrayList<Tsbk>(); var bad = 0
+ var at = NID_DIBITS
+ while (out.size + bad < 3 && at + BLOCK_DIBITS <= d.size) {
+ val b = trellis(deinterleave(d, at))
+ at += BLOCK_DIBITS
+ if (b == null || !crcOk(b)) { bad++; continue }
+ val t = Tsbk(b.copyOf(10))
+ out += t
+ if (t.last) break
+ }
+ return Decoded(nid, out, bad)
+ }
+
+ /** Takes out the status symbols: every 36th dibit counting from the sync's first ([frame] starts after the sync). */
+ fun stripStatus(frame: IntArray): IntArray =
+ frame.filterIndexed { i, _ -> (i + SYNC_DIBITS + 1) % 36 != 0 }.toIntArray()
+
+ // ---- NID: 16 bits (NAC, DUID), 47 BCH parity bits, 1 parity bit ----
+
+ /** BCH(63,16,23) generator, octal 6331141367235453 (GF(64) from x^6+x+1; it corrects 11 errors). */
+ const val BCH_GENERATOR = 0xCD930BDD3B2BL // = 0o6331141367235453
+
+ /** The 63-bit codeword for [info] (NAC << 4 | DUID): [info] then its remainder mod the generator. */
+ fun nidCodeword(info: Int): Long {
+ var r = info.toLong() shl 47
+ for (bit in 62 downTo 47) if (r shr bit and 1L == 1L) r = r xor (BCH_GENERATOR shl (bit - 47))
+ return (info.toLong() shl 47) or r
+ }
+
+ private val codewords: LongArray by lazy { LongArray(1 shl 16) { nidCodeword(it) } }
+
+ /** The NID from the first 32 dibits; null when more than 11 bits are wrong. */
+ fun nid(d: IntArray): Nid? {
+ if (d.size < NID_DIBITS) return null
+ var v = 0L
+ for (i in 0 until NID_DIBITS) v = v shl 2 or d[i].toLong()
+ val received = v ushr 1 // the 64th bit is a plain parity bit
+ var best = -1; var bestErr = 64
+ val cw = codewords
+ for (info in cw.indices) {
+ val e = java.lang.Long.bitCount(cw[info] xor received)
+ if (e < bestErr) { bestErr = e; best = info; if (e == 0) break }
+ }
+ return if (bestErr <= 11) Nid(best shr 4, best and 0xf, bestErr) else null
+ }
+
+ // ---- Trunking blocks ----
+
+ /** 4-bit symbol [k] of a block comes in at dibit pair [SYMBOL_AT][k] (the 49 symbols go out in four groups). */
+ internal val SYMBOL_AT = IntArray(49) { k -> 2 * (k / 4 + intArrayOf(0, 13, 25, 37)[k % 4]) }
+
+ /** The block's 49 four-bit trellis symbols, in order, from the 98 dibits at [from]. */
+ fun deinterleave(d: IntArray, from: Int): IntArray =
+ IntArray(49) { k -> d[from + SYMBOL_AT[k]] shl 2 or d[from + SYMBOL_AT[k] + 1] }
+
+ /** Rate-1/2 trellis: the symbol sent for input dibit [in] from state (the previous input) [s]: NEXT[s][in]. */
+ val NEXT = arrayOf(intArrayOf(0x2, 0xC, 0x1, 0xF), intArrayOf(0xE, 0x0, 0xD, 0x3),
+ intArrayOf(0x9, 0x7, 0xA, 0x4), intArrayOf(0x5, 0xB, 0x6, 0x8))
+
+ /** Viterbi decode of 49 symbols into 48 dibits (12 bytes; the 49th input is the flush). Null when too damaged. */
+ fun trellis(sym: IntArray): ByteArray? {
+ val inf = Int.MAX_VALUE / 2
+ var metric = intArrayOf(0, inf, inf, inf)
+ val from = Array(sym.size) { IntArray(4) }
+ for (t in sym.indices) {
+ val next = IntArray(4) { inf }
+ for (s in 0 until 4) if (metric[s] < inf) for (input in 0 until 4) {
+ val m = metric[s] + Integer.bitCount(NEXT[s][input] xor sym[t])
+ if (m < next[input]) { next[input] = m; from[t][input] = s }
+ }
+ metric = next
+ }
+ // Ends in state 0: the flush input.
+ var s = 0
+ if (metric[0] > MAX_TRELLIS_ERRORS) return null
+ val dibits = IntArray(sym.size)
+ for (t in sym.indices.reversed()) { dibits[t] = s; s = from[t][s] }
+ val out = ByteArray(12)
+ for (i in 0 until 48) out[i / 4] = (out[i / 4].toInt() or (dibits[i] shl (6 - 2 * (i % 4)))).toByte()
+ return out
+ }
+
+ /**
+ * The block's 96 bits divided by x^16+x^12+x^5+1 leave all ones when it is intact (the sender appends the
+ * inverted CRC-CCITT of the first 10 bytes).
+ */
+ fun crcOk(b: ByteArray): Boolean = remainder(b) == 0xffff
+
+ /** Remainder of [b] (bits MSB first) divided by the CCITT polynomial. */
+ fun remainder(b: ByteArray): Int {
+ var r = 0
+ for (byte in b) for (bit in 7 downTo 0) {
+ r = r shl 1 or (byte.toInt() shr bit and 1)
+ if (r and 0x10000 != 0) r = r and 0xffff xor 0x1021
+ }
+ return r
+ }
+
+ private const val SYNC_DIBITS = 24
+ private const val NID_DIBITS = 32
+ private const val BLOCK_DIBITS = 98
+ /** Bit errors the trellis path may carry before the block is dropped (the CRC catches the rest). */
+ private const val MAX_TRELLIS_ERRORS = 20
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt
new file mode 100644
index 0000000..f1f8d69
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Hunt.kt
@@ -0,0 +1,214 @@
+package com.rfsentinel.app.sdr
+
+import kotlin.math.abs
+import kotlin.math.log10
+import kotlin.math.pow
+import kotlin.math.roundToLong
+
+/**
+ * P25 control channel, fourth stage: finds a site's control channel and stays on it.
+ *
+ * [hunt] sweeps the base-station downlinks (700 MHz 769-775, 800 MHz 851-869) for channels that are on,
+ * strongest first, and listens briefly to each with [P25Demod] + [P25Frame]: the first one whose trunking
+ * blocks pass their CRC is the control channel. The spectrum peak is where this dongle hears it, its
+ * crystal error included, so no frequency correction is needed (the demodulator's loop follows drift).
+ * [listen] then stays on it and hands each message on until the channel goes quiet, when the caller hunts again.
+ *
+ * Times count in samples, not the clock: unit-tested with a simulated dongle.
+ */
+class P25Hunt(private val sdr: SdrDevice, private val log: (String) -> Unit = {}) {
+
+ data class Candidate(val hz: Long, val snrDb: Float)
+ /** A control channel: [hz] where this dongle hears it, [nac] the system's network access code. */
+ data class Lock(val hz: Long, val nac: Int)
+
+ /** Channels listened to in the last hunt, for the log. */
+ var tried = 0; private set
+ /** Good trunking blocks heard while listening, for the log. */
+ var blocks = 0L; private set
+
+ private val buf = ByteArray(XFER)
+
+ /**
+ * What the decoder made of one channel's frames, for the log: how far each stage got tells a weak
+ * signal (few syncs) from a wrong modulation (syncs, no NID) from a decoding fault (NIDs, no good blocks).
+ */
+ private class Stats {
+ var frames = 0; var nids = 0; var tsdu = 0; var good = 0; var bad = 0; var otherNac = 0; var stalls = 0
+ val opcodes = java.util.TreeMap<String, Int>()
+ fun add(d: P25Frame.Decoded) {
+ frames++
+ val nid = d.nid ?: return
+ nids++
+ if (nid.duid == P25Frame.DUID_TSDU) tsdu++
+ good += d.tsbks.size; bad += d.badBlocks
+ for (t in d.tsbks) opcodes.merge(if (t.mfid > 1) "vendor" else "%02X".format(t.opcode), 1, Int::plus)
+ }
+ override fun toString() = "$frames frame syncs, $nids NIDs ($tsdu trunking), $good good blocks, $bad failed" +
+ (if (otherNac > 0) ", $otherNac from another NAC" else "") + (if (stalls > 0) ", $stalls failed reads" else "")
+ }
+
+ private fun band(hz: Long) = if (hz < 800_000_000L) "700 MHz" else "800 MHz"
+
+ /** 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 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 " +
+ "${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
+ for (c in tries) {
+ if (stop()) return null
+ tried++
+ trial(c, "$tried/${tries.size}", stop)?.let { return it }
+ }
+ return null
+ }
+
+ /** A short listen on [c]: a [Lock] when trunking blocks decode there. */
+ private fun trial(c: Candidate, which: String, stop: () -> Boolean): Lock? {
+ val head = "P25 try $which: ${band(c.hz)} band, %.0f dB:".format(c.snrDb)
+ val center = c.hz - OFFSET_HZ
+ if (!sdr.tune(center)) { log("$head the tuner didn't lock"); return null }
+ repeat(sdr.settleReads) { sdr.read(buf) }
+ val st = Stats()
+ val nacs = HashMap<Int, Int>()
+ val demod = P25Demod(OFFSET_HZ.toDouble()) { f ->
+ val d = P25Frame.decode(f)
+ st.add(d)
+ if (d.nid != null && d.tsbks.isNotEmpty()) nacs.merge(d.nid.nac, 1, Int::plus)
+ }
+ var samples = 0L; var fails = 0
+ while (st.good < MIN_BLOCKS && samples < TRIAL_S * P25Demod.SAMPLE_RATE) {
+ if (stop()) return null
+ val n = sdr.read(buf)
+ if (n <= 0) {
+ st.stalls++
+ if (++fails >= STALL_READS) { log("$head $st - the samples stopped"); return null }
+ continue
+ }
+ fails = 0
+ demod.feed(buf, n / 2); samples += n / 2
+ }
+ val drift = "frequency loop moved %+.0f Hz in %.2f s".format(demod.offsetHz - OFFSET_HZ, samples.toDouble() / P25Demod.SAMPLE_RATE)
+ if (st.good < MIN_BLOCKS) { log("$head $st, $drift - not a control channel"); return null }
+ log("$head $st, $drift - control channel (${nacs.size} NAC${if (nacs.size == 1) "" else "s"} seen)")
+ return Lock(center + demod.offsetHz.roundToLong(), nacs.maxBy { it.value }.key)
+ }
+
+ /**
+ * 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].
+ */
+ fun listen(lock: Lock, stop: () -> Boolean, 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()
+ var samples = 0L; var lastGood = 0L; var fails = 0; var lastLog = 0L
+ var st = Stats()
+ val kinds = java.util.TreeMap<String, Int>()
+ val demod = P25Demod(OFFSET_HZ.toDouble()) { f ->
+ val d = P25Frame.decode(f)
+ if (d.nid != null && d.nid.nac != lock.nac) { st.frames++; st.otherNac++; return@P25Demod }
+ st.add(d)
+ if (d.tsbks.isNotEmpty()) lastGood = samples
+ blocks += d.tsbks.size
+ for (t in d.tsbks) P25Tsbk.parse(t)?.let { kinds.merge(it.javaClass.simpleName, 1, Int::plus); onMsg(it) }
+ }
+ fun report(why: String) {
+ log("P25 $why: $st, block types ${st.opcodes.entries.joinToString(" ") { "${it.key}x${it.value}" }.ifEmpty { "none" }}, " +
+ "messages ${kinds.entries.joinToString(" ") { "${it.key}x${it.value}" }.ifEmpty { "none" }}, " +
+ "frequency loop at %+.0f Hz".format(demod.offsetHz - OFFSET_HZ))
+ st = Stats(); kinds.clear()
+ }
+ while (!stop()) {
+ val n = sdr.read(buf)
+ if (n <= 0) { st.stalls++; if (++fails % STALL_READS == 0) sdr.resetBuffer(); continue }
+ fails = 0
+ demod.feed(buf, n / 2); samples += n / 2
+ if (samples - lastGood > LOST_S * P25Demod.SAMPLE_RATE) {
+ report("control channel quiet for ${LOST_S.toInt()} s (no good block)")
+ return true
+ }
+ if (samples - lastLog >= LOG_S * P25Demod.SAMPLE_RATE) { lastLog = samples; report("last ${LOG_S.toInt()} s") }
+ }
+ report("listen stopped")
+ return false
+ }
+
+ companion object {
+ /** Base-station downlinks: 700 MHz narrowband and 800 MHz public safety. */
+ val BANDS = listOf(769_000_000L..775_000_000L, 851_000_000L..869_000_000L)
+ private const val XFER = 16_384
+ /** ~70 ms of samples per scan step: always-on channels stand out, short bursts average down. */
+ private const val SCAN_READS = 16
+ /** The channel this far above the tuned centre, clear of the receiver's DC spike. */
+ private const val OFFSET_HZ = 250_000L
+ /** A control channel sends a frame every ~75 ms: this long without two good blocks, it isn't one. */
+ private const val TRIAL_S = 0.8
+ private const val MIN_BLOCKS = 2
+ private const val MAX_TRIES = 12
+ const val LOST_S = 3.0
+ private const val LOG_S = 60.0
+ private const val STALL_READS = 8
+ private const val MIN_SNR_DB = 10.0
+ private const val CHANNEL_HALF_HZ = 5_000.0
+ private const val MERGE_HZ = 6_250L
+
+ /** 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() }
+
+ /** 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> {
+ val n = psd.size; val mid = n / 2
+ val binHz = sampleRate.toDouble() / n
+ val p = DoubleArray(n) { 10.0.pow(psd[it] / 10.0) }
+ val noise = p.sorted()[mid]
+ val half = (CHANNEL_HALF_HZ / binHz).toInt()
+ val usable = (RadioWatch.USABLE_HZ / binHz).toInt()
+ val guard = (RadioWatch.DC_GUARD_HZ / binHz).toInt() + half
+ val win = DoubleArray(n) { k -> if (k < half || k >= n - half) 0.0 else (k - half..k + half).sumOf { p[it] } / (2 * half + 1) }
+ val out = ArrayList<Candidate>()
+ for (k in mid - usable + 2 * half..mid + usable - 2 * half) {
+ if (abs(k - mid) <= guard) continue
+ val snr = 10 * log10(win[k] / noise)
+ if (snr < MIN_SNR_DB) continue
+ // The highest point within a channel either side (the first of equal ones).
+ if ((k - 2 * half until k).any { win[it] >= win[k] } || (k + 1..k + 2 * half).any { win[it] > win[k] }) continue
+ var w = 0.0; var at = 0.0
+ for (j in k - half..k + half) { val e = (p[j] - noise).coerceAtLeast(0.0); w += e; at += e * (j - mid) }
+ out += Candidate(center + (at / w * binHz).roundToLong(), snr.toFloat())
+ }
+ return out
+ }
+
+ /** Strongest first, each channel once (seen from two tuned centres). */
+ internal fun strongest(all: List<Candidate>): List<Candidate> {
+ val out = ArrayList<Candidate>()
+ for (c in all.sortedByDescending { it.snrDb }) if (out.none { abs(it.hz - c.hz) <= MERGE_HZ }) out += c
+ return out
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt
new file mode 100644
index 0000000..c53094e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Log.kt
@@ -0,0 +1,82 @@
+package com.rfsentinel.app.sdr
+
+/**
+ * P25 control channel, last stage: what the site said, kept for the talkgroup screen. Per talkgroup (or
+ * radio-to-radio call): calls, the last channel and radio, radios affiliated, emergency / encrypted flags.
+ * [add] says when a new call starts, for the watched-talkgroup alerts. Fed from the SDR thread, read by the
+ * screen: synchronized. Pure: unit-tested.
+ */
+class P25Log {
+
+ /** One talkgroup ([tg]) or, with [tg] null, private calls to radio [target]. */
+ data class Row(val tg: Int?, val target: Int?, val calls: Int, val lastAt: Long, val lastChannel: Int?,
+ val lastHz: Long?, val lastSource: Int?, val radios: Int, val emergency: Boolean, val encrypted: Boolean)
+
+ /** The site and how much was heard there, for the screen's header. */
+ data class Summary(val site: P25Tsbk.Site?, val messages: Long, val registrations: Int, val since: Long)
+
+ private class Group { var calls = 0; var lastAt = 0L; var lastChannel: Int? = null; var lastSource: Int? = null
+ val radios = HashSet<Int>(); var emergency = false; var encrypted = false }
+
+ private val groups = HashMap<Pair<Int?, Int?>, Group>()
+ private val channels = P25Tsbk.Channels()
+ private var site: P25Tsbk.Site? = null
+ private var messages = 0L
+ private var registrations = 0
+ private var since = 0L
+
+ /** A new control channel: forget the last site. */
+ @Synchronized fun clear(now: Long) {
+ groups.clear(); site = null; messages = 0; registrations = 0; since = now
+ }
+
+ /** Takes in one message; the talkgroups whose call just started (not heard for [CALL_GAP_MS]). */
+ @Synchronized fun add(m: P25Tsbk.Msg, now: Long): List<Int> {
+ messages++
+ if (since == 0L) since = now
+ return when (m) {
+ is P25Tsbk.Grant -> listOfNotNull(call(m.tg, m.target, m.channel, m.source, now, m.emergency, m.encrypted))
+ is P25Tsbk.GrantUpdate -> m.calls.mapNotNull { (ch, tg) -> call(tg, null, ch, null, now, false, false) }
+ is P25Tsbk.Affiliation -> { group(m.tg, null).radios += m.radio; emptyList() }
+ is P25Tsbk.Registration -> { if (m.accepted) registrations++; emptyList() }
+ is P25Tsbk.Iden -> { channels.learn(m); emptyList() }
+ is P25Tsbk.Site -> { site = site?.let { s -> m.copy(wacn = m.wacn ?: s.wacn, rfss = m.rfss ?: s.rfss, site = m.site ?: s.site) } ?: m; emptyList() }
+ is P25Tsbk.Neighbor -> emptyList()
+ }
+ }
+
+ private fun group(tg: Int?, target: Int?) = groups.getOrPut(tg to target) { Group() }
+
+ private fun call(tg: Int?, target: Int?, channel: Int, source: Int?, now: Long, emergency: Boolean, encrypted: Boolean): Int? {
+ val g = group(tg, target)
+ val new = g.calls == 0 || now - g.lastAt > CALL_GAP_MS
+ if (new) g.calls++
+ g.lastAt = now; g.lastChannel = channel
+ if (source != null) { g.lastSource = source; g.radios += source }
+ g.emergency = g.emergency || emergency
+ g.encrypted = encrypted || (g.encrypted && source == null) // an update doesn't say: keep the last grant's
+ return if (new) tg else null
+ }
+
+ /** Most recent first. */
+ @Synchronized fun rows(): List<Row> = groups.map { (k, g) ->
+ Row(k.first, k.second, g.calls, g.lastAt, g.lastChannel, g.lastChannel?.let(channels::hz), g.lastSource,
+ g.radios.size, g.emergency, g.encrypted)
+ }.filter { it.calls > 0 || it.radios > 0 }.sortedByDescending { it.lastAt }
+
+ @Synchronized fun summary() = Summary(site, messages, registrations, since)
+
+ companion object {
+ /** A grant or update for a talkgroup heard within this long is the same call going on. */
+ const val CALL_GAP_MS = 10_000L
+
+ private val LINE = Regex("""^\s*(\d{1,5})\b\s*[,;:\-]?\s*(.*)$""")
+
+ /** "1234 Sheriff dispatch" lines (Settings): talkgroup to name ("" when unnamed). */
+ fun watched(text: String): Map<Int, String> = text.lines().mapNotNull { line ->
+ val m = LINE.find(line) ?: return@mapNotNull null
+ val tg = m.groupValues[1].toInt().takeIf { it in 1..0xFFFF } ?: return@mapNotNull null
+ tg to m.groupValues[2].trim()
+ }.toMap()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt b/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt
new file mode 100644
index 0000000..2f85443
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/P25Tsbk.kt
@@ -0,0 +1,73 @@
+package com.rfsentinel.app.sdr
+
+/**
+ * P25 control channel, third stage: a trunking block ([P25Frame.Tsbk]) to what it says. Metadata only -
+ * who was granted a channel for which talkgroup, who affiliated or registered, and the system's own
+ * broadcasts (its IDs and the tables that turn channel numbers into frequencies). Standard (MFID 0)
+ * outbound messages per TIA-102.AABC; vendor ones are skipped. Field positions cross-checked with OP25.
+ * Pure: unit-tested.
+ */
+object P25Tsbk {
+
+ sealed class Msg
+ /** A voice channel granted: to talkgroup [tg], or radio to radio ([target]); [source] the radio keying up. */
+ data class Grant(val channel: Int, val tg: Int?, val target: Int?, val source: Int,
+ val emergency: Boolean, val encrypted: Boolean) : Msg()
+ /** Calls still going on: (channel, talkgroup) pairs. */
+ 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()
+ /** 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. */
+ data class Neighbor(val rfss: Int, val site: Int, val channel: Int) : Msg()
+
+ fun parse(t: P25Frame.Tsbk): Msg? {
+ if (t.protected || (t.mfid != 0x00 && t.mfid != 0x01)) return null
+ val a = args(t.bytes)
+ fun f(shift: Int, width: Int) = (a ushr (shift - 16) and ((1L shl width) - 1)).toInt()
+ return when (t.opcode) {
+ 0x00 -> f(72, 8).let { o -> Grant(f(56, 16), f(40, 16), null, f(16, 24), o and 0x80 != 0, o and 0x40 != 0) }
+ 0x02 -> GrantUpdate(listOf(f(64, 16) to f(48, 16), f(32, 16) to f(16, 16)).distinct())
+ 0x03 -> GrantUpdate(listOf(f(48, 16) to f(16, 16)))
+ 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)])
+ 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))
+ else -> null
+ }
+ }
+
+ /** 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
+ for (i in 2 until 10) v = v shl 8 or (b[i].toLong() and 0xff)
+ return v
+ }
+
+ /** Slots per carrier by TDMA channel type (types above 5 are reserved). */
+ private val SLOTS = intArrayOf(1, 1, 1, 2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
+
+ /**
+ * The channel tables a site broadcasts, to turn a 16-bit channel (4-bit table, 12-bit number) into the
+ * downlink frequency. Null until that table has been heard.
+ */
+ class Channels {
+ private val tables = arrayOfNulls<Iden>(16)
+ fun learn(i: Iden) { tables[i.id] = i }
+ fun hz(channel: Int): Long? {
+ val t = tables[channel shr 12 and 0xf] ?: return null
+ return t.baseHz + t.spacingHz.toLong() * ((channel and 0xfff) / t.slots)
+ }
+ }
+
+ /** "1-0123" style: the table and the channel number, for a channel whose frequency isn't known yet. */
+ fun channelName(channel: Int) = "%d-%04d".format(channel shr 12 and 0xf, channel and 0xfff)
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
index f59d165..0ae7062 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -16,8 +16,9 @@ import com.rfsentinel.app.usb.UsbWifi
* transmissions nearby. Only signal strength per channel is measured. Its log goes into
* the USB adapter log (Settings → Export USB WiFi adapter log).
*
- * Or, with [adsb] on, it stays on 1090 MHz as an ADS-B receiver ([ModeS], [AdsbTracker]):
- * aircraft heard directly, no internet needed, handed to [onAircraft] every few seconds.
+ * 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 of [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).
@@ -35,6 +36,7 @@ object SdrRadio {
private const val ADSB_PUSH_MS = 2_000L
private const val TUNED_READS = 4 // ~16 ms of samples per waterfall row
private const val TUNED_ROW_MS = 40L // at most ~25 rows a second
+ private const val P25_RETRY_MS = 30_000L // no control channel found: look again after this
@Volatile var status: String = ""; private set
/** ADS-B messages decoded since the app started, for the main screen's messages-per-second line. */
@@ -55,8 +57,33 @@ 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
- /** Receive ADS-B on 1090 MHz instead of sweeping the radio bands; switches at the next sweep. */
- @Volatile var adsb = false
+ enum class Mode(val label: String) { SWEEP("radio sweep"), ADSB("ADS-B"), P25("P25") }
+ /** What the SDR does (Settings > RTL-SDR radio); with more than one it takes turns of [turnMs]. */
+ @Volatile var modes: Set<Mode> = setOf(Mode.SWEEP)
+ @Volatile var turnMs = 60_000L
+ /** The scan whose turn it is now; null when none is ticked. */
+ @Volatile var mode: Mode? = null; private set
+ @Volatile private var turnEnd = 0L
+ /** [m] keeps the SDR: its turn, still ticked, and the waterfall not zoomed in. */
+ private fun keeps(m: Mode) = mode == m && m in modes && tuneHz == null && (modes.size == 1 || System.currentTimeMillis() < turnEnd)
+ /** The scan after the current one, round the ticked ones. */
+ private fun next(): Mode? = Mode.entries.filter { it in modes }.let { l -> l.firstOrNull { it.ordinal > (mode?.ordinal ?: -1) } ?: l.firstOrNull() }
+ /** " · ADS-B in 40 s" while taking turns, for the status line. */
+ private fun turnNote(): String {
+ if (modes.size < 2) return ""
+ val left = ((turnEnd - System.currentTimeMillis()) / 1000).coerceAtLeast(0)
+ return " · ${next()?.label} in $left s"
+ }
+ /** P25: the control channel to go back to on its next turn, and the system the talkgroup list is for. */
+ private var p25Hunt: P25Hunt? = null
+ private var p25Lock: P25Hunt.Lock? = null
+ private var p25Nac: Int? = null
+ /** Control-channel messages decoded since the app started. */
+ @Volatile var p25Messages = 0L; private set
+ /** Talkgroups and calls heard on the current control channel (the P25 screen). */
+ val p25Log = P25Log()
+ /** A call started on this talkgroup (the service alerts on watched ones). */
+ @Volatile var onP25Call: ((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.
@@ -195,11 +222,22 @@ object SdrRadio {
else "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"
return false
}
- sweepWatch = null
- while (!halted && !sdr.lost && !gone(d.deviceName)) when {
- tuneHz != null -> runTuned(sdr, d.deviceName)
- adsb -> runAdsb(sdr, d.deviceName)
- else -> runSweep(sdr, d.deviceName)
+ sweepWatch = null; p25Hunt = null; p25Lock = null
+ while (!halted && !sdr.lost && !gone(d.deviceName)) {
+ if (tuneHz != null) { runTuned(sdr, d.deviceName); continue }
+ val m = next()
+ if (m == null) {
+ mode = null
+ status = "$deviceLabel · idle: no scan ticked in Settings › RTL-SDR radio"
+ Thread.sleep(500); continue
+ }
+ if (modes.size > 1) UsbWifi.log("$deviceLabel: turn: ${m.label} for ${turnMs / 1000} s")
+ mode = m; turnEnd = System.currentTimeMillis() + turnMs
+ when (m) {
+ Mode.SWEEP -> runSweep(sdr, d.deviceName)
+ Mode.ADSB -> runAdsb(sdr, d.deviceName)
+ Mode.P25 -> runP25(sdr, d.deviceName)
+ }
}
if (sdr.lost) UsbWifi.log("$deviceLabel: the dongle stopped answering (unplugged?)")
val away = sdr.lost || gone(d.deviceName)
@@ -214,12 +252,12 @@ object SdrRadio {
UsbWifi.log("$deviceLabel: the tuner didn't lock on 1090 MHz")
status = "$deviceLabel · ADS-B: the tuner didn't lock on 1090 MHz"
var waited = 0
- while (!halted && adsb && waited < 50) { Thread.sleep(100); waited++ }
+ while (!halted && keeps(Mode.ADSB) && waited < 50) { Thread.sleep(100); waited++ }
return
}
sdr.resetBuffer()
UsbWifi.log("$deviceLabel: ADS-B receiver on 1090 MHz, ${sdr.sampleRate} S/s, gain ${ADSB_GAIN_TENTHS_DB / 10.0} dB")
- status = "$deviceLabel · ADS-B · listening on 1090 MHz…"
+ status = "$deviceLabel · ADS-B · listening on 1090 MHz…" + turnNote()
// One read is ~33 ms of samples; Android before 9 caps a transfer at 16 KB.
val xfer = if (android.os.Build.VERSION.SDK_INT >= 28) 131_072 else XFER
val buf = ByteArray(xfer)
@@ -230,7 +268,7 @@ object SdrRadio {
val frames = ArrayList<ModeS.Frame>()
var lastPush = 0L; var lastLog = System.currentTimeMillis(); var fails = 0; var messages = 0L; var logged = 0L
var lastCheck = System.currentTimeMillis()
- while (!halted && !sdr.lost && adsb && tuneHz == null) {
+ while (!halted && !sdr.lost && keeps(Mode.ADSB)) {
val n = sdr.read(buf)
// Every couple of seconds: still plugged in? (Reads alone can fail quietly for a long time.)
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
@@ -260,7 +298,7 @@ object SdrRadio {
val located = tracker.located(now)
val unlocated = tracker.unlocated(now)
onAircraft?.invoke(located, unlocated)
- if (!halted) status = "$deviceLabel · ADS-B · ${located.size + unlocated.size} aircraft heard, ${located.size} with a position"
+ if (!halted) status = "$deviceLabel · ADS-B · ${located.size + unlocated.size} aircraft heard, ${located.size} with a position" + turnNote()
}
if (now - lastLog >= 60_000) {
UsbWifi.log("$deviceLabel: ADS-B ${messages - logged} messages in ${(now - lastLog) / 1000} s, " +
@@ -268,7 +306,8 @@ object SdrRadio {
lastLog = now; logged = messages
}
}
- onAircraft?.invoke(emptyList(), emptyList())
+ // Only its turn ended: the aircraft stay listed until they go stale, and come back on the next turn.
+ if (Mode.ADSB !in modes) onAircraft?.invoke(emptyList(), emptyList())
UsbWifi.log("$deviceLabel: ADS-B receiver stopped after $messages messages")
}
@@ -292,11 +331,11 @@ object SdrRadio {
var lastCheck = System.currentTimeMillis()
// The waterfall's row for this sweep, while it is on screen.
var row = ArrayList<SdrWaterfall.Segment>()
- while (!halted && !sdr.lost && !adsb && tuneHz == null) {
+ while (!halted && !sdr.lost && keeps(Mode.SWEEP)) {
// Settings changed: the new bands / targets / sensitivity from this sweep on.
if (config != cfg) { cfg = config; plan = RadioWatch.plan(cfg); watch.config = cfg; logPlan() }
for (center in plan) {
- if (halted || sdr.lost || adsb || tuneHz != null) break
+ if (halted || sdr.lost || !keeps(Mode.SWEEP)) break
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
if (!sdr.tune(center)) { unlocked++; continue }
repeat(sdr.settleReads) { sdr.read(buf) }
@@ -330,7 +369,7 @@ object SdrRadio {
onEvent?.invoke(e)
}
}
- if (tuneHz != null || adsb) break // cut short: not a whole sweep
+ if (!keeps(Mode.SWEEP)) break // cut short: not a whole sweep
watch.sweepDone()
val now = System.currentTimeMillis()
if (row.isNotEmpty()) {
@@ -339,8 +378,8 @@ object SdrRadio {
}
sweepMs = now - sweepStart; sweepStart = now
if (gone(name)) break
- if (!halted) status = if (watch.sweeps < 6) "$deviceLabel · learning the radio bands here…"
- else "$deviceLabel · live · sweep ${sweepMs / 100 / 10.0} s · $events transmissions nearby so far"
+ if (!halted) status = (if (watch.sweeps < 6) "$deviceLabel · learning the radio bands here…"
+ else "$deviceLabel · live · sweep ${sweepMs / 100 / 10.0} s · $events transmissions nearby so far") + turnNote()
if (now - lastLog > (if (watch.sweeps < 20) 10_000 else 60_000)) {
lastLog = now
UsbWifi.log("$deviceLabel: sweep ${watch.sweeps} in $sweepMs ms, ${watch.learnedChannels} channels, ${watch.busyChannels} always busy, " +
@@ -350,6 +389,50 @@ object SdrRadio {
UsbWifi.log("$deviceLabel: radio sweep stopped after ${watch.sweeps} sweeps")
}
+ /** Finds a P25 control channel and follows it; looks again when it goes quiet or none was found. */
+ private fun runP25(sdr: SdrDevice, name: String) {
+ sdr.setGain(GAIN_TENTHS_DB)
+ sdr.resetBuffer()
+ val hunt = p25Hunt ?: P25Hunt(sdr) { UsbWifi.log("$deviceLabel: $it") }.also { p25Hunt = 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.P25)
+ }
+ UsbWifi.log("$deviceLabel: P25 control channel receiver, gain ${GAIN_TENTHS_DB / 10.0} dB")
+ while (!stop()) {
+ // Its last turn's control channel first: no new search when it is still there.
+ val known = p25Lock
+ if (known == null) status = "$deviceLabel · P25 · looking for a control channel…" + turnNote()
+ val lock = known ?: hunt.hunt(stop)
+ if (lock == null) {
+ if (stop()) break
+ UsbWifi.log("$deviceLabel: P25 - no control channel decoded (${hunt.tried} channels tried), looking again in ${P25_RETRY_MS / 1000} s")
+ status = "$deviceLabel · P25 · no control channel heard here · looking again shortly" + turnNote()
+ val until = System.currentTimeMillis() + P25_RETRY_MS
+ while (!stop() && System.currentTimeMillis() < until) Thread.sleep(200)
+ continue
+ }
+ // Frequency and network code stay off the log: together they name the local system.
+ UsbWifi.log(if (known != null) "$deviceLabel: P25 back on the control channel" else "$deviceLabel: P25 control channel found after ${hunt.tried} tries")
+ p25Lock = lock
+ if (lock.nac != p25Nac) { p25Log.clear(System.currentTimeMillis()); p25Nac = lock.nac } // another system: a new list
+ 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) {
+ messages++; p25Messages++
+ val now = System.currentTimeMillis()
+ for (tg in p25Log.add(it, now)) onP25Call?.invoke(tg)
+ if (now - lastStatus >= 2_000L && !halted) { lastStatus = now; status = "$deviceLabel · P25 · control channel $where · $messages messages" + turnNote() }
+ }
+ if (lost) p25Lock = null
+ UsbWifi.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" })
+ }
+ }
+
/** Holds [tuneHz] for the waterfall screen: a row of the ~2 MHz around it every few tens of ms. */
private fun runTuned(sdr: SdrDevice, name: String) {
val hz = tuneHz ?: return
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 64b9cae..77b3a22 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -73,6 +73,8 @@ class ScanForegroundService : Service() {
private const val RADAR_QUIET_MS = 2_500L
private const val OWNER_CHECK_MS = 30_000L
private const val RADAR_HOLD_MS = 120_000L
+ /** A watched talkgroup's call: the user asked for it, like a watched frequency. */
+ private const val P25_CONFIDENCE = 70
/** "GPS connected" again only after the fix was lost this long. */
private const val GPS_RECONNECT_MS = 120_000L
/** The latest position's time and accuracy, for the GPS dot (null: none while scanning). */
@@ -306,6 +308,11 @@ class ScanForegroundService : Service() {
super.onCreate()
NotificationHelper.createChannels(this)
OuiWatchlist.load(this)
+ serviceScope.launch {
+ val today = java.time.LocalDate.now().atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()
+ runCatching { com.rfsentinel.app.detect.FixedRouter.load(AppDatabase.getInstance(this@ScanForegroundService)
+ .knownDeviceDao().familiarRouters(com.rfsentinel.app.detect.FixedRouter.MIN_SESSIONS, today)) }
+ }
pipelineThread = HandlerThread("rf-pipeline").apply { start() }
pipeline = Handler(pipelineThread.looper)
@@ -388,13 +395,19 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.usb.UsbBluetooth.start(this) { list -> pipeline.post { list.forEach(::processUsbBt) } }
com.rfsentinel.app.usb.DeauthWatch.onAttack = { a -> pipeline.post { onDeauth(a) } }
com.rfsentinel.app.usb.KarmaWatch.onAttack = { a -> pipeline.post { onKarma(a) } }
- // An RTL-SDR dongle: strong two-way radio transmissions nearby (signal strength only),
- // or aircraft on 1090 MHz when it's set up as an ADS-B receiver.
- val sdrAdsb = Prefs.sdrAdsb(this) && Prefs.categoryEnabled(this, Category.AIRCRAFT)
- com.rfsentinel.app.sdr.SdrRadio.adsb = sdrAdsb
+ // What the SDR does (Settings > RTL-SDR radio): any mix, in turns.
+ val radioOn = Prefs.categoryEnabled(this, Category.RADIO)
+ 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) }
+ ).toSet()
+ com.rfsentinel.app.sdr.SdrRadio.modes = sdrModes
+ com.rfsentinel.app.sdr.SdrRadio.turnMs = Prefs.sdrTurnS(this) * 1000L
+ com.rfsentinel.app.sdr.SdrRadio.onP25Call = { tg -> pipeline.post { onP25Call(tg) } }
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 (sdrAdsb || Prefs.categoryEnabled(this, Category.RADIO)) {
+ if (sdrModes.isNotEmpty() || radioOn) {
// Settings > RTL-SDR radio: bands, excluded ranges, watched frequencies, sensitivity (re-read on every refresh).
com.rfsentinel.app.sdr.SdrRadio.config = com.rfsentinel.app.sdr.RadioSettings.config(this)
com.rfsentinel.app.sdr.FreqNames.load(this)
@@ -475,6 +488,7 @@ class ScanForegroundService : Service() {
*/
private fun noteLocating(mac: String) {
val now = System.currentTimeMillis()
+ if (Prefs.pinpointAlertsOnly(this) && now - (lastAlerted[mac] ?: 0L) > LOCATING_HOLD_MS) return
val was = now < locatingUntil
locatingUntil = now + LOCATING_HOLD_MS
// Called for every packet of a flagged device: only the switch-on does the setting / permission checks.
@@ -734,7 +748,7 @@ class ScanForegroundService : Service() {
this, mac, trackerHit.label, a.rssi, now, DeviceRegistry.linkedFrom(mac))
) return
if (WhitelistCache.contains(mac)) return
- noteLocating(mac)
+ if (!com.rfsentinel.app.detect.FixedRouter.quiet(mac, c.hits, Prefs.alertThreshold(this))) noteLocating(mac)
maybeLog(a, best, c.vendor, loc, now)
maybeAlert(a, best, c.hits, now, via)
@@ -1068,6 +1082,8 @@ class ScanForegroundService : Service() {
// Someone else's tracker nearby is normal; trackers only alert when they follow you.
if (best.category == Category.TRACKER) return
if (best.listOnly || best.confidence < Prefs.alertThreshold(this)) return
+ // A shop's router you pass every day: listed and logged, no alert.
+ if (com.rfsentinel.app.detect.FixedRouter.quiet(a.mac, hits, Prefs.alertThreshold(this))) return
// Acknowledged from the list: listed and logged, no alert.
if (com.rfsentinel.app.data.AlertMutes.isMuted(this, a.mac, now)) return
val window = Prefs.dedupeWindowMs(this)
@@ -1469,31 +1485,51 @@ class ScanForegroundService : Service() {
} + (via?.let { " · via $it" } ?: "")
val hit = Hit(Category.RADIO, label, e.confidence, if (cell) cellDetail else detail,
if (e.tdma) "SDR signal strength and TETRA burst timing (no decoding)" else "SDR signal strength (no decoding)")
+ // Spoken: the frequency (and its name) when that's on, else the short phrase.
+ val spoken = when {
+ cell -> "Cellular transmitter nearby"
+ Prefs.radioSpeakFreq(this) -> (if (e.tdma) "TETRA radio " else "Radio ") + spokenMhz(e.freqHz) + (name?.let { ", $it" } ?: "")
+ e.tdma -> "TETRA radio nearby"
+ else -> "Radio transmitting nearby"
+ } + (via?.let { ", via $it" } ?: "")
+ radioDetection(hit, "RADIO " + e.mhz + " MHz", e.snrDb, detail, now, "radio:" + e.freqHz, spoken, e.confidence >= threshold)
+ }
+
+ /** A radio [hit] into the detection history (tagged with where you are), and alerted when [alert]. */
+ private fun radioDetection(hit: Hit, mac: String, rssi: Int, evidence: String, now: Long, key: String, spoken: String, alert: Boolean) {
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,
+ mac = mac, label = hit.label, source = "SDR", rssi = rssi,
timestamp = now,
latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = Category.RADIO.name, confidence = e.confidence, evidence = detail
+ category = hit.category.name, confidence = hit.confidence, evidence = evidence
)
)
}
- if (e.confidence >= threshold) {
- val off = alertsOff(hit.category)
- NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java,
- banner = AlertKind.BANNER !in off)
- // Spoken: the frequency (and its name) when that's on, else the short phrase.
- val spoken = when {
- cell -> "Cellular transmitter nearby"
- Prefs.radioSpeakFreq(this) -> (if (e.tdma) "TETRA radio " else "Radio ") + spokenMhz(e.freqHz) + (name?.let { ", $it" } ?: "")
- e.tdma -> "TETRA radio nearby"
- else -> "Radio transmitting nearby"
- } + (via?.let { ", via $it" } ?: "")
- AlertPlayer.play(this, hit.tier, spoken, off = off)
- }
+ if (!alert) return
+ val off = alertsOff(hit.category)
+ NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java,
+ banner = AlertKind.BANNER !in off)
+ AlertPlayer.play(this, hit.tier, spoken, off = off)
+ }
+
+ /** A call started on a P25 talkgroup: reported when it is one you watch (Settings > RTL-SDR radio). */
+ private fun onP25Call(tg: Int) {
+ if (!Prefs.categoryEnabled(this, Category.RADIO)) return
+ val name = com.rfsentinel.app.sdr.P25Log.watched(Prefs.p25Talkgroups(this))[tg] ?: return
+ val row = com.rfsentinel.app.sdr.SdrRadio.p25Log.rows().firstOrNull { it.tg == tg }
+ val called = name.ifEmpty { "talkgroup $tg" }
+ val detail = "A call started on P25 talkgroup $tg${if (name.isNotEmpty()) " ($name)" else ""}, one you watch. " +
+ (row?.lastSource?.let { "Radio $it keyed up. " } ?: "") +
+ (if (row?.emergency == true) "Marked as an emergency call. " else "") +
+ (if (row?.encrypted == true) "Encrypted. " else "") +
+ "Heard on the site's control channel: the radios may be anywhere the site covers, not necessarily near you."
+ val hit = Hit(Category.RADIO, "Talkgroup active: $called", P25_CONFIDENCE, detail, "P25 control channel (signalling only, no voice)")
+ radioDetection(hit, "P25 TG $tg", 0, detail, System.currentTimeMillis(), "p25:$tg", "Talkgroup $called active",
+ P25_CONFIDENCE >= Prefs.alertThreshold(this))
}
/** "154.43" for 154.430 MHz: three decimals, trailing zeros dropped, read well by the voice. */
@@ -1503,7 +1539,10 @@ class ScanForegroundService : Service() {
/** Police aircraft (ADS-B) and Waze reports: internet sources, both off by default. */
private val onlineWatchLazy = lazy {
com.rfsentinel.app.online.OnlineWatch(this, serviceScope, { lastLocation ?: lastFix },
- onCallout = { text -> pipeline.post { AlertPlayer.callout(this, text) } }) { alert ->
+ onCallout = { text -> pipeline.post {
+ // Waze "getting closer" call-outs follow the category's Voice chip too.
+ if (AlertKind.VOICE !in alertsOff(Category.POLICE_REPORT)) AlertPlayer.callout(this, text)
+ } }) { alert ->
pipeline.post { onOnlineHit(alert) }
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
index cf52600..cad7488 100644
--- a/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/WifiScanEngine.kt
@@ -36,7 +36,9 @@ class WifiScanEngine(
// current position and could fake a device following you.
try {
val nowUs = SystemClock.elapsedRealtime() * 1000
- val fresh = wifiManager.scanResults.filter { nowUs - it.timestamp <= MAX_RESULT_AGE_US }
+ val band = com.rfsentinel.app.util.Prefs.wifiBand(context)
+ val fresh = wifiManager.scanResults.filter { nowUs - it.timestamp <= MAX_RESULT_AGE_US &&
+ (band == com.rfsentinel.app.util.Prefs.WifiBand.ALL || (band == com.rfsentinel.app.util.Prefs.WifiBand.HIGH) == (it.frequency > 3000)) }
if (fresh.isNotEmpty()) onResults(fresh)
} catch (e: SecurityException) {
// Missing location permission - caller should have requested it already.
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 f225c6f..1a83075 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -890,6 +890,7 @@ class SettingsActivity : AppCompatActivity() {
info(binding.rotationLabel, "Normal follows the phone's auto-rotate.\n\nAuto-rotate, upside down too: also turns upside down, which phones like the Pixel never do on their own.\n\nAlways upside down: the USB-C port at the top, for an antenna or adapter plugged in.")
info(binding.bannerLabel, "A picture across the header of the styled themes (a logo or artwork you own). Your custom themes have their own banner, set in the theme maker.")
info(binding.hideTrustedSwitch, "Devices on your whitelist are left off the list and radar.")
+ info(binding.wifiBandLabel, "Which WiFi networks and devices are listed. On a USB WiFi adapter it also sets the channels it hops: 5 and 6 GHz only gives those channels more listening time (police in-car networks are usually on 5 GHz). Adapters that only do 2.4 GHz keep scanning 2.4 GHz.\n\nThe phone's own WiFi scan always covers every band; the others are only left out of the list. A USB adapter picks up a change when it next starts.")
info(binding.scanModeLabel, "Maximum finds devices fastest and uses the most battery. Battery saver notices them later.")
info(binding.intervalLabel, "How often WiFi is scanned. Android allows an app 4 scans in 2 minutes unless WiFi scan throttling is turned off in Developer options.")
withUnit(binding.intervalInput, "s")
@@ -897,7 +898,9 @@ class SettingsActivity : AppCompatActivity() {
info(binding.carAutoSwitch, "Starts scanning when the phone connects to your car's Bluetooth or Android Auto, and stops when you leave.")
info(binding.carRecordSwitch, "Records a GPS trace when the phone connects to your car's Bluetooth or Android Auto, and saves it when you leave. Starts scanning too if it isn't running. A trace you started yourself is never stopped.")
info(binding.presetLabel, PRESETS_INFO)
- info(binding.thresholdLabel, "Weak: every match, more false alarms.\n\nProbable: recommended.\n\nStrong only: the fewest alerts.")
+ info(binding.thresholdLabel, "Weak: every match, more false alarms.\n\nProbable: recommended.\n\nStrong only: the fewest alerts.\n\n" +
+ "Probable and Strong only don't alert on a vehicle router (Cradlepoint, Sierra Wireless) you hear day after day, " +
+ "like one in a shop, unless something else backs it. Weak alerts on all of them.")
binding.thresholdMedium.text = tagged("Probable", "recommended")
info(binding.radarBeepSwitch, "Beeps faster as a flagged device gets closer, like a radar detector.")
info(binding.detectorSoundSwitch, "Alerts use radar-detector tones (Ka, K and X) and say \"GPS connected\" when the first GPS fix comes in.")
@@ -933,6 +936,7 @@ class SettingsActivity : AppCompatActivity() {
info(binding.rtl5gSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS. Experimental.")
info(binding.usbLightSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS: the light blinks with received traffic.")
info(binding.pinpointSwitch, "Works out where a flagged device is from many readings as you move (GPS runs precise every second while one is in range).")
+ info(binding.pinpointAlertsSwitch, "Pinpoints and shows the live read card only for devices that alerted you, not for every flagged device (a shop's router you pass daily).")
info(binding.liveExportSwitch, "Keeps a live copy of matches, devices and radio hits in a folder other apps can read.")
info(binding.retentionLabel, "How long device history is kept. 0 keeps it forever.")
withUnit(binding.retentionInput, "days")
@@ -1253,9 +1257,41 @@ class SettingsActivity : AppCompatActivity() {
setOnCheckedChangeListener { _, v -> save(v) }
}.also { box.addView(if (info == null) it else infoRow(it, info)) }
- switch("ADS-B aircraft receiver", Prefs.sdrAdsb(this),
- "Listens on 1090 MHz for aircraft instead of sweeping the radio bands. Police aircraft are found without internet. " +
- "Needs Police aircraft turned on. A 1090 MHz antenna helps; the stock one hears out to about 50 km.") { Prefs.setSdrAdsb(this, it) }
+ // What the SDR does: any mix; with more than one ticked it takes turns.
+ var showSdrOptions: () -> Unit = {}
+ info(label("Scan with the SDR"), "Tick what the RTL-SDR or HackRF does while scanning. One SDR hears one thing at a time: " +
+ "with more than one ticked it takes turns, and each scan hears nothing while another has its turn. " +
+ "Tick only one to give it all the time.", "Scan with the SDR")
+ fun scan(t: String, on: Boolean, details: String, save: (Boolean) -> Unit) = android.widget.CheckBox(this).apply {
+ text = t; isChecked = on
+ setOnCheckedChangeListener { _, v -> save(v); showSdrOptions() }
+ }.also { box.addView(infoRow(it, details)) }
+ val sweepBox = scan("Radio activity sweep", Prefs.sdrSweep(this),
+ "Sweeps the radio bands below for strong two-way radio transmissions nearby: signal strength only, nothing decoded. " +
+ "Needs Two-way radio turned on.") { Prefs.setSdrSweep(this, it) }
+ val adsbBox = scan("ADS-B aircraft receiver", Prefs.sdrAdsb(this),
+ "Listens on 1090 MHz for aircraft: police aircraft are found without internet. Needs Police aircraft turned on. " +
+ "A 1090 MHz antenna helps; the stock one hears out to about 50 km.") { Prefs.setSdrAdsb(this, it) }
+ val p25Box = scan("P25 control channel", Prefs.sdrP25(this),
+ "Experimental. Finds the P25 trunked-radio control channel here (700 / 800 MHz, used in the United States and Canada) and " +
+ "follows it: which talkgroups get a channel, and when (Tools › P25 talkgroups). Signalling only: voice is never decoded. " +
+ "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) }
+ slider(30, 300, Prefs.sdrTurnS(this), { "Time for each scan: $it s" }) { Prefs.setSdrTurnS(this, it) }
+ info(box.getChildAt(box.childCount - 2), "With more than one scan ticked, the SDR spends this long on each in turn. Longer misses less " +
+ "within a scan; shorter comes back to each sooner.", "Time for each scan")
+ val turnViews = listOf(box.getChildAt(box.childCount - 2), box.getChildAt(box.childCount - 1))
+ lines("Watch these talkgroups", "1234 Sheriff dispatch\n2001", Prefs.p25Talkgroups(this),
+ "P25: alerts when a call starts on one of them, and names them on the P25 talkgroups screen. One per line: the " +
+ "talkgroup number, with an optional name.") { Prefs.setP25Talkgroups(this, it) }
+ val talkgroupViews = listOf(box.getChildAt(box.childCount - 2), box.getChildAt(box.childCount - 1))
+ showSdrOptions = {
+ val ticked = listOf(sweepBox, adsbBox, p25Box).count { it.isChecked }
+ turnViews.forEach { it.visibility = if (ticked > 1) View.VISIBLE else View.GONE }
+ talkgroupViews.forEach { it.visibility = if (p25Box.isChecked) View.VISIBLE else View.GONE }
+ }
+ showSdrOptions()
slider(com.rfsentinel.app.sdr.RadioWatch.MIN_SNR_SETTING, com.rfsentinel.app.sdr.RadioWatch.MAX_SNR_SETTING, Prefs.radioMinSnr(this),
{ "Sensitivity: $it dB above the noise" }) {
Prefs.setRadioMinSnr(this, it)
@@ -1799,6 +1835,7 @@ class SettingsActivity : AppCompatActivity() {
}
var off = Prefs.categoryAlertsOff(this, c)
com.rfsentinel.app.data.AlertKind.entries.forEach { kind ->
+ if (kind == com.rfsentinel.app.data.AlertKind.BEEP && !Prefs.hasRadarTicks(c)) return@forEach
chips.addView(com.rfsentinel.app.ui.FitChip(this).apply {
text = kind.label; isCheckable = true
com.rfsentinel.app.ui.ChipStyle.apply(this)
@@ -2248,6 +2285,11 @@ class SettingsActivity : AppCompatActivity() {
// Scanning
binding.bleSwitch.isChecked = Prefs.bleEnabled(this)
binding.wifiSwitch.isChecked = Prefs.wifiEnabled(this)
+ binding.wifiBandGroup.check(when (Prefs.wifiBand(this)) {
+ Prefs.WifiBand.LOW -> R.id.wifiBandLow
+ Prefs.WifiBand.HIGH -> R.id.wifiBandHigh
+ Prefs.WifiBand.ALL -> R.id.wifiBandAll
+ })
binding.scanModeGroup.check(
when (Prefs.bleScanMode(this)) {
ScanSettings.SCAN_MODE_BALANCED -> R.id.scanModeBalanced
@@ -2440,6 +2482,7 @@ class SettingsActivity : AppCompatActivity() {
binding.followMetersInput.setText(Prefs.followMinMeters(this).toString())
binding.gpsSwitch.isChecked = Prefs.gpsTaggingEnabled(this)
binding.pinpointSwitch.isChecked = Prefs.pinpointFlagged(this)
+ binding.pinpointAlertsSwitch.isChecked = Prefs.pinpointAlertsOnly(this)
binding.autoRecordSwitch.isChecked = Prefs.autoRecordTrace(this)
binding.ouiSpyRelaySwitch.isChecked = Prefs.ouiSpyRelayAll(this)
binding.ouiSpyPhoneBleSwitch.isChecked = Prefs.ouiSpyPhoneBle(this)
@@ -2650,6 +2693,11 @@ class SettingsActivity : AppCompatActivity() {
private fun save() {
Prefs.setBleEnabled(this, binding.bleSwitch.isChecked)
Prefs.setWifiEnabled(this, binding.wifiSwitch.isChecked)
+ Prefs.setWifiBand(this, when (binding.wifiBandGroup.checkedRadioButtonId) {
+ R.id.wifiBandLow -> Prefs.WifiBand.LOW
+ R.id.wifiBandHigh -> Prefs.WifiBand.HIGH
+ else -> Prefs.WifiBand.ALL
+ })
Prefs.setBleScanMode(
this,
when (binding.scanModeGroup.checkedRadioButtonId) {
@@ -2713,6 +2761,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setFollowMinMeters(this, (binding.followMetersInput.text.toString().toIntOrNull() ?: 800).coerceIn(100, 50_000))
Prefs.setGpsTaggingEnabled(this, binding.gpsSwitch.isChecked)
Prefs.setPinpointFlagged(this, binding.pinpointSwitch.isChecked)
+ Prefs.setPinpointAlertsOnly(this, binding.pinpointAlertsSwitch.isChecked)
Prefs.setAutoRecordTrace(this, binding.autoRecordSwitch.isChecked)
Prefs.setOuiSpyRelayAll(this, binding.ouiSpyRelaySwitch.isChecked)
Prefs.setOuiSpyPhoneBle(this, binding.ouiSpyPhoneBleSwitch.isChecked)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
index 5f9a273..44afe6d 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
@@ -153,7 +153,7 @@ class AircraftActivity : AppCompatActivity() {
sources.text = if (demo) "Demo aircraft" else "RTL-SDR: $mine · online feeds: $online" +
if (list.any { it.distanceKm == null }) " · ${list.count { it.distanceKm == null }} not placed (no position yet)" else ""
// The RTL-SDR's receiver: messages decoded per second over the last minute.
- val adsb = SdrRadio.status.contains("ADS-B")
+ val adsb = SdrRadio.mode == SdrRadio.Mode.ADSB
rateCard.visibility = if (adsb) View.VISIBLE else View.GONE
if (adsb) {
val n = SdrRadio.adsbMessages
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index 2938bb4..9e55a83 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -232,7 +232,8 @@ class DeviceDetailActivity : AppCompatActivity() {
binding.gauge.set(live.rssi, live.bestRssi, trendDir)
binding.rssiDetail.text = (if (visual) "${ProximityUtil.band(live.rssi)}\n" else "dBm · ${ProximityUtil.band(live.rssi)} $trend\n") +
"${DeviceIntel.formatDistance(live.distanceM)} (rough) · best ${live.bestRssi} dBm" +
- (if (liveMac != mac) "\nNow heard as $liveMac" else "")
+ (if (liveMac != mac) "\nNow heard as $liveMac" else "") +
+ (if (locatingThis()) LiveRead.sweepText()?.let { "\n$it" }.orEmpty() else "")
binding.graph.setSamples(live.history)
binding.locateButton.isEnabled = true
binding.locateButton.text = if (locatingThis()) "Stop" else "Locate"
@@ -570,7 +571,7 @@ class DeviceDetailActivity : AppCompatActivity() {
private fun startLocate() {
LiveRead.startLocate(this, mac)
binding.locateButton.text = "Stop"
- Toast.makeText(this, "Walk around: beeps speed up as the signal gets stronger. It keeps going on the map", Toast.LENGTH_LONG).show()
+ Toast.makeText(this, "Walk around: beeps speed up as the signal gets stronger. Or stand still, phone flat, and turn slowly for its direction", Toast.LENGTH_LONG).show()
}
private fun stopLocate() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
index 4deab40..5fe8062 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveRead.kt
@@ -3,6 +3,10 @@ package com.rfsentinel.app.ui
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PixelFormat
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
import android.media.AudioManager
import android.media.ToneGenerator
import android.os.Build
@@ -33,10 +37,13 @@ object LiveRead {
enum class Mode(val label: String) { LOCATE("LOCATING"), PINPOINT("PINPOINTING") }
- /** [rssi] and [distanceM] are null while it isn't heard; [trend] 1 getting closer, -1 moving away, 0 steady. */
+ /**
+ * [rssi] and [distanceM] are null while it isn't heard; [trend] 1 getting closer, -1 moving away, 0 steady.
+ * [sweep]: the on-foot sweep's hint while locating on a phone with a compass.
+ */
data class Read(
val mode: Mode, val mac: String, val title: String, val tag: String?, val color: Int,
- val rssi: Int?, val distanceM: Double?, val trend: Int
+ val rssi: Int?, val distanceM: Double?, val trend: Int, val sweep: String? = null
)
private const val TICK_MS = 1_000L
@@ -44,6 +51,8 @@ object LiveRead {
private const val HEARD_MS = 10_000L
/** A pinpointed device unheard this long gives way to another flagged one. */
private const val PINPOINT_SWITCH_MS = 15_000L
+ /** The pinpointing card hides after this on one device (pinpointing goes on), so a parked one doesn't keep it up. */
+ private const val PINPOINT_CARD_MS = 60_000L
private const val NO_FLAG_COLOR = 0xFF9AA5AD.toInt()
private val main = Handler(Looper.getMainLooper())
@@ -58,9 +67,26 @@ object LiveRead {
private var tone: ToneGenerator? = null
private var appContext: Context? = null
+ // ---- Sweep (main thread): compass heading + each new signal reading while locating ----
+ private val sweep = Sweep()
+ /** Compass degrees the phone faces, null without a compass or before its first reading. */
+ @Volatile private var heading: Float? = null
+ private var sweepFed = 0L
+ private val compass = object : SensorEventListener {
+ private val m = FloatArray(9); private val o = FloatArray(3)
+ override fun onSensorChanged(e: SensorEvent) {
+ SensorManager.getRotationMatrixFromVector(m, e.values)
+ SensorManager.getOrientation(m, o)
+ heading = ((Math.toDegrees(o[0].toDouble()) + 360) % 360).toFloat()
+ }
+ override fun onAccuracyChanged(s: Sensor?, a: Int) {}
+ }
+
// ---- Pinpoint (the scan's pipeline thread) ----
private var pinMac: String? = null
private var pinHeard = 0L
+ /** When [pinMac] became the one read. */
+ @Volatile private var pinSince = 0L
@Volatile private var pinUntil = 0L
/** The pinpointed device whose card was dismissed (it comes back for another device or the next pinpointing). */
@Volatile private var dismissedPin: String? = null
@@ -72,6 +98,10 @@ object LiveRead {
locating = mac
followed = null
tone = runCatching { ToneGenerator(AudioManager.STREAM_MUSIC, 80) }.getOrNull()
+ sweep.clear(); sweepFed = 0L; heading = null
+ (context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager)?.let { sm ->
+ sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)?.let { sm.registerListener(compass, it, SensorManager.SENSOR_DELAY_UI) }
+ }
main.post(beep)
tick()
}
@@ -82,6 +112,8 @@ object LiveRead {
val was = locating != null
locating = null; followed = null
tone?.release(); tone = null
+ (appContext?.getSystemService(Context.SENSOR_SERVICE) as? SensorManager)?.unregisterListener(compass)
+ heading = null
if (was) tick()
}
@@ -97,6 +129,8 @@ object LiveRead {
}
// Out of range (gone from the list): Locate ends, as on the device screen.
val s = DeviceRegistry.get(liveMac) ?: DeviceRegistry.get(mac) ?: run { stopLocate(); return }
+ // Each new reading, with the way the phone faces now (a slow turn barely moves between the two).
+ heading?.let { h -> if (s.lastSeen != sweepFed) { sweepFed = s.lastSeen; sweep.add(s.lastSeen, h, s.rssi) } }
if (!AlertPlayer.locateTick(ctx)) tone?.startTone(ToneGenerator.TONE_PROP_BEEP, 60)
// Faster as the signal gets stronger (same curve as the radar beeps).
main.postDelayed(this, Beeper.tickIntervalMs(s.rssi))
@@ -111,7 +145,10 @@ object LiveRead {
fun pinpoint(mac: String, now: Long, until: Long) {
val cur = pinMac
if (now > pinUntil) dismissedPin = null // a new round of pinpointing
- if (cur == null || cur == mac || now > pinUntil || now - pinHeard > PINPOINT_SWITCH_MS) { pinMac = mac; pinHeard = now }
+ if (cur == null || cur == mac || now > pinUntil || now - pinHeard > PINPOINT_SWITCH_MS) {
+ if (cur != mac || now > pinUntil) pinSince = now
+ pinMac = mac; pinHeard = now
+ }
val starting = now > pinUntil
pinUntil = until
if (starting) main.post { tick() }
@@ -133,9 +170,9 @@ object LiveRead {
/** What to show now, or null for no card. */
fun current(now: Long = System.currentTimeMillis()): Read? {
- locating?.let { m -> return read(Mode.LOCATE, m, now) }
+ locating?.let { m -> return read(Mode.LOCATE, m, now).copy(sweep = sweepText(now)) }
val p = synchronized(this) { pinMac } ?: return null
- if (now > pinUntil || p == dismissedPin) return null
+ if (now > pinUntil || p == dismissedPin || now - pinSince > PINPOINT_CARD_MS) return null
return read(Mode.PINPOINT, p, now)
}
@@ -155,6 +192,19 @@ object LiveRead {
)
}
+ /** The sweep's hint while locating: how to turn, then the direction. Null without a compass. Main thread. */
+ fun sweepText(now: Long = System.currentTimeMillis()): String? {
+ val h = heading ?: return null
+ val dir = sweep.direction(now) ?: return "Sweep: phone flat in front of you, turn slowly " +
+ "(${sweep.covered(now) * 360 / Sweep.SECTORS}° of 360°)"
+ val turn = Sweep.turn(h, dir)
+ return "Strongest facing ${Sweep.compassPoint(dir)} · " + when {
+ kotlin.math.abs(turn) <= 20 -> "ahead"
+ turn > 0 -> "turn right $turn°"
+ else -> "turn left ${-turn}°"
+ }
+ }
+
/** 1 getting closer, -1 moving away, 0 steady: the newest reading against the few before it. */
fun trend(s: DeviceRegistry.Snapshot): Int {
val recent = s.history.takeLast(6).dropLast(1)
@@ -210,6 +260,8 @@ internal class LiveReadCard(private val b: ViewLiveReadBinding) {
r.distanceM?.let { DeviceIntel.formatDistance(it) + " (rough)" },
when (r.trend) { 1 -> "▲ closer"; -1 -> "▼ farther"; else -> null }
).joinToString(" · ")
+ b.liveSweep.text = r.sweep
+ b.liveSweep.visibility = if (r.sweep == null) View.GONE else View.VISIBLE
val level = VisualMode.dbmLevel(r.rssi)
b.liveBar.set(level, VisualMode.heat(level))
b.liveClose.contentDescription = if (r.mode == LiveRead.Mode.LOCATE) "Stop locating" else "Hide the live read"
@@ -251,7 +303,7 @@ internal class LiveReadOverlay(
if (b == null) {
val nb = ViewLiveReadBinding.inflate(LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_RFSentinel)))
// A little smaller than on the full map: it sits beside another app.
- nb.liveTitle.textSize = 14f; nb.liveDetail.textSize = 12f
+ nb.liveTitle.textSize = 14f; nb.liveDetail.textSize = 12f; nb.liveSweep.textSize = 12f
nb.root.elevation = 6f * context.resources.displayMetrics.density
val type = if (Build.VERSION.SDK_INT >= 26) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE
diff --git a/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt
new file mode 100644
index 0000000..4f79b14
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt
@@ -0,0 +1,128 @@
+package com.rfsentinel.app.ui
+
+import android.annotation.SuppressLint
+import android.os.Bundle
+import android.text.format.DateUtils
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.widget.doAfterTextChanged
+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.sdr.P25Log
+import com.rfsentinel.app.sdr.P25Tsbk
+import com.rfsentinel.app.sdr.SdrRadio
+import com.rfsentinel.app.util.Prefs
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import java.util.Locale
+
+/**
+ * The P25 control channel the SDR follows (Settings > RTL-SDR radio > P25 control channel): its site, and the
+ * talkgroups and private calls granted a channel there, most recent first. Watched talkgroups are named and
+ * marked. Signalling only: nothing here is voice.
+ */
+class P25Activity : AppCompatActivity() {
+
+ private lateinit var binding: ActivityLogBinding
+ private var rows: List<P25Log.Row> = emptyList()
+ private var watched: Map<Int, String> = emptyMap()
+ 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 = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
+ override fun getItemCount() = rows.size
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
+ object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}
+
+ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
+ val r = rows[position]
+ ItemDetectionBinding.bind(holder.itemView).apply {
+ val name = r.tg?.let { watched[it] }
+ labelText.text = listOfNotNull(title(r), name?.ifEmpty { "watched" }, "EMERGENCY".takeIf { r.emergency },
+ "encrypted".takeIf { r.encrypted }).joinToString(" · ")
+ labelText.setTextColor(when {
+ r.emergency -> EMERGENCY
+ name != null -> ChipStyle.accent(this@P25Activity).first
+ else -> macText.currentTextColor
+ })
+ macText.text = listOfNotNull(
+ r.lastHz?.let { String.format(Locale.US, "%.4f MHz", it / 1e6) } ?: r.lastChannel?.let { "channel ${P25Tsbk.channelName(it)}" },
+ r.lastSource?.let { "last radio $it" }
+ ).joinToString(" · ").ifEmpty { "No call yet: radios affiliated" }
+ metaText.text = listOfNotNull(
+ "${r.calls} call${if (r.calls == 1) "" else "s"}",
+ "${r.radios} radio${if (r.radios == 1) "" else "s"}",
+ r.lastAt.takeIf { it > 0 }?.let { DateUtils.getRelativeTimeSpanString(it, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS) }
+ ).joinToString(" · ")
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ binding = ActivityLogBinding.inflate(layoutInflater)
+ setContentView(binding.root)
+ binding.root.applySystemBarInsets()
+ title = "P25 talkgroups"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding.searchInput.doAfterTextChanged { refresh() }
+ binding.root.addView(header, 2)
+ binding.recyclerView.layoutManager = LinearLayoutManager(this)
+ binding.recyclerView.adapter = adapter
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(1_000) }
+ }
+ }
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ @SuppressLint("NotifyDataSetChanged")
+ private fun refresh() {
+ watched = P25Log.watched(Prefs.p25Talkgroups(this))
+ val q = binding.searchInput.text?.toString()?.trim().orEmpty()
+ rows = SdrRadio.p25Log.rows().filter { r ->
+ q.isEmpty() || listOfNotNull(title(r), r.tg?.let { watched[it] }, r.lastSource?.toString()).any { it.contains(q, ignoreCase = true) }
+ }
+ val s = SdrRadio.p25Log.summary()
+ header.text = listOfNotNull(
+ SdrRadio.status.ifBlank { "No SDR running" },
+ s.site?.let { site ->
+ listOfNotNull(site.wacn?.let { "WACN %05X".format(it) }, "system %03X".format(site.sysId),
+ site.rfss?.let { rfss -> "site $rfss-${site.site}" }).joinToString(" · ")
+ },
+ if (s.messages > 0) "${s.messages} messages · ${s.registrations} radios registered" else null
+ ).joinToString("\n")
+ adapter.notifyDataSetChanged()
+ val empty = when {
+ rows.isNotEmpty() -> null
+ q.isNotEmpty() -> "Nothing matches."
+ SdrRadio.Mode.P25 !in SdrRadio.modes -> "P25 is off.\nTick P25 control channel in Settings › RTL-SDR radio. It runs while scanning, with an RTL-SDR plugged in."
+ else -> "No calls heard yet.\nTalkgroups show up here as the control channel grants them a channel."
+ }
+ 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
+ }
+
+ companion object {
+ private val EMERGENCY = 0xFFD0503C.toInt()
+
+ /** "Talkgroup 1234", or "Private call to radio 123456". */
+ fun title(r: P25Log.Row) = r.tg?.let { "Talkgroup $it" } ?: "Private call to radio ${r.target}"
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
index 524511a..efac4f1 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RadarView.kt
@@ -19,15 +19,21 @@ import kotlin.math.sin
* Radar-style view of nearby devices. Distance from the centre = signal
* strength (a stronger signal plots closer). The ANGLE is a stable position
* derived from the address so blips don't jump around - a single phone
- * antenna cannot measure direction, and the view says so.
+ * antenna cannot measure direction, and the view says so. An alert whose
+ * position is known ([Blip.bearing]) plots in its real direction instead,
+ * with a line from you.
*/
class RadarView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {
- data class Blip(val mac: String, val rssi: Int, val color: Int, val flagged: Boolean, val label: String?)
+ /** [bearing]: compass degrees from you to the device, when its position is known. */
+ data class Blip(val mac: String, val rssi: Int, val color: Int, val flagged: Boolean, val label: String?,
+ val bearing: Float? = null)
var onBlipClick: ((String) -> Unit)? = null
+ /** Your course in compass degrees for heading-up; null is north-up. */
+ var heading: Float? = null
private var blips: List<Blip> = emptyList()
private var sweep = 0f
@@ -84,10 +90,13 @@ class RadarView @JvmOverloads constructor(
return ((h and 0x7fffffff) % 3600) / 3600.0 * 2 * Math.PI
}
+ /** Screen angle (0 = right, clockwise) of a compass bearing, with up = [heading] or north. */
+ private fun screenAngle(bearing: Float) = Math.toRadians((bearing - (heading ?: 0f) - 90f).toDouble())
+
private fun position(b: Blip): Pair<Float, Float> {
val (cx, cy) = center()
val r = radius() * rssiToFraction(b.rssi)
- val a = angleOf(b.mac)
+ val a = b.bearing?.let { screenAngle(it) } ?: angleOf(b.mac)
return Pair(cx + (r * cos(a)).toFloat(), cy + (r * sin(a)).toFloat())
}
@@ -115,11 +124,22 @@ class RadarView @JvmOverloads constructor(
canvas.drawCircle(cx, cy, rad, sweepPaint)
canvas.restore()
+ val directional = blips.any { it.bearing != null }
+ if (directional) {
+ val n = screenAngle(0f)
+ canvas.drawText("N", cx + ((rad - 10 * density) * cos(n)).toFloat() - 4 * density,
+ cy + ((rad - 10 * density) * sin(n)).toFloat() + 4 * density, labelPaint.apply { color = scopeText })
+ }
+
val t = (System.currentTimeMillis() % 1000L) / 1000f
// Ordinary devices first so flagged ones draw on top.
for (b in blips.sortedBy { it.flagged }) {
val (x, y) = position(b)
blipPaint.color = b.color
+ if (b.bearing != null) {
+ pulsePaint.color = alpha(b.color, 0x99)
+ canvas.drawLine(cx, cy, x, y, pulsePaint)
+ }
if (b.flagged) {
pulsePaint.color = (b.color and 0x00FFFFFF) or (((1f - t) * 200).toInt() shl 24)
canvas.drawCircle(x, y, (7 + 14 * t) * density, pulsePaint)
@@ -135,7 +155,8 @@ class RadarView @JvmOverloads constructor(
canvas.drawCircle(cx, cy, 5 * density, youPaint)
canvas.drawText(
- "Closer to centre = stronger signal · angle is not direction",
+ if (directional) "Closer = stronger signal · lines point to located alerts"
+ else "Closer to centre = stronger signal · angle is not direction",
8 * density, height - 8 * density, textPaint
)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt b/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt
new file mode 100644
index 0000000..31cde12
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/Sweep.kt
@@ -0,0 +1,62 @@
+package com.rfsentinel.app.ui
+
+import kotlin.math.roundToInt
+
+/**
+ * On-foot direction finding while Locate runs: hold the phone flat in front of you and turn slowly. Your body
+ * blocks the signal from behind, so the device is heard strongest when you face it. Readings go into
+ * [SECTORS] compass sectors; once most of a turn is covered, the strongest sector is the direction.
+ * Pure (unit-tested): the compass and signal readings come from [LiveRead].
+ */
+class Sweep {
+
+ private class Reading(val time: Long, val heading: Float, val rssi: Int)
+ private val readings = ArrayDeque<Reading>()
+
+ /** A new signal reading [rssi] heard while facing [heading] (compass degrees). */
+ fun add(now: Long, heading: Float, rssi: Int) {
+ readings.addLast(Reading(now, (heading % 360f + 360f) % 360f, rssi))
+ while (readings.isNotEmpty() && now - readings.first().time > WINDOW_MS) readings.removeFirst()
+ }
+
+ fun clear() = readings.clear()
+
+ /** Sectors with a reading in the last [WINDOW_MS] (out of [SECTORS]). */
+ fun covered(now: Long) = strongest(now).count { it != null }
+
+ /** Compass degrees of the strongest sector's centre, or null until a turn is covered and one sector stands out. */
+ fun direction(now: Long): Float? {
+ val best = strongest(now)
+ val heard = best.filterNotNull()
+ if (heard.size < MIN_SECTORS) return null
+ val peak = heard.max()
+ if (peak - heard.sorted()[heard.size / 2] < MIN_LEAD_DB) return null
+ return best.indexOf(peak) * SECTOR_DEG + SECTOR_DEG / 2
+ }
+
+ private fun strongest(now: Long): Array<Int?> {
+ val best = arrayOfNulls<Int>(SECTORS)
+ for (r in readings) if (now - r.time <= WINDOW_MS) {
+ val i = (r.heading / SECTOR_DEG).toInt().coerceIn(0, SECTORS - 1)
+ best[i] = maxOf(best[i] ?: Int.MIN_VALUE, r.rssi)
+ }
+ return best
+ }
+
+ companion object {
+ const val SECTORS = 12
+ const val SECTOR_DEG = 360f / SECTORS
+ /** A turn covers this many sectors (240°) before a direction is given. */
+ const val MIN_SECTORS = 8
+ /** The strongest sector must beat the typical one by this much, else the body shadow didn't show. */
+ const val MIN_LEAD_DB = 4
+ /** Readings older than this drop out, so walking somewhere new starts a fresh sweep. */
+ const val WINDOW_MS = 30_000L
+
+ private val POINTS = arrayOf("N", "NE", "E", "SE", "S", "SW", "W", "NW")
+ fun compassPoint(deg: Float) = POINTS[(((deg % 360f + 360f) % 360f) / 45f).roundToInt() % 8]
+
+ /** Degrees to turn from [heading] to face [target]: positive right, negative left (-180..180). */
+ fun turn(heading: Float, target: Float): Int = (((target - heading) % 360f + 540f) % 360f - 180f).roundToInt()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
index cfb66f6..28e251f 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
@@ -123,7 +123,8 @@ class WaterfallActivity : AppCompatActivity() {
binding.hintText.text = when {
!running -> "Plug in an RTL-SDR or HackRF and start scanning to see the radio bands live."
tuned != null -> "Zoomed in on about 2 MHz. Radio detection is paused until you go back to the sweep. Tap to move."
- SdrRadio.adsb -> "The SDR is receiving ADS-B. Tune to look at a frequency."
+ 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."
else -> "One row per sweep of your watched bands, newest at the top. Tap a signal to zoom in."
}
binding.sweepButton.visibility = if (tuned != null) View.VISIBLE else View.GONE
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
index f079e3a..99573e6 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
@@ -27,12 +27,13 @@ object Mt7612uMonitor {
@Volatile private var stop = false
private val frames = MonitorFrames()
- private val HOP = intArrayOf(
+ private val ALL_HOP = intArrayOf(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
36, 40, 44, 48, 52, 56, 60, 64,
100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144,
149, 153, 157, 161, 165
)
+ private var HOP = ALL_HOP
private const val DWELL_MS = 125L
private val FRESH_MS get() = (HOP.size * DWELL_MS * 9 / 5).coerceAtLeast(3000L)
private const val REPORT_MS = 10_000L
@@ -127,6 +128,7 @@ object Mt7612uMonitor {
fun run(ctx: Context, device: UsbDevice, chipName: String, onStatus: (String) -> Unit,
onFrame: (List<MonitorSighting>) -> Unit) {
if (running) return
+ HOP = UsbWifi.hops(ALL_HOP)
running = true; stop = false; frames.clear(); lastCalMs.clear(); mcuLogged = 0; ctlErrors = 0; mcuAsked = 0; mcuAnswered = 0; uncalibrated = false
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val c = mgr.openDevice(device) ?: run { onStatus("$chipName: couldn't reopen adapter"); running = false; return }
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
index d27c1d3..e293f4c 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
@@ -54,8 +54,9 @@ object Mt7921uMonitor {
*/
internal fun roundPlan(round: Int, active6: Set<Int>): List<Pair<Int, Int>> {
val six = HOP.filter { it.first == 2 }
- return HOP.filter { it.first != 2 } +
- six.filterIndexed { i, (_, ch) -> i % SIX_GHZ_EVERY == round % SIX_GHZ_EVERY || ch in active6 }
+ return (HOP.filter { it.first != 2 } +
+ six.filterIndexed { i, (_, ch) -> i % SIX_GHZ_EVERY == round % SIX_GHZ_EVERY || ch in active6 })
+ .filter { UsbWifi.inBand(it.first != 0) }.ifEmpty { HOP }
}
private const val RX_ANTENNAS = 0x3
private const val SWITCH_TIMEOUT_MS = 500L
@@ -580,7 +581,7 @@ object Mt7921uMonitor {
private class RxState {
var hopAt = 0L; var lastEmit = 0L; var lastRxAt = 0L; var lastCheck = 0L; var hopIdx = 0
- var round = 0; var plan: List<Pair<Int, Int>> = HOP
+ var round = 0; var plan: List<Pair<Int, Int>> = HOP.filter { UsbWifi.inBand(it.first != 0) }
/** 6 GHz channel number -> when a frame was last heard on it. */
val heard6 = HashMap<Int, Long>()
/** The channel held for the antenna check instead of hopping. */
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
index 84e4c64..f2c952a 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
@@ -31,7 +31,7 @@ object Rtl8812auMonitor {
private val HOP_24 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
/** UNII-1 and UNII-3, like the RTL8814AU driver (where most 5 GHz networks are). */
private val HOP_5 = intArrayOf(36, 40, 44, 48, 149, 153, 157, 161, 165)
- private val HOP = HOP_24 + HOP_5
+ private var HOP = HOP_24 + HOP_5
/** The board type the efuse says (which antenna switch and LNA lines the baseband drives); 0 when it can't be read. */
private var rfe = 0
/** The chip's revision: 0 = A, 1 = B, 2 = C... */
@@ -64,6 +64,7 @@ object Rtl8812auMonitor {
fun run(ctx: Context, device: UsbDevice, onStatus: (String) -> Unit,
onFrame: (List<MonitorSighting>) -> Unit) {
if (running) return
+ HOP = UsbWifi.hops(HOP_24 + HOP_5)
running = true; stop = false; frames.clear(); rfShadow.forEach { it.clear() }
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val conn = mgr.openDevice(device) ?: run { onStatus("RTL8812AU: couldn't reopen adapter"); running = false; return }
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
index ae50095..a39de08 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
@@ -23,7 +23,8 @@ object Rtl8814auMonitor {
@Volatile private var stop = false
private val frames = MonitorFrames()
- private val HOP = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 149, 153, 157, 161, 165)
+ private val ALL_HOP = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 36, 40, 44, 48, 149, 153, 157, 161, 165)
+ private var HOP = ALL_HOP
private const val DWELL_MS = 125L
private val FRESH_MS get() = (HOP.size * DWELL_MS * 9 / 5).coerceAtLeast(3000L)
private const val REPORT_MS = 10_000L
@@ -43,6 +44,7 @@ object Rtl8814auMonitor {
fun run(ctx: Context, device: UsbDevice, chipName: String, onStatus: (String) -> Unit,
onFrame: (List<MonitorSighting>) -> Unit) {
if (running) return
+ HOP = UsbWifi.hops(ALL_HOP)
running = true; stop = false; frames.clear(); ctlErrors = 0
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val c = mgr.openDevice(device) ?: run { onStatus("$chipName: couldn't reopen adapter"); running = false; return }
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
index db87729..9279548 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
@@ -103,7 +103,7 @@ object Rtl8821auMonitor {
w16(conn, Rtl8821auTables.REG_RXFLTMAP0, Rtl8821auTables.RXFLTMAP_ALL)
w16(conn, Rtl8821auTables.REG_RXFLTMAP1, Rtl8821auTables.RXFLTMAP_ALL)
w16(conn, Rtl8821auTables.REG_RXFLTMAP2, Rtl8821auTables.RXFLTMAP_ALL)
- HOP = if (scan5g) HOP_24 + HOP_5 else HOP_24
+ HOP = UsbWifi.hops(if (scan5g) HOP_24 + HOP_5 else HOP_24)
if (scan5g) UsbWifi.log("RTL8821AU: 5 GHz hopping on (experimental): ${HOP.joinToString()}")
channelTune(conn, HOP[0])
UsbWifi.log("RTL8821AU: RCR=0x%08x BB(0x800)=0x%08x — monitor live ch ${HOP[0]}".format(
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
index 692eb02..dcb372b 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
@@ -143,7 +143,7 @@ object Rtl8822buMonitor {
private class RxState(val label: String) {
var total = 0L; var bufs = 0L; var lastLog = 0L; var hopAt = 0L; var lastEmit = 0L; var digAt = 0L
- var cycle = 0; var hopIdx = 0; var plan = hopCycle(0)
+ var cycle = 0; var hopIdx = 0; var plan = UsbWifi.hops(hopCycle(0))
/** Register accesses that failed in a row; the adapter is gone or wedged past a limit. */
var ioFailures = 0
/** A channel held by a debug command instead of hopping (0 = hopping). */
@@ -193,7 +193,7 @@ object Rtl8822buMonitor {
if (lock != null && st.parked == lock) AntennaCheck.holding = lock
if (st.parked == 0 && now - st.hopAt > DWELL_MS) {
st.hopIdx++
- if (st.hopIdx >= st.plan.size) { st.cycle++; st.plan = hopCycle(st.cycle); st.hopIdx = 0 }
+ if (st.hopIdx >= st.plan.size) { st.cycle++; st.plan = UsbWifi.hops(hopCycle(st.cycle)); st.hopIdx = 0 }
chipIo(st) { chip.tune(st.channel) }
val (aps, clients) = frames.live(now, REPORT_MS)
val band = if (st.channel > 14) "5 GHz" else "2.4 GHz"
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 86f30c7..109f018 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -160,6 +160,13 @@ object UsbWifi {
@Volatile var status: String = ""
private set
+ /** Settings > WiFi bands, read as a session starts. */
+ @Volatile var band = com.rfsentinel.app.util.Prefs.WifiBand.ALL
+ /** True when a channel of the 5 / 6 GHz bands ([high]) or of 2.4 GHz is in the chosen band. */
+ fun inBand(high: Boolean) = band == com.rfsentinel.app.util.Prefs.WifiBand.ALL || (band == com.rfsentinel.app.util.Prefs.WifiBand.HIGH) == high
+ /** [all]'s channels in the chosen band (2.4 GHz is 1-14); all of them when none are (a 2.4 GHz-only adapter on 5 GHz). */
+ fun hops(all: IntArray): IntArray = all.filter { inBand(it > 14) }.toIntArray().takeIf { it.isNotEmpty() } ?: all
+
/** The adapter waiting for its chip firmware (FOSS build, not downloaded yet), for [FirmwarePrompt]; null when none. */
@Volatile var firmwareNeeded: Chip? = null
private set
@@ -364,6 +371,7 @@ object UsbWifi {
// A quick stop and start: each driver refuses to start while its last session is still stopping.
previous?.join(3_000)
if (previous?.isAlive == true) { status = "USB WiFi (${chip.name}): the last session is still stopping - unplug and replug the adapter"; return@runCatching }
+ band = com.rfsentinel.app.util.Prefs.wifiBand(context)
val onStatus: (String) -> Unit = { s -> status = s }
val onFrames: (List<MonitorSighting>) -> Unit = { list -> onSightings?.invoke(list) }
when (chip.driver) {
diff --git a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
index 388c835..bb6921f 100644
--- a/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/AlertPlayer.kt
@@ -44,14 +44,14 @@ object AlertPlayer {
.setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
- private val carSpeechAttributes = AudioAttributes.Builder()
+ /**
+ * Speech too, on the phone as in the car: a notification usage is muted by Do Not Disturb, which
+ * the phone's driving mode turns on when it joins the car's Bluetooth - silent voice, even the test.
+ */
+ private val speechAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
- private val phoneSpeechAttributes = AudioAttributes.Builder()
- .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
- .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
- .build()
private val main = Handler(Looper.getMainLooper())
private var focusRequest: AudioFocusRequest? = null
@@ -95,7 +95,7 @@ object AlertPlayer {
}
if (willSpeak) {
val app = context.applicationContext
- val attrs = if (inCar) carSpeechAttributes else phoneSpeechAttributes
+ val attrs = speechAttributes
val priority = when {
following -> VoiceQueue.FOLLOWING
tier == Tier.STRONG -> VoiceQueue.STRONG
@@ -195,7 +195,7 @@ object AlertPlayer {
/** A spoken navigation instruction (no beep, no vibration); silent when alerts are muted. */
fun announce(context: Context, text: String) {
if (Prefs.alertsSilenced(context)) return
- Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)
+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, speechAttributes)
}
/**
@@ -205,7 +205,7 @@ object AlertPlayer {
*/
fun navigate(context: Context, text: String, urgent: Boolean) {
if (!Prefs.navVoice(context)) return
- Voice.sayNav(context.applicationContext, text, urgent, carSpeechAttributes)
+ Voice.sayNav(context.applicationContext, text, urgent, speechAttributes)
}
/**
@@ -215,13 +215,13 @@ object AlertPlayer {
fun callout(context: Context, text: String) {
val inCar = CarState.connected
if (Prefs.alertsSilenced(context) || !(Prefs.voiceEnabled(context) || (inCar && Prefs.carVoice(context)))) return
- Voice.say(context.applicationContext, text, VoiceQueue.STRONG, if (inCar) carSpeechAttributes else phoneSpeechAttributes)
+ Voice.say(context.applicationContext, text, VoiceQueue.STRONG, speechAttributes)
}
/** The Settings "Test voice" button: speaks right away with the chosen voice and speed. */
fun testVoice(context: Context, short: Boolean = Prefs.shortVoice(context)) {
Voice.test(context.applicationContext, if (short) "Body cam" else "RF Sentinel voice alerts. Axon body camera nearby.",
- if (CarState.connected) carSpeechAttributes else phoneSpeechAttributes)
+ speechAttributes)
}
/**
@@ -242,7 +242,7 @@ object AlertPlayer {
val am = context.getSystemService(AudioManager::class.java) ?: return
focusRequest?.let { am.abandonAudioFocusRequest(it) }
val req = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)
- .setAudioAttributes(carSpeechAttributes)
+ .setAudioAttributes(speechAttributes)
.build()
focusRequest = req
am.requestAudioFocus(req)
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 47430e1..37ce0d1 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -48,13 +48,22 @@ object Prefs {
/** The ways a category doesn't alert you (Settings › What to detect): banner, sound, voice, vibration, radar beep. */
fun categoryAlertsOff(context: Context, category: Category): Set<com.rfsentinel.app.data.AlertKind> =
- com.rfsentinel.app.data.AlertKind.parse(sp(context).getString("cat_alerts_off_" + category.name, null))
+ com.rfsentinel.app.data.AlertKind.parse(sp(context).getString("cat_alerts_off_" + category.name, null)).let {
+ // Saved before these had no Beep chip: Beep off meant "stop the beeping", which is their alert sound.
+ if (!hasRadarTicks(category) && com.rfsentinel.app.data.AlertKind.BEEP in it)
+ it - com.rfsentinel.app.data.AlertKind.BEEP + com.rfsentinel.app.data.AlertKind.SOUND else it
+ }
fun setCategoryAlertsOff(context: Context, category: Category, off: Set<com.rfsentinel.app.data.AlertKind>) = sp(context).edit {
val key = "cat_alerts_off_" + category.name
- com.rfsentinel.app.data.AlertKind.format(off)?.let { putString(key, it) } ?: remove(key)
+ val kept = if (hasRadarTicks(category)) off else off - com.rfsentinel.app.data.AlertKind.BEEP
+ com.rfsentinel.app.data.AlertKind.format(kept)?.let { putString(key, it) } ?: remove(key)
}
+ /** Radar beeps tick for devices heard nearby; these alerts aren't one (online reports, GPS, cell network). */
+ fun hasRadarTicks(category: Category) =
+ category !in setOf(Category.AIRCRAFT, Category.POLICE_REPORT, Category.GNSS, Category.CELL_ANOMALY)
+
// ---- Alerts ---------------------------------------------------------------
fun soundEnabled(context: Context): Boolean = bool(context, "sound_enabled", true)
@@ -200,6 +209,9 @@ object Prefs {
/** Pinpoint flagged devices from many readings as you move (GPS runs precise every second while one is in range). */
fun pinpointFlagged(context: Context): Boolean = bool(context, "pinpoint_flagged", true)
fun setPinpointFlagged(context: Context, value: Boolean) = setBool(context, "pinpoint_flagged", value)
+ /** Pinpoint (and show the live read card for) only devices that alerted, not every flagged one. */
+ fun pinpointAlertsOnly(context: Context): Boolean = bool(context, "pinpoint_alerts_only", false)
+ fun setPinpointAlertsOnly(context: Context, value: Boolean) = setBool(context, "pinpoint_alerts_only", value)
/**
* How the app turns: NORMAL follows auto-rotate (never upside down on phones like the Pixel), ALL_WAYS
@@ -412,6 +424,12 @@ object Prefs {
}
/** Have the OUI-SPY board relay every network and Bluetooth device it hears (its Wardrive engine). */
/** Whether the screen stays on while an RF Sentinel screen is open. */
+ /** WiFi bands scanned (Settings > Scanning): the phone's results and the USB adapters' channel hopping. */
+ enum class WifiBand { ALL, LOW, HIGH }
+ fun wifiBand(context: Context): WifiBand =
+ runCatching { WifiBand.valueOf(sp(context).getString("wifi_band", null)!!) }.getOrDefault(WifiBand.ALL)
+ fun setWifiBand(context: Context, band: WifiBand) = sp(context).edit { putString("wifi_band", band.name) }
+
enum class ScreenMode { ALWAYS_ON, ON_WHILE_CHARGING, NORMAL }
fun screenMode(context: Context): ScreenMode =
runCatching { ScreenMode.valueOf(sp(context).getString("screen_mode", null)!!) }.getOrDefault(ScreenMode.ON_WHILE_CHARGING)
@@ -558,6 +576,19 @@ object Prefs {
/** The RTL-SDR as an ADS-B aircraft receiver on 1090 MHz instead of the radio sweep (off by default). */
fun sdrAdsb(context: Context): Boolean = bool(context, "sdr_adsb", false)
fun setSdrAdsb(context: Context, v: Boolean) = setBool(context, "sdr_adsb", v)
+ /** The SDR's radio-activity sweep: on by default, unless ADS-B or P25 was switched on when they replaced it. */
+ fun sdrSweep(context: Context): Boolean = bool(context, "sdr_sweep", !sdrAdsb(context) && !bool(context, "sdr_p25", false))
+ fun setSdrSweep(context: Context, v: Boolean) = setBool(context, "sdr_sweep", v)
+ /** The SDR follows a P25 control channel: on by default where P25 is used (the United States or Canada region picked). */
+ 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) = setBool(context, "sdr_p25", v)
+ /** P25 talkgroups to alert on, "1234 Name" a line ([com.rfsentinel.app.sdr.P25Log.watched]). */
+ fun p25Talkgroups(context: Context) = str(context, "p25_talkgroups")
+ fun setP25Talkgroups(context: Context, v: String) = setStr(context, "p25_talkgroups", 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))
/** Name hits from RadioReference (needs the user's own Premium login and developer key; off by default). */
fun radioReferenceOn(context: Context): Boolean = bool(context, "radio_reference_on", false)
diff --git a/app/src/main/java/com/rfsentinel/app/util/Voice.kt b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
index a464a8a..028841b 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Voice.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Voice.kt
@@ -250,7 +250,7 @@ object Voice {
/** English voices, best first: installed (offline) before network, then by quality, US/GB first. */
private fun englishVoices(engine: TextToSpeech): List<android.speech.tts.Voice> =
runCatching { engine.voices.orEmpty() }.getOrDefault(emptySet())
- .filter { it.locale.language == "en" && !it.features.orEmpty().contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED) }
+ .filter { runCatching { it.locale.isO3Language }.getOrNull() == "eng" && !it.features.orEmpty().contains(TextToSpeech.Engine.KEY_FEATURE_NOT_INSTALLED) }
.sortedWith(
compareBy<android.speech.tts.Voice> { it.isNetworkConnectionRequired }
.thenByDescending { it.quality }
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 30801ae..918665a 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -115,6 +115,18 @@
android:layout_height="wrap_content"
android:text="WiFi scanning" />
+ <TextView android:id="@+id/wifiBandLabel" style="@style/SettingsLabel" android:text="WiFi bands" />
+
+ <RadioGroup
+ android:id="@+id/wifiBandGroup"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
+
+ <RadioButton android:id="@+id/wifiBandAll" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="All bands" />
+ <RadioButton android:id="@+id/wifiBandLow" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="2.4 GHz only" />
+ <RadioButton android:id="@+id/wifiBandHigh" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="5 and 6 GHz only" />
+ </RadioGroup>
+
<TextView android:id="@+id/scanModeLabel" style="@style/SettingsLabel" android:text="Bluetooth scan intensity" />
<RadioGroup
@@ -834,6 +846,12 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pinpoint flagged devices on the map" />
+
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/pinpointAlertsSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Pinpoint alerts only" />
</LinearLayout>
<!-- ================= Data ================= -->
diff --git a/app/src/main/res/layout/view_live_read.xml b/app/src/main/res/layout/view_live_read.xml
index 35d18c2..6d68217 100644
--- a/app/src/main/res/layout/view_live_read.xml
+++ b/app/src/main/res/layout/view_live_read.xml
@@ -63,6 +63,16 @@
android:textColor="#B0BAC1"
android:textSize="13sp" />
+ <TextView
+ android:id="@+id/liveSweep"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:ellipsize="end"
+ android:maxLines="1"
+ android:textColor="#B0BAC1"
+ android:textSize="13sp"
+ android:visibility="gone" />
+
<com.rfsentinel.app.ui.LevelBarView
android:id="@+id/liveBar"
android:layout_width="match_parent"
diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xml
index d47d0b0..3cd7f39 100644
--- a/app/src/main/res/menu/menu_main.xml
+++ b/app/src/main/res/menu/menu_main.xml
@@ -19,6 +19,8 @@
app:showAsAction="always" />
<item android:id="@+id/action_waze_now" android:title="Check Waze now" app:showAsAction="never" />
<item android:id="@+id/action_waze_status" android:title="Waze status" app:showAsAction="never" />
+ <item android:id="@+id/action_watchlist" android:title="Watchlist" app:showAsAction="never" />
+ <item android:id="@+id/action_whitelist" android:title="Whitelist" app:showAsAction="never" />
<!-- Everything the app remembers, in one place. -->
<item android:id="@+id/action_history_menu" android:title="History" app:showAsAction="never">
<menu>
diff --git a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt
index f6ba1ae..ebdf389 100644
--- a/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/detect/DetectionTest.kt
@@ -267,6 +267,7 @@ class DetectionTest {
fun wifiSecurityAndChannels() {
assertEquals("WPA3", DeviceIntel.security("[RSN-SAE-CCMP][ESS]"))
assertEquals("Open (no password)", DeviceIntel.security("[ESS]"))
+ assertEquals("Unknown (not read in monitor mode)", DeviceIntel.security(""))
assertEquals(6, DeviceIntel.channelOf(2437))
assertEquals(36, DeviceIntel.channelOf(5180))
assertFalse(DeviceIntel.distanceMeters(ble()).isNaN())
diff --git a/app/src/test/java/com/rfsentinel/app/detect/FixedRouterTest.kt b/app/src/test/java/com/rfsentinel/app/detect/FixedRouterTest.kt
new file mode 100644
index 0000000..f20718a
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/detect/FixedRouterTest.kt
@@ -0,0 +1,24 @@
+package com.rfsentinel.app.detect
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class FixedRouterTest {
+
+ private fun hit(label: String) = Hit(Category.PUBLIC_SAFETY, label, 40, "", "")
+ private val router = hit("Cradlepoint vehicle router - police cars, buses, stores, traffic-signal cabinets")
+
+ @Test
+ fun familiarRouterOnlyIsQuiet() {
+ FixedRouter.load(listOf("00:30:44:aa:bb:cc"))
+ assertTrue(FixedRouter.quiet("00:30:44:AA:BB:CC", listOf(router), 50))
+ // On the Weak threshold every match alerts, familiar routers too.
+ assertFalse(FixedRouter.quiet("00:30:44:AA:BB:CC", listOf(router), 0))
+ // Something else backs it: it still alerts.
+ assertFalse(FixedRouter.quiet("00:30:44:AA:BB:CC", listOf(router, hit("Police car network - Axon Fleet in-car video")), 50))
+ // A router not heard often: alerts.
+ assertFalse(FixedRouter.quiet("00:30:44:11:22:33", listOf(router), 50))
+ assertFalse(FixedRouter.routerOnly(emptyList()))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/detect/PoliceSsidTest.kt b/app/src/test/java/com/rfsentinel/app/detect/PoliceSsidTest.kt
index 127013f..e805917 100644
--- a/app/src/test/java/com/rfsentinel/app/detect/PoliceSsidTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/detect/PoliceSsidTest.kt
@@ -24,9 +24,18 @@ class PoliceSsidTest {
assertTrue(SignatureEngine.policeVehicleSsid("R1900-c0d") != null)
}
+ @Test
+ fun emergencyNamesMatchAsWholeWords() {
+ for (name in listOf("SHERIFF-12", "Medic 7", "PD_Unit4", "K9-12", "Engine12 FD"))
+ assertTrue(name, SignatureEngine.policeVehicleSsid(name)!!.confidence < 50) // weak alone
+ // A familiar router named for an agency still alerts: the name match isn't a router-only match.
+ assertTrue(!FixedRouter.routerOnly(listOf(SignatureEngine.policeVehicleSsid("SHERIFF-12")!!)))
+ }
+
@Test
fun ordinaryNetworksDont() {
- for (name in listOf("NETGEAR42-5G", "Home-5G", "papillon", "Axon", "IBR900", "MBR1400-3e2", "5g", "1-5g"))
+ for (name in listOf("NETGEAR42-5G", "Home-5G", "papillon", "Axon", "IBR900", "MBR1400-3e2", "5g", "1-5g",
+ "Firefly", "Spdnet", "Remedics", "Patrolla"))
assertNull(name, SignatureEngine.policeVehicleSsid(name))
}
}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25DemodTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25DemodTest.kt
new file mode 100644
index 0000000..db14cd2
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25DemodTest.kt
@@ -0,0 +1,52 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+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 P25DemodTest {
+
+ /** Sync + [payload] as dongle I/Q: FM on [carrierHz] from the centre, 8-bit, with a little noise. */
+ private fun signal(payload: IntArray, carrierHz: Double, frames: Int): ByteArray {
+ val dibits = IntArray(40) { (it * 7 + 3) % 4 } + (0 until frames).flatMap { (P25TestSignal.SYNC + payload).toList() } + IntArray(40) { it % 4 }
+ val perSymbol = P25Demod.SAMPLE_RATE / P25Demod.SYMBOL_RATE
+ val out = ByteArray(dibits.size * perSymbol * 2)
+ val rnd = java.util.Random(7)
+ var phase = 0.0; var k = 0
+ for (d in dibits) repeat(perSymbol) {
+ phase += 2 * PI * (carrierHz + P25TestSignal.hz(d)) / P25Demod.SAMPLE_RATE
+ out[k++] = (127.5 + 50 * cos(phase) + rnd.nextGaussian() * 4).roundToInt().coerceIn(0, 255).toByte()
+ out[k++] = (127.5 + 50 * sin(phase) + rnd.nextGaussian() * 4).roundToInt().coerceIn(0, 255).toByte()
+ }
+ return out
+ }
+
+ @Test
+ fun recoversDibitsAfterEachSync() {
+ val rnd = java.util.Random(1)
+ val payload = IntArray(P25Demod.FRAME_DIBITS) { rnd.nextInt(4) }
+ val frames = ArrayList<IntArray>()
+ // The channel 200 kHz off the centre, the dongle's crystal another 900 Hz off.
+ val demod = P25Demod(200_000.0) { frames += it.copyOf() }
+ val iq = signal(payload, 200_900.0, 3)
+ // Fed in USB-sized pieces.
+ var at = 0
+ while (at < iq.size) { val len = minOf(16_384, iq.size - at); demod.feed(iq.copyOfRange(at, at + len), len / 2); at += len }
+ assertEquals(3, demod.syncs)
+ assertEquals(3, frames.size)
+ for (f in frames) assertArrayEquals(payload, f)
+ assertTrue("frequency loop followed the drift: ${demod.offsetHz}", demod.offsetHz > 200_200.0)
+ }
+
+ @Test
+ fun syncPattern() {
+ assertEquals(listOf(3, 3, 3, 3, 3, -3), P25Demod.SYNC.take(6))
+ assertEquals(1, P25Demod.slice(1.1)); assertEquals(0, P25Demod.slice(0.3))
+ assertEquals(2, P25Demod.slice(-0.3)); assertEquals(3, P25Demod.slice(-1.0))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25FrameTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25FrameTest.kt
new file mode 100644
index 0000000..eb41610
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25FrameTest.kt
@@ -0,0 +1,51 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import com.rfsentinel.app.sdr.P25TestSignal.block
+import com.rfsentinel.app.sdr.P25TestSignal.frame
+
+class P25FrameTest {
+
+ private val grant = byteArrayOf(0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x08)
+ private val last = byteArrayOf(0x80.toByte(), 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09)
+
+ @Test
+ fun generatorIsTheStandardOne() {
+ assertEquals(java.lang.Long.parseLong("6331141367235453", 8), P25Frame.BCH_GENERATOR)
+ }
+
+ @Test
+ fun decodesATsduWithErrors() {
+ val f = frame(0x293, P25Frame.DUID_TSDU, block(grant), block(last))
+ // 6 wrong bits in the NID (BCH fixes up to 11) and 3 in the first block (trellis).
+ for (i in listOf(0, 3, 9, 14, 20, 30)) f[i] = f[i] xor 1
+ for (i in listOf(40, 60, 90)) f[i] = f[i] xor 2
+ val d = P25Frame.decode(f)
+ assertEquals(P25Frame.Nid(0x293, 7, 6), d.nid)
+ assertEquals(2, d.tsbks.size)
+ assertArrayEquals(grant, d.tsbks[0].bytes)
+ assertFalse(d.tsbks[0].last)
+ assertTrue(d.tsbks[1].last)
+ assertEquals(0, d.tsbks[1].opcode)
+ }
+
+ @Test
+ fun damagedBlockFailsItsCrc() {
+ val blk = block(last)
+ for (i in 0 until 98 step 3) blk[i] = blk[i] xor 3
+ val d = P25Frame.decode(frame(0x293, P25Frame.DUID_TSDU, blk))
+ assertEquals(0, d.tsbks.size)
+ assertTrue(d.badBlocks > 0)
+ }
+
+ @Test
+ fun noiseIsNoNid() {
+ val r = java.util.Random(3)
+ assertNull(P25Frame.nid(IntArray(32) { r.nextInt(4) }))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25HuntTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25HuntTest.kt
new file mode 100644
index 0000000..ecd8305
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25HuntTest.kt
@@ -0,0 +1,93 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+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 P25HuntTest {
+
+ /** A transmitter: C4FM [dibits] on repeat at [hz], [amp] in dongle units. */
+ private class Carrier(val hz: Long, val amp: Double, val dibits: IntArray) { var phase = 0.0 }
+
+ /** A dongle whose crystal is [ERROR_HZ] off, hearing [carriers] (within its bandwidth) in noise. Time runs on across retunes. */
+ private class FakeDongle(val carriers: List<Carrier>) : SdrDevice {
+ override val label = "fake"
+ override val sampleRate = P25Demod.SAMPLE_RATE
+ override val ctlErrors = 0
+ override val lost = false
+ override val tunerWriteFails = 0
+ override val settleReads = 1
+ var tuned = 0L
+ var p25On = true
+ private var t = 0L
+ private val rnd = java.util.Random(5)
+ override fun open() = true
+ override fun close() {}
+ override fun setSampleRate(rate: Int) {}
+ override fun tune(hz: Long): Boolean { tuned = hz; return true }
+ override fun setGain(tenthsDb: Int) {}
+ override fun resetBuffer() {}
+ override fun read(buf: ByteArray, len: Int): Int {
+ val perSymbol = sampleRate / P25Demod.SYMBOL_RATE
+ val heard = carriers.filter { abs(it.hz + ERROR_HZ - tuned) < 950_000 && (p25On || it !== carriers[0]) }
+ var k = 0
+ while (k < len) {
+ var i = rnd.nextGaussian() * 3; var q = rnd.nextGaussian() * 3
+ for (c in heard) {
+ val d = c.dibits[((t / perSymbol) % c.dibits.size).toInt()]
+ c.phase += 2 * PI * (c.hz + ERROR_HZ - tuned + P25TestSignal.hz(d)) / sampleRate
+ i += c.amp * cos(c.phase); q += c.amp * sin(c.phase)
+ }
+ buf[k++] = (127.5 + i).roundToInt().coerceIn(0, 255).toByte()
+ buf[k++] = (127.5 + q).roundToInt().coerceIn(0, 255).toByte()
+ t++
+ }
+ return len
+ }
+ }
+
+ private val network = byteArrayOf(0x3B, 0x00, 0x01, 0xBE.toByte(), 0xE0.toByte(), 0x03, 0xA1.toByte(), 0x10, 0x40, 0x70)
+ private val grant = byteArrayOf(0x80.toByte(), 0x00, 0x00, 0x10, 0x05, 0x01, 0x23, 0x0A, 0x0B, 0x0C)
+
+ @Test
+ fun findsTheControlChannelPastAStrongerOneAndNoticesWhenItStops() {
+ val control = P25TestSignal.SYNC + P25TestSignal.frame(0x293, P25Frame.DUID_TSDU,
+ P25TestSignal.block(network), P25TestSignal.block(grant))
+ val rnd = java.util.Random(2)
+ val other = IntArray(2000) { rnd.nextInt(4) } // 4-level FSK that isn't P25: no sync, no NID
+ val dongle = FakeDongle(listOf(Carrier(771_106_250L, 20.0, control), Carrier(772_400_000L, 40.0, other)))
+ val logs = ArrayList<String>()
+ val hunt = P25Hunt(dongle) { logs += it; println(it) }
+
+ val lock = hunt.hunt { false }!!
+ assertEquals(2, hunt.tried) // the louder decoy first, then the control channel
+ assertEquals(0x293, lock.nac)
+ assertTrue("locked at ${lock.hz}", abs(lock.hz - (771_106_250L + ERROR_HZ)) < 1_500)
+
+ val heard = ArrayList<P25Tsbk.Msg>()
+ // The control channel goes off the air after a few messages: listen gives up on it.
+ val lost = hunt.listen(lock, { dongle.p25On = heard.size < 6; false }) { heard += it }
+ assertTrue(lost)
+ assertTrue(heard.contains(P25Tsbk.Site(0xBEE00, 0x3A1, null, null, 0x1040)))
+ assertTrue(heard.contains(P25Tsbk.Grant(0x1005, 0x0123, null, 0x0A0B0C, false, false)))
+ // The log tells each stage apart, and keeps the frequency and network code out.
+ assertTrue(logs.any { it.startsWith("P25 try 1/2") && it.endsWith("not a control channel") })
+ assertTrue(logs.any { it.startsWith("P25 try 2/2") && it.contains("control channel (1 NAC seen)") })
+ assertTrue(logs.any { it.startsWith("P25 control channel quiet") && it.contains("Sitex") })
+ assertTrue(logs.none { it.contains("771.") || it.contains("293") })
+ }
+
+ @Test
+ fun everyChannelIsSeenAwayFromTheTunedCentre() {
+ val plan = P25Hunt.plan()
+ for (b in P25Hunt.BANDS) for (f in b step 6_250L)
+ assertTrue("$f", plan.any { abs(f - it) in RadioWatch.DC_GUARD_HZ + 6_000..RadioWatch.USABLE_HZ.toLong() - 6_000 })
+ }
+
+ companion object { const val ERROR_HZ = 18_000L }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25LogTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25LogTest.kt
new file mode 100644
index 0000000..5f77e8b
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25LogTest.kt
@@ -0,0 +1,48 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class P25LogTest {
+
+ @Test
+ fun callsStartOnceAndKeepTheirDetails() {
+ val log = P25Log()
+ log.add(P25Tsbk.Iden(1, 851_006_250L, 6_250, 1), 0)
+ // A grant starts a call; its updates keep it going; after the gap it is a new call.
+ assertEquals(listOf(0x300), log.add(P25Tsbk.Grant(0x1002, 0x300, null, 1001, emergency = false, encrypted = true), 1_000))
+ assertEquals(emptyList<Int>(), log.add(P25Tsbk.GrantUpdate(listOf(0x1002 to 0x300)), 5_000))
+ // One update can start two calls: both are reported.
+ assertEquals(listOf(0x301, 0x302), log.add(P25Tsbk.GrantUpdate(listOf(0x1003 to 0x301, 0x1004 to 0x302)), 6_000))
+ assertEquals(listOf(0x300), log.add(P25Tsbk.Grant(0x1002, 0x300, null, 1002, false, false), 30_000))
+ log.add(P25Tsbk.Affiliation(1003, 0x300), 31_000)
+ log.add(P25Tsbk.Grant(0x1005, null, 77, 1001, false, false), 32_000)
+
+ val rows = log.rows()
+ assertEquals(listOf(null, 0x300), rows.take(2).map { it.tg })
+ assertEquals(setOf(0x301, 0x302), rows.drop(2).map { it.tg }.toSet()) // same moment: either order
+ assertEquals(77, rows[0].target)
+ val tg = rows[1]
+ assertEquals(2, tg.calls)
+ assertEquals(3, tg.radios)
+ assertEquals(851_006_250L + 2 * 6_250, tg.lastHz)
+ assertEquals(false, tg.encrypted)
+ }
+
+ @Test
+ fun siteFillsInAndClearForgets() {
+ val log = P25Log()
+ log.add(P25Tsbk.Site(0xBEE00, 0x3A1, null, null, 0x1040), 0)
+ log.add(P25Tsbk.Site(null, 0x3A1, 1, 7, 0x1040), 0)
+ assertEquals(P25Tsbk.Site(0xBEE00, 0x3A1, 1, 7, 0x1040), log.summary().site)
+ log.clear(10)
+ assertEquals(null, log.summary().site)
+ assertEquals(emptyList<P25Log.Row>(), log.rows())
+ }
+
+ @Test
+ fun watchedTalkgroups() {
+ assertEquals(mapOf(1234 to "Sheriff dispatch", 2001 to "", 9 to "Fire"),
+ P25Log.watched("1234 Sheriff dispatch\n2001\n 9 - Fire\nnot a number\n70000 too big"))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25TestSignal.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25TestSignal.kt
new file mode 100644
index 0000000..9261ceb
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25TestSignal.kt
@@ -0,0 +1,32 @@
+package com.rfsentinel.app.sdr
+
+/** P25 test signals as a transmitter builds them: frames, trellis blocks, C4FM deviation. */
+object P25TestSignal {
+
+ fun dibitsOf(v: Long, count: Int) = IntArray(count) { i -> (v ushr (2 * (count - 1 - i)) and 3L).toInt() }
+
+ /** Frame sync 0x5575F5FF77FF as dibits. */
+ val SYNC = dibitsOf(0x5575F5FF77FFL, 24)
+
+ /** C4FM deviation per dibit: 01 → +1800 Hz, 00 → +600, 10 → -600, 11 → -1800. */
+ fun hz(d: Int) = when (d) { 1 -> 1800.0; 0 -> 600.0; 2 -> -600.0; else -> -1800.0 }
+
+ /** A block as sent: 10 bytes + inverted CRC, trellis coded, interleaved. */
+ fun block(data: ByteArray): IntArray {
+ val crc = P25Frame.remainder(data + byteArrayOf(0, 0)) xor 0xffff
+ val bytes = data + byteArrayOf((crc shr 8).toByte(), crc.toByte())
+ val inputs = IntArray(49) { i -> if (i == 48) 0 else bytes[i / 4].toInt() shr (6 - 2 * (i % 4)) and 3 }
+ var state = 0
+ val sym = IntArray(49) { i -> P25Frame.NEXT[state][inputs[i]].also { state = inputs[i] } }
+ val out = IntArray(98)
+ for (k in 0 until 49) { out[P25Frame.SYMBOL_AT[k]] = sym[k] shr 2; out[P25Frame.SYMBOL_AT[k] + 1] = sym[k] and 3 }
+ return out
+ }
+
+ /** NID + blocks with status symbols put in, padded to a demodulator frame (what follows the sync). */
+ fun frame(nac: Int, duid: Int, vararg blocks: IntArray): IntArray {
+ val nid = dibitsOf(P25Frame.nidCodeword(nac shl 4 or duid) shl 1, 32)
+ val data = ArrayDeque((nid + blocks.flatMap { it.toList() }).toList())
+ return IntArray(P25Demod.FRAME_DIBITS) { i -> if ((i + 25) % 36 == 0) 2 else data.removeFirstOrNull() ?: 0 }
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt
new file mode 100644
index 0000000..82c2a35
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/P25TsbkTest.kt
@@ -0,0 +1,49 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class P25TsbkTest {
+
+ /** A block from its opcode and 64 argument bits (MFID 0). */
+ private fun tsbk(opcode: Int, args: Long, mfid: Int = 0) =
+ P25Frame.Tsbk(ByteArray(10) { i -> when (i) { 0 -> (0x80 or opcode).toByte(); 1 -> mfid.toByte(); else -> (args ushr (8 * (9 - i))).toByte() } })
+
+ @Test
+ fun groupGrant() {
+ // Options 0x40 (encrypted), channel 0x1123, talkgroup 0x0F2A, source radio 0x1B2C3D.
+ val m = P25Tsbk.parse(tsbk(0x00, 0x40_1123_0F2A_1B2C3DL))
+ assertEquals(P25Tsbk.Grant(0x1123, 0x0F2A, null, 0x1B2C3D, emergency = false, encrypted = true), m)
+ }
+
+ @Test
+ fun unitToUnitAndUpdates() {
+ assertEquals(P25Tsbk.Grant(0x1005, null, 0x000102, 0x0A0B0C, false, false),
+ P25Tsbk.parse(tsbk(0x04, 0x1005_000102_0A0B0CL)))
+ assertEquals(P25Tsbk.GrantUpdate(listOf(0x1001 to 100, 0x1002 to 200)),
+ P25Tsbk.parse(tsbk(0x02, 0x1001_0064_1002_00C8L)))
+ assertEquals(P25Tsbk.Affiliation(0x123456, 0x0300), P25Tsbk.parse(tsbk(0x28, 0x00_0000_0300_123456L)))
+ }
+
+ @Test
+ fun channelTableGivesFrequencies() {
+ // Table 1: base 851.00625 MHz (/5 Hz), spacing 6.25 kHz (/125 Hz); TDMA table 2: 2 slots a carrier.
+ val iden = P25Tsbk.parse(tsbk(0x3D, (1L shl 60) or (50L shl 32) or (851_006_250L / 5))) as P25Tsbk.Iden
+ assertEquals(P25Tsbk.Iden(1, 851_006_250L, 6_250, 1), iden)
+ val tdma = P25Tsbk.parse(tsbk(0x33, (2L shl 60) or (3L shl 56) or (100L shl 32) or (769_006_250L / 5))) as P25Tsbk.Iden
+ assertEquals(2, tdma.slots)
+ val ch = P25Tsbk.Channels().apply { learn(iden); learn(tdma) }
+ assertEquals(851_006_250L + 10 * 6_250, ch.hz(0x100A))
+ assertEquals(769_006_250L + 2 * 12_500, ch.hz(0x2005)) // channel 5 = carrier 2, slot 1
+ assertNull(ch.hz(0x3001))
+ }
+
+ @Test
+ fun siteBroadcasts() {
+ // WACN 0xBEE00, system 0x3A1, control channel 0x1040.
+ assertEquals(P25Tsbk.Site(0xBEE00, 0x3A1, null, null, 0x1040),
+ P25Tsbk.parse(tsbk(0x3B, 0x01_BEE00_3A1_1040_70L)))
+ assertNull(P25Tsbk.parse(tsbk(0x00, 0L, mfid = 0x90))) // vendor message: skipped
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt b/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt
new file mode 100644
index 0000000..18009bf
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/SweepTest.kt
@@ -0,0 +1,37 @@
+package com.rfsentinel.app.ui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class SweepTest {
+
+ @Test
+ fun fullTurnFindsTheStrongestSide() {
+ val s = Sweep()
+ // A slow turn: -80 dBm with your back to it, -66 facing east (about 90°).
+ for (h in 0 until 360 step 10) s.add(1_000L + h * 10, h.toFloat(), if (h in 90..110) -66 else -80)
+ assertEquals(105f, s.direction(5_000L)!!, 0.1f)
+ assertEquals("E", Sweep.compassPoint(105f))
+ }
+
+ @Test
+ fun noDirectionUntilTurnedOrWhenFlat() {
+ val half = Sweep()
+ for (h in 0 until 180 step 10) half.add(1_000L, h.toFloat(), if (h == 90) -60 else -80)
+ assertNull(half.direction(1_000L)) // only half a turn
+ val flat = Sweep()
+ for (h in 0 until 360 step 10) flat.add(1_000L, h.toFloat(), -70 - (h / 10) % 2)
+ assertNull(flat.direction(1_000L)) // no side stands out
+ // Old readings drop out.
+ for (h in 0 until 360 step 10) flat.add(1_000L, h.toFloat(), if (h == 90) -50 else -80)
+ assertEquals(0, flat.covered(1_000L + Sweep.WINDOW_MS + 1))
+ }
+
+ @Test
+ fun turnIsShortestWay() {
+ assertEquals(30, Sweep.turn(10f, 40f))
+ assertEquals(-20, Sweep.turn(10f, 350f))
+ assertEquals(180, Sweep.turn(0f, 180f).let { kotlin.math.abs(it) })
+ }
+}