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.

Sentinel Link over Meshtastic: reach far Sentinels through a LoRa node

CIS-C0666d0184e537
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index c9789d4..249177e 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -491,7 +491,8 @@ class MainActivity : AppCompatActivity() {
},
com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }
?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) },
- com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) }
+ com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) },
+ com.rfsentinel.app.link.MeshNode.status.takeIf { it.isNotBlank() }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) }
)
statusPanel.update(running, warning, hardware)
return
@@ -514,7 +515,8 @@ class MainActivity : AppCompatActivity() {
com.rfsentinel.app.sdr.SdrRadio.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +
com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }
?.let { "\n$it" }.orEmpty() +
- com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty()
+ com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +
+ com.rfsentinel.app.link.MeshNode.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty()
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
index 09707ae..8e101fb 100644
--- a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
@@ -218,7 +218,8 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
UsbWifi.status.takeIf { it.isNotBlank() },
SdrRadio.status.takeIf { it.isNotBlank() },
OuiSpyBle.status.takeIf { it.isNotBlank() },
- com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }
+ com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() },
+ com.rfsentinel.app.link.MeshNode.status.takeIf { it.isNotBlank() }
).joinToString(" · ").ifEmpty { "Phone radios only" }
// ---- now playing -------------------------------------------------------------------
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
index c1895b0..d930171 100644
--- a/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
@@ -92,4 +92,34 @@ object LinkStore {
if (changed) sp(c).edit { putString("members", now.values.joinToString("\n") { "${it.id}|${it.name}" }) }
return changed
}
+
+ // ---- Meshtastic node
+
+ /** Sentinel Link also goes over a Meshtastic node (off until turned on). */
+ fun meshOn(c: Context) = sp(c).getBoolean("mesh_on", false)
+ fun setMeshOn(c: Context, on: Boolean) = sp(c).edit { putBoolean("mesh_on", on) }
+ /** The node's Bluetooth address and name, null until one is chosen. */
+ fun meshNode(c: Context): String? = sp(c).getString("mesh_node", null)
+ fun meshNodeName(c: Context): String? = sp(c).getString("mesh_node_name", null)
+ fun setMeshNode(c: Context, address: String, name: String) =
+ sp(c).edit { putString("mesh_node", address); putString("mesh_node_name", name.take(40)) }
+ /** Seconds between two packets (watchlist matches can go sooner). */
+ fun meshIntervalSec(c: Context) = sp(c).getInt("mesh_interval", 60).coerceIn(MESH_INTERVAL_MIN, MESH_INTERVAL_MAX)
+ fun setMeshIntervalSec(c: Context, s: Int) = sp(c).edit { putInt("mesh_interval", s) }
+ const val MESH_INTERVAL_MIN = 15
+ const val MESH_INTERVAL_MAX = 300
+
+ private var meshNext = -1L
+ private var meshReserved = 0L
+
+ /** A message counter never used before by this phone (blocks of 256 are saved ahead, so a restart skips ahead). */
+ @Synchronized
+ fun nextMeshCounter(c: Context): Int {
+ if (meshNext < 0) { meshNext = sp(c).getLong("mesh_counter", 0L); meshReserved = meshNext }
+ if (meshNext >= meshReserved) {
+ meshReserved = meshNext + 256
+ sp(c).edit(commit = true) { putLong("mesh_counter", meshReserved) }
+ }
+ return (meshNext++ and 0x7FFFFFFFL).toInt()
+ }
}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshCodec.kt b/app/src/main/java/com/rfsentinel/app/link/MeshCodec.kt
new file mode 100644
index 0000000..2da858e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshCodec.kt
@@ -0,0 +1,166 @@
+package com.rfsentinel.app.link
+
+import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Hit
+import java.io.ByteArrayOutputStream
+import java.nio.ByteBuffer
+import javax.crypto.Cipher
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Sentinel Link over Meshtastic: what one Sentinel heard, packed into one LoRa packet (233 bytes at most).
+ *
+ * Clear header `[0x52][version][group tag 4][origin 8][counter 4]`, then AES-256-GCM of the body with a key made
+ * from the group key (nonce = origin + counter, which never repeats: the counter is kept across restarts).
+ * Body: flags, time, the Sentinel's position once for all its devices, its name now and then, then one record per
+ * device (address, radio, signal, age, name, and up to two matches).
+ */
+object MeshCodec {
+ /** The Meshtastic channel RF Sentinel adds to the node; its key comes from the group key. */
+ const val CHANNEL_NAME = "RFSentinel"
+ private const val MAGIC = 0x52
+ private const val VERSION = 1
+ private const val HEADER = 18
+ private const val GCM_TAG = 16
+ /** Room for the body in one packet. */
+ const val MAX_BODY = MeshProto.MAX_PAYLOAD - HEADER - GCM_TAG - 3
+ private const val NAME_MAX = 24
+ private const val LABEL_MAX = 32
+ private const val NO_POS = Int.MIN_VALUE
+
+ private val SALT = "RF Sentinel mesh".toByteArray()
+ fun messageKey(groupKey: ByteArray) = LinkCrypto.hkdf(groupKey, SALT, "message key")
+ fun channelKey(groupKey: ByteArray) = LinkCrypto.hkdf(groupKey, SALT, "channel key")
+ private fun groupTag(key: ByteArray) = LinkCrypto.hmac(key, "group".toByteArray()).copyOf(4)
+
+ /** One device as it goes over the mesh. */
+ class Device(val mac: String, val source: Advert.Source, val rssi: Int, val ageSec: Int, val name: String?, val hits: List<Hit>)
+
+ class Message(
+ val origin: Long, val counter: Int, val time: Long,
+ /** Where that Sentinel was, NaN when unknown. */
+ val lat: Double, val lon: Double,
+ val name: String?, val devices: List<Device>,
+ )
+
+ /** Bytes one device takes in a body. */
+ fun size(d: Device): Int =
+ 6 + 3 + (d.name?.let { 1 + utf8(it, NAME_MAX).size } ?: 0) +
+ d.hits.take(2).sumOf { 1 + utf8(it.category.name, 20).size + 1 + 1 + utf8(it.label, LABEL_MAX).size }
+
+ /** Bytes the body takes before the devices. */
+ fun baseSize(hasPosition: Boolean, name: String?) = 5 + (if (hasPosition) 8 else 0) + (name?.let { 1 + utf8(it, NAME_MAX).size } ?: 0)
+
+ fun seal(key: ByteArray, origin: Long, counter: Int, timeMs: Long, lat: Double, lon: Double, name: String?,
+ devices: List<Device>): ByteArray {
+ val hasPos = !lat.isNaN() && !lon.isNaN()
+ val body = ByteArrayOutputStream()
+ body.write((if (hasPos) 1 else 0) or (if (name != null) 2 else 0))
+ body.write(ByteBuffer.allocate(4).putInt((timeMs / 1000).toInt()).array())
+ if (hasPos) body.write(ByteBuffer.allocate(8).putInt(Math.round(lat * 1e5).toInt()).putInt(Math.round(lon * 1e5).toInt()).array())
+ name?.let { text(body, it, NAME_MAX) }
+ for (d in devices) {
+ val mac = macBytes(d.mac) ?: continue
+ if (body.size() + size(d) > MAX_BODY) break
+ body.write(mac)
+ val hits = d.hits.take(2)
+ body.write((if (d.source == Advert.Source.WIFI) 1 else 0) or (if (d.name != null) 2 else 0) or (hits.size shl 2))
+ body.write(d.rssi.coerceIn(-128, 127))
+ body.write(d.ageSec.coerceIn(0, 255))
+ d.name?.let { text(body, it, NAME_MAX) }
+ for (h in hits) {
+ text(body, h.category.name, 20)
+ body.write(h.confidence.coerceIn(0, 100))
+ text(body, h.label, LABEL_MAX)
+ }
+ }
+ val header = ByteBuffer.allocate(HEADER).put(MAGIC.toByte()).put(VERSION.toByte()).put(groupTag(key))
+ .putLong(origin).putInt(counter).array()
+ return header + cipher(Cipher.ENCRYPT_MODE, key, header).doFinal(body.toByteArray())
+ }
+
+ /** Null when it isn't this group's (or was changed on the way). */
+ fun open(key: ByteArray, bytes: ByteArray): Message? = runCatching {
+ if (bytes.size < HEADER + GCM_TAG || bytes[0].toInt() != MAGIC || bytes[1].toInt() != VERSION) return null
+ val header = bytes.copyOfRange(0, HEADER)
+ if (!header.copyOfRange(2, 6).contentEquals(groupTag(key))) return null
+ val hb = ByteBuffer.wrap(header, 6, 12)
+ val origin = hb.long
+ val counter = hb.int
+ val body = ByteBuffer.wrap(cipher(Cipher.DECRYPT_MODE, key, header).doFinal(bytes, HEADER, bytes.size - HEADER))
+ val flags = body.get().toInt()
+ val time = (body.int.toLong() and 0xFFFFFFFFL) * 1000
+ var lat = Double.NaN
+ var lon = Double.NaN
+ if (flags and 1 != 0) {
+ val la = body.int
+ val lo = body.int
+ if (la != NO_POS) { lat = la / 1e5; lon = lo / 1e5 }
+ }
+ val name = if (flags and 2 != 0) text(body) else null
+ val devices = ArrayList<Device>()
+ while (body.remaining() >= 9) {
+ val mac = ByteArray(6).also { body.get(it) }.joinToString(":") { "%02X".format(it.toInt() and 0xFF) }
+ val b = body.get().toInt()
+ val rssi = body.get().toInt()
+ val age = body.get().toInt() and 0xFF
+ val dName = if (b and 2 != 0) text(body) else null
+ val hits = (0 until ((b shr 2) and 3)).mapNotNull {
+ val cat = text(body)
+ val conf = body.get().toInt() and 0xFF
+ val label = text(body)
+ runCatching { Category.valueOf(cat) }.getOrNull()?.let {
+ Hit(it, label, conf.coerceAtMost(100), "Matched by a linked Sentinel", "Sentinel Link")
+ }
+ }
+ devices += Device(mac, if (b and 1 != 0) Advert.Source.WIFI else Advert.Source.BLE, rssi, age, dName, hits)
+ }
+ Message(origin, counter, time, lat, lon, name, devices)
+ }.getOrNull()
+
+ /** A message as a Sentinel Link batch: seq kept apart from Bluetooth batches' (negative), already one hop away. */
+ fun toBatch(m: Message): LinkCodec.Batch = LinkCodec.Batch(
+ m.origin, m.counter or Int.MIN_VALUE, 1, m.time, m.lat, m.lon,
+ m.devices.map { d ->
+ LinkCodec.Sighting(LinkCodec.KIND_PHONE, Advert(d.mac, d.source, d.rssi, name = d.name,
+ timestamp = m.time - d.ageSec * 1000L), hits = d.hits)
+ },
+ emptyList()
+ )
+
+ private fun cipher(mode: Int, key: ByteArray, header: ByteArray): Cipher =
+ Cipher.getInstance("AES/GCM/NoPadding").apply {
+ init(mode, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG * 8, header.copyOfRange(6, HEADER)))
+ updateAAD(header)
+ }
+
+ private fun macBytes(mac: String): ByteArray? {
+ val parts = mac.split(':')
+ if (parts.size != 6) return null
+ return ByteArray(6) { i -> parts[i].toIntOrNull(16)?.toByte() ?: return null }
+ }
+
+ /** UTF-8, cut to [max] bytes without splitting a character. */
+ fun utf8(s: String, max: Int): ByteArray {
+ var t = s
+ var b = t.toByteArray(Charsets.UTF_8)
+ while (b.size > max) {
+ t = t.dropLast(if (t.length >= 2 && t[t.length - 1].isLowSurrogate()) 2 else 1)
+ b = t.toByteArray(Charsets.UTF_8)
+ }
+ return b
+ }
+
+ private fun text(out: ByteArrayOutputStream, s: String, max: Int) {
+ val b = utf8(s, max)
+ out.write(b.size)
+ out.write(b)
+ }
+
+ private fun text(b: ByteBuffer): String {
+ val n = b.get().toInt() and 0xFF
+ return String(ByteArray(n).also { b.get(it) }, Charsets.UTF_8)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
new file mode 100644
index 0000000..f28a1f1
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshNode.kt
@@ -0,0 +1,450 @@
+package com.rfsentinel.app.link
+
+import android.annotation.SuppressLint
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothGatt
+import android.bluetooth.BluetoothGattCallback
+import android.bluetooth.BluetoothGattCharacteristic
+import android.bluetooth.BluetoothGattDescriptor
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothStatusCodes
+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.HandlerThread
+import android.os.Looper
+import android.os.ParcelUuid
+import android.os.SystemClock
+import android.util.Log
+import java.util.UUID
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * A Meshtastic node (LoRa board with the official firmware) used by Sentinel Link to reach Sentinels far away.
+ *
+ * Talks to the node over Bluetooth with Meshtastic's phone API, like the Meshtastic app does: asks for its config,
+ * makes sure it has the group's private "RFSentinel" channel (adds it to a free slot when missing, key made from
+ * the group key), then sends and receives RF Sentinel's packets on that channel. Reconnects on its own.
+ * The node serves one app at a time: the Meshtastic app on this phone can't use it meanwhile.
+ */
+@SuppressLint("MissingPermission")
+object MeshNode {
+ private const val TAG = "MeshNode"
+ val SERVICE: UUID = UUID.fromString("6ba1b218-15a8-461f-9fa8-5dcae273eafd")
+ 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 const val MTU = 512
+ private const val TICK_MS = 5_000L
+ private const val OP_TIMEOUT_MS = 15_000L
+ private const val SETUP_TIMEOUT_MS = 45_000L
+ private const val BOND_WAIT_MS = 90_000L
+ private const val RETRY_MIN_MS = 10_000L
+ private const val RETRY_MAX_MS = 120_000L
+ /** While the node is out of reach, packets beyond this wait are dropped (they'd be stale). */
+ private const val MAX_QUEUED = 12
+
+ private val thread = HandlerThread("rf-mesh").apply { start() }
+ private val h = Handler(thread.looper)
+ private val main = Handler(Looper.getMainLooper())
+
+ /** One line for the screens, "" while off. */
+ @Volatile var status = ""; private set
+ /** Connected, set up, and the RFSentinel channel in place. */
+ @Volatile var ready = false; private set
+ @Volatile var lastSent = 0L; private set
+ @Volatile var lastHeard = 0L; private set
+ private val listeners = CopyOnWriteArrayList<() -> Unit>()
+ fun addListener(l: () -> Unit) { listeners += l }
+ fun removeListener(l: () -> Unit) { listeners -= l }
+ private fun changed() = main.post { listeners.forEach { it() } }
+
+ private var ctx: Context? = null
+ private var running = false
+ private var address: String? = null
+ private var channelPsk: ByteArray? = null
+ private var onPacket: ((ByteArray) -> Unit)? = null
+
+ private var gatt: BluetoothGatt? = null
+ private var toRadio: BluetoothGattCharacteristic? = null
+ private var fromRadio: BluetoothGattCharacteristic? = null
+ private var connectStarted = 0L
+ private var bondStarted = 0L
+ private var retryMs = RETRY_MIN_MS
+ private var retryPending = false
+ private var ticking = false
+
+ // What the node told us.
+ private var myNode = 0L
+ private var hopLimit = 3
+ private var region = -1
+ private var txEnabled = true
+ private val channels = HashMap<Int, MeshProto.From.ChannelInfo>()
+ private var channelIndex = -1
+ private var channelTries = 0
+
+ // One Bluetooth operation at a time.
+ private sealed class Op {
+ class Write(val data: ByteArray) : Op()
+ object Read : Op()
+ }
+ private val ops = ArrayDeque<Op>()
+ private var inFlight: Op? = null
+ private var opSince = 0L
+ private var busyTries = 0
+ private var ioReady = false
+ private var draining = false
+ private var drainAgain = false
+
+ /** Starts using the node at [nodeAddress]; [packets] gets RF Sentinel payloads from the mesh (on this thread). */
+ fun start(context: Context, nodeAddress: String, groupKey: ByteArray, packets: (ByteArray) -> Unit) = h.post {
+ ctx = context.applicationContext
+ onPacket = packets
+ val psk = MeshCodec.channelKey(groupKey)
+ val changedNode = nodeAddress != address || !psk.contentEquals(channelPsk)
+ address = nodeAddress
+ channelPsk = psk
+ if (running && !changedNode) return@post
+ if (running) teardown()
+ running = true
+ channelTries = 0
+ retryMs = RETRY_MIN_MS
+ startTicking()
+ connect()
+ }
+
+ fun stop() = h.post {
+ if (!running) return@post
+ running = false
+ onPacket = null
+ teardown()
+ setStatus("")
+ }
+
+ /** Sends one RF Sentinel payload on the RFSentinel channel; false when the node isn't ready. */
+ fun send(payload: ByteArray, urgent: Boolean): Boolean {
+ if (!ready) return false
+ h.post {
+ if (!ready || channelIndex < 0 || !txEnabled) return@post
+ if (ops.count { it is Op.Write } >= MAX_QUEUED) return@post
+ enqueue(Op.Write(MeshProto.packet(MeshProto.BROADCAST, channelIndex, MeshProto.PORT_PRIVATE_APP, payload,
+ packetId(), hopLimit, if (urgent) MeshProto.PRIORITY_RELIABLE else MeshProto.PRIORITY_BACKGROUND)))
+ lastSent = System.currentTimeMillis()
+ changed()
+ }
+ return true
+ }
+
+ // ---------------------------------------------------------------- finding and pairing a node
+
+ /** Looks for nodes nearby; [found] (main thread) gets each one's name, address and signal. Returns how to stop. */
+ fun find(context: Context, found: (name: String, address: String, rssi: Int) -> Unit): (() -> Unit)? {
+ val scanner = runCatching {
+ context.getSystemService(BluetoothManager::class.java)?.adapter?.takeIf { it.isEnabled }?.bluetoothLeScanner
+ }.getOrNull() ?: return null
+ val cb = object : ScanCallback() {
+ override fun onScanResult(callbackType: Int, r: ScanResult) {
+ val name = r.scanRecord?.deviceName ?: runCatching { r.device.name }.getOrNull() ?: r.device.address
+ main.post { found(name, r.device.address, r.rssi) }
+ }
+ }
+ val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE)).build()
+ val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
+ try {
+ scanner.startScan(listOf(filter), settings, cb)
+ } catch (e: Exception) {
+ return null
+ }
+ return { runCatching { scanner.stopScan(cb) } }
+ }
+
+ /** Pairs with the node now, while the user is looking: Android asks for its PIN (on its screen, or 123456). */
+ fun pair(context: Context, nodeAddress: String) {
+ runCatching {
+ val d = context.getSystemService(BluetoothManager::class.java)?.adapter?.getRemoteDevice(nodeAddress) ?: return
+ if (d.bondState == BluetoothDevice.BOND_NONE) d.createBond()
+ }
+ }
+
+ // ---------------------------------------------------------------- connection
+
+ private fun adapter() = ctx?.getSystemService(BluetoothManager::class.java)?.adapter
+
+ private fun connect() {
+ if (!running || gatt != null) return
+ val c = ctx ?: return
+ val addr = address ?: return
+ if (!PhoneLink.canUse(c)) { setStatus("Meshtastic node: allow \"Nearby devices\""); scheduleRetry(); return }
+ val adapter = adapter()
+ if (adapter == null || !adapter.isEnabled) { setStatus("Meshtastic node: Bluetooth is off"); scheduleRetry(); return }
+ val device = runCatching { adapter.getRemoteDevice(addr) }.getOrNull()
+ ?: run { setStatus("Meshtastic node: choose the node again"); return }
+ // Meshtastic nodes want a paired phone (PIN on the node's screen, or 123456).
+ when (device.bondState) {
+ BluetoothDevice.BOND_NONE -> {
+ if (bondStarted == 0L || SystemClock.elapsedRealtime() - bondStarted > BOND_WAIT_MS) {
+ bondStarted = SystemClock.elapsedRealtime()
+ runCatching { device.createBond() }
+ setStatus("Meshtastic node: pairing - enter the node's PIN if Android asks")
+ } else {
+ setStatus("Meshtastic node: not paired - enter the PIN Android asks for")
+ }
+ scheduleRetry(5_000L)
+ return
+ }
+ BluetoothDevice.BOND_BONDING -> { setStatus("Meshtastic node: pairing…"); scheduleRetry(3_000L); return }
+ }
+ bondStarted = 0L
+ setStatus("Meshtastic node: connecting…")
+ connectStarted = SystemClock.elapsedRealtime()
+ gatt = runCatching { device.connectGatt(c, false, callback, BluetoothDevice.TRANSPORT_LE) }.getOrNull()
+ if (gatt == null) { setStatus("Meshtastic node: can't connect"); scheduleRetry() }
+ }
+
+ private fun teardown() {
+ gatt?.let { g -> runCatching { g.disconnect() }; runCatching { g.close() } }
+ gatt = null
+ toRadio = null; fromRadio = null
+ ops.clear(); inFlight = null; ioReady = false; busyTries = 0
+ draining = false; drainAgain = false
+ channels.clear(); channelIndex = -1; myNode = 0L
+ if (ready) { ready = false; changed() }
+ }
+
+ private fun scheduleRetry(delay: Long = retryMs) {
+ if (!running || retryPending) return
+ retryPending = true
+ if (delay == retryMs) retryMs = (retryMs * 2).coerceAtMost(RETRY_MAX_MS)
+ h.postDelayed({ retryPending = false; connect() }, delay)
+ }
+
+ private fun lost(why: String) {
+ Log.i(TAG, "lost: $why")
+ teardown()
+ setStatus("Meshtastic node: $why - retrying")
+ scheduleRetry()
+ }
+
+ private fun startTicking() {
+ if (ticking) return
+ ticking = true
+ h.postDelayed(::tick, TICK_MS)
+ }
+
+ private fun tick() {
+ if (!running) { ticking = false; return }
+ val now = SystemClock.elapsedRealtime()
+ if (gatt != null && !ready && now - connectStarted > SETUP_TIMEOUT_MS) lost("no answer")
+ else if (inFlight != null && now - opSince > OP_TIMEOUT_MS) lost("stopped answering")
+ h.postDelayed(::tick, TICK_MS)
+ }
+
+ private val callback = object : BluetoothGattCallback() {
+ override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
+ h.post {
+ if (gatt !== g) { runCatching { g.close() }; return@post }
+ when (newState) {
+ BluetoothProfile.STATE_CONNECTED -> if (!g.requestMtu(MTU)) discover(g)
+ BluetoothProfile.STATE_DISCONNECTED -> lost(if (ready) "out of reach" else "can't connect")
+ }
+ }
+ }
+
+ override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) { h.post { if (gatt === g) discover(g) } }
+
+ override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
+ h.post {
+ if (gatt !== g) return@post
+ val svc = g.getService(SERVICE) ?: run { lost("not a Meshtastic node"); return@post }
+ toRadio = svc.getCharacteristic(TO_RADIO)
+ fromRadio = svc.getCharacteristic(FROM_RADIO)
+ val num = svc.getCharacteristic(FROM_NUM)
+ if (toRadio == null || fromRadio == null) { lost("not a Meshtastic node"); return@post }
+ val cccd = num?.getDescriptor(CCCD)
+ if (num == null || cccd == null) { onIoReady(); return@post }
+ g.setCharacteristicNotification(num, true)
+ val ok = runCatching {
+ if (Build.VERSION.SDK_INT >= 33) g.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) == BluetoothStatusCodes.SUCCESS
+ else {
+ @Suppress("DEPRECATION") cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
+ @Suppress("DEPRECATION") g.writeDescriptor(cccd)
+ }
+ }.getOrDefault(false)
+ if (!ok) onIoReady()
+ }
+ }
+
+ override fun onDescriptorWrite(g: BluetoothGatt, d: BluetoothGattDescriptor, status: Int) {
+ h.post { if (gatt === g && !ioReady) onIoReady() }
+ }
+
+ override fun onCharacteristicWrite(g: BluetoothGatt, c: BluetoothGattCharacteristic, status: Int) {
+ h.post {
+ if (gatt !== g) return@post
+ if (status != BluetoothGatt.GATT_SUCCESS) { lost("refused a message ($status)"); return@post }
+ done()
+ }
+ }
+
+ override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray, status: Int) {
+ h.post { if (gatt === g) onRead(value, status) }
+ }
+
+ @Deprecated("Android 12 and older")
+ @Suppress("DEPRECATION")
+ override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, status: Int) {
+ if (Build.VERSION.SDK_INT >= 33) return
+ val v = c.value?.copyOf() ?: ByteArray(0)
+ h.post { if (gatt === g) onRead(v, status) }
+ }
+
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray) {
+ if (c.uuid == FROM_NUM) h.post { if (gatt === g) drain() }
+ }
+
+ @Deprecated("Android 12 and older")
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic) {
+ if (Build.VERSION.SDK_INT >= 33 || c.uuid != FROM_NUM) return
+ h.post { if (gatt === g) drain() }
+ }
+ }
+
+ private fun discover(g: BluetoothGatt) { if (!g.discoverServices()) lost("can't read the node") }
+
+ private fun onIoReady() {
+ ioReady = true
+ setStatus("Meshtastic node: reading its settings…")
+ askConfig()
+ }
+
+ /** The node's settings and channels (not its node list). */
+ private fun askConfig() {
+ channels.clear()
+ enqueue(Op.Write(MeshProto.wantConfig(MeshProto.CONFIG_ONLY)))
+ drain()
+ }
+
+ // ---------------------------------------------------------------- operations
+
+ private fun enqueue(op: Op) { ops.addLast(op); next() }
+
+ private fun next() {
+ val g = gatt ?: return
+ if (inFlight != null || !ioReady) return
+ val op = ops.removeFirstOrNull() ?: return
+ val ok = runCatching {
+ when (op) {
+ is Op.Write -> {
+ val c = toRadio ?: return
+ if (Build.VERSION.SDK_INT >= 33) g.writeCharacteristic(c, op.data, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) == BluetoothStatusCodes.SUCCESS
+ else {
+ c.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
+ @Suppress("DEPRECATION") c.value = op.data
+ @Suppress("DEPRECATION") g.writeCharacteristic(c)
+ }
+ }
+ Op.Read -> g.readCharacteristic(fromRadio ?: return)
+ }
+ }.getOrDefault(false)
+ if (!ok) {
+ // The stack is busy for a moment: try again shortly, not forever.
+ ops.addFirst(op)
+ if (++busyTries > 50) { lost("stopped answering"); return }
+ h.postDelayed(::next, 200L)
+ return
+ }
+ busyTries = 0
+ inFlight = op
+ opSince = SystemClock.elapsedRealtime()
+ }
+
+ private fun done() {
+ inFlight = null
+ opSince = 0L
+ next()
+ }
+
+ /** Reads everything the node has for the phone. */
+ private fun drain() {
+ if (draining) { drainAgain = true; return }
+ draining = true
+ enqueue(Op.Read)
+ }
+
+ private fun onRead(value: ByteArray, status: Int) {
+ if (status != BluetoothGatt.GATT_SUCCESS) { lost("can't read the node ($status)"); return }
+ inFlight = null
+ opSince = 0L
+ if (value.isEmpty()) {
+ draining = false
+ if (drainAgain) { drainAgain = false; drain() }
+ } else {
+ runCatching { handle(MeshProto.readFromRadio(value)) }.onFailure { Log.w(TAG, "bad message from the node", it) }
+ ops.addFirst(Op.Read)
+ }
+ next()
+ }
+
+ private fun handle(m: MeshProto.From) {
+ when (m) {
+ is MeshProto.From.MyInfo -> myNode = m.nodeNum
+ is MeshProto.From.ChannelInfo -> channels[m.index] = m
+ is MeshProto.From.Lora -> { hopLimit = if (m.hopLimit in 1..7) m.hopLimit else 3; region = m.region; txEnabled = m.txEnabled }
+ is MeshProto.From.ConfigComplete -> configDone()
+ is MeshProto.From.Packet -> if (m.port == MeshProto.PORT_PRIVATE_APP && (channelIndex < 0 || m.channel == channelIndex)) {
+ lastHeard = System.currentTimeMillis()
+ onPacket?.invoke(m.payload)
+ changed()
+ }
+ 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
+ }
+ }
+
+ /** Settings read: use the RFSentinel channel, adding it first when it's missing or has another group's key. */
+ private fun configDone() {
+ val psk = channelPsk ?: return
+ if (region == 0) { setStatus("Meshtastic node: set its LoRa region in the Meshtastic app first"); return }
+ val ours = channels.values.firstOrNull { it.role != MeshProto.ROLE_DISABLED && it.name == MeshCodec.CHANNEL_NAME && it.psk.contentEquals(psk) }
+ if (ours != null) {
+ channelIndex = ours.index
+ ready = true
+ retryMs = RETRY_MIN_MS
+ setStatus(if (!txEnabled) "Meshtastic node: its LoRa transmit is off" else "Meshtastic node · connected")
+ return
+ }
+ if (channelTries >= 2 || myNode == 0L) {
+ setStatus("Meshtastic node: couldn't add the ${MeshCodec.CHANNEL_NAME} channel")
+ return
+ }
+ val slot = channels.values.firstOrNull { it.index in 1..7 && it.name == MeshCodec.CHANNEL_NAME }?.index
+ ?: channels.values.filter { it.index in 1..7 && it.role == MeshProto.ROLE_DISABLED }.minOfOrNull { it.index }
+ if (slot == null) { setStatus("Meshtastic node: no free channel - free one in the Meshtastic app"); return }
+ channelTries++
+ setStatus("Meshtastic node: adding the ${MeshCodec.CHANNEL_NAME} channel…")
+ // Admin message to the node itself (from this phone: no admin key needed); channels change without a restart.
+ enqueue(Op.Write(MeshProto.packet(myNode, 0, MeshProto.PORT_ADMIN_APP,
+ MeshProto.setChannel(slot, MeshCodec.CHANNEL_NAME, psk), packetId(), 0, MeshProto.PRIORITY_RELIABLE)))
+ val g = gatt
+ h.postDelayed({ if (gatt === g && g != null && !ready) askConfig() }, 3_000L)
+ }
+
+ private fun packetId(): Long {
+ var id = 0L
+ while (id == 0L) id = LinkCrypto.randomId() and 0xFFFFFFFFL
+ return id
+ }
+
+ private fun setStatus(s: String) {
+ if (s == status) return
+ status = s
+ changed()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshOutbox.kt b/app/src/main/java/com/rfsentinel/app/link/MeshOutbox.kt
new file mode 100644
index 0000000..4d3be6a
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshOutbox.kt
@@ -0,0 +1,89 @@
+package com.rfsentinel.app.link
+
+import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Hit
+
+/**
+ * What goes out over the mesh next. LoRa carries one small packet now and then, so devices take turns:
+ * watchlist matches first (again every minute while heard), then flagged devices (every 3 minutes),
+ * then every other device (once, then every 15 minutes), newest first.
+ */
+class MeshOutbox {
+ private class Entry(var source: Advert.Source, var rssi: Int, var name: String?, var hits: List<Hit>, var seen: Long) {
+ var sent = 0L
+ var sentHits: List<Hit> = emptyList()
+ val priority get() = when {
+ hits.any { it.category == Category.CUSTOM } -> 2
+ hits.isNotEmpty() -> 1
+ else -> 0
+ }
+ }
+
+ private val devices = LinkedHashMap<String, Entry>()
+
+ /** A device heard here (or by a Sentinel linked over Bluetooth), with what it matched. */
+ @Synchronized
+ fun add(a: Advert, hits: List<Hit>, now: Long) {
+ // Very weak matches don't alert: not worth the air time.
+ val keep = hits.filter { !it.listOnly }
+ val watch = keep.firstOrNull { it.category == Category.CUSTOM }
+ val send = listOfNotNull(watch) + keep.filter { it !== watch }.take(if (watch == null) 2 else 1)
+ val e = devices[a.mac]
+ if (e == null) {
+ if (devices.size >= MAX_DEVICES) trim(now)
+ devices[a.mac] = Entry(a.source, a.rssi, a.name, send, now)
+ } else {
+ e.source = a.source; e.rssi = a.rssi; e.seen = now
+ if (a.name != null) e.name = a.name
+ e.hits = send
+ }
+ }
+
+ /** A watchlist match not sent yet (or newly matched): worth sending before the usual wait. */
+ @Synchronized
+ fun urgent(now: Long) = devices.values.any {
+ it.priority == 2 && now - it.seen < FRESH_MS && (it.sent == 0L || it.hits != it.sentHits)
+ }
+
+ /** The devices due, most important first, filling one packet; they count as sent. */
+ @Synchronized
+ fun take(now: Long, room: Int): List<MeshCodec.Device> {
+ trim(now)
+ val due = devices.entries.filter { (_, e) ->
+ now - e.seen < FRESH_MS && (e.sent == 0L || e.hits != e.sentHits || now - e.sent >= repeatMs(e.priority))
+ }.sortedWith(compareByDescending<Map.Entry<String, Entry>> { it.value.priority }
+ .thenBy { it.value.sent != 0L }
+ .thenByDescending { it.value.seen })
+ val out = ArrayList<MeshCodec.Device>()
+ var left = room
+ for ((mac, e) in due) {
+ val d = MeshCodec.Device(mac, e.source, e.rssi, ((now - e.seen) / 1000).toInt(), e.name, e.hits)
+ val size = MeshCodec.size(d)
+ if (size > left) continue
+ out += d
+ left -= size
+ e.sent = now
+ e.sentHits = e.hits
+ if (left < 9) break
+ }
+ return out
+ }
+
+ private fun trim(now: Long) {
+ devices.entries.removeAll { now - it.value.seen > FORGET_MS }
+ while (devices.size >= MAX_DEVICES) devices.remove(devices.keys.first())
+ }
+
+ companion object {
+ /** Only devices heard this recently go out. */
+ const val FRESH_MS = 2 * 60_000L
+ const val FORGET_MS = 5 * 60_000L
+ const val MAX_DEVICES = 2_000
+ fun repeatMs(priority: Int) = when (priority) {
+ 2 -> 60_000L
+ 1 -> 3 * 60_000L
+ else -> 15 * 60_000L
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt b/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt
new file mode 100644
index 0000000..1d4470e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/MeshProto.kt
@@ -0,0 +1,246 @@
+package com.rfsentinel.app.link
+
+import java.io.ByteArrayOutputStream
+
+/**
+ * The few messages of the Meshtastic phone API (ToRadio / FromRadio protobufs) Sentinel Link uses, written by hand
+ * with the field numbers of meshtastic/protobufs (mesh.proto, channel.proto, admin.proto, config.proto), so the
+ * official firmware needs nothing added. Unknown fields are skipped, as protobuf readers do.
+ */
+object MeshProto {
+ /** Meshtastic's port for apps' own data: RF Sentinel's messages, which other apps leave alone. */
+ const val PORT_PRIVATE_APP = 256
+ const val PORT_ADMIN_APP = 6
+ 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
+ /** Largest payload of one packet (Constants.DATA_PAYLOAD_LEN). */
+ const val MAX_PAYLOAD = 233
+ const val PRIORITY_BACKGROUND = 10
+ const val PRIORITY_DEFAULT = 64
+ const val PRIORITY_RELIABLE = 70
+ const val ROLE_DISABLED = 0
+ const val ROLE_SECONDARY = 2
+
+ // ------------------------------------------------------------------ to the node
+
+ fun wantConfig(nonce: Int): ByteArray = W().apply { uint(3, nonce.toLong() and 0xFFFFFFFFL) }.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 {
+ msg(1) {
+ fixed32(2, to)
+ uint(3, channel.toLong())
+ msg(4) { uint(1, port.toLong()); bytes(2, payload) }
+ fixed32(6, id)
+ uint(9, hopLimit.toLong())
+ uint(11, priority.toLong())
+ }
+ }.bytes()
+
+ /** AdminMessage.set_channel: a secondary channel with this name and key, no MQTT. */
+ fun setChannel(index: Int, name: String, psk: ByteArray): ByteArray = W().apply {
+ msg(33) {
+ uint(1, index.toLong())
+ msg(2) { bytes(2, psk); string(3, name) }
+ uint(3, ROLE_SECONDARY.toLong())
+ }
+ }.bytes()
+
+ // ------------------------------------------------------------------ from the node
+
+ sealed class From {
+ data class MyInfo(val nodeNum: Long) : From()
+ class ChannelInfo(val index: Int, val role: Int, val name: String, val psk: ByteArray) : From()
+ /** 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()
+ data class Queue(val res: Int, val free: Int) : From()
+ object Rebooted : From()
+ object Other : From()
+ }
+
+ fun readFromRadio(b: ByteArray): From {
+ var out: From = From.Other
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 2 && w == 2 -> { out = readPacket(r.bytes()); true }
+ f == 3 && w == 2 -> { out = readMyInfo(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 }
+ f == 10 && w == 2 -> { out = readChannel(r.bytes()); true }
+ f == 11 && w == 2 -> { out = readQueue(r.bytes()); true }
+ else -> false
+ }
+ }
+ return out
+ }
+
+ 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
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 1 && w == 5 -> { from = r.fixed32(); true }
+ f == 2 && w == 5 -> { to = r.fixed32(); true }
+ f == 3 && w == 0 -> { channel = r.varint().toInt(); true }
+ f == 4 && w == 2 -> {
+ val d = R(r.bytes())
+ d.fields { df, dw ->
+ when {
+ df == 1 && dw == 0 -> { port = d.varint().toInt(); true }
+ df == 2 && dw == 2 -> { payload = d.bytes(); true }
+ else -> false
+ }
+ }
+ true
+ }
+ f == 12 && w == 0 -> { rssi = r.varint().toInt(); true }
+ else -> false
+ }
+ }
+ return From.Packet(from, to, channel, port, payload, rssi)
+ }
+
+ private fun readMyInfo(b: ByteArray): From {
+ var num = 0L
+ val r = R(b)
+ r.fields { f, w -> if (f == 1 && w == 0) { num = r.varint() and 0xFFFFFFFFL; true } else false }
+ return From.MyInfo(num)
+ }
+
+ private fun readConfig(b: ByteArray): From {
+ var out: From = From.Other
+ val r = R(b)
+ r.fields { f, w ->
+ if (f == 6 && w == 2) {
+ var hop = 0; var region = 0; var tx = false
+ val l = R(r.bytes())
+ l.fields { lf, lw ->
+ when {
+ lf == 7 && lw == 0 -> { region = l.varint().toInt(); true }
+ lf == 8 && lw == 0 -> { hop = l.varint().toInt(); true }
+ lf == 9 && lw == 0 -> { tx = l.varint() != 0L; true }
+ else -> false
+ }
+ }
+ out = From.Lora(hop, region, tx)
+ true
+ } else false
+ }
+ return out
+ }
+
+ private fun readChannel(b: ByteArray): From {
+ var index = 0; var role = 0; var name = ""; var psk = ByteArray(0)
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 1 && w == 0 -> { index = r.varint().toInt(); true }
+ f == 2 && w == 2 -> {
+ val st = R(r.bytes())
+ st.fields { sf, sw ->
+ when {
+ sf == 2 && sw == 2 -> { psk = st.bytes(); true }
+ sf == 3 && sw == 2 -> { name = String(st.bytes(), Charsets.UTF_8); true }
+ else -> false
+ }
+ }
+ true
+ }
+ f == 3 && w == 0 -> { role = r.varint().toInt(); true }
+ else -> false
+ }
+ }
+ return From.ChannelInfo(index, role, name, psk)
+ }
+
+ private fun readQueue(b: ByteArray): From {
+ var res = 0; var free = 0
+ val r = R(b)
+ r.fields { f, w ->
+ when {
+ f == 1 && w == 0 -> { res = r.varint().toInt(); true }
+ f == 2 && w == 0 -> { free = r.varint().toInt(); true }
+ else -> false
+ }
+ }
+ return From.Queue(res, free)
+ }
+
+ // ------------------------------------------------------------------ wire format
+
+ /** Protobuf writer: zero / false / empty values are left out, as proto3 does. */
+ class W {
+ private val out = ByteArrayOutputStream()
+ fun bytes(): ByteArray = out.toByteArray()
+ private fun varint(value: Long) {
+ var v = value
+ while (v and 0x7FL.inv() != 0L) { out.write(((v and 0x7F) or 0x80).toInt()); v = v ushr 7 }
+ out.write(v.toInt())
+ }
+ private fun tag(field: Int, wire: Int) = varint(((field shl 3) or wire).toLong())
+ fun uint(field: Int, v: Long) { if (v != 0L) { tag(field, 0); varint(v) } }
+ /** A signed int32 (negative ones take 10 bytes, sign-extended). */
+ fun int32(field: Int, v: Int) { if (v != 0) { tag(field, 0); varint(v.toLong()) } }
+ fun bool(field: Int, v: Boolean) { if (v) { tag(field, 0); varint(1) } }
+ fun fixed32(field: Int, v: Long) {
+ tag(field, 5)
+ for (i in 0 until 4) out.write(((v ushr (8 * i)) and 0xFF).toInt())
+ }
+ fun bytes(field: Int, b: ByteArray) { tag(field, 2); varint(b.size.toLong()); out.write(b) }
+ fun string(field: Int, s: String) { if (s.isNotEmpty()) bytes(field, s.toByteArray(Charsets.UTF_8)) }
+ fun msg(field: Int, block: W.() -> Unit) = bytes(field, W().apply(block).bytes())
+ }
+
+ /** Protobuf reader; throws on malformed input. */
+ class R(private val b: ByteArray) {
+ private var pos = 0
+ fun varint(): Long {
+ var shift = 0
+ var r = 0L
+ while (true) {
+ require(pos < b.size && shift < 64) { "bad varint" }
+ val x = b[pos++].toInt() and 0xFF
+ r = r or ((x and 0x7F).toLong() shl shift)
+ if (x and 0x80 == 0) return r
+ shift += 7
+ }
+ }
+ fun fixed32(): Long {
+ require(pos + 4 <= b.size) { "short fixed32" }
+ var v = 0L
+ for (i in 0 until 4) v = v or ((b[pos + i].toLong() and 0xFF) shl (8 * i))
+ pos += 4
+ return v
+ }
+ fun bytes(): ByteArray {
+ val n = varint()
+ require(n >= 0 && pos + n <= b.size) { "short bytes" }
+ return b.copyOfRange(pos, pos + n.toInt()).also { pos += n.toInt() }
+ }
+ private fun skip(wire: Int) {
+ when (wire) {
+ 0 -> varint()
+ 1 -> pos += 8
+ 2 -> bytes()
+ 5 -> pos += 4
+ else -> throw IllegalArgumentException("wire type $wire")
+ }
+ require(pos <= b.size) { "short field" }
+ }
+ /** Each field in turn: [f] reads it and returns true, or returns false to skip it. */
+ fun fields(f: (field: Int, wire: Int) -> Boolean) {
+ while (pos < b.size) {
+ val key = varint()
+ val field = (key ushr 3).toInt()
+ val wire = (key and 7).toInt()
+ if (!f(field, wire)) skip(wire)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
index 073618f..61bb26b 100644
--- a/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
@@ -77,6 +77,7 @@ object PhoneLink {
private const val PAIR_PICK_MS = 2_500L
private const val ADVERT_RECHECK_MS = 5_000L
private const val TICK_MS = 5_000L
+ private const val MESH_MAX_SKEW_MS = 15 * 60_000L
private val thread = HandlerThread("rf-link").apply { start() }
private val h = Handler(thread.looper)
@@ -85,6 +86,7 @@ object PhoneLink {
private var ctx: Context? = null
private var sharing = false
private var groupKey: ByteArray? = null
+ private var meshKey: ByteArray? = null
private var myId = 0L
private var names: Map<Long, String> = emptyMap()
@@ -121,6 +123,8 @@ object PhoneLink {
/** When each Sentinel was last heard from (directly or relayed), wall clock. */
val lastHeard = ConcurrentHashMap<Long, Long>()
+ /** When each Sentinel was last heard over the mesh (Meshtastic node). */
+ val lastHeardMesh = ConcurrentHashMap<Long, Long>()
private val listeners = CopyOnWriteArraySet<() -> Unit>()
fun addListener(l: () -> Unit) { listeners += l }
@@ -208,6 +212,7 @@ object PhoneLink {
private fun loadGroup() {
val c = ctx ?: return
groupKey = LinkStore.groupKey(c)
+ meshKey = groupKey?.let { MeshCodec.messageKey(it) }
myId = LinkStore.myId(c)
names = LinkStore.members(c).associate { it.id to it.name }
tagSlot = Long.MIN_VALUE
@@ -749,13 +754,40 @@ object PhoneLink {
lastHeard[b.origin] = System.currentTimeMillis()
l.peer?.id?.let { lastHeard[it] = System.currentTimeMillis() }
onBatch?.invoke(b, nameOf(b.origin))
- if (b.hops < LinkCodec.MAX_HOPS) {
- val targets = links.filter { it !== l && it.ready && it.peer?.id != b.origin && it.queuedBytes < MAX_QUEUED_BYTES }
- if (targets.isNotEmpty()) {
- val bytes = LinkCodec.batch(b.relayed())
- targets.forEach { sendSealed(it, bytes) }
- }
+ relay(b, l)
+ }
+
+ /** Passes [b] on to the other linked Sentinels, up to [LinkCodec.MAX_HOPS] times. */
+ private fun relay(b: LinkCodec.Batch, from: Link?) {
+ if (b.hops >= LinkCodec.MAX_HOPS) return
+ val targets = links.filter { it !== from && it.ready && it.peer?.id != b.origin && it.queuedBytes < MAX_QUEUED_BYTES }
+ if (targets.isEmpty()) return
+ val bytes = LinkCodec.batch(b.relayed())
+ targets.forEach { sendSealed(it, bytes) }
+ }
+
+ /**
+ * A packet from the Meshtastic node: what a Sentinel far away heard. Shown like a Bluetooth one and passed on
+ * to the Sentinels linked here over Bluetooth (each one shows it once, whichever way it arrives first).
+ */
+ fun meshIn(payload: ByteArray) = h.post {
+ if (!sharing) return@post
+ val key = meshKey ?: return@post
+ val m = MeshCodec.open(key, payload) ?: return@post
+ if (m.origin == myId) return@post
+ val now = System.currentTimeMillis()
+ // Kept from being replayed much later (phones' clocks are close enough).
+ if (kotlin.math.abs(now - m.time) > MESH_MAX_SKEW_MS) return@post
+ val c = ctx ?: return@post
+ m.name?.let { if (LinkStore.addMembers(c, listOf(LinkCodec.Member(m.origin, it)))) names = LinkStore.members(c).associate { x -> x.id to x.name } }
+ lastHeard[m.origin] = now
+ lastHeardMesh[m.origin] = now
+ val b = MeshCodec.toBatch(m)
+ if (seen.first(b.origin, b.seq)) {
+ onBatch?.invoke(b, nameOf(b.origin))
+ relay(b, null)
}
+ changed()
}
// ---------------------------------------------------------------- linking a new phone
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 037b00c..4c4ed2f 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -111,6 +111,11 @@ class ScanForegroundService : Service() {
private const val LINK_FLUSH_MS = 1_000L
/** A device this phone (or its hardware) heard this recently isn't taken from another Sentinel. */
private const val HEARD_HERE_MS = 10_000L
+ /** Mesh: how often the send queue is checked, the shortest gap for a watchlist match, a presence packet, the name. */
+ private const val MESH_TICK_MS = 5_000L
+ private const val MESH_MIN_GAP_MS = 15_000L
+ private const val MESH_PRESENCE_MS = 10 * 60_000L
+ private const val MESH_NAME_MS = 10 * 60_000L
/** A network fix this soon after a raw GPS fix is ignored. */
private const val RAW_GPS_PREFERRED_MS = 10_000L
private const val PLACING_MAX_ACCURACY_M = 50f
@@ -614,7 +619,7 @@ class ScanForegroundService : Service() {
* null for what this phone and its hardware heard.
*/
private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null, broadcast: DeviceRegistry.GeoSample? = null,
- via: String? = null, peerAt: Location? = null) {
+ via: String? = null, peerAt: Location? = null, toMesh: Boolean = via == null) {
val now = a.timestamp
val mac = a.mac
if (OuiWatchlist.version != watchlistVersion) recheckWatchlist(now)
@@ -648,6 +653,8 @@ class ScanForegroundService : Service() {
val geo = if (via != null) loc?.let { DeviceRegistry.GeoSample(now, it.latitude, it.longitude) } else loc?.let { placeNow(it, now) }
val isFirst = DeviceRegistry.report(a, c.hits, c.identity, c.vendor, remoteId, geo, now, broadcast)
if (isFirst) serviceScope.launch { loadHistory(mac) }
+ // Over the mesh too (Meshtastic node): not the user's own whitelisted devices.
+ if (toMesh && !WhitelistCache.contains(mac)) meshOutbox?.add(a, c.hits, now)
if (TripRecorder.isRecording) {
TripRecorder.onDevice(
mac, a.rssi, a.source.name,
@@ -778,9 +785,71 @@ class ScanForegroundService : Service() {
pipeline.postDelayed(linkFlush, LINK_FLUSH_MS)
}
com.rfsentinel.app.link.PhoneLink.start(this) { b, name -> pipeline.post { onPeerBatch(b, name) } }
+ updateMesh()
+ }
+
+ /** What goes out over the Meshtastic node (null while it's off). */
+ @Volatile private var meshOutbox: com.rfsentinel.app.link.MeshOutbox? = null
+ private var meshLastSend = 0L
+ private var meshLastName = 0L
+
+ /** The Meshtastic node runs with Sentinel Link when it's turned on and chosen. */
+ private fun updateMesh() {
+ val link = com.rfsentinel.app.link.LinkStore
+ val node = link.meshNode(this)
+ val key = link.groupKey(this)
+ if (linkOutbox == null || !link.meshOn(this) || node == null || key == null) { stopMesh(); return }
+ if (meshOutbox == null) {
+ meshOutbox = com.rfsentinel.app.link.MeshOutbox()
+ meshLastSend = 0L
+ meshLastName = 0L
+ pipeline.postDelayed(meshFlush, MESH_TICK_MS)
+ }
+ com.rfsentinel.app.link.MeshNode.start(this, node, key) { com.rfsentinel.app.link.PhoneLink.meshIn(it) }
+ }
+
+ private fun stopMesh() {
+ if (meshOutbox == null) return
+ meshOutbox = null
+ pipeline.removeCallbacks(meshFlush)
+ com.rfsentinel.app.link.MeshNode.stop()
+ }
+
+ /**
+ * One packet now and then: at the chosen interval, sooner (15 s apart at least) for a new watchlist match,
+ * and every 10 minutes even with nothing new so the others know this Sentinel is there and where.
+ */
+ private val meshFlush = object : Runnable {
+ override fun run() {
+ val box = meshOutbox ?: return
+ pipeline.postDelayed(this, MESH_TICK_MS)
+ val node = com.rfsentinel.app.link.MeshNode
+ if (!node.ready) return
+ val ctx = this@ScanForegroundService
+ val link = com.rfsentinel.app.link.LinkStore
+ val now = System.currentTimeMillis()
+ val since = now - meshLastSend
+ val urgent = box.urgent(now)
+ val presence = since >= MESH_PRESENCE_MS
+ if (since < link.meshIntervalSec(ctx) * 1000L && !(urgent && since >= MESH_MIN_GAP_MS) && !presence) return
+ val key = link.groupKey(ctx) ?: return
+ val loc = lastLocation?.takeIf { usableForPlacing(it) }
+ val lat = loc?.latitude ?: Double.NaN
+ val lon = loc?.longitude ?: Double.NaN
+ val name = if (now - meshLastName >= MESH_NAME_MS) link.myName(ctx) else null
+ val codec = com.rfsentinel.app.link.MeshCodec
+ val devices = box.take(now, codec.MAX_BODY - codec.baseSize(!lat.isNaN(), name))
+ if (devices.isEmpty() && !presence) return
+ val bytes = codec.seal(codec.messageKey(key), link.myId(ctx), link.nextMeshCounter(ctx), now, lat, lon, name, devices)
+ if (node.send(bytes, urgent)) {
+ meshLastSend = now
+ if (name != null) meshLastName = now
+ }
+ }
}
private fun stopLink() {
+ stopMesh()
if (linkOutbox == null) return
linkOutbox = null
pipeline.removeCallbacks(linkFlush)
@@ -816,7 +885,8 @@ class ScanForegroundService : Service() {
// Heard here too: this phone's own reading (signal, place) is the one shown.
if (heardBy.phone.within(mac, HEARD_HERE_MS, now) || heardBy.esp.within(mac, HEARD_HERE_MS, now) ||
heardBy.usb.within(mac, HEARD_HERE_MS, now)) continue
- process(a, via = via, peerAt = at)
+ // Heard by a Sentinel linked here over Bluetooth: this phone's node passes it on to the mesh.
+ process(a, via = via, peerAt = at, toMesh = b.hops == 0)
}
for (r in b.radios) {
val kind = runCatching { com.rfsentinel.app.sdr.RadioWatch.Kind.valueOf(r.kind) }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
index 0e0c559..2e1b511 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
@@ -6,7 +6,9 @@ import android.os.Bundle
import android.text.format.DateUtils
import android.view.Gravity
import android.view.View
+import android.widget.ArrayAdapter
import android.widget.EditText
+import android.widget.ListView
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
@@ -19,8 +21,10 @@ import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.slider.Slider
import com.google.android.material.switchmaterial.SwitchMaterial
import com.rfsentinel.app.link.LinkStore
+import com.rfsentinel.app.link.MeshNode
import com.rfsentinel.app.link.PhoneLink
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.applySystemBarInsets
@@ -37,14 +41,18 @@ class SentinelLinkActivity : AppCompatActivity() {
private lateinit var share: SwitchMaterial
private lateinit var list: LinearLayout
private lateinit var leave: MaterialButton
+ private lateinit var meshSection: LinearLayout
+ private lateinit var meshSwitch: SwitchMaterial
+ private lateinit var meshNodeText: TextView
+ private lateinit var meshStatus: TextView
private var pairDialog: AlertDialog? = null
- private var pendingHost: Boolean? = null
+ private var pending: (() -> Unit)? = null
private val onLinkChanged: () -> Unit = { refresh() }
private val permissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
- val host = pendingHost ?: return@registerForActivityResult
- pendingHost = null
- if (PhoneLink.canUse(this)) startPairing(host)
+ val action = pending ?: return@registerForActivityResult
+ pending = null
+ if (PhoneLink.canUse(this)) action()
else Toast.makeText(this, "Sentinel Link needs \"Nearby devices\"", Toast.LENGTH_LONG).show()
}
@@ -100,11 +108,13 @@ class SentinelLinkActivity : AppCompatActivity() {
setOnClickListener { confirmLeave() }
}
+ meshSection = meshSection(::button)
+
val column = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(pad(16), pad(16), pad(16), pad(16))
addView(intro); addView(status); addView(nameLabel); addView(name); addView(share)
- addView(hostButton); addView(joinButton); addView(listHeader); addView(list); addView(leave)
+ addView(hostButton); addView(joinButton); addView(listHeader); addView(list); addView(meshSection); addView(leave)
}
val scroll = ScrollView(this).apply { addView(column) }
setContentView(scroll)
@@ -120,13 +130,107 @@ class SentinelLinkActivity : AppCompatActivity() {
override fun onStart() {
super.onStart()
PhoneLink.addListener(onLinkChanged)
+ MeshNode.addListener(onLinkChanged)
}
override fun onStop() {
PhoneLink.removeListener(onLinkChanged)
+ MeshNode.removeListener(onLinkChanged)
super.onStop()
}
+ /** Meshtastic node: on / off, which node, how it's doing, how often it sends. */
+ private fun meshSection(button: (String, () -> Unit) -> MaterialButton): LinearLayout {
+ val header = TextView(this).apply {
+ textSize = 16f; setTypeface(typeface, Typeface.BOLD); text = "Meshtastic node"; setPadding(0, pad(20), 0, pad(4))
+ }
+ val about = TextView(this).apply {
+ textSize = 14f
+ setLineSpacing(0f, 1.2f)
+ text = "Reach Sentinels kilometres away through a Meshtastic node: a LoRa board with the official firmware, " +
+ "paired with this phone over Bluetooth. RF Sentinel adds a private channel named ${com.rfsentinel.app.link.MeshCodec.CHANNEL_NAME} " +
+ "to the node, made from the group's key, so only your group reads it. LoRa is slow: watchlist matches go " +
+ "first, then flagged devices, then every other device, a few per packet. While RF Sentinel uses the node, " +
+ "the Meshtastic app on this phone can't."
+ }
+ meshSwitch = SwitchMaterial(this).apply {
+ text = "Use a Meshtastic node"
+ isChecked = LinkStore.meshOn(this@SentinelLinkActivity)
+ setOnCheckedChangeListener { _, on ->
+ LinkStore.setMeshOn(this@SentinelLinkActivity, on)
+ ScanForegroundService.refreshLink(this@SentinelLinkActivity)
+ if (on && LinkStore.meshNode(this@SentinelLinkActivity) == null) chooseNode()
+ refresh()
+ }
+ setPadding(0, pad(8), 0, pad(8))
+ }
+ meshNodeText = TextView(this).apply { textSize = 14f }
+ meshStatus = TextView(this).apply { textSize = 14f; setPadding(0, pad(4), 0, 0) }
+ val choose = button("Choose a node") { chooseNode() }
+ val intervalLabel = TextView(this).apply { textSize = 14f; setPadding(0, pad(12), 0, 0) }
+ fun showInterval(s: Int) { intervalLabel.text = "Send a packet every $s s - watchlist matches sooner" }
+ val step = 15
+ val interval = Slider(this).apply {
+ valueFrom = LinkStore.MESH_INTERVAL_MIN.toFloat()
+ valueTo = LinkStore.MESH_INTERVAL_MAX.toFloat()
+ stepSize = step.toFloat()
+ value = (LinkStore.meshIntervalSec(this@SentinelLinkActivity) / step * step).toFloat()
+ .coerceIn(valueFrom, valueTo)
+ addOnChangeListener { _, v, fromUser ->
+ showInterval(v.toInt())
+ if (fromUser) LinkStore.setMeshIntervalSec(this@SentinelLinkActivity, v.toInt())
+ }
+ }
+ showInterval(interval.value.toInt())
+ return LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(header); addView(about); addView(meshSwitch); addView(meshNodeText); addView(meshStatus)
+ addView(choose); addView(intervalLabel); addView(interval)
+ setPadding(0, 0, 0, pad(12))
+ }
+ }
+
+ /** Lists the Meshtastic nodes nearby; the one tapped is paired (Android asks for its PIN) and used. */
+ private fun chooseNode() = withPermission {
+ val names = ArrayList<String>()
+ val addresses = ArrayList<String>()
+ val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, names)
+ val hint = TextView(this).apply {
+ textSize = 14f
+ text = "Looking for Meshtastic nodes nearby… Turn the node on, keep it close, and close the Meshtastic app if it's connected to it."
+ setPadding(pad(24), pad(12), pad(24), pad(8))
+ }
+ val listView = ListView(this).apply { this.adapter = adapter }
+ val body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; addView(hint); addView(listView) }
+ var stop: (() -> Unit)? = null
+ val dialog = MaterialAlertDialogBuilder(this)
+ .setTitle("Choose a Meshtastic node")
+ .setView(body)
+ .setNegativeButton("Cancel", null)
+ .create()
+ listView.setOnItemClickListener { _, _, i, _ ->
+ val address = addresses.getOrNull(i) ?: return@setOnItemClickListener
+ stop?.invoke(); stop = null
+ LinkStore.setMeshNode(this, address, names[i].substringBefore(" · "))
+ LinkStore.setMeshOn(this, true)
+ meshSwitch.isChecked = true
+ MeshNode.pair(this, address)
+ ScanForegroundService.refreshLink(this)
+ dialog.dismiss()
+ refresh()
+ Toast.makeText(this, "If Android asks for a PIN: it's on the node's screen, or 123456", Toast.LENGTH_LONG).show()
+ }
+ dialog.setOnDismissListener { stop?.invoke(); stop = null }
+ stop = MeshNode.find(this) { name, address, rssi ->
+ val label = "$name · $rssi dBm"
+ val i = addresses.indexOf(address)
+ if (i >= 0) names[i] = label else { addresses += address; names += label }
+ adapter.notifyDataSetChanged()
+ }
+ if (stop == null) { Toast.makeText(this, "Turn Bluetooth on first", Toast.LENGTH_LONG).show(); return@withPermission }
+ dialog.show()
+ }
+
override fun onDestroy() {
if (pairDialog?.isShowing == true) PhoneLink.cancelPairing()
pairDialog = null
@@ -152,6 +256,15 @@ class SentinelLinkActivity : AppCompatActivity() {
}
share.visibility = if (grouped) View.VISIBLE else View.GONE
leave.visibility = if (grouped) View.VISIBLE else View.GONE
+ meshSection.visibility = if (grouped) View.VISIBLE else View.GONE
+ meshNodeText.text = LinkStore.meshNodeName(this)?.let { "Node: $it" } ?: "No node chosen yet"
+ meshStatus.text = when {
+ !LinkStore.meshOn(this) -> "Off"
+ LinkStore.meshNode(this) == null -> "Choose a node"
+ !ScanForegroundService.isRunning || !LinkStore.enabled(this) -> "Starts with sharing, while scanning"
+ else -> MeshNode.status.ifBlank { "Starting…" } +
+ (MeshNode.lastSent.takeIf { it > 0 }?.let { " · sent " + DateUtils.getRelativeTimeSpanString(it, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS) } ?: "")
+ }
list.removeAllViews()
val members = LinkStore.members(this)
@@ -166,8 +279,11 @@ class SentinelLinkActivity : AppCompatActivity() {
val now = System.currentTimeMillis()
for (m in members) {
val heard = PhoneLink.lastHeard[m.id]
+ val overMesh = PhoneLink.lastHeardMesh[m.id]
val detail = when {
linked.containsKey(m.id) -> "Linked now"
+ overMesh != null && overMesh == heard ->
+ "Over the mesh · last heard " + DateUtils.getRelativeTimeSpanString(overMesh, now, DateUtils.MINUTE_IN_MILLIS)
heard != null -> "Last heard " + DateUtils.getRelativeTimeSpanString(heard, now, DateUtils.MINUTE_IN_MILLIS)
else -> "Not in reach"
}
@@ -201,17 +317,20 @@ class SentinelLinkActivity : AppCompatActivity() {
.setTitle("Join another group?")
.setMessage("This phone is linked with $others Sentinel${if (others == 1) "" else "s"}. Joining leaves that group for the " +
"other phone's. To add a phone to this group instead, tap \"Link up a Sentinel\" here and \"Join a Sentinel\" on the new phone.")
- .setPositiveButton("Join") { _, _ -> withPermission(false) }
+ .setPositiveButton("Join") { _, _ -> withPermission { startPairing(false) } }
.setNegativeButton("Cancel", null)
.show()
return
}
- withPermission(host)
+ withPermission { startPairing(host) }
}
- private fun withPermission(host: Boolean) {
- if (PhoneLink.canUse(this)) { startPairing(host); return }
- pendingHost = host
+ private fun withPermission(action: () -> Unit) {
+ if (PhoneLink.canUse(this) && (Build.VERSION.SDK_INT < 31 ||
+ checkSelfPermission(android.Manifest.permission.BLUETOOTH_SCAN) == android.content.pm.PackageManager.PERMISSION_GRANTED)) {
+ action(); return
+ }
+ pending = action
permissions.launch(if (Build.VERSION.SDK_INT >= 31) arrayOf(
android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_ADVERTISE,
android.Manifest.permission.BLUETOOTH_SCAN) else emptyArray())
diff --git a/app/src/test/java/com/rfsentinel/app/link/MeshLinkTest.kt b/app/src/test/java/com/rfsentinel/app/link/MeshLinkTest.kt
new file mode 100644
index 0000000..9baeef2
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/link/MeshLinkTest.kt
@@ -0,0 +1,172 @@
+package com.rfsentinel.app.link
+
+import android.app.Application
+import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Hit
+import org.junit.Assert.assertArrayEquals
+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 org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.ConscryptMode
+
+/** Sentinel Link over Meshtastic: the phone-API protobufs, RF Sentinel's packet, and what goes out first. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+@ConscryptMode(ConscryptMode.Mode.OFF)
+class MeshLinkTest {
+
+ @Test
+ fun wantConfigMatchesTheFirmwaresSpecialNonce() {
+ // ToRadio.want_config_id (field 3) = 69420.
+ assertArrayEquals(byteArrayOf(0x18, 0xAC.toByte(), 0x9E.toByte(), 0x04), MeshProto.wantConfig(MeshProto.CONFIG_ONLY))
+ }
+
+ @Test
+ fun readsPacketsAndSkipsUnknownFields() {
+ val payload = byteArrayOf(1, 2, 3)
+ val bytes = MeshProto.W().apply {
+ uint(1, 77) // FromRadio.id
+ msg(2) {
+ fixed32(1, 0xA1B2C3D4L)
+ fixed32(2, MeshProto.BROADCAST)
+ uint(3, 2)
+ msg(4) { uint(1, MeshProto.PORT_PRIVATE_APP.toLong()); bytes(2, payload); uint(9, 5) }
+ fixed32(7, 1_700_000_000L)
+ int32(12, -97)
+ uint(99, 12345)
+ }
+ }.bytes()
+ val p = MeshProto.readFromRadio(bytes) as MeshProto.From.Packet
+ assertEquals(0xA1B2C3D4L, p.from)
+ assertEquals(MeshProto.BROADCAST, p.to)
+ assertEquals(2, p.channel)
+ assertEquals(MeshProto.PORT_PRIVATE_APP, p.port)
+ assertArrayEquals(payload, p.payload)
+ assertEquals(-97, p.rxRssi)
+ }
+
+ @Test
+ fun readsTheNodesSettings() {
+ val my = MeshProto.W().apply { msg(3) { uint(1, 0xDEADBEEFL) } }.bytes()
+ assertEquals(MeshProto.From.MyInfo(0xDEADBEEFL), MeshProto.readFromRadio(my))
+ val lora = MeshProto.W().apply { msg(5) { msg(6) { uint(2, 0); uint(7, 1); uint(8, 4); bool(9, true) } } }.bytes()
+ assertEquals(MeshProto.From.Lora(4, 1, true), MeshProto.readFromRadio(lora))
+ val done = MeshProto.W().apply { uint(7, MeshProto.CONFIG_ONLY.toLong()) }.bytes()
+ assertEquals(MeshProto.From.ConfigComplete(MeshProto.CONFIG_ONLY.toLong()), MeshProto.readFromRadio(done))
+ val psk = ByteArray(32) { it.toByte() }
+ val ch = MeshProto.W().apply { msg(10) { uint(1, 3); msg(2) { bytes(2, psk); string(3, "RFSentinel") }; uint(3, 2) } }.bytes()
+ val c = MeshProto.readFromRadio(ch) as MeshProto.From.ChannelInfo
+ assertEquals(3, c.index); assertEquals(2, c.role); assertEquals("RFSentinel", c.name); assertArrayEquals(psk, c.psk)
+ assertTrue(MeshProto.readFromRadio(MeshProto.W().apply { uint(16, 1) }.bytes()) === MeshProto.From.Other)
+ assertTrue(runCatching { MeshProto.readFromRadio(byteArrayOf(0x12, 0x7F)) }.isFailure)
+ }
+
+ @Test
+ fun outgoingPacketHasTheRightFields() {
+ val payload = byteArrayOf(9, 8, 7)
+ val toRadio = MeshProto.packet(MeshProto.BROADCAST, 2, MeshProto.PORT_PRIVATE_APP, payload, 0x01020304L, 3,
+ MeshProto.PRIORITY_BACKGROUND)
+ // ToRadio.packet is field 1, FromRadio.packet field 2: same MeshPacket inside.
+ assertEquals(0x0A, toRadio[0].toInt())
+ val p = MeshProto.readFromRadio(byteArrayOf(0x12) + toRadio.copyOfRange(1, toRadio.size)) as MeshProto.From.Packet
+ assertEquals(MeshProto.BROADCAST, p.to); assertEquals(2, p.channel); assertEquals(MeshProto.PORT_PRIVATE_APP, p.port)
+ assertArrayEquals(payload, p.payload)
+ }
+
+ @Test
+ fun setChannelIsASecondaryChannelWithOurKey() {
+ val psk = ByteArray(32) { 7 }
+ val admin = MeshProto.setChannel(4, MeshCodec.CHANNEL_NAME, psk)
+ // AdminMessage.set_channel = field 33: key 33 << 3 | 2 = 266, two varint bytes.
+ assertEquals(0x8A, admin[0].toInt() and 0xFF); assertEquals(0x02, admin[1].toInt())
+ val c = MeshProto.readFromRadio(byteArrayOf(0x52) + admin.copyOfRange(2, admin.size)) as MeshProto.From.ChannelInfo
+ assertEquals(4, c.index); assertEquals(MeshProto.ROLE_SECONDARY, c.role); assertEquals(MeshCodec.CHANNEL_NAME, c.name)
+ assertArrayEquals(psk, c.psk)
+ }
+
+ private val watch = Hit(Category.CUSTOM, "My watched camera", 90, "prefix", "Watchlist")
+ private val cam = Hit(Category.BODY_CAM, "Axon body camera", 80, "company id", "BLE")
+
+ @Test
+ fun meshPacketRoundTripsAndFitsOnePacket() {
+ val gk = LinkCrypto.random(32)
+ val key = MeshCodec.messageKey(gk)
+ val devices = listOf(
+ MeshCodec.Device("AA:BB:CC:00:11:22", Advert.Source.BLE, -61, 3, "Axon Body 3", listOf(watch, cam)),
+ MeshCodec.Device("11:22:33:44:55:66", Advert.Source.WIFI, -80, 40, null, emptyList()),
+ )
+ val sealed = MeshCodec.seal(key, 42L, 7, 1_700_000_000_000L, 10.5, -20.25, "Pixel 7", devices)
+ assertTrue(sealed.size <= MeshProto.MAX_PAYLOAD)
+ val m = MeshCodec.open(key, sealed)!!
+ assertEquals(42L, m.origin); assertEquals(7, m.counter); assertEquals(1_700_000_000_000L, m.time)
+ assertEquals(10.5, m.lat, 1e-5); assertEquals(-20.25, m.lon, 1e-5); assertEquals("Pixel 7", m.name)
+ assertEquals(2, m.devices.size)
+ val d = m.devices[0]
+ assertEquals("AA:BB:CC:00:11:22", d.mac); assertEquals(Advert.Source.BLE, d.source); assertEquals(-61, d.rssi)
+ assertEquals(3, d.ageSec); assertEquals("Axon Body 3", d.name)
+ assertEquals(listOf(Category.CUSTOM, Category.BODY_CAM), d.hits.map { it.category })
+ assertEquals("Axon body camera", d.hits[1].label); assertEquals(80, d.hits[1].confidence)
+ assertEquals(Advert.Source.WIFI, m.devices[1].source); assertNull(m.devices[1].name)
+
+ // Another group, or changed on the way: not read.
+ assertNull(MeshCodec.open(MeshCodec.messageKey(LinkCrypto.random(32)), sealed))
+ assertNull(MeshCodec.open(key, sealed.copyOf().also { it[it.size - 20] = (it[it.size - 20].toInt() xor 1).toByte() }))
+ assertNull(MeshCodec.open(key, sealed.copyOf().also { it[12] = (it[12].toInt() xor 1).toByte() })) // origin is authenticated too
+
+ // No position, no name, too many devices: still one packet, the rest left out.
+ val many = (0 until 60).map { MeshCodec.Device("AA:00:00:00:00:%02X".format(it), Advert.Source.BLE, -70, 1, "Device $it", emptyList()) }
+ val full = MeshCodec.seal(key, 1L, 8, 1_700_000_000_000L, Double.NaN, Double.NaN, null, many)
+ assertTrue(full.size <= MeshProto.MAX_PAYLOAD)
+ val back = MeshCodec.open(key, full)!!
+ assertTrue(back.lat.isNaN())
+ assertTrue(back.devices.size in 5 until 60)
+ }
+
+ @Test
+ fun meshMessageBecomesABatchApartFromBluetoothOnes() {
+ val m = MeshCodec.Message(5L, 3, 1_000_000L, 1.0, 2.0, null,
+ listOf(MeshCodec.Device("AA:BB:CC:00:11:22", Advert.Source.BLE, -60, 10, "x", listOf(cam))))
+ val b = MeshCodec.toBatch(m)
+ assertTrue(b.seq < 0)
+ assertEquals(1, b.hops)
+ assertEquals(990_000L, b.sightings[0].advert.timestamp)
+ assertEquals(listOf(cam.category), b.sightings[0].hits.map { it.category })
+ }
+
+ @Test
+ fun textIsCutWithoutBreakingCharacters() {
+ val b = MeshCodec.utf8("caméra 📷📷📷", 10)
+ assertTrue(b.size <= 10)
+ assertFalse(String(b, Charsets.UTF_8).contains('�'))
+ }
+
+ @Test
+ fun watchlistGoesFirstThenFlaggedThenTheRest() {
+ val box = MeshOutbox()
+ fun adv(mac: String) = Advert(mac, Advert.Source.BLE, -60, timestamp = 0)
+ box.add(adv("00:00:00:00:00:01"), emptyList(), 1_000)
+ box.add(adv("00:00:00:00:00:02"), listOf(cam), 1_000)
+ box.add(adv("00:00:00:00:00:03"), listOf(watch), 1_000)
+ assertTrue(box.urgent(1_000))
+ val first = box.take(2_000, MeshCodec.MAX_BODY)
+ assertEquals(listOf("00:00:00:00:00:03", "00:00:00:00:00:02", "00:00:00:00:00:01"), first.map { it.mac })
+ assertFalse(box.urgent(2_000))
+ // Nothing new: nothing due until each one's turn comes back.
+ assertTrue(box.take(3_000, MeshCodec.MAX_BODY).isEmpty())
+ box.add(adv("00:00:00:00:00:03"), listOf(watch), 61_000)
+ box.add(adv("00:00:00:00:00:02"), listOf(cam), 61_000)
+ assertEquals(listOf("00:00:00:00:00:03"), box.take(62_500, MeshCodec.MAX_BODY).map { it.mac })
+ // Small room: the most important one that fits.
+ box.add(adv("00:00:00:00:00:04"), listOf(watch), 63_000)
+ box.add(adv("00:00:00:00:00:05"), emptyList(), 63_000)
+ assertEquals(listOf("00:00:00:00:00:05"), box.take(63_500, 10).map { it.mac })
+ // Not heard for a while: not sent.
+ assertTrue(box.take(63_000 + MeshOutbox.FRESH_MS + 1, MeshCodec.MAX_BODY).isEmpty())
+ }
+}