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.

Mesh radios: Meshtastic and MeshCore nodes heard over USB or Bluetooth go on the map, read-only (experimental, untested on hardware); CH9102 and CH343 boards open as CDC ACM

CIS-C05a2777693157
diff --git a/README.md b/README.md
index 7498585..632f34a 100644
--- a/README.md
+++ b/README.md
@@ -268,6 +268,7 @@ Everything the app does, grouped by area.
<summary><b>Hardware</b></summary>
- ESP32 boards over USB OTG (OUI-Spy, GhostESP, Marauder incl. dual-band ESP32-C5 boards, or through a Flipper Zero) or Bluetooth (OUI-SPY App-Controlled) add their detections and extend range
+- **Mesh radios:** a Meshtastic or MeshCore radio on USB or Bluetooth puts the nodes it hears on the map, read-only (experimental, untested on hardware)
- **USB WiFi adapters in monitor mode** over OTG, no root: RTL8811AU / RTL8821AU (e.g. ALFA AWUS036ACS, 2.4 GHz; 5 GHz experimental, Settings → External hardware), **RTL8812AU** (e.g. ALFA AWUS036ACH, 2.4 + 5 GHz, experimental), **RTL8812BU / RTL8822BU** (2.4 + 5 GHz, e.g. TP-Link Archer T3U, Wise Tiger AC1200), **RTL8814AU** (ALFA AWUS1900, 2.4 + 5 GHz), **MT7612U** (ALFA AWUS036ACM, 2.4 + 5 GHz), **MT7921AU** (ALFA AWUS036AXML / AXM, WiFi 6E: 2.4 + 5 + **6 GHz**), **RTL8187** (ALFA AWUS036H), **RT3070** (ALFA AWUS036NH / NEH) and, experimental, **AR9271** (ALFA AWUS036NHA), **RT5370 / RT5372** and **MT7610U** (2.4 + 5 GHz). No Android scan limit, longer range, and **client devices** (laptops, phones, cameras connected to a network) the phone's WiFi scan can't see. Single-antenna dongles are detected and handled automatically
- **Requested networks:** the WiFi names nearby devices ask for (probe requests), from a USB adapter or a Marauder board, in an optional list; **watch** a name to get an alert whenever any device asks for it
- **USB Bluetooth adapters** as a second Bluetooth LE scanner, no root: the Bluetooth part of an MT7921AU, RTL8821AU or RTL8822BU combo adapter, or a USB Bluetooth dongle (standard controllers, Realtek RTL8761B / 8761C and others), listening only, with LE Coded long range where the chip has it; devices it hears get a **USB BT** badge (Settings → External hardware)
@@ -643,6 +644,7 @@ merges into the list with a blue **ESP32** badge.
| [GhostESP](https://github.com/GhostESP-Revival/GhostESP) | USB | The WiFi networks it scans, about every 10 s |
| [FREE-WiLi 2](https://freewili.com) | USB | The WiFi networks its ESP32-C5 scans from its console's WiFi menu (2.4 + 5 GHz) |
| [ESP32 Marauder](https://github.com/justcallmekoko/ESP32Marauder) | USB, or through a Flipper Zero | WiFi networks and client devices from its passive beacon and probe sniffers, batched every 2 s; on ESP32-C5 boards (Marauder v8, BFFB v2, LilyGo T-Dongle C5, C5 DevKit) both 2.4 and 5 GHz |
+| [Meshtastic](https://meshtastic.org) / [MeshCore](https://meshcore.co.uk) radio | USB, or Bluetooth (Settings → External hardware → Pair mesh radio) | Nodes heard over LoRa, with their name and position; MQTT-only nodes and old list entries are left out. Experimental, untested on hardware |
<details>
<summary><b>Supported boards, Marauder, Flipper Zero and OUI-SPY setup</b></summary>
diff --git a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
index 153d409..b4a4e83 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/EspReader.kt
@@ -1,5 +1,7 @@
package com.rfsentinel.app.esp
+import com.rfsentinel.app.link.MeshProto
+
/**
* Reads one ESP32 board until [stop] is called. RF Sentinel only listens and
* asks read-only questions: OUI-Spy may be sent `CMD:VERSION` and, in
@@ -8,6 +10,7 @@ package com.rfsentinel.app.esp
* `help` and its passive `sniffbeacon` / `sniffprobe` sniffers; a FREE-WiLi 2 ([freeWili])
* only gets its console's WiFi-menu keys and its access-point scan. An ESP32-C5 with the
* V2X2MAP firmware streams on its own and is never sent anything that changes it ([pollV2x]).
+ * A Meshtastic or MeshCore radio is asked for its node list and left listening ([probeMesh]).
*/
/** V2X frames carry no signal strength (the board sends the frame only); its position is what counts. */
private const val V2X_NOMINAL_RSSI = -70
@@ -59,12 +62,61 @@ class EspReader(
return
}
heard += banner
+ // 5. A mesh radio answers only in its own framing.
+ if (probeMesh(buf)) return
+ heard += probeText
}
- // 5. OUI-Spy - or a quiet board: Flock-You and Sky Spy say nothing until they find
+ // 6. OUI-Spy - or a quiet board: Flock-You and Sky Spy say nothing until they find
// something, so keep listening rather than giving up on it.
readOuiSpy(heard, buf)
}
+ /** What a board that isn't a mesh radio said meanwhile: a quiet OUI-Spy's first detection can land here. */
+ private val probeText = StringBuilder()
+
+ private fun meshFrames(frames: MeshFrames, buf: ByteArray, ms: Long, each: (ByteArray) -> Boolean): Boolean {
+ val until = System.currentTimeMillis() + ms
+ while (!stopped && System.currentTimeMillis() < until) {
+ val n = port.read(buf, 300)
+ if (n <= 0) continue
+ if (probeText.length < 16_384) probeText.append(text.decode(buf, n))
+ if (frames.feed(buf, n).map(each).any { it }) return true
+ }
+ return false
+ }
+
+ private fun probeMesh(buf: ByteArray): Boolean {
+ val want = MeshFrames.meshtastic(MeshProto.wantConfig(MeshProto.NODES_ONLY))
+ port.write(want)
+ val log = MeshtasticLog()
+ fun read(f: ByteArray) = runCatching { MeshProto.readFromRadio(f) }.getOrDefault(MeshProto.From.Other)
+ fun take(m: MeshProto.From) {
+ if (m == MeshProto.From.Rebooted) port.write(want)
+ log.feed(m)?.let { onSightings(listOf(it)) }
+ }
+ val frames = MeshFrames(meshtastic = true)
+ if (meshFrames(frames, buf, 2_500) { f -> read(f).also(::take) != MeshProto.From.Other }) {
+ var beat = System.currentTimeMillis()
+ while (!stopped) {
+ meshFrames(frames, buf, 1_000) { f -> take(read(f)); false }
+ onStatus("Meshtastic radio · live · ${log.heard.size} nodes heard")
+ val now = System.currentTimeMillis()
+ if (now - beat > 300_000) { beat = now; port.write(MeshFrames.meshtastic(MeshProto.heartbeat())) }
+ }
+ return true
+ }
+ val core = MeshCoreLog()
+ val replies = MeshFrames(meshtastic = false)
+ port.write(MeshFrames.meshCore(MeshCoreLog.APP_START))
+ if (!meshFrames(replies, buf, 2_500) { MeshCoreLog.isSelfInfo(it) }) return false
+ port.write(MeshFrames.meshCore(MeshCoreLog.GET_CONTACTS))
+ while (!stopped) {
+ meshFrames(replies, buf, 1_000) { f -> core.feed(f)?.let { onSightings(listOf(it)) }; false }
+ onStatus("MeshCore radio · live · ${core.heard.size} nodes heard")
+ }
+ return true
+ }
+
private fun readOuiSpy(already: String, buf: ByteArray) {
var mode = OuiSpyReports.modeOf(already)
val pending = StringBuilder()
diff --git a/app/src/main/java/com/rfsentinel/app/esp/MeshBle.kt b/app/src/main/java/com/rfsentinel/app/esp/MeshBle.kt
new file mode 100644
index 0000000..cc520de
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/esp/MeshBle.kt
@@ -0,0 +1,255 @@
+package com.rfsentinel.app.esp
+
+import android.annotation.SuppressLint
+import android.bluetooth.BluetoothGatt
+import android.bluetooth.BluetoothGattCallback
+import android.bluetooth.BluetoothGattCharacteristic
+import android.bluetooth.BluetoothGattDescriptor
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothProfile
+import android.bluetooth.le.ScanCallback
+import android.bluetooth.le.ScanFilter
+import android.bluetooth.le.ScanResult
+import android.bluetooth.le.ScanSettings
+import android.content.Context
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.os.ParcelUuid
+import android.util.Log
+import com.rfsentinel.app.link.MeshNode
+import com.rfsentinel.app.link.MeshProto
+import java.util.UUID
+
+/**
+ * A Meshtastic or MeshCore radio paired over Bluetooth, read while scanning: every node it hears lands on the map.
+ * Only listens: it asks for the node list and never changes the radio. The radio serves one app at a time.
+ */
+@SuppressLint("MissingPermission")
+object MeshBle {
+ private const val TAG = "MeshBle"
+ private const val MTU = 512
+ private const val RECONNECT_MS = 10_000L
+ private const val SETUP_TIMEOUT_MS = 45_000L // leaves time for the pairing prompt
+ private val NUS: UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
+ private val NUS_WRITE = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e")
+ private val NUS_NOTIFY = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e")
+ private val TO_RADIO = UUID.fromString("f75c76d2-129e-4dad-a1dd-7866124401e7")
+ private val FROM_RADIO = UUID.fromString("2c55e69e-4993-11ed-b878-0242ac120002")
+ private val FROM_NUM = UUID.fromString("ed9da18c-a800-4f66-a670-aa7547e34453")
+ private val CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
+
+ private val main = Handler(Looper.getMainLooper())
+ private var appContext: Context? = null
+ private var address: String? = null
+ private var gatt: BluetoothGatt? = null
+ private var onSightings: ((List<EspSighting>) -> Unit)? = null
+ private var active = false
+ private var live = false
+
+ private var toRadio: BluetoothGattCharacteristic? = null
+ private var fromRadio: BluetoothGattCharacteristic? = null
+ private var meshtastic: MeshtasticLog? = null
+ private var meshCore: MeshCoreLog? = null
+ // GATT runs one operation at a time.
+ private val writes = ArrayDeque<ByteArray>()
+ private var busy = false
+ private var wantRead = false
+
+ @Volatile var status = ""; private set
+ var onStatusChanged: (() -> Unit)? = null
+ private fun setStatus(s: String) { status = s; onStatusChanged?.invoke() }
+
+ class Found(val address: String, val name: String?, val rssi: Int)
+
+ /** Looks for radios nearby for [ms]. MeshCore has no service of its own (Nordic UART): the name tells them apart in the list. */
+ fun find(context: Context, ms: Long = 6_000L, done: (List<Found>) -> Unit) {
+ val scanner = runCatching {
+ context.getSystemService(BluetoothManager::class.java)?.adapter?.takeIf { it.isEnabled }?.bluetoothLeScanner
+ }.getOrNull()
+ if (scanner == null) { done(emptyList()); return }
+ val seen = LinkedHashMap<String, Found>()
+ val cb = object : ScanCallback() {
+ override fun onScanResult(callbackType: Int, r: ScanResult) {
+ val name = r.scanRecord?.deviceName ?: runCatching { r.device.name }.getOrNull()
+ val addr = r.device.address
+ main.post { seen[addr] = Found(addr, name ?: seen[addr]?.name, r.rssi) }
+ }
+ }
+ val filters = listOf(MeshNode.SERVICE, NUS).map { ScanFilter.Builder().setServiceUuid(ParcelUuid(it)).build() }
+ val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(0).build()
+ try { scanner.startScan(filters, settings, cb) } catch (e: Exception) { Log.w(TAG, "search failed", e); done(emptyList()); return }
+ main.postDelayed({
+ runCatching { scanner.stopScan(cb) }
+ done(seen.values.sortedByDescending { it.rssi })
+ }, ms)
+ }
+
+ /** Starts (or keeps) the link to the radio at [radio] while scanning. */
+ fun start(context: Context, radio: String, sightings: (List<EspSighting>) -> Unit) = main.post {
+ onSightings = sightings
+ if (active && address == radio) return@post
+ stopNow()
+ appContext = context.applicationContext
+ address = radio
+ active = true
+ connect()
+ }
+
+ fun stop() = main.post { stopNow() }
+
+ private fun stopNow() {
+ active = false
+ main.removeCallbacks(connector); main.removeCallbacks(stall)
+ drop()
+ setStatus("")
+ }
+
+ private fun drop() {
+ gatt?.let { g -> runCatching { g.disconnect(); g.close() } }
+ gatt = null; live = false; busy = false; wantRead = false
+ writes.clear(); toRadio = null; fromRadio = null; meshtastic = null; meshCore = null
+ }
+
+ private val connector = Runnable { connect() }
+ private val stall = Runnable { if (active && !live) lost("mesh radio: no answer - reconnecting…") }
+
+ private fun lost(why: String) {
+ drop()
+ if (!active) return
+ setStatus(why)
+ main.removeCallbacks(stall); main.removeCallbacks(connector)
+ main.postDelayed(connector, RECONNECT_MS)
+ }
+
+ private fun connect() {
+ val ctx = appContext ?: return
+ if (!active) return
+ if (!OuiSpyBle.canConnect(ctx)) { setStatus("Mesh radio: allow \"Nearby devices\" to connect to it"); return }
+ val adapter = ctx.getSystemService(BluetoothManager::class.java)?.adapter ?: return
+ if (!adapter.isEnabled) { lost("Mesh radio: Bluetooth is off"); return }
+ val device = runCatching { adapter.getRemoteDevice(address) }.getOrNull() ?: return
+ setStatus("Mesh radio: connecting…")
+ gatt = device.connectGatt(ctx, false, callback, BluetoothDevice.TRANSPORT_LE)
+ main.postDelayed(stall, SETUP_TIMEOUT_MS)
+ }
+
+ private fun send(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray): Boolean =
+ if (Build.VERSION.SDK_INT >= 33) g.writeCharacteristic(c, value, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) == 0
+ else {
+ @Suppress("DEPRECATION") run { c.value = value; g.writeCharacteristic(c) }
+ }
+
+ private fun pump(g: BluetoothGatt) {
+ if (busy) return
+ val c = toRadio ?: return
+ val next = writes.removeFirstOrNull()
+ if (next != null) { busy = send(g, c, next); return }
+ if (wantRead) { wantRead = false; fromRadio?.let { busy = g.readCharacteristic(it) } }
+ }
+
+ private fun report(s: EspSighting?, count: Int, what: String) {
+ if (!live) { live = true; main.removeCallbacks(stall) }
+ s?.let { onSightings?.invoke(listOf(it)) }
+ setStatus("$what · live · $count node${if (count == 1) "" else "s"} heard")
+ }
+
+ private fun onFrame(g: BluetoothGatt, f: ByteArray) {
+ val log = meshCore ?: return
+ if (MeshCoreLog.isSelfInfo(f)) { writes.addLast(MeshCoreLog.GET_CONTACTS); pump(g) }
+ report(log.feed(f), log.heard.size, "MeshCore radio")
+ }
+
+ private fun onRead(g: BluetoothGatt, value: ByteArray) {
+ busy = false
+ val log = meshtastic
+ if (value.isNotEmpty() && log != null) {
+ wantRead = true
+ val m = runCatching { MeshProto.readFromRadio(value) }.getOrNull()
+ if (m != null) report(log.feed(m), log.heard.size, "Meshtastic radio")
+ }
+ pump(g)
+ }
+
+ private val callback = object : BluetoothGattCallback() {
+ override fun onConnectionStateChange(g: BluetoothGatt, st: Int, newState: Int) {
+ main.post {
+ if (g !== gatt) return@post
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ setStatus("Mesh radio: connected, setting up…")
+ if (!g.requestMtu(MTU)) g.discoverServices()
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) lost("Mesh radio: out of reach - reconnecting…")
+ }
+ }
+
+ override fun onMtuChanged(g: BluetoothGatt, mtu: Int, st: Int) { main.post { if (g === gatt) g.discoverServices() } }
+
+ override fun onServicesDiscovered(g: BluetoothGatt, st: Int) {
+ main.post {
+ if (g !== gatt) return@post
+ val mt = g.getService(MeshNode.SERVICE)
+ val nus = g.getService(NUS)
+ val notify = if (mt != null) {
+ toRadio = mt.getCharacteristic(TO_RADIO); fromRadio = mt.getCharacteristic(FROM_RADIO)
+ meshtastic = MeshtasticLog()
+ mt.getCharacteristic(FROM_NUM)
+ } else {
+ toRadio = nus?.getCharacteristic(NUS_WRITE)
+ meshCore = MeshCoreLog()
+ nus?.getCharacteristic(NUS_NOTIFY)
+ }
+ val cccd = notify?.getDescriptor(CCCD)
+ if (cccd == null || toRadio == null) { setStatus("Mesh radio: not a Meshtastic or MeshCore radio"); return@post }
+ g.setCharacteristicNotification(notify, true)
+ if (Build.VERSION.SDK_INT >= 33) g.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)
+ else @Suppress("DEPRECATION") run { cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE; g.writeDescriptor(cccd) }
+ }
+ }
+
+ override fun onDescriptorWrite(g: BluetoothGatt, d: BluetoothGattDescriptor, st: Int) {
+ main.post {
+ if (g !== gatt) return@post
+ writes.addLast(if (meshtastic != null) MeshProto.wantConfig(MeshProto.NODES_ONLY) else MeshCoreLog.APP_START)
+ pump(g)
+ }
+ }
+
+ override fun onCharacteristicWrite(g: BluetoothGatt, c: BluetoothGattCharacteristic, st: Int) {
+ main.post {
+ if (g !== gatt) return@post
+ busy = false
+ if (meshtastic != null) wantRead = true
+ pump(g)
+ }
+ }
+
+ override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray, st: Int) {
+ main.post { if (g === gatt) onRead(g, value) }
+ }
+
+ @Deprecated("Android 12 and older")
+ @Suppress("DEPRECATION")
+ override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, st: Int) {
+ if (Build.VERSION.SDK_INT >= 33) return
+ val v = c.value ?: ByteArray(0)
+ main.post { if (g === gatt) onRead(g, v) }
+ }
+
+ private fun changed(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray) {
+ main.post {
+ if (g !== gatt) return@post
+ if (c.uuid == FROM_NUM) { wantRead = true; pump(g) } else if (c.uuid == NUS_NOTIFY) onFrame(g, value)
+ }
+ }
+
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray) = changed(g, c, value)
+
+ @Deprecated("Android 12 and older")
+ @Suppress("DEPRECATION")
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic) {
+ if (Build.VERSION.SDK_INT >= 33) return
+ changed(g, c, c.value ?: return)
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/esp/MeshRadio.kt b/app/src/main/java/com/rfsentinel/app/esp/MeshRadio.kt
new file mode 100644
index 0000000..83ff678
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/esp/MeshRadio.kt
@@ -0,0 +1,135 @@
+package com.rfsentinel.app.esp
+
+import com.rfsentinel.app.link.MeshProto
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/** LoRa nodes report no RSSI of their own in a node list: the weakest a LoRa radio still hears. */
+private const val NOMINAL_RSSI = -120
+/** A node in the radio's list counts as heard here only this recently: the list keeps nodes for days. */
+private const val RECENT_S = 30 * 60L
+private const val MAX_FRAME = 512
+
+/** A mesh node has no MAC on the air: a locally administered address made from its node number or key. */
+private fun nodeMac(kind: Int, id: ByteArray) =
+ (listOf(0x06, kind) + id.take(4).map { it.toInt() and 0xFF }).joinToString(":") { "%02X".format(it) }
+
+/** What a Meshtastic radio tells its phone, as sightings: only nodes it heard over LoRa, never over MQTT. */
+class MeshtasticLog(private val nowS: () -> Long = { System.currentTimeMillis() / 1000 }) {
+ private var me = 0L
+ private val names = HashMap<Long, String>()
+ private val spots = HashMap<Long, Pair<Double, Double>>()
+ val heard = HashSet<Long>()
+
+ fun feed(m: MeshProto.From): EspSighting? {
+ when (m) {
+ is MeshProto.From.MyInfo -> me = m.nodeNum
+ is MeshProto.From.NodeInfo -> {
+ if (m.name.isNotEmpty()) names[m.num] = m.name
+ m.position?.let { spots[m.num] = it }
+ if (m.num != me && !m.viaMqtt && nowS() - m.lastHeard < RECENT_S) return sighting(m.num, NOMINAL_RSSI)
+ }
+ is MeshProto.From.Packet -> {
+ if (m.from == 0L || m.from == me || m.viaMqtt) return null
+ when (m.port) {
+ MeshProto.PORT_NODEINFO_APP -> MeshProto.userName(m.payload).takeIf { it.isNotEmpty() }?.let { names[m.from] = it }
+ MeshProto.PORT_POSITION_APP -> MeshProto.position(m.payload)?.let { spots[m.from] = it }
+ }
+ return sighting(m.from, m.rxRssi.takeIf { it != 0 } ?: NOMINAL_RSSI)
+ }
+ else -> Unit
+ }
+ return null
+ }
+
+ private fun sighting(num: Long, rssi: Int): EspSighting {
+ heard += num
+ val id = ByteArray(4) { (num ushr (24 - 8 * it)).toByte() }
+ return EspSighting(nodeMac(0x4D, id), rssi, ble = true, name = "Meshtastic: ${names[num] ?: "!%08x".format(num)}", position = spots[num])
+ }
+}
+
+/**
+ * MeshCore's companion protocol ("Companion Radio" firmware): the radio pushes every advert it hears.
+ * Its contact list only supplies names and positions: contacts can be months old. Read-only: no message is
+ * fetched or sent and the radio's settings stay as they are.
+ */
+class MeshCoreLog(private val nowMs: () -> Long = System::currentTimeMillis) {
+ private class Contact(val name: String, val position: Pair<Double, Double>?)
+ private val contacts = HashMap<String, Contact>()
+ private var rssi = NOMINAL_RSSI
+ private var rssiAt = 0L
+ val heard = HashSet<String>()
+
+ fun feed(f: ByteArray): EspSighting? {
+ when (f.firstOrNull()?.toInt()?.and(0xFF)) {
+ RESP_CONTACT -> if (f.size >= CONTACT_LEN) contacts[key(f)] = contact(f)
+ PUSH_NEW_ADVERT -> if (f.size >= CONTACT_LEN) { contacts[key(f)] = contact(f); return sighting(f) }
+ PUSH_ADVERT -> if (f.size >= 33) return sighting(f)
+ PUSH_LOG_RX -> if (f.size >= 3) { rssi = f[2].toInt(); rssiAt = nowMs() } // comes just before the advert it carried
+ }
+ return null
+ }
+
+ private fun key(f: ByteArray) = f.copyOfRange(1, 33).joinToString("") { "%02x".format(it) }
+
+ private fun contact(f: ByteArray): Contact {
+ val b = ByteBuffer.wrap(f).order(ByteOrder.LITTLE_ENDIAN)
+ val end = (100 until 132).firstOrNull { f[it].toInt() == 0 } ?: 132
+ val lat = b.getInt(136); val lon = b.getInt(140)
+ return Contact(String(f, 100, end - 100, Charsets.UTF_8), if (lat == 0 && lon == 0) null else lat / 1e6 to lon / 1e6)
+ }
+
+ private fun sighting(f: ByteArray): EspSighting {
+ val k = key(f)
+ heard += k
+ val c = contacts[k]
+ val level = if (nowMs() - rssiAt < 2_000) rssi else NOMINAL_RSSI
+ return EspSighting(nodeMac(0x43, f.copyOfRange(1, 5)), level, ble = true, name = "MeshCore: ${c?.name?.ifEmpty { null } ?: k.take(8)}", position = c?.position)
+ }
+
+ companion object {
+ const val RESP_SELF_INFO = 5
+ private const val RESP_CONTACT = 3
+ private const val PUSH_ADVERT = 0x80
+ private const val PUSH_LOG_RX = 0x88
+ private const val PUSH_NEW_ADVERT = 0x8A
+ private const val CONTACT_LEN = 148
+ /** CMD_APP_START: the command, 7 reserved bytes, the app's name. */
+ val APP_START = byteArrayOf(1, 0, 0, 0, 0, 0, 0, 0) + "RF Sentinel".toByteArray()
+ val GET_CONTACTS = byteArrayOf(4)
+ fun isSelfInfo(f: ByteArray) = f.size >= 36 && f[0].toInt() == RESP_SELF_INFO
+ }
+}
+
+/** Frames on a mesh radio's USB serial line, between its log text: Meshtastic's or MeshCore's framing. */
+class MeshFrames(private val meshtastic: Boolean) {
+ private var buf = ByteArray(0)
+ private val header = if (meshtastic) 4 else 3
+
+ private fun u8(i: Int) = buf[i].toInt() and 0xFF
+ private fun startsAt(i: Int) =
+ if (meshtastic) u8(i) == 0x94 && (i + 1 >= buf.size || u8(i + 1) == 0xC3) else u8(i) == '>'.code
+
+ fun feed(b: ByteArray, n: Int): List<ByteArray> {
+ buf += b.copyOf(n)
+ val out = ArrayList<ByteArray>()
+ var i = 0
+ while (true) {
+ while (i < buf.size && !startsAt(i)) i++
+ if (i + header > buf.size) break
+ val len = if (meshtastic) (u8(i + 2) shl 8) or u8(i + 3) else u8(i + 1) or (u8(i + 2) shl 8)
+ if (len == 0 || len > MAX_FRAME) { i++; continue }
+ if (i + header + len > buf.size) break
+ out += buf.copyOfRange(i + header, i + header + len)
+ i += header + len
+ }
+ buf = buf.copyOfRange(i, buf.size)
+ return out
+ }
+
+ companion object {
+ fun meshtastic(p: ByteArray) = byteArrayOf(0x94.toByte(), 0xC3.toByte(), (p.size ushr 8).toByte(), p.size.toByte()) + p
+ fun meshCore(p: ByteArray) = byteArrayOf('<'.code.toByte(), p.size.toByte(), (p.size ushr 8).toByte()) + p
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt b/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt
index 8549581..7a61079 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/SerialPort.kt
@@ -9,19 +9,22 @@ import android.hardware.usb.UsbInterface
/** A USB serial line to an ESP32 board (115200 8N1). */
interface SerialPort {
fun write(text: String)
+ fun write(bytes: ByteArray)
/** 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; FREEWILI is the FREE-WiLi 2's console (CDC-ACM). */
- enum class Chip { NATIVE_USB, CP210X, CH34X, FREEWILI }
+ enum class Chip { NATIVE_USB, CP210X, CH34X, CDC_BRIDGE, FREEWILI }
companion object {
fun chipOf(vid: Int, pid: Int): Chip? = when {
vid == 0x303A -> Chip.NATIVE_USB // Espressif native USB (S2, S3, C3, C5, C6...)
+ vid == 0x239A || vid == 0x2886 || vid == 0x2E8A -> Chip.NATIVE_USB // nRF52 / RP2040 mesh radios (RAK, Heltec T114, T-Echo, Seeed)
vid == 0x0483 && pid == 0x5740 -> Chip.NATIVE_USB // Flipper Zero (USB-UART bridge to its ESP32 board)
vid == 0x10C4 && pid == 0xEA60 -> Chip.CP210X // Silicon Labs CP2102 / CP2104
- vid == 0x1A86 && pid in setOf(0x7523, 0x5523, 0x55D4) -> Chip.CH34X // WCH CH340 / CH341 / CH9102
+ vid == 0x1A86 && pid in setOf(0x7523, 0x5523) -> Chip.CH34X // WCH CH340 / CH341
+ vid == 0x1A86 && pid in setOf(0x55D3, 0x55D4) -> Chip.CDC_BRIDGE // WCH CH343 / CH9102: plain CDC ACM, as Linux drives them
vid == 0x093C && pid == 0x205A -> Chip.FREEWILI // FREE-WiLi 2 console (its ESP32-C5 does WiFi)
else -> null
}
@@ -30,7 +33,7 @@ interface SerialPort {
fun open(conn: UsbDeviceConnection, device: UsbDevice): SerialPort? =
when (chipOf(device.vendorId, device.productId)) {
Chip.NATIVE_USB -> CdcAcmPort(conn, device).takeIf { it.open() }
- Chip.FREEWILI -> CdcAcmPort(conn, device, raiseDtr = false).takeIf { it.open() }
+ Chip.FREEWILI, Chip.CDC_BRIDGE -> CdcAcmPort(conn, device, raiseDtr = false).takeIf { it.open() } // DTR low: no auto-reset
Chip.CP210X -> Cp210xPort(conn, device).takeIf { it.open() }
Chip.CH34X -> Ch34xPort(conn, device).takeIf { it.open() }
null -> null
@@ -55,10 +58,11 @@ abstract class BulkPort(protected val conn: UsbDeviceConnection) : SerialPort {
}
}
- override fun write(text: String) {
+ override fun write(text: String) = write(text.toByteArray())
+
+ override fun write(bytes: ByteArray) {
val out = epOut ?: return
- val b = text.toByteArray()
- conn.bulkTransfer(out, b, b.size, 1000)
+ conn.bulkTransfer(out, bytes, bytes.size, 1000)
}
override fun read(buf: ByteArray, timeoutMs: Int): Int {
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
index af25818..b441ce4 100644
--- a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
@@ -56,6 +56,8 @@ object MeshNode {
/** One line for the screens, "" while off. */
@Volatile var status = ""; private set
+ /** What the node reports, for the map (on this thread). */
+ @Volatile var heard: ((MeshProto.From) -> Unit)? = null
/** Connected, set up, and the RFSentinel channel in place. */
@Volatile var ready = false; private set
@Volatile var lastSent = 0L; private set
@@ -412,6 +414,7 @@ object MeshNode {
}
private fun handle(m: MeshProto.From) {
+ heard?.invoke(m)
when (m) {
is MeshProto.From.MyInfo -> myNode = m.nodeNum
is MeshProto.From.ChannelInfo -> channels[m.index] = m
@@ -424,7 +427,7 @@ object MeshNode {
}
is MeshProto.From.Queue -> if (m.res != 0) Log.i(TAG, "node queue: ${m.res}, ${m.free} free")
MeshProto.From.Rebooted -> lost("restarted")
- MeshProto.From.Other -> Unit
+ is MeshProto.From.NodeInfo, MeshProto.From.Other -> Unit
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt b/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt
index 1d4470e..e3b3d63 100644
--- a/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt
@@ -14,6 +14,10 @@ object MeshProto {
const val BROADCAST = 0xFFFFFFFFL
/** want_config_id asking for the node's config and channels without its node list (much shorter). */
const val CONFIG_ONLY = 69420
+ /** want_config_id asking for the node list without the config. */
+ const val NODES_ONLY = 69421
+ const val PORT_POSITION_APP = 3
+ const val PORT_NODEINFO_APP = 4
/** Largest payload of one packet (Constants.DATA_PAYLOAD_LEN). */
const val MAX_PAYLOAD = 233
const val PRIORITY_BACKGROUND = 10
@@ -26,6 +30,9 @@ object MeshProto {
fun wantConfig(nonce: Int): ByteArray = W().apply { uint(3, nonce.toLong() and 0xFFFFFFFFL) }.bytes()
+ /** Keeps the serial API open: the radio drops a client that's silent for 15 minutes. */
+ fun heartbeat(): ByteArray = W().apply { bytes(7, ByteArray(0)) }.bytes()
+
/** A MeshPacket for the node to send (ToRadio.packet). */
fun packet(to: Long, channel: Int, port: Int, payload: ByteArray, id: Long, hopLimit: Int, priority: Int): ByteArray =
W().apply {
@@ -56,7 +63,9 @@ object MeshProto {
/** LoRaConfig: hop limit (0 = the firmware's default), region (0 = not set: the radio stays off). */
data class Lora(val hopLimit: Int, val region: Int, val txEnabled: Boolean) : From()
data class ConfigComplete(val id: Long) : From()
- class Packet(val from: Long, val to: Long, val channel: Int, val port: Int, val payload: ByteArray, val rxRssi: Int) : From()
+ class Packet(val from: Long, val to: Long, val channel: Int, val port: Int, val payload: ByteArray, val rxRssi: Int, val viaMqtt: Boolean = false) : From()
+ /** An entry of the radio's node list. */
+ class NodeInfo(val num: Long, val name: String, val position: Pair<Double, Double>?, val lastHeard: Long, val viaMqtt: Boolean) : From()
data class Queue(val res: Int, val free: Int) : From()
object Rebooted : From()
object Other : From()
@@ -69,6 +78,7 @@ object MeshProto {
when {
f == 2 && w == 2 -> { out = readPacket(r.bytes()); true }
f == 3 && w == 2 -> { out = readMyInfo(r.bytes()); true }
+ f == 4 && w == 2 -> { out = readNode(r.bytes()); true }
f == 5 && w == 2 -> { out = readConfig(r.bytes()); true }
f == 7 && w == 0 -> { out = From.ConfigComplete(r.varint() and 0xFFFFFFFFL); true }
f == 8 && w == 0 -> { if (r.varint() != 0L) out = From.Rebooted; true }
@@ -81,7 +91,7 @@ object MeshProto {
}
private fun readPacket(b: ByteArray): From {
- var from = 0L; var to = 0L; var channel = 0; var port = -1; var payload = ByteArray(0); var rssi = 0
+ var from = 0L; var to = 0L; var channel = 0; var port = -1; var payload = ByteArray(0); var rssi = 0; var mqtt = false
val r = R(b)
r.fields { f, w ->
when {
@@ -100,10 +110,55 @@ object MeshProto {
true
}
f == 12 && w == 0 -> { rssi = r.varint().toInt(); true }
+ f == 14 && w == 0 -> { mqtt = r.varint() != 0L; true }
+ else -> false
+ }
+ }
+ return From.Packet(from, to, channel, port, payload, rssi, mqtt)
+ }
+
+ private fun readNode(b: ByteArray): From {
+ var num = 0L; var name = ""; var spot: Pair<Double, Double>? = null; var heard = 0L; var mqtt = false
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 1 && w == 0 -> { num = r.varint() and 0xFFFFFFFFL; true }
+ f == 2 && w == 2 -> { name = userName(r.bytes()); true }
+ f == 3 && w == 2 -> { spot = position(r.bytes()); true }
+ f == 5 && w == 5 -> { heard = r.fixed32(); true }
+ f == 8 && w == 0 -> { mqtt = r.varint() != 0L; true }
+ else -> false
+ }
+ }
+ return From.NodeInfo(num, name, spot, heard, mqtt)
+ }
+
+ /** A User message's long name, or its short name. */
+ fun userName(b: ByteArray): String {
+ var long = ""; var short = ""
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 2 && w == 2 -> { long = String(r.bytes(), Charsets.UTF_8); true }
+ f == 3 && w == 2 -> { short = String(r.bytes(), Charsets.UTF_8); true }
+ else -> false
+ }
+ }
+ return long.ifEmpty { short }
+ }
+
+ /** A Position message as latitude to longitude, or null without a fix. */
+ fun position(b: ByteArray): Pair<Double, Double>? {
+ var lat = 0; var lon = 0
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 1 && w == 5 -> { lat = r.fixed32().toInt(); true }
+ f == 2 && w == 5 -> { lon = r.fixed32().toInt(); true }
else -> false
}
}
- return From.Packet(from, to, channel, port, payload, rssi)
+ return if (lat == 0 && lon == 0) null else lat / 1e7 to lon / 1e7
}
private fun readMyInfo(b: ByteArray): From {
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 f5de28c..c138762 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -467,6 +467,11 @@ class ScanForegroundService : Service() {
pipeline.post { list.forEach(::processEsp) }
}
} ?: com.rfsentinel.app.esp.OuiSpyBle.stop()
+ // A Meshtastic or MeshCore radio paired over Bluetooth, unless Sentinel Link already holds it (see startMesh).
+ val link = com.rfsentinel.app.link.LinkStore
+ Prefs.meshRadio(this)?.takeUnless { link.meshOn(this) && it.equals(link.meshNode(this), ignoreCase = true) }?.let { addr ->
+ com.rfsentinel.app.esp.MeshBle.start(this, addr) { list -> pipeline.post { list.forEach(::processEsp) } }
+ } ?: com.rfsentinel.app.esp.MeshBle.stop()
updateLink()
updateLocationUpdates()
startHousekeeping()
@@ -1017,6 +1022,8 @@ class ScanForegroundService : Service() {
meshLastName = 0L
pipeline.postDelayed(meshFlush, MESH_TICK_MS)
}
+ val meshLog = com.rfsentinel.app.esp.MeshtasticLog()
+ com.rfsentinel.app.link.MeshNode.heard = { m -> meshLog.feed(m)?.let { s -> pipeline.post { processEsp(s) } } }
com.rfsentinel.app.link.MeshNode.start(this, node, key) { com.rfsentinel.app.link.PhoneLink.meshIn(it) }
}
@@ -1025,6 +1032,7 @@ class ScanForegroundService : Service() {
meshOutbox = null
pipeline.removeCallbacks(meshFlush)
com.rfsentinel.app.link.MeshNode.stop()
+ com.rfsentinel.app.link.MeshNode.heard = null
}
/**
@@ -1956,6 +1964,7 @@ class ScanForegroundService : Service() {
if (onlineWatchLazy.isInitialized()) onlineWatch.stop() // not built just to be stopped
com.rfsentinel.app.esp.OuiSpyBle.onLiveChanged = null // its stop must not restart the phone's scan here
com.rfsentinel.app.esp.OuiSpyBle.stop()
+ com.rfsentinel.app.esp.MeshBle.stop()
stopLink()
// External hardware is gone with the scan: its "heard by" marks (External filter, badges) go too.
com.rfsentinel.app.esp.HeardBy.esp.clear()
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 f1df60a..fe0f41f 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -521,6 +521,57 @@ class SettingsActivity : AppCompatActivity() {
binding.ouiSpyText.text = if (board == null) "OUI-SPY over Bluetooth: not paired"
else com.rfsentinel.app.esp.OuiSpyBle.status.ifBlank { "OUI-SPY $board: connects while scanning" }
binding.ouiSpyButton.text = if (board == null) "Pair OUI-SPY board" else "Change or forget OUI-SPY board"
+ val radio = Prefs.meshRadio(this)
+ binding.meshRadioText.text = if (radio == null) "Mesh radio over Bluetooth: not paired"
+ else com.rfsentinel.app.esp.MeshBle.status.ifBlank { "Mesh radio: connects while scanning" }
+ binding.meshRadioButton.text = if (radio == null) "Pair mesh radio" else "Change or forget mesh radio"
+ }
+
+ private val meshConnectPermission = registerForActivityResult(
+ androidx.activity.result.contract.ActivityResultContracts.RequestPermission()
+ ) { granted -> if (granted) pairMeshRadio() }
+
+ /** Picks the Meshtastic or MeshCore radio whose heard nodes go on the map. */
+ private fun pairMeshRadio() {
+ if (!com.rfsentinel.app.esp.OuiSpyBle.canConnect(this)) {
+ meshConnectPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT); return
+ }
+ val looking = MaterialAlertDialogBuilder(this)
+ .setTitle("Looking for mesh radios…")
+ .setMessage("Keep the radio powered and close by. A radio connected to another app doesn't show up.")
+ .setNegativeButton("Cancel", null)
+ .show()
+ com.rfsentinel.app.esp.MeshBle.find(this) { found ->
+ if (!looking.isShowing || isFinishing || isDestroyed) return@find
+ looking.dismiss()
+ val current = Prefs.meshRadio(this)
+ val labels = found.map { "${it.name ?: "Mesh radio"} (${it.address}, ${it.rssi} dBm)" }.toMutableList()
+ if (current != null) labels += "Forget the paired radio"
+ if (labels.isEmpty()) {
+ MaterialAlertDialogBuilder(this)
+ .setTitle("No mesh radio found")
+ .setMessage("Check that it has power, its Bluetooth is on, and the Meshtastic or MeshCore app isn't connected to it.")
+ .setPositiveButton("Try again") { _, _ -> pairMeshRadio() }
+ .setNegativeButton("OK", null)
+ .show()
+ return@find
+ }
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Which mesh radio?")
+ .setItems(labels.toTypedArray()) { _, i ->
+ if (i < found.size) {
+ Prefs.setMeshRadio(this, found[i].address)
+ com.rfsentinel.app.link.MeshNode.pair(this, found[i].address)
+ } else {
+ Prefs.setMeshRadio(this, null)
+ com.rfsentinel.app.esp.MeshBle.stop()
+ }
+ updateEspStatus()
+ if (com.rfsentinel.app.service.ScanForegroundService.isRunning) com.rfsentinel.app.service.ScanForegroundService.start(this)
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
}
private val ouiSpyConnectPermission = registerForActivityResult(
@@ -789,6 +840,8 @@ class SettingsActivity : AppCompatActivity() {
"RTL8811AU / 8821AU (ALFA AWUS036ACS), RTL8812BU / 8822BU, RTL8814AU (AWUS1900), MT7612U (AWUS036ACM), " +
"MT7921AU (AWUS036AXML, WiFi 6E: 2.4, 5 and 6 GHz, experimental), " +
"RTL8187 (AWUS036H), RT3070 (AWUS036NH / NEH), RT5370 / RT5372 (experimental), MT7610U (experimental), AR9271 (AWUS036NHA, experimental).\n\n" +
+ "• Meshtastic or MeshCore radios, on USB or over Bluetooth (experimental): the nodes they hear land on the map. " +
+ "Read-only, nothing on the radio changes.\n\n" +
"AWUS036ACS 5 GHz (experimental, off by default): the RTL8811AU / 8821AU also hops 5 GHz channels 36-48 and " +
"149-165. Untested on every unit: if it misbehaves, turn it off and send the adapter log. Applies when the adapter is plugged in.\n\n" +
"Adapter light: the AWUS036ACS blinks with received traffic; switch it off to keep it dark (for example in a car at night). " +
@@ -2493,6 +2546,7 @@ class SettingsActivity : AppCompatActivity() {
override fun onDestroy() {
com.rfsentinel.app.esp.EspBoards.onStatusChanged = null
com.rfsentinel.app.esp.OuiSpyBle.onStatusChanged = null
+ com.rfsentinel.app.esp.MeshBle.onStatusChanged = null
stopObservingPrefetch?.invoke()
stopObservingDeflock?.invoke()
super.onDestroy()
@@ -2718,7 +2772,9 @@ class SettingsActivity : AppCompatActivity() {
updateEspStatus()
com.rfsentinel.app.esp.EspBoards.onStatusChanged = { runOnUiThread { updateEspStatus() } }
com.rfsentinel.app.esp.OuiSpyBle.onStatusChanged = { runOnUiThread { updateEspStatus() } }
+ com.rfsentinel.app.esp.MeshBle.onStatusChanged = { runOnUiThread { updateEspStatus() } }
binding.ouiSpyButton.setOnClickListener { pairOuiSpy() }
+ binding.meshRadioButton.setOnClickListener { pairMeshRadio() }
binding.ouiSpyEnginesButton.setOnClickListener { chooseOuiSpyEngines() }
binding.linkButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ui.SentinelLinkActivity::class.java)) }
binding.linkSaveSwitch.isChecked = Prefs.saveLinked(this)
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 8762f91..b89bc28 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -487,6 +487,10 @@ object Prefs {
fun trackerFollowPausedUntil(context: Context): Long = sp(context).getLong("tracker_follow_paused_until", 0L)
fun setTrackerFollowPausedUntil(context: Context, value: Long) = sp(context).edit { putLong("tracker_follow_paused_until", value) }
/** Bluetooth address of the OUI-SPY board to connect to while scanning (null = none). */
+ /** The Meshtastic or MeshCore radio paired over Bluetooth for logging its nodes. */
+ fun meshRadio(context: Context): String? = sp(context).getString("mesh_radio", null)
+ fun setMeshRadio(context: Context, address: String?) = sp(context).edit { putString("mesh_radio", address) }
+
fun ouiSpyBoard(context: Context): String? = sp(context).getString("ouispy_board", null)
fun setOuiSpyBoard(context: Context, address: String?) = sp(context).edit {
if (address == null) remove("ouispy_board") else putString("ouispy_board", address)
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index d021827..c491ff7 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -752,6 +752,16 @@
android:layout_height="wrap_content"
android:text="OUI-SPY engines" />
+ <TextView
+ android:id="@+id/meshRadioText"
+ style="@style/SettingsLabel"
+ android:paddingTop="6dp" />
+
+ <Button
+ android:id="@+id/meshRadioButton"
+ style="@style/SettingsTextButton"
+ android:text="Pair mesh radio" />
+
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/ouiSpyPhoneBleSwitch"
android:layout_width="match_parent"
diff --git a/app/src/main/res/xml/usb_device_filter.xml b/app/src/main/res/xml/usb_device_filter.xml
index c5d5a66..7605a08 100644
--- a/app/src/main/res/xml/usb_device_filter.xml
+++ b/app/src/main/res/xml/usb_device_filter.xml
@@ -244,9 +244,14 @@
<usb-device vendor-id="6790" product-id="29987" />
<usb-device vendor-id="6790" product-id="21795" />
<usb-device vendor-id="6790" product-id="21972" />
+ <usb-device vendor-id="6790" product-id="21971" />
<usb-device vendor-id="2364" product-id="8282" />
<!-- Espressif native USB (ESP32-S2, S3, C3, C5, C6...): every product -->
<usb-device vendor-id="12346" />
+ <!-- nRF52 / RP2040 mesh radios: Adafruit bootloader VID, Seeed, Raspberry Pi -->
+ <usb-device vendor-id="9114" />
+ <usb-device vendor-id="10374" />
+ <usb-device vendor-id="11914" />
<!-- Any standard USB Bluetooth controller (class e0 / 01 / 01) -->
<usb-device class="224" subclass="1" protocol="1" />
</resources>
diff --git a/app/src/test/java/com/rfsentinel/app/esp/EspReaderTest.kt b/app/src/test/java/com/rfsentinel/app/esp/EspReaderTest.kt
index 55b8b0d..4f2cdc3 100644
--- a/app/src/test/java/com/rfsentinel/app/esp/EspReaderTest.kt
+++ b/app/src/test/java/com/rfsentinel/app/esp/EspReaderTest.kt
@@ -22,6 +22,8 @@ class EspReaderTest {
reply(text.trim())?.let { push(it) }
}
+ override fun write(bytes: ByteArray) {}
+
override fun read(buf: ByteArray, timeoutMs: Int): Int {
val b = out.poll() ?: run { Thread.sleep(minOf(timeoutMs, 20).toLong()); return 0 }
System.arraycopy(b, 0, buf, 0, b.size)
@@ -59,14 +61,23 @@ class EspReaderTest {
fun aQuietBoardIsKeptAndItsLaterDetectionsAreRead() {
// Flock-You with nothing around: silent, ignores CMD:VERSION and help.
val board = FakeBoard("") { null }
- val (statuses, seen) = runFor(board, 9_500) { b ->
- Thread { Thread.sleep(8_800); b.push(flockLine) }.start()
+ val (statuses, seen) = runFor(board, 14_500) { b ->
+ Thread { Thread.sleep(13_800); b.push(flockLine) }.start()
}
assertEquals(listOf("CMD:VERSION", "help"), board.written.toList())
assertTrue(statuses.any { it.startsWith("ESP32 connected · waiting for detections") })
assertEquals(1, seen.size)
}
+ @Test
+ fun aDetectionDuringTheMeshRadioProbeIsKept() {
+ val board = FakeBoard("") { null }
+ val (_, seen) = runFor(board, 13_800) { b ->
+ Thread { Thread.sleep(8_800); b.push(flockLine) }.start()
+ }
+ assertEquals(1, seen.size)
+ }
+
@Test
fun detectorIsIdentifiedAndItsLiveTableFetched() {
val det = """{"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,"last_seen_ms":2,"hit_count":3,"replay_source":"ram"}"""
diff --git a/app/src/test/java/com/rfsentinel/app/esp/MeshRadioTest.kt b/app/src/test/java/com/rfsentinel/app/esp/MeshRadioTest.kt
new file mode 100644
index 0000000..f67a6d4
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/esp/MeshRadioTest.kt
@@ -0,0 +1,89 @@
+package com.rfsentinel.app.esp
+
+import com.rfsentinel.app.link.MeshProto
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/** Meshtastic and MeshCore radios: framing, and which nodes count as heard. */
+class MeshRadioTest {
+
+ private fun node(num: Long, name: String, lastHeard: Long, mqtt: Boolean = false): ByteArray = MeshProto.W().apply {
+ msg(4) {
+ uint(1, num)
+ msg(2) { string(2, name) }
+ msg(3) { fixed32(1, 105_000_000L); fixed32(2, (-205_000_000L) and 0xFFFFFFFFL) }
+ fixed32(5, lastHeard)
+ bool(8, mqtt)
+ }
+ }.bytes()
+
+ private fun contact(code: Int, name: String, lat: Int = 0, lon: Int = 0): ByteArray {
+ val f = ByteArray(148)
+ f[0] = code.toByte()
+ for (i in 1..32) f[i] = i.toByte()
+ name.toByteArray().copyInto(f, 100)
+ ByteBuffer.wrap(f).order(ByteOrder.LITTLE_ENDIAN).putInt(136, lat).putInt(140, lon)
+ return f
+ }
+
+ @Test
+ fun meshtasticNodeList() {
+ val log = MeshtasticLog { 100_000 }
+ log.feed(MeshProto.From.MyInfo(0x11))
+ assertNull("itself", log.feed(MeshProto.readFromRadio(node(0x11, "Me", 99_999))))
+ assertNull("over MQTT", log.feed(MeshProto.readFromRadio(node(0x22, "Far", 99_999, mqtt = true))))
+ assertNull("old", log.feed(MeshProto.readFromRadio(node(0x33, "Old", 100_000 - 3 * 3600))))
+ val s = log.feed(MeshProto.readFromRadio(node(0xA1B2C3D4, "Hilltop", 99_900)))!!
+ assertEquals("06:4D:A1:B2:C3:D4", s.mac)
+ assertEquals("Meshtastic: Hilltop", s.name)
+ assertEquals(10.5, s.position!!.first, 1e-6)
+ assertEquals(-20.5, s.position!!.second, 1e-6)
+ assertEquals(setOf(0xA1B2C3D4), log.heard)
+ }
+
+ @Test
+ fun meshtasticPacketsSkipMqttAndUseRssi() {
+ val log = MeshtasticLog { 0 }
+ assertEquals(-97, log.feed(MeshProto.From.Packet(0x55, 0xFFFFFFFFL, 0, 1, ByteArray(0), -97))!!.rssi)
+ assertNull(log.feed(MeshProto.From.Packet(0x66, 0xFFFFFFFFL, 0, 1, ByteArray(0), -97, viaMqtt = true)))
+ }
+
+ @Test
+ fun meshCoreLogsAdvertsNotContacts() {
+ var now = 1_000L
+ val log = MeshCoreLog { now }
+ assertNull("the contact list is history", log.feed(contact(3, "Repeater", 10_500_000, -20_500_000)))
+ assertNull(log.feed(byteArrayOf(0x88.toByte(), 8, (-88).toByte(), 1, 2)))
+ val s = log.feed(contact(3, "x").copyOf(33).also { it[0] = 0x80.toByte() })!!
+ assertEquals("06:43:01:02:03:04", s.mac)
+ assertEquals("MeshCore: Repeater", s.name)
+ assertEquals(-88, s.rssi)
+ assertEquals(10.5, s.position!!.first, 1e-6)
+ now += 10_000
+ assertEquals("the level was for another packet", -120, log.feed(contact(0x8A, "New"))!!.rssi)
+ }
+
+ @Test
+ fun framesBetweenLogTextAndAcrossReads() {
+ val f = MeshFrames(meshtastic = true)
+ val wire = "INFO boot\n".toByteArray() + MeshFrames.meshtastic(byteArrayOf(1, 2, 3)) + "log".toByteArray() + MeshFrames.meshtastic(byteArrayOf(4))
+ val out = f.feed(wire, 13) + f.feed(wire.copyOfRange(13, wire.size), wire.size - 13)
+ assertEquals(listOf(listOf<Byte>(1, 2, 3), listOf<Byte>(4)), out.map { it.toList() })
+
+ val c = MeshFrames(meshtastic = false)
+ val reply = byteArrayOf('>'.code.toByte(), 2, 0, 5, 9)
+ assertEquals(listOf<Byte>(5, 9), c.feed(reply, reply.size).single().toList())
+ }
+
+ @Test
+ fun selfInfoAndStartCommand() {
+ assertTrue(MeshCoreLog.isSelfInfo(ByteArray(58).also { it[0] = 5 }))
+ assertEquals(8 + 11, MeshCoreLog.APP_START.size)
+ assertNotNull(MeshProto.readFromRadio(node(1, "a", 1)) as? MeshProto.From.NodeInfo)
+ }
+}