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.

USB WiFi: RTL8812BU / RTL8822BU monitor-mode driver; "External" filter

CIS-C01c414de4970c
diff --git a/app/src/main/assets/usbwifi/rtl8822b_agc_tab.bin b/app/src/main/assets/usbwifi/rtl8822b_agc_tab.bin
new file mode 100644
index 0000000..958477e
Binary files /dev/null and b/app/src/main/assets/usbwifi/rtl8822b_agc_tab.bin differ
diff --git a/app/src/main/assets/usbwifi/rtl8822b_fw.bin b/app/src/main/assets/usbwifi/rtl8822b_fw.bin
new file mode 100644
index 0000000..7ed1ab4
Binary files /dev/null and b/app/src/main/assets/usbwifi/rtl8822b_fw.bin differ
diff --git a/app/src/main/assets/usbwifi/rtl8822b_phy_reg.bin b/app/src/main/assets/usbwifi/rtl8822b_phy_reg.bin
new file mode 100644
index 0000000..88a46d0
Binary files /dev/null and b/app/src/main/assets/usbwifi/rtl8822b_phy_reg.bin differ
diff --git a/app/src/main/assets/usbwifi/rtl8822b_radioa.bin b/app/src/main/assets/usbwifi/rtl8822b_radioa.bin
new file mode 100644
index 0000000..7ec5e8b
Binary files /dev/null and b/app/src/main/assets/usbwifi/rtl8822b_radioa.bin differ
diff --git a/app/src/main/assets/usbwifi/rtl8822b_radiob.bin b/app/src/main/assets/usbwifi/rtl8822b_radiob.bin
new file mode 100644
index 0000000..6341958
Binary files /dev/null and b/app/src/main/assets/usbwifi/rtl8822b_radiob.bin differ
diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
index ae48801..4cde821 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
@@ -13,7 +13,7 @@ import com.rfsentinel.app.ui.DeviceFilter
/**
* A driver-safe list of nearby devices, filtered like the phone's chips
- * (Flagged, Trackers, Drones, Favorites, New, Bluetooth, WiFi, ESP32).
+ * (Flagged, Trackers, Drones, Favorites, New, Bluetooth, WiFi, External).
* Tapping a row opens its details.
*/
class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter) : LiveScreen(carContext) {
@@ -69,7 +69,7 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)
DeviceFilter.ALL -> "All nearby"
DeviceFilter.FLAGGED -> "Flagged nearby"
DeviceFilter.NEW -> "New devices"
- DeviceFilter.ESP32 -> "Heard by ESP32 / USB"
+ DeviceFilter.EXTERNAL -> "Heard by external hardware"
else -> f.label
}
@@ -79,7 +79,7 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)
f == DeviceFilter.TRACKERS -> "No trackers nearby"
f == DeviceFilter.DRONES -> "No drones nearby"
f == DeviceFilter.FAVORITES -> "No favorites nearby"
- f == DeviceFilter.ESP32 -> "Nothing from an ESP32 board or USB adapter - see More > Hardware"
+ f == DeviceFilter.EXTERNAL -> "Nothing from an ESP32 board or USB WiFi adapter - see More > Hardware"
f == DeviceFilter.ALL -> "Listening... no devices heard yet"
else -> "Nothing here right now"
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
index b6bc268..20b16d6 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
@@ -41,7 +41,7 @@ class HardwareScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
if (board == null) "Not paired (pair it in Settings on the phone)"
else "$board · " + OuiSpyBle.status.ifBlank { "connects while scanning" }, R.drawable.ic_car_usb),
Triple("USB WiFi adapter", UsbWifi.status.ifBlank {
- if (running) "None connected (RTL8811AU / 8821AU, e.g. ALFA AWUS036ACS)" else "Connects while scanning"
+ if (running) "None connected (RTL8811AU / 8821AU or RTL8812BU / 8822BU)" else "Connects while scanning"
}, R.drawable.ic_car_usb)
)
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
index 4f3820e..e1e738c 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
@@ -129,7 +129,7 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {
// 5. Everything nearby, filtered like the phone's chips.
rows += Row.Builder()
.setTitle("Nearby devices (${m.devices})")
- .addText("Flagged, trackers, drones, favorites, new, ESP32...")
+ .addText("Flagged, trackers, drones, favorites, new, external...")
.setImage(CarUi.icon(carContext, R.drawable.ic_car_drone))
.setBrowsable(true)
.setOnClickListener { screenManager.push(NearbyDevicesScreen(carContext)) }
diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
index 2d2feb4..9df7664 100644
--- a/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
@@ -48,7 +48,7 @@ class NearbyDevicesScreen(carContext: CarContext) : LiveScreen(carContext) {
DeviceFilter.FLAGGED -> R.drawable.ic_car_warning
DeviceFilter.TRACKERS, DeviceFilter.DRONES -> R.drawable.ic_car_drone
DeviceFilter.FAVORITES -> R.drawable.ic_car_star
- DeviceFilter.ESP32 -> R.drawable.ic_car_usb
+ DeviceFilter.EXTERNAL -> R.drawable.ic_car_usb
else -> R.drawable.ic_car_list
}
}
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 94e1160..14fd275 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt
@@ -107,7 +107,10 @@ object EspBoards {
@Synchronized
private fun stopBoard(name: String) {
running.remove(name)?.reader?.stop()
- if (running.isEmpty()) setStatus("ESP32 disconnected")
+ if (running.isEmpty()) {
+ setStatus("ESP32 disconnected")
+ if (!OuiSpyBle.connected) HeardBy.esp.clear()
+ }
}
private fun setStatus(s: String) {
diff --git a/app/src/main/java/com/rfsentinel/app/esp/OuiSpyBle.kt b/app/src/main/java/com/rfsentinel/app/esp/OuiSpyBle.kt
index 7756fd4..9aff7ba 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/OuiSpyBle.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/OuiSpyBle.kt
@@ -41,6 +41,9 @@ object OuiSpyBle {
private var relayAll = true
private var onSightings: ((List<EspSighting>) -> Unit)? = null
@Volatile private var active = false
+
+ /** An OUI-SPY board is set to run (its reports keep devices marked as heard by external hardware). */
+ val connected: Boolean get() = active
private var inSpool = false
private var discovering = false
private var live = false
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 ca8edd3..c3a1c81 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -881,6 +881,9 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.esp.EspBoards.stop(this)
com.rfsentinel.app.usb.UsbWifi.stop(this)
com.rfsentinel.app.esp.OuiSpyBle.stop()
+ // External hardware is gone with the scan: its "heard by" marks (External filter, badges) go too.
+ com.rfsentinel.app.esp.HeardBy.esp.clear()
+ com.rfsentinel.app.esp.HeardBy.usb.clear()
bleEngine.stop()
wifiEngine.stop()
if (btStateReceiverRegistered) {
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 be4ee2d..e04a8de 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -187,7 +187,7 @@ class SettingsActivity : AppCompatActivity() {
val s = com.rfsentinel.app.esp.EspBoards.status
binding.espStatusText.text = "ESP32 on USB (OUI-Spy, GhostESP or Marauder; also through a Flipper Zero): " +
s.ifBlank { "plug one in with an OTG cable while scanning to add its detections" }
- binding.usbWifiText.text = "USB WiFi adapter in monitor mode (RTL8811AU / 8821AU, e.g. ALFA AWUS036ACS): " +
+ binding.usbWifiText.text = "USB WiFi adapter in monitor mode (RTL8811AU / 8821AU such as the ALFA AWUS036ACS, or RTL8812BU / 8822BU): " +
com.rfsentinel.app.usb.UsbWifi.status.ifBlank { "plug one in with an OTG cable while scanning - longer range, and it hears devices connected to networks" }
val board = Prefs.ouiSpyBoard(this)
binding.ouiSpyText.text = if (board == null)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
index a0378a8..25b8c53 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
@@ -19,7 +19,8 @@ enum class DeviceFilter(val label: String) {
WIFI("WiFi"),
/** Cell towers: not devices, listed from the cell snapshot (list only, not the map). */
CELLS("Cells"),
- ESP32("ESP32");
+ /** Heard by external hardware: an ESP32 board (USB or OUI-SPY over Bluetooth) or a USB WiFi adapter. */
+ EXTERNAL("External");
fun matches(s: DeviceRegistry.Snapshot): Boolean = when (this) {
ALL -> true
@@ -29,7 +30,7 @@ enum class DeviceFilter(val label: String) {
DRONES -> s.hits.any { it.category == Category.DRONE } || s.remoteId != null
NEW -> s.isNew
CELLS -> false
- ESP32 -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac)
+ EXTERNAL -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac)
FAVORITES -> Favorites.contains(s.mac)
BLE -> Advert.Source.BLE in s.sources
WIFI -> Advert.Source.WIFI in s.sources
diff --git a/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
new file mode 100644
index 0000000..dbd1dda
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/usb/MonitorFrames.kt
@@ -0,0 +1,165 @@
+package com.rfsentinel.app.usb
+
+/**
+ * Access points and client devices heard by a USB WiFi adapter in monitor mode,
+ * built from raw 802.11 frames. Shared by the USB WiFi drivers; not thread-safe
+ * (each driver feeds it from its own RX thread).
+ */
+class MonitorFrames {
+ /** Also report client devices (probe requests, data frames), not just access points. */
+ @Volatile var captureClients = true
+
+ private class Sighting(val mac: String, var isAp: Boolean) {
+ var ssid: String? = null; var bssid: String? = null
+ var rssi = NOMINAL_RSSI; var rssiAt = 0L; var measured = false; var channel = 0
+ var lastSeen = 0L
+ // Per-window counters for driver diagnostics (debug builds).
+ var winHits = 0; var winMeasured = 0; var winMax = -128; var winSum = 0L
+ var winOfdm = 0; var winA = -128; var winB = -128
+ }
+
+ private val sightings = LinkedHashMap<String, Sighting>()
+
+ val tracked: Int get() = sightings.size
+
+ fun clear() = sightings.clear()
+
+ /**
+ * One received 802.11 frame in [b] from [d] to [end] (exclusive), heard while tuned
+ * to [channel] at [rssi] dBm. Beacons and probe responses carry their own channel,
+ * which wins over the tuned one (a strong access point leaks into neighbouring
+ * channels, and a frame can arrive just after a hop). [rssi] is null when the
+ * frame carried no usable signal report: the device keeps its last reading.
+ */
+ fun frame(b: ByteArray, d: Int, end: Int, channel: Int, rssi: Int?, now: Long = System.currentTimeMillis(),
+ pathA: Int? = null, pathB: Int? = null) {
+ if (end - d < 24 || end > b.size) return
+ fun u8(i: Int) = b[i].toInt() and 0xff
+ val fc = u8(d); val ftype = (fc shr 2) and 3; val sub = (fc shr 4) and 0xf
+ val fc1 = u8(d + 1); val toDs = fc1 and 0x01; val fromDs = (fc1 shr 1) and 0x01
+ val a1 = d + 4; val a2 = d + 10; val a3 = d + 16
+ fun touch(at: Int, ap: Boolean, ch: Int = channel): Sighting? {
+ if (!isReal(b, at)) return null
+ val m = mac(b, at)
+ val s = sightings.getOrPut(m) { Sighting(m, ap) }
+ // Strongest reading of the last couple of seconds, so a device that drove off fades.
+ if (rssi != null && (!s.measured || rssi > s.rssi || now - s.rssiAt > RSSI_WINDOW_MS)) {
+ s.rssi = rssi; s.rssiAt = now; s.measured = true
+ }
+ s.channel = ch; s.lastSeen = now
+ s.winHits++
+ if (rssi != null) { s.winMeasured++; s.winSum += rssi; if (rssi > s.winMax) s.winMax = rssi }
+ if (pathA != null || pathB != null) {
+ s.winOfdm++
+ pathA?.let { if (it > s.winA) s.winA = it }; pathB?.let { if (it > s.winB) s.winB = it }
+ }
+ return s
+ }
+ when (ftype) {
+ 0 -> when (sub) {
+ // Beacon or probe response: an access point.
+ 8, 5 -> if (d + 36 <= end) {
+ val ies = Ies.read(b, d + 36, end)
+ touch(a3, ap = true, ch = ies.channel.takeIf { validChannel(it) } ?: channel)?.let {
+ it.isAp = true
+ if (ies.ssid != null && it.ssid == null) it.ssid = ies.ssid
+ }
+ }
+ // Probe request: a device looking for networks (e.g. a laptop or a Flock camera).
+ 4 -> if (captureClients) touch(a2, ap = false)
+ 0, 2, 10, 11, 12 -> if (captureClients) touch(a2, ap = false)?.let { it.bssid = mac(b, a3) }
+ }
+ 2 -> if (captureClients) when {
+ toDs == 1 && fromDs == 0 -> touch(a2, ap = false)?.let { it.bssid = mac(b, a1) }
+ toDs == 0 && fromDs == 1 -> touch(a1, ap = false)?.let { it.bssid = mac(b, a2) }
+ else -> touch(a2, ap = false)
+ }
+ }
+ }
+
+ /** Access points and client devices heard within [windowMs]. */
+ fun live(now: Long, windowMs: Long): Pair<Int, Int> {
+ var aps = 0; var clients = 0
+ for (s in sightings.values) if (now - s.lastSeen < windowMs) { if (s.isAp) aps++ else clients++ }
+ return aps to clients
+ }
+
+ /** Everything heard within [freshMs], for the app; forgets what hasn't been heard for [pruneMs]. */
+ fun drain(now: Long, freshMs: Long, pruneMs: Long = PRUNE_MS): List<MonitorSighting> {
+ val batch = sightings.values.filter { now - it.lastSeen < freshMs }.map { s ->
+ MonitorSighting(
+ mac = s.mac,
+ ssid = s.ssid,
+ rssi = s.rssi.coerceIn(-120, -20),
+ frequencyMhz = frequencyOf(s.channel),
+ isAccessPoint = s.isAp,
+ bssid = s.bssid
+ )
+ }
+ sightings.entries.removeAll { now - it.value.lastSeen > pruneMs }
+ return batch
+ }
+
+ /**
+ * Diagnostics: every device heard since the last call, strongest first, as
+ * "mac ssid ch N frames max/avg dBm"; resets the window.
+ */
+ fun window(limit: Int = 12): List<String> {
+ val heard = sightings.values.filter { it.winHits > 0 }.sortedByDescending { it.winMax }
+ val out = heard.take(limit).map { s ->
+ "%s %-14s ch %3d %3d fr max %4d avg %4d%s%s".format(s.mac, (s.ssid ?: "").take(14), s.channel, s.winHits,
+ s.winMax, if (s.winMeasured > 0) (s.winSum / s.winMeasured).toInt() else 0, if (s.isAp) " AP" else "",
+ if (s.winOfdm > 0) " | OFDM %d: path A %d, B %d".format(s.winOfdm, s.winA, s.winB) else "")
+ }
+ for (s in sightings.values) { s.winHits = 0; s.winMeasured = 0; s.winMax = -128; s.winSum = 0; s.winOfdm = 0; s.winA = -128; s.winB = -128 }
+ return out
+ }
+
+ /** Network name and channel from a management frame's information elements. */
+ data class Ies(val ssid: String?, val channel: Int) {
+ companion object {
+ fun read(b: ByteArray, from: Int, end: Int): Ies {
+ var ssid: String? = null; var ds = 0; var ht = 0
+ var i = from
+ while (i + 2 <= end) {
+ val tag = b[i].toInt() and 0xff; val tl = b[i + 1].toInt() and 0xff
+ if (i + 2 + tl > end) break
+ when (tag) {
+ 0 -> if (ssid == null) ssid = String(b, i + 2, tl, Charsets.UTF_8).trim { it <= ' ' }
+ 3 -> if (tl >= 1) ds = b[i + 2].toInt() and 0xff // DS parameter set (2.4 GHz)
+ 61 -> if (tl >= 1) ht = b[i + 2].toInt() and 0xff // HT operation: primary channel
+ }
+ i += 2 + tl
+ }
+ return Ies(ssid, if (ds != 0) ds else ht)
+ }
+ }
+ }
+
+ companion object {
+ const val PRUNE_MS = 60_000L
+ /** Reported for a device whose frames never carried a signal reading. */
+ const val NOMINAL_RSSI = -60
+ private const val RSSI_WINDOW_MS = 2_000L
+
+ fun validChannel(ch: Int) = ch in 1..14 || ch in 32..177
+
+ /** Centre frequency of a 20 MHz WiFi channel, 0 when unknown. */
+ fun frequencyOf(ch: Int): Int = when (ch) {
+ in 1..13 -> 2407 + ch * 5
+ 14 -> 2484
+ in 32..177 -> 5000 + ch * 5
+ else -> 0
+ }
+
+ private fun mac(b: ByteArray, at: Int) = (at until at + 6).joinToString(":") { "%02x".format(b[it].toInt() and 0xff) }
+
+ /** Not broadcast, empty or a multicast group address. */
+ private fun isReal(b: ByteArray, at: Int): Boolean {
+ val m0 = b[at].toInt() and 0xff
+ if (m0 and 0x01 != 0) return false // group address (broadcast, IPv4/IPv6 multicast, STP...)
+ for (k in 0 until 6) if (b[at + k].toInt() != 0) return true
+ return false
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
index f8e90dc..b729c0b 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
+++ b/app/src/main/java/com/rfsentinel/app/usb/NOTICE.md
@@ -1,15 +1,20 @@
-# USB WiFi monitor-mode driver: sources and licenses
+# USB WiFi monitor-mode drivers: sources and licenses
-`Rtl8821auMonitor.kt` and `Rtl8821auTables.kt` drive Realtek RTL8811AU / RTL8821AU
-USB WiFi adapters (e.g. ALFA AWUS036ACS) in receive-only monitor mode from userspace.
+These drivers run USB WiFi adapters in receive-only monitor mode from userspace.
+
+- `Rtl8821auMonitor.kt` and `Rtl8821auTables.kt` drive Realtek RTL8811AU / RTL8821AU adapters (e.g. ALFA AWUS036ACS).
+- `Rtl8822buMonitor.kt` and `Rtl8822bTables.kt` drive Realtek RTL8812BU / RTL8822BU adapters, with the firmware and register tables in `assets/usbwifi/rtl8822b_*.bin`.
+- `MonitorFrames.kt` turns the received 802.11 frames into access points and client devices for both drivers.
| Part | Origin | License |
|---|---|---|
-| Register tables (power-on sequence, MAC / BB / AGC / RF tables, channel tuning) | Realtek 88xxau Linux driver, as maintained in [aircrack-ng/rtl8812au](https://github.com/aircrack-ng/rtl8812au) | GPL-2.0 |
-| Userspace USB driver and 802.11 frame parsing | [Wardrive Go](https://github.com/RocketGod-git/wardrive-go) by RocketGod | GPL-3.0 |
-| Integration into RF Sentinel, removal of handshake / PMKID capture | RF Sentinel (CIS-C0) | GPL-3.0 |
+| RTL8811AU / 8821AU register tables (power-on sequence, MAC / BB / AGC / RF tables, channel tuning) | Realtek 88xxau Linux driver, as maintained in [aircrack-ng/rtl8812au](https://github.com/aircrack-ng/rtl8812au) | GPL-2.0 |
+| RTL8811AU / 8821AU userspace USB driver and 802.11 frame parsing | [Wardrive Go](https://github.com/RocketGod-git/wardrive-go) by RocketGod | GPL-3.0 |
+| RTL8812BU / 8822BU bring-up (power sequence, HalMAC firmware download, MAC init, channel tuning, gain control, RX descriptor parsing) | [devourer](https://github.com/OpenIPC/devourer) by OpenIPC, `src/jaguar2/` | GPL-2.0 |
+| RTL8822B firmware image and phydm BB / AGC / RF tables | Realtek rtl88x2bu Linux driver, as extracted by devourer | Realtek firmware / GPL-2.0 |
+| Integration into RF Sentinel; removal of handshake / PMKID capture (8821AU) and of every transmit, beamforming and calibration-for-TX path (8822BU) | RF Sentinel (CIS-C0) | GPL-3.0 |
RF Sentinel is distributed under the GNU GPL v3.0 (see `LICENSE`). The register
-values are hardware configuration data taken from Realtek's GPL driver; credit
-and thanks to Realtek and the aircrack-ng rtl8812au maintainers, and to RocketGod
-for Wardrive Go.
+values and firmware are hardware configuration data from Realtek's driver; credit
+and thanks to Realtek, the aircrack-ng rtl8812au maintainers, RocketGod for
+Wardrive Go, and OpenIPC for devourer.
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 d9efb23..7d67c11 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8821auMonitor.kt
@@ -25,23 +25,14 @@ import java.util.concurrent.TimeoutException
object Rtl8821auMonitor {
@Volatile var running = false; private set
@Volatile private var stop = false
- @Volatile var captureClients = true
- private class Sighting(val mac: String, var isAp: Boolean) {
- var ssid: String? = null; var bssid: String? = null
- var rssi = -128; var channel = 0
- var good = false; var hits = 0; var lastSeen = 0L
- fun trusted() = good || hits >= 2
- }
- private val sightings = LinkedHashMap<String, Sighting>()
+ private val frames = MonitorFrames()
private val HOP = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
private const val DWELL_MS = 350L
private val FRESH_MS get() = (HOP.size * DWELL_MS * 9 / 5).coerceAtLeast(3000L)
- private const val PRUNE_MS = 60_000L
private const val REPORT_MS = 10_000L
private const val NOMINAL_RSSI = -60
- private fun freqOf(ch: Int) = 2407 + ch * 5
private const val OUT_VENDOR = 0x40; private const val IN_VENDOR = 0xC0
private const val VREQ = 0x05
@@ -56,7 +47,7 @@ object Rtl8821auMonitor {
fun run(ctx: Context, device: UsbDevice, onStatus: (String) -> Unit,
onFrame: (List<MonitorSighting>) -> Unit) {
if (running) return
- running = true; stop = false; sightings.clear(); rfShadow.clear()
+ 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
@@ -164,18 +155,16 @@ object Rtl8821auMonitor {
private fun rxTick(conn: UsbDeviceConnection, now: Long, st: RxState,
onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
if (now - st.lastLog > 3000) {
- val shown = sightings.values.filter { it.trusted() && now - it.lastSeen < REPORT_MS }
- val aps = shown.count { it.isAp }
- UsbWifi.log("RTL8821AU: RX ${st.bufs} bufs / ${st.total} B ch ${HOP[st.hopIdx]} | ${shown.size} live ($aps AP · ${shown.size - aps} client, ${sightings.size} tracked)")
+ val (aps, clients) = frames.live(now, REPORT_MS)
+ 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.hopAt > DWELL_MS) {
val ni = (st.hopIdx + 1) % HOP.size
if (ni != st.hopIdx) { st.hopIdx = ni; runCatching { channelTune(conn, HOP[st.hopIdx]) } }
- val shown = sightings.values.filter { it.trusted() && now - it.lastSeen < REPORT_MS }
- val aps = shown.count { it.isAp }
- onStatus("RTL8811AU / 8821AU · live · $aps access points · ${shown.size - aps} devices · ch ${HOP[st.hopIdx]}")
+ val (aps, clients) = frames.live(now, REPORT_MS)
+ onStatus("RTL8811AU / 8821AU · live · $aps access points · $clients devices · ch ${HOP[st.hopIdx]}")
st.hopAt = now
}
}
@@ -265,58 +254,12 @@ object Rtl8821auMonitor {
if (crc == 0 && fe - fs >= 24) {
val rate = b[off + 12].toInt() and 0x7f
val rssi = if (drv >= 8 && off + size + drv <= n) rtlRssi(b, off + size, rate) else NOMINAL_RSSI
- parse80211(b, fs, fe, ch, rssi)
+ frames.frame(b, fs, fe, ch, rssi)
}
off += (size + drv + shift + pkt + 7) and 7.inv()
}
}
- private fun parse80211(b: ByteArray, d: Int, end: Int, ch: Int, rssi: Int) {
- fun u8(i: Int) = b[i].toInt() and 0xff
- val fc = u8(d); val ftype = (fc shr 2) and 3; val sub = (fc shr 4) and 0xf
- val fc1 = u8(d + 1); val toDs = fc1 and 0x01; val fromDs = (fc1 shr 1) and 0x01
- val a1 = d + 4; val a2 = d + 10; val a3 = d + 16
- fun mac(at: Int) = (at until at + 6).joinToString(":") { "%02x".format(u8(it)) }
- fun isReal(m: String) = m != "ff:ff:ff:ff:ff:ff" && m != "00:00:00:00:00:00" &&
- !m.startsWith("01:00:5e") && !m.startsWith("33:33") && !m.startsWith("01:80:c2")
- fun readSsid(from: Int): String? {
- var i = from
- while (i + 2 <= end) {
- val tag = u8(i); val tl = u8(i + 1)
- if (i + 2 + tl > end) break
- if (tag == 0) return String(b, i + 2, tl, Charsets.UTF_8).trim { it <= ' ' }
- i += 2 + tl
- }
- return null
- }
- fun touch(m: String, ap: Boolean): Sighting? {
- if (!isReal(m)) return null
- val s = sightings.getOrPut(m) { Sighting(m, ap) }
- s.hits++; s.good = true
- if (rssi > s.rssi) s.rssi = rssi
- s.channel = ch; s.lastSeen = System.currentTimeMillis()
- return s
- }
- when (ftype) {
- 0 -> when (sub) {
- 8, 5 -> if (d + 36 <= end) {
- val ssid = readSsid(d + 36)
- touch(mac(a3), ap = true)?.let { if (ssid != null && it.ssid == null) it.ssid = ssid }
- }
- // Probe request: a device looking for networks (e.g. a laptop or a Flock camera).
- 4 -> if (captureClients) touch(mac(a2), ap = false)
- 0, 2, 10, 11, 12 -> if (captureClients) touch(mac(a2), ap = false)?.let { it.bssid = mac(a3) }
- }
- 2 -> {
- if (captureClients) when {
- toDs == 1 && fromDs == 0 -> touch(mac(a2), ap = false)?.let { it.bssid = mac(a1) }
- toDs == 0 && fromDs == 1 -> touch(mac(a1), ap = false)?.let { it.bssid = mac(a2) }
- else -> touch(mac(a2), ap = false)
- }
- }
- }
- }
-
private fun rtlRssi(b: ByteArray, di: Int, rate: Int): Int {
fun u8(i: Int) = b[i].toInt() and 0xff
return if (rate <= 3) {
@@ -337,18 +280,7 @@ object Rtl8821auMonitor {
}
private fun emitSightings(onFrame: (List<MonitorSighting>) -> Unit) {
- val now = System.currentTimeMillis()
- val batch = sightings.values.filter { it.trusted() && now - it.lastSeen < FRESH_MS }.map { s ->
- MonitorSighting(
- mac = s.mac,
- ssid = s.ssid,
- rssi = s.rssi.coerceIn(-120, -20),
- frequencyMhz = if (s.channel > 0) freqOf(s.channel) else 0,
- isAccessPoint = s.isAp,
- bssid = s.bssid
- )
- }
- sightings.entries.removeAll { now - it.value.lastSeen > PRUNE_MS }
+ val batch = frames.drain(System.currentTimeMillis(), FRESH_MS)
if (batch.isNotEmpty()) onFrame(batch)
}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822bTables.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822bTables.kt
new file mode 100644
index 0000000..75ca64e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822bTables.kt
@@ -0,0 +1,128 @@
+package com.rfsentinel.app.usb
+
+/*
+ * RTL8822B (RTL8812BU / RTL8822BU) firmware, power sequences and phydm register
+ * tables for receive-only monitor mode over USB.
+ *
+ * The firmware image and the BB / AGC / RF tables ship as binary assets
+ * (assets/usbwifi/rtl8822b_*.bin, little-endian), extracted from devourer
+ * (OpenIPC, https://github.com/OpenIPC/devourer, GPL-2.0), which takes them from
+ * Realtek's rtl88x2bu Linux driver. The power sequences and the table walker are
+ * ported from devourer's src/jaguar2/HalJaguar2.cpp and src/PhyTableLoader.cpp.
+ */
+
+import android.content.Context
+import java.io.IOException
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+object Rtl8822bTables {
+
+ class Data(val firmware: ByteArray, val phyReg: IntArray, val agcTab: IntArray, val radioA: IntArray, val radioB: IntArray)
+
+ fun load(ctx: Context): Data {
+ fun bytes(name: String) = ctx.assets.open("usbwifi/rtl8822b_$name.bin").use { it.readBytes() }
+ fun words(name: String): IntArray {
+ val b = bytes(name)
+ if (b.size % 8 != 0) throw IOException("rtl8822b_$name.bin is damaged")
+ return IntArray(b.size / 4).also { ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(it) }
+ }
+ val fw = bytes("fw")
+ checkFirmware(fw)
+ return Data(fw, words("phy_reg"), words("agc_tab"), words("radioa"), words("radiob"))
+ }
+
+ // --- Firmware header (HalMAC WLAN_FW_HDR_*) ---
+ const val FW_HDR_SIZE = 64
+ const val FW_CHKSUM_SIZE = 8
+
+ fun le32(b: ByteArray, i: Int) = (b[i].toInt() and 0xff) or ((b[i + 1].toInt() and 0xff) shl 8) or
+ ((b[i + 2].toInt() and 0xff) shl 16) or ((b[i + 3].toInt() and 0xff) shl 24)
+
+ fun dmemSize(fw: ByteArray) = le32(fw, 36) + FW_CHKSUM_SIZE
+ fun imemSize(fw: ByteArray) = le32(fw, 48) + FW_CHKSUM_SIZE
+ fun ememSize(fw: ByteArray) = if (fw[24].toInt() and 0x10 != 0) le32(fw, 52) + FW_CHKSUM_SIZE else 0
+ fun dmemAddr(fw: ByteArray) = le32(fw, 32) and 0x7fffffff
+ fun imemAddr(fw: ByteArray) = le32(fw, 60) and 0x7fffffff
+ fun ememAddr(fw: ByteArray) = le32(fw, 56) and 0x7fffffff
+ fun version(fw: ByteArray) = "${(fw[4].toInt() and 0xff) or ((fw[5].toInt() and 0xff) shl 8)}.${fw[6].toInt() and 0xff}"
+
+ /** The image's declared section sizes must add up to its length (HalMAC chk_fw_size). */
+ fun checkFirmware(fw: ByteArray) {
+ if (fw.size < FW_HDR_SIZE || FW_HDR_SIZE + dmemSize(fw) + imemSize(fw) + ememSize(fw) != fw.size)
+ throw IOException("RTL8822B firmware image is damaged")
+ }
+
+ // --- Power sequences: {offset, command, mask, value} (halmac_pwr_seq_8822b.c, USB + all-interface rows) ---
+ const val PW = 0; const val PP = 1; const val PD = 2
+
+ /** card_en_flow_8822b: card-disable -> card-emulation -> active. */
+ val PWR_ON = arrayOf(
+ intArrayOf(0x004A, PW, 0x01, 0), intArrayOf(0x0005, PW, 0x98, 0),
+ intArrayOf(0xFF0A, PW, 0xFF, 0), intArrayOf(0xFF0B, PW, 0xFF, 0),
+ intArrayOf(0x0012, PW, 0x02, 0), intArrayOf(0x0012, PW, 0x01, 0x01),
+ intArrayOf(0x0020, PW, 0x01, 0x01), intArrayOf(0x0001, PD, 0, 1),
+ intArrayOf(0x0000, PW, 0x20, 0), intArrayOf(0x0005, PW, 0x1C, 0),
+ intArrayOf(0x0006, PP, 0x02, 0x02), intArrayOf(0xFF1A, PW, 0xFF, 0),
+ intArrayOf(0x0006, PW, 0x01, 0x01), intArrayOf(0x0005, PW, 0x80, 0),
+ intArrayOf(0x0005, PW, 0x18, 0), intArrayOf(0x10C3, PW, 0x01, 0x01),
+ intArrayOf(0x0005, PW, 0x01, 0x01), intArrayOf(0x0005, PP, 0x01, 0),
+ intArrayOf(0x0020, PW, 0x08, 0x08),
+ intArrayOf(0x10A8, PW, 0xFF, 0), intArrayOf(0x10A9, PW, 0xFF, 0xEF), intArrayOf(0x10AA, PW, 0xFF, 0x0C),
+ intArrayOf(0x0029, PW, 0xFF, 0xF9), intArrayOf(0x0024, PW, 0x04, 0),
+ intArrayOf(0x00AF, PW, 0x20, 0x20)
+ )
+
+ /** card_dis_flow_8822b: active -> card-emulation -> card-disable. */
+ val PWR_OFF = arrayOf(
+ intArrayOf(0x0093, PW, 0xFF, 0xC4), intArrayOf(0x001F, PW, 0xFF, 0),
+ intArrayOf(0x00EF, PW, 0xFF, 0), intArrayOf(0xFF1A, PW, 0xFF, 0x30),
+ intArrayOf(0x0049, PW, 0x02, 0), intArrayOf(0x0006, PW, 0x01, 0x01),
+ intArrayOf(0x0002, PW, 0x02, 0), intArrayOf(0x10C3, PW, 0x01, 0),
+ intArrayOf(0x0005, PW, 0x02, 0x02), intArrayOf(0x0005, PP, 0x02, 0),
+ intArrayOf(0x0020, PW, 0x08, 0), intArrayOf(0x0000, PW, 0x20, 0x20),
+ intArrayOf(0x0007, PW, 0xFF, 0x20), intArrayOf(0x0067, PW, 0x20, 0),
+ intArrayOf(0x004A, PW, 0x01, 0), intArrayOf(0x0081, PW, 0xC0, 0),
+ intArrayOf(0x0005, PW, 0x18, 0x08), intArrayOf(0x0090, PW, 0x02, 0)
+ )
+
+ // --- phydm table walker (check_positive + IF / ELSE_IF / ELSE / ENDIF blocks) ---
+
+ private const val ITRF_USB = 0x02
+ private const val PLATFORM_CE = 0x04
+
+ /** Whether a conditional block's selector [c1] matches this chip's cut and RFE type. */
+ fun checkPositive(c1: Int, cut: Int, rfe: Int): Boolean {
+ val cutForPara = if (cut == 0) 15 else cut
+ val pkgForPara = 15 // package type unknown
+ val driver1 = (cutForPara shl 24) or ((ITRF_USB and 0xF0) shl 16) or (PLATFORM_CE shl 16) or
+ (pkgForPara shl 12) or ((ITRF_USB and 0x0F) shl 8) or (rfe and 0xff)
+ if (c1 and 0x0F000000 != 0 && c1 and 0x0F000000 != driver1 and 0x0F000000) return false
+ if (c1 and 0x0000F000 != 0 && c1 and 0x0000F000 != driver1 and 0x0000F000) return false
+ if (c1 and 0x00000F00 != 0 && c1 and 0x00000F00 != driver1 and 0x00000F00) return false
+ return (c1 and 0xFF) == (driver1 and 0xFF)
+ }
+
+ /** Calls [write] for every (address, value) pair of [table] that applies to this chip. */
+ inline fun walk(table: IntArray, cut: Int, rfe: Int, write: (Int, Int) -> Unit) {
+ var matched = true; var skipped = false; var preV1 = 0
+ var i = 0
+ while (i + 1 < table.size) {
+ val v1 = table[i]; val v2 = table[i + 1]
+ if (v1 and 0xC0000000.toInt() != 0) {
+ if (v1 < 0) { // positive half: IF / ELSE_IF / ELSE / ENDIF
+ when ((v1 ushr 28) and 3) {
+ 3 -> { matched = true; skipped = false }
+ 2 -> matched = !skipped
+ else -> preV1 = v1
+ }
+ } else { // negative half completes an IF / ELSE_IF
+ if (!skipped) {
+ if (checkPositive(preV1, cut, rfe)) { matched = true; skipped = true } else { matched = false }
+ } else matched = false
+ }
+ } else if (matched) write(v1, v2)
+ i += 2
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
new file mode 100644
index 0000000..69c040b
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/usb/Rtl8822buMonitor.kt
@@ -0,0 +1,1181 @@
+package com.rfsentinel.app.usb
+
+/*
+ * Receive-only monitor mode for Realtek RTL8812BU / RTL8822BU (88x2bu, "Jaguar2")
+ * USB WiFi adapters, driven from userspace over Android's USB host API - no root,
+ * no kernel driver. Hops the 2.4 and 5 GHz channels and reports the access points
+ * and client devices it hears. It never transmits 802.11 frames: the only bulk-OUT
+ * traffic is the chip's own firmware download and two configuration messages to
+ * that firmware (rfe type, cut, antenna paths).
+ *
+ * Bring-up, channel tuning, gain control and RX descriptor parsing are ported from
+ * devourer (OpenIPC, https://github.com/OpenIPC/devourer, GPL-2.0), src/jaguar2/:
+ * RtlJaguar2Device, HalJaguar2, HalmacJaguar2MacInit, HalmacJaguar2Fw and
+ * FrameParserJaguar2. devourer's TX, beamforming, calibration-for-TX, IQK and
+ * narrowband code is not included.
+ */
+
+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.io.IOException
+import java.nio.ByteBuffer
+import java.util.concurrent.TimeoutException
+
+object Rtl8822buMonitor {
+ @Volatile var running = false; private set
+ @Volatile private var stop = false
+
+ private val frames = MonitorFrames()
+ private val pathSense = PathSense()
+
+ /**
+ * Finds which receive path has the antenna. Single-antenna dongles wire only one of
+ * the chip's two paths (the Wise Tiger 8812BU uses path B), but the chip receives
+ * 2.4 GHz CCK frames - most 2.4 GHz beacons - on path A only, so they arrive ~30 dB
+ * weak. OFDM frames report both paths' power; when one path is consistently far
+ * stronger, CCK is moved to it. Two-antenna adapters never reach a verdict.
+ */
+ internal class PathSense {
+ var aVotes = 0; private set
+ var bVotes = 0; private set
+ var decided = false
+
+ fun add(a: Int, b: Int) {
+ if (decided || maxOf(a, b) < -95) return
+ if (b - a >= GAP_DB) bVotes++ else if (a - b >= GAP_DB) aVotes++
+ }
+
+ /** 0 = path A, 1 = path B, null while undecided or when both paths have antennas. */
+ fun verdict(): Int? {
+ val n = aVotes + bVotes
+ if (n < MIN_VOTES) return null
+ return when {
+ bVotes >= n * 0.85 -> 1
+ aVotes >= n * 0.85 -> 0
+ else -> null
+ }
+ }
+
+ fun reset() { aVotes = 0; bVotes = 0; decided = false }
+
+ companion object {
+ const val GAP_DB = 10
+ const val MIN_VOTES = 40
+ }
+ }
+
+ /** 2.4 GHz channels, every cycle. */
+ internal val HOP_24 = IntArray(13) { it + 1 }
+ /** 5 GHz channels without radar rules, every cycle (where vehicle and mobile routers usually sit). */
+ internal val HOP_5 = intArrayOf(36, 40, 44, 48, 149, 153, 157, 161, 165)
+ /** 5 GHz radar (DFS) channels, two per cycle. */
+ internal val HOP_DFS = intArrayOf(52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144)
+
+ /** Channels of hop cycle [k]: all of 2.4 GHz, the common 5 GHz ones and two radar channels in turn. */
+ internal fun hopCycle(k: Int): IntArray {
+ val n = HOP_DFS.size
+ val i = Math.floorMod(2 * k, n)
+ return HOP_24 + HOP_5 + intArrayOf(HOP_DFS[i], HOP_DFS[(i + 1) % n])
+ }
+
+ private const val DWELL_MS = 200L
+ private val CYCLE_MS = hopCycle(0).size * DWELL_MS
+ private val FRESH_MS = CYCLE_MS * 9 / 5
+ private const val REPORT_MS = 10_000L
+ private const val DIG_MS = 200L
+
+ fun abort() { stop = true }
+
+ /**
+ * Debug builds: commands sent with adb (see [UsbWifi]), run on the RX thread -
+ * `park <ch>`, `hop`, `igi <hex>`, `dig`, `stats`, `rd <addr>`, `w8|w32 <addr> <val>`,
+ * `bb <addr> <mask> <val>`, `rfrd <path> <addr>`, `rf <path> <addr> <mask> <val>` (hex).
+ */
+ internal val commands = java.util.concurrent.ConcurrentLinkedQueue<String>()
+
+ fun run(ctx: Context, device: UsbDevice, label: String, onStatus: (String) -> Unit,
+ onFrame: (List<MonitorSighting>) -> Unit) {
+ // A previous session that was just told to stop gets a moment to power the chip down.
+ val wait = System.currentTimeMillis() + 3000
+ while (running && System.currentTimeMillis() < wait) sleep(50)
+ if (running) { onStatus("$label: previous session still stopping, replug the adapter"); return }
+ running = true; stop = false; frames.clear(); pathSense.reset()
+ val mgr = ctx.getSystemService(Context.USB_SERVICE) as UsbManager
+ val conn = mgr.openDevice(device) ?: run { onStatus("$label: couldn't open the adapter"); running = false; return }
+ var chip: Chip? = null
+ try {
+ // The WiFi function is the vendor-specific interface (combo chips add Bluetooth ones).
+ val intf = (0 until device.interfaceCount).map { device.getInterface(it) }
+ .firstOrNull { it.interfaceClass == UsbConstants.USB_CLASS_VENDOR_SPEC } ?: device.getInterface(0)
+ if (!conn.claimInterface(intf, true)) throw IOException("couldn't claim the USB interface")
+ var epIn: UsbEndpoint? = null; var epOut: UsbEndpoint? = null
+ for (i in 0 until intf.endpointCount) {
+ val ep = intf.getEndpoint(i)
+ if (ep.type != UsbConstants.USB_ENDPOINT_XFER_BULK) continue
+ if (ep.direction == UsbConstants.USB_DIR_IN) { if (epIn == null) epIn = ep } else if (epOut == null) epOut = ep
+ }
+ val rx = epIn ?: throw IOException("no bulk-IN endpoint")
+ val tx = epOut ?: throw IOException("no bulk-OUT endpoint")
+ UsbWifi.log("=== $label bring-up (88x2bu) === RX EP 0x%02x, firmware EP 0x%02x".format(rx.address, tx.address))
+
+ val tables = Rtl8822bTables.load(ctx)
+ val c = Chip(conn, tx, tables, onStatus, label)
+ chip = c
+ c.bringUp(hopCycle(0)[0])
+ // A stalled bulk-IN endpoint never delivers frames (CLEAR_FEATURE ENDPOINT_HALT).
+ conn.controlTransfer(0x02, 0x01, 0, rx.address, null, 0, 500)
+ onStatus("$label · live · 2.4 + 5 GHz monitor")
+ rxLoop(conn, rx, c, label, onFrame, onStatus)
+ } catch (e: Exception) {
+ UsbWifi.log("$label: stopped — ${e.message}")
+ onStatus("$label: error · ${e.message}")
+ } finally {
+ chip?.let { if (it.up) runCatching { it.powerOff() } }
+ runCatching { conn.close() }
+ running = false
+ }
+ }
+
+ private class RxState(val label: String) {
+ var total = 0L; var bufs = 0L; var lastLog = 0L; var hopAt = 0L; var lastEmit = 0L; var digAt = 0L
+ var cycle = 0; var hopIdx = 0; var plan = hopCycle(0)
+ /** Register accesses that failed in a row; the adapter is gone or wedged past a limit. */
+ var ioFailures = 0
+ /** A channel held by a debug command instead of hopping (0 = hopping). */
+ var parked = 0
+ var dig = true
+ val channel get() = if (parked > 0) parked else plan[hopIdx]
+ fun start() { val t = System.currentTimeMillis(); lastLog = t; hopAt = t; lastEmit = t; digAt = t }
+ }
+
+ private fun rxTick(chip: Chip, now: Long, st: RxState,
+ onFrame: (List<MonitorSighting>) -> Unit, onStatus: (String) -> Unit) {
+ while (true) {
+ val c = commands.poll() ?: break
+ try { command(chip, st, c) } catch (e: Exception) { UsbWifi.log("${st.label}: command '$c' failed — ${e.message}") }
+ }
+ if (now - st.lastLog > 3000) {
+ if (st.parked > 0) frames.window().forEach { UsbWifi.log("${st.label}: $it") }
+ val (aps, clients) = frames.live(now, REPORT_MS)
+ 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 (!pathSense.decided && chip.rf2t2r) pathSense.verdict()?.let { path ->
+ pathSense.decided = true
+ val name = if (path == 1) "B" else "A"
+ UsbWifi.log("${st.label}: antenna on path $name (${pathSense.bVotes} frames stronger on B, ${pathSense.aVotes} on A)" +
+ if (path == 1) " — 2.4 GHz CCK reception moved to path B" else "")
+ if (path == 1) chipIo(st) { chip.setCckPath(1) }
+ }
+ if (st.dig && now - st.digAt > DIG_MS) {
+ // A failed read under RX load skips one gain step; the next one re-reads everything.
+ chipIo(st) { chip.digStep() }
+ st.digAt = now
+ }
+ if (st.parked == 0 && now - st.hopAt > DWELL_MS) {
+ st.hopIdx++
+ if (st.hopIdx >= st.plan.size) { st.cycle++; st.plan = hopCycle(st.cycle); st.hopIdx = 0 }
+ chipIo(st) { chip.tune(st.channel) }
+ val (aps, clients) = frames.live(now, REPORT_MS)
+ val band = if (st.channel > 14) "5 GHz" else "2.4 GHz"
+ onStatus("${st.label} · live · $aps access points · $clients devices · ch ${st.channel} ($band)")
+ st.hopAt = now
+ }
+ }
+
+ private fun command(chip: Chip, st: RxState, line: String) {
+ val a = line.trim().split(Regex("\\s+"))
+ fun h(i: Int) = java.lang.Long.decode(if (a[i].startsWith("0x")) a[i] else "0x" + a[i]).toInt()
+ val l = st.label
+ when (a[0]) {
+ "park" -> { st.parked = a[1].toInt(); chip.tune(st.parked); frames.window(); UsbWifi.log("$l: parked on ch ${st.parked}") }
+ "hop" -> { st.parked = 0; UsbWifi.log("$l: hopping") }
+ "igi" -> { st.dig = false; chip.setIgi(h(1)); UsbWifi.log("$l: IGI fixed 0x%02x".format(h(1))) }
+ "dig" -> { st.dig = true; UsbWifi.log("$l: DIG on") }
+ "stats" -> frames.window().forEach { UsbWifi.log("$l: $it") }
+ "rd" -> UsbWifi.log("$l: [0x%04x] = 0x%08x".format(h(1), chip.r32(h(1))))
+ "w8" -> chip.w8(h(1), h(2))
+ "w32" -> chip.w32(h(1), h(2))
+ "bb" -> { chip.bb(h(1), h(2), h(3)); UsbWifi.log("$l: [0x%04x] now 0x%08x".format(h(1), chip.r32(h(1)))) }
+ "rfrd" -> UsbWifi.log("$l: RF%s 0x%02x = 0x%05x".format(if (h(1) == 0) "A" else "B", h(2), chip.rfRead(h(1), h(2))))
+ "rf" -> { chip.rfSet(h(1), h(2), h(3), h(4)); UsbWifi.log("$l: RF%s 0x%02x now 0x%05x".format(if (h(1) == 0) "A" else "B", h(2), chip.rfRead(h(1), h(2)))) }
+ else -> UsbWifi.log("$l: unknown command '$line'")
+ }
+ }
+
+ private inline fun chipIo(st: RxState, op: () -> Unit) {
+ try { op(); st.ioFailures = 0 } catch (e: IOException) {
+ if (++st.ioFailures % 10 == 1) UsbWifi.log("${st.label}: register access failed (${st.ioFailures}) — ${e.message}")
+ if (st.ioFailures >= MAX_IO_FAILURES) throw IOException("adapter stopped responding (replug it)")
+ }
+ }
+
+ private const val MAX_IO_FAILURES = 30
+
+ 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)
+ }
+ 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)
+ 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++; b.rewind(); b.get(scratch, 0, n) }
+ 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)
+ 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) {
+ val frameOffset get() = RXDESC_SIZE + drvInfo + shift
+ /** Offset of the next descriptor, 8-byte aligned. */
+ val next get() = (frameOffset + pktLen + 7) and 7.inv()
+ }
+
+ internal const val RXDESC_SIZE = 24
+ private const val FCS_LEN = 4
+
+ internal fun rxDesc(b: ByteArray, off: Int): RxDesc {
+ val d0 = Rtl8822bTables.le32(b, off)
+ return RxDesc(
+ pktLen = d0 and 0x3fff,
+ crcErr = (d0 ushr 14) and 1 != 0,
+ drvInfo = ((d0 ushr 16) and 0xf) * 8,
+ shift = (d0 ushr 24) and 3,
+ physt = (d0 ushr 26) and 1 != 0,
+ rate = b[off + 12].toInt() and 0x7f,
+ c2h = b[off + 11].toInt() and 0x10 != 0
+ )
+ }
+
+ /**
+ * Per-path receive power from a jaguar2 PHY status report, in dBm: page 0 (CCK)
+ * has one value, page 1 (OFDM / HT / VHT) one per path. The page number in the
+ * report, not the frame's rate, says which (as rtw88 reads it). Readings at or
+ * below the noise floor or above 0 dBm (a corrupt report) come back null.
+ */
+ internal fun phyPaths(b: ByteArray, at: Int, paths: Int): IntArray? {
+ fun dbm(i: Int) = (b[i].toInt() and 0xff).takeIf { it in 1..110 }?.let { it - 110 } ?: NO_SIGNAL
+ return when (b[at].toInt() and 0x0f) {
+ 0 -> intArrayOf(dbm(at + 1))
+ 1 -> IntArray(paths) { dbm(at + 1 + it) }
+ else -> null
+ }
+ }
+
+ internal const val NO_SIGNAL = Int.MIN_VALUE
+
+ internal fun parseRxBuf(b: ByteArray, n: Int, ch: Int, twoPaths: Boolean, sink: MonitorFrames = frames,
+ sense: PathSense? = pathSense) {
+ var off = 0
+ while (off + RXDESC_SIZE <= n) {
+ val d = rxDesc(b, off)
+ if (d.pktLen == 0 || off + d.frameOffset + d.pktLen > n) break
+ if (!d.c2h && !d.crcErr) {
+ val fs = off + d.frameOffset
+ val fe = fs + d.pktLen - FCS_LEN // RCR appends the FCS
+ if (fe - fs >= 24) {
+ val p = if (d.physt && d.drvInfo >= 28) phyPaths(b, off + RXDESC_SIZE + d.shift, if (twoPaths) 2 else 1) else null
+ val best = p?.max()?.takeIf { it != NO_SIGNAL }
+ // Both paths of an OFDM report: which one has the antenna, and diagnostics.
+ val pa = p?.takeIf { it.size == 2 }?.get(0)?.takeIf { it != NO_SIGNAL }
+ val pb = p?.takeIf { it.size == 2 }?.get(1)?.takeIf { it != NO_SIGNAL }
+ if (pa != null && pb != null) sense?.add(pa, pb)
+ sink.frame(b, fs, fe, ch, best, System.currentTimeMillis(), pa, pb)
+ }
+ }
+ off += d.next
+ }
+ }
+
+ /**
+ * One RTL8822B behind a USB connection: register access, firmware download,
+ * MAC / BB / RF bring-up, channel tuning and gain control. Used only from the
+ * driver's RX thread.
+ */
+ private class Chip(private val conn: UsbDeviceConnection, private val epOut: UsbEndpoint,
+ private val t: Rtl8822bTables.Data, private val onStatus: (String) -> Unit,
+ private val label: String) {
+ var up = false; private set
+ var cut = 0; private set
+ var rf2t2r = false; private set
+ private var rfe = 0
+ private var rsvdBoundary = 0
+ private var h2cSeq = 0
+ private var lastPktOffset = 0
+ var igi = 0; private set
+ var lastFa = 0; private set
+
+ // --- register access (Realtek vendor request 0x05, wValue = address) ---
+ private val io = ByteArray(4)
+
+ private fun read(addr: Int, len: Int): Int {
+ repeat(3) {
+ if (conn.controlTransfer(0xC0, 0x05, addr and 0xffff, 0, io, len, 500) == len) return when (len) {
+ 1 -> io[0].toInt() and 0xff
+ 2 -> (io[0].toInt() and 0xff) or ((io[1].toInt() and 0xff) shl 8)
+ else -> Rtl8822bTables.le32(io, 0)
+ }
+ }
+ throw IOException("register read 0x%04x failed (unplugged?)".format(addr))
+ }
+
+ private fun write(addr: Int, v: Int, len: Int) {
+ val b = ByteArray(len) { (v ushr (8 * it)).toByte() }
+ repeat(3) { if (conn.controlTransfer(0x40, 0x05, addr and 0xffff, 0, b, len, 500) == len) return }
+ throw IOException("register write 0x%04x failed (unplugged?)".format(addr))
+ }
+
+ fun r8(a: Int) = read(a, 1)
+ fun r16(a: Int) = read(a, 2)
+ fun r32(a: Int) = read(a, 4)
+ fun w8(a: Int, v: Int) = write(a, v, 1)
+ fun w16(a: Int, v: Int) = write(a, v, 2)
+ fun w32(a: Int, v: Int) = write(a, v, 4)
+
+ /** Masked BB / MAC register write (phy_set_bb_reg). */
+ fun bb(a: Int, mask: Int, v: Int) {
+ if (mask == -1) { w32(a, v); return }
+ val s = Integer.numberOfTrailingZeros(mask)
+ w32(a, (r32(a) and mask.inv()) or ((v shl s) and mask))
+ }
+
+ // --- RF registers: 3-wire LSSI write, direct read window ---
+ fun rfWrite(path: Int, addr: Int, v: Int) {
+ if (addr == 0xfe || addr == 0xffe) { sleep(50); return }
+ w32(if (path == 0) 0x0C90 else 0x0E90, (((addr and 0xff) shl 20) or (v and 0xfffff)) and 0x0fffffff)
+ }
+
+ fun rfRead(path: Int, addr: Int): Int = r32((if (path == 0) 0x2800 else 0x2c00) + ((addr and 0xff) shl 2)) and 0xfffff
+
+ fun rfSet(path: Int, addr: Int, mask: Int, v: Int) {
+ val data = if (mask == 0xfffff) v else {
+ val s = Integer.numberOfTrailingZeros(mask)
+ (rfRead(path, addr) and mask.inv()) or ((v shl s) and mask)
+ }
+ rfWrite(path, addr, data)
+ }
+
+ // --- bring-up (RtlJaguar2Device::bring_up, RX subset) ---
+ fun bringUp(ch: Int) {
+ val id = r8(0x00FC)
+ UsbWifi.log("$label: chip id 0x%02x".format(id))
+ if (id != 0x0a && id != 0x50) throw IOException("not an RTL8822B chip (id 0x%02x)".format(id))
+ onStatus("$label · powering on…")
+ var fwOk = false
+ for (attempt in 0 until 4) {
+ checkStop()
+ if (attempt > 0) UsbWifi.log("$label: firmware didn't start — full power cycle, try ${attempt + 1}/4")
+ preInitSystemCfg()
+ powerOn()
+ readChipVersion()
+ initSystemCfg()
+ onStatus("$label · loading firmware…")
+ fwOk = downloadFirmware(t.firmware) || downloadFirmware(t.firmware)
+ if (fwOk) break
+ }
+ if (!fwOk) throw IOException("firmware didn't start (replug the adapter)")
+ UsbWifi.log("$label: firmware ${Rtl8822bTables.version(t.firmware)} running")
+ checkStop()
+ initMacCfg()
+ initUsbCfg()
+ enableBbRf()
+ rfe = readEfuseRfe()
+ sendFwGeneralInfo()
+ onStatus("$label · loading radio tables…")
+ applyTables()
+ checkStop()
+ configTrxMode()
+ setChannel(ch)
+ doLck()
+ configTrxMode()
+ rfeInit()
+ coexWlanOnly(ch > 14)
+ enableRx()
+ up = true
+ UsbWifi.log("$label: monitor live ch $ch — CR 0x%04x RCR 0x%08x RF18 0x%05x".format(r16(0x100), r32(0x608), rfRead(0, 0x18)))
+ }
+
+ private fun checkStop() { if (stop) throw IOException("stopped") }
+
+ private fun runPwrSeq(seq: Array<IntArray>, timeoutMs: Long, fatal: Boolean) {
+ for (s in seq) {
+ val off = s[0]; val msk = s[2]; val v = s[3]
+ when (s[1]) {
+ Rtl8822bTables.PW -> w8(off, (r8(off) and msk.inv()) or (v and msk))
+ Rtl8822bTables.PD -> sleep(v)
+ Rtl8822bTables.PP -> {
+ val end = System.currentTimeMillis() + timeoutMs
+ while (r8(off) and msk != v and msk) {
+ if (System.currentTimeMillis() > end) {
+ if (fatal) throw IOException("power-on didn't complete (chip not responding)")
+ break
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fun powerOff() = runPwrSeq(Rtl8822bTables.PWR_OFF, 200, fatal = false)
+
+ private fun powerOn() {
+ powerOff() // from whatever state the adapter was left in
+ runPwrSeq(Rtl8822bTables.PWR_ON, 500, fatal = true)
+ }
+
+ private fun readChipVersion() {
+ val v = r32(0x00F0)
+ cut = (v ushr 12) and 0xf
+ rf2t2r = v and (1 shl 27) != 0
+ UsbWifi.log("$label: 8822B cut $cut, ${if (rf2t2r) "2T2R" else "1T1R"} (SYS_CFG1 0x%08x)".format(v))
+ }
+
+ private fun enableBbRf() {
+ w8(0x0002, r8(0x0002) or 0x03)
+ w8(0x001F, r8(0x001F) or 0x07)
+ w32(0x00EC, r32(0x00EC) or (0x7 shl 24))
+ }
+
+ private fun preInitSystemCfg() {
+ w8(0x001C, 0)
+ if (r8(0x00FF) == 0x20) w8(0xFE5B, r8(0xFE5B) or 0x10) // USB 3 workaround
+ w32(0x0064, r32(0x0064) or (3 shl 28)) // pinmux
+ w32(0x004C, r32(0x004C) and ((1 shl 25) or (1 shl 26)).inv())
+ w32(0x0040, r32(0x0040) or (1 shl 2))
+ w8(0x0002, r8(0x0002) and 0x03.inv())
+ w8(0x001F, r8(0x001F) and 0x07.inv())
+ w32(0x00EC, r32(0x00EC) and (0x7 shl 24).inv())
+ }
+
+ private fun initSystemCfg() {
+ w32(0x1080, r32(0x1080) or (1 shl 16)) // WL platform reset only
+ w8(0x0003, r8(0x0003) or 0xD8)
+ val mcu = r32(0x0080)
+ if (mcu and (1 shl 20) != 0) { // boot from flash: off
+ w32(0x0080, mcu and (1 shl 20).inv())
+ w32(0x0040, r32(0x0040) and (1 shl 19).inv())
+ }
+ if (cut == 1) w8(0x1018, r8(0x1018) and 0x07.inv())
+ }
+
+ // --- firmware download (HalmacJaguar2Fw) ---
+
+ private fun downloadFirmware(fw: ByteArray): Boolean {
+ val lteBackup = ltecoexRead(0x38) ?: 0
+ wlanCpuEn(false)
+ val pqMap1 = r8(0x010D); w8(0x010D, 3 shl 6)
+ val cr = r8(0x0100)
+ w8(0x0100, 0x01 or 0x04) // HCI TXDMA + TXDMA
+ w32(0x1330, 1 shl 31)
+ val page1 = r16(0x0230)
+ val rqpn = r32(0x022C) or (1 shl 31)
+ w16(0x0230, 0x200); w32(0x022C, rqpn)
+ val bcn = r8(0x0550)
+ w8(0x0550, (bcn and 0x08.inv()) or 0x10)
+ pltfmReset()
+
+ var ok = startDlfw(fw)
+
+ w8(0x010D, pqMap1); w8(0x0100, cr); w32(0x1330, 1 shl 31)
+ w16(0x0230, page1); w32(0x022C, rqpn); w8(0x0550, bcn)
+ if (ok) ok = dlfwEndFlow()
+ if (!ok) {
+ w8(0x0080, r8(0x0080) and 0x01.inv())
+ w8(0x0003, r8(0x0003) or 0x04)
+ }
+ ltecoexWrite(0x38, lteBackup)
+ return ok
+ }
+
+ private fun wlanCpuEn(on: Boolean) {
+ if (on) { w8(0x001D, r8(0x001D) or 0x01); w8(0x0003, r8(0x0003) or 0x04) }
+ else { w8(0x0003, r8(0x0003) and 0x04.inv()); w8(0x001D, r8(0x001D) and 0x01.inv()) }
+ }
+
+ private fun pltfmReset() {
+ w8(0x1082, r8(0x1082) and 0x01.inv())
+ w8(0x0009, r8(0x0009) and 0x40.inv())
+ w8(0x1082, r8(0x1082) or 0x01)
+ w8(0x0009, r8(0x0009) or 0x40)
+ }
+
+ private fun ltecoexReady(): Boolean {
+ val end = System.currentTimeMillis() + 500
+ while (r8(0x1703) and 0x20 == 0) if (System.currentTimeMillis() > end) return false
+ return true
+ }
+
+ private fun ltecoexRead(offset: Int): Int? {
+ if (!ltecoexReady()) { UsbWifi.log("$label: LTE coex not ready (read)"); return null }
+ w32(0x1700, 0x800F0000.toInt() or offset)
+ return r32(0x1708)
+ }
+
+ private fun ltecoexWrite(offset: Int, v: Int) {
+ if (!ltecoexReady()) { UsbWifi.log("$label: LTE coex not ready (write)"); return }
+ w32(0x1704, v)
+ w32(0x1700, 0xC00F0000.toInt() or offset)
+ }
+
+ private fun startDlfw(fw: ByteArray): Boolean {
+ w16(0x0080, (r16(0x0080) and 0x3800) or 0x1)
+ val dmem = Rtl8822bTables.dmemSize(fw); val imem = Rtl8822bTables.imemSize(fw); val emem = Rtl8822bTables.ememSize(fw)
+ var at = Rtl8822bTables.FW_HDR_SIZE
+ if (!dlfwToMem(fw, at, Rtl8822bTables.dmemAddr(fw), dmem)) return false
+ at += dmem
+ if (!dlfwToMem(fw, at, Rtl8822bTables.imemAddr(fw), imem)) return false
+ at += imem
+ if (emem != 0 && !dlfwToMem(fw, at, Rtl8822bTables.ememAddr(fw), emem)) return false
+ return true
+ }
+
+ private fun dlfwToMem(fw: ByteArray, from: Int, dest: Int, size: Int): Boolean {
+ w32(0x1208, r32(0x1208) or (1 shl 25)) // reset the DDMA checksum
+ var done = 0; var first = true
+ while (done < size) {
+ val pkt = minOf(DLFW_CHUNK, size - done)
+ if (!sendFwPage(0, fw, from + done, pkt)) return false
+ if (!iddmaDlfw(OCPBASE_TXBUF + TXDESC_SIZE + lastPktOffset, dest + done, pkt, first)) return false
+ first = false
+ done += pkt
+ }
+ return checkFwChksum(dest)
+ }
+
+ private fun ddmaIdle(): Boolean {
+ repeat(1000) { if (r32(0x1208) and (1 shl 31) == 0) return true }
+ return false
+ }
+
+ private fun iddmaDlfw(src: Int, dest: Int, len: Int, first: Boolean): Boolean {
+ if (!ddmaIdle()) { UsbWifi.log("$label: firmware DMA busy"); return false }
+ var ctrl = (1 shl 29) or (1 shl 31) or (len and 0x3ffff) // checksum on, owned by DMA
+ if (!first) ctrl = ctrl or (1 shl 24) // continue the checksum
+ w32(0x1200, src); w32(0x1204, dest); w32(0x1208, ctrl)
+ return ddmaIdle().also { if (!it) UsbWifi.log("$label: firmware DMA stuck") }
+ }
+
+ private fun checkFwChksum(memAddr: Int): Boolean {
+ var fwCtrl = r8(0x0080)
+ val imem = memAddr < OCPBASE_DMEM
+ if (r32(0x1208) and (1 shl 27) != 0) {
+ fwCtrl = if (imem) (fwCtrl or 0x08) and 0x10.inv() else (fwCtrl or 0x20) and 0x40.inv()
+ w8(0x0080, fwCtrl)
+ UsbWifi.log("$label: firmware checksum failed (${if (imem) "IMEM" else "DMEM"})")
+ return false
+ }
+ w8(0x0080, fwCtrl or if (imem) 0x18 else 0x60)
+ return true
+ }
+
+ /** Sends one chunk into the reserved TX page, the way HalMAC's dl_rsvd_page does. */
+ private fun sendFwPage(page: Int, src: ByteArray, from: Int, size: Int): Boolean {
+ w16(0x0204, (page and 0xfff) or 0x8000)
+ val cr1 = r8(0x0101); w8(0x0101, cr1 or 0x01)
+ val txq2 = r8(0x0422); w8(0x0422, txq2 and 0x40.inv())
+ // A transfer that's an exact multiple of the bulk packet size gets 8 bytes of
+ // padding the descriptor declares, so it still ends with a short packet.
+ var len = TXDESC_SIZE + size
+ val pad = if (len % 512 == 0) 8 else 0
+ len += pad
+ lastPktOffset = pad
+ val frame = ByteArray(len)
+ setDesc(frame, 0x00, 0, 16, size) // TXPKTSIZE
+ setDesc(frame, 0x00, 16, 8, TXDESC_SIZE + pad) // OFFSET
+ if (pad != 0) setDesc(frame, 0x04, 24, 5, 1) // PKT_OFFSET
+ setDesc(frame, 0x04, 8, 5, QSEL_BEACON) // reserved-page queue
+ txDescChecksum(frame)
+ System.arraycopy(src, from, frame, TXDESC_SIZE + pad, size)
+ conn.bulkTransfer(epOut, frame, frame.size, 1000)
+ // The beacon-valid latch, not the bulk completion, says the page arrived.
+ var ok = false
+ val end = System.currentTimeMillis() + 200
+ while (System.currentTimeMillis() < end) { if (r8(0x0205) and 0x80 != 0) { ok = true; break } }
+ if (!ok) UsbWifi.log("$label: firmware page not acknowledged (offset $from, $size B)")
+ w16(0x0204, rsvdBoundary or 0x8000)
+ w8(0x0422, txq2)
+ w8(0x0101, cr1)
+ return ok
+ }
+
+ private fun dlfwEndFlow(): Boolean {
+ w32(0x0210, 1 shl 2)
+ val fwCtrl = r16(0x0080)
+ if (fwCtrl and 0x50 != 0x50) { UsbWifi.log("$label: firmware IMEM/DMEM checksum not ready (0x%04x)".format(fwCtrl)); return false }
+ w16(0x0080, (fwCtrl or (1 shl 14)) and 0x01.inv())
+ wlanCpuEn(true)
+ val end = System.currentTimeMillis() + 1000
+ while (r16(0x0080) != 0xC078) {
+ if (System.currentTimeMillis() > end) {
+ UsbWifi.log("$label: firmware didn't report ready (0x80 = 0x%04x)".format(r16(0x0080)))
+ return false
+ }
+ sleep(1)
+ }
+ return true
+ }
+
+ // --- MAC init after the firmware runs (HalmacJaguar2MacInit) ---
+
+ private fun initMacCfg() {
+ // TX DMA queue mapping (USB, 3 bulk-OUT) and page allocation.
+ w16(0x010C, (3 shl 14) or (3 shl 12) or (1 shl 10) or (1 shl 8) or (2 shl 6) or (2 shl 4))
+ val fwff = r8(0x0601) and 0x80
+ if (fwff != 0) w8(0x0601, r8(0x0601) and 0x80.inv())
+ w8(0x0100, 0)
+ w16(0x029C, r16(0x02A0))
+ w8(0x0100, 0xFF) // the whole MAC on before the LLT init
+ if (fwff != 0) w8(0x0601, r8(0x0601) or 0x80)
+ w32(0x1330, 1 shl 31)
+
+ val txPages = TX_FIFO_SIZE shr 7 // 2048 pages of 128 B
+ val rsvdPages = 16 + 24 + 8 + 8 + 0 + 4 + 50 // drv, h2c extra/static, h2cq, cpu, fw txbuf, csi
+ rsvdBoundary = txPages - rsvdPages // 1938
+ val csiAddr = txPages - 50
+ val pub = rsvdBoundary - 64 - 64 - 64 - 0 - 1
+ w16(0x0230, 64); w16(0x0234, 64); w16(0x0238, 64); w16(0x023C, 0); w16(0x0240, pub)
+ w32(0x022C, r32(0x022C) or (1 shl 31))
+ w16(0x169C, csiAddr)
+ w8(0x0422, r8(0x0422) or 0x10)
+ w16(0x0204, rsvdBoundary); w16(0x0424, rsvdBoundary); w16(0x0206, rsvdBoundary); w16(0x0456, rsvdBoundary)
+ w32(0x011C, RX_FIFO_SIZE - 256 - 1)
+ w8(0x0208, (r8(0x0208) and 0xF0.inv()) or (3 shl 4))
+ w8(0x020B, 3)
+ w8(0x020D, r8(0x020D) or 0x02)
+ w8(0x0208, r8(0x0208) or 0x01) // auto LLT init
+ var n = 1000
+ while (r8(0x0208) and 0x01 != 0) if (--n == 0) throw IOException("LLT init timed out")
+ w8(0x0103, 0)
+
+ // H2C queue
+ val h2cq = (txPages - 50 - 4 - 0 - 8) shl 7
+ val h2cqSize = 8 shl 7
+ w32(0x0244, (r32(0x0244) and 0xFFFC0000.toInt()) or h2cq)
+ w32(0x024C, (r32(0x024C) and 0xFFFC0000.toInt()) or h2cq)
+ w32(0x0248, (r32(0x0248) and 0xFFFC0000.toInt()) or (h2cq + h2cqSize))
+ w8(0x0254, (r8(0x0254) and 0xFC) or 0x01)
+ w8(0x0254, (r8(0x0254) and 0xFB) or 0x04)
+ w8(0x020D, (r8(0x020D) and 0x7f) or 0x80)
+
+ // MAC clock 80 MHz and the matching microsecond ticks.
+ w32(0x0024, r32(0x0024) and ((1 shl 20) or (1 shl 21)).inv())
+ w8(0x055C, 80); w8(0x0638, 80)
+
+ // Protocol
+ w8(0x04BC, r8(0x04BC) and 0x40.inv())
+ w8(0x0455, 0x70)
+ w8(0x045E, r8(0x045E) or 0x04)
+ w32(0x04C8, 0xFF or (0x08 shl 8) or (0x20 shl 16) or (0x20 shl 24))
+ w16(0x04CE, 0x01 or (0x08 shl 8))
+ w8(0x1448, 6); w8(0x144A, 6); w8(0x144C, 6); w8(0x144E, 6)
+ w8(0x0480, r8(0x0480) or 0x20)
+
+ // EDCA
+ w8(0x05B4, r8(0x05B4) and 0x70.inv())
+ w16(0x0522, 0)
+ w8(0x051B, 0x09); w8(0x0512, 0x19)
+ w32(0x0514, 0x0A or (0x0E shl 8) or (0x10 shl 16) or (0x10 shl 24))
+ w16(0x0502, 0x186); w16(0x0506, 0x3BC)
+ w32(0x0544, 0x05 or (0x1B shl 16))
+ w16(0x055E, 0x30 or (0x30 shl 8))
+ w8(0x0550, r8(0x0550) or 0x08)
+ w32(0x0540, 0x04 or (0x064 shl 8))
+ w8(0x0558, 0x04); w8(0x0559, 0x02)
+ w8(0x0521, r8(0x0521) and 0x10.inv())
+
+ // WMAC: group-address filter and RX filter maps wide open.
+ w32(0x0620, -1); w32(0x0624, -1)
+ w32(0x06A0, 0x0FFFFFFF); w16(0x06A4, 0xFFFF)
+ w32(0x0608, 0xE400220E.toInt())
+ w8(0x060C, 12288 shr 9)
+ w8(0x0606, 0x30); w8(0x0605, 0x30)
+ w8(0x066C, r8(0x066C) or 0x02)
+ w8(0x0718, r8(0x0718) or 0x40)
+ w32(0x07D8, 0x30810041); w8(0x07D4, 0x98)
+ }
+
+ /** USB RX DMA and aggregation (kept under 16 KB per transfer). */
+ private fun initUsbCfg() {
+ val usb3 = r8(0x00FF) == 0x20
+ var v = 0x02 or (0x3 shl 2)
+ v = v or when { usb3 -> 0; r8(0xFE11) and 0x3 == 0x1 -> 0x10; else -> 0x20 }
+ w8(0x0290, v)
+ w16(0x020C, r16(0x020C) or (1 shl 9))
+ val agg = r8(0x0283) and 0x80.inv()
+ val pq = r8(0x010C) or 0x04
+ w32(0x0280, r32(0x0280) and (1 shl 29).inv())
+ w8(0x010C, pq)
+ w8(0x0283, agg)
+ w16(0x0280, 0x03 or ((if (usb3) 0x0A else 0x20) shl 8))
+ UsbWifi.log("$label: USB ${if (usb3) "3" else "2"}, RX aggregation on")
+ }
+
+ /** Physical efuse -> logical map walk; the RFE type (antenna front-end) is at 0xCA. */
+ private fun readEfuseRfe(): Int {
+ fun efuse(addr: Int): Int {
+ w8(0x0031, addr and 0xff)
+ w8(0x0032, ((addr shr 8) and 0x03) or (r8(0x0032) and 0xFC))
+ w8(0x0033, r8(0x0033) and 0x7f)
+ val end = System.currentTimeMillis() + 100
+ while (r8(0x0033) and 0x80 == 0) { if (System.currentTimeMillis() > end) return 0xFF }
+ return r8(0x0030)
+ }
+ var rfe = 0xFF
+ var phys = 0
+ while (phys < 1024) {
+ val hdr = efuse(phys++)
+ if (hdr == 0xFF) break
+ val offset: Int; val wordEn: Int
+ if (hdr and 0x1F == 0x0F) {
+ val ext = efuse(phys++)
+ if (ext and 0x0F == 0x0F) continue
+ offset = ((ext and 0xF0) shr 1) or ((hdr and 0xE0) shr 5)
+ wordEn = ext and 0x0F
+ } else {
+ offset = (hdr shr 4) and 0x0F
+ wordEn = hdr and 0x0F
+ }
+ val base = offset shl 3
+ for (i in 0 until 4) {
+ if (wordEn and (1 shl i) != 0) continue
+ for (k in 0 until 2) {
+ val d = efuse(phys++)
+ if (base + i * 2 + k == 0xCA) rfe = d
+ }
+ }
+ }
+ UsbWifi.log("$label: efuse RFE type ${if (rfe == 0xFF) "blank (using 0)" else "0x%02x".format(rfe)}")
+ return if (rfe == 0xFF) 0 else rfe
+ }
+
+ /** HalMAC GENERAL_INFO + PHYDM_INFO to the firmware, as the Linux driver sends after boot. */
+ private fun sendFwGeneralInfo() {
+ val gen = ByteArray(32)
+ gen[0] = 0x01; gen[1] = 0xff.toByte(); gen[2] = 0x0d; gen[4] = 12; gen[6] = (h2cSeq++).toByte()
+ gen[10] = (TX_FIFO_SIZE / 128 - 50 - 4 - rsvdBoundary).toByte() // fw TX buffer page above the boundary
+ val phy = ByteArray(32)
+ phy[0] = 0x01; phy[1] = 0xff.toByte(); phy[2] = 0x11; phy[4] = 16; phy[6] = (h2cSeq++).toByte()
+ phy[8] = rfe.toByte(); phy[9] = (if (rf2t2r) 0x02 else 0x04).toByte(); phy[10] = cut.toByte()
+ phy[11] = (if (rf2t2r) 0x33 else 0x11).toByte(); phy[13] = 7
+ for (p in listOf(gen, phy)) {
+ val frame = ByteArray(TXDESC_SIZE + 32)
+ setDesc(frame, 0x00, 0, 16, 32)
+ setDesc(frame, 0x04, 8, 5, 0x13) // H2C queue
+ txDescChecksum(frame)
+ System.arraycopy(p, 0, frame, TXDESC_SIZE, 32)
+ if (conn.bulkTransfer(epOut, frame, frame.size, 1000) != frame.size)
+ UsbWifi.log("$label: firmware info message not sent (continuing)")
+ }
+ }
+
+ // --- BB / RF (HalJaguar2) ---
+
+ private fun applyTables() {
+ bb(0x0808, (1 shl 28) or (1 shl 29), 0) // OFDM / CCK off while loading
+ for (tab in listOf(t.phyReg, t.agcTab)) Rtl8822bTables.walk(tab, cut, rfe) { a, v ->
+ when (a) {
+ 0xfe -> sleep(50)
+ 0xfd -> sleep(5)
+ 0xfc -> sleep(1)
+ 0xfb, 0xfa, 0xf9 -> {} // microsecond delays: a USB round trip is longer
+ else -> w32(a, v)
+ }
+ }
+ Rtl8822bTables.walk(t.radioA, cut, rfe) { a, v -> rfWrite(0, a, v) }
+ Rtl8822bTables.walk(t.radioB, cut, rfe) { a, v -> rfWrite(1, a, v) }
+ bb(0x0808, (1 shl 28) or (1 shl 29), 0x3)
+ UsbWifi.log("$label: BB / AGC / RF tables applied (rfe $rfe)")
+ }
+
+ /** RF mode table and TX / RX antenna paths (config_phydm_trx_mode_8822b). */
+ private fun configTrxMode() {
+ val path = if (rf2t2r) 0x3 else 0x1
+ bb(0x0c08, 0xffff, 0x3231)
+ if (rf2t2r) bb(0x0e08, 0xffff, 0x3231)
+ bb(0x093c, (1 shl 19) or (1 shl 18), 0x3)
+ bb(0x080c, (1 shl 29) or (1 shl 28), 0x1)
+ bb(0x080c, 1 shl 30, 0x1)
+ bb(0x080c, 0xff, (path shl 4) or path)
+ bb(0x0a04, 0xf0000000.toInt(), 0x8)
+ bb(0x093c, 0xfff00000.toInt(), 0x001)
+ if (rf2t2r) bb(0x0940, 0xfff0, 0x043) else { bb(0x0940, 0xf0, 0x1); bb(0x0940, 0xff00, 0x0) }
+ w32(0x19a8, 0xd90a0000.toInt()) // SoML on
+ bb(0x0a2c, 1 shl 22, 0); bb(0x0a2c, 1 shl 18, 0)
+ bb(0x0a04, 0x0f000000, 0)
+ bb(0x0808, 0xff, (path shl 4) or path)
+ val two = if (rf2t2r) 1 else 0
+ bb(0x1904, 1 shl 16, two); bb(0x0800, 1 shl 28, two); bb(0x0850, 1 shl 23, two)
+ for (i in 0 until 100) {
+ rfWrite(0, 0xef, 0x80000); rfWrite(0, 0x33, 0x00001)
+ if (rfRead(0, 0x33) == 0x00001) break
+ }
+ rfWrite(0, 0xef, 0x80000); rfWrite(0, 0x33, 0x00001)
+ rfWrite(0, 0x3e, 0x00034); rfWrite(0, 0x3f, 0x4080c); rfWrite(0, 0xef, 0x00000)
+ }
+
+ /** LC calibration: locks the RF local oscillator. */
+ private fun doLck() {
+ val aac = (rfRead(0, 0xc9) and 0xf8) shr 3
+ if (aac < 4 || aac > 7) { rfSet(0, 0xca, 1 shl 19, 0); rfSet(0, 0xb2, 0x7c000, 0x6) }
+ val c00 = r32(0x0c00); val e00 = r32(0x0e00)
+ w32(0x0c00, 0x4); w32(0x0e00, 0x4)
+ rfWrite(0, 0x0, 0x10000); if (rf2t2r) rfWrite(1, 0x0, 0x10000)
+ val lc = rfRead(0, 0x18)
+ rfWrite(0, 0xc4, 0x01402)
+ rfWrite(0, 0x18, lc or 0x08000)
+ sleep(100)
+ var locked = false
+ for (i in 0 until 5) { if (rfRead(0, 0x18) and 0x8000 == 0) { locked = true; break }; sleep(10) }
+ rfWrite(0, 0x18, lc and 0x08000.inv()); rfWrite(0, 0xc4, 0x81402)
+ w32(0x0c00, c00); w32(0x0e00, e00)
+ rfWrite(0, 0x0, 0x3ffff); if (rf2t2r) rfWrite(1, 0x0, 0x3ffff)
+ UsbWifi.log("$label: LC calibration ${if (locked) "locked" else "timed out (continuing)"}")
+ }
+
+ /** RFE mux: chip-top pins and the RFE source select (phydm_rfe_8822b_init). */
+ private fun rfeInit() {
+ bb(0x0064, (1 shl 29) or (1 shl 28), 0x3)
+ bb(0x004c, (1 shl 26) or (1 shl 25), 0x0)
+ bb(0x0040, 1 shl 2, 0x1)
+ bb(0x1990, 0x3f, 0x30)
+ bb(0x1990, (1 shl 11) or (1 shl 10), 0x3)
+ bb(0x0974, 0x3f, 0x3f)
+ bb(0x0974, (1 shl 11) or (1 shl 10), 0x3)
+ }
+
+ /** Gives the antennas to WiFi (without it a combo chip leaves them with Bluetooth). */
+ private fun coexWlanOnly(is5g: Boolean) {
+ bb(0x004c, 0x01800000, 0x2)
+ bb(0x0cb4, 0xff, 0x77)
+ bb(0x0974, 0x300, 0x3)
+ bb(0x1990, 0x300, 0x0)
+ bb(0x0cbc, 0x80000, 0x0)
+ bb(0x0070, 0xff000000.toInt(), 0x0e)
+ w32(0x1704, 0x7700)
+ w32(0x1700, 0xc00f0038.toInt())
+ switchAntenna(is5g)
+ }
+
+ private fun switchAntenna(is5g: Boolean) = bb(0x0cbc, 0x300, if (is5g) 0x1 else 0x2)
+
+ /** MAC RX on, promiscuous monitor RCR (with PHY status), starting gain. */
+ private fun enableRx() {
+ w16(0x0100, 0x06FF)
+ w32(0x0608, 0xF000002F.toInt())
+ igi = 0x40
+ bb(0x0c50, 0x7f, igi); bb(0x0e50, 0x7f, igi)
+ }
+
+ // --- channels ---
+
+ private var tunedCh = 0
+ private var primed = false
+ private var rf18Cache = 0; private var agcCache = 0; private var fcCache = 0; private var rfBeCache = 0
+ private var lastAgcBucket = -1; private var lastFc = -1; private var lastRfBe = -1; private var lastDf18 = -1; private var lastCckKey = -1
+
+ /** Moves to channel [ch]: a full channel set on a band change, the fast path within a band. */
+ fun tune(ch: Int) {
+ if (ch == tunedCh) return
+ if (tunedCh == 0 || (tunedCh <= 14) != (ch <= 14)) {
+ setChannel(ch)
+ switchAntenna(ch > 14)
+ } else fastRetune(ch)
+ }
+
+ private fun rfeIfem(ch: Int) {
+ val g2 = ch <= 14
+ bb(0x0cb0, 0xffffff, if (g2) 0x745774 else 0x477547)
+ bb(0x0eb0, 0xffffff, if (g2) 0x745774 else 0x477547)
+ bb(0x0cb4, 0x0000ff00, if (g2) 0x57 else 0x75)
+ bb(0x0eb4, 0x0000ff00, if (g2) 0x57 else 0x75)
+ bb(0x0cbc, 0x3f, 0x0); bb(0x0cbc, (1 shl 11) or (1 shl 10), 0x0)
+ bb(0x0ebc, 0x3f, 0x0); bb(0x0ebc, (1 shl 11) or (1 shl 10), 0x0)
+ bb(0x0ca0, 0x0000ffff, if (g2) 0xa501 else 0xa5a5)
+ bb(0x0ea0, 0x0000ffff, if (g2) 0xa501 else 0xa5a5)
+ }
+
+ /** CCK block, CCK checks and CCA mask per band (config_phydm_switch_band_8822b). */
+ private fun bandBlock(g2: Boolean) {
+ if (g2) {
+ bb(0x0808, 1 shl 28, 0x1)
+ bb(0x0454, 1 shl 7, 0x0)
+ bb(0x0a80, 1 shl 18, 0x0)
+ bb(0x0814, 0x0000FC00, 15)
+ } else {
+ bb(0x0a80, 1 shl 18, 0x1)
+ bb(0x0454, 1 shl 7, 0x1)
+ bb(0x0808, 1 shl 28, 0x0)
+ bb(0x0814, 0x0000FC00, 34)
+ }
+ }
+
+ private fun igiToggle() {
+ val v = r32(0x0c50) and 0x7f
+ bb(0x0c50, 0x7f, v - 2); bb(0x0c50, 0x7f, v)
+ bb(0x0e50, 0x7f, v - 2); bb(0x0e50, 0x7f, v)
+ }
+
+ /** Full 20 MHz channel set (config_phydm_switch_channel / _bandwidth_8822b). */
+ private fun setChannel(ch: Int) {
+ primed = false; lastAgcBucket = -1; lastFc = -1; lastRfBe = -1; lastDf18 = -1; lastCckKey = -1
+ val g2 = ch <= 14
+ rfeIfem(ch)
+ bandBlock(g2)
+ var rf18 = rf18For(rfRead(0, 0x18), ch)
+ if (g2) {
+ bb(0x0958, 0x1f, 0x0)
+ bb(0x0860, 0x1ffe0000, 0x96a)
+ if (ch == 14) { w32(0x0a24, 0x00006577); bb(0x0a28, 0xffff, 0x0000) }
+ else { w32(0x0a24, 0x384f6577); bb(0x0a28, 0xffff, 0x1525) }
+ } else {
+ agcBucket(ch).takeIf { it >= 0 }?.let { bb(0x0958, 0x1f, it) }
+ fcFor(ch).takeIf { it >= 0 }?.let { bb(0x0860, 0x1ffe0000, it) }
+ }
+ bb(0x0c04, (1 shl 21) or (1 shl 18), 0x0)
+ bb(0x0e04, (1 shl 21) or (1 shl 18), 0x0)
+ if (!g2 || rfe !in intArrayOf(3, 5, 8, 17)) { w32(0x08cc, 0x08108000); bb(0x08d8, 1 shl 27, 0) }
+ else { w32(0x08cc, 0x08108492); bb(0x08d8, 1 shl 27, 1) }
+ val be = rfBeFor(ch)
+ if (be != 0xff) rfSet(0, 0xbe, 0x38000, be)
+ rfSet(0, 0xdf, 1 shl 18, if (ch == 144) 1 else 0) // before RF18 on channel 144
+ // 20 MHz
+ w32(0x08ac, r32(0x08ac) and 0xFFCFFC00.toInt())
+ bb(0x08c4, 1 shl 30, 0x1)
+ rfWrite(0, 0x18, rf18)
+ if (rf2t2r) rfWrite(1, 0x18, rf18)
+ rfSet(0, 0xb8, 1 shl 19, 0); rfSet(0, 0xb8, 1 shl 19, 1)
+ // RX digital filter for 20 MHz
+ bb(0x0948, (1 shl 29) or (1 shl 28), 0x2)
+ bb(0x094c, (1 shl 29) or (1 shl 28), 0x2)
+ bb(0x0c20, 1 shl 31, 0x1)
+ bb(0x0e20, 1 shl 31, 0x1)
+ // CCA thresholds
+ val col = if (g2) (if (rf2t2r) 1 else 0) else (if (rf2t2r) 3 else 2)
+ val cca = if (rfe in intArrayOf(3, 5, 12, 15, 16, 17, 19)) CCA_IFEM_RFE else CCA_IFEM
+ w32(0x082c, cca[0][col]); w32(0x0830, cca[1][col]); w32(0x0838, cca[2][col])
+ if (!g2 && (ch in 52..64 || ch in 100..144)) bb(0x0838, 0xf0, 0x5)
+ // Leave the RX dead zone: toggle the RX paths, then the gain.
+ val rxAnt = if (rf2t2r) 0x3 else 0x1
+ bb(0x0808, 0xff, 0x0)
+ bb(0x0808, 0xff, rxAnt or (rxAnt shl 4))
+ igiToggle()
+ // Spur notch / CSI mask reset (the PSD spur search itself isn't ported).
+ bb(0x087c, 1 shl 13, 0x0); bb(0x0c20, 1 shl 28, 0x0); bb(0x0e20, 1 shl 28, 0x0)
+ for (a in 0x880..0x89c step 4) w32(a, 0)
+ bb(0x0874, 0x1, 0x0)
+ tunedCh = ch
+ }
+
+ /** Within-band hop: RF18 plus the channel-keyed constants that changed (devourer fast_retune). */
+ private fun fastRetune(ch: Int) {
+ if (!primed) {
+ rf18Cache = rfRead(0, 0x18); agcCache = r32(0x0958); fcCache = r32(0x0860); rfBeCache = rfRead(0, 0xbe)
+ primed = true
+ }
+ val g2 = ch <= 14
+ var rf18 = rf18For(rf18Cache, ch)
+ val agc = agcBucket(ch)
+ if (agc >= 0 && agc != lastAgcBucket) { agcCache = (agcCache and 0x1f.inv()) or agc; w32(0x0958, agcCache); lastAgcBucket = agc }
+ val fc = fcFor(ch)
+ if (fc >= 0 && fc != lastFc) { fcCache = (fcCache and 0x1ffe0000.inv()) or (fc shl 17); w32(0x0860, fcCache); lastFc = fc }
+ val be = rfBeFor(ch)
+ if (be != 0xff && be != lastRfBe) { rfBeCache = (rfBeCache and 0x38000.inv()) or (be shl 15); rfWrite(0, 0xbe, rfBeCache); lastRfBe = be }
+ val df18 = if (ch == 144) 1 else 0
+ if (df18 != lastDf18) { rfSet(0, 0xdf, 1 shl 18, df18); lastDf18 = df18 }
+ if (g2) {
+ val key = if (ch == 14) 1 else 0
+ if (key != lastCckKey) {
+ if (ch == 14) { w32(0x0a24, 0x00006577); bb(0x0a28, 0xffff, 0x0000) }
+ else { w32(0x0a24, 0x384f6577); bb(0x0a28, 0xffff, 0x1525) }
+ lastCckKey = key
+ }
+ }
+ rfWrite(0, 0x18, rf18)
+ if (rf2t2r) rfWrite(1, 0x18, rf18)
+ rf18Cache = rf18
+ tunedCh = ch
+ }
+
+ /**
+ * Dynamic initial gain: raises the receiver's gain floor when false alarms flood
+ * in and lowers it when the channel is quiet, so weak signals still decode.
+ * Thresholds are devourer's per-100 ms values scaled to [DIG_MS].
+ */
+ /** Path that receives CCK (0xa04[27:24]: 0 = path A, 5 = path B; phydm_config_rx_path_8822b). */
+ fun setCckPath(path: Int) = bb(0x0a04, 0x0f000000, if (path == 1) 0x5 else 0x0)
+
+ fun setIgi(v: Int) { igi = v and 0x7f; bb(0x0c50, 0x7f, igi); bb(0x0e50, 0x7f, igi) }
+
+ fun digStep() {
+ val ofdm = r32(0x0f48) and 0xffff
+ val cck = r32(0x0a5c) and 0xffff
+ val fa = ofdm + cck
+ lastFa = fa
+ bb(0x09a4, 1 shl 17, 1); bb(0x09a4, 1 shl 17, 0) // reset the OFDM / CCK counters
+ bb(0x0a2c, 1 shl 15, 0); bb(0x0a2c, 1 shl 15, 1)
+ val cur = r8(0x0c50) and 0x7f
+ val scale = (DIG_MS / 100).toInt()
+ var next = when {
+ fa > 750 * scale -> cur + 2
+ fa > 500 * scale -> cur + 1
+ fa < 250 * scale -> if (cur >= 2) cur - 2 else cur
+ else -> cur
+ }
+ next = next.coerceIn(0x1c, 0x3e)
+ if (next != cur) { bb(0x0c50, 0x7f, next); bb(0x0e50, 0x7f, next) }
+ igi = next
+ }
+ }
+
+ // --- channel constants (config_phydm_switch_channel_8822b) ---
+
+ /**
+ * RF 0x18 for a 20 MHz channel, from its current value: band, channel, sub-band and
+ * bandwidth fields set explicitly (rtw8822b_set_channel_rf), other bits kept except
+ * the LC-calibration trigger (bit 15), which the read-back can still show set.
+ */
+ internal fun rf18For(cur: Int, ch: Int): Int {
+ var v = cur and (RF18_BAND or 0xff or RF18_RFSI or RF18_BW or RF18_LCK).inv()
+ if (ch > 14) v = v or (1 shl 16) or (1 shl 8)
+ v = v or (ch and 0xff)
+ if (ch > 144) v = v or (1 shl 18) else if (ch >= 80) v = v or (1 shl 17)
+ return v or RF18_BW // 20 MHz
+ }
+
+ private const val RF18_BAND = (1 shl 16) or (1 shl 9) or (1 shl 8)
+ private const val RF18_RFSI = (1 shl 18) or (1 shl 17)
+ private const val RF18_BW = (1 shl 11) or (1 shl 10)
+ private const val RF18_LCK = 1 shl 15
+
+ internal fun agcBucket(ch: Int) = when {
+ ch <= 14 -> 0
+ ch <= 64 -> 1
+ ch in 100..144 -> 2
+ ch >= 149 -> 3
+ else -> -1
+ }
+
+ internal fun fcFor(ch: Int) = when {
+ ch <= 14 -> 0x96a
+ ch <= 48 -> 0x494
+ ch in 52..64 -> 0x453
+ ch in 100..116 -> 0x452
+ ch >= 118 -> 0x412
+ else -> -1
+ }
+
+ /** RF 0xBE[17:15] VCO band for a 5 GHz channel; 0 on 2.4 GHz, 0xff for no change. */
+ internal fun rfBeFor(ch: Int): Int {
+ if (ch <= 14) return 0
+ return when {
+ ch < 36 -> RF_BE_LOW[0]
+ ch <= 64 -> RF_BE_LOW[(ch - 36) shr 1]
+ ch in 100..144 -> RF_BE_MID[(ch - 100) shr 1]
+ ch in 149..177 -> RF_BE_HIGH[(ch - 149) shr 1]
+ ch > 177 -> RF_BE_HIGH[(177 - 149) shr 1]
+ else -> 0xff
+ }
+ }
+
+ private val RF_BE_LOW = intArrayOf(0x7, 0x6, 0x6, 0x5, 0x0, 0x0, 0x7, 0xff, 0x6, 0x5, 0x0, 0x0, 0x7, 0x6, 0x6)
+ private val RF_BE_MID = intArrayOf(0x6, 0x5, 0x0, 0x0, 0x7, 0x6, 0x6, 0xff, 0x0, 0x0, 0x7, 0x6,
+ 0x6, 0x5, 0x0, 0xff, 0x7, 0x6, 0x6, 0x5, 0x0, 0x0, 0x7)
+ private val RF_BE_HIGH = intArrayOf(0x5, 0x5, 0x0, 0x7, 0x7, 0x6, 0x5, 0xff, 0x0, 0x7, 0x7, 0x6, 0x5, 0x5, 0x0)
+
+ /** CCA thresholds 0x82c / 0x830 / 0x838; columns 2.4 GHz 1R, 2.4 GHz 2R, 5 GHz 1R, 5 GHz 2R. */
+ private val CCA_IFEM = arrayOf(
+ intArrayOf(0x75C97010, 0x75C97010, 0x75C97010, 0x75C97010),
+ intArrayOf(0x79a0eaaa, 0x79A0EAAC, 0x79a0eaaa, 0x79a0eaaa),
+ intArrayOf(0x87765541.toInt(), 0x87746341.toInt(), 0x87765541.toInt(), 0x87746341.toInt())
+ )
+ private val CCA_IFEM_RFE = arrayOf(
+ intArrayOf(0x75da8010, 0x75da8010, 0x75da8010, 0x75da8010),
+ intArrayOf(0x79a0eaaa, 0x97A0EAAC.toInt(), 0x79a0eaaa, 0x79a0eaaa),
+ intArrayOf(0x87765541.toInt(), 0x86666341.toInt(), 0x87765561.toInt(), 0x86666361.toInt())
+ )
+
+ // --- HalMAC constants ---
+ private const val TXDESC_SIZE = 48
+ private const val QSEL_BEACON = 0x10
+ private const val DLFW_CHUNK = 4096
+ private const val OCPBASE_TXBUF = 0x18780000
+ private const val OCPBASE_DMEM = 0x00200000
+ private const val TX_FIFO_SIZE = 262144
+ private const val RX_FIFO_SIZE = 24576
+
+ /** Sets [bits] bits at [shift] of the little-endian dword at [at] in a TX descriptor. */
+ internal fun setDesc(d: ByteArray, at: Int, shift: Int, bits: Int, v: Int) {
+ val mask = if (bits == 32) -1 else ((1 shl bits) - 1) shl shift
+ val cur = Rtl8822bTables.le32(d, at)
+ val nv = (cur and mask.inv()) or ((v shl shift) and mask)
+ for (k in 0 until 4) d[at + k] = (nv ushr (8 * k)).toByte()
+ }
+
+ /** The 8822B checksums only the first 32 bytes of a TX descriptor: XOR of 16 LE words. */
+ internal fun txDescChecksum(d: ByteArray) {
+ setDesc(d, 0x1C, 0, 16, 0)
+ var sum = 0
+ for (w in 0 until 16) sum = sum xor ((d[2 * w].toInt() and 0xff) or ((d[2 * w + 1].toInt() and 0xff) shl 8))
+ setDesc(d, 0x1C, 0, 16, sum)
+ }
+
+ private fun sleep(ms: Int) = try { Thread.sleep(ms.toLong()) } catch (_: InterruptedException) {}
+}
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 b48b5f3..ec3138b 100644
--- a/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
+++ b/app/src/main/java/com/rfsentinel/app/usb/UsbWifi.kt
@@ -34,18 +34,48 @@ object UsbWifi {
private const val TAG = "UsbWifi"
private const val ACTION_PERMISSION = "com.rfsentinel.app.USB_WIFI_PERMISSION"
- /** USB IDs with a working driver: vendor:product -> chip. */
- private val SUPPORTED = mapOf(
- (0x0bda to 0x0811) to "RTL8811AU / RTL8821AU" // ALFA AWUS036ACS and other 88xxau dongles
+ /** Driver families. */
+ enum class Driver { RTL88XXAU, RTL88X2BU }
+
+ /** A supported adapter: the chip name shown to the user and the driver that runs it. */
+ data class Chip(val name: String, val driver: Driver)
+
+ private val AU = Chip("RTL8811AU / 8821AU", Driver.RTL88XXAU)
+ private val BU = Chip("RTL8812BU / 8822BU", Driver.RTL88X2BU)
+
+ /** USB IDs with a working driver: vendor:product -> chip. 88x2bu IDs from the Linux rtw88 driver. */
+ private val SUPPORTED: Map<Pair<Int, Int>, Chip> = mapOf(
+ (0x0bda to 0x0811) to AU, // ALFA AWUS036ACS and other 88xxau dongles
+ (0x0bda to 0xb812) to Chip("RTL8812BU", Driver.RTL88X2BU), // generic AC1200 dongles (e.g. Wise Tiger)
+ (0x0bda to 0xb82c) to Chip("RTL8822BU", Driver.RTL88X2BU),
+ (0x0bda to 0x2102) to BU, (0x0bda to 0xb81a) to BU,
+ (0x7392 to 0xb822) to BU, (0x7392 to 0xc822) to BU, (0x7392 to 0xd822) to BU, // Edimax EW-7822U*
+ (0x7392 to 0xe822) to BU, (0x7392 to 0xf822) to BU,
+ (0x0b05 to 0x1841) to BU, (0x0b05 to 0x184c) to BU, (0x0b05 to 0x19aa) to BU, // ASUS USB-AC53 / AC55 / AC58
+ (0x0b05 to 0x1870) to BU, (0x0b05 to 0x1874) to BU,
+ (0x2001 to 0x331e) to BU, (0x2001 to 0x331c) to BU, (0x2001 to 0x331f) to BU, (0x2001 to 0x3322) to BU, // D-Link
+ (0x13b1 to 0x0043) to BU, (0x13b1 to 0x0045) to BU, // Linksys WUSB6400M / WUSB3600 v2
+ (0x2357 to 0x012d) to BU, (0x2357 to 0x0138) to BU, (0x2357 to 0x0115) to BU, // TP-Link Archer T3U / T4U v3
+ (0x2357 to 0x012e) to BU, (0x2357 to 0x0116) to BU, (0x2357 to 0x0117) to BU,
+ (0x0846 to 0x9055) to BU, // Netgear A6150
+ (0x0e66 to 0x0025) to BU, (0x04ca to 0x8602) to BU,
+ (0x20f4 to 0x808a) to BU, (0x20f4 to 0x805a) to BU, // TRENDnet
+ (0x056e to 0x4011) to BU, (0x2c4e to 0x0107) to BU, (0x2c4e to 0x010a) to BU,
+ (0x0411 to 0x03d1) to BU, (0x0411 to 0x03d0) to BU // Buffalo
)
/** Known monitor-mode chips without a driver here yet (named in the status so users know why). */
private val KNOWN = mapOf(
(0x0bda to 0x8812) to "RTL8812AU", (0x0bda to 0x881a) to "RTL8812AU", (0x0bda to 0x8813) to "RTL8814AU",
+ (0x0bda to 0xc811) to "RTL8811CU / 8821CU", (0x0bda to 0xc820) to "RTL8821CU", (0x0bda to 0xc812) to "RTL8812CU",
(0x0cf3 to 0x9271) to "AR9271", (0x0e8d to 0x7612) to "MT7612U", (0x148f to 0x3070) to "RT3070",
(0x0bda to 0x8187) to "RTL8187"
)
private var receiver: BroadcastReceiver? = null
+ /** Debug builds: driver commands from adb, e.g.
+ * `adb shell am broadcast -a com.rfsentinel.app.USB_WIFI_CMD -p com.rfsentinel.app.debug --es cmd "park 11"` */
+ private var cmdReceiver: BroadcastReceiver? = null
+ private const val ACTION_CMD = "com.rfsentinel.app.USB_WIFI_CMD"
private var onSightings: ((List<MonitorSighting>) -> Unit)? = null
private var thread: Thread? = null
@Volatile private var runningDevice: String? = null
@@ -57,23 +87,32 @@ object UsbWifi {
/** Recent driver log lines (bring-up, RX stats, errors), for troubleshooting from Settings. */
private val logLines = ArrayDeque<String>()
+ /** Debug builds: the log also goes to files/usbwifi.log (read with adb run-as), which logcat can't rotate away. */
+ @Volatile private var logFile: java.io.File? = null
+
fun log(line: String) {
Log.d(TAG, line)
synchronized(logLines) {
- logLines.addLast(java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.US).format(java.util.Date()) + " " + line)
+ val stamped = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.US).format(java.util.Date()) + " " + line
+ logLines.addLast(stamped)
while (logLines.size > 300) logLines.removeFirst()
+ logFile?.let { f -> runCatching { if (f.length() > 2_000_000) f.delete(); f.appendText(stamped + "\n") } }
}
}
fun logText(): String = synchronized(logLines) { logLines.joinToString("\n") }
- fun chipOf(d: UsbDevice): String? = SUPPORTED[d.vendorId to d.productId]
+ fun chipOf(d: UsbDevice): Chip? = SUPPORTED[d.vendorId to d.productId]
+
+ /** The chip behind a USB ID, for tests and the status line. */
+ fun chipOf(vendorId: Int, productId: Int): Chip? = SUPPORTED[vendorId to productId]
private fun knownOnly(d: UsbDevice): String? = KNOWN[d.vendorId to d.productId]
@Synchronized
fun start(context: Context, sightings: (List<MonitorSighting>) -> Unit) {
val app = context.applicationContext
onSightings = sightings
+ if (com.rfsentinel.app.BuildConfig.DEBUG) logFile = java.io.File(app.filesDir, "usbwifi.log")
if (receiver == null) {
val r = object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
@@ -94,6 +133,17 @@ object UsbWifi {
ContextCompat.registerReceiver(app, r, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
receiver = r
}
+ if (com.rfsentinel.app.BuildConfig.DEBUG && cmdReceiver == null) {
+ val r = object : BroadcastReceiver() {
+ override fun onReceive(c: Context, intent: Intent) {
+ val cmd = intent.getStringExtra("cmd") ?: return
+ log("adb command: $cmd")
+ Rtl8822buMonitor.commands.add(cmd)
+ }
+ }
+ ContextCompat.registerReceiver(app, r, IntentFilter(ACTION_CMD), ContextCompat.RECEIVER_EXPORTED)
+ cmdReceiver = r
+ }
connect(app)
}
@@ -101,6 +151,8 @@ object UsbWifi {
fun stop(context: Context) {
receiver?.let { runCatching { context.applicationContext.unregisterReceiver(it) } }
receiver = null
+ cmdReceiver?.let { runCatching { context.applicationContext.unregisterReceiver(it) } }
+ cmdReceiver = null
stopAdapter("")
onSightings = null
}
@@ -129,11 +181,16 @@ object UsbWifi {
}
val chip = chipOf(d)!!
runningDevice = d.deviceName
- status = "USB WiFi ($chip) · starting…"
- log("Starting $chip (${"%04x:%04x".format(d.vendorId, d.productId)})")
+ status = "USB WiFi (${chip.name}) · starting…"
+ log("Starting ${chip.name} (${"%04x:%04x".format(d.vendorId, d.productId)})")
thread = Thread({
runCatching {
- Rtl8821auMonitor.run(context, d, { s -> status = s }) { list -> onSightings?.invoke(list) }
+ val onStatus: (String) -> Unit = { s -> status = s }
+ val onFrames: (List<MonitorSighting>) -> Unit = { list -> onSightings?.invoke(list) }
+ when (chip.driver) {
+ Driver.RTL88XXAU -> Rtl8821auMonitor.run(context, d, onStatus, onFrames)
+ Driver.RTL88X2BU -> Rtl8822buMonitor.run(context, d, chip.name, onStatus, onFrames)
+ }
}.onFailure { log("Driver stopped: ${it.message}"); status = "USB WiFi adapter error: ${it.message}" }
synchronized(this) { if (runningDevice == d.deviceName) runningDevice = null }
}, "usb-wifi").also { it.start() }
@@ -142,8 +199,10 @@ object UsbWifi {
@Synchronized
private fun stopAdapter(newStatus: String) {
Rtl8821auMonitor.abort()
+ Rtl8822buMonitor.abort()
runningDevice = null
thread = null
status = newStatus
+ com.rfsentinel.app.esp.HeardBy.usb.clear() // unplugged or stopped: nothing is "heard by USB" any more
}
}
diff --git a/app/src/test/java/com/rfsentinel/app/usb/UsbWifiDriverTest.kt b/app/src/test/java/com/rfsentinel/app/usb/UsbWifiDriverTest.kt
new file mode 100644
index 0000000..d17b3fe
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/usb/UsbWifiDriverTest.kt
@@ -0,0 +1,371 @@
+package com.rfsentinel.app.usb
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.io.IOException
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+class UsbWifiDriverTest {
+
+ // --- 802.11 frames ---
+
+ private fun mac(s: String) = s.split(":").map { it.toInt(16).toByte() }.toByteArray()
+
+ private fun beacon(bssid: String, ssid: String, vararg ies: Pair<Int, ByteArray>): ByteArray {
+ val hdr = ByteArray(24)
+ hdr[0] = 0x80.toByte() // management, beacon
+ System.arraycopy(mac("ff:ff:ff:ff:ff:ff"), 0, hdr, 4, 6)
+ System.arraycopy(mac(bssid), 0, hdr, 10, 6)
+ System.arraycopy(mac(bssid), 0, hdr, 16, 6)
+ val fixed = ByteArray(12)
+ val body = mutableListOf<Byte>()
+ body += 0.toByte(); body += ssid.length.toByte(); body += ssid.toByteArray().toList()
+ for ((tag, v) in ies) { body += tag.toByte(); body += v.size.toByte(); body += v.toList() }
+ return hdr + fixed + body.toByteArray()
+ }
+
+ private fun probeRequest(sa: String): ByteArray {
+ val f = ByteArray(24 + 2)
+ f[0] = 0x40 // management, probe request
+ System.arraycopy(mac("ff:ff:ff:ff:ff:ff"), 0, f, 4, 6)
+ System.arraycopy(mac(sa), 0, f, 10, 6)
+ System.arraycopy(mac("ff:ff:ff:ff:ff:ff"), 0, f, 16, 6)
+ return f
+ }
+
+ private fun dataToAp(sa: String, bssid: String): ByteArray {
+ val f = ByteArray(24 + 8)
+ f[0] = 0x08; f[1] = 0x01 // data, to-DS
+ System.arraycopy(mac(bssid), 0, f, 4, 6)
+ System.arraycopy(mac(sa), 0, f, 10, 6)
+ System.arraycopy(mac("01:00:5e:00:00:fb"), 0, f, 16, 6)
+ return f
+ }
+
+ @Test
+ fun beaconsUseTheirOwnChannelOverTheTunedOne() {
+ val t = MonitorFrames()
+ val b = beacon("00:30:44:11:22:33", "Patrol-12", 3 to byteArrayOf(6))
+ t.frame(b, 0, b.size, channel = 7, rssi = -70, now = 1000)
+ val out = t.drain(1000, 5000)
+ assertEquals(1, out.size)
+ val s = out[0]
+ assertEquals("00:30:44:11:22:33", s.mac)
+ assertEquals("Patrol-12", s.ssid)
+ assertTrue(s.isAccessPoint)
+ assertEquals(2437, s.frequencyMhz)
+ assertEquals(-70, s.rssi)
+ }
+
+ @Test
+ fun fiveGhzBeaconTakesTheHtPrimaryChannel() {
+ val t = MonitorFrames()
+ val b = beacon("00:30:44:aa:bb:cc", "", 61 to ByteArray(22).also { it[0] = 44 })
+ t.frame(b, 0, b.size, channel = 40, rssi = -80, now = 0)
+ assertEquals(5220, t.drain(0, 5000).single().frequencyMhz)
+ }
+
+ @Test
+ fun clientsAreTrackedWithTheirAccessPoint() {
+ val t = MonitorFrames()
+ val p = probeRequest("da:a1:19:00:00:01")
+ t.frame(p, 0, p.size, channel = 1, rssi = -60, now = 0)
+ val d = dataToAp("3c:22:fb:00:00:02", "00:30:44:11:22:33")
+ t.frame(d, 0, d.size, channel = 36, rssi = -65, now = 0)
+ val out = t.drain(0, 5000).associateBy { it.mac }
+ assertFalse(out.getValue("da:a1:19:00:00:01").isAccessPoint)
+ assertEquals(2412, out.getValue("da:a1:19:00:00:01").frequencyMhz)
+ assertEquals("00:30:44:11:22:33", out.getValue("3c:22:fb:00:00:02").bssid)
+ assertEquals(5180, out.getValue("3c:22:fb:00:00:02").frequencyMhz)
+ assertEquals(0 to 2, t.live(0, 1000))
+ }
+
+ @Test
+ fun clientCaptureCanBeTurnedOff() {
+ val t = MonitorFrames().apply { captureClients = false }
+ val p = probeRequest("da:a1:19:00:00:01")
+ t.frame(p, 0, p.size, channel = 1, rssi = -60, now = 0)
+ assertTrue(t.drain(0, 5000).isEmpty())
+ }
+
+ @Test
+ fun groupAddressesAndShortFramesAreIgnored() {
+ val t = MonitorFrames()
+ val b = beacon("01:00:5e:00:00:01", "x")
+ t.frame(b, 0, b.size, 1, -50, 0)
+ val zero = beacon("00:00:00:00:00:00", "x")
+ t.frame(zero, 0, zero.size, 1, -50, 0)
+ t.frame(ByteArray(10), 0, 10, 1, -50, 0)
+ assertEquals(0, t.tracked)
+ }
+
+ @Test
+ fun signalFollowsTheLastFewSecondsAndOldDevicesArePruned() {
+ val t = MonitorFrames()
+ val b = beacon("00:30:44:11:22:33", "a")
+ t.frame(b, 0, b.size, 1, -40, now = 0)
+ t.frame(b, 0, b.size, 1, -70, now = 500)
+ assertEquals(-40, t.drain(500, 5000).single().rssi) // strongest of the recent burst
+ t.frame(b, 0, b.size, 1, -75, now = 5000)
+ assertEquals(-75, t.drain(5000, 5000).single().rssi) // the car moved away
+ assertTrue(t.drain(5000 + MonitorFrames.PRUNE_MS + 1, 5000).isEmpty())
+ assertEquals(0, t.tracked)
+ }
+
+ @Test
+ fun framesWithoutASignalReadingKeepTheLastRealOne() {
+ val t = MonitorFrames()
+ val b = beacon("c0:94:35:fc:65:48", "Alaindion", 3 to byteArrayOf(1))
+ t.frame(b, 0, b.size, 1, rssi = null, now = 0)
+ assertEquals(MonitorFrames.NOMINAL_RSSI, t.drain(0, 5000).single().rssi) // nothing measured yet
+ t.frame(b, 0, b.size, 1, rssi = -82, now = 100) // the first real reading wins at once
+ t.frame(b, 0, b.size, 1, rssi = null, now = 200)
+ assertEquals(-82, t.drain(200, 5000).single().rssi)
+ }
+
+ @Test
+ fun channelFrequencies() {
+ assertEquals(2412, MonitorFrames.frequencyOf(1))
+ assertEquals(2472, MonitorFrames.frequencyOf(13))
+ assertEquals(2484, MonitorFrames.frequencyOf(14))
+ assertEquals(5180, MonitorFrames.frequencyOf(36))
+ assertEquals(5825, MonitorFrames.frequencyOf(165))
+ assertEquals(0, MonitorFrames.frequencyOf(0))
+ }
+
+ // --- 8822B RX path ---
+
+ private fun le32(b: ByteArray, at: Int, v: Int) { for (k in 0 until 4) b[at + k] = (v ushr (8 * k)).toByte() }
+
+ /** One RX descriptor + optional 32-byte PHY status + frame (+ FCS), padded to 8 bytes. */
+ private fun rxUnit(frame: ByteArray, crcErr: Boolean = false, c2h: Boolean = false, pwdb: Int? = null, rate: Int = 4): ByteArray {
+ val drv = if (pwdb != null) 32 else 0
+ val pkt = frame.size + 4
+ val len = (24 + drv + pkt + 7) and 7.inv()
+ val u = ByteArray(len)
+ var d0 = pkt or ((drv / 8) shl 16)
+ if (crcErr) d0 = d0 or (1 shl 14)
+ if (pwdb != null) d0 = d0 or (1 shl 26)
+ le32(u, 0, d0)
+ if (c2h) u[11] = 0x10
+ u[12] = rate.toByte()
+ if (pwdb != null) { u[24] = (if (rate <= 3) 0 else 1).toByte(); u[24 + 1] = pwdb.toByte(); u[24 + 2] = (pwdb - 6).toByte() }
+ System.arraycopy(frame, 0, u, 24 + drv, frame.size)
+ return u
+ }
+
+ @Test
+ fun aggregatedRxBufferIsWalkedAndBadFramesSkipped() {
+ val good = beacon("00:30:44:11:22:33", "Good", 3 to byteArrayOf(11))
+ val bad = beacon("00:30:44:44:55:66", "Bad")
+ val c2h = beacon("00:30:44:77:88:99", "Firmware")
+ val buf = rxUnit(good, pwdb = 110 - 58) + rxUnit(bad, crcErr = true) + rxUnit(c2h, c2h = true) +
+ rxUnit(probeRequest("da:a1:19:00:00:01"))
+ val t = MonitorFrames()
+ Rtl8822buMonitor.parseRxBuf(buf, buf.size, ch = 11, twoPaths = true, sink = t)
+ val out = t.drain(System.currentTimeMillis(), 60_000).associateBy { it.mac }
+ assertEquals(setOf("00:30:44:11:22:33", "da:a1:19:00:00:01"), out.keys)
+ assertEquals(-58, out.getValue("00:30:44:11:22:33").rssi) // strongest path from the PHY status
+ assertEquals(-60, out.getValue("da:a1:19:00:00:01").rssi) // no PHY status: nominal
+ }
+
+ @Test
+ fun singleAntennaOnPathBIsDetected() {
+ // Wise Tiger 8812BU: one antenna, on path B; path A hears 25-35 dB less (measured).
+ val s = Rtl8822buMonitor.PathSense()
+ repeat(39) { s.add(-70, -40) }
+ assertNull(s.verdict()) // not enough frames yet
+ s.add(-70, -40)
+ assertEquals(1, s.verdict())
+ // Noise-floor frames don't vote.
+ val quiet = Rtl8822buMonitor.PathSense()
+ repeat(100) { quiet.add(-110, -100) }
+ assertNull(quiet.verdict())
+ }
+
+ @Test
+ fun twoAntennaAdaptersKeepBothPaths() {
+ val s = Rtl8822buMonitor.PathSense()
+ val r = java.util.Random(7)
+ // Both paths connected: multipath fades swing either way, rarely by 10 dB.
+ repeat(2000) { val a = -60 + r.nextInt(17) - 8; s.add(a, -60 + r.nextInt(17) - 8) }
+ repeat(30) { s.add(-50, -62) }; repeat(30) { s.add(-62, -50) }
+ assertNull(s.verdict())
+ }
+
+ @Test
+ fun ofdmFramesFeedThePathVote() {
+ val ofdm = rxUnit(beacon("00:30:44:11:22:33", "x"), pwdb = 40, rate = 4) // path A 40, B 34 (helper)
+ ofdm[24 + 1] = 40; ofdm[24 + 2] = 72 // A -70 dBm, B -38 dBm
+ val s = Rtl8822buMonitor.PathSense()
+ val t = MonitorFrames()
+ repeat(40) { Rtl8822buMonitor.parseRxBuf(ofdm, ofdm.size, ch = 36, twoPaths = true, sink = t, sense = s) }
+ assertEquals(1, s.verdict())
+ assertEquals(-38, t.drain(System.currentTimeMillis(), 60_000).single().rssi)
+ }
+
+ @Test
+ fun truncatedRxBufferStopsCleanly() {
+ val u = rxUnit(beacon("00:30:44:11:22:33", "x"))
+ val t = MonitorFrames()
+ Rtl8822buMonitor.parseRxBuf(u, u.size - 12, ch = 1, twoPaths = false, sink = t)
+ assertEquals(0, t.tracked)
+ }
+
+ @Test
+ fun rxDescriptorFields() {
+ val u = rxUnit(beacon("00:30:44:11:22:33", "x"), pwdb = 50, rate = 2)
+ val d = Rtl8822buMonitor.rxDesc(u, 0)
+ assertEquals(32, d.drvInfo)
+ assertTrue(d.physt)
+ assertEquals(2, d.rate)
+ assertEquals(24 + 32, d.frameOffset)
+ assertEquals(u.size, d.next)
+ assertEquals(listOf(-60), Rtl8822buMonitor.phyPaths(u, 24, paths = 2)!!.toList()) // page 0: one CCK value
+ val ofdm = ByteArray(32).also { it[0] = 1; it[1] = 70; it[2] = 0 }
+ assertEquals(listOf(-40, Rtl8822buMonitor.NO_SIGNAL), Rtl8822buMonitor.phyPaths(ofdm, 0, paths = 2)!!.toList())
+ // A corrupt report (seen on CCK frames after moving CCK to path B) isn't a +141 dBm signal.
+ val bad = ByteArray(32).also { it[1] = 251.toByte() }
+ assertEquals(listOf(Rtl8822buMonitor.NO_SIGNAL), Rtl8822buMonitor.phyPaths(bad, 0, paths = 1)!!.toList())
+ }
+
+ @Test
+ fun txDescriptorChecksumMatchesTheLinuxDriver() {
+ // The kernel's H2C GENERAL_INFO descriptor: TXPKTSIZE 32, QSEL 0x13 -> checksum 0x1320.
+ val d = ByteArray(48)
+ Rtl8822buMonitor.setDesc(d, 0x00, 0, 16, 32)
+ Rtl8822buMonitor.setDesc(d, 0x04, 8, 5, 0x13)
+ Rtl8822buMonitor.txDescChecksum(d)
+ assertEquals(0x00000020, Rtl8822bTables.le32(d, 0))
+ assertEquals(0x00001300, Rtl8822bTables.le32(d, 4))
+ assertEquals(0x1320, Rtl8822bTables.le32(d, 0x1C) and 0xffff)
+ }
+
+ // --- channels ---
+
+ @Test
+ fun hopPlanCoversEveryChannelAndAllRadarChannelsInTurn() {
+ val first = Rtl8822buMonitor.hopCycle(0)
+ assertEquals(24, first.size)
+ assertEquals(1, first[0])
+ assertTrue(first.all { MonitorFrames.validChannel(it) })
+ val dfsSeen = (0 until 8).flatMap { Rtl8822buMonitor.hopCycle(it).toList() }.toSet()
+ assertTrue(Rtl8822buMonitor.HOP_DFS.all { it in dfsSeen })
+ assertTrue(Rtl8822buMonitor.HOP_5.all { it in first } && Rtl8822buMonitor.HOP_24.all { it in first })
+ }
+
+ @Test
+ fun rf18SetsTheBandExplicitly() {
+ // 2.4 -> 5 GHz: the band bits come from the channel, not from what the radio was left on.
+ assertEquals(0x10d24, Rtl8822buMonitor.rf18For(0x00c01, 36)) // the vendor's 5 GHz value
+ assertEquals(0x00c09, Rtl8822buMonitor.rf18For(0x10d24, 9)) // and its clean 2.4 GHz one
+ assertEquals(0x30d64, Rtl8822buMonitor.rf18For(0x00c01, 100)) // >= ch 80: sub-band bit 17
+ assertEquals(0x50d95, Rtl8822buMonitor.rf18For(0x00c01, 149)) // > ch 144: bit 18
+ assertEquals(0x07c06, Rtl8822buMonitor.rf18For(0x0f201, 6) and 0xfffff) // other bits kept, BW forced to 20 MHz
+ assertEquals(0x00c01, Rtl8822buMonitor.rf18For(0x18c01, 1)) // bring-up read-back: 5 GHz band + LCK bits dropped
+ }
+
+ @Test
+ fun statsWindowCountsFramesAndResets() {
+ val t = MonitorFrames()
+ val b = beacon("00:30:44:11:22:33", "Patrol-12", 3 to byteArrayOf(6))
+ t.frame(b, 0, b.size, 6, -70, 0); t.frame(b, 0, b.size, 6, -60, 100)
+ val w = t.window()
+ assertEquals(1, w.size)
+ assertTrue(w[0], w[0].contains("2 fr max -60 avg -65 AP"))
+ assertTrue(t.window().isEmpty())
+ }
+
+ @Test
+ fun channelConstantsMatchThePhydmTables() {
+ assertEquals(0, Rtl8822buMonitor.agcBucket(6))
+ assertEquals(1, Rtl8822buMonitor.agcBucket(36))
+ assertEquals(2, Rtl8822buMonitor.agcBucket(120))
+ assertEquals(3, Rtl8822buMonitor.agcBucket(165))
+ assertEquals(0x96a, Rtl8822buMonitor.fcFor(1))
+ assertEquals(0x494, Rtl8822buMonitor.fcFor(44))
+ assertEquals(0x453, Rtl8822buMonitor.fcFor(60))
+ assertEquals(0x452, Rtl8822buMonitor.fcFor(112))
+ assertEquals(0x412, Rtl8822buMonitor.fcFor(149))
+ assertEquals(0x0, Rtl8822buMonitor.rfBeFor(11))
+ assertEquals(0x7, Rtl8822buMonitor.rfBeFor(36))
+ assertEquals(0x6, Rtl8822buMonitor.rfBeFor(100))
+ assertEquals(0x5, Rtl8822buMonitor.rfBeFor(149))
+ assertEquals(0x0, Rtl8822buMonitor.rfBeFor(165))
+ }
+
+ // --- tables and firmware ---
+
+ @Test
+ fun tableWalkerPicksTheBlockForThisRfeAndCut() {
+ val t = intArrayOf(
+ 0x111, 1,
+ 0x80000000.toInt(), 0, 0x40000000, 0, // IF rfe 0
+ 0x222, 2,
+ 0x90000003.toInt(), 0, 0x40000000, 0, // ELSE IF rfe 3
+ 0x333, 3,
+ 0xA0000000.toInt(), 0, // ELSE
+ 0x444, 4,
+ 0xB0000000.toInt(), 0, // ENDIF
+ 0x555, 5,
+ 0x8A000000.toInt(), 0, 0x40000000, 0, // IF cut 10 (any rfe 0)
+ 0x666, 6,
+ 0xB0000000.toInt(), 0
+ )
+ fun run(cut: Int, rfe: Int) = mutableListOf<Int>().also { out -> Rtl8822bTables.walk(t, cut, rfe) { a, _ -> out += a } }
+ assertEquals(listOf(0x111, 0x222, 0x555), run(cut = 2, rfe = 0))
+ assertEquals(listOf(0x111, 0x333, 0x555), run(cut = 2, rfe = 3))
+ assertEquals(listOf(0x111, 0x444, 0x555), run(cut = 2, rfe = 5))
+ assertEquals(listOf(0x111, 0x222, 0x555, 0x666), run(cut = 10, rfe = 0))
+ }
+
+ private fun asset(name: String) = File("src/main/assets/usbwifi/rtl8822b_$name.bin").readBytes()
+ private fun words(name: String) = asset(name).let { b -> IntArray(b.size / 4).also { ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(it) } }
+
+ @Test
+ fun bundledFirmwareIsComplete() {
+ val fw = asset("fw")
+ Rtl8822bTables.checkFirmware(fw)
+ assertEquals(0x200000, Rtl8822bTables.dmemAddr(fw))
+ assertEquals(0, Rtl8822bTables.imemAddr(fw))
+ try {
+ Rtl8822bTables.checkFirmware(fw.copyOf(fw.size - 1)); throw AssertionError("damaged image accepted")
+ } catch (_: IOException) {}
+ }
+
+ @Test
+ fun bundledTablesWalkToPlainRegisterWrites() {
+ for (name in listOf("phy_reg", "agc_tab", "radioa", "radiob")) {
+ val tab = words(name)
+ assertEquals(0, tab.size % 2)
+ for (rfe in listOf(0, 1, 3, 5)) {
+ var n = 0
+ Rtl8822bTables.walk(tab, cut = 2, rfe = rfe) { a, _ ->
+ assertEquals("$name rfe $rfe: condition word leaked as a write", 0, a and 0xC0000000.toInt())
+ n++
+ }
+ assertTrue("$name rfe $rfe applies nothing", n > 100)
+ }
+ }
+ // The AGC table differs per antenna front-end; the walker must actually choose.
+ val agc = words("agc_tab")
+ fun count(rfe: Int) = mutableListOf<Long>().also { l -> Rtl8822bTables.walk(agc, 2, rfe) { a, v -> l += (a.toLong() shl 32) or (v.toLong() and 0xffffffffL) } }
+ assertFalse(count(0) == count(5))
+ }
+
+ // --- adapter list ---
+
+ @Test
+ fun adaptersMapToTheirDrivers() {
+ assertEquals(UsbWifi.Driver.RTL88X2BU, UsbWifi.chipOf(0x0bda, 0xb812)?.driver)
+ assertEquals("RTL8812BU", UsbWifi.chipOf(0x0bda, 0xb812)?.name)
+ assertEquals(UsbWifi.Driver.RTL88X2BU, UsbWifi.chipOf(0x2357, 0x012d)?.driver) // TP-Link Archer T3U
+ assertEquals(UsbWifi.Driver.RTL88XXAU, UsbWifi.chipOf(0x0bda, 0x0811)?.driver) // ALFA AWUS036ACS
+ assertNull(UsbWifi.chipOf(0x0bda, 0x8812))
+ }
+}