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.

Share USB receive loops and monitor sighting emission

greyxp1ac2d96974ce5
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt b/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt
index a1141f2..883bcc1 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt
@@ -21,9 +21,7 @@ object EspBoards {
private const val ACTION_PERMISSION = "com.rfsentinel.app.ESP_USB_PERMISSION"
- private class Running(val reader: EspReader, val thread: Thread)
-
- private val running = HashMap<String, Running>()
+ private val running = HashMap<String, EspReader>()
private var receiver: BroadcastReceiver? = null
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
private var onSightings: ((List<EspSighting>) -> Unit)? = null
@@ -109,14 +107,14 @@ object EspBoards {
runCatching { port.close() }
synchronized(this) { running.remove(d.deviceName) }
}, "esp32-${d.deviceName}")
- running[d.deviceName] = Running(reader, t)
+ running[d.deviceName] = reader
t.start()
}
}
@Synchronized
private fun stopBoard(name: String) {
- running.remove(name)?.reader?.stop()
+ running.remove(name)?.stop()
if (running.isEmpty()) {
setStatus("ESP32 disconnected")
if (!OuiSpyBle.connected) HeardBy.esp.clear()
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
index e6c3a01..153d409 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
@@ -282,14 +282,14 @@ class EspReader(
}
/** Reads for up to [ms], stopping early once [done] is true for what was read. */
- private fun readFor(buf: ByteArray, ms: Long, done: (String) -> Boolean = { false }): String {
+ private fun readFor(buf: ByteArray, ms: Long, done: ((String) -> Boolean)? = null): String {
val sb = StringBuilder()
val until = System.currentTimeMillis() + ms
while (!stopped && System.currentTimeMillis() < until) {
val n = port.read(buf, 300)
if (n > 0) {
sb.append(text.decode(buf, n))
- if (done(sb.toString())) break
+ if (done?.invoke(sb.toString()) == true) break
}
}
return sb.toString()
diff --git a/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt b/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt
index c5ea7e2..2442b79 100644
--- a/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt
+++ b/app/src/main/java/com/rfsentinel/app/sdr/HackRf.kt
@@ -27,7 +27,6 @@ class HackRf(private val conn: UsbDeviceConnection, private val device: UsbDevic
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 ->
@@ -73,7 +72,7 @@ class HackRf(private val conn: UsbDeviceConnection, private val device: UsbDevic
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++
+ if (!ok) tunerWriteFails++
return ok
}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Ar9271Monitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Ar9271Monitor.kt
index be01868..c3f283b 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Ar9271Monitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Ar9271Monitor.kt
@@ -456,7 +456,7 @@ object Ar9271Monitor {
val (aps, clients) = frames.live(now, REPORT_MS)
"ch $curChannel, $aps access points, $clients devices, USB errors $ctlErrors"
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -467,15 +467,10 @@ object Ar9271Monitor {
st.hopAt = System.currentTimeMillis() // the dwell starts once the retune is done
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("AR9271: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/**
* The firmware's RX stream: packets of | length (le16) | tag 0x4e00 (le16) | HTC header (8) |
* RX status (40) | frame + FCS | (HTC trailer) |, each padded to 4 bytes; one can continue in
diff --git a/app/src/main/java/com/rfsentinel/app/usb/BulkRx.kt b/app/src/main/java/com/rfsentinel/app/usb/BulkRx.kt
index 07abd0e..d74f0bd 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/BulkRx.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/BulkRx.kt
@@ -7,7 +7,7 @@ import java.nio.ByteBuffer
import java.util.concurrent.TimeoutException
/**
- * Bulk-IN receive loop for the RTL8187 and RT3070 drivers: keeps [count] transfers of
+ * Bulk-IN receive loop for monitor drivers: keeps [count] transfers of
* [size] bytes in flight (async [UsbRequest]), or falls back to synchronous transfers
* where the platform can't queue them. [onData] gets each completed transfer; [onTick]
* runs at least every ~100 ms (channel hops, reports) until [stopped] says so.
@@ -16,13 +16,13 @@ import java.util.concurrent.TimeoutException
internal object BulkRx {
fun run(tag: String, conn: UsbDeviceConnection, ep: UsbEndpoint, count: Int, size: Int,
- stopped: () -> Boolean, onData: (ByteArray, Int) -> Unit, onTick: (Long) -> Unit): Long {
+ stopped: () -> Boolean, onData: (ByteArray, Int) -> Unit, syncTimeoutMs: Int = 200, onTick: (Long) -> Unit): Long {
val buffers = Array(count) { ByteBuffer.allocateDirect(size) }
val reqs = ArrayList<UsbRequest>(count)
var async = true
for (i in 0 until count) {
val r = UsbRequest()
- if (!r.initialize(conn, ep)) { async = false; break }
+ if (!r.initialize(conn, ep)) { runCatching { r.close() }; async = false; break }
r.clientData = i
if (!r.queue(buffers[i])) { runCatching { r.close() }; async = false; break }
reqs.add(r)
@@ -30,7 +30,7 @@ internal object BulkRx {
if (!async) {
UsbWifi.log("$tag: async RX unavailable (${reqs.size}/$count) - synchronous RX")
reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- return runSync(conn, ep, size, stopped, onData, onTick)
+ return runSync(conn, ep, size, stopped, onData, onTick, syncTimeoutMs)
}
UsbWifi.log("$tag: async RX live - $count buffers in flight")
val scratch = ByteArray(size)
@@ -49,10 +49,12 @@ internal object BulkRx {
if (!runCatching { req.queue(b) }.getOrDefault(false)) {
runCatching { req.close() }
val nr = UsbRequest()
- if (runCatching { nr.initialize(conn, ep) }.getOrDefault(false)) {
+ val queued = runCatching {
+ if (!nr.initialize(conn, ep)) return@runCatching false
nr.clientData = idx
- if (runCatching { nr.queue(b) }.getOrDefault(false)) reqs[idx] = nr
- }
+ nr.queue(b)
+ }.getOrDefault(false)
+ if (queued) reqs[idx] = nr else runCatching { nr.close() }
}
if (n in 1..size) { total += n; guard.data(); runCatching { onData(scratch, n) } } else guard.empty()
}
@@ -66,11 +68,11 @@ internal object BulkRx {
}
private fun runSync(conn: UsbDeviceConnection, ep: UsbEndpoint, size: Int, stopped: () -> Boolean,
- onData: (ByteArray, Int) -> Unit, onTick: (Long) -> Unit): Long {
+ onData: (ByteArray, Int) -> Unit, onTick: (Long) -> Unit, timeoutMs: Int): Long {
val buf = ByteArray(size)
var total = 0L
while (!stopped()) {
- val n = conn.bulkTransfer(ep, buf, size, 200)
+ val n = conn.bulkTransfer(ep, buf, size, timeoutMs)
if (n > 0) { total += n; runCatching { onData(buf, n) } }
onTick(System.currentTimeMillis())
}
@@ -174,8 +176,8 @@ internal object BulkRx {
return ok
}
- /** The bulk-IN endpoint at [address], else the interface's first bulk-IN endpoint. */
- fun inEndpoint(intf: android.hardware.usb.UsbInterface, address: Int): UsbEndpoint? {
+ /** The bulk-IN endpoint at [address], or the first bulk-IN endpoint if unspecified or absent. */
+ fun inEndpoint(intf: android.hardware.usb.UsbInterface, address: Int = -1): UsbEndpoint? {
var first: UsbEndpoint? = null
for (i in 0 until intf.endpointCount) {
val ep = intf.getEndpoint(i)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt b/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt
index 5beaa34..8965506 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/DeauthWatch.kt
@@ -41,7 +41,6 @@ object DeauthWatch {
private class Net {
val frames = ArrayDeque<Pair<Long, Boolean>>()
- var channel = 0
var lastReport = Long.MIN_VALUE / 2
}
@@ -53,7 +52,6 @@ object DeauthWatch {
if (nets.size > MAX_NETWORKS) nets.entries.removeAll { (_, n) -> n.frames.isEmpty() || now - n.frames.last().first > WINDOW_MS }
val n = nets.getOrPut(bssid) { Net() }
n.frames.addLast(now to broadcast)
- n.channel = channel
while (n.frames.isNotEmpty() && (now - n.frames.first().first > WINDOW_MS || n.frames.size > MAX_KEPT)) n.frames.removeFirst()
if (now - n.lastReport < REPEAT_MS || !(burst(n, now) || stream(n, now))) return@synchronized null
n.lastReport = now
diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
index 39298f7..2b41804 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
@@ -193,6 +193,11 @@ class MonitorFrames {
return batch
}
+ fun emit(freshMs: Long, onFrame: (List<MonitorSighting>) -> Unit) {
+ val batch = drain(System.currentTimeMillis(), freshMs)
+ if (batch.isNotEmpty()) onFrame(batch)
+ }
+
/**
* Diagnostics: every device heard since the last call, strongest first, as
* "mac ssid ch N frames max/avg dBm"; resets the window.
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
index 99573e6..fbc3dcc 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7612uMonitor.kt
@@ -529,7 +529,7 @@ object Mt7612uMonitor {
st.lastRxAt = now
}
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -542,15 +542,10 @@ object Mt7612uMonitor {
st.hopAt = System.currentTimeMillis() // the dwell starts once the retune is done
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("MT7612U: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/** Where the 802.11 frame sits in a transfer and the radio's raw RSSI per chain (0 and 1, before calibration; null when absent). */
internal data class Rx(val start: Int, val end: Int, val rawRssi: Int?, val rawRssi1: Int? = null)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
index e293f4c..a56a1be 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Mt7921uMonitor.kt
@@ -639,7 +639,7 @@ object Mt7921uMonitor {
st.lastRxAt = now
}
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
// As the kernel does, a channel switch is only done once the firmware confirms it: the
// dwell is counted from that answer, so slow switches don't eat the listening time.
if (st.pendingSeq >= 0 && now - st.sentAt > SWITCH_TIMEOUT_MS) { st.unconfirmed++; st.pendingSeq = -1; st.hopAt = now }
@@ -664,15 +664,10 @@ object Mt7921uMonitor {
st.hopAt = now
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("MT7921AU: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
// ---- register access (mt76 usb.c: 32-bit address split over wValue / wIndex) ----
private fun ctl(type: Int, req: Int, value: Int, index: Int, data: ByteArray?, len: Int): Int {
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rt3070Monitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rt3070Monitor.kt
index f94a78b..0717134 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rt3070Monitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rt3070Monitor.kt
@@ -434,7 +434,7 @@ object Rt3070Monitor {
val (aps, clients) = frames.live(now, REPORT_MS)
"ch ${HOP[st.hopIdx]}, $aps access points, $clients devices, USB errors $ctlErrors"
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -445,15 +445,10 @@ object Rt3070Monitor {
st.hopAt = System.currentTimeMillis() // the dwell starts once the retune is done
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("RT3070: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/**
* Frames in one bulk transfer: | RXINFO (4) | RXWI (16) | 802.11 frame, padded | RXD (4) |,
* RXINFO giving the length up to RXD. Frames with a bad checksum are skipped; [onFrame]
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8187Monitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8187Monitor.kt
index d235ab5..c4ce3fb 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8187Monitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8187Monitor.kt
@@ -509,7 +509,7 @@ object Rtl8187Monitor {
val (aps, clients) = frames.live(now, REPORT_MS)
"ch ${HOP[st.hopIdx]}, $aps access points, $clients devices, USB errors $ctlErrors"
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -520,15 +520,10 @@ object Rtl8187Monitor {
st.hopAt = System.currentTimeMillis() // the dwell starts once the retune is done
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("RTL8187: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/** Where the 802.11 frame sits in a received transfer (FCS removed) and its signal in dBm. */
internal data class Rx(val start: Int, val end: Int, val rssi: Int)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
index f2c952a..c0c4375 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8812auMonitor.kt
@@ -14,14 +14,10 @@ package com.rfsentinel.app.usb
*/
import android.content.Context
-import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbManager
-import android.hardware.usb.UsbRequest
-import java.nio.ByteBuffer
-import java.util.concurrent.TimeoutException
object Rtl8812auMonitor {
@Volatile var running = false; private set
@@ -68,15 +64,10 @@ object Rtl8812auMonitor {
running = true; stop = false; frames.clear(); rfShadow.forEach { it.clear() }
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val conn = mgr.openDevice(device) ?: run { onStatus("RTL8812AU: couldn't reopen adapter"); running = false; return }
- var epRx: UsbEndpoint? = null
try {
val intf = device.getInterface(0)
BulkRx.claim("RTL8812AU", conn, intf) { stop }
- for (i in 0 until intf.endpointCount) {
- val ep = intf.getEndpoint(i)
- if (ep.type == UsbConstants.USB_ENDPOINT_XFER_BULK && ep.direction == UsbConstants.USB_DIR_IN) { epRx = ep; break }
- }
- val rx = epRx ?: run { UsbWifi.log("RTL8812AU: no bulk-IN endpoint"); onStatus("RTL8812AU: no RX endpoint"); return }
+ val rx = BulkRx.inEndpoint(intf) ?: run { UsbWifi.log("RTL8812AU: no bulk-IN endpoint"); onStatus("RTL8812AU: no RX endpoint"); return }
UsbWifi.log("=== RTL8812AU bring-up (rtl8812au) ===")
UsbWifi.log("RTL8812AU: RX EP=0x%02x".format(rx.address))
@@ -262,7 +253,7 @@ object Rtl8812auMonitor {
UsbWifi.log("RTL8812AU: RX ${st.bufs} bufs / ${st.total} B ch ${HOP[st.hopIdx]} | ${aps + clients} live ($aps AP · $clients client, ${frames.tracked} tracked)")
st.lastLog = now
}
- if (now - st.lastEmit > 2000) { emitSightings(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -276,72 +267,12 @@ object Rtl8812auMonitor {
private fun rxLoop(conn: UsbDeviceConnection, epRx: UsbEndpoint,
onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
- val nbuf = 24; val bufSz = 16384
- val buffers = Array(nbuf) { ByteBuffer.allocateDirect(bufSz) }
- val reqs = ArrayList<UsbRequest>(nbuf)
- var initOk = true
- for (i in 0 until nbuf) {
- val r = UsbRequest()
- if (!r.initialize(conn, epRx)) { initOk = false; break }
- r.clientData = i; buffers[i].clear()
- if (!r.queue(buffers[i])) { initOk = false; break }
- reqs.add(r)
- }
- if (!initOk) {
- UsbWifi.log("RTL8812AU: async RX unavailable (${reqs.size}/$nbuf) — synchronous RX")
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- rxLoopSync(conn, epRx, onFrame, onStatus); return
- }
- UsbWifi.log("RTL8812AU: async RX live — $nbuf buffers in flight")
- val scratch = ByteArray(bufSz)
val st = RxState().apply { start() }
- val guard = BulkRx.EmptyGuard("RTL8812AU")
- try {
- while (!stop) {
- val req = try { conn.requestWait(100L) } catch (e: TimeoutException) { null }
- val now = System.currentTimeMillis()
- if (req != null) {
- val idx = req.clientData as? Int ?: -1
- if (idx in 0 until nbuf) {
- val b = buffers[idx]
- val n = b.position()
- val parseLen = if (n in 1..bufSz) {
- st.total += n; st.bufs++; guard.data()
- b.rewind(); b.get(scratch, 0, n); n
- } else { guard.empty(); 0 }
-
- b.clear()
- if (!runCatching { req.queue(b) }.getOrDefault(false)) {
- runCatching { req.close() }
- val nr = UsbRequest()
- if (runCatching { nr.initialize(conn, epRx) }.getOrDefault(false)) {
- nr.clientData = idx; b.clear()
- if (runCatching { nr.queue(b) }.getOrDefault(false)) reqs[idx] = nr
- }
- }
- if (parseLen > 0) runCatching { st.frames += parseRxBuf(scratch, parseLen, HOP[st.hopIdx]) }
- }
- }
- rxTick(conn, now, st, onFrame, onStatus)
- }
- } finally {
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- }
- emitSightings(onFrame)
- UsbWifi.log("RTL8812AU: RX loop stopped (${st.total} B)")
- }
-
- private fun rxLoopSync(conn: UsbDeviceConnection, epRx: UsbEndpoint,
- onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
- val buf = ByteArray(16384)
- val st = RxState().apply { start() }
- while (!stop) {
- val n = conn.bulkTransfer(epRx, buf, buf.size, 500)
- val now = System.currentTimeMillis()
- if (n > 0) { st.total += n; st.bufs++; runCatching { st.frames += parseRxBuf(buf, n, HOP[st.hopIdx]) } }
- rxTick(conn, now, st, onFrame, onStatus)
- }
- emitSightings(onFrame)
+ BulkRx.run("RTL8812AU", conn, epRx, 24, 16384, { stop }, { b, n ->
+ st.total += n; st.bufs++
+ st.frames += parseRxBuf(b, n, HOP[st.hopIdx])
+ }, syncTimeoutMs = 500) { now -> rxTick(conn, now, st, onFrame, onStatus) }
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("RTL8812AU: RX loop stopped (${st.total} B)")
}
@@ -391,11 +322,6 @@ object Rtl8812auMonitor {
}
}
- private fun emitSightings(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
private fun r(conn: UsbDeviceConnection, addr: Int, len: Int): ByteArray {
val b = ByteArray(len)
return if (conn.controlTransfer(IN_VENDOR, VREQ, addr, 0, b, len, 500) == len) b else ByteArray(len)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
index a39de08..2c0da2d 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8814auMonitor.kt
@@ -207,7 +207,7 @@ object Rtl8814auMonitor {
val (aps, clients) = frames.live(now, REPORT_MS)
"ch ${HOP[st.hopIdx]}, $aps access points, $clients devices, USB errors $ctlErrors"
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
val lock = AntennaCheck.lockIndex(HOP) // antenna check: hold the reference's channel
if (lock >= 0 && lock == st.hopIdx) AntennaCheck.holding = HOP[lock]
if (if (lock >= 0) lock != st.hopIdx else now - st.hopAt > DWELL_MS) {
@@ -218,15 +218,10 @@ object Rtl8814auMonitor {
st.hopAt = System.currentTimeMillis() // the dwell starts once the retune is done
}
}
- emit(onFrame)
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("RTL8814AU: RX loop stopped ($total B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/**
* Frames in one bulk transfer, each | RX descriptor (24) | PHY status | shift | frame + FCS |,
* padded to 8 bytes. [onFrame] gets the 802.11 frame's [start, end) without the FCS, its
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
index 9279548..63d9ea5 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
@@ -13,14 +13,10 @@ package com.rfsentinel.app.usb
*/
import android.content.Context
-import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbManager
-import android.hardware.usb.UsbRequest
-import java.nio.ByteBuffer
-import java.util.concurrent.TimeoutException
object Rtl8821auMonitor {
@Volatile var running = false; private set
@@ -66,15 +62,10 @@ object Rtl8821auMonitor {
running = true; stop = false; frames.clear(); rfShadow.clear()
val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
val conn = mgr.openDevice(device) ?: run { onStatus("RTL8821AU: couldn't reopen adapter"); running = false; return }
- var epRx: UsbEndpoint? = null
try {
val intf = device.getInterface(0)
BulkRx.claim("RTL8821AU", conn, intf) { stop }
- for (i in 0 until intf.endpointCount) {
- val ep = intf.getEndpoint(i)
- if (ep.type == UsbConstants.USB_ENDPOINT_XFER_BULK && ep.direction == UsbConstants.USB_DIR_IN) { epRx = ep; break }
- }
- val rx = epRx ?: run { UsbWifi.log("RTL8821AU: no bulk-IN endpoint"); onStatus("RTL8821AU: no RX endpoint"); return }
+ val rx = BulkRx.inEndpoint(intf) ?: run { UsbWifi.log("RTL8821AU: no bulk-IN endpoint"); onStatus("RTL8821AU: no RX endpoint"); return }
UsbWifi.log("=== RTL8821AU bring-up (88xxau) ===")
UsbWifi.log("RTL8821AU: RX EP=0x%02x".format(rx.address))
@@ -192,7 +183,7 @@ object Rtl8821auMonitor {
UsbWifi.log("RTL8821AU: RX ${st.bufs} bufs / ${st.total} B ch ${HOP[st.hopIdx]} | ${aps + clients} live ($aps AP · $clients client, ${frames.tracked} tracked)")
st.lastLog = now
}
- if (now - st.lastEmit > 2000) { emitSightings(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
// Blinks while frames come in; steady on when the air is quiet (still running); dark when switched off.
if (now - st.ledAt >= BLINK_MS) {
val want = nextLight(lightEnabled, st.frames != st.ledFrames, st.ledOn)
@@ -212,72 +203,12 @@ object Rtl8821auMonitor {
private fun rxLoop(conn: UsbDeviceConnection, epRx: UsbEndpoint,
onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
- val nbuf = 24; val bufSz = 16384
- val buffers = Array(nbuf) { ByteBuffer.allocateDirect(bufSz) }
- val reqs = ArrayList<UsbRequest>(nbuf)
- var initOk = true
- for (i in 0 until nbuf) {
- val r = UsbRequest()
- if (!r.initialize(conn, epRx)) { initOk = false; break }
- r.clientData = i; buffers[i].clear()
- if (!r.queue(buffers[i])) { initOk = false; break }
- reqs.add(r)
- }
- if (!initOk) {
- UsbWifi.log("RTL8821AU: async RX unavailable (${reqs.size}/$nbuf) — synchronous RX")
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- rxLoopSync(conn, epRx, onFrame, onStatus); return
- }
- UsbWifi.log("RTL8821AU: async RX live — $nbuf buffers in flight")
- val scratch = ByteArray(bufSz)
- val st = RxState().apply { start() }
- val guard = BulkRx.EmptyGuard("RTL8821AU")
- try {
- while (!stop) {
- val req = try { conn.requestWait(100L) } catch (e: TimeoutException) { null }
- val now = System.currentTimeMillis()
- if (req != null) {
- val idx = req.clientData as? Int ?: -1
- if (idx in 0 until nbuf) {
- val b = buffers[idx]
- val n = b.position()
- val parseLen = if (n in 1..bufSz) {
- st.total += n; st.bufs++; guard.data()
- b.rewind(); b.get(scratch, 0, n); n
- } else { guard.empty(); 0 }
-
- b.clear()
- if (!runCatching { req.queue(b) }.getOrDefault(false)) {
- runCatching { req.close() }
- val nr = UsbRequest()
- if (runCatching { nr.initialize(conn, epRx) }.getOrDefault(false)) {
- nr.clientData = idx; b.clear()
- if (runCatching { nr.queue(b) }.getOrDefault(false)) reqs[idx] = nr
- }
- }
- if (parseLen > 0) runCatching { st.frames += parseRxBuf(scratch, parseLen, HOP[st.hopIdx]) }
- }
- }
- rxTick(conn, now, st, onFrame, onStatus)
- }
- } finally {
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- }
- emitSightings(onFrame)
- UsbWifi.log("RTL8821AU: RX loop stopped (${st.total} B)")
- }
-
- private fun rxLoopSync(conn: UsbDeviceConnection, epRx: UsbEndpoint,
- onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
- val buf = ByteArray(16384)
val st = RxState().apply { start() }
- while (!stop) {
- val n = conn.bulkTransfer(epRx, buf, buf.size, 500)
- val now = System.currentTimeMillis()
- if (n > 0) { st.total += n; st.bufs++; runCatching { st.frames += parseRxBuf(buf, n, HOP[st.hopIdx]) } }
- rxTick(conn, now, st, onFrame, onStatus)
- }
- emitSightings(onFrame)
+ BulkRx.run("RTL8821AU", conn, epRx, 24, 16384, { stop }, { b, n ->
+ st.total += n; st.bufs++
+ st.frames += parseRxBuf(b, n, HOP[st.hopIdx])
+ }, syncTimeoutMs = 500) { now -> rxTick(conn, now, st, onFrame, onStatus) }
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("RTL8821AU: RX loop stopped (${st.total} B)")
}
@@ -329,11 +260,6 @@ object Rtl8821auMonitor {
}
}
- private fun emitSightings(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
private fun r(conn: UsbDeviceConnection, addr: Int, len: Int): ByteArray {
val b = ByteArray(len)
return if (conn.controlTransfer(IN_VENDOR, VREQ, addr, 0, b, len, 500) == len) b else ByteArray(len)
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
index dcb372b..a9459a9 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
@@ -21,10 +21,7 @@ import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbManager
-import android.hardware.usb.UsbRequest
import java.io.IOException
-import java.nio.ByteBuffer
-import java.util.concurrent.TimeoutException
object Rtl8822buMonitor {
@Volatile var running = false; private set
@@ -167,7 +164,7 @@ object Rtl8822buMonitor {
UsbWifi.log("${st.label}: RX ${st.bufs} bufs / ${st.total} B ch ${st.channel} IGI 0x%02x FA ${chip.lastFa} | ${aps + clients} live ($aps AP · $clients client, ${frames.tracked} tracked)".format(chip.igi))
st.lastLog = now
}
- if (now - st.lastEmit > 2000) { emit(onFrame); st.lastEmit = now }
+ if (now - st.lastEmit > 2000) { frames.emit(FRESH_MS, onFrame); st.lastEmit = now }
if (!pathSense.decided && chip.rf2t2r) pathSense.verdict()?.let { path ->
pathSense.decided = true
val name = if (path == 1) "B" else "A"
@@ -233,68 +230,16 @@ object Rtl8822buMonitor {
private fun rxLoop(conn: UsbDeviceConnection, epRx: UsbEndpoint, chip: Chip, label: String,
onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
- // 16 KB buffers: the chip's RX aggregation is capped below that, so an aggregate
- // never spans two transfers (and some Android USB hosts never complete larger reads).
- val nbuf = 16; val bufSz = 16384
- val buffers = Array(nbuf) { ByteBuffer.allocateDirect(bufSz) }
- val reqs = ArrayList<UsbRequest>(nbuf)
- for (i in 0 until nbuf) {
- val r = UsbRequest()
- if (!r.initialize(conn, epRx)) { runCatching { r.close() }; break }
- r.clientData = i; buffers[i].clear()
- if (!r.queue(buffers[i])) { runCatching { r.close() }; break }
- reqs.add(r)
- }
+ // Keep aggregation inside one 16 KB transfer for Android USB hosts.
val st = RxState(label).apply { start() }
- if (reqs.size < nbuf) {
- UsbWifi.log("$label: async RX unavailable (${reqs.size}/$nbuf) — synchronous RX")
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- val buf = ByteArray(bufSz)
- while (!stop) {
- val n = conn.bulkTransfer(epRx, buf, buf.size, 100)
- if (n > 0) { st.total += n; st.bufs++; runCatching { parseRxBuf(buf, n, st.channel, chip.rf2t2r) } }
- rxTick(chip, System.currentTimeMillis(), st, onFrame, onStatus)
- }
- } else {
- UsbWifi.log("$label: async RX live — $nbuf buffers in flight")
- val scratch = ByteArray(bufSz)
- val guard = BulkRx.EmptyGuard(label)
- try {
- while (!stop) {
- val req = try { conn.requestWait(100L) } catch (e: TimeoutException) { null }
- if (req != null) {
- val idx = req.clientData as? Int ?: -1
- if (idx in 0 until nbuf) {
- val b = buffers[idx]
- val n = b.position()
- if (n in 1..bufSz) { st.total += n; st.bufs++; guard.data(); b.rewind(); b.get(scratch, 0, n) } else guard.empty()
- b.clear()
- if (!runCatching { req.queue(b) }.getOrDefault(false)) {
- runCatching { req.close() }
- val nr = UsbRequest()
- if (runCatching { nr.initialize(conn, epRx) }.getOrDefault(false)) {
- nr.clientData = idx
- if (runCatching { nr.queue(b) }.getOrDefault(false)) reqs[idx] = nr
- }
- }
- if (n in 1..bufSz) runCatching { parseRxBuf(scratch, n, st.channel, chip.rf2t2r) }
- }
- }
- rxTick(chip, System.currentTimeMillis(), st, onFrame, onStatus)
- }
- } finally {
- reqs.forEach { runCatching { it.cancel() }; runCatching { it.close() } }
- }
- }
- emit(onFrame)
+ BulkRx.run(label, conn, epRx, 16, 16384, { stop }, { b, n ->
+ st.total += n; st.bufs++
+ parseRxBuf(b, n, st.channel, chip.rf2t2r)
+ }, syncTimeoutMs = 100) { now -> rxTick(chip, now, st, onFrame, onStatus) }
+ frames.emit(FRESH_MS, onFrame)
UsbWifi.log("$label: RX loop stopped (${st.total} B)")
}
- private fun emit(onFrame: (List<MonitorSighting>) -> Unit) {
- val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
- if (batch.isNotEmpty()) onFrame(batch)
- }
-
/** One RX descriptor of an aggregated bulk-IN buffer (88xx layout, 24 bytes). */
internal class RxDesc(val pktLen: Int, val crcErr: Boolean, val drvInfo: Int, val shift: Int,
val physt: Boolean, val rate: Int, val c2h: Boolean) {