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.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
ESP32 boards on USB: OUI-Spy and GhostESP reports
CIS-C0c0dd52ad1dea
diff --git a/README.md b/README.mdindex 936eeb4..dfbcb79 100644--- a/README.md+++ b/README.md@@ -249,6 +249,24 @@ or updated. Enable *Unknown sources* first, then install (or reinstall) the APK,open RF Sentinel once on the phone, and reconnect. Also check **Android Autosettings → Customize launcher** in case it's listed under hidden apps.+## ESP32 boards on USB (optional)++Plug an ESP32 board into the phone with a USB OTG cable while scanning and+RF Sentinel adds what the board reports to its own detections (allow USB access+on the prompt the first time). Supported firmware:++- **[OUI-Spy](https://github.com/colonelpanichacks/oui-spy-unified-blue)**+ (recommended): its Flock-You, Detector and Sky Spy modes stream every+ detection - Flock cameras, your board's watchlist matches, Remote ID drones+ with their position - as they happen.+- **[GhostESP](https://github.com/GhostESP-Revival/GhostESP)**: the Wi-Fi+ networks it scans, about every 10 seconds (no Bluetooth over USB).++Boards with native USB (ESP32-S2/S3/C3/C6) and those with a CP210x or CH340+USB chip work. RF Sentinel only listens: it never sends OUI-Spy anything, and+only asks GhostESP to scan and list networks. Settings shows the board's+status.+## ThemesPick a theme in the setup wizard or under **Settings → Appearance**.diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 6199a87..931b9d2 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -18,6 +18,8 @@<uses-permission android:name="androidx.car.app.MAP_TEMPLATES" /><!-- Android Auto: draw RF Sentinel's own pannable map (devices, cameras, route). --><uses-permission android:name="androidx.car.app.ACCESS_SURFACE" />+ <!-- Optional ESP32 boards (OUI-Spy / GhostESP) on a USB OTG cable. -->+ <uses-feature android:name="android.hardware.usb.host" android:required="false" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt b/app/src/main/java/com/rfsentinel/app/esp/EspBoards.ktnew file mode 100644index 0000000..35a907d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/esp/EspBoards.kt@@ -0,0 +1,115 @@+package com.rfsentinel.app.esp++import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.hardware.usb.UsbDevice+import android.hardware.usb.UsbManager+import androidx.core.content.ContextCompat++/**+ * ESP32 boards on USB (OTG cable), used alongside the phone's own radios while+ * scanning. Supports OUI-Spy (Flock-You, Detector, Sky Spy) and GhostESP.+ * Android asks once per board for permission; plugging a board in while+ * scanning starts it.+ */+object EspBoards {++ private const val ACTION_PERMISSION = "com.rfsentinel.app.ESP_USB_PERMISSION"++ private class Running(val reader: EspReader, val thread: Thread)++ private val running = HashMap<String, Running>()+ private var receiver: BroadcastReceiver? = null+ private var onSightings: ((List<EspSighting>) -> Unit)? = null++ /** Latest status per board, for Settings and the notification. */+ @Volatile var status: String = ""+ private set+ var onStatusChanged: (() -> Unit)? = null++ fun isEsp32(d: UsbDevice) = SerialPort.chipOf(d.vendorId, d.productId) != null++ /** Starts every attached board (asking permission where needed) and watches for new ones. */+ @Synchronized+ fun start(context: Context, sightings: (List<EspSighting>) -> Unit) {+ val app = context.applicationContext+ onSightings = sightings+ if (receiver == null) {+ val r = object : BroadcastReceiver() {+ override fun onReceive(c: Context, intent: Intent) {+ when (intent.action) {+ UsbManager.ACTION_USB_DEVICE_ATTACHED, ACTION_PERMISSION -> connectAll(app)+ UsbManager.ACTION_USB_DEVICE_DETACHED -> {+ deviceOf(intent)?.let { stopBoard(it.deviceName) }+ }+ }+ }+ }+ val filter = IntentFilter().apply {+ addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)+ addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)+ addAction(ACTION_PERMISSION)+ }+ ContextCompat.registerReceiver(app, r, filter, ContextCompat.RECEIVER_NOT_EXPORTED)+ receiver = r+ }+ connectAll(app)+ }++ @Synchronized+ fun stop(context: Context) {+ receiver?.let { runCatching { context.applicationContext.unregisterReceiver(it) } }+ receiver = null+ running.keys.toList().forEach { stopBoard(it) }+ onSightings = null+ setStatus("")+ }++ private fun deviceOf(intent: Intent): UsbDevice? =+ if (android.os.Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)+ else @Suppress("DEPRECATION") intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)++ @Synchronized+ private fun connectAll(context: Context) {+ val mgr = context.getSystemService(UsbManager::class.java) ?: return+ val boards = runCatching { mgr.deviceList.values.filter { isEsp32(it) } }.getOrDefault(emptyList())+ if (boards.isEmpty() && running.isEmpty()) setStatus("")+ for (d in boards) {+ if (running.containsKey(d.deviceName)) continue+ if (!mgr.hasPermission(d)) {+ val pi = PendingIntent.getBroadcast(+ context, 0, Intent(ACTION_PERMISSION).setPackage(context.packageName),+ PendingIntent.FLAG_MUTABLE+ )+ setStatus("ESP32 found - allow USB access on the prompt")+ runCatching { mgr.requestPermission(d, pi) }+ continue+ }+ val conn = mgr.openDevice(d) ?: continue+ val port = SerialPort.open(conn, d)+ if (port == null) { runCatching { conn.close() }; setStatus("ESP32: couldn't open its USB serial port"); continue }+ val reader = EspReader(port, ::setStatus) { list -> onSightings?.invoke(list) }+ val t = Thread({+ runCatching { reader.run() }+ runCatching { port.close() }+ synchronized(this) { running.remove(d.deviceName) }+ }, "esp32-${d.deviceName}")+ running[d.deviceName] = Running(reader, t)+ t.start()+ }+ }++ @Synchronized+ private fun stopBoard(name: String) {+ running.remove(name)?.reader?.stop()+ if (running.isEmpty()) setStatus("ESP32 disconnected")+ }++ private fun setStatus(s: String) {+ status = s+ onStatusChanged?.invoke()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReader.ktnew file mode 100644index 0000000..f7c068a--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt@@ -0,0 +1,86 @@+package com.rfsentinel.app.esp++/**+ * Reads one ESP32 board until [stop] is called. RF Sentinel only listens:+ * OUI-Spy streams its detections by itself and is never sent anything;+ * GhostESP is only ever asked to scan for networks and list them.+ */+class EspReader(+ private val port: SerialPort,+ private val onStatus: (String) -> Unit,+ private val onSightings: (List<EspSighting>) -> Unit+) {+ @Volatile private var stopped = false++ fun stop() { stopped = true }++ fun run() {+ val buf = ByteArray(4096)+ onStatus("ESP32 · listening…")+ val heard = StringBuilder()+ val listenUntil = System.currentTimeMillis() + 4_000+ while (!stopped && System.currentTimeMillis() < listenUntil && !OuiSpyReports.recognises(heard.toString())) {+ val n = port.read(buf, 300)+ if (n > 0) heard.append(String(buf, 0, n))+ }+ if (stopped) return+ if (OuiSpyReports.recognises(heard.toString())) {+ readOuiSpy(heard.toString(), buf)+ return+ }+ // Not streaming on its own: see whether it's GhostESP.+ port.write("help\r\n")+ val banner = readFor(buf, 2_500)+ if (GhostEspReports.recognises(banner)) pollGhostEsp(buf)+ else onStatus("ESP32 connected, but its firmware isn't OUI-Spy or GhostESP")+ }++ private fun readOuiSpy(already: String, buf: ByteArray) {+ val pending = StringBuilder(already)+ var count = 0+ onStatus("OUI-Spy · live")+ while (!stopped) {+ val n = port.read(buf, 500)+ if (n <= 0) continue+ pending.append(String(buf, 0, n))+ while (true) {+ val nl = pending.indexOf('\n')+ if (nl < 0) break+ val line = pending.substring(0, nl)+ pending.delete(0, nl + 1)+ OuiSpyReports.parse(line)?.let {+ count+++ onSightings(listOf(it))+ onStatus("OUI-Spy · live · $count detections")+ }+ }+ if (pending.length > 16_384) pending.setLength(0) // not line-based output (another mode)+ }+ }++ private fun pollGhostEsp(buf: ByteArray) {+ onStatus("GhostESP · live")+ while (!stopped) {+ port.write("scanap\r\n")+ readFor(buf, 6_000)+ if (stopped) break+ port.write("stopscan\r\n")+ readFor(buf, 400)+ port.write("list -a\r\n")+ val networks = GhostEspReports.parseList(readFor(buf, 3_000))+ if (networks.isNotEmpty()) onSightings(networks)+ onStatus("GhostESP · live · ${networks.size} Wi-Fi networks")+ }+ runCatching { port.write("stopscan\r\n") }+ }++ private fun readFor(buf: ByteArray, ms: Long): String {+ val sb = StringBuilder()+ val until = System.currentTimeMillis() + ms+ while (!stopped && System.currentTimeMillis() < until) {+ val n = port.read(buf, 300)+ if (n > 0) sb.append(String(buf, 0, n))+ }+ return sb.toString()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReports.ktnew file mode 100644index 0000000..c2fe3cd--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReports.kt@@ -0,0 +1,133 @@+package com.rfsentinel.app.esp++import com.google.gson.JsonObject+import com.google.gson.JsonParser+import com.rfsentinel.app.detect.Category+import com.rfsentinel.app.detect.Hit+import com.rfsentinel.app.detect.RemoteId++/**+ * One device an ESP32 board reported. RF Sentinel turns it into a normal+ * observation, so all its own detection rules apply on top of [hits].+ */+data class EspSighting(+ val mac: String,+ val rssi: Int,+ val ble: Boolean,+ /** Wi-Fi network name (access points) or Bluetooth device name. */+ val name: String? = null,+ val frequencyMhz: Int = 0,+ val companyId: Int? = null,+ val serviceUuid16: Int? = null,+ /** Drone position (OUI-Spy Sky Spy mode). */+ val remoteId: RemoteId.Info? = null,+ /** Matches the board itself reported. */+ val hits: List<Hit> = emptyList()+)++/**+ * Lines printed by OUI-Spy (colonelpanichacks/oui-spy-unified-blue) in its+ * streaming modes: Flock-You and Detector (`{"event":"detection",...}`) and+ * Sky Spy (`{"mac":..,"drone_lat":..}`).+ */+object OuiSpyReports {++ const val SOURCE = "OUI-Spy board over USB"++ fun recognises(text: String): Boolean =+ "\"event\":\"detection\"" in text || "\"drone_lat\"" in text || "\"status\":\"scanning\"" in text ||+ "OUI-SPY" in text || "[flockyou]" in text++ fun parse(line: String): EspSighting? {+ val t = line.trim()+ if (!t.startsWith("{") || !t.endsWith("}")) return null+ val o = runCatching { JsonParser.parseString(t).asJsonObject }.getOrNull() ?: return null+ return when {+ o.has("drone_lat") -> drone(o)+ o.text("event") == "detection" -> detection(o)+ else -> null+ }+ }++ private fun JsonObject.text(k: String): String? =+ get(k)?.takeIf { !it.isJsonNull }?.let { runCatching { it.asString }.getOrNull() }?.takeIf { it.isNotBlank() }++ private fun JsonObject.number(k: String): Int? =+ get(k)?.takeIf { !it.isJsonNull }?.let { runCatching { it.asInt }.getOrNull() }++ private fun JsonObject.coord(k: String): Double? =+ get(k)?.takeIf { !it.isJsonNull }?.let { runCatching { it.asDouble }.getOrNull() }?.takeIf { it != 0.0 }++ private fun detection(o: JsonObject): EspSighting? {+ val mac = o.text("mac_address")?.uppercase() ?: return null+ val method = o.text("detection_method").orEmpty()+ val ble = o.text("protocol") == "ble" || method.startsWith("ble_")+ val tier = o.number("detection_tier")+ val signature = o.text("matched_signature")+ val hit = when {+ "wildcard_probe" in method -> Hit(Category.ALPR, "Flock camera (wildcard probe)", 80,+ "Reported by OUI-Spy: a Flock-style network probe ($method)", SOURCE)+ method == "wifi_ssid" -> Hit(Category.ALPR, "Flock camera (Wi-Fi name)", 80,+ "Reported by OUI-Spy: Flock network name \"${o.text("ssid") ?: "?"}\"", SOURCE)+ tier != null -> Hit(Category.ALPR, "Possible Flock equipment", when (tier) { 3 -> 70; 2 -> 55; else -> 35 },+ "Reported by OUI-Spy Flock-You ($method, tier $tier)", SOURCE)+ signature != null -> Hit(Category.CUSTOM, "OUI-Spy target: $signature", 70,+ "Matched the watchlist set up on the OUI-Spy board", SOURCE)+ else -> null+ }+ return EspSighting(+ mac = mac, rssi = o.number("rssi") ?: -90, ble = ble,+ name = if (ble) o.text("local_name") ?: o.text("device_name") else o.text("ssid"),+ frequencyMhz = if (ble) 0 else o.number("frequency") ?: 0,+ companyId = o.number("company_id"), serviceUuid16 = o.number("service_uuid"),+ hits = listOfNotNull(hit)+ )+ }++ private fun drone(o: JsonObject): EspSighting? {+ val mac = o.text("mac")?.uppercase() ?: return null+ val info = RemoteId.Info(+ uasId = o.text("basic_id"),+ latitude = o.coord("drone_lat"), longitude = o.coord("drone_long"),+ altitudeGeoM = o.number("drone_altitude")?.toDouble(),+ operatorLatitude = o.coord("pilot_lat"), operatorLongitude = o.coord("pilot_long")+ )+ return EspSighting(+ mac = mac, rssi = o.number("rssi") ?: -90, ble = true, remoteId = info,+ hits = listOf(Hit(Category.DRONE, "Drone broadcasting Remote ID", 95,+ "Reported by OUI-Spy Sky Spy" + (info.uasId?.let { " (ID $it)" } ?: ""), SOURCE))+ )+ }+}++/**+ * GhostESP's `list -a` network list: `[0] SSID: Name, BSSID: AA:BB:..., RSSI: -55, Company: X`+ * (channel / band fields when the firmware prints them).+ */+object GhostEspReports {++ private val ANSI = Regex("""\u001B\[[0-9;]*m""")+ private val ROW = Regex("""\[\d+]\s*SSID:\s*(.*?),\s*BSSID:\s*([0-9A-Fa-f:]{17})(.*)""")+ private val RSSI = Regex("""RSSI:\s*(-?\d+)""")+ private val CHANNEL = Regex("""Channel:\s*(\d+)""")++ fun recognises(text: String): Boolean = "ghost esp" in text.lowercase() || "ghostesp" in text.lowercase()++ fun parseList(text: String): List<EspSighting> = text.lines().mapNotNull { raw ->+ val m = ROW.find(ANSI.replace(raw, "")) ?: return@mapNotNull null+ val ssid = m.groupValues[1].trim().takeUnless { it.isEmpty() || it.equals("(Hidden)", true) }+ val rest = m.groupValues[3]+ val ch = CHANNEL.find(rest)?.groupValues?.get(1)?.toIntOrNull()+ EspSighting(+ mac = m.groupValues[2].uppercase(),+ rssi = RSSI.find(rest)?.groupValues?.get(1)?.toIntOrNull() ?: -90,+ ble = false, name = ssid,+ frequencyMhz = when {+ ch == null -> 0+ ch == 14 -> 2484+ ch in 1..13 -> 2407 + ch * 5+ else -> 5000 + ch * 5+ }+ )+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt b/app/src/main/java/com/rfsentinel/app/esp/SerialPort.ktnew file mode 100644index 0000000..d4cbdb8--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt@@ -0,0 +1,143 @@+package com.rfsentinel.app.esp++import android.hardware.usb.UsbConstants+import android.hardware.usb.UsbDevice+import android.hardware.usb.UsbDeviceConnection+import android.hardware.usb.UsbEndpoint+import android.hardware.usb.UsbInterface++/** A USB serial line to an ESP32 board (115200 8N1). */+interface SerialPort {+ fun write(text: String)+ /** Bytes read into [buf], 0 on timeout, negative on error. */+ fun read(buf: ByteArray, timeoutMs: Int): Int+ fun close()++ /** The USB-serial chips found on ESP32 boards. */+ enum class Chip { NATIVE_USB, CP210X, CH34X }++ companion object {+ fun chipOf(vid: Int, pid: Int): Chip? = when {+ vid == 0x303A -> Chip.NATIVE_USB // Espressif native USB (S2, S3, C3, C6...)+ vid == 0x10C4 && pid == 0xEA60 -> Chip.CP210X // Silicon Labs CP2102 / CP2104+ vid == 0x1A86 && pid in setOf(0x7523, 0x5523, 0x55D4) -> Chip.CH34X // WCH CH340 / CH341 / CH9102+ else -> null+ }++ /** Opens [device] at 115200 baud, or returns null. */+ fun open(conn: UsbDeviceConnection, device: UsbDevice): SerialPort? =+ when (chipOf(device.vendorId, device.productId)) {+ Chip.NATIVE_USB -> CdcAcmPort(conn, device).takeIf { it.open() }+ Chip.CP210X -> Cp210xPort(conn, device).takeIf { it.open() }+ Chip.CH34X -> Ch34xPort(conn, device).takeIf { it.open() }+ null -> null+ }+ }+}++/** Shared bulk-endpoint handling. */+abstract class BulkPort(protected val conn: UsbDeviceConnection) : SerialPort {+ protected var epIn: UsbEndpoint? = null+ protected var epOut: UsbEndpoint? = null+ private val claimed = mutableListOf<UsbInterface>()++ protected fun claim(intf: UsbInterface): Boolean = conn.claimInterface(intf, true).also { if (it) claimed += intf }++ protected fun findBulk(intf: UsbInterface) {+ for (i in 0 until intf.endpointCount) {+ val ep = intf.getEndpoint(i)+ if (ep.type == UsbConstants.USB_ENDPOINT_XFER_BULK) {+ if (ep.direction == UsbConstants.USB_DIR_IN) epIn = ep else epOut = ep+ }+ }+ }++ override fun write(text: String) {+ val out = epOut ?: return+ val b = text.toByteArray()+ conn.bulkTransfer(out, b, b.size, 1000)+ }++ override fun read(buf: ByteArray, timeoutMs: Int): Int {+ val inp = epIn ?: return -1+ return conn.bulkTransfer(inp, buf, buf.size, timeoutMs).coerceAtLeast(0)+ }++ override fun close() {+ claimed.forEach { runCatching { conn.releaseInterface(it) } }+ runCatching { conn.close() }+ }+}++/** USB CDC-ACM: ESP32-S2/S3/C3/C6 native USB. DTR is raised so the firmware sees a host. */+class CdcAcmPort(conn: UsbDeviceConnection, private val device: UsbDevice) : BulkPort(conn) {+ fun open(): Boolean {+ var comm: UsbInterface? = null+ var data: UsbInterface? = null+ for (i in 0 until device.interfaceCount) {+ val intf = device.getInterface(i)+ when (intf.interfaceClass) {+ UsbConstants.USB_CLASS_COMM -> if (comm == null) comm = intf+ UsbConstants.USB_CLASS_CDC_DATA -> if (data == null) data = intf+ }+ }+ val d = data ?: return false+ if (comm != null && !claim(comm)) return false+ if (!claim(d)) return false+ findBulk(d)+ if (epIn == null || epOut == null) return false+ val index = (comm ?: d).id+ // SET_LINE_CODING 115200 8N1, then SET_CONTROL_LINE_STATE with DTR.+ val coding = byteArrayOf(0x00, 0xC2.toByte(), 0x01, 0x00, 0, 0, 8)+ conn.controlTransfer(0x21, 0x20, 0, index, coding, coding.size, 1000)+ conn.controlTransfer(0x21, 0x22, 0x01, index, null, 0, 1000)+ return true+ }+}++/** Silicon Labs CP210x. DTR / RTS stay low so the board's auto-reset circuit leaves it running. */+class Cp210xPort(conn: UsbDeviceConnection, private val device: UsbDevice) : BulkPort(conn) {+ fun open(): Boolean {+ val intf = device.getInterface(0)+ if (!claim(intf)) return false+ findBulk(intf)+ if (epIn == null || epOut == null) return false+ val i = intf.id+ conn.controlTransfer(0x41, 0x00, 0x0001, i, null, 0, 1000) // IFC_ENABLE+ val baud = byteArrayOf(0x00, 0xC2.toByte(), 0x01, 0x00) // 115200+ conn.controlTransfer(0x41, 0x1E, 0, i, baud, baud.size, 1000) // SET_BAUDRATE+ conn.controlTransfer(0x41, 0x03, 0x0800, i, null, 0, 1000) // SET_LINE_CTL 8N1+ conn.controlTransfer(0x41, 0x07, 0x0300, i, null, 0, 1000) // SET_MHS: DTR, RTS low+ return true+ }+}++/**+ * WCH CH340 / CH341, with the vendor requests the Linux ch341 driver uses.+ * DTR / RTS stay released so the ESP32 isn't held in reset.+ */+class Ch34xPort(conn: UsbDeviceConnection, private val device: UsbDevice) : BulkPort(conn) {+ fun open(): Boolean {+ val intf = device.getInterface(0)+ if (!claim(intf)) return false+ findBulk(intf)+ if (epIn == null || epOut == null) return false+ conn.controlTransfer(0xC0, 0x5F, 0, 0, ByteArray(2), 2, 1000) // read version+ out(0xA1, 0, 0) // serial init+ setBaud115200()+ out(0x9A, 0x2518, 0xC3) // LCR: RX + TX on, 8N1+ setBaud115200()+ out(0xA4, 0xFF, 0) // modem control: DTR, RTS released+ return true+ }++ private fun out(request: Int, value: Int, index: Int) =+ conn.controlTransfer(0x40, request, value, index, null, 0, 1000)++ private fun setBaud115200() {+ // ch341: factor = 0x10000 - 1532620800 / 115200 with divisor 3 (+0x80 = don't wait for a full buffer).+ val factor = 0x10000 - (1532620800L / 115200).toInt()+ out(0x9A, 0x1312, (factor and 0xFF00) or 0x83)+ out(0x9A, 0x0F2C, factor and 0xFF)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex ecce9fc..ce6e7e5 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -87,6 +87,7 @@ class ScanForegroundService : Service() {private const val CELL_CHECK_MS = 15_000Lprivate const val CELL_REPEAT_MS = 30 * 60_000Lprivate const val PLACING_MAX_AGE_MS = 30_000L+ private const val ESP_HIT_TTL_MS = 5 * 60_000Lprivate const val PLACING_MAX_ACCURACY_M = 50f/**@@ -238,6 +239,8 @@ class ScanForegroundService : Service() {// Re-evaluated on every start command, so Settings changes apply live.if (Prefs.bleEnabled(this)) { bleEngine.stop(); startBle() } else stopBle()if (Prefs.wifiEnabled(this)) startWifiPolling() else stopWifiPolling()+ // ESP32 boards on USB (OUI-Spy / GhostESP): their reports join the same pipeline.+ com.rfsentinel.app.esp.EspBoards.start(this) { list -> pipeline.post { list.forEach(::processEsp) } }updateLocationUpdates()startHousekeeping()startCellChecks()@@ -379,12 +382,12 @@ class ScanForegroundService : Service() {// ---- Pipeline -------------------------------------------------------------- private fun process(a: Advert) {+ private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null) {val now = a.timestampval mac = a.mac// Remote ID messages arrive one type at a time; merge every packet.- var remoteId: RemoteId.Info? = null+ var remoteId: RemoteId.Info? = reportedRemoteIdif (a.isBle) {a.serviceData[Advert.uuid16(0xFFFA)]?.let { remoteId = RemoteId.decodeBle(it, DeviceRegistry.remoteIdOf(mac)) }} else {@@ -437,6 +440,28 @@ class ScanForegroundService : Service() {}}+ /** Matches an ESP32 board reported, kept a few minutes so re-classification keeps them. */+ private val espHits = HashMap<String, Pair<Long, List<Hit>>>()++ /** One ESP32 report: becomes a normal observation, with the board's own matches added. */+ private fun processEsp(e: com.rfsentinel.app.esp.EspSighting) {+ val now = System.currentTimeMillis()+ if (e.hits.isNotEmpty()) {+ espHits[e.mac] = now to e.hits+ classified.remove(e.mac) // re-classify with the new evidence+ }+ val advert = if (e.ble) Advert(+ mac = e.mac, source = Advert.Source.BLE, rssi = e.rssi, name = e.name,+ manufacturerData = e.companyId?.let { mapOf(it to ByteArray(0)) }.orEmpty(),+ serviceUuids = listOfNotNull(e.serviceUuid16?.let { Advert.uuid16(it) }),+ timestamp = now+ ) else Advert(+ mac = e.mac, source = Advert.Source.WIFI, rssi = e.rssi, name = e.name,+ wifi = Advert.WifiInfo(e.frequencyMhz, "", null, emptyList()), timestamp = now+ )+ process(advert, e.remoteId)+ }+private fun classify(a: Advert, now: Long): Classified {val macVendor = VendorDb.macVendor(a.mac)val identity = DeviceIntel.identify(a, macVendor)@@ -447,7 +472,8 @@ class ScanForegroundService : Service() {val raw = SignatureEngine.classify(a) +OuiWatchlist.hits(a.mac, a.name, listOfNotNull(macVendor) + companyVendors) +DeviceRegistry.inheritedHits(a.mac) +- listOfNotNull(DeviceRegistry.clusterHit(a.mac, now))+ listOfNotNull(DeviceRegistry.clusterHit(a.mac, now)) ++ espHits[a.mac]?.takeIf { now - it.first < ESP_HIT_TTL_MS }?.second.orEmpty()val hits = EvidenceFusion.fuse(raw.filter { Prefs.categoryEnabled(this, it.category) })return Classified(now, hits, identity, vendor)}@@ -703,6 +729,7 @@ class ScanForegroundService : Service() {}override fun onDestroy() {+ com.rfsentinel.app.esp.EspBoards.stop(this)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.ktindex f5e8305..daa980b 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -112,11 +112,19 @@ class SettingsActivity : AppCompatActivity() {binding.trackerIgnoreButton.visibility = if (n > 0 || paused) android.view.View.VISIBLE else android.view.View.GONE}+ /** ESP32 boards on USB (OUI-Spy / GhostESP) are picked up while scanning. */+ private fun updateEspStatus() {+ val s = com.rfsentinel.app.esp.EspBoards.status+ binding.espStatusText.text = "ESP32 on USB (OUI-Spy or GhostESP): " ++ s.ifBlank { "plug one in with an OTG cable while scanning to add its detections" }+ }+private fun updateBannerButtons() {binding.bannerClearButton.isEnabled = ThemeManager.hasBanner(this)}override fun onDestroy() {+ com.rfsentinel.app.esp.EspBoards.onStatusChanged = nullstopObservingPrefetch?.invoke()super.onDestroy()}@@ -243,6 +251,8 @@ class SettingsActivity : AppCompatActivity() {// Locationbinding.followSwitch.isChecked = Prefs.followerAlerts(this)updateTrackerIgnoreText()+ updateEspStatus()+ com.rfsentinel.app.esp.EspBoards.onStatusChanged = { runOnUiThread { updateEspStatus() } }binding.trackerIgnoreButton.setOnClickListener {com.rfsentinel.app.data.TrackerMutes.clear(this)Prefs.setTrackerFollowPausedUntil(this, 0L)diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex c8581c8..86f0483 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -347,6 +347,12 @@android:layout_height="wrap_content"android:text="Warn when approaching a known speed or red-light camera (same download)" />+ <TextView+ android:id="@+id/espStatusText"+ style="@style/SettingsLabel"+ android:paddingTop="6dp"+ android:textSize="12sp" />+<com.google.android.material.switchmaterial.SwitchMaterialandroid:id="@+id/autoRecordSwitch"android:layout_width="match_parent"diff --git a/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt b/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.ktnew file mode 100644index 0000000..8015cc6--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/esp/EspReportsTest.kt@@ -0,0 +1,75 @@+package com.rfsentinel.app.esp++import com.rfsentinel.app.detect.Category+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/** Lines in the formats OUI-Spy and GhostESP print (made-up addresses and names). */+class EspReportsTest {++ @Test+ fun ouiSpyFlockYouWildcardProbe() {+ val s = OuiSpyReports.parse("""{"event":"detection","detection_method":"wifi_wildcard_probe","detection_tier":3,"protocol":"wifi_2_4ghz","mac_address":"70:c9:4e:11:22:33","oui":"70:c9:4e","device_name":"","rssi":-71,"channel":6,"frequency":2437,"ssid":""}""")!!+ assertEquals("70:C9:4E:11:22:33", s.mac)+ assertFalse(s.ble)+ assertEquals(2437, s.frequencyMhz)+ assertEquals(Category.ALPR, s.hits.single().category)+ assertEquals(80, s.hits.single().confidence)+ }++ @Test+ fun ouiSpyFlockYouBleTierAndDetectorTarget() {+ val ble = OuiSpyReports.parse("""{"event":"detection","detection_method":"ble_mfg","detection_tier":2,"protocol":"ble","mac_address":"aa:bb:cc:00:11:22","oui":"aa:bb:cc","device_name":"Penguin-1","rssi":-60,"channel":255,"frequency":0,"ssid":""}""")!!+ assertTrue(ble.ble)+ assertEquals("Penguin-1", ble.name)+ assertEquals(55, ble.hits.single().confidence)++ val target = OuiSpyReports.parse("""{"event":"detection","protocol":"ble","detection_method":"ble_oui","mac_address":"00:25:df:aa:bb:cc","addr_type":"public","rssi":-55,"rssi_min":-70,"rssi_max":-50,"company_id":845,"service_uuid":null,"local_name":"","device_name":"","match_method":"oui","matched_signature":"00:25:DF","first_seen_ms":1}""")!!+ assertEquals(845, target.companyId)+ assertNull(target.serviceUuid16)+ assertEquals("OUI-Spy target: 00:25:DF", target.hits.single().label)+ }++ @Test+ fun ouiSpySkySpyDrone() {+ val d = OuiSpyReports.parse("""{"mac":"60:60:1f:01:02:03","rssi":-80,"drone_lat":10.501000,"drone_long":-20.502000,"drone_altitude":120,"pilot_lat":10.500000,"pilot_long":-20.500000,"basic_id":"1581F5FJD123"}""")!!+ assertEquals("1581F5FJD123", d.remoteId?.uasId)+ assertEquals(10.501, d.remoteId!!.latitude!!, 1e-9)+ assertEquals(Category.DRONE, d.hits.single().category)+ }++ @Test+ fun ouiSpyIgnoresOtherLines() {+ assertNull(OuiSpyReports.parse("""{"status":"scanning"}"""))+ assertNull(OuiSpyReports.parse("[flockyou] DETECT-OUI mac=70:c9:4e:11:22:33 rssi=-70"))+ assertNull(OuiSpyReports.parse("{not json"))+ assertTrue(OuiSpyReports.recognises("boot...\n{\"status\":\"scanning\"}\n"))+ assertFalse(OuiSpyReports.recognises("Ghost ESP Commands:"))+ }++ @Test+ fun ghostEspNetworkList() {+ val text = "\u001B[0;32m[0] SSID: Example Net, BSSID: 34:53:D2:C4:5D:E6, RSSI: -55, Company: Unknown\u001B[0m\n" ++ "[1] SSID: (Hidden), BSSID: aa:bb:cc:dd:ee:ff, RSSI: -80, Channel: 11, Company: X\n" ++ "some other log line\n"+ val list = GhostEspReports.parseList(text)+ assertEquals(2, list.size)+ assertEquals("Example Net", list[0].name)+ assertEquals(-55, list[0].rssi)+ assertNull(list[1].name)+ assertEquals("AA:BB:CC:DD:EE:FF", list[1].mac)+ assertEquals(2462, list[1].frequencyMhz)+ assertTrue(GhostEspReports.recognises("Ghost ESP Commands:"))+ }++ @Test+ fun espChipsAreRecognised() {+ assertEquals(SerialPort.Chip.NATIVE_USB, SerialPort.chipOf(0x303A, 0x1001))+ assertEquals(SerialPort.Chip.CP210X, SerialPort.chipOf(0x10C4, 0xEA60))+ assertEquals(SerialPort.Chip.CH34X, SerialPort.chipOf(0x1A86, 0x7523))+ assertNull(SerialPort.chipOf(0x0BDA, 0x0811)) // not an ESP32 serial board+ }+}