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.

2.34.0: waterfall keeps a failed chunk's place (no restart each sweep), MQTT relay single-lock reconnect fix

CIS-C09f5c492e7984
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index f773b07..8c72ff9 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -7,8 +7,8 @@ plugins {
}
// Bump both for every release. versionName ends up in the APK file name.
-val appVersionCode = 65
-val appVersionName = "2.33.0"
+val appVersionCode = 66
+val appVersionName = "2.34.0"
// Release signing credentials live in keystore.properties (git-ignored).
// Without that file, release builds are produced unsigned.
diff --git a/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt b/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt
index 3c26290..7250cd3 100644
--- a/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt
@@ -69,7 +69,6 @@ object MqttRelay {
private var thread: Thread? = null
@Volatile private var socket: Socket? = null
@Volatile private var out: OutputStream? = null
- private val writeLock = Any()
@Volatile private var lastWrite = 0L
/** Connects (again, when anything changed); [packets] gets the group's payloads, on the relay's thread. */
@@ -87,8 +86,7 @@ object MqttRelay {
config = null
thread?.interrupt()
thread = null
- closeSocket()
- ready = false
+ closeSocket(socket)
setStatus("")
}
@@ -104,17 +102,18 @@ object MqttRelay {
if (ready && now - lastWrite >= PING_MS) write(MqttCodec.PINGREQ)
}
- private fun write(bytes: ByteArray): Boolean = synchronized(writeLock) {
+ // One lock (this object) for the connection's fields, start / stop and writes: a thread being replaced
+ // never touches the new connection.
+ private fun write(bytes: ByteArray): Boolean = synchronized(this) {
val o = out ?: return false
try { o.write(bytes); o.flush(); lastWrite = System.currentTimeMillis(); true }
- catch (e: IOException) { closeSocket(); false } // the reader sees it and reconnects
+ catch (e: IOException) { closeSocket(socket); false } // the reader sees it and reconnects
}
- private fun closeSocket() {
- ready = false
- out = null
- runCatching { socket?.close() }
- socket = null
+ /** Closes [s]; the shared fields are cleared only while they're still [s]'s. */
+ private fun closeSocket(s: Socket?) {
+ synchronized(this) { if (socket === s) { ready = false; out = null; socket = null } }
+ runCatching { s?.close() }
}
private fun current(c: Config) = synchronized(this) { config === c }
@@ -122,17 +121,16 @@ object MqttRelay {
private fun run(c: Config, packets: (ByteArray) -> Unit) {
var retry = RETRY_MIN_MS
while (current(c) && !Thread.currentThread().isInterrupted) {
+ var s: Socket? = null
try {
setStatus("Connecting to ${c.broker.host}…")
- val s = open(c.broker, c.checkCert)
- socket = s
+ s = open(c.broker, c.checkCert)
s.soTimeout = DEAD_MS.toInt()
val input = DataInputStream(BufferedInputStream(s.getInputStream()))
val o = s.getOutputStream()
- synchronized(writeLock) { out = o }
// A fresh client id each time: nothing ties two sessions (or the phone) together on the broker.
val id = "rfs-" + LinkCrypto.random(6).joinToString("") { "%02x".format(it) }
- if (!write(MqttCodec.connect(id, c.user, c.password, KEEPALIVE_S))) throw IOException("closed")
+ o.write(MqttCodec.connect(id, c.user, c.password, KEEPALIVE_S)); o.flush()
val ack = MqttCodec.read(input)
if (ack.type != MqttCodec.CONNACK || ack.body.size < 2) throw IOException("not an MQTT broker")
when (val code = ack.body[1].toInt()) {
@@ -140,8 +138,11 @@ object MqttRelay {
4, 5 -> throw Refused("The broker refused the username or password")
else -> throw Refused("The broker refused the connection (code $code)")
}
- if (!write(MqttCodec.subscribe(1, c.topic))) throw IOException("closed")
- ready = true
+ o.write(MqttCodec.subscribe(1, c.topic)); o.flush()
+ synchronized(this) {
+ if (!current(c)) throw IOException("stopped")
+ socket = s; out = o; lastWrite = System.currentTimeMillis(); ready = true
+ }
retry = RETRY_MIN_MS
setStatus("Connected to ${c.broker.host}")
while (current(c)) {
@@ -157,7 +158,7 @@ object MqttRelay {
Log.d(TAG, "connection ended: ${e.javaClass.simpleName}")
setStatus("Can't reach ${c.broker.host} - ${e.message?.take(60) ?: e.javaClass.simpleName}, retrying")
} finally {
- closeSocket()
+ closeSocket(s)
}
try { Thread.sleep(retry) } catch (e: InterruptedException) { break }
retry = (retry * 2).coerceAtMost(RETRY_MAX_MS)
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 b6dea48..3f29b9e 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrRadio.kt
@@ -423,7 +423,11 @@ object SdrRadio {
for (center in plan) {
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 }
+ fun skipped() {
+ if (SdrWaterfall.listening) row += SdrWaterfall.blank(center, sdr.sampleRate, RadioWatch.USABLE_HZ,
+ cfg.bands.firstOrNull { RadioWatch.covers(it, center) }?.label)
+ }
+ if (!sdr.tune(center)) { unlocked++; skipped(); continue }
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) }
@@ -439,6 +443,7 @@ object SdrRadio {
if (failedChunks <= STALL_CHUNKS * 3) UsbWifi.log("$deviceLabel: no samples for $failedChunks chunks in a row - restarting the stream")
sdr.resetBuffer()
}
+ skipped()
continue
}
failedChunks = 0
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt b/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt
index 370f76e..e1d5729 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/SdrWaterfall.kt
@@ -25,7 +25,7 @@ object SdrWaterfall {
fun segment(centerHz: Long, psd: FloatArray, sampleRate: Int, halfSpanHz: Double, band: String?): Segment {
val n = psd.size
val binHz = sampleRate.toDouble() / n
- val half = (halfSpanHz / binHz).toInt().coerceIn(1, n / 2 - 1)
+ val half = half(n, sampleRate, halfSpanHz)
val out = psd.copyOfRange(n / 2 - half, n / 2 + half + 1)
val guard = maxOf(1, (RadioWatch.DC_GUARD_HZ / binHz).toInt()).coerceAtMost(half - 1)
val level = minOf(out[half - guard - 1], out[half + guard + 1])
@@ -33,4 +33,19 @@ object SdrWaterfall {
val edge = (half * binHz).toLong()
return Segment(centerHz - edge, centerHz + edge, out, band)
}
+
+ /** A value that isn't a reading: drawn black and left out of the noise floor. */
+ const val NO_DATA = -200f
+
+ /**
+ * The same stretch as [segment] for a chunk that gave nothing (didn't tune, or the stream stalled), so every
+ * sweep's row keeps the same layout: a row missing a chunk made the screen start over, and looked stuck.
+ */
+ fun blank(centerHz: Long, sampleRate: Int, halfSpanHz: Double, band: String?, n: Int = 1024): Segment {
+ val half = half(n, sampleRate, halfSpanHz)
+ val edge = (half * sampleRate.toDouble() / n).toLong()
+ return Segment(centerHz - edge, centerHz + edge, FloatArray(2 * half + 1) { NO_DATA }, band)
+ }
+
+ private fun half(n: Int, sampleRate: Int, halfSpanHz: Double) = (halfSpanHz / (sampleRate.toDouble() / n)).toInt().coerceIn(1, n / 2 - 1)
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt
index 929c938..2b9fdeb 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallView.kt
@@ -83,12 +83,16 @@ class WaterfallView @JvmOverloads constructor(context: Context, attrs: Attribute
for (k in colFrom[x]..colTo[x]) if (d[k] > m) m = d[k]
m
}
- val median = values.copyOf().also { it.sort() }[w / 2]
- floor = if (floor.isNaN()) median else floor + (median - floor) * (if (row.tuned) 0.05f else 0.3f)
+ val heard = values.filter { it > SdrWaterfall.NO_DATA }.sorted()
+ if (heard.isNotEmpty()) {
+ val median = heard[heard.size / 2]
+ floor = if (floor.isNaN()) median else floor + (median - floor) * (if (row.tuned) 0.05f else 0.3f)
+ }
spectrum = values
peak = peak?.let { p -> FloatArray(w) { maxOf(values[it], p[it] - (if (row.tuned) 0.15f else 1.5f)) } } ?: values.copyOf()
val bmp = bitmap ?: return
- for (x in 0 until w) pixels[x] = PALETTE[(((values[x] - floor + 3f) / RANGE_DB) * 255).toInt().coerceIn(0, 255)]
+ if (floor.isNaN()) return
+ for (x in 0 until w) pixels[x] = if (values[x] <= SdrWaterfall.NO_DATA) PALETTE[0] else PALETTE[(((values[x] - floor + 3f) / RANGE_DB) * 255).toInt().coerceIn(0, 255)]
newest = (newest - 1 + bmp.height) % bmp.height
bmp.setPixels(pixels, 0, w, 0, newest, w, 1)
rows = minOf(rows + 1, bmp.height)
diff --git a/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt b/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt
index 04bb802..2eca387 100644
--- a/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/sdr/SdrWaterfallTest.kt
@@ -24,4 +24,15 @@ class SdrWaterfallTest {
assertEquals("VHF", s.band)
assertTrue("the input is left alone", psd[n / 2] == 0f)
}
+
+ @Test
+ fun aFailedChunkKeepsTheSameStretchSoTheRowLayoutHolds() {
+ val rate = 2_048_000
+ val s = SdrWaterfall.segment(155_000_000L, FloatArray(1024) { -60f }, rate, RadioWatch.USABLE_HZ, "VHF")
+ val b = SdrWaterfall.blank(155_000_000L, rate, RadioWatch.USABLE_HZ, "VHF")
+ assertEquals(s.startHz, b.startHz)
+ assertEquals(s.endHz, b.endHz)
+ assertEquals(s.db.size, b.db.size)
+ assertTrue(b.db.all { it == SdrWaterfall.NO_DATA })
+ }
}