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.

TETRA handset detection on 380-385 MHz and HackRF support

CIS-C0af18da576785
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt b/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt
new file mode 100644
index 0000000..c5ea7e2
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt
@@ -0,0 +1,151 @@
+package com.rfsentinel.app.sdr
+
+import android.hardware.usb.UsbConstants
+import android.hardware.usb.UsbDevice
+import android.hardware.usb.UsbDeviceConnection
+import android.hardware.usb.UsbEndpoint
+import android.hardware.usb.UsbInterface
+
+/**
+ * Userspace driver for the HackRF One (Great Scott Gadgets) over USB, receive only: the vendor
+ * requests libhackrf sends (hackrf.c, GPL-2.0), with nothing that transmits. The transceiver is
+ * only ever switched to RECEIVE or OFF; the RF amplifier and the antenna port's bias power stay off.
+ *
+ * The HackRF delivers signed 8-bit I/Q; [read] flips the sign bit so the samples match the
+ * RTL-SDR's unsigned format and the same spectrum and ADS-B code reads both.
+ */
+class HackRf(private val conn: UsbDeviceConnection, private val device: UsbDevice, private val log: (String) -> Unit) : SdrDevice {
+
+ override val label = "HackRF"
+ override var sampleRate = 0; private set
+ override var ctlErrors = 0; private set
+ @Volatile override var lost = false; private set
+ override var tunerWriteFails = 0; private set
+ /** The HackRF keeps streaming through a retune: about 48 KB still holds the old frequency. */
+ override val settleReads = 3
+
+ private var intf: UsbInterface? = null
+ private var rx: UsbEndpoint? = null
+ private var ctlFailRun = 0
+ private var centerHz = 0L
+
+ override fun open(): Boolean {
+ val i = (0 until device.interfaceCount).map { device.getInterface(it) }.firstOrNull { f ->
+ (0 until f.endpointCount).any { f.getEndpoint(it).let { e -> e.type == UsbConstants.USB_ENDPOINT_XFER_BULK && e.direction == UsbConstants.USB_DIR_IN } }
+ } ?: run { log("HackRF: no bulk IN endpoint"); return false }
+ if (!conn.claimInterface(i, true)) { log("HackRF: couldn't claim the USB interface"); return false }
+ intf = i
+ rx = (0 until i.endpointCount).map { i.getEndpoint(it) }
+ .first { it.type == UsbConstants.USB_ENDPOINT_XFER_BULK && it.direction == UsbConstants.USB_DIR_IN }
+ val id = ByteArray(1)
+ val board = if (ctlIn(BOARD_ID_READ, 0, 0, id) == 1) id[0].toInt() and 0xff else -1
+ val ver = ByteArray(64).let { b -> val n = ctlIn(VERSION_STRING_READ, 0, 0, b); if (n > 0) String(b, 0, n, Charsets.US_ASCII) else "?" }
+ log("HackRF: board ${BOARDS[board] ?: "id $board"}, firmware $ver")
+ if (board < 0) return false
+ setTransceiver(MODE_OFF)
+ ctlOut(AMP_ENABLE, 0, 0) // RF amplifier off: protects the front end from strong signals nearby
+ ctlOut(ANTENNA_ENABLE, 0, 0) // no bias power on the antenna port
+ setSampleRate(2_048_000)
+ setGain(297)
+ tune(100_000_000L)
+ setTransceiver(MODE_RECEIVE)
+ return !lost
+ }
+
+ override fun close() {
+ if (lost) return
+ setTransceiver(MODE_OFF)
+ intf?.let { runCatching { conn.releaseInterface(it) } }
+ }
+
+ /** Sample rate in Hz (2 - 20 MS/s), with the baseband filter set to the narrowest that passes it. */
+ override fun setSampleRate(rate: Int) {
+ val r = rate.coerceIn(2_000_000, 20_000_000)
+ val p = ByteArray(8)
+ le32(p, 0, r); le32(p, 4, 1) // freq_hz, divider
+ if (ctlOutData(SAMPLE_RATE_SET, 0, 0, p) == p.size) sampleRate = r
+ val bw = FILTERS.lastOrNull { it <= r * 3 / 4 } ?: FILTERS.first()
+ ctlOut(BASEBAND_FILTER_BANDWIDTH_SET, bw and 0xffff, bw ushr 16)
+ }
+
+ override fun tune(hz: Long): Boolean {
+ if (hz !in MIN_HZ..MAX_HZ) return false
+ val p = ByteArray(8)
+ le32(p, 0, (hz / 1_000_000).toInt()); le32(p, 4, (hz % 1_000_000).toInt())
+ val ok = ctlOutData(SET_FREQ, 0, 0, p) == p.size
+ if (ok) centerHz = hz else tunerWriteFails++
+ return ok
+ }
+
+ /** Split over the LNA (0-40 dB, 8 dB steps) and the baseband VGA (0-62 dB, 2 dB steps). */
+ override fun setGain(tenthsDb: Int) {
+ val db = tenthsDb / 10
+ val lna = ((db - 10) / 8 * 8).coerceIn(0, 40)
+ val vga = ((db - lna) / 2 * 2).coerceIn(0, 62)
+ val r = ByteArray(1)
+ if (ctlIn(SET_LNA_GAIN, 0, lna, r) != 1 || r[0].toInt() == 0) tunerWriteFails++
+ if (ctlIn(SET_VGA_GAIN, 0, vga, r) != 1 || r[0].toInt() == 0) tunerWriteFails++
+ }
+
+ override fun resetBuffer() {
+ setTransceiver(MODE_OFF)
+ setTransceiver(MODE_RECEIVE)
+ }
+
+ override fun read(buf: ByteArray, len: Int): Int {
+ val n = conn.bulkTransfer(rx ?: return -1, buf, len, 1000)
+ for (k in 0 until n) buf[k] = (buf[k].toInt() xor 0x80).toByte()
+ return n
+ }
+
+ private fun setTransceiver(mode: Int) { ctlOut(SET_TRANSCEIVER_MODE, mode, 0) }
+
+ /** Counts failed control transfers; a long unbroken run of them means the HackRF is gone. */
+ private fun ctl(result: Int): Int {
+ if (result < 0) { ctlErrors++; if (++ctlFailRun >= LOST_AFTER_FAILS) lost = true } else ctlFailRun = 0
+ return result
+ }
+ private fun ctlOut(req: Int, value: Int, index: Int) = ctl(conn.controlTransfer(OUT, req, value, index, null, 0, TIMEOUT))
+ private fun ctlOutData(req: Int, value: Int, index: Int, data: ByteArray) =
+ ctl(conn.controlTransfer(OUT, req, value, index, data, data.size, TIMEOUT))
+ private fun ctlIn(req: Int, value: Int, index: Int, data: ByteArray) =
+ ctl(conn.controlTransfer(IN, req, value, index, data, data.size, TIMEOUT))
+
+ private fun le32(b: ByteArray, at: Int, v: Int) {
+ b[at] = v.toByte(); b[at + 1] = (v shr 8).toByte(); b[at + 2] = (v shr 16).toByte(); b[at + 3] = (v shr 24).toByte()
+ }
+
+ companion object {
+ /** HackRF One, Jawbreaker and rad1o (Great Scott Gadgets' USB vendor ID). */
+ private val IDS = setOf(0x1d50 to 0x6089, 0x1d50 to 0x604b, 0x1d50 to 0xcc15)
+ fun isHackRf(vid: Int, pid: Int) = (vid to pid) in IDS
+
+ const val MIN_HZ = 1_000_000L
+ const val MAX_HZ = 6_000_000_000L
+
+ // libhackrf vendor requests (hackrf_vendor_request).
+ private const val SET_TRANSCEIVER_MODE = 1
+ private const val SAMPLE_RATE_SET = 6
+ private const val BASEBAND_FILTER_BANDWIDTH_SET = 7
+ private const val BOARD_ID_READ = 14
+ private const val VERSION_STRING_READ = 15
+ private const val SET_FREQ = 16
+ private const val AMP_ENABLE = 17
+ private const val SET_LNA_GAIN = 19
+ private const val SET_VGA_GAIN = 20
+ private const val ANTENNA_ENABLE = 23
+ private const val MODE_OFF = 0
+ private const val MODE_RECEIVE = 1
+
+ private const val OUT = 0x40 // vendor, host to device
+ private const val IN = 0xC0 // vendor, device to host
+ private const val TIMEOUT = 500
+ private const val LOST_AFTER_FAILS = 6
+
+ /** MAX2837 baseband filter bandwidths (libhackrf max2837_ft). */
+ private val FILTERS = listOf(1_750_000, 2_500_000, 3_500_000, 5_000_000, 5_500_000, 6_000_000, 7_000_000, 8_000_000,
+ 9_000_000, 10_000_000, 12_000_000, 14_000_000, 15_000_000, 20_000_000, 24_000_000, 28_000_000)
+ private val BOARDS = mapOf(0 to "Jellybean", 1 to "Jawbreaker", 2 to "HackRF One", 3 to "rad1o",
+ 4 to "HackRF One r9", 5 to "HackRF Pro")
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
index 2d90f67..5f32df2 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioSettings.kt
@@ -26,7 +26,8 @@ object RadioSettings {
val off = Prefs.radioBandsOff(context)
return RadioWatch.Config(
bands = BUILT_IN.filter { it.first !in off }.map { it.second } + customBands(Prefs.radioCustomBands(context)) +
- (if (Prefs.radioCellOn(context)) RadioWatch.LTE_UPLINK_BANDS else emptyList()),
+ (if (Prefs.radioCellOn(context)) RadioWatch.LTE_UPLINK_BANDS else emptyList()) +
+ (if (Prefs.radioTetraOn(context)) listOf(RadioWatch.TETRA_BAND) else emptyList()),
excluded = ranges(Prefs.radioExcluded(context)).map { it.first },
targets = targets(Prefs.radioTargets(context)),
minSnrDb = Prefs.radioMinSnr(context)
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
index 8982459..a390167 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RadioWatch.kt
@@ -18,10 +18,15 @@ import kotlin.math.sin
* a quiet channel. The 700 / 800 MHz bands it watches are where public-safety radios
* (not towers) transmit; on the shared VHF / UHF bands businesses, schools and transit
* use the same kind of radios, so those count as weak signs unless very strong.
+ *
+ * In Europe (and much of the world) emergency services use TETRA, encrypted digital radio, with
+ * handsets transmitting on 380-385 MHz. A TETRA handset sends in time slots: a ~14 ms burst every
+ * ~57 ms frame. On that band the power is also kept in 2 ms steps ([Bursts]) and a burst rhythm
+ * marks the signal as a TETRA radio. Still energy only - TETRA can't and won't be decoded here.
*/
class RadioWatch {
- enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED, CUSTOM, TARGET, CELLULAR_UPLINK }
+ enum class Kind { PUBLIC_SAFETY_MOBILE, SHARED, CUSTOM, TARGET, CELLULAR_UPLINK, TETRA }
data class Band(val label: String, val startHz: Long, val endHz: Long, val kind: Kind)
@@ -41,9 +46,10 @@ class RadioWatch {
/**
* A strong transmission on a normally quiet channel. [repeat]: the same channel again within
* [REPEAT_MS] - not a new alert, but it keeps the live list and the closer / farther trend current.
+ * [tdma]: it came in TETRA-like time-slot bursts.
*/
data class Event(val freqHz: Long, val snrDb: Int, val band: Band, val confidence: Int,
- val target: Target? = null, val repeat: Boolean = false) {
+ val target: Target? = null, val repeat: Boolean = false, val tdma: Boolean = false) {
val mhz: String get() = "%.4f".format(java.util.Locale.US, freqHz / 1e6)
}
@@ -69,11 +75,18 @@ class RadioWatch {
fun sweepDone() { sweeps++ }
+ /**
+ * The power spectrum in short steps over one chunk ([burstSpectrum]): [psd] the average,
+ * [groups] one spectrum per [groupMs] slice of time, all FFT-shifted like [powerSpectrum].
+ */
+ class Bursts(val psd: FloatArray, val groups: Array<FloatArray>, val groupMs: Double)
+
/**
* One tuned chunk: [psdDb] is the averaged power spectrum (FFT-shifted, DC in the middle)
- * at [centerHz] and [sampleRate]. Returns the transmissions worth reporting.
+ * at [centerHz] and [sampleRate]. Returns the transmissions worth reporting. [bursts]: the
+ * same samples in time steps, for the TETRA band's time-slot check.
*/
- fun analyze(centerHz: Long, psdDb: FloatArray, sampleRate: Int, now: Long): List<Event> {
+ fun analyze(centerHz: Long, psdDb: FloatArray, sampleRate: Int, now: Long, bursts: Bursts? = null): List<Event> {
val n = psdDb.size
val binHz = sampleRate.toDouble() / n
val usableBins = (USABLE_HZ / binHz).toInt()
@@ -91,12 +104,23 @@ class RadioWatch {
val mid = n / 2 + (off / binHz).roundToInt()
var p = -200f
for (k in mid - half..mid + half) if (k in 0 until n && psdDb[k] > p) p = psdDb[k]
- val snr = (p - floor).roundToInt()
+ var snr = (p - floor).roundToInt()
+ var tdma = false
+ if (band.kind == Kind.TETRA && bursts != null && bursts.groups.isNotEmpty()) {
+ // A burst is only on part of the time: its own level, not the average, is the signal.
+ val levels = FloatArray(bursts.groups.size) { g ->
+ var q = -200f
+ for (k in mid - half..mid + half) if (k in 0 until n && bursts.groups[g][k] > q) q = bursts.groups[g][k]
+ q - floor
+ }
+ snr = maxOf(snr, levels.max().roundToInt())
+ tdma = isTdma(levels, bursts.groupMs)
+ }
val ch = channels.getOrPut(f) { Channel() }
val active = snr >= ACTIVE_DB
ch.recent = (ch.recent shl 1) or (if (active) 1L else 0L)
ch.visits++
- if (active) eventFor(f, snr, band, ch, now, cfg.minSnrDb)?.let { found += it }
+ if (active) eventFor(f, snr, band, ch, now, cfg.minSnrDb, tdma)?.let { found += it }
}
f += STEP_HZ
}
@@ -180,14 +204,17 @@ class RadioWatch {
}
/** [min]: the sensitivity setting; at the default (30 dB) the thresholds are the original ones. */
- private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long, min: Int = DEFAULT_MIN_SNR): Event? {
+ private fun eventFor(f: Long, snr: Int, band: Band, ch: Channel, now: Long, min: Int = DEFAULT_MIN_SNR,
+ tdma: Boolean = false): Event? {
if (sweeps < LEARN_SWEEPS) return null // still learning what's always there
if (ch.visits >= MIN_VISITS_BUSY && ch.busyRatio() >= BUSY_RATIO) return null // tower / control channel / pager
- val confidence = when (band.kind) {
- Kind.PUBLIC_SAFETY_MOBILE -> when { snr >= min + 10 -> 75; snr >= min -> 60; else -> return null }
+ val confidence = when {
+ band.kind == Kind.PUBLIC_SAFETY_MOBILE -> when { snr >= min + 10 -> 75; snr >= min -> 60; else -> return null }
+ // TETRA time slots on the handset band: an emergency-services radio, and a strong sign even when weaker.
+ band.kind == Kind.TETRA && tdma -> when { snr >= min + 5 -> 80; snr >= min - 5 -> 65; else -> return null }
else -> when { snr >= min + 15 -> 55; snr >= min + 5 -> 35; else -> return null }
}
- return Event(f, snr, band, confidence, repeat = now - ch.lastEvent < REPEAT_MS)
+ return Event(f, snr, band, confidence, repeat = now - ch.lastEvent < REPEAT_MS, tdma = tdma)
}
companion object {
@@ -226,6 +253,43 @@ class RadioWatch {
Band("Cellular uplink - AWS 1700 MHz (Band 4/66, partial)", 1_710_000_000L, 1_766_000_000L, Kind.CELLULAR_UPLINK)
)
+ /**
+ * The TETRA handset (uplink) band used by emergency services across Europe and beyond; the
+ * base stations send on 390-395 MHz, left out so a mast never looks like a radio.
+ */
+ val TETRA_BAND = Band("TETRA emergency-services radio band", 380_000_000L, 385_000_000L, Kind.TETRA)
+
+ /** A TETRA slot: ~14.2 ms on air in a ~56.7 ms frame. */
+ private const val SLOT_MS = 14.17
+ private const val FRAME_MS = 56.67
+ /** Time step of [burstSpectrum]: short enough to see a slot's edges. */
+ private const val GROUP_MS = 2.0
+
+ /**
+ * Time-slot bursts in one channel's level over time ([levels], dB above the noise, one per
+ * [groupMs]): on for about one TETRA slot at a time, and truly off in between - not a carrier
+ * that stays on, and not noise. Also true for 2 slots of a frame, as a data call may use.
+ */
+ fun isTdma(levels: FloatArray, groupMs: Double): Boolean {
+ if (levels.size * groupMs < FRAME_MS * 0.9) return false
+ val peak = levels.max()
+ if (peak < ACTIVE_DB + 6) return false
+ val on = BooleanArray(levels.size) { levels[it] >= peak - 10 && levels[it] >= ACTIVE_DB }
+ val quiet = levels.count { it <= 6f }
+ var run = 0; var longest = 0; var runs = 0
+ for (i in on.indices) {
+ if (on[i]) { run++; if (run == 1) runs++; longest = maxOf(longest, run) } else run = 0
+ }
+ val longestMs = longest * groupMs
+ return runs >= 1 && quiet >= levels.size / 3 &&
+ longestMs >= SLOT_MS * 0.5 && longestMs <= 2 * SLOT_MS + 2 * groupMs &&
+ on.count { it } <= levels.size * 0.6
+ }
+
+ /** Whether the tuned chunk at [centerHz] sees part of [band]. */
+ fun covers(band: Band, centerHz: Long) =
+ band.startHz <= centerHz + USABLE_HZ.toLong() && band.endHz >= centerHz - USABLE_HZ.toLong()
+
/** North American (FCC) public-safety land-mobile bands. */
val BANDS = listOf(
Band("700 MHz public-safety radio band", 799_000_000L, 805_000_000L, Kind.PUBLIC_SAFETY_MOBILE),
@@ -290,6 +354,32 @@ class RadioWatch {
}
}
+ /**
+ * [powerSpectrum], also kept in ~[GROUP_MS] steps of time ([Bursts.groups]) to see a
+ * time-slot radio's bursts.
+ */
+ fun burstSpectrum(iq: ByteArray, count: Int, sampleRate: Int, n: Int = 1024): Bursts {
+ val per = maxOf(1, (GROUP_MS / 1000 * sampleRate / n).roundToInt())
+ val acc = DoubleArray(n); val part = DoubleArray(n)
+ val re = DoubleArray(n); val im = DoubleArray(n)
+ val win = DoubleArray(n) { 0.5 - 0.5 * cos(2 * PI * it / (n - 1)) }
+ val groups = ArrayList<FloatArray>()
+ fun db(a: DoubleArray, frames: Int) = FloatArray(n) { k -> (10 * log10(a[(k + n / 2) % n] / maxOf(1, frames) + 1e-20)).toFloat() }
+ var frames = 0; var inGroup = 0
+ var s = 0
+ while (s + n <= count) {
+ for (k in 0 until n) {
+ re[k] = ((iq[2 * (s + k)].toInt() and 0xff) - 127.5) / 127.5 * win[k]
+ im[k] = ((iq[2 * (s + k) + 1].toInt() and 0xff) - 127.5) / 127.5 * win[k]
+ }
+ fft(re, im)
+ for (k in 0 until n) { val p = re[k] * re[k] + im[k] * im[k]; acc[k] += p; part[k] += p }
+ frames++; s += n
+ if (++inGroup == per) { groups += db(part, per); part.fill(0.0); inGroup = 0 }
+ }
+ return Bursts(db(acc, frames), groups.toTypedArray(), per * n * 1000.0 / sampleRate)
+ }
+
/** In-place iterative radix-2 FFT. */
private fun fft(re: DoubleArray, im: DoubleArray) {
val n = re.size
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt
index b68d937..e9ef527 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/RtlSdr.kt
@@ -16,19 +16,22 @@ import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
-class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevice, private val log: (String) -> Unit) {
+class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevice, private val log: (String) -> Unit) : SdrDevice {
+
+ override val label = "RTL-SDR"
+ override val settleReads = 2
enum class Tuner { R820T, R828D }
var tuner: Tuner? = null; private set
/** RTL-SDR Blog V4: R828D with a 28.8 MHz crystal, its own band inputs and notch filters. */
var blogV4 = false; private set
- var sampleRate = 0; private set
- var ctlErrors = 0; private set
+ override var sampleRate = 0; private set
+ override var ctlErrors = 0; private set
/** True once the dongle stops answering altogether (unplugged, or its USB link died). */
- @Volatile var lost = false; private set
+ @Volatile override var lost = false; private set
/** Tuner register writes that still failed after retrying. */
- var tunerWriteFails = 0; private set
+ override var tunerWriteFails = 0; private set
private var ctlFailRun = 0
private var centerHz = 0L
private lateinit var rx: UsbEndpoint
@@ -44,7 +47,7 @@ class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevic
private var input = -1
/** Opens the dongle: baseband, tuner detection and init. False when no supported tuner answers. */
- fun open(): Boolean {
+ override fun open(): Boolean {
val intf = device.getInterface(0)
if (!conn.claimInterface(intf, true)) log("RTL-SDR: couldn't claim the USB interface (continuing)")
rx = (0 until intf.endpointCount).map { intf.getEndpoint(it) }.firstOrNull { it.address == 0x81 }
@@ -80,7 +83,7 @@ class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevic
return ok
}
- fun close() {
+ override fun close() {
if (lost) return
runCatching {
setI2cRepeater(true); r82xxStandby(); setI2cRepeater(false)
@@ -132,7 +135,7 @@ class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevic
}
/** Sample rate in Hz (0.9 - 3.2 MS/s), with the tuner's IF filter set to match. */
- fun setSampleRate(rate: Int) {
+ override fun setSampleRate(rate: Int) {
var ratio = ((RTL_XTAL.toLong() * (1L shl 22)) / rate).toInt() and 0x0ffffffc
val real = (ratio.toLong() or ((ratio.toLong() and 0x08000000L) shl 1))
sampleRate = ((RTL_XTAL.toLong() * (1L shl 22)) / real).toInt()
@@ -148,7 +151,7 @@ class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevic
}
/** Tunes to [hz]; false when the tuner's PLL doesn't lock. */
- fun tune(hz: Long): Boolean {
+ override fun tune(hz: Long): Boolean {
setI2cRepeater(true)
val ok = r82xxSetFreq(hz)
setI2cRepeater(false)
@@ -157,17 +160,17 @@ class RtlSdr(private val conn: UsbDeviceConnection, private val device: UsbDevic
}
/** Fixed tuner gain in tenths of a dB (e.g. 297 = 29.7 dB): a steady scale for comparing channels over time. */
- fun setGain(tenthsDb: Int) {
+ override fun setGain(tenthsDb: Int) {
setI2cRepeater(true); r82xxSetGain(tenthsDb); setI2cRepeater(false)
}
- fun resetBuffer() {
+ override fun resetBuffer() {
writeReg(USBB, USB_EPA_CTL, 0x1002, 2)
writeReg(USBB, USB_EPA_CTL, 0x0000, 2)
}
/** Reads raw 8-bit I/Q samples; bytes read, or a negative value on error. */
- fun read(buf: ByteArray, len: Int = buf.size): Int = conn.bulkTransfer(rx, buf, len, 1000)
+ override fun read(buf: ByteArray, len: Int): Int = conn.bulkTransfer(rx, buf, len, 1000)
// ---- register access ----
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrDevice.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrDevice.kt
new file mode 100644
index 0000000..4b30faa
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrDevice.kt
@@ -0,0 +1,31 @@
+package com.rfsentinel.app.sdr
+
+/**
+ * A receive-only SDR on USB, as [SdrRadio] uses it: tune, fixed gain, and raw 8-bit I/Q samples
+ * (unsigned, 127.5 = zero, as the RTL2832U delivers them). [RtlSdr] and [HackRf] implement it.
+ */
+interface SdrDevice {
+ /** Short name for the status line and the log ("RTL-SDR", "HackRF"). */
+ val label: String
+ val sampleRate: Int
+ val ctlErrors: Int
+ /** The device stopped answering (unplugged). */
+ val lost: Boolean
+ val tunerWriteFails: Int
+ /** Reads to throw away after a retune, so no samples from the last frequency are measured. */
+ val settleReads: Int
+
+ /** False when this model can't be driven (an unsupported tuner, say). */
+ fun open(): Boolean
+ fun close()
+ fun setSampleRate(rate: Int)
+ /** Tunes to [hz]; false when it didn't take (PLL not locked, request failed). */
+ fun tune(hz: Long): Boolean
+ /** Fixed gain in tenths of a dB: a steady scale for comparing channels over time. */
+ fun setGain(tenthsDb: Int)
+ /** Restarts the sample stream after it stalled. */
+ fun resetBuffer()
+ /** Reads unsigned 8-bit I/Q into [buf]; bytes read, or a negative value on error. */
+ fun read(buf: ByteArray, len: Int): Int
+ fun read(buf: ByteArray): Int = read(buf, buf.size)
+}
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 e815677..02d7da5 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -11,7 +11,7 @@ import androidx.core.content.ContextCompat
import com.rfsentinel.app.usb.UsbWifi
/**
- * An RTL-SDR dongle on an OTG cable, used while scanning as a receive-only radio-activity
+ * An RTL-SDR dongle or a HackRF ([SdrDevice]) on an OTG cable, used while scanning as a receive-only radio-activity
* detector ([RadioWatch]): it sweeps the public-safety bands and reports strong
* transmissions nearby. Only signal strength per channel is measured. Its log goes into
* the USB adapter log (Settings → Export USB WiFi adapter log).
@@ -26,7 +26,7 @@ object SdrRadio {
private const val GAIN_TENTHS_DB = 297
private const val XFER = 16_384 // bytes per USB read (8192 samples)
private const val READS_PER_CHUNK = 8 // ~32 ms of samples per tuned chunk
- private const val SETTLE_READS = 2 // samples after a retune are discarded
+ private const val TETRA_READS = 16 // ~64 ms: more than one TETRA frame, so a radio's slot is always in it
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
@@ -45,7 +45,9 @@ object SdrRadio {
@Volatile private var usb: UsbManager? = null
private var appContext: Context? = null
private val main = android.os.Handler(android.os.Looper.getMainLooper())
- private const val UNPLUGGED = "RTL-SDR unplugged"
+ /** "RTL-SDR" or "HackRF": the plugged-in device, for the status line. */
+ @Volatile private var deviceLabel = "RTL-SDR"
+ 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. */
@@ -55,7 +57,8 @@ object SdrRadio {
/** 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)
+ fun isSdr(d: UsbDevice) = RtlSdr.isRtlSdr(d.vendorId, d.productId) || HackRf.isHackRf(d.vendorId, d.productId)
+ private fun labelOf(d: UsbDevice) = if (HackRf.isHackRf(d.vendorId, d.productId)) "HackRF" else "RTL-SDR"
@Synchronized
fun start(context: Context, events: (RadioWatch.Event) -> Unit) {
@@ -118,23 +121,25 @@ object SdrRadio {
runningDevice?.let { name ->
if (!gone(name)) return
// Unplugged without the system saying so: let that one go so the dongle can start again.
- UsbWifi.log("RTL-SDR: $name is gone - starting over")
+ UsbWifi.log("$deviceLabel: $name is gone - starting over")
halt("")
}
val d = runCatching { mgr.deviceList.values.firstOrNull { isSdr(it) } }.getOrNull() ?: return
+ deviceLabel = labelOf(d)
if (!mgr.hasPermission(d)) {
- UsbWifi.log("%04x:%04x (RTL-SDR) plugged in - asking for USB access".format(d.vendorId, d.productId))
- status = "RTL-SDR found - allow USB access on the prompt"
+ UsbWifi.log("%04x:%04x ($deviceLabel) plugged in - asking for USB access".format(d.vendorId, d.productId))
+ status = "$deviceLabel found - allow USB access on the prompt"
val pi = PendingIntent.getBroadcast(context, 2, Intent(ACTION_PERMISSION).setPackage(context.packageName), PendingIntent.FLAG_MUTABLE)
runCatching { mgr.requestPermission(d, pi) }
return
}
- val conn = mgr.openDevice(d) ?: run { status = "RTL-SDR: couldn't open it"; return }
+ val conn = mgr.openDevice(d) ?: run { status = "$deviceLabel: couldn't open it"; return }
runningDevice = d.deviceName
stop = false
- status = "RTL-SDR · starting…"
+ status = "$deviceLabel · starting…"
val t = Thread({
- val result = runCatching { run(RtlSdr(conn, d, UsbWifi::log), d) }
+ val sdr: SdrDevice = if (HackRf.isHackRf(d.vendorId, d.productId)) HackRf(conn, d, UsbWifi::log) else RtlSdr(conn, d, UsbWifi::log)
+ val result = runCatching { run(sdr, d) }
val failure = result.exceptionOrNull()
runCatching { conn.close() }
synchronized(this) {
@@ -143,14 +148,14 @@ object SdrRadio {
runningDevice = null
// Never leave the last "live" line behind: unplugged, failed, or just stopped answering.
if (gone(d.deviceName) || result.getOrNull() == true) {
- UsbWifi.log("RTL-SDR: unplugged or not answering")
+ UsbWifi.log("$deviceLabel: unplugged or not answering")
status = UNPLUGGED
clearUnpluggedSoon()
// Plugged back in already (it gets a new name), or it was only stuck: try again shortly.
appContext?.let { main.postDelayed({ if (receiver != null) connect(it) }, 3_000L) }
} else if (failure != null) {
- UsbWifi.log("RTL-SDR stopped: ${UsbWifi.describe(failure)}")
- status = "RTL-SDR error: ${failure.message}"
+ UsbWifi.log("$deviceLabel stopped: ${UsbWifi.describe(failure)}")
+ status = "$deviceLabel error: ${failure.message}"
}
}
}, "rtl-sdr")
@@ -159,32 +164,34 @@ object SdrRadio {
}
/** Reads until stopped; true when it ended because the dongle went away (unplugged or not answering). */
- private fun run(sdr: RtlSdr, d: UsbDevice): Boolean {
- UsbWifi.log("=== RTL-SDR radio activity watch (%04x:%04x) ===".format(d.vendorId, d.productId))
+ private fun run(sdr: SdrDevice, d: UsbDevice): Boolean {
+ UsbWifi.log("=== $deviceLabel radio activity watch (%04x:%04x) ===".format(d.vendorId, d.productId))
if (!sdr.open()) {
if (sdr.lost || gone(d.deviceName)) return true
- status = "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"; return false
+ status = if (sdr is HackRf) "HackRF: couldn't start it (see the USB log)"
+ else "RTL-SDR: this tuner isn't supported yet (R820T / R820T2 / R860 / R828D only)"
+ return false
}
while (!halted && !sdr.lost && !gone(d.deviceName)) if (adsb) runAdsb(sdr, d.deviceName) else runSweep(sdr, d.deviceName)
- if (sdr.lost) UsbWifi.log("RTL-SDR: the dongle stopped answering (unplugged?)")
+ if (sdr.lost) UsbWifi.log("$deviceLabel: the dongle stopped answering (unplugged?)")
val away = sdr.lost || gone(d.deviceName)
if (!away) sdr.close()
return away && !halted
}
- private fun runAdsb(sdr: RtlSdr, name: String) {
+ private fun runAdsb(sdr: SdrDevice, name: String) {
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"
+ 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++ }
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…"
+ 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…"
// 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)
@@ -201,7 +208,7 @@ object SdrRadio {
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
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")
+ if (fails <= STALL_CHUNKS * 3) UsbWifi.log("$deviceLabel: no samples for $fails reads in a row - restarting the stream")
sdr.resetBuffer()
}
continue
@@ -225,19 +232,19 @@ object SdrRadio {
val located = tracker.located(now)
val unlocated = tracker.unlocated(now)
onAircraft?.invoke(located, unlocated)
- if (!halted) status = "RTL-SDR · 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"
}
if (now - lastLog >= 60_000) {
- UsbWifi.log("RTL-SDR: ADS-B ${messages - logged} messages in ${(now - lastLog) / 1000} s, " +
+ UsbWifi.log("$deviceLabel: 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")
+ UsbWifi.log("$deviceLabel: ADS-B receiver stopped after $messages messages")
}
- private fun runSweep(sdr: RtlSdr, name: String) {
+ private fun runSweep(sdr: SdrDevice, name: String) {
sdr.setSampleRate(SAMPLE_RATE)
sdr.setGain(GAIN_TENTHS_DB)
sdr.resetBuffer()
@@ -245,13 +252,13 @@ object SdrRadio {
var plan = RadioWatch.plan(cfg)
val watch = RadioWatch()
watch.config = cfg
- fun logPlan() = UsbWifi.log("RTL-SDR: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " +
+ fun logPlan() = UsbWifi.log("$deviceLabel: ${sdr.sampleRate} S/s, gain ${GAIN_TENTHS_DB / 10.0} dB, ${plan.size} chunks per sweep over " +
cfg.bands.joinToString { "%.1f-%.1f MHz".format(it.startHz / 1e6, it.endHz / 1e6) } +
(if (cfg.targets.isNotEmpty()) ", ${cfg.targets.size} watched frequencies" else "") +
", reporting from ${cfg.minSnrDb} dB, USB errors ${sdr.ctlErrors}")
logPlan()
val buf = ByteArray(XFER)
- val iq = ByteArray(XFER * READS_PER_CHUNK)
+ val iq = ByteArray(XFER * maxOf(READS_PER_CHUNK, TETRA_READS))
var lastLog = 0L; var sweepStart = System.currentTimeMillis(); var sweepMs = 0L
var events = 0; var unlocked = 0; var readErrors = 0; var failedChunks = 0
var lastCheck = System.currentTimeMillis()
@@ -262,9 +269,11 @@ object SdrRadio {
if (halted || sdr.lost || adsb) break
if (System.currentTimeMillis() - lastCheck >= 2_000L) { lastCheck = System.currentTimeMillis(); if (gone(name)) break }
if (!sdr.tune(center)) { unlocked++; continue }
- repeat(SETTLE_READS) { sdr.read(buf) }
+ repeat(sdr.settleReads) { sdr.read(buf) }
+ // TETRA chunks also keep the power in 2 ms steps, to see a radio's 14 ms time-slot bursts.
+ val tetra = cfg.bands.any { it.kind == RadioWatch.Kind.TETRA && RadioWatch.covers(it, center) }
var got = 0
- for (i in 0 until READS_PER_CHUNK) {
+ for (i in 0 until if (tetra) TETRA_READS else READS_PER_CHUNK) {
val n = sdr.read(buf)
if (n <= 0) { readErrors++; break }
System.arraycopy(buf, 0, iq, got, n); got += n
@@ -272,17 +281,19 @@ object SdrRadio {
if (got < 2 * 1024) {
// The sample stream stalled: restart it (as librtlsdr's reset_buffer) instead of sweeping on with nothing.
if (++failedChunks % STALL_CHUNKS == 0) {
- if (failedChunks <= STALL_CHUNKS * 3) UsbWifi.log("RTL-SDR: no samples for $failedChunks chunks in a row - restarting the stream")
+ if (failedChunks <= STALL_CHUNKS * 3) UsbWifi.log("$deviceLabel: no samples for $failedChunks chunks in a row - restarting the stream")
sdr.resetBuffer()
}
continue
}
failedChunks = 0
- val psd = RadioWatch.powerSpectrum(iq, got / 2)
- for (e in watch.analyze(center, psd, sdr.sampleRate, System.currentTimeMillis())) {
+ val bursts = if (tetra) RadioWatch.burstSpectrum(iq, got / 2, sdr.sampleRate) else null
+ val psd = bursts?.psd ?: RadioWatch.powerSpectrum(iq, got / 2)
+ for (e in watch.analyze(center, psd, sdr.sampleRate, System.currentTimeMillis(), bursts)) {
if (!e.repeat) {
events++
- UsbWifi.log("RTL-SDR: transmission ${e.mhz} MHz, ${e.snrDb} dB above the noise (${e.band.label})")
+ UsbWifi.log("$deviceLabel: transmission ${e.mhz} MHz, ${e.snrDb} dB above the noise (${e.band.label})" +
+ if (e.tdma) ", TETRA time slots" else "")
}
onEvent?.invoke(e)
}
@@ -291,14 +302,14 @@ object SdrRadio {
val now = System.currentTimeMillis()
sweepMs = now - sweepStart; sweepStart = now
if (gone(name)) break
- if (!halted) status = if (watch.sweeps < 6) "RTL-SDR · learning the radio bands here…"
- else "RTL-SDR · 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"
if (now - lastLog > (if (watch.sweeps < 20) 10_000 else 60_000)) {
lastLog = now
- UsbWifi.log("RTL-SDR: sweep ${watch.sweeps} in $sweepMs ms, ${watch.learnedChannels} channels, ${watch.busyChannels} always busy, " +
+ UsbWifi.log("$deviceLabel: sweep ${watch.sweeps} in $sweepMs ms, ${watch.learnedChannels} channels, ${watch.busyChannels} always busy, " +
"$events reported, PLL unlocked $unlocked, read errors $readErrors, tuner write failures ${sdr.tunerWriteFails}, USB errors ${sdr.ctlErrors}")
}
}
- UsbWifi.log("RTL-SDR: radio sweep stopped after ${watch.sweeps} sweeps")
+ UsbWifi.log("$deviceLabel: 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 d11b95a..06f0d1b 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -1089,6 +1089,10 @@ class ScanForegroundService : Service() {
when (e.band.kind) {
com.rfsentinel.app.sdr.RadioWatch.Kind.PUBLIC_SAFETY_MOBILE ->
"Public-safety radios (police, fire, EMS) transmit on this band; not proof of who it is."
+ com.rfsentinel.app.sdr.RadioWatch.Kind.TETRA -> if (e.tdma)
+ "It came in TETRA time-slot bursts: an emergency-services (police, fire, ambulance) TETRA handset or car radio. " +
+ "Encrypted, nothing decoded; not proof of who it is."
+ else "Emergency-service TETRA handsets transmit on this band, but this signal had no TETRA time slots; a weak sign on its own."
com.rfsentinel.app.sdr.RadioWatch.Kind.TARGET -> "One of the frequencies you watch (Settings > RTL-SDR radio)."
com.rfsentinel.app.sdr.RadioWatch.Kind.CUSTOM -> "A band you added in Settings > RTL-SDR radio."
else -> "Police use this band, but so do businesses, schools and transit; a weak sign on its own."
@@ -1101,9 +1105,11 @@ class ScanForegroundService : Service() {
val label = when {
cell -> "Cellular transmitter nearby (LTE uplink)"
name != null -> "Radio transmitting: $name"
+ e.tdma -> "TETRA radio transmitting nearby"
else -> "Two-way radio transmitting nearby"
}
- val hit = Hit(Category.RADIO, label, e.confidence, if (cell) cellDetail else detail, "RTL-SDR signal strength (no decoding)")
+ 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)")
val loc = lastLocation
val tag = Prefs.gpsTaggingEnabled(this)
serviceScope.launch {
@@ -1121,7 +1127,8 @@ class ScanForegroundService : Service() {
// Spoken: the frequency (and its name) when that's on, else the short phrase.
val spoken = when {
cell -> "Cellular transmitter nearby"
- Prefs.radioSpeakFreq(this) -> "Radio ${spokenMhz(e.freqHz)}" + (name?.let { ", $it" } ?: "")
+ 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"
}
AlertPlayer.play(this, hit.tier, spoken)
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 9db2948..67baf71 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -315,7 +315,7 @@ class SettingsActivity : AppCompatActivity() {
val s = com.rfsentinel.app.esp.EspBoards.status
binding.espStatusText.text = s.ifBlank { "ESP32 board on USB: not connected" }
binding.usbWifiText.text = com.rfsentinel.app.usb.UsbWifi.status.ifBlank { "USB WiFi adapter: not connected" }
- binding.sdrStatusText.text = com.rfsentinel.app.sdr.SdrRadio.status.ifBlank { "RTL-SDR: not connected" }
+ binding.sdrStatusText.text = com.rfsentinel.app.sdr.SdrRadio.status.ifBlank { "RTL-SDR / HackRF: not connected" }
val board = Prefs.ouiSpyBoard(this)
binding.ouiSpyText.text = if (board == null) "OUI-SPY over Bluetooth: not paired"
else com.rfsentinel.app.esp.OuiSpyBle.status.ifBlank { "OUI-SPY $board: connects while scanning" }
@@ -432,7 +432,7 @@ class SettingsActivity : AppCompatActivity() {
Section("detect", binding.headerDetect, binding.sectionDetect,
"Each type of equipment can be turned on or off. Network / home cameras are off by default (many false alarms).\n\n" +
"GPS / satellite checks cover every system the phone hears: GPS, GLONASS, Galileo, BeiDou, QZSS and NavIC.\n\n" +
- "Two-way radio needs an RTL-SDR dongle on USB.\n\n" +
+ "Two-way radio needs an RTL-SDR dongle or a HackRF on USB.\n\n" +
"Police aircraft and Waze reports are online sources, off by default. Aircraft: every minute, a position " +
"rounded to about 1 km goes to the community ADS-B feeds adsb.fi / adsb.lol; matched against a list of " +
"about 1,400 US and Canadian law-enforcement aircraft, plus unlisted aircraft circling low overhead. With an RTL-SDR " +
@@ -561,7 +561,8 @@ class SettingsActivity : AppCompatActivity() {
"Adapter light: the AWUS036ACS blinks with received traffic; switch it off to keep it dark (for example in a car at night). " +
"Only adapters whose light the app can control have this option (the RTL8811AU / 8821AU); the others keep their own behaviour. " +
"Applies at once.\n\n" +
- "• RTL-SDR dongle: notices two-way radios transmitting nearby (signal strength only, nothing is decoded).\n\n" +
+ "• RTL-SDR dongle or HackRF: notices two-way radios transmitting nearby (signal strength only, nothing is decoded). " +
+ "The HackRF is only ever used to receive.\n\n" +
"OUI-SPY over Bluetooth needs its App-Controlled firmware. Relay mode passes on every network and device it hears " +
"so RF Sentinel's own lists check them (the board also sends standard Wi-Fi scan probes).\n\n" +
"Adapter not working? Export its log and send it to the developer.\n\n" +
@@ -577,7 +578,7 @@ class SettingsActivity : AppCompatActivity() {
"Ordinary cars are counted, not listed. North America uses a different V2X radio (C-V2X) that this board can't hear. " +
"Receiving V2X may fall under telecom or privacy law where you are."),
Section("radio", binding.headerRadio, binding.sectionRadio,
- "An RTL-SDR dongle on USB notices two-way radios transmitting nearby, from signal strength only - nothing is " +
+ "An RTL-SDR dongle or a HackRF on USB notices two-way radios transmitting nearby, from signal strength only - nothing is " +
"decoded or recorded. Needs the Police radio category on (What to detect).\n\n" +
"Sensitivity: how far above the noise a burst must be to count. Lower hears farther radios, and more false alarms.\n\n" +
"Bands: the built-in North American public-safety bands, your own bands (one per line, \"380-400 TETRA\"), " +
@@ -1100,6 +1101,10 @@ class SettingsActivity : AppCompatActivity() {
"Experimental. Watches the phone / modem side of the LTE bands (uplink) for a transmitter travelling near you: a vehicle modem, a " +
"Cradlepoint-style router, a camera with a SIM. Energy only, nothing decoded. Adds time to each sweep; " +
"a phone counts too, so it is a weak sign on its own.") { Prefs.setRadioCellOn(this, it) }
+ switch("Detect TETRA radios", Prefs.radioTetraOn(this),
+ "Watches 380-385 MHz, where emergency-service TETRA handsets transmit in Europe and many other countries. " +
+ "A handset sends short time-slot bursts; that rhythm marks it as a TETRA radio. Energy only: TETRA is encrypted " +
+ "and nothing is decoded. On by default when the phone's region is in Europe.") { Prefs.setRadioTetraOn(this, it) }
slider(0, 20, Prefs.radioTrendDb(this), { if (it == 0) "Closer / moving away: off" else "Say \"getting closer\" / \"moving away\" when the signal changes by $it dB" }) {
Prefs.setRadioTrendDb(this, it)
}
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 dcb1b5c..6598eee 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -220,7 +220,9 @@ object UsbWifi {
val sb = StringBuilder()
val what = chipOf(d)?.let { "supported (${it.name})" }
?: knownOnly(d)?.let { "$it, not supported yet" }
- ?: if (com.rfsentinel.app.sdr.RtlSdr.isRtlSdr(d.vendorId, d.productId)) "RTL-SDR (radio activity detector)" else "not a supported WiFi adapter"
+ ?: if (com.rfsentinel.app.sdr.RtlSdr.isRtlSdr(d.vendorId, d.productId)) "RTL-SDR (radio activity detector)"
+ else if (com.rfsentinel.app.sdr.HackRf.isHackRf(d.vendorId, d.productId)) "HackRF (radio activity detector, receive only)"
+ else "not a supported WiFi adapter"
val allowed = runCatching { mgr?.hasPermission(d) }.getOrNull() == true
// Names are only readable once USB access is allowed.
val name = listOfNotNull(runCatching { d.manufacturerName }.getOrNull(), runCatching { d.productName }.getOrNull())
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 93f51a8..058a7c7 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -475,6 +475,13 @@ object Prefs {
/** Also sweep the cellular UPLINK bands for a transmitter travelling near you (experimental, off by default). */
fun radioCellOn(context: Context): Boolean = bool(context, "radio_cell_on", false)
fun setRadioCellOn(context: Context, value: Boolean) = setBool(context, "radio_cell_on", value)
+ /** Also sweep the TETRA handset band (380-385 MHz); on by default where the phone's region uses TETRA. */
+ fun radioTetraOn(context: Context): Boolean = bool(context, "radio_tetra_on", tetraRegion(java.util.Locale.getDefault().country))
+ fun setRadioTetraOn(context: Context, value: Boolean) = setBool(context, "radio_tetra_on", value)
+ /** Europe's emergency services use TETRA on 380-385 MHz (from the phone's language region, not its location). */
+ fun tetraRegion(country: String) = country.uppercase() in TETRA_REGIONS
+ private val TETRA_REGIONS = setOf("AT", "BE", "BG", "CH", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GB", "GR", "HR",
+ "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MT", "NL", "NO", "PL", "PT", "RO", "SE", "SI", "SK")
fun setRadioBandsOff(context: Context, v: Set<String>) = sp(context).edit { putStringSet("radio_bands_off", v) }
/** The user's own bands, one "start-end MHz label" per line. */
fun radioCustomBands(context: Context) = str(context, "radio_custom_bands")
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/TetraTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/TetraTest.kt
new file mode 100644
index 0000000..2b82f8d
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/sdr/TetraTest.kt
@@ -0,0 +1,114 @@
+package com.rfsentinel.app.sdr
+
+import com.rfsentinel.app.util.Prefs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.math.PI
+import kotlin.math.cos
+import kotlin.math.roundToInt
+import kotlin.math.sin
+
+/** TETRA on 380-385 MHz: a handset's time-slot bursts are told apart from a carrier that stays on. */
+class TetraTest {
+
+ private val rate = 2_048_000
+ private val count = 131_072 // 64 ms, as SdrRadio reads a TETRA chunk
+ private val center = 382_400_000L
+ private val radio = 382_612_500L
+
+ /** Noise, plus a tone at [freq] that is on during [on] (ms into the chunk). */
+ private fun iq(freq: Long?, amp: Double = 50.0, seed: Int = 1, on: (Double) -> Boolean = { true }): ByteArray {
+ val rnd = java.util.Random(seed.toLong())
+ val b = ByteArray(2 * count)
+ for (i in 0 until count) {
+ var re = rnd.nextGaussian() * 1.5; var im = rnd.nextGaussian() * 1.5
+ if (freq != null && on(i * 1000.0 / rate)) {
+ val ph = 2 * PI * (freq - center) * i / rate
+ re += amp * cos(ph); im += amp * sin(ph)
+ }
+ b[2 * i] = (127.5 + re).roundToInt().coerceIn(0, 255).toByte()
+ b[2 * i + 1] = (127.5 + im).roundToInt().coerceIn(0, 255).toByte()
+ }
+ return b
+ }
+
+ /** One TETRA slot (14.17 ms) per 56.67 ms frame, starting [start] ms in. */
+ private fun slot(start: Double) = { t: Double -> ((t - start) % 56.67 + 56.67) % 56.67 < 14.17 }
+
+ private fun watch(): Pair<RadioWatch, Long> {
+ val w = RadioWatch()
+ w.config = RadioWatch.Config(bands = listOf(RadioWatch.TETRA_BAND))
+ var t = 0L
+ repeat(8) { s ->
+ val b = RadioWatch.burstSpectrum(iq(null, seed = s), count, rate)
+ w.analyze(center, b.psd, rate, t, b); w.sweepDone(); t += 2_500
+ }
+ return w to t
+ }
+
+ @Test
+ fun burstSpectrumKeepsTwoMillisecondSteps() {
+ val b = RadioWatch.burstSpectrum(iq(radio, on = slot(10.0)), count, rate)
+ assertEquals(2.0, b.groupMs, 0.01)
+ assertEquals(32, b.groups.size)
+ }
+
+ @Test
+ fun aHandsetsSlotIsTdmaAndAnAlert() {
+ val (w, t) = watch()
+ for (start in listOf(0.0, 20.0, 47.0)) {
+ val b = RadioWatch.burstSpectrum(iq(radio, on = slot(start)), count, rate)
+ val ev = w.analyze(center, b.psd, rate, t + (start * 1000).toLong(), b).single()
+ assertTrue("slot at $start ms", ev.tdma)
+ assertEquals(RadioWatch.Kind.TETRA, ev.band.kind)
+ assertTrue(kotlin.math.abs(ev.freqHz - radio) <= 12_500)
+ }
+ val b = RadioWatch.burstSpectrum(iq(radio, on = slot(5.0)), count, rate)
+ assertTrue(w.analyze(center, b.psd, rate, t + 500_000, b).single().confidence >= 65)
+ }
+
+ @Test
+ fun aCarrierThatStaysOnIsNotTdma() {
+ val (w, t) = watch()
+ val b = RadioWatch.burstSpectrum(iq(radio), count, rate)
+ val ev = w.analyze(center, b.psd, rate, t, b)
+ assertTrue(ev.none { it.tdma })
+ assertTrue(ev.all { it.confidence <= 55 })
+ }
+
+ @Test
+ fun noiseIsNotTdma() {
+ val levels = FloatArray(32) { if (it % 3 == 0) 7f else 3f }
+ assertFalse(RadioWatch.isTdma(levels, 2.0))
+ // A short chunk can't show a whole frame.
+ assertFalse(RadioWatch.isTdma(FloatArray(16) { if (it < 7) 40f else 0f }, 2.0))
+ assertTrue(RadioWatch.isTdma(FloatArray(32) { if (it in 5..11) 40f else 0f }, 2.0))
+ }
+
+ @Test
+ fun theBandIsOnlyTheHandsetSide() {
+ val b = RadioWatch.TETRA_BAND
+ assertEquals(380_000_000L, b.startHz)
+ assertEquals(385_000_000L, b.endHz)
+ assertEquals(4, RadioWatch.plan(RadioWatch.Config(bands = listOf(b))).size)
+ assertTrue(RadioWatch.covers(b, 384_000_000L))
+ assertFalse(RadioWatch.covers(b, 392_000_000L)) // base stations: never swept
+ }
+
+ @Test
+ fun onByDefaultInEurope() {
+ assertTrue(Prefs.tetraRegion("de"))
+ assertTrue(Prefs.tetraRegion("GB"))
+ assertFalse(Prefs.tetraRegion("US"))
+ assertFalse(Prefs.tetraRegion(""))
+ }
+
+ @Test
+ fun hackRfIsAnSdr() {
+ assertTrue(HackRf.isHackRf(0x1d50, 0x6089))
+ assertFalse(HackRf.isHackRf(0x0bda, 0x2838))
+ assertFalse(RtlSdr.isRtlSdr(0x1d50, 0x6089))
+ }
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/55.txt b/fastlane/metadata/android/en-US/changelogs/55.txt
index 03d4265..299bf93 100644
--- a/fastlane/metadata/android/en-US/changelogs/55.txt
+++ b/fastlane/metadata/android/en-US/changelogs/55.txt
@@ -1,5 +1,7 @@
+- TETRA: spots emergency-service radios on 380-385 MHz by their time-slot bursts (on by default in Europe, nothing decoded).
+- HackRF One works as the radio detector (receive only).
- Recording banner and scan warnings can be hidden with ✕.
-- Fewer "Bluetooth scan restarted" stalls: the scan is no longer restarted by every start request, which could trip Android's scan limit.
-- A VeryFit smartwatch (IDW26) using TASER's Bluetooth ID no longer shows as Axon gear.
-- "No signal reported" no longer logs as +127 dBm.
-- RTL8822BU register tables now ship as text.
+- Fewer "Bluetooth scan restarted" stalls.
+- A VeryFit watch (IDW26) using TASER's Bluetooth ID no longer shows as Axon gear.
+- "No signal" no longer logs as +127 dBm.
+- RTL8822BU register tables ship as text.