Skip to content

RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.

RTL-SDR ADS-B receiver: police aircraft without internet

CIS-C01c7054643e73
diff --git a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt
index 3b1fad0..abc47a3 100644
--- a/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/OnlineWatch.kt
@@ -109,6 +109,44 @@ class OnlineWatch(
(best?.let { " · ${it.label}" } ?: ", none police")
}
+ /**
+ * Aircraft heard by the RTL-SDR's own ADS-B receiver (no internet): checked like the feed's,
+ * every couple of seconds. [unlocated]: addresses heard without a position, flagged only
+ * when they are in the law-enforcement registry.
+ */
+ fun localAircraft(planes: List<PoliceAircraft.Plane>, unlocated: List<String>) {
+ val now = System.currentTimeMillis()
+ if (!Prefs.categoryEnabled(context, Category.AIRCRAFT)) { PoliceAircraft.local = emptyList(); return }
+ val registry = PoliceAircraft.load(context)
+ val me = location()
+ val seen = ArrayList<PoliceAircraft.Seen>(planes.size)
+ synchronized(loiter) {
+ fun report(hit: Hit, key: String, lat: Double, lon: Double) {
+ val last = lastAircraftHit[key] ?: 0L
+ if (now - last < AIRCRAFT_REPEAT_MS) return
+ lastAircraftHit[key] = now
+ onAlert(Alert(hit, lat, lon, "air:$key"))
+ }
+ for (p in planes) {
+ val circling = loiter.update(p, now)
+ val hit = PoliceAircraft.classify(p, registry, circling,
+ me?.let { PoliceAircraft.distance(p, it.latitude, it.longitude) }, PoliceAircraft.VIA_LOCAL)
+ seen += PoliceAircraft.Seen(p, hit)
+ hit?.let { report(it, p.hex, p.lat, p.lon) }
+ }
+ // No position: logged where you are, which is where it was heard.
+ if (me != null) for (hex in unlocated) PoliceAircraft.heardNearby(hex, registry)?.let { report(it, hex, me.latitude, me.longitude) }
+ loiter.prune(now)
+ }
+ PoliceAircraft.local = seen
+ PoliceAircraft.localAt = now
+ seen.mapNotNull { it.hit }.maxByOrNull { it.confidence }?.let { best ->
+ val cur = AmbientThreats.aircraft
+ if (cur == null || now - cur.first > AIRCRAFT_MS || best.confidence >= cur.second.score)
+ AmbientThreats.aircraft = now to AmbientThreats.Threat(best.confidence, best.label, Category.AIRCRAFT)
+ }
+ }
+
private fun clock(t: Long) = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(t))
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt
index f86d6f4..96fc69a 100644
--- a/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt
+++ b/app/src/main/java/com/rfsentinel/app/online/PoliceAircraft.kt
@@ -93,13 +93,13 @@ object PoliceAircraft {
* What an aircraft is, or null when it's ordinary traffic. [circling] comes from
* [LoiterTracker]; [distanceM] is the ground distance from you.
*/
- fun classify(p: Plane, registry: Map<String, Entry>, circling: Boolean, distanceM: Double): Hit? {
+ fun classify(p: Plane, registry: Map<String, Entry>, circling: Boolean, distanceM: Double?, via: String = VIA_ONLINE): Hit? {
val where = describe(p, distanceM)
registry[p.hex]?.let { e ->
return Hit(Category.AIRCRAFT, "Police aircraft overhead: ${titleCase(e.owner)}", if (circling) 90 else 85,
"${e.registration} (${e.model.ifBlank { p.type ?: "aircraft" }}), registered to ${titleCase(e.owner)}. $where" +
if (circling) " It is circling." else "",
- "FAA / Transport Canada aircraft registry; ADS-B (adsb.fi / adsb.lol)")
+ "FAA / Transport Canada aircraft registry; $via")
}
p.owner?.takeIf { LE_OWNER.containsMatchIn(it) }?.let { owner ->
return Hit(Category.AIRCRAFT, "Police aircraft overhead: ${titleCase(owner)}", if (circling) 85 else 80,
@@ -112,7 +112,7 @@ object PoliceAircraft {
return Hit(Category.AIRCRAFT, "Aircraft circling overhead", if (low) 55 else 45,
"${p.registration ?: p.callsign ?: p.hex.uppercase()} (${p.type ?: "aircraft"}) keeps circling over the same area. $where " +
"Police and surveillance flights orbit like this, but so do news, training and survey flights - verify.",
- "ADS-B track (loiter detection)")
+ "$via track (loiter detection)")
}
if (p.military) {
return Hit(Category.AIRCRAFT, "Military / government aircraft nearby", 40,
@@ -122,9 +122,23 @@ object PoliceAircraft {
return null
}
- private fun describe(p: Plane, distanceM: Double): String =
+ /**
+ * A law-enforcement aircraft the RTL-SDR heard (its transponder answering radar, or ADS-B
+ * without a position): in radio range - tens of km - but where exactly isn't known.
+ */
+ fun heardNearby(hex: String, registry: Map<String, Entry>): Hit? = registry[hex]?.let { e ->
+ Hit(Category.AIRCRAFT, "Police aircraft in radio range: ${titleCase(e.owner)}", 60,
+ "${e.registration} (${e.model.ifBlank { "aircraft" }}), registered to ${titleCase(e.owner)}. Its transponder was " +
+ "heard by your RTL-SDR, so it is within radio range (usually under 100 km), but it sent no position.",
+ "FAA / Transport Canada aircraft registry; $VIA_LOCAL")
+ }
+
+ const val VIA_ONLINE = "ADS-B (adsb.fi / adsb.lol)"
+ const val VIA_LOCAL = "ADS-B heard by your RTL-SDR"
+
+ private fun describe(p: Plane, distanceM: Double?): String =
listOfNotNull(
- "About ${com.rfsentinel.app.util.Units.distance(distanceM)} from you",
+ distanceM?.let { "About ${com.rfsentinel.app.util.Units.distance(it)} from you" },
p.altitudeFt?.let { if (it <= 0) "on the ground" else "at ${it} ft" },
p.speedKt?.let { "${it.toInt()} kt" }
).joinToString(", ") + "."
@@ -179,10 +193,22 @@ object PoliceAircraft {
/** Every aircraft from the latest poll, for the map; empty when the source is off. */
@Volatile var latest: List<Seen> = emptyList()
@Volatile var latestAt = 0L
+ /** Every aircraft the RTL-SDR's ADS-B receiver has a position for. */
+ @Volatile var local: List<Seen> = emptyList()
+ @Volatile var localAt = 0L
+
+ /** The aircraft to draw: heard by the RTL-SDR and from the online feeds, while fresh; the RTL-SDR's are newer. */
+ fun all(now: Long = System.currentTimeMillis()): List<Seen> {
+ val mine = if (now - localAt <= 30_000L) local else emptyList()
+ val online = if (now - latestAt <= 3 * 60_000L) latest else emptyList()
+ if (mine.isEmpty()) return online
+ val heard = mine.mapTo(HashSet()) { it.plane.hex }
+ return mine + online.filter { it.plane.hex !in heard }
+ }
- /** Aircraft [hex] (ICAO address) in the latest poll while it's fresh (as the map draws it), or null. */
+ /** Aircraft [hex] (ICAO address) as the map draws it, or null. */
fun current(hex: String, now: Long = System.currentTimeMillis()): Seen? =
- if (now - latestAt > 3 * 60_000L) null else latest.firstOrNull { it.plane.hex.equals(hex, ignoreCase = true) }
+ all(now).firstOrNull { it.plane.hex.equals(hex, ignoreCase = true) }
fun feedUrls(lat: Double, lon: Double, radiusKm: Int): List<String> {
val nm = Math.round(radiusKm / 1.852).toInt().coerceIn(1, 250)
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/AdsbTracker.kt b/app/src/main/java/com/rfsentinel/app/sdr/AdsbTracker.kt
new file mode 100644
index 0000000..ff903b2
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/AdsbTracker.kt
@@ -0,0 +1,80 @@
+package com.rfsentinel.app.sdr
+
+import com.rfsentinel.app.online.PoliceAircraft
+import com.rfsentinel.app.service.DeviceRegistry
+
+/**
+ * Aircraft heard by the RTL-SDR's own ADS-B receiver ([ModeS]), put together from their
+ * messages: call sign, altitude, speed and track, and position from CPR (an even and an odd
+ * frame together, then each new frame against the last position). Positions more than
+ * [MAX_RANGE_M] away are dropped as decoding errors.
+ */
+class AdsbTracker {
+
+ private class Plane(val icao: Int) {
+ var lastSeen = 0L
+ var messages = 0
+ var signal = 0
+ var callsign: String? = null
+ var altitudeFt: Int? = null
+ var speedKt: Double? = null
+ var trackDeg: Double? = null
+ var even: Cpr? = null; var odd: Cpr? = null
+ var lat = 0.0; var lon = 0.0; var positionAt = 0L
+ }
+
+ private class Cpr(val lat: Int, val lon: Int, val at: Long)
+
+ private val planes = HashMap<Int, Plane>()
+
+ /** Adds one message heard at [now]; [refLat] / [refLon]: where you are, when known. */
+ fun add(f: ModeS.Frame, now: Long, refLat: Double?, refLon: Double?) {
+ val info = ModeS.decode(f)
+ val p = planes.getOrPut(info.icao) { Plane(info.icao) }
+ p.lastSeen = now; p.messages++; p.signal = f.signal
+ info.callsign?.let { p.callsign = it }
+ info.altitudeFt?.let { p.altitudeFt = it }
+ info.speedKt?.let { p.speedKt = it }
+ info.trackDeg?.let { p.trackDeg = it }
+ val odd = info.cprOdd ?: return
+ val cpr = Cpr(info.cprLat, info.cprLon, now)
+ if (odd) p.odd = cpr else p.even = cpr
+ val e = p.even; val o = p.odd
+ var pos: Pair<Double, Double>? = null
+ if (e != null && o != null && kotlin.math.abs(e.at - o.at) <= PAIR_MS)
+ pos = ModeS.globalPosition(e.lat, e.lon, o.lat, o.lon, oddNewer = odd)
+ // One frame alone decodes against the aircraft's own position from moments ago (a reference
+ // that can't be in the wrong zone), never against yours: a far aircraft would land near you.
+ if (pos == null && p.positionAt > 0 && now - p.positionAt <= PAIR_MS)
+ pos = ModeS.localPosition(info.cprLat, info.cprLon, odd, p.lat, p.lon)
+ if (pos == null) return
+ if (refLat != null && refLon != null && DeviceRegistry.metersBetween(refLat, refLon, pos.first, pos.second) > MAX_RANGE_M) return
+ p.lat = pos.first; p.lon = pos.second; p.positionAt = now
+ }
+
+ /** Aircraft with a recent position, as the police-aircraft check takes them. */
+ fun located(now: Long): List<PoliceAircraft.Plane> = planes.values
+ .filter { now - it.lastSeen <= STALE_MS && it.positionAt > 0 && now - it.positionAt <= STALE_MS }
+ .map { p ->
+ PoliceAircraft.Plane(hex = "%06x".format(p.icao), callsign = p.callsign, registration = null, type = null,
+ owner = null, lat = p.lat, lon = p.lon, altitudeFt = p.altitudeFt, speedKt = p.speedKt,
+ trackDeg = p.trackDeg, military = false)
+ }
+
+ /** Addresses heard recently without a position (Mode S replies, or ADS-B without GPS). */
+ fun unlocated(now: Long): List<String> = planes.values
+ .filter { now - it.lastSeen <= STALE_MS && (it.positionAt == 0L || now - it.positionAt > STALE_MS) }
+ .map { "%06x".format(it.icao) }
+
+ val count get() = planes.size
+
+ fun prune(now: Long) { planes.values.removeAll { now - it.lastSeen > STALE_MS } }
+
+ companion object {
+ /** Even and odd frames this close together decode globally. */
+ const val PAIR_MS = 10_000L
+ const val STALE_MS = 60_000L
+ /** Further than a 1090 MHz receiver on a phone can hear: a bad decode. */
+ const val MAX_RANGE_M = 450_000.0
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/ModeS.kt b/app/src/main/java/com/rfsentinel/app/sdr/ModeS.kt
new file mode 100644
index 0000000..170a2fd
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/ModeS.kt
@@ -0,0 +1,295 @@
+package com.rfsentinel.app.sdr
+
+import kotlin.math.abs
+import kotlin.math.acos
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.floor
+import kotlin.math.hypot
+import kotlin.math.sqrt
+
+/**
+ * Mode S / ADS-B on 1090 MHz from an RTL-SDR at 2 MS/s (one sample per half microsecond),
+ * written from the published format (ICAO Annex 10 vol. IV, "The 1090 MHz Riddle") with
+ * SkyPulse and dump1090 as references for the preamble test. Pure Kotlin, unit-tested.
+ *
+ * - [Demod] finds messages in raw 8-bit I/Q: the 8 µs preamble, then 56 or 112 bits of pulse
+ * position (a 1 is high then low). Messages that fail the CRC are dropped, a single wrong bit
+ * in an extended squitter is corrected.
+ * - [decode] reads what's useful here: the aircraft address (DF11 all-call replies, DF17/18
+ * extended squitters), its call sign, barometric altitude, position (CPR) and ground speed.
+ */
+object ModeS {
+
+ const val SAMPLE_RATE = 2_000_000
+ const val FREQ_HZ = 1_090_000_000L
+ /** Samples of preamble (8 µs) and of a long message (112 bits × 2). */
+ private const val PREAMBLE = 16
+ private const val LONG_SAMPLES = 224
+ /** Samples a buffer must keep from the previous read so a message across two reads is found. */
+ const val OVERLAP = PREAMBLE + LONG_SAMPLES
+
+ /** Message magnitude per I/Q byte pair: |(i - 127.5, q - 127.5)|, scaled to 0..~360. */
+ private val MAG = IntArray(256 * 256).also { t ->
+ for (i in 0 until 256) for (q in 0 until 256) {
+ val di = i - 127.5; val dq = q - 127.5
+ t[(i shl 8) or q] = (sqrt(di * di + dq * dq) * 2).toInt()
+ }
+ }
+
+ /** Magnitudes of [samples] I/Q pairs from [iq] into [out] at [at]. */
+ fun magnitudes(iq: ByteArray, samples: Int, out: IntArray, at: Int) {
+ for (s in 0 until samples) out[at + s] = MAG[((iq[2 * s].toInt() and 0xff) shl 8) or (iq[2 * s + 1].toInt() and 0xff)]
+ }
+
+ // ---- CRC ------------------------------------------------------------------------------
+
+ private const val POLY = 0xFFF409
+
+ /** Mode S parity (CRC-24) of the first [bits] - 24 bits of [msg]. */
+ fun parity(msg: ByteArray, bits: Int): Int {
+ var crc = 0
+ for (i in 0 until (bits - 24) / 8) {
+ crc = crc xor ((msg[i].toInt() and 0xff) shl 16)
+ repeat(8) { crc = if (crc and 0x800000 != 0) ((crc shl 1) xor POLY) and 0xffffff else (crc shl 1) and 0xffffff }
+ }
+ return crc
+ }
+
+ /** The parity field's syndrome: 0 for an intact DF17/18/11 (IID 0) message, the aircraft address for DF4/5/20/21. */
+ fun syndrome(msg: ByteArray, bits: Int): Int {
+ val n = bits / 8
+ val p = ((msg[n - 3].toInt() and 0xff) shl 16) or ((msg[n - 2].toInt() and 0xff) shl 8) or (msg[n - 1].toInt() and 0xff)
+ return parity(msg, bits) xor p
+ }
+
+ /** Syndrome of a single flipped bit in a 112-bit message: lets one bad bit be found and fixed. */
+ private val ONE_BIT: Map<Int, Int> by lazy {
+ val m = HashMap<Int, Int>()
+ for (bit in 0 until 112) {
+ val b = ByteArray(14); b[bit / 8] = (0x80 ushr (bit % 8)).toByte()
+ m[syndrome(b, 112)] = bit
+ }
+ m
+ }
+
+ /** Length in bits of a message with downlink format [df]. */
+ fun lengthOf(df: Int) = if (df >= 16) 112 else 56
+
+ // ---- Demodulator -----------------------------------------------------------------------
+
+ /** A message that passed its CRC: the raw bytes, its address and the signal it came in at (0..~360). */
+ class Frame(val bytes: ByteArray, val icao: Int, val signal: Int) {
+ val df get() = (bytes[0].toInt() and 0xff) ushr 3
+ }
+
+ /**
+ * Finds messages in a stream of magnitudes. Feed it buffers whose first [OVERLAP] samples
+ * repeat the end of the previous buffer.
+ */
+ class Demod {
+ var preambles = 0L; private set
+ var good = 0L; private set
+ var fixed = 0L; private set
+
+ /** Messages in [mag] from 0 until [count] - [OVERLAP] (later starts are in the next buffer). */
+ fun scan(mag: IntArray, count: Int, out: MutableList<Frame>) {
+ var j = 0
+ val last = count - OVERLAP
+ val msg = ByteArray(14)
+ while (j < last) {
+ if (!preamble(mag, j)) { j++; continue }
+ preambles++
+ val frame = bits(mag, j + PREAMBLE, msg)
+ if (frame == null) { j++; continue }
+ good++
+ out += frame
+ j += PREAMBLE + 2 * lengthOf(frame.df)
+ }
+ }
+
+ /** Pulses at 0, 1, 3.5 and 4.5 µs and quiet in between and after (sample units: 0, 2, 7, 9). */
+ private fun preamble(m: IntArray, j: Int): Boolean {
+ val m0 = m[j]; val m1 = m[j + 1]; val m2 = m[j + 2]; val m3 = m[j + 3]
+ val m7 = m[j + 7]; val m8 = m[j + 8]; val m9 = m[j + 9]
+ if (!(m0 > m1 && m1 < m2 && m2 > m3 && m3 < m0 && m[j + 4] < m0 && m[j + 5] < m0 && m[j + 6] < m0 &&
+ m7 > m8 && m8 < m9 && m9 > m[j + 6])) return false
+ val high = (m0 + m2 + m7 + m9) / 6
+ if (m[j + 4] >= high || m[j + 5] >= high) return false
+ for (k in 11..14) if (m[j + k] >= high) return false
+ return true
+ }
+
+ private fun bits(m: IntArray, from: Int, msg: ByteArray): Frame? {
+ java.util.Arrays.fill(msg, 0)
+ var prev = 0; var weak = 0; var sum = 0L
+ for (i in 0 until 112) {
+ val a = m[from + 2 * i]; val b = m[from + 2 * i + 1]
+ val bit = when {
+ a > b -> 1
+ a < b -> 0
+ else -> { weak++; prev }
+ }
+ if (abs(a - b) < 4) weak++
+ if (bit == 1) msg[i / 8] = (msg[i / 8].toInt() or (0x80 ushr (i % 8))).toByte()
+ prev = bit
+ sum += maxOf(a, b)
+ // Short messages are judged on their first 56 bits only.
+ if (i == 55 && ((msg[0].toInt() and 0xff) ushr 3) < 16) break
+ }
+ val df = (msg[0].toInt() and 0xff) ushr 3
+ val len = lengthOf(df)
+ if (weak > len / 8) return null
+ return accept(msg, len, (sum / (len)).toInt())
+ }
+
+ private fun accept(msg: ByteArray, len: Int, signal: Int): Frame? {
+ val df = (msg[0].toInt() and 0xff) ushr 3
+ val s = syndrome(msg, len)
+ val icao = icaoOf(msg)
+ return when (df) {
+ 17, 18 -> when {
+ s == 0 -> Frame(msg.copyOf(14), icao, signal)
+ else -> ONE_BIT[s]?.takeIf { it >= 5 }?.let { bit ->
+ val c = msg.copyOf(14)
+ c[bit / 8] = (c[bit / 8].toInt() xor (0x80 ushr (bit % 8))).toByte()
+ fixed++
+ Frame(c, icaoOf(c), signal)
+ }
+ }
+ // All-call reply: parity is the interrogator code (II / SI) in the low 7 bits.
+ 11 -> if (s and 0xffff80 == 0) Frame(msg.copyOf(7), icao, signal) else null
+ else -> null
+ }
+ }
+ }
+
+ private fun icaoOf(msg: ByteArray) =
+ ((msg[1].toInt() and 0xff) shl 16) or ((msg[2].toInt() and 0xff) shl 8) or (msg[3].toInt() and 0xff)
+
+ // ---- Decoding --------------------------------------------------------------------------
+
+ /** What one message said about an aircraft. CPR fields are raw 17-bit values. */
+ data class Info(
+ val icao: Int,
+ val callsign: String? = null,
+ val altitudeFt: Int? = null,
+ val cprOdd: Boolean? = null,
+ val cprLat: Int = 0,
+ val cprLon: Int = 0,
+ val speedKt: Double? = null,
+ val trackDeg: Double? = null,
+ val onGround: Boolean = false
+ ) {
+ val hasCpr get() = cprOdd != null
+ }
+
+ private const val CHARS = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ##### ###############0123456789######"
+
+ /** Reads [f]; DF11 gives the address only. */
+ fun decode(f: Frame): Info {
+ if (f.df != 17 && f.df != 18) return Info(f.icao)
+ val me = f.bytes.copyOfRange(4, 11)
+ fun bitsAt(from: Int, n: Int): Int { // 1-based ME bit positions, as the specs number them
+ var v = 0
+ for (k in 0 until n) {
+ val i = from - 1 + k
+ v = (v shl 1) or (((me[i / 8].toInt() and 0xff) ushr (7 - i % 8)) and 1)
+ }
+ return v
+ }
+ val tc = bitsAt(1, 5)
+ return when (tc) {
+ in 1..4 -> {
+ val sb = StringBuilder()
+ for (k in 0 until 8) sb.append(CHARS[bitsAt(9 + 6 * k, 6)])
+ Info(f.icao, callsign = sb.toString().replace("#", "").trim().ifEmpty { null })
+ }
+ in 5..8 -> Info(f.icao, onGround = true, altitudeFt = 0)
+ in 9..18 -> Info(f.icao, altitudeFt = altitude(bitsAt(9, 12)), cprOdd = bitsAt(22, 1) == 1,
+ cprLat = bitsAt(23, 17), cprLon = bitsAt(40, 17))
+ in 20..22 -> Info(f.icao, cprOdd = bitsAt(22, 1) == 1, cprLat = bitsAt(23, 17), cprLon = bitsAt(40, 17))
+ 19 -> velocity(f.icao, bitsAt(6, 3), ::bitsAt)
+ else -> Info(f.icao)
+ }
+ }
+
+ /** 12-bit altitude field with the Q bit set: 25 ft steps from -1000 ft. Gillham (Q = 0) is left out. */
+ internal fun altitude(a: Int): Int? {
+ if (a == 0 || a and 0x10 == 0) return null
+ val n = ((a and 0xfe0) ushr 1) or (a and 0x0f)
+ return n * 25 - 1000
+ }
+
+ private fun velocity(icao: Int, sub: Int, bitsAt: (Int, Int) -> Int): Info = when (sub) {
+ 1, 2 -> {
+ val scale = if (sub == 2) 4 else 1
+ val ew = bitsAt(15, 10); val ns = bitsAt(26, 10)
+ if (ew == 0 || ns == 0) Info(icao)
+ else {
+ val vx = (ew - 1) * scale * (if (bitsAt(14, 1) == 1) -1 else 1)
+ val vy = (ns - 1) * scale * (if (bitsAt(25, 1) == 1) -1 else 1)
+ Info(icao, speedKt = hypot(vx.toDouble(), vy.toDouble()),
+ trackDeg = (Math.toDegrees(atan2(vx.toDouble(), vy.toDouble())) + 360) % 360)
+ }
+ }
+ 3, 4 -> {
+ val heading = if (bitsAt(14, 1) == 1) bitsAt(15, 10) * 360.0 / 1024 else null
+ val air = bitsAt(26, 10).takeIf { it != 0 }?.let { (it - 1) * (if (sub == 4) 4 else 1).toDouble() }
+ Info(icao, speedKt = air, trackDeg = heading)
+ }
+ else -> Info(icao)
+ }
+
+ // ---- CPR position ----------------------------------------------------------------------
+
+ private const val CPR_MAX = 131072.0
+
+ /** Number of longitude zones at [lat] (NZ = 15). */
+ internal fun nl(lat: Double): Int {
+ val a = abs(lat)
+ if (a < 1e-9) return 59
+ if (abs(a - 87) < 1e-9) return 2
+ if (a > 87) return 1
+ val t = 1 - (1 - cos(Math.PI / 30)) / (cos(Math.PI / 180 * a).let { it * it })
+ return floor(2 * Math.PI / acos(t)).toInt()
+ }
+
+ private fun mod(a: Double, b: Double) = ((a % b) + b) % b
+
+ /**
+ * Global decode from an even and an odd airborne frame (at most 10 s apart); [oddNewer]
+ * picks the newer one's latitude. Null when they straddle a longitude-zone boundary.
+ */
+ fun globalPosition(evenLat: Int, evenLon: Int, oddLat: Int, oddLon: Int, oddNewer: Boolean): Pair<Double, Double>? {
+ val le = evenLat / CPR_MAX; val lo = oddLat / CPR_MAX
+ val j = floor(59 * le - 60 * lo + 0.5)
+ var latE = 360.0 / 60 * (mod(j, 60.0) + le)
+ var latO = 360.0 / 59 * (mod(j, 59.0) + lo)
+ if (latE >= 270) latE -= 360
+ if (latO >= 270) latO -= 360
+ if (nl(latE) != nl(latO)) return null
+ val lat = if (oddNewer) latO else latE
+ val nlLat = nl(lat)
+ val ni = maxOf(nlLat - (if (oddNewer) 1 else 0), 1)
+ val m = floor(evenLon / CPR_MAX * (nlLat - 1) - oddLon / CPR_MAX * nlLat + 0.5)
+ var lon = 360.0 / ni * (mod(m, ni.toDouble()) + (if (oddNewer) oddLon else evenLon) / CPR_MAX)
+ if (lon >= 180) lon -= 360
+ return lat to lon
+ }
+
+ /** Local decode of one airborne frame against a reference within ~300 km (the receiver). */
+ fun localPosition(cprLat: Int, cprLon: Int, odd: Boolean, refLat: Double, refLon: Double): Pair<Double, Double> {
+ val i = if (odd) 1 else 0
+ val dLat = 360.0 / (60 - i)
+ val la = cprLat / CPR_MAX
+ val j = floor(refLat / dLat) + floor(0.5 + mod(refLat, dLat) / dLat - la)
+ val lat = dLat * (j + la)
+ val dLon = 360.0 / maxOf(nl(lat) - i, 1)
+ val lo = cprLon / CPR_MAX
+ val m = floor(refLon / dLon) + floor(0.5 + mod(refLon, dLon) / dLon - lo)
+ var lon = dLon * (m + lo)
+ if (lon >= 180) lon -= 360
+ return lat to lon
+ }
+}
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 d13c5d7..1b3ad1b 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -15,6 +15,9 @@ import com.rfsentinel.app.usb.UsbWifi
* detector ([RadioWatch]): it sweeps the public-safety bands and reports strong
* transmissions nearby. Only signal strength per channel is measured. Its log goes into
* the USB adapter log (Settings → Export USB WiFi adapter log).
+ *
+ * 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.
*/
object SdrRadio {
@@ -25,6 +28,8 @@ object SdrRadio {
private const val READS_PER_CHUNK = 8 // ~32 ms of samples per tuned chunk
private const val SETTLE_READS = 2 // samples after a retune are discarded
private const val STALL_CHUNKS = 8 // chunks in a row without samples before the stream is restarted
+ private const val ADSB_GAIN_TENTHS_DB = 496 // the tuner's most: aircraft are far and faint
+ private const val ADSB_PUSH_MS = 2_000L
@Volatile var status: String = ""; private set
/** What to watch (Settings > RTL-SDR radio); picked up at the next sweep. */
@@ -33,6 +38,12 @@ object SdrRadio {
private var onEvent: ((RadioWatch.Event) -> Unit)? = null
@Volatile private var runningDevice: String? = null
@Volatile private var stop = false
+ /** Receive ADS-B on 1090 MHz instead of sweeping the radio bands; switches at the next sweep. */
+ @Volatile var adsb = false
+ /** Where you are (latitude, longitude), to drop impossible aircraft positions. */
+ @Volatile var location: (() -> Pair<Double, Double>?)? = null
+ /** Aircraft with a position, and addresses heard without one, every couple of seconds in ADS-B mode. */
+ @Volatile var onAircraft: ((List<com.rfsentinel.app.online.PoliceAircraft.Plane>, List<String>) -> Unit)? = null
fun isSdr(d: UsbDevice) = RtlSdr.isRtlSdr(d.vendorId, d.productId)
@@ -108,6 +119,73 @@ object SdrRadio {
private fun run(sdr: RtlSdr, d: UsbDevice) {
UsbWifi.log("=== RTL-SDR radio activity watch (%04x:%04x) ===".format(d.vendorId, d.productId))
if (!sdr.open()) { status = "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"; return }
+ while (!stop && !sdr.lost) if (adsb) runAdsb(sdr) else runSweep(sdr)
+ if (sdr.lost) UsbWifi.log("RTL-SDR: the dongle stopped answering (unplugged?)")
+ sdr.close()
+ }
+
+ private fun runAdsb(sdr: RtlSdr) {
+ sdr.setSampleRate(ModeS.SAMPLE_RATE)
+ sdr.setGain(ADSB_GAIN_TENTHS_DB)
+ if (!sdr.tune(ModeS.FREQ_HZ)) {
+ UsbWifi.log("RTL-SDR: the tuner didn't lock on 1090 MHz")
+ status = "RTL-SDR · ADS-B: the tuner didn't lock on 1090 MHz"
+ var waited = 0
+ while (!stop && adsb && waited < 50) { Thread.sleep(100); waited++ }
+ return
+ }
+ sdr.resetBuffer()
+ UsbWifi.log("RTL-SDR: ADS-B receiver on 1090 MHz, ${sdr.sampleRate} S/s, gain ${ADSB_GAIN_TENTHS_DB / 10.0} dB")
+ status = "RTL-SDR · ADS-B · listening on 1090 MHz…"
+ // 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)
+ val mag = IntArray(xfer / 2 + 2 * ModeS.OVERLAP)
+ var have = 0
+ val demod = ModeS.Demod()
+ val tracker = AdsbTracker()
+ val frames = ArrayList<ModeS.Frame>()
+ var lastPush = 0L; var lastLog = System.currentTimeMillis(); var fails = 0; var messages = 0L; var logged = 0L
+ while (!stop && !sdr.lost && adsb) {
+ val n = sdr.read(buf)
+ if (n <= 0) {
+ if (++fails % STALL_CHUNKS == 0) {
+ if (fails <= STALL_CHUNKS * 3) UsbWifi.log("RTL-SDR: no samples for $fails reads in a row - restarting the stream")
+ sdr.resetBuffer()
+ }
+ continue
+ }
+ fails = 0
+ ModeS.magnitudes(buf, n / 2, mag, have)
+ val total = have + n / 2
+ if (total < 2 * ModeS.OVERLAP) { have = total; continue }
+ frames.clear()
+ demod.scan(mag, total, frames)
+ val now = System.currentTimeMillis()
+ val me = location?.invoke()
+ for (f in frames) tracker.add(f, now, me?.first, me?.second)
+ messages += frames.size
+ System.arraycopy(mag, total - ModeS.OVERLAP, mag, 0, ModeS.OVERLAP)
+ have = ModeS.OVERLAP
+ if (now - lastPush >= ADSB_PUSH_MS) {
+ lastPush = now
+ tracker.prune(now)
+ val located = tracker.located(now)
+ val unlocated = tracker.unlocated(now)
+ onAircraft?.invoke(located, unlocated)
+ status = "RTL-SDR · ADS-B · ${located.size + unlocated.size} aircraft heard, ${located.size} with a position"
+ }
+ if (now - lastLog >= 60_000) {
+ UsbWifi.log("RTL-SDR: ADS-B ${messages - logged} messages in ${(now - lastLog) / 1000} s, " +
+ "${demod.preambles} preambles, ${demod.fixed} fixed, ${tracker.count} aircraft, USB errors ${sdr.ctlErrors}")
+ lastLog = now; logged = messages
+ }
+ }
+ onAircraft?.invoke(emptyList(), emptyList())
+ UsbWifi.log("RTL-SDR: ADS-B receiver stopped after $messages messages")
+ }
+
+ private fun runSweep(sdr: RtlSdr) {
sdr.setSampleRate(SAMPLE_RATE)
sdr.setGain(GAIN_TENTHS_DB)
sdr.resetBuffer()
@@ -124,11 +202,11 @@ object SdrRadio {
val iq = ByteArray(XFER * READS_PER_CHUNK)
var lastLog = 0L; var sweepStart = System.currentTimeMillis(); var sweepMs = 0L
var events = 0; var unlocked = 0; var readErrors = 0; var failedChunks = 0
- while (!stop && !sdr.lost) {
+ while (!stop && !sdr.lost && !adsb) {
// 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 (stop || sdr.lost) break
+ if (stop || sdr.lost || adsb) break
if (!sdr.tune(center)) { unlocked++; continue }
repeat(SETTLE_READS) { sdr.read(buf) }
var got = 0
@@ -166,8 +244,6 @@ object SdrRadio {
"$events reported, PLL unlocked $unlocked, read errors $readErrors, tuner write failures ${sdr.tunerWriteFails}, USB errors ${sdr.ctlErrors}")
}
}
- if (sdr.lost) UsbWifi.log("RTL-SDR: the dongle stopped answering (unplugged?)")
- sdr.close()
- UsbWifi.log("RTL-SDR: stopped after ${watch.sweeps} sweeps")
+ UsbWifi.log("RTL-SDR: radio sweep stopped after ${watch.sweeps} sweeps")
}
}
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 6e1b348..05b9b96 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -327,8 +327,13 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.usb.UsbWifi.start(this) { list -> pipeline.post { list.forEach(::processUsbWifi) } }
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).
- if (Prefs.categoryEnabled(this, Category.RADIO)) {
+ // 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
+ 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)) {
// 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)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
index b5671d2..6972185 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/RfMap.kt
@@ -282,8 +282,7 @@ internal class RfMap(private val activity: AppCompatActivity, val map: MapEngine
GeoJson.feature(GeoJson.line(listOf(r.operatorLatitude!! to r.operatorLongitude!!, r.latitude!! to r.longitude!!)))
})
- val fresh = System.currentTimeMillis() - PoliceAircraft.latestAt <= 3 * 60_000L
- val air = if (fresh) PoliceAircraft.latest else emptyList()
+ val air = PoliceAircraft.all()
planes = air.associateBy { it.plane.hex }
set(AIRCRAFT, air.map { (p, hit) ->
GeoJson.feature(GeoJson.point(p.lat, p.lon),
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 9be5425..3eb4b0d 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -482,6 +482,9 @@ object Prefs {
/** A hit matches a named frequency within ± this many kHz. */
fun radioMatchKhz(context: Context): Int = int(context, "radio_match_khz", 7).coerceIn(1, 50)
fun setRadioMatchKhz(context: Context, v: Int) = setInt(context, "radio_match_khz", v.coerceIn(1, 50))
+ /** 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)
+
/** 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)
fun setRadioReferenceOn(context: Context, v: Boolean) = setBool(context, "radio_reference_on", v)
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/ModeSTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/ModeSTest.kt
new file mode 100644
index 0000000..f909b37
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/ModeSTest.kt
@@ -0,0 +1,110 @@
+package com.rfsentinel.app.sdr
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Example messages from "The 1090 MHz Riddle" (Junzi Sun), with its worked answers. */
+class ModeSTest {
+
+ private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
+
+ private fun frame(s: String): ModeS.Frame {
+ val b = hex(s)
+ assertEquals("CRC", 0, ModeS.syndrome(b, b.size * 8))
+ return ModeS.Frame(b, ((b[1].toInt() and 0xff) shl 16) or ((b[2].toInt() and 0xff) shl 8) or (b[3].toInt() and 0xff), 100)
+ }
+
+ @Test
+ fun identification() {
+ val i = ModeS.decode(frame("8D4840D6202CC371C32CE0576098"))
+ assertEquals(0x4840D6, i.icao)
+ assertEquals("KLM1023", i.callsign)
+ }
+
+ @Test
+ fun airbornePositionGlobalAndLocal() {
+ val even = ModeS.decode(frame("8D40621D58C382D690C8AC2863A7"))
+ val odd = ModeS.decode(frame("8D40621D58C386435CC412692AD6"))
+ assertEquals(false, even.cprOdd); assertEquals(true, odd.cprOdd)
+ assertEquals(38000, even.altitudeFt)
+ val (lat, lon) = ModeS.globalPosition(even.cprLat, even.cprLon, odd.cprLat, odd.cprLon, oddNewer = false)!!
+ assertEquals(52.2572, lat, 0.0001); assertEquals(3.91937, lon, 0.0001)
+ val (la, lo) = ModeS.localPosition(even.cprLat, even.cprLon, false, 52.258, 3.918)
+ assertEquals(52.2572, la, 0.0001); assertEquals(3.9194, lo, 0.0001)
+ }
+
+ @Test
+ fun groundSpeedAndAirspeed() {
+ val v = ModeS.decode(frame("8D485020994409940838175B284F"))
+ assertEquals(159.2, v.speedKt!!, 0.1); assertEquals(182.88, v.trackDeg!!, 0.01)
+ val a = ModeS.decode(frame("8DA05F219B06B6AF189400CBC33F"))
+ assertEquals(375.0, a.speedKt!!, 0.1); assertEquals(243.98, a.trackDeg!!, 0.01)
+ }
+
+ @Test
+ fun longitudeZones() {
+ assertEquals(59, ModeS.nl(0.0)); assertEquals(36, ModeS.nl(52.2572)); assertEquals(1, ModeS.nl(88.0))
+ }
+
+ /** Magnitudes for a preamble and [msg] in pulse-position code, with noise-free levels. */
+ private fun signal(msg: ByteArray, lead: Int = 40): IntArray {
+ val m = IntArray(lead + ModeS.OVERLAP + 100) { 2 }
+ for (p in intArrayOf(0, 2, 7, 9)) m[lead + p] = 120
+ for (i in 0 until msg.size * 8) {
+ val one = (msg[i / 8].toInt() ushr (7 - i % 8)) and 1 == 1
+ m[lead + 16 + 2 * i + (if (one) 0 else 1)] = 120
+ }
+ return m
+ }
+
+ @Test
+ fun demodulatesAndFixesOneBadBit() {
+ val msg = hex("8D4840D6202CC371C32CE0576098")
+ val out = ArrayList<ModeS.Frame>()
+ val d = ModeS.Demod()
+ d.scan(signal(msg), signal(msg).size, out)
+ assertEquals(1, out.size)
+ assertEquals("KLM1023", ModeS.decode(out[0]).callsign)
+
+ val bad = msg.copyOf().also { it[6] = (it[6].toInt() xor 0x10).toByte() }
+ out.clear()
+ d.scan(signal(bad), signal(bad).size, out)
+ assertEquals("KLM1023", ModeS.decode(out.single()).callsign)
+ assertEquals(1L, d.fixed)
+ }
+
+ @Test
+ fun noiseIsNotAMessage() {
+ val r = java.util.Random(1)
+ val m = IntArray(200_000) { r.nextInt(60) }
+ val out = ArrayList<ModeS.Frame>()
+ ModeS.Demod().scan(m, m.size, out)
+ assertTrue(out.size <= 1)
+ }
+
+ @Test
+ fun altitudeNeedsTheQBit() {
+ assertNull(ModeS.altitude(0))
+ assertNotNull(ModeS.altitude(0x10))
+ }
+
+ @Test
+ fun trackerPutsPositionTogether() {
+ val t = AdsbTracker()
+ t.add(frame("8D40621D58C386435CC412692AD6"), 1_000, null, null)
+ assertTrue(t.located(1_000).isEmpty())
+ t.add(frame("8D40621D58C382D690C8AC2863A7"), 2_000, null, null)
+ val p = t.located(2_000).single()
+ assertEquals("40621d", p.hex)
+ assertEquals(52.2572, p.lat, 0.0001)
+ assertEquals(38000, p.altitudeFt)
+ // A decode far from you is dropped.
+ val far = AdsbTracker()
+ far.add(frame("8D40621D58C386435CC412692AD6"), 0, 10.5, -20.5)
+ far.add(frame("8D40621D58C382D690C8AC2863A7"), 500, 10.5, -20.5)
+ assertTrue(far.located(500).isEmpty())
+ }
+}