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: share detections between nearby RF Sentinel phones over Bluetooth

CIS-C0bb37193db8a3
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index be4bbb9..79cb1f7 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -12,8 +12,10 @@
makes Android strip some beacon-style advertisements from results, and we
hold location permission anyway (WiFi scan results require it). -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
- <!-- Only to recognise your car's Bluetooth connection for auto-start (asked when you turn it on). -->
+ <!-- Your car's Bluetooth connection for auto-start, OUI-SPY boards and Sentinel Link (asked when you turn them on). -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+ <!-- Sentinel Link: other RF Sentinel phones find this one by a Bluetooth advert (API 31+). -->
+ <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Android Auto: the plate camera & drone map screen (PlaceListMapTemplate). -->
<uses-permission android:name="androidx.car.app.MAP_TEMPLATES" />
<!-- Android Auto: draw RF Sentinel's own pannable map (devices, cameras, route). -->
@@ -84,6 +86,7 @@
<activity android:name=".ui.CellTowersActivity" android:exported="false" />
<activity android:name=".ui.GnssActivity" android:exported="false" />
<activity android:name=".ui.WazeStatusActivity" android:exported="false" />
+ <activity android:name=".ui.SentinelLinkActivity" android:exported="false" />
<activity android:name=".ui.WifiAnalyzerActivity" android:exported="false" />
<activity android:name=".ui.AntennaCheckActivity" android:exported="false" />
<activity android:name=".ui.AircraftActivity" android:exported="false" />
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 60503ba..c9789d4 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -490,7 +490,8 @@ class MainActivity : AppCompatActivity() {
if (it.contains("ADS-B")) ({ com.rfsentinel.app.sdr.SdrRadio.adsbMessages }) else null, " msg/s")
},
com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }
- ?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) }
+ ?.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) }
)
statusPanel.update(running, warning, hardware)
return
@@ -512,7 +513,8 @@ class MainActivity : AppCompatActivity() {
com.rfsentinel.app.usb.UsbWifi.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty() +
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()
+ ?.let { "\n$it" }.orEmpty() +
+ com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }?.let { "\n$it" }.orEmpty()
}
}
@@ -985,6 +987,7 @@ class MainActivity : AppCompatActivity() {
heardByEsp = com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac, now),
heardByUsb = com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac, now),
heardByPhone = com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac, now),
+ heardByPeer = com.rfsentinel.app.esp.HeardBy.peer.via(s.mac, now),
rssi = s.rssi,
confidence = best?.confidence?.takeIf { !whitelisted }
)
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
index b381e88..bd8a0e4 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarUi.kt
@@ -94,10 +94,12 @@ object CarUi {
}
}
- /** Which radio heard it: an ESP32 board, a USB WiFi adapter, or the phone (Bluetooth / WiFi). */
+ /** Which radio heard it: an ESP32 board, a USB WiFi adapter, a linked Sentinel, or the phone (Bluetooth / WiFi). */
fun sourceTag(s: DeviceRegistry.Snapshot): String = when {
com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac) -> "USB WiFi"
com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) -> "ESP32"
+ !com.rfsentinel.app.esp.HeardBy.phone.recent(s.mac) && com.rfsentinel.app.esp.HeardBy.peer.recent(s.mac) ->
+ "via " + com.rfsentinel.app.esp.HeardBy.peer.via(s.mac)
s.source == com.rfsentinel.app.detect.Advert.Source.WIFI -> "WiFi"
else -> "Bluetooth"
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
index 112220a..139a223 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
@@ -201,10 +201,11 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live
private fun heardBy(s: DeviceRegistry.Snapshot): String = listOfNotNull(
if (com.rfsentinel.app.esp.HeardBy.phone.recent(mac) || (!com.rfsentinel.app.esp.HeardBy.esp.recent(mac) &&
- !com.rfsentinel.app.esp.HeardBy.usb.recent(mac)))
+ !com.rfsentinel.app.esp.HeardBy.usb.recent(mac) && !com.rfsentinel.app.esp.HeardBy.peer.recent(mac)))
"phone " + if (s.source == com.rfsentinel.app.detect.Advert.Source.WIFI) "WiFi" else "Bluetooth" else null,
if (com.rfsentinel.app.esp.HeardBy.esp.recent(mac)) "ESP32" else null,
- if (com.rfsentinel.app.esp.HeardBy.usb.recent(mac)) "USB WiFi" else null
+ if (com.rfsentinel.app.esp.HeardBy.usb.recent(mac)) "USB WiFi" else null,
+ com.rfsentinel.app.esp.HeardBy.peer.via(mac)?.let { "Sentinel $it" }
).joinToString(" + ")
private fun toggleWhitelist(whitelisted: Boolean, label: String) {
diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
index 03916fc..3a87fe3 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
@@ -70,6 +70,7 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)
DeviceFilter.FLAGGED -> "Flagged nearby"
DeviceFilter.NEW -> "New devices"
DeviceFilter.EXTERNAL -> "Heard by external hardware"
+ DeviceFilter.SENTINELS -> "Heard by linked Sentinels"
else -> f.label
}
@@ -80,6 +81,7 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)
f == DeviceFilter.DRONES -> "No drones nearby"
f == DeviceFilter.FAVORITES -> "No favorites nearby"
f == DeviceFilter.EXTERNAL -> "Nothing from an ESP32 board or USB WiFi adapter - see More > Hardware"
+ f == DeviceFilter.SENTINELS -> "Nothing from linked Sentinels - link phones in Settings > Sentinel Link"
f == DeviceFilter.ALL -> "Listening... no devices heard yet"
else -> "Nothing here right now"
}
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 1dd4fff..09707ae 100644
--- a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
@@ -217,7 +217,8 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
EspBoards.status.takeIf { it.isNotBlank() },
UsbWifi.status.takeIf { it.isNotBlank() },
SdrRadio.status.takeIf { it.isNotBlank() },
- OuiSpyBle.status.takeIf { it.isNotBlank() }
+ OuiSpyBle.status.takeIf { it.isNotBlank() },
+ com.rfsentinel.app.link.PhoneLink.status.takeIf { it.isNotBlank() }
).joinToString(" · ").ifEmpty { "Phone radios only" }
// ---- now playing -------------------------------------------------------------------
diff --git a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
index 46bcb56..39eec4b 100644
--- a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
+++ b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt
@@ -4,7 +4,7 @@ import java.util.concurrent.ConcurrentHashMap
/**
* Which radio heard a device recently: an ESP32 board (USB or OUI-SPY over
- * Bluetooth) and/or the phone's own chips, so the list can badge and filter them.
+ * Bluetooth), the phone's own chips and/or a linked Sentinel, so the list can badge and filter them.
*/
class RecentMacs {
private val last = ConcurrentHashMap<String, Long>()
@@ -23,11 +23,38 @@ class RecentMacs {
return false
}
+ /** Heard within [ms]. */
+ fun within(mac: String, ms: Long, now: Long = System.currentTimeMillis()): Boolean =
+ last[mac.uppercase()]?.let { now - it < ms } == true
+
fun clear() = last.clear()
private companion object { const val MAX_MACS = 5_000 }
}
+/** Devices another Sentinel (Sentinel Link) heard, with that Sentinel's name. */
+class PeerMacs {
+ private val last = ConcurrentHashMap<String, Pair<Long, String>>()
+
+ fun mark(mac: String, via: String, now: Long = System.currentTimeMillis()) {
+ last[mac.uppercase()] = now to via
+ if (last.size > 5_000) last.entries.removeAll { now - it.value.first >= HeardBy.WINDOW_MS }
+ }
+
+ /** The Sentinel that heard [mac] recently, or null. */
+ fun via(mac: String, now: Long = System.currentTimeMillis()): String? {
+ val key = mac.uppercase()
+ val v = last[key] ?: return null
+ if (now - v.first < HeardBy.WINDOW_MS) return v.second
+ last.remove(key, v)
+ return null
+ }
+
+ fun recent(mac: String, now: Long = System.currentTimeMillis()) = via(mac, now) != null
+
+ fun clear() = last.clear()
+}
+
object HeardBy {
/** How long a device keeps its badge after that radio last heard it. */
const val WINDOW_MS = 5 * 60_000L
@@ -36,4 +63,6 @@ object HeardBy {
/** A USB WiFi adapter in monitor mode. */
val usb = RecentMacs()
val phone = RecentMacs()
+ /** Another Sentinel (Sentinel Link). */
+ val peer = PeerMacs()
}
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkCodec.kt b/app/src/main/java/com/rfsentinel/app/link/LinkCodec.kt
new file mode 100644
index 0000000..1f444c5
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkCodec.kt
@@ -0,0 +1,235 @@
+package com.rfsentinel.app.link
+
+import com.rfsentinel.app.detect.AddressType
+import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.detect.Category
+import com.rfsentinel.app.detect.Hit
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.DataInputStream
+import java.io.DataOutputStream
+import java.nio.ByteBuffer
+import java.util.UUID
+import java.util.zip.Deflater
+import java.util.zip.DeflaterOutputStream
+import java.util.zip.InflaterInputStream
+
+/** What one Sentinel shares, and its wire format (big-endian, plain JVM so it's unit-tested). */
+object LinkCodec {
+ // ---- Message types: the first byte of every frame ----
+ /** Joiner -> host: ECDH public key + nonce. */
+ const val PAIR_HELLO = 1
+ /** Host -> joiner: ECDH public key + nonce. */
+ const val PAIR_REPLY = 2
+ /** Joiner -> host, sealed: the joiner's id and name once its user confirmed the code. */
+ const val PAIR_CONFIRM = 3
+ /** Host -> joiner, sealed: the group key and the Sentinels in it. */
+ const val PAIR_GROUP = 4
+ const val PAIR_CANCEL = 5
+ /** Connecting Sentinel -> other: nonce + proof of the group key. */
+ const val HELLO = 10
+ /** Answer to [HELLO]: nonce + proof. */
+ const val HELLO_REPLY = 11
+ /** Counter + AES-GCM data; inside, one of the inner types below. */
+ const val SEALED = 12
+
+ // ---- Inner (sealed) types ----
+ const val INFO = 20
+ const val BATCH = 21
+
+ /** Who heard it: the phone's own radios, an ESP32 board, a USB WiFi adapter. */
+ const val KIND_PHONE = 0
+ const val KIND_ESP = 1
+ const val KIND_USB = 2
+
+ data class Member(val id: Long, val name: String)
+
+ /** One device heard by a Sentinel, with what its hardware added. */
+ class Sighting(
+ val kind: Int,
+ val advert: Advert,
+ /** An ESP32 board's own watchlist matches. */
+ val hits: List<Hit> = emptyList(),
+ /** Network names it asked for (USB adapter / ESP32). */
+ val probed: List<String> = emptyList(),
+ val fingerprint: String? = null,
+ val hidden: Boolean = false,
+ )
+
+ /** One RTL-SDR / HackRF transmission ([com.rfsentinel.app.sdr.RadioWatch.Event]). */
+ data class Radio(
+ val freqHz: Long, val snrDb: Int, val bandLabel: String, val bandStartHz: Long, val bandEndHz: Long, val kind: String,
+ val confidence: Int, val targetLabel: String?, val repeat: Boolean, val tdma: Boolean, val time: Long,
+ )
+
+ /** What one Sentinel heard in about a second, passed on by others up to [MAX_HOPS] times. */
+ class Batch(
+ val origin: Long, val seq: Int, val hops: Int, val time: Long,
+ /** Where the Sentinel that heard these was (NaN when it had no fix). */
+ val lat: Double, val lon: Double,
+ val sightings: List<Sighting>, val radios: List<Radio>,
+ ) {
+ fun relayed() = Batch(origin, seq, hops + 1, time, lat, lon, sightings, radios)
+ }
+
+ const val MAX_HOPS = 2
+
+ /** [a] heard at [timestamp] (on this phone's clock: phones' clocks differ). */
+ fun rebased(a: Advert, timestamp: Long) = Advert(a.mac, a.source, a.rssi, a.name, a.manufacturerData, a.serviceUuids,
+ a.serviceData, a.rawBytes, a.txPower, a.addressType, a.connectable, a.phy, a.wifi, timestamp)
+
+ // ---- Small messages ----
+
+ fun pairHello(type: Int, pub: ByteArray, nonce: ByteArray): ByteArray = write {
+ writeByte(type); bytes(pub); bytes(nonce)
+ }
+
+ /** (public key, nonce) of [PAIR_HELLO] / [PAIR_REPLY]. */
+ fun readPairHello(b: ByteArray): Pair<ByteArray, ByteArray> = read(b) { readByte(); bytes() to bytes() }
+
+ fun member(m: Member): ByteArray = write { writeLong(m.id); writeUTF(m.name.take(40)) }
+ fun readMember(b: ByteArray): Member = read(b) { Member(readLong(), readUTF()) }
+
+ fun group(key: ByteArray, members: List<Member>): ByteArray = write {
+ bytes(key); writeShort(members.size); members.forEach { writeLong(it.id); writeUTF(it.name.take(40)) }
+ }
+
+ fun readGroup(b: ByteArray): Pair<ByteArray, List<Member>> = read(b) {
+ val key = bytes()
+ key to List(readUnsignedShort()) { Member(readLong(), readUTF()) }
+ }
+
+ fun hello(type: Int, nonce: ByteArray, proof: ByteArray): ByteArray = write { writeByte(type); bytes(nonce); bytes(proof) }
+ fun readHello(b: ByteArray): Pair<ByteArray, ByteArray> = read(b) { readByte(); bytes() to bytes() }
+
+ fun sealed(counter: Long, data: ByteArray): ByteArray =
+ ByteBuffer.allocate(9 + data.size).put(SEALED.toByte()).putLong(counter).put(data).array()
+
+ /** (counter, data) of a [SEALED] frame. */
+ fun readSealed(b: ByteArray): Pair<Long, ByteArray> = ByteBuffer.wrap(b).let { it.get(); it.long to b.copyOfRange(9, b.size) }
+
+ /** [INFO]: who this Sentinel is and every Sentinel it knows (so a new one spreads through the group). */
+ fun info(me: Member, members: List<Member>): ByteArray = write {
+ writeByte(INFO); writeLong(me.id); writeUTF(me.name.take(40))
+ writeShort(members.size); members.forEach { writeLong(it.id); writeUTF(it.name.take(40)) }
+ }
+
+ fun readInfo(b: ByteArray): Pair<Member, List<Member>> = read(b) {
+ readByte()
+ Member(readLong(), readUTF()) to List(readUnsignedShort()) { Member(readLong(), readUTF()) }
+ }
+
+ // ---- Batches ----
+
+ fun batch(b: Batch): ByteArray {
+ val body = ByteArrayOutputStream()
+ DataOutputStream(DeflaterOutputStream(body, Deflater(Deflater.BEST_SPEED))).use { o ->
+ o.writeLong(b.origin); o.writeInt(b.seq); o.writeByte(b.hops); o.writeLong(b.time)
+ o.writeDouble(b.lat); o.writeDouble(b.lon)
+ o.writeShort(b.sightings.size)
+ b.sightings.forEach { o.sighting(it, b.time) }
+ o.writeShort(b.radios.size)
+ b.radios.forEach { r ->
+ o.writeLong(r.freqHz); o.writeShort(r.snrDb); o.writeUTF(r.bandLabel); o.writeLong(r.bandStartHz); o.writeLong(r.bandEndHz)
+ o.writeUTF(r.kind); o.writeByte(r.confidence); o.optUtf(r.targetLabel); o.writeBoolean(r.repeat); o.writeBoolean(r.tdma)
+ o.writeInt((b.time - r.time).toInt())
+ }
+ }
+ return byteArrayOf(BATCH.toByte()) + body.toByteArray()
+ }
+
+ /** Null for a batch that doesn't parse (a newer version, or damaged). */
+ fun readBatch(bytes: ByteArray): Batch? = runCatching {
+ DataInputStream(InflaterInputStream(ByteArrayInputStream(bytes, 1, bytes.size - 1))).use { i ->
+ val origin = i.readLong(); val seq = i.readInt(); val hops = i.readUnsignedByte(); val time = i.readLong()
+ val lat = i.readDouble(); val lon = i.readDouble()
+ val sightings = List(i.readUnsignedShort()) { i.sighting(time) }
+ val radios = List(i.readUnsignedShort()) {
+ Radio(i.readLong(), i.readShort().toInt(), i.readUTF(), i.readLong(), i.readLong(), i.readUTF(), i.readUnsignedByte(),
+ i.optUtf(), i.readBoolean(), i.readBoolean(), time - i.readInt())
+ }
+ Batch(origin, seq, hops, time, lat, lon, sightings, radios)
+ }
+ }.getOrNull()
+
+ private fun DataOutputStream.sighting(s: Sighting, time: Long) {
+ val a = s.advert
+ writeByte(s.kind)
+ write(macBytes(a.mac))
+ writeByte(a.source.ordinal); writeShort(a.rssi); writeInt((time - a.timestamp).toInt())
+ optUtf(a.name)
+ writeShort(a.manufacturerData.size); a.manufacturerData.forEach { (id, v) -> writeShort(id); bytes(v) }
+ writeShort(a.serviceUuids.size); a.serviceUuids.forEach { uuid(it) }
+ writeShort(a.serviceData.size); a.serviceData.forEach { (u, v) -> uuid(u); bytes(v) }
+ writeBoolean(a.rawBytes != null); a.rawBytes?.let { bytes(it) }
+ writeBoolean(a.txPower != null); a.txPower?.let { writeShort(it) }
+ writeByte(a.addressType.ordinal)
+ writeByte(when (a.connectable) { null -> 2; true -> 1; false -> 0 })
+ optUtf(a.phy)
+ val w = a.wifi
+ writeBoolean(w != null)
+ if (w != null) {
+ writeInt(w.frequencyMhz); writeUTF(w.capabilities); optUtf(w.standard)
+ writeShort(w.infoElements.size); w.infoElements.forEach { (id, v) -> writeByte(id); bytes(v) }
+ writeBoolean(w.client); writeBoolean(w.wildcardProbe); writeBoolean(w.flockProbeIe)
+ writeBoolean(w.probeSkeleton != null); w.probeSkeleton?.let { writeLong(it) }
+ }
+ writeShort(s.hits.size)
+ s.hits.forEach { h -> writeUTF(h.category.name); writeUTF(h.label); writeByte(h.confidence); writeUTF(h.evidence); writeUTF(h.source) }
+ writeShort(s.probed.size); s.probed.forEach { writeUTF(it) }
+ optUtf(s.fingerprint)
+ writeBoolean(s.hidden)
+ }
+
+ private fun DataInputStream.sighting(time: Long): Sighting {
+ val kind = readUnsignedByte()
+ val mac = ByteArray(6).also { readFully(it) }.joinToString(":") { "%02X".format(it) }
+ val source = Advert.Source.entries[readUnsignedByte()]
+ val rssi = readShort().toInt()
+ val ts = time - readInt()
+ val name = optUtf()
+ val mfr = LinkedHashMap<Int, ByteArray>().apply { repeat(readUnsignedShort()) { put(readUnsignedShort(), bytes()) } }
+ val uuids = List(readUnsignedShort()) { uuid() }
+ val sd = LinkedHashMap<UUID, ByteArray>().apply { repeat(readUnsignedShort()) { put(uuid(), bytes()) } }
+ val raw = if (readBoolean()) bytes() else null
+ val tx = if (readBoolean()) readShort().toInt() else null
+ val addressType = AddressType.entries.getOrElse(readUnsignedByte()) { AddressType.UNKNOWN }
+ val connectable = when (readUnsignedByte()) { 1 -> true; 0 -> false; else -> null }
+ val phy = optUtf()
+ val wifi = if (readBoolean()) {
+ val freq = readInt(); val caps = readUTF(); val std = optUtf()
+ val ies = List(readUnsignedShort()) { readUnsignedByte() to bytes() }
+ val client = readBoolean(); val wildcard = readBoolean(); val flock = readBoolean()
+ val skeleton = if (readBoolean()) readLong() else null
+ Advert.WifiInfo(freq, caps, std, ies, client, wildcard, flock, skeleton)
+ } else null
+ val hits = List(readUnsignedShort()) {
+ val cat = readUTF()
+ Hit(Category.entries.firstOrNull { it.name == cat } ?: Category.CUSTOM, readUTF(), readUnsignedByte(), readUTF(), readUTF())
+ }
+ val probed = List(readUnsignedShort()) { readUTF() }
+ val fingerprint = optUtf()
+ val hidden = readBoolean()
+ return Sighting(kind, Advert(mac, source, rssi, name, mfr, uuids, sd, raw, tx, addressType, connectable, phy, wifi, ts),
+ hits, probed, fingerprint, hidden)
+ }
+
+ // ---- Helpers ----
+
+ private fun macBytes(mac: String): ByteArray {
+ val hex = mac.filter { it.isLetterOrDigit() }.padEnd(12, '0').take(12)
+ return ByteArray(6) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
+ }
+
+ private fun DataOutputStream.bytes(b: ByteArray) { writeShort(b.size); write(b) }
+ private fun DataInputStream.bytes(): ByteArray = ByteArray(readUnsignedShort()).also { readFully(it) }
+ private fun DataOutputStream.optUtf(s: String?) { writeBoolean(s != null); s?.let { writeUTF(it) } }
+ private fun DataInputStream.optUtf(): String? = if (readBoolean()) readUTF() else null
+ private fun DataOutputStream.uuid(u: UUID) { writeLong(u.mostSignificantBits); writeLong(u.leastSignificantBits) }
+ private fun DataInputStream.uuid() = UUID(readLong(), readLong())
+
+ private fun write(block: DataOutputStream.() -> Unit): ByteArray =
+ ByteArrayOutputStream().also { DataOutputStream(it).use(block) }.toByteArray()
+
+ private fun <T> read(b: ByteArray, block: DataInputStream.() -> T): T = DataInputStream(ByteArrayInputStream(b)).use(block)
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkCrypto.kt b/app/src/main/java/com/rfsentinel/app/link/LinkCrypto.kt
new file mode 100644
index 0000000..c8519fc
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkCrypto.kt
@@ -0,0 +1,122 @@
+package com.rfsentinel.app.link
+
+import java.nio.ByteBuffer
+import java.security.KeyFactory
+import java.security.KeyPair
+import java.security.KeyPairGenerator
+import java.security.PublicKey
+import java.security.SecureRandom
+import java.security.spec.ECGenParameterSpec
+import java.security.spec.X509EncodedKeySpec
+import javax.crypto.Cipher
+import javax.crypto.KeyAgreement
+import javax.crypto.Mac
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Sentinel Link's cryptography, plain JVM so it's unit-tested.
+ *
+ * - Linking two phones: ephemeral P-256 ECDH; both screens show a 6-digit code derived from the exchange
+ * (numeric comparison: a phone in the middle would make the codes differ). Confirmed, the host hands
+ * over the group key, sealed with a key from the exchange.
+ * - Linked phones: every connection proves the group key both ways (fresh nonces, HMAC) and derives its own
+ * pair of AES-256-GCM keys, one per direction, with a counter as nonce (replays are refused).
+ * - Adverts carry only tags that change every 15 minutes and mean something only with the group key.
+ */
+object LinkCrypto {
+ private val rng = SecureRandom()
+
+ const val KEY_BYTES = 32
+ const val NONCE_BYTES = 16
+ /** How long one advert tag lasts. */
+ const val SLOT_MS = 15 * 60_000L
+
+ fun random(n: Int) = ByteArray(n).also { rng.nextBytes(it) }
+
+ fun randomId(): Long {
+ var id = 0L
+ while (id == 0L) id = rng.nextLong()
+ return id
+ }
+
+ fun hmac(key: ByteArray, vararg parts: ByteArray): ByteArray {
+ val mac = Mac.getInstance("HmacSHA256")
+ mac.init(SecretKeySpec(key, "HmacSHA256"))
+ parts.forEach { mac.update(it) }
+ return mac.doFinal()
+ }
+
+ /** RFC 5869 HKDF-SHA256. */
+ fun hkdf(ikm: ByteArray, salt: ByteArray, info: String, length: Int = KEY_BYTES): ByteArray {
+ val prk = hmac(if (salt.isEmpty()) ByteArray(32) else salt, ikm)
+ val out = java.io.ByteArrayOutputStream()
+ var t = ByteArray(0)
+ var i = 1
+ while (out.size() < length) {
+ t = hmac(prk, t, info.toByteArray(), byteArrayOf(i.toByte()))
+ out.write(t)
+ i++
+ }
+ return out.toByteArray().copyOf(length)
+ }
+
+ fun ecKeyPair(): KeyPair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1"), rng) }.generateKeyPair()
+
+ fun publicBytes(kp: KeyPair): ByteArray = kp.public.encoded
+
+ fun publicFrom(bytes: ByteArray): PublicKey = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(bytes))
+
+ fun ecdh(kp: KeyPair, peer: PublicKey): ByteArray =
+ KeyAgreement.getInstance("ECDH").apply { init(kp.private); doPhase(peer, true) }.generateSecret()
+
+ /**
+ * The 6 digits both phones show while linking. [joinerPub]/[hostPub] and the nonces fix the order, so both
+ * sides compute the same code - and an attacker relaying between them can't make the two codes match.
+ */
+ fun code(secret: ByteArray, joinerPub: ByteArray, hostPub: ByteArray, joinerNonce: ByteArray, hostNonce: ByteArray): String {
+ val h = hmac(secret, "rfs-link-code".toByteArray(), joinerPub, hostPub, joinerNonce, hostNonce)
+ val n = ((h[0].toLong() and 0xFF) shl 24 or ((h[1].toLong() and 0xFF) shl 16) or
+ ((h[2].toLong() and 0xFF) shl 8) or (h[3].toLong() and 0xFF)) % 1_000_000L
+ return "%06d".format(n)
+ }
+
+ /** The key that seals the linking messages, one per direction. */
+ fun pairKey(secret: ByteArray, joinerNonce: ByteArray, hostNonce: ByteArray, toHost: Boolean): ByteArray =
+ hkdf(secret, joinerNonce + hostNonce, if (toHost) "rfs-pair-j2h" else "rfs-pair-h2j")
+
+ /** Proof that a phone holds the group key, bound to this connection's nonces. */
+ fun proof(groupKey: ByteArray, role: String, vararg nonces: ByteArray): ByteArray =
+ hmac(groupKey, "rfs-hello-$role".toByteArray(), *nonces).copyOf(16)
+
+ /** A connection's key for one direction ([toServer] = written by the phone that connected). */
+ fun sessionKey(groupKey: ByteArray, clientNonce: ByteArray, serverNonce: ByteArray, toServer: Boolean): ByteArray =
+ hkdf(groupKey, clientNonce + serverNonce, if (toServer) "rfs-c2s" else "rfs-s2c")
+
+ private fun iv(counter: Long) = ByteBuffer.allocate(12).putInt(0x52465331).putLong(counter).array()
+
+ fun seal(key: ByteArray, counter: Long, plain: ByteArray): ByteArray =
+ Cipher.getInstance("AES/GCM/NoPadding").run {
+ init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv(counter)))
+ doFinal(plain)
+ }
+
+ /** Null when the data was altered or sealed with another key / counter. */
+ fun open(key: ByteArray, counter: Long, sealed: ByteArray): ByteArray? = runCatching {
+ Cipher.getInstance("AES/GCM/NoPadding").run {
+ init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv(counter)))
+ doFinal(sealed)
+ }
+ }.getOrNull()
+
+ fun slot(now: Long) = now / SLOT_MS
+
+ private fun long(v: Long) = ByteBuffer.allocate(8).putLong(v).array()
+
+ /** Says "one of ours" in an advert; changes every [SLOT_MS]. */
+ fun groupTag(groupKey: ByteArray, slot: Long): ByteArray = hmac(groupKey, "g".toByteArray(), long(slot)).copyOf(4)
+
+ /** Says which phone, to phones of the group only; changes every [SLOT_MS]. */
+ fun nodeTag(groupKey: ByteArray, slot: Long, nodeId: Long): ByteArray =
+ hmac(groupKey, "n".toByteArray(), long(slot), long(nodeId)).copyOf(4)
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkFrames.kt b/app/src/main/java/com/rfsentinel/app/link/LinkFrames.kt
new file mode 100644
index 0000000..8e1e65e
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkFrames.kt
@@ -0,0 +1,46 @@
+package com.rfsentinel.app.link
+
+import java.io.ByteArrayOutputStream
+import java.nio.ByteBuffer
+
+/**
+ * Messages over a Bluetooth GATT link: the link carries a byte stream in pieces of up to MTU - 3 bytes,
+ * so every message goes as a 4-byte length and then its bytes, and the other side puts them back together.
+ */
+object LinkFrames {
+ /** Far above any real batch: a bigger length means a broken stream. */
+ const val MAX_FRAME = 512 * 1024
+
+ fun frame(payload: ByteArray): ByteArray = ByteBuffer.allocate(4 + payload.size).putInt(payload.size).put(payload).array()
+
+ /** [frame] cut into pieces for writes / notifications of up to [size] bytes. */
+ fun chunks(frame: ByteArray, size: Int): List<ByteArray> {
+ val n = size.coerceAtLeast(20)
+ return (frame.indices step n).map { frame.copyOfRange(it, minOf(it + n, frame.size)) }
+ }
+
+ /** Puts pieces back into whole messages. */
+ class Reassembler {
+ private val buf = ByteArrayOutputStream()
+
+ /** The messages completed by [chunk]; throws on a stream that can't be valid (the link is then closed). */
+ fun feed(chunk: ByteArray): List<ByteArray> {
+ buf.write(chunk)
+ val out = mutableListOf<ByteArray>()
+ var data = buf.toByteArray()
+ var pos = 0
+ while (data.size - pos >= 4) {
+ val len = ByteBuffer.wrap(data, pos, 4).int
+ require(len in 1..MAX_FRAME) { "bad frame length $len" }
+ if (data.size - pos - 4 < len) break
+ out += data.copyOfRange(pos + 4, pos + 4 + len)
+ pos += 4 + len
+ }
+ if (pos > 0) {
+ data = data.copyOfRange(pos, data.size)
+ buf.reset(); buf.write(data)
+ }
+ return out
+ }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkOutbox.kt b/app/src/main/java/com/rfsentinel/app/link/LinkOutbox.kt
new file mode 100644
index 0000000..96f265c
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkOutbox.kt
@@ -0,0 +1,67 @@
+package com.rfsentinel.app.link
+
+/**
+ * What this Sentinel will send next: devices are heard many times a second, so each one goes out when first heard,
+ * then again only every [REPEAT_MS] or when its signal or matches change - about a second's worth per [drain].
+ */
+class LinkOutbox(private val myId: Long) {
+ private class Sent(val at: Long, val rssi: Int, val hits: Int)
+
+ private val lastSent = HashMap<String, Sent>()
+ private val sightings = LinkedHashMap<String, LinkCodec.Sighting>()
+ private val radios = ArrayList<LinkCodec.Radio>()
+ // Starts at the clock (seconds), so a restarted Sentinel's batches never repeat numbers the others already saw.
+ private var seq = (System.currentTimeMillis() / 1000).toInt()
+
+ @Synchronized
+ fun add(s: LinkCodec.Sighting) {
+ val a = s.advert
+ val key = "${s.kind}|${a.mac}"
+ val hitsKey = s.hits.hashCode() * 31 + s.probed.hashCode()
+ val last = lastSent[key]
+ if (last != null && a.timestamp - last.at < REPEAT_MS && kotlin.math.abs(a.rssi - last.rssi) < RSSI_STEP && last.hits == hitsKey) return
+ lastSent[key] = Sent(a.timestamp, a.rssi, hitsKey)
+ sightings[key] = s // the latest for this device replaces one still waiting
+ if (lastSent.size > MAX_TRACKED) lastSent.entries.removeAll { a.timestamp - it.value.at > REPEAT_MS }
+ }
+
+ @Synchronized
+ fun addRadio(r: LinkCodec.Radio) { if (radios.size < MAX_RADIOS) radios += r }
+
+ /** The batch to send now, or null when nothing new was heard. */
+ @Synchronized
+ fun drain(now: Long, lat: Double, lon: Double): LinkCodec.Batch? {
+ if (sightings.isEmpty() && radios.isEmpty()) return null
+ val list = sightings.values.take(MAX_PER_BATCH)
+ val keys = sightings.keys.take(MAX_PER_BATCH)
+ keys.forEach { sightings.remove(it) }
+ val b = LinkCodec.Batch(myId, ++seq, 0, now, lat, lon, list, radios.toList())
+ radios.clear()
+ return b
+ }
+
+ @Synchronized
+ fun clear() { lastSent.clear(); sightings.clear(); radios.clear() }
+
+ companion object {
+ const val REPEAT_MS = 3_000L
+ const val RSSI_STEP = 8
+ const val MAX_PER_BATCH = 400
+ const val MAX_RADIOS = 50
+ const val MAX_TRACKED = 5_000
+ }
+}
+
+/** Batches already handled (heard straight from their Sentinel or relayed by another), so each is used and passed on once. */
+class SeenBatches(private val capacity: Int = 4_000) {
+ private val seen = object : LinkedHashMap<Pair<Long, Int>, Unit>(capacity, 0.75f, false) {
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Pair<Long, Int>, Unit>?) = size > capacity
+ }
+
+ /** True the first time this batch shows up. */
+ @Synchronized
+ fun first(origin: Long, seq: Int): Boolean = seen.put(origin to seq, Unit) == null
+
+ @Synchronized
+ fun clear() = seen.clear()
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
new file mode 100644
index 0000000..c1895b0
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
@@ -0,0 +1,95 @@
+package com.rfsentinel.app.link
+
+import android.content.Context
+import android.util.Base64
+import androidx.core.content.edit
+import com.rfsentinel.app.util.SecureStore
+
+/**
+ * This phone's Sentinel Link: its own id and name, the group key (Keystore-encrypted, never backed up) and
+ * the Sentinels of the group. Kept out of backups and phone-to-phone transfers: a copied id or key would
+ * make two phones the same Sentinel.
+ */
+object LinkStore {
+ private const val PREFS = "sentinel_link"
+ private const val KEY_NAME = "sentinel_link_key"
+
+ private fun sp(c: Context) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+
+ @Volatile private var cachedKey: ByteArray? = null
+
+ /** This phone's id in every group it joins. */
+ fun myId(c: Context): Long {
+ val sp = sp(c)
+ sp.getLong("node_id", 0L).takeIf { it != 0L }?.let { return it }
+ val id = LinkCrypto.randomId()
+ sp.edit(commit = true) { putLong("node_id", id) }
+ return id
+ }
+
+ /** What the other Sentinels call this phone. */
+ fun myName(c: Context): String = sp(c).getString("name", null) ?: android.os.Build.MODEL.take(40)
+ fun setMyName(c: Context, name: String) = sp(c).edit { putString("name", name.trim().take(40).ifEmpty { null }) }
+
+ fun me(c: Context) = LinkCodec.Member(myId(c), myName(c))
+
+ /** Sharing on (Sentinel Link screen); a group alone doesn't start the radio. */
+ fun enabled(c: Context) = sp(c).getBoolean("enabled", true)
+ fun setEnabled(c: Context, on: Boolean) = sp(c).edit { putBoolean("enabled", on) }
+
+ fun groupKey(c: Context): ByteArray? {
+ cachedKey?.let { return it }
+ val k = SecureStore.get(c, KEY_NAME)?.let { runCatching { Base64.decode(it, Base64.NO_WRAP) }.getOrNull() }
+ ?.takeIf { it.size == LinkCrypto.KEY_BYTES }
+ cachedKey = k
+ return k
+ }
+
+ fun hasGroup(c: Context) = groupKey(c) != null
+
+ /** A new group with just this phone (the first link-up). */
+ fun createGroup(c: Context): ByteArray {
+ val key = LinkCrypto.random(LinkCrypto.KEY_BYTES)
+ saveGroup(c, key, emptyList())
+ return key
+ }
+
+ /** Joined a group: its key and Sentinels replace any group this phone was in. */
+ fun saveGroup(c: Context, key: ByteArray, members: List<LinkCodec.Member>) {
+ SecureStore.put(c, KEY_NAME, Base64.encodeToString(key, Base64.NO_WRAP))
+ cachedKey = key
+ sp(c).edit { remove("members") }
+ addMembers(c, members)
+ }
+
+ /** Leaves the group: forgets the key and the Sentinels. */
+ fun leave(c: Context) {
+ SecureStore.put(c, KEY_NAME, null)
+ cachedKey = null
+ sp(c).edit { remove("members") }
+ }
+
+ /** The other Sentinels of the group (not this phone). */
+ fun members(c: Context): List<LinkCodec.Member> {
+ val me = myId(c)
+ return sp(c).getString("members", null).orEmpty().lines().mapNotNull { line ->
+ val cut = line.indexOf('|')
+ if (cut <= 0) null else line.substring(0, cut).toLongOrNull()?.let { LinkCodec.Member(it, line.substring(cut + 1)) }
+ }.filter { it.id != me }
+ }
+
+ /** Adds Sentinels (or updates their names); true when something changed. */
+ @Synchronized
+ fun addMembers(c: Context, list: List<LinkCodec.Member>): Boolean {
+ val me = myId(c)
+ val now = members(c).associateBy { it.id }.toMutableMap()
+ var changed = false
+ for (m in list) {
+ if (m.id == me || m.id == 0L) continue
+ val name = m.name.replace('\n', ' ').replace('|', ' ').trim().take(40).ifEmpty { "Sentinel" }
+ if (now[m.id]?.name != name) { now[m.id] = LinkCodec.Member(m.id, name); changed = true }
+ }
+ if (changed) sp(c).edit { putString("members", now.values.joinToString("\n") { "${it.id}|${it.name}" }) }
+ return changed
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
new file mode 100644
index 0000000..073618f
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
@@ -0,0 +1,969 @@
+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.BluetoothGattServer
+import android.bluetooth.BluetoothGattServerCallback
+import android.bluetooth.BluetoothGattService
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothStatusCodes
+import android.bluetooth.le.AdvertiseCallback
+import android.bluetooth.le.AdvertiseData
+import android.bluetooth.le.AdvertiseSettings
+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.SystemClock
+import android.util.Log
+import com.rfsentinel.app.util.Permissions
+import java.security.KeyPair
+import java.security.MessageDigest
+import java.util.UUID
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.CopyOnWriteArraySet
+
+/**
+ * Sentinel Link: RF Sentinel phones near each other share what they hear over Bluetooth LE, so every
+ * linked phone shows the same devices, radar and map, whichever phone (or its ESP32 board, USB adapter,
+ * SDR) heard a device first.
+ *
+ * No Android pairing: each phone runs a small GATT server and connects to the others as a client. Phones
+ * find each other by an advert that only phones of the group can read ([LinkCrypto.groupTag]); everything
+ * on a link is end-to-end encrypted with keys from the group key ([LinkCrypto]). A new phone joins by a
+ * 6-digit code shown on both screens (see [host] / [join]).
+ *
+ * All state lives on the "rf-link" thread.
+ */
+@SuppressLint("MissingPermission") // every entry point checks canUse()
+object PhoneLink {
+ private const val TAG = "PhoneLink"
+
+ val SERVICE: UUID = UUID.fromString("7c2f5a10-3b6e-4d1a-9f0e-52a1c0d3b7e1")
+ /** Written by the phone that connected. */
+ private val RX: UUID = UUID.fromString("7c2f5a11-3b6e-4d1a-9f0e-52a1c0d3b7e1")
+ /** Notified to the phone that connected. */
+ private val TX: UUID = UUID.fromString("7c2f5a12-3b6e-4d1a-9f0e-52a1c0d3b7e1")
+ private val CCCD: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
+
+ /** Manufacturer id of the link adverts (reserved for tests: no real maker uses it). */
+ const val COMPANY = 0xFFFF
+ private const val AD_MEMBER = 0xA1
+ private const val AD_PAIR = 0xA2
+
+ private const val MTU = 517
+ private const val MTU_FALLBACK_MS = 2_500L
+ private const val SETUP_TIMEOUT_MS = 25_000L
+ private const val IDLE_TIMEOUT_MS = 60_000L
+ private const val KEEPALIVE_MS = 20_000L
+ private const val SEND_STUCK_MS = 15_000L
+ private const val RETRY_MS = 30_000L
+ /** A Sentinel with a lower id connects to us; after this long without a link we connect ourselves. */
+ private const val WAIT_FOR_LOWER_MS = 45_000L
+ private const val MAX_LINKS = 6
+ /** More waiting than this and the link is too slow: new batches skip it rather than pile up. */
+ private const val MAX_QUEUED_BYTES = 256 * 1024
+ private const val PAIR_TIMEOUT_MS = 3 * 60_000L
+ private const val PAIR_PICK_MS = 2_500L
+ private const val ADVERT_RECHECK_MS = 5_000L
+ private const val TICK_MS = 5_000L
+
+ private val thread = HandlerThread("rf-link").apply { start() }
+ private val h = Handler(thread.looper)
+ private val main = Handler(Looper.getMainLooper())
+
+ private var ctx: Context? = null
+ private var sharing = false
+ private var groupKey: ByteArray? = null
+ private var myId = 0L
+ private var names: Map<Long, String> = emptyMap()
+
+ private var server: BluetoothGattServer? = null
+ private var txChar: BluetoothGattCharacteristic? = null
+ private var serverReady = false
+ private val serverMtu = HashMap<String, Int>()
+
+ private var advertised: String? = null
+ private var advertCallback: AdvertiseCallback? = null
+ private var pairTag = ByteArray(0)
+
+ private val links = ArrayList<Link>()
+ private val seen = SeenBatches()
+ private val lastTry = HashMap<String, Long>()
+ private val waitingSince = HashMap<Long, Long>()
+ private val lastAdvert = ConcurrentHashMap<String, Long>()
+ private var tagSlot = Long.MIN_VALUE
+ private var groupTags: List<Pair<Long, ByteArray>> = emptyList()
+ private var problem: String? = null
+ private var ticking = false
+
+ private var pairing: Pairing? = null
+
+ /** The status line ("" while Sentinel Link isn't running). */
+ @Volatile var status: String = ""
+ private set
+
+ /** A Sentinel this phone is linked to now. */
+ data class Peer(val id: Long, val name: String, val since: Long)
+
+ @Volatile var linked: List<Peer> = emptyList()
+ private set
+
+ /** When each Sentinel was last heard from (directly or relayed), wall clock. */
+ val lastHeard = ConcurrentHashMap<Long, Long>()
+
+ private val listeners = CopyOnWriteArraySet<() -> Unit>()
+ fun addListener(l: () -> Unit) { listeners += l }
+ fun removeListener(l: () -> Unit) { listeners -= l }
+ private fun changed() = main.post { listeners.forEach { it() } }
+
+ /** What another Sentinel heard ([LinkCodec.Batch]) and that Sentinel's name; called on the link thread. */
+ @Volatile private var onBatch: ((LinkCodec.Batch, String) -> Unit)? = null
+
+ fun canUse(context: Context) = Build.VERSION.SDK_INT < 31 ||
+ (Permissions.granted(context, android.Manifest.permission.BLUETOOTH_CONNECT) &&
+ Permissions.granted(context, android.Manifest.permission.BLUETOOTH_ADVERTISE))
+
+ fun nameOf(id: Long): String = names[id] ?: "Sentinel"
+
+ // ---------------------------------------------------------------- sharing (the scan service)
+
+ /** Starts sharing with the group (scanning started with a group and sharing on). */
+ fun start(context: Context, batches: (LinkCodec.Batch, String) -> Unit) {
+ h.post {
+ ctx = context.applicationContext
+ onBatch = batches
+ if (sharing) return@post
+ sharing = true
+ loadGroup()
+ ensureServer()
+ refreshAdvert()
+ startTicking()
+ updateStatus()
+ }
+ }
+
+ fun stop() = h.post {
+ if (!sharing) return@post
+ sharing = false
+ onBatch = null
+ links.filter { !it.pairing }.forEach { close(it) }
+ refreshAdvert()
+ maybeStopServer()
+ updateStatus()
+ }
+
+ /** The group was joined, left or replaced: links of the old group end. */
+ fun groupChanged() = h.post {
+ links.filter { !it.pairing }.forEach { close(it) }
+ seen.clear(); waitingSince.clear(); lastTry.clear()
+ loadGroup()
+ refreshAdvert()
+ if (sharing && groupKey == null) { sharing = false; maybeStopServer() }
+ updateStatus()
+ }
+
+ /** The names changed (this phone renamed): tell the linked Sentinels. */
+ fun meChanged() = h.post { loadGroup(); links.filter { it.ready }.forEach { sendInfo(it) } }
+
+ /** What this phone heard in the last second, to every linked Sentinel. */
+ fun send(b: LinkCodec.Batch) = h.post {
+ if (!sharing) return@post
+ seen.first(b.origin, b.seq)
+ val bytes = LinkCodec.batch(b)
+ links.filter { it.ready }.forEach { if (it.queuedBytes < MAX_QUEUED_BYTES) sendSealed(it, bytes) }
+ }
+
+ /**
+ * A scan result from the scan service: true for a Sentinel Link advert (handled here, not a device to list).
+ * Called on the scan's thread.
+ */
+ fun onScanResult(r: ScanResult): Boolean {
+ val d = r.scanRecord?.getManufacturerSpecificData(COMPANY) ?: return false
+ val type = d.firstOrNull()?.toInt()?.and(0xFF) ?: return false
+ if (!(type == AD_MEMBER && d.size == 9) && !(type == AD_PAIR && d.size == 5)) return false
+ if (type == AD_MEMBER) {
+ val addr = r.device.address
+ val now = SystemClock.elapsedRealtime()
+ val last = lastAdvert[addr]
+ if (last == null || now - last >= ADVERT_RECHECK_MS) {
+ lastAdvert[addr] = now
+ if (lastAdvert.size > 500) lastAdvert.entries.removeAll { now - it.value > 60_000L }
+ h.post { onMemberAdvert(r.device, d) }
+ }
+ }
+ return true
+ }
+
+ private fun loadGroup() {
+ val c = ctx ?: return
+ groupKey = LinkStore.groupKey(c)
+ myId = LinkStore.myId(c)
+ names = LinkStore.members(c).associate { it.id to it.name }
+ tagSlot = Long.MIN_VALUE
+ }
+
+ private fun startTicking() {
+ if (ticking) return
+ ticking = true
+ h.postDelayed(::tick, TICK_MS)
+ }
+
+ private fun tick() {
+ val now = SystemClock.elapsedRealtime()
+ for (l in links.toList()) {
+ when {
+ !l.ready && !l.pairing && now - l.createdAt > SETUP_TIMEOUT_MS -> close(l)
+ now - l.lastRx > IDLE_TIMEOUT_MS && !l.pairing -> close(l)
+ l.busy && now - l.busySince > SEND_STUCK_MS -> close(l)
+ l.ready && now - l.lastTx > KEEPALIVE_MS -> sendInfo(l)
+ }
+ }
+ // Bluetooth turned on or "Nearby devices" allowed since: start now.
+ if (sharing && server == null) { ensureServer(); updateStatus() }
+ refreshAdvert()
+ if (sharing || pairing != null || links.isNotEmpty()) h.postDelayed(::tick, TICK_MS) else ticking = false
+ }
+
+ private fun updateStatus() {
+ val peers = links.filter { it.ready }.mapNotNull { l -> l.peer?.let { Peer(it.id, it.name, l.readyAt) } }
+ .groupBy { it.id }.map { (_, v) -> v.minBy { it.since } }
+ linked = peers
+ val n = peers.size
+ status = when {
+ !sharing -> ""
+ problem != null -> "Sentinel Link: $problem"
+ n == 0 -> "Sentinel Link · waiting for Sentinels"
+ else -> "Sentinel Link · $n Sentinel${if (n == 1) "" else "s"} linked"
+ }
+ changed()
+ }
+
+ private fun adapter() = ctx?.getSystemService(BluetoothManager::class.java)?.adapter
+
+ // ---------------------------------------------------------------- GATT server
+
+ private fun ensureServer() {
+ val c = ctx ?: return
+ if (server != null) return
+ if (!canUse(c)) { problem = "allow \"Nearby devices\" to link Sentinels"; return }
+ val adapter = adapter()
+ if (adapter == null || !adapter.isEnabled) { problem = "Bluetooth is off"; return }
+ problem = null
+ val s = runCatching { c.getSystemService(BluetoothManager::class.java)?.openGattServer(c, serverCallback) }.getOrNull()
+ if (s == null) { problem = "Bluetooth link failed to start"; return }
+ val svc = BluetoothGattService(SERVICE, BluetoothGattService.SERVICE_TYPE_PRIMARY)
+ val rx = BluetoothGattCharacteristic(RX, BluetoothGattCharacteristic.PROPERTY_WRITE, BluetoothGattCharacteristic.PERMISSION_WRITE)
+ val tx = BluetoothGattCharacteristic(TX, BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ)
+ tx.addDescriptor(BluetoothGattDescriptor(CCCD, BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE))
+ svc.addCharacteristic(rx); svc.addCharacteristic(tx)
+ server = s
+ txChar = tx
+ serverReady = false
+ if (!s.addService(svc)) { problem = "Bluetooth link failed to start"; s.close(); server = null }
+ }
+
+ private fun maybeStopServer() {
+ if (sharing || pairing != null) return
+ links.toList().forEach { close(it) }
+ stopAdvert()
+ runCatching { server?.close() }
+ server = null; txChar = null; serverReady = false
+ serverMtu.clear()
+ }
+
+ private fun serverLink(device: BluetoothDevice, create: Boolean): ServerLink? {
+ links.firstOrNull { it is ServerLink && it.address == device.address }?.let { return it as ServerLink }
+ if (!create || server == null) return null
+ if (links.size >= MAX_LINKS + 2) return null
+ return ServerLink(device).also { l ->
+ serverMtu[device.address]?.let { l.payload = it - 3 }
+ links += l
+ }
+ }
+
+ private val serverCallback = object : BluetoothGattServerCallback() {
+ override fun onServiceAdded(status: Int, service: BluetoothGattService) {
+ h.post {
+ serverReady = status == BluetoothGatt.GATT_SUCCESS
+ if (!serverReady) problem = "Bluetooth link failed to start"
+ refreshAdvert(); updateStatus()
+ }
+ }
+
+ override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
+ if (newState == BluetoothProfile.STATE_DISCONNECTED) h.post {
+ serverMtu.remove(device.address)
+ serverLink(device, false)?.let { close(it, cancel = false) }
+ }
+ }
+
+ override fun onMtuChanged(device: BluetoothDevice, mtu: Int) {
+ h.post {
+ serverMtu[device.address] = mtu
+ serverLink(device, false)?.payload = mtu - 3
+ }
+ }
+
+ override fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor,
+ preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray?) {
+ val ok = descriptor.uuid == CCCD && !preparedWrite
+ if (ok) h.post {
+ val l = serverLink(device, true) ?: return@post
+ l.open = value?.firstOrNull()?.toInt() == 1
+ pump(l)
+ }
+ if (responseNeeded) runCatching {
+ server?.sendResponse(device, requestId, if (ok) BluetoothGatt.GATT_SUCCESS else BluetoothGatt.GATT_FAILURE, offset, value)
+ }
+ }
+
+ override fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) {
+ runCatching { server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, byteArrayOf(0, 0)) }
+ }
+
+ override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, characteristic: BluetoothGattCharacteristic) {
+ runCatching { server?.sendResponse(device, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null) }
+ }
+
+ override fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, characteristic: BluetoothGattCharacteristic,
+ preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray?) {
+ val ok = characteristic.uuid == RX && !preparedWrite && offset == 0 && value != null
+ // Queued before answering: the next piece is only written after the answer, so pieces stay in order.
+ if (ok) h.post { serverLink(device, true)?.let { onData(it, value!!) } }
+ if (responseNeeded) runCatching {
+ server?.sendResponse(device, requestId, if (ok) BluetoothGatt.GATT_SUCCESS else BluetoothGatt.GATT_FAILURE, 0, null)
+ }
+ }
+
+ override fun onNotificationSent(device: BluetoothDevice, status: Int) {
+ h.post { serverLink(device, false)?.let { onSent(it) } }
+ }
+ }
+
+ // ---------------------------------------------------------------- adverts
+
+ private fun refreshAdvert() {
+ val gk = groupKey
+ val now = System.currentTimeMillis()
+ val want: Pair<String, ByteArray>? = when {
+ server == null || !serverReady -> null
+ pairing?.host == true -> "pair" to (byteArrayOf(AD_PAIR.toByte()) + pairTag)
+ sharing && gk != null -> {
+ val slot = LinkCrypto.slot(now)
+ "member $slot" to (byteArrayOf(AD_MEMBER.toByte()) + LinkCrypto.groupTag(gk, slot) + LinkCrypto.nodeTag(gk, slot, myId))
+ }
+ else -> null
+ }
+ if (want?.first == advertised) return
+ stopAdvert()
+ if (want == null) return
+ val advertiser = runCatching { adapter()?.bluetoothLeAdvertiser }.getOrNull() ?: return
+ val settings = AdvertiseSettings.Builder()
+ .setAdvertiseMode(if (pairing?.host == true) AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY else AdvertiseSettings.ADVERTISE_MODE_BALANCED)
+ .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
+ .setConnectable(true)
+ .setTimeout(0)
+ .build()
+ // No name, no services: only the tag, meaningless without the group key.
+ val data = AdvertiseData.Builder().setIncludeDeviceName(false).setIncludeTxPowerLevel(false)
+ .addManufacturerData(COMPANY, want.second).build()
+ val cb = object : AdvertiseCallback() {
+ override fun onStartFailure(errorCode: Int) {
+ h.post {
+ if (advertCallback !== this) return@post
+ Log.w(TAG, "advertising failed: $errorCode")
+ advertised = null; advertCallback = null
+ pairing?.takeIf { it.host }?.let { endPairing(it, "This phone can't advertise over Bluetooth ($errorCode)"); return@post }
+ problem = "this phone can't be found by other Sentinels (advertising failed)"
+ updateStatus()
+ }
+ }
+ override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
+ h.post { if (advertCallback === this && problem?.contains("advertising") == true) { problem = null; updateStatus() } }
+ }
+ }
+ try {
+ advertiser.startAdvertising(settings, data, cb)
+ advertCallback = cb
+ advertised = want.first
+ } catch (e: Exception) {
+ Log.w(TAG, "advertising unavailable", e)
+ }
+ }
+
+ private fun stopAdvert() {
+ val cb = advertCallback ?: return
+ runCatching { adapter()?.bluetoothLeAdvertiser?.stopAdvertising(cb) }
+ advertCallback = null
+ advertised = null
+ }
+
+ /** Which Sentinel of the group sent this advert: (true, id) for a known one, (true, null) for one not met yet. */
+ private fun identify(d: ByteArray): Pair<Boolean, Long?> {
+ val gk = groupKey ?: return false to null
+ val slot = LinkCrypto.slot(System.currentTimeMillis())
+ if (slot != tagSlot) {
+ tagSlot = slot
+ groupTags = (slot - 1..slot + 1).map { it to LinkCrypto.groupTag(gk, it) }
+ }
+ val g = d.copyOfRange(1, 5)
+ val s = groupTags.firstOrNull { it.second.contentEquals(g) }?.first ?: return false to null
+ val n = d.copyOfRange(5, 9)
+ return true to names.keys.firstOrNull { LinkCrypto.nodeTag(gk, s, it).contentEquals(n) }
+ }
+
+ private fun onMemberAdvert(device: BluetoothDevice, d: ByteArray) {
+ if (!sharing || server == null) return
+ val (ours, id) = identify(d)
+ if (!ours || id == myId) return
+ val now = SystemClock.elapsedRealtime()
+ if (id != null && links.any { it.ready && it.peer?.id == id }) { waitingSince.remove(id); return }
+ if (links.any { it.address == device.address }) return
+ if (links.count { !it.pairing } >= MAX_LINKS) return
+ // The lower id connects; wait for it, unless it never does.
+ if (id != null && id < myId) {
+ val since = waitingSince.getOrPut(id) { now }
+ if (now - since < WAIT_FOR_LOWER_MS) return
+ }
+ val last = lastTry[device.address]
+ if (last != null && now - last < RETRY_MS) return
+ lastTry[device.address] = now
+ if (lastTry.size > 200) lastTry.entries.removeAll { now - it.value > RETRY_MS }
+ connect(device, pairing = false)
+ }
+
+ // ---------------------------------------------------------------- links
+
+ private abstract class Link(val address: String) {
+ var pairing = false
+ var open = false
+ var ready = false
+ var readyAt = 0L
+ var closed = false
+ var peer: LinkCodec.Member? = null
+ val reasm = LinkFrames.Reassembler()
+ var payload = 20
+ val queue = ArrayDeque<ByteArray>()
+ var queuedBytes = 0
+ var busy = false
+ var busySince = 0L
+ var closeWhenDrained = false
+ val createdAt = SystemClock.elapsedRealtime()
+ var lastRx = createdAt
+ var lastTx = createdAt
+ // Session.
+ val nonce = LinkCrypto.random(LinkCrypto.NONCE_BYTES)
+ var txKey: ByteArray? = null
+ var rxKey: ByteArray? = null
+ var txCounter = 0L
+ var rxCounter = -1L
+ abstract val isClient: Boolean
+ /** Starts sending one piece; false when the radio can't take it now. */
+ abstract fun write(chunk: ByteArray): Boolean
+ abstract fun disconnect(cancel: Boolean)
+ }
+
+ private class ServerLink(val device: BluetoothDevice) : Link(device.address) {
+ override val isClient = false
+ override fun write(chunk: ByteArray): Boolean {
+ val s = server ?: return false
+ val c = txChar ?: return false
+ return runCatching {
+ if (Build.VERSION.SDK_INT >= 33) s.notifyCharacteristicChanged(device, c, false, chunk) == BluetoothStatusCodes.SUCCESS
+ else {
+ @Suppress("DEPRECATION") c.value = chunk
+ @Suppress("DEPRECATION") s.notifyCharacteristicChanged(device, c, false)
+ }
+ }.getOrDefault(false)
+ }
+ override fun disconnect(cancel: Boolean) {
+ // Not while this phone is also the client on the same connection: that would end both.
+ if (cancel && links.none { it is ClientLink && it.address == address }) runCatching { server?.cancelConnection(device) }
+ }
+ }
+
+ private class ClientLink(val device: BluetoothDevice) : Link(device.address) {
+ override val isClient = true
+ var gatt: BluetoothGatt? = null
+ var rx: BluetoothGattCharacteristic? = null
+ var discovering = false
+ override fun write(chunk: ByteArray): Boolean {
+ val g = gatt ?: return false
+ val c = rx ?: return false
+ return runCatching {
+ if (Build.VERSION.SDK_INT >= 33) g.writeCharacteristic(c, chunk, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) == BluetoothStatusCodes.SUCCESS
+ else {
+ c.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
+ @Suppress("DEPRECATION") c.value = chunk
+ @Suppress("DEPRECATION") g.writeCharacteristic(c)
+ }
+ }.getOrDefault(false)
+ }
+ override fun disconnect(cancel: Boolean) {
+ val g = gatt ?: return
+ gatt = null
+ runCatching { g.disconnect() }
+ runCatching { g.close() }
+ }
+ }
+
+ private fun connect(device: BluetoothDevice, pairing: Boolean): ClientLink? {
+ val c = ctx ?: return null
+ val l = ClientLink(device).also { it.pairing = pairing }
+ val cb = object : BluetoothGattCallback() {
+ override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
+ h.post {
+ if (l.closed || l.gatt !== g) { if (l.gatt !== g) runCatching { g.close() }; return@post }
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (!g.requestMtu(MTU)) discover(l, g)
+ else h.postDelayed({ if (l.gatt === g) discover(l, g) }, MTU_FALLBACK_MS)
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) close(l, cancel = false)
+ }
+ }
+ override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {
+ h.post { if (l.gatt === g) { if (status == BluetoothGatt.GATT_SUCCESS) l.payload = mtu - 3; discover(l, g) } }
+ }
+ override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
+ h.post {
+ if (l.gatt !== g) return@post
+ val svc = g.getService(SERVICE)
+ val rx = svc?.getCharacteristic(RX)
+ val tx = svc?.getCharacteristic(TX)
+ val cccd = tx?.getDescriptor(CCCD)
+ if (rx == null || cccd == null) { close(l); return@post }
+ l.rx = rx
+ g.setCharacteristicNotification(tx, 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) close(l)
+ }
+ }
+ override fun onDescriptorWrite(g: BluetoothGatt, d: BluetoothGattDescriptor, status: Int) {
+ h.post {
+ if (l.gatt !== g) return@post
+ if (status != BluetoothGatt.GATT_SUCCESS) { close(l); return@post }
+ l.open = true
+ onClientOpen(l)
+ }
+ }
+ override fun onCharacteristicWrite(g: BluetoothGatt, c: BluetoothGattCharacteristic, status: Int) {
+ h.post {
+ if (l.gatt !== g) return@post
+ if (status != BluetoothGatt.GATT_SUCCESS) close(l) else onSent(l)
+ }
+ }
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray) {
+ if (c.uuid == TX) h.post { if (l.gatt === g) onData(l, value) }
+ }
+ @Deprecated("Android 12 and older")
+ @Suppress("DEPRECATION")
+ override fun onCharacteristicChanged(g: BluetoothGatt, c: BluetoothGattCharacteristic) {
+ if (Build.VERSION.SDK_INT >= 33 || c.uuid != TX) return
+ val v = c.value?.copyOf() ?: return
+ h.post { if (l.gatt === g) onData(l, v) }
+ }
+ }
+ val g = runCatching { device.connectGatt(c, false, cb, BluetoothDevice.TRANSPORT_LE) }.getOrNull() ?: return null
+ l.gatt = g
+ links += l
+ startTicking()
+ return l
+ }
+
+ private fun discover(l: ClientLink, g: BluetoothGatt) {
+ if (l.discovering) return
+ l.discovering = true
+ if (!g.discoverServices()) close(l)
+ }
+
+ private fun close(l: Link, cancel: Boolean = true) {
+ if (l.closed) return
+ l.closed = true
+ links.remove(l)
+ l.disconnect(cancel)
+ val p = pairing
+ if (p != null && p.link === l && !p.done) endPairing(p, "Lost the other phone")
+ if (l.ready) updateStatus()
+ }
+
+ private fun send(l: Link, payload: ByteArray) {
+ if (l.closed) return
+ LinkFrames.chunks(LinkFrames.frame(payload), l.payload).forEach { l.queue.addLast(it); l.queuedBytes += it.size }
+ pump(l)
+ }
+
+ private fun pump(l: Link) {
+ if (l.busy || !l.open || l.closed) return
+ val next = l.queue.firstOrNull()
+ if (next == null) {
+ if (l.closeWhenDrained) h.postDelayed({ close(l) }, 1_500L)
+ return
+ }
+ if (l.write(next)) {
+ l.queue.removeFirst()
+ l.queuedBytes -= next.size
+ l.busy = true
+ l.busySince = SystemClock.elapsedRealtime()
+ } else {
+ h.postDelayed({ pump(l) }, 100L)
+ }
+ }
+
+ private fun onSent(l: Link) {
+ l.busy = false
+ l.lastTx = SystemClock.elapsedRealtime()
+ pump(l)
+ }
+
+ private fun onData(l: Link, chunk: ByteArray) {
+ if (l.closed) return
+ l.lastRx = SystemClock.elapsedRealtime()
+ val messages = try { l.reasm.feed(chunk) } catch (e: Exception) { close(l); return }
+ for (m in messages) {
+ if (l.closed) return
+ try { handle(l, m) } catch (e: Exception) { Log.w(TAG, "bad message", e); close(l); return }
+ }
+ }
+
+ private fun handle(l: Link, m: ByteArray) {
+ when (m[0].toInt() and 0xFF) {
+ LinkCodec.PAIR_HELLO -> hostPairHello(l, m)
+ LinkCodec.PAIR_REPLY -> joinerPairReply(l, m)
+ LinkCodec.PAIR_CONFIRM -> hostPairConfirm(l, m)
+ LinkCodec.PAIR_GROUP -> joinerPairGroup(l, m)
+ LinkCodec.PAIR_CANCEL -> pairing?.takeIf { it.link === l }?.let { endPairing(it, "The other phone cancelled") } ?: close(l)
+ LinkCodec.HELLO -> serverHello(l, m)
+ LinkCodec.HELLO_REPLY -> clientHelloReply(l, m)
+ LinkCodec.SEALED -> sealedIn(l, m)
+ }
+ }
+
+ // ---------------------------------------------------------------- linked Sentinels
+
+ private fun onClientOpen(l: ClientLink) {
+ if (l.pairing) { joinerOpen(l); return }
+ val gk = groupKey ?: run { close(l); return }
+ send(l, LinkCodec.hello(LinkCodec.HELLO, l.nonce, LinkCrypto.proof(gk, "c", l.nonce)))
+ }
+
+ private fun serverHello(l: Link, m: ByteArray) {
+ val gk = groupKey
+ if (l.isClient || l.txKey != null || gk == null || !sharing) { close(l); return }
+ val (nc, proof) = LinkCodec.readHello(m)
+ if (!MessageDigest.isEqual(proof, LinkCrypto.proof(gk, "c", nc))) { close(l); return }
+ send(l, LinkCodec.hello(LinkCodec.HELLO_REPLY, l.nonce, LinkCrypto.proof(gk, "s", nc, l.nonce)))
+ l.txKey = LinkCrypto.sessionKey(gk, nc, l.nonce, toServer = false)
+ l.rxKey = LinkCrypto.sessionKey(gk, nc, l.nonce, toServer = true)
+ sendInfo(l)
+ }
+
+ private fun clientHelloReply(l: Link, m: ByteArray) {
+ val gk = groupKey
+ if (!l.isClient || l.txKey != null || gk == null) { close(l); return }
+ val (ns, proof) = LinkCodec.readHello(m)
+ if (!MessageDigest.isEqual(proof, LinkCrypto.proof(gk, "s", l.nonce, ns))) { close(l); return }
+ l.txKey = LinkCrypto.sessionKey(gk, l.nonce, ns, toServer = true)
+ l.rxKey = LinkCrypto.sessionKey(gk, l.nonce, ns, toServer = false)
+ sendInfo(l)
+ }
+
+ private fun sendSealed(l: Link, inner: ByteArray) {
+ val key = l.txKey ?: return
+ val c = l.txCounter++
+ send(l, LinkCodec.sealed(c, LinkCrypto.seal(key, c, inner)))
+ }
+
+ private fun sendInfo(l: Link) {
+ val c = ctx ?: return
+ sendSealed(l, LinkCodec.info(LinkStore.me(c), LinkStore.members(c)))
+ l.lastTx = SystemClock.elapsedRealtime()
+ }
+
+ private fun sealedIn(l: Link, m: ByteArray) {
+ val key = l.rxKey ?: run { close(l); return }
+ val (counter, data) = LinkCodec.readSealed(m)
+ if (counter <= l.rxCounter) { close(l); return }
+ val plain = LinkCrypto.open(key, counter, data) ?: run { close(l); return }
+ l.rxCounter = counter
+ when (plain[0].toInt() and 0xFF) {
+ LinkCodec.INFO -> onInfo(l, plain)
+ LinkCodec.BATCH -> onBatchIn(l, plain)
+ }
+ }
+
+ private fun onInfo(l: Link, plain: ByteArray) {
+ val c = ctx ?: return
+ val (them, known) = LinkCodec.readInfo(plain)
+ if (them.id == myId || them.id == 0L) { close(l); return }
+ val renamed = l.peer?.name != them.name
+ l.peer = them
+ lastHeard[them.id] = System.currentTimeMillis()
+ if (LinkStore.addMembers(c, listOf(them) + known)) names = LinkStore.members(c).associate { it.id to it.name }
+ if (!l.ready) {
+ l.ready = true
+ l.readyAt = System.currentTimeMillis()
+ waitingSince.remove(them.id)
+ Log.i(TAG, "linked")
+ keepOneLink(l)
+ updateStatus()
+ } else if (renamed) updateStatus()
+ }
+
+ /**
+ * Two phones that connected to each other at once have two links: both keep the one the lower id opened
+ * (and, between two the same way, the newest), so they agree without talking about it.
+ */
+ private fun keepOneLink(l: Link) {
+ val id = l.peer?.id ?: return
+ val opener = { x: Link -> if (x.isClient) myId else id }
+ val keepId = minOf(myId, id)
+ for (other in links.filter { it !== l && it.ready && it.peer?.id == id }) {
+ val loser = when {
+ opener(other) == keepId && opener(l) != keepId -> l
+ else -> other
+ }
+ close(loser, cancel = false)
+ if (loser === l) return
+ }
+ }
+
+ private fun onBatchIn(l: Link, plain: ByteArray) {
+ val b = LinkCodec.readBatch(plain) ?: return
+ if (b.origin == myId || !seen.first(b.origin, b.seq)) return
+ 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) }
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------- linking a new phone
+
+ /** Tells the Sentinel Link screen how linking goes; called on the main thread. */
+ interface PairListener {
+ fun onStatus(text: String)
+ /** The 6 digits to compare with the other phone. */
+ fun onCode(code: String)
+ fun onLinked(name: String)
+ fun onEnded(message: String)
+ }
+
+ private class Pairing(val host: Boolean, val listener: PairListener) {
+ val kp: KeyPair = LinkCrypto.ecKeyPair()
+ val nonce = LinkCrypto.random(LinkCrypto.NONCE_BYTES)
+ var link: Link? = null
+ var toPeer: ByteArray? = null
+ var fromPeer: ByteArray? = null
+ var confirmed = false
+ var peer: LinkCodec.Member? = null
+ var done = false
+ var scan: ScanCallback? = null
+ val found = HashMap<String, Pair<BluetoothDevice, Int>>()
+ var picking = false
+ }
+
+ private fun tell(p: Pairing, block: PairListener.() -> Unit) = main.post { p.listener.block() }
+
+ /** Lets a new phone join: advertises for it and shows the code once it connects. */
+ fun host(context: Context, listener: PairListener) = h.post {
+ ctx = context.applicationContext
+ pairing?.let { endPairing(it, null) }
+ if (!canUse(context)) { main.post { listener.onEnded("Allow \"Nearby devices\" first") }; return@post }
+ if (adapter()?.isEnabled != true) { main.post { listener.onEnded("Turn Bluetooth on first") }; return@post }
+ if (!LinkStore.hasGroup(context)) { LinkStore.createGroup(context); loadGroup() }
+ val p = Pairing(host = true, listener = listener)
+ pairing = p
+ pairTag = LinkCrypto.random(4)
+ ensureServer()
+ if (server == null) { endPairing(p, problem?.replaceFirstChar { it.uppercase() } ?: "Bluetooth link failed to start"); return@post }
+ refreshAdvert()
+ startTicking()
+ h.postDelayed({ if (pairing === p && !p.done) endPairing(p, "No phone joined in time") }, PAIR_TIMEOUT_MS)
+ tell(p) { onStatus("On the other phone, tap \"Join a Sentinel\"…") }
+ }
+
+ /** Joins the group of a phone that's hosting ("Link up a Sentinel") nearby. */
+ fun join(context: Context, listener: PairListener) = h.post {
+ ctx = context.applicationContext
+ pairing?.let { endPairing(it, null) }
+ if (!canUse(context)) { main.post { listener.onEnded("Allow \"Nearby devices\" first") }; return@post }
+ val scanner = runCatching { adapter()?.takeIf { it.isEnabled }?.bluetoothLeScanner }.getOrNull()
+ if (scanner == null) { main.post { listener.onEnded("Turn Bluetooth on first") }; return@post }
+ val p = Pairing(host = false, listener = listener)
+ pairing = p
+ val cb = object : ScanCallback() {
+ override fun onScanResult(callbackType: Int, r: ScanResult) {
+ val d = r.scanRecord?.getManufacturerSpecificData(COMPANY) ?: return
+ if (d.size == 5 && (d[0].toInt() and 0xFF) == AD_PAIR) h.post { joinerFound(p, r.device, r.rssi) }
+ }
+ override fun onScanFailed(errorCode: Int) { h.post { if (pairing === p) endPairing(p, "Bluetooth search failed ($errorCode)") } }
+ }
+ val filter = ScanFilter.Builder().setManufacturerData(COMPANY, byteArrayOf(AD_PAIR.toByte()), byteArrayOf(0xFF.toByte())).build()
+ val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(0).build()
+ try { scanner.startScan(listOf(filter), settings, cb); p.scan = cb } catch (e: Exception) {
+ endPairing(p, "Bluetooth search failed"); return@post
+ }
+ startTicking()
+ h.postDelayed({ if (pairing === p && !p.done) endPairing(p, "No Sentinel found - tap \"Link up a Sentinel\" on the other phone") }, PAIR_TIMEOUT_MS)
+ tell(p) { onStatus("Looking for the other phone…") }
+ }
+
+ /** This phone's user saw the same code on both screens. */
+ fun confirmCode() = h.post {
+ val p = pairing ?: return@post
+ val l = p.link ?: return@post
+ val key = p.toPeer ?: return@post
+ if (p.confirmed) return@post
+ p.confirmed = true
+ if (p.host) {
+ if (!hostFinish(p)) tell(p) { onStatus("Waiting for the other phone to confirm…") }
+ } else {
+ val c = ctx ?: return@post
+ send(l, byteArrayOf(LinkCodec.PAIR_CONFIRM.toByte()) + LinkCrypto.seal(key, 0, LinkCodec.member(LinkStore.me(c))))
+ tell(p) { onStatus("Waiting for the other phone to confirm…") }
+ }
+ }
+
+ fun cancelPairing() = h.post { pairing?.let { endPairing(it, null) } }
+
+ /** Ends linking: [message] for the screen, or null when this phone's user cancelled. */
+ private fun endPairing(p: Pairing, message: String?) {
+ if (pairing === p) pairing = null
+ val wasDone = p.done
+ p.done = true
+ p.scan?.let { cb -> runCatching { adapter()?.bluetoothLeScanner?.stopScan(cb) } }
+ p.scan = null
+ p.link?.let { l ->
+ if (!l.closed && !wasDone) {
+ send(l, byteArrayOf(LinkCodec.PAIR_CANCEL.toByte()))
+ l.closeWhenDrained = true
+ pump(l)
+ h.postDelayed({ close(l) }, 3_000L)
+ }
+ }
+ refreshAdvert()
+ maybeStopServer()
+ if (!wasDone && message != null) main.post { p.listener.onEnded(message) }
+ }
+
+ private fun joinerFound(p: Pairing, device: BluetoothDevice, rssi: Int) {
+ if (pairing !== p || p.link != null) return
+ p.found[device.address] = device to rssi
+ if (p.picking) return
+ p.picking = true
+ // Gather for a moment, then take the nearest phone that's hosting.
+ h.postDelayed({
+ if (pairing !== p || p.link != null) return@postDelayed
+ p.scan?.let { cb -> runCatching { adapter()?.bluetoothLeScanner?.stopScan(cb) } }
+ p.scan = null
+ val best = p.found.values.maxBy { it.second }.first
+ val l = connect(best, pairing = true)
+ if (l == null) { endPairing(p, "Couldn't connect to the other phone"); return@postDelayed }
+ p.link = l
+ tell(p) { onStatus("Found it - connecting…") }
+ }, PAIR_PICK_MS)
+ }
+
+ private fun joinerOpen(l: ClientLink) {
+ val p = pairing?.takeIf { it.link === l && !it.host } ?: run { close(l); return }
+ send(l, LinkCodec.pairHello(LinkCodec.PAIR_HELLO, LinkCrypto.publicBytes(p.kp), p.nonce))
+ }
+
+ private fun hostPairHello(l: Link, m: ByteArray) {
+ val p = pairing
+ if (l.isClient || p == null || !p.host || p.link != null) {
+ send(l, byteArrayOf(LinkCodec.PAIR_CANCEL.toByte())); l.closeWhenDrained = true; pump(l); return
+ }
+ l.pairing = true
+ p.link = l
+ val (theirPub, theirNonce) = LinkCodec.readPairHello(m)
+ val myPub = LinkCrypto.publicBytes(p.kp)
+ val secret = LinkCrypto.ecdh(p.kp, LinkCrypto.publicFrom(theirPub))
+ p.toPeer = LinkCrypto.pairKey(secret, theirNonce, p.nonce, toHost = false)
+ p.fromPeer = LinkCrypto.pairKey(secret, theirNonce, p.nonce, toHost = true)
+ send(l, LinkCodec.pairHello(LinkCodec.PAIR_REPLY, myPub, p.nonce))
+ val code = LinkCrypto.code(secret, theirPub, myPub, theirNonce, p.nonce)
+ tell(p) { onCode(code) }
+ }
+
+ private fun joinerPairReply(l: Link, m: ByteArray) {
+ val p = pairing?.takeIf { it.link === l && !it.host } ?: run { close(l); return }
+ if (p.toPeer != null) { close(l); return }
+ val (theirPub, theirNonce) = LinkCodec.readPairHello(m)
+ val myPub = LinkCrypto.publicBytes(p.kp)
+ val secret = LinkCrypto.ecdh(p.kp, LinkCrypto.publicFrom(theirPub))
+ p.toPeer = LinkCrypto.pairKey(secret, p.nonce, theirNonce, toHost = true)
+ p.fromPeer = LinkCrypto.pairKey(secret, p.nonce, theirNonce, toHost = false)
+ val code = LinkCrypto.code(secret, myPub, theirPub, p.nonce, theirNonce)
+ tell(p) { onCode(code) }
+ }
+
+ private fun hostPairConfirm(l: Link, m: ByteArray) {
+ val p = pairing?.takeIf { it.link === l && it.host } ?: run { close(l); return }
+ val key = p.fromPeer ?: run { close(l); return }
+ val plain = LinkCrypto.open(key, 0, m.copyOfRange(1, m.size)) ?: run { endPairing(p, "The codes didn't match"); return }
+ p.peer = LinkCodec.readMember(plain)
+ if (!hostFinish(p)) tell(p) { onStatus("The other phone confirmed - check the code and tap Confirm") }
+ }
+
+ /** Both users confirmed: the new phone gets the group. */
+ private fun hostFinish(p: Pairing): Boolean {
+ val c = ctx ?: return false
+ val l = p.link ?: return false
+ val peer = p.peer ?: return false
+ val key = p.toPeer ?: return false
+ if (!p.confirmed) return false
+ val gk = groupKey ?: LinkStore.groupKey(c) ?: return false
+ LinkStore.addMembers(c, listOf(peer))
+ names = LinkStore.members(c).associate { it.id to it.name }
+ val members = listOf(LinkStore.me(c)) + LinkStore.members(c)
+ send(l, byteArrayOf(LinkCodec.PAIR_GROUP.toByte()) + LinkCrypto.seal(key, 0, LinkCodec.group(gk, members)))
+ l.closeWhenDrained = true
+ pump(l)
+ p.done = true
+ pairing = null
+ refreshAdvert()
+ main.post { p.listener.onLinked(peer.name) }
+ // Linked Sentinels learn about the new one.
+ links.filter { it.ready }.forEach { sendInfo(it) }
+ h.postDelayed({ maybeStopServer() }, 5_000L)
+ return true
+ }
+
+ private fun joinerPairGroup(l: Link, m: ByteArray) {
+ val c = ctx ?: return
+ val p = pairing?.takeIf { it.link === l && !it.host && it.confirmed } ?: run { close(l); return }
+ val key = p.fromPeer ?: run { close(l); return }
+ val plain = LinkCrypto.open(key, 0, m.copyOfRange(1, m.size)) ?: run { endPairing(p, "The codes didn't match"); return }
+ val (gk, members) = LinkCodec.readGroup(plain)
+ if (gk.size != LinkCrypto.KEY_BYTES) { endPairing(p, "The other phone sent a bad answer"); return }
+ LinkStore.saveGroup(c, gk, members)
+ p.done = true
+ pairing = null
+ close(l)
+ main.post { p.listener.onLinked(members.firstOrNull()?.name ?: "Sentinel") }
+ groupChanged()
+ h.post { maybeStopServer() }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
index aa24398..e0e7b73 100644
--- a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
@@ -153,6 +153,9 @@ class BleScanEngine(
val heyCyan = ParcelUuid.fromString("7905fff0-b5ce-4e99-a40f-4b1e122d00d0")
out += ScanFilter.Builder().setServiceUuid(heyCyan).build()
out += ScanFilter.Builder().setServiceData(heyCyan, ByteArray(0)).build()
+ // Linked Sentinels (Sentinel Link), so phones keep finding each other with the screen off.
+ out += ScanFilter.Builder().setManufacturerData(com.rfsentinel.app.link.PhoneLink.COMPANY,
+ byteArrayOf(0xA1.toByte()), byteArrayOf(0xFF.toByte())).build()
// Controllers offload a limited number of filters; keep the total around 40.
watchedMacs.take(8).forEach { mac ->
runCatching { out += ScanFilter.Builder().setDeviceAddress(mac).build() }
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 ebd55a3..037b00c 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -41,6 +41,8 @@ import com.rfsentinel.app.detect.Hit
import com.rfsentinel.app.detect.RemoteId
import com.rfsentinel.app.detect.SignatureEngine
import com.rfsentinel.app.detect.VendorDb
+import com.rfsentinel.app.link.LinkCodec
+import com.rfsentinel.app.link.LinkOutbox
import com.rfsentinel.app.oui.OuiWatchlist
import com.rfsentinel.app.ui.StatusWidget
import com.rfsentinel.app.util.AlertPlayer
@@ -77,6 +79,8 @@ class ScanForegroundService : Service() {
const val ACTION_STOP = "com.rfsentinel.app.action.STOP"
/** Re-evaluates location updates, e.g. after trace recording starts or stops. */
const val ACTION_REFRESH_LOCATION = "com.rfsentinel.app.action.REFRESH_LOCATION"
+ /** Re-applies Sentinel Link (joined, left, sharing switched) to a running scan. */
+ const val ACTION_REFRESH_LINK = "com.rfsentinel.app.action.REFRESH_LINK"
/** Android downgrades an unfiltered BLE scan to opportunistic after ~30 min; restart before. */
private const val BLE_RESTART_INTERVAL_MS = 25 * 60 * 1000L
@@ -103,6 +107,10 @@ class ScanForegroundService : Service() {
private const val CELL_REPEAT_MS = 30 * 60_000L
private const val PLACING_MAX_AGE_MS = 30_000L
private const val ESP_HIT_TTL_MS = 5 * 60_000L
+ /** Sentinel Link: what this phone gathers goes out about this often. */
+ 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
/** 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
@@ -157,6 +165,12 @@ class ScanForegroundService : Service() {
fun stop(context: Context) {
context.stopService(Intent(context, ScanForegroundService::class.java))
}
+
+ /** Sentinel Link changed: a running scan starts or stops linking (never starts a scan). */
+ fun refreshLink(context: Context) {
+ if (!isRunning) return
+ runCatching { context.startService(Intent(context, ScanForegroundService::class.java).setAction(ACTION_REFRESH_LINK)) }
+ }
}
private class Classified(val time: Long, val hits: List<Hit>, val identity: DeviceIntel.Identity, val vendor: String?)
@@ -279,6 +293,8 @@ class ScanForegroundService : Service() {
lastBleResultAt = t
bleResults.incrementAndGet()
bleWatchdogRestartAt?.let { onRecovered("Bluetooth", it, t); bleWatchdogRestartAt = null; bleSilenceMs = BLE_SILENCE_MS }
+ // Another Sentinel's link advert: handled by Sentinel Link, not a device to list.
+ if (com.rfsentinel.app.link.PhoneLink.onScanResult(r)) return@BleScanEngine
pipeline.post { AdvertFactory.fromBle(r)?.let(::processPhone) }
}
wifiEngine = WifiScanEngine(this) { results ->
@@ -304,6 +320,11 @@ class ScanForegroundService : Service() {
updateLocationUpdates()
return START_STICKY
}
+ if (intent?.action == ACTION_REFRESH_LINK) {
+ if (!isRunning) { stopSelf(); return START_NOT_STICKY }
+ updateLink()
+ return START_STICKY
+ }
if (!enterForeground()) {
stopSelf()
return START_NOT_STICKY
@@ -362,6 +383,7 @@ class ScanForegroundService : Service() {
Prefs.ouiSpyBoard(this)?.let { addr ->
com.rfsentinel.app.esp.OuiSpyBle.start(this, addr, Prefs.ouiSpyRelayAll(this)) { list -> pipeline.post { list.forEach(::processEsp) } }
} ?: com.rfsentinel.app.esp.OuiSpyBle.stop()
+ updateLink()
updateLocationUpdates()
startHousekeeping()
startCellChecks()
@@ -583,10 +605,16 @@ class ScanForegroundService : Service() {
/** Something the phone's own Bluetooth or Wi-Fi chip heard. */
private fun processPhone(a: Advert) {
com.rfsentinel.app.esp.HeardBy.phone.mark(a.mac)
+ linkOutbox?.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, a))
process(a)
}
- private fun process(a: Advert, reportedRemoteId: RemoteId.Info? = null, broadcast: DeviceRegistry.GeoSample? = null) {
+ /**
+ * @param via the linked Sentinel that heard it (Sentinel Link), with [peerAt] where that Sentinel was;
+ * 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) {
val now = a.timestamp
val mac = a.mac
if (OuiWatchlist.version != watchlistVersion) recheckWatchlist(now)
@@ -615,8 +643,9 @@ class ScanForegroundService : Service() {
// Place devices only with a fresh, precise fix: a stale or WiFi/cell-based one
// (often 100 m+ off) would put the dot far from where the device really was.
- val loc = lastLocation?.takeIf { usableForPlacing(it) }
- val geo = loc?.let { placeNow(it, now) }
+ val loc = if (via != null) peerAt else lastLocation?.takeIf { usableForPlacing(it) }
+ // Heard by another Sentinel: placed where that Sentinel was.
+ 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) }
if (TripRecorder.isRecording) {
@@ -628,7 +657,7 @@ class ScanForegroundService : Service() {
)
}
- remoteId?.let { info -> if (loc != null) maybeAlertDroneOverhead(a, info, loc, now) }
+ if (via == null) remoteId?.let { info -> if (loc != null) maybeAlertDroneOverhead(a, info, loc, now) }
val best = c.hits.firstOrNull() ?: return
// Ignored trackers (their address changes, so they can't be whitelisted); this is
@@ -642,7 +671,9 @@ class ScanForegroundService : Service() {
noteLocating()
maybeLog(a, best, c.vendor, loc, now)
- maybeAlert(a, best, now)
+ maybeAlert(a, best, now, via)
+ // Following is about this phone: a device near another Sentinel isn't following it.
+ if (via != null) return
val trackerPaused = best.category == Category.TRACKER && now < Prefs.trackerFollowPausedUntil(this)
val followMs = Prefs.followMinMinutes(this) * 60_000L
@@ -689,7 +720,7 @@ class ScanForegroundService : Service() {
val mac = com.rfsentinel.app.util.MacUtil.normalize(m.mac)
com.rfsentinel.app.esp.HeardBy.usb.mark(mac, now)
noteProbes(mac, m.probedSsids, m.rssi, now, m.wps, m.fingerprint, m.hiddenNetwork, m.probeSkeleton)
- process(Advert(
+ val a = Advert(
// A client has no network name; its WPS device name or model says what it is.
mac = mac, source = Advert.Source.WIFI, rssi = m.rssi, name = m.ssid ?: m.wps?.label,
addressType = com.rfsentinel.app.detect.AddressType.ofWifi(mac),
@@ -697,7 +728,9 @@ class ScanForegroundService : Service() {
wildcardProbe = m.wildcardProbe, flockProbeIe = m.flockProbeIe, probeSkeleton = m.probeSkeleton,
probeRun = m.probeRun),
timestamp = now
- ), null)
+ )
+ linkOutbox?.add(LinkCodec.Sighting(LinkCodec.KIND_USB, a, probed = m.probedSsids, fingerprint = m.fingerprint, hidden = m.hiddenNetwork))
+ process(a, null)
}
private fun processEsp(e: com.rfsentinel.app.esp.EspSighting) {
@@ -717,9 +750,83 @@ class ScanForegroundService : Service() {
mac = e.mac, source = Advert.Source.WIFI, rssi = e.rssi, name = e.name,
wifi = Advert.WifiInfo(e.frequencyMhz, e.capabilities, null, emptyList(), client = e.client), timestamp = now
)
+ linkOutbox?.add(LinkCodec.Sighting(LinkCodec.KIND_ESP, advert, hits = e.hits, probed = e.probedSsids))
process(advert, e.remoteId, e.position?.let { DeviceRegistry.GeoSample(now, it.first, it.second) })
}
+ // ---- Sentinel Link -------------------------------------------------------------
+
+ /** What this phone heard, waiting to go to the linked Sentinels (null while Sentinel Link is off). */
+ @Volatile private var linkOutbox: LinkOutbox? = null
+
+ private val linkFlush = object : Runnable {
+ override fun run() {
+ val box = linkOutbox ?: return
+ val loc = lastLocation?.takeIf { usableForPlacing(it) }
+ box.drain(System.currentTimeMillis(), loc?.latitude ?: Double.NaN, loc?.longitude ?: Double.NaN)
+ ?.let { com.rfsentinel.app.link.PhoneLink.send(it) }
+ pipeline.postDelayed(this, LINK_FLUSH_MS)
+ }
+ }
+
+ /** Sentinel Link runs with the scan when this phone is in a group and sharing is on. */
+ private fun updateLink() {
+ val link = com.rfsentinel.app.link.LinkStore
+ if (!link.hasGroup(this) || !link.enabled(this)) { stopLink(); return }
+ if (linkOutbox == null) {
+ linkOutbox = LinkOutbox(link.myId(this))
+ pipeline.postDelayed(linkFlush, LINK_FLUSH_MS)
+ }
+ com.rfsentinel.app.link.PhoneLink.start(this) { b, name -> pipeline.post { onPeerBatch(b, name) } }
+ }
+
+ private fun stopLink() {
+ if (linkOutbox == null) return
+ linkOutbox = null
+ pipeline.removeCallbacks(linkFlush)
+ com.rfsentinel.app.link.PhoneLink.stop()
+ com.rfsentinel.app.esp.HeardBy.peer.clear()
+ }
+
+ /**
+ * What a linked Sentinel heard: its hardware's evidence is kept like this phone's own, and a device this
+ * phone isn't hearing itself goes through the same pipeline (list, radar, map, alerts) placed where that
+ * Sentinel was.
+ */
+ private fun onPeerBatch(b: LinkCodec.Batch, via: String) {
+ if (linkOutbox == null) return
+ val now = System.currentTimeMillis()
+ // Phones' clocks differ: ages are kept, times are this phone's.
+ val shift = now - b.time
+ val at = if (b.lat.isNaN() || b.lon.isNaN()) null else Location("sentinel-link").apply {
+ latitude = b.lat; longitude = b.lon; time = now
+ }
+ val heardBy = com.rfsentinel.app.esp.HeardBy
+ for (s in b.sightings) {
+ val mac = s.advert.mac
+ val a = LinkCodec.rebased(s.advert, (s.advert.timestamp + shift).coerceAtMost(now))
+ heardBy.peer.mark(mac, via, now)
+ if (s.hits.isNotEmpty()) {
+ espHits[mac] = now to s.hits
+ classified.remove(mac)
+ }
+ if (s.probed.isNotEmpty() || s.fingerprint != null) {
+ noteProbes(mac, s.probed, a.rssi, now, fingerprint = s.fingerprint, hidden = s.hidden, skeleton = a.wifi?.probeSkeleton)
+ }
+ // 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)
+ }
+ for (r in b.radios) {
+ val kind = runCatching { com.rfsentinel.app.sdr.RadioWatch.Kind.valueOf(r.kind) }
+ .getOrDefault(com.rfsentinel.app.sdr.RadioWatch.Kind.SHARED)
+ onRadio(com.rfsentinel.app.sdr.RadioWatch.Event(r.freqHz, r.snrDb,
+ com.rfsentinel.app.sdr.RadioWatch.Band(r.bandLabel, r.bandStartHz, r.bandEndHz, kind), r.confidence,
+ r.targetLabel?.let { com.rfsentinel.app.sdr.RadioWatch.Target(r.freqHz, it) }, r.repeat, r.tdma), via)
+ }
+ }
+
/** The watchlist version the cached classifications were made with. */
private var watchlistVersion = OuiWatchlist.version
@@ -788,7 +895,7 @@ class ScanForegroundService : Service() {
}
}
- private fun maybeAlert(a: Advert, best: Hit, now: Long) {
+ private fun maybeAlert(a: Advert, best: Hit, now: Long, via: String? = null) {
// Someone else's tracker nearby is normal; trackers only alert when they follow you.
if (best.category == Category.TRACKER) return
if (best.listOnly || best.confidence < Prefs.alertThreshold(this)) return
@@ -796,8 +903,8 @@ class ScanForegroundService : Service() {
val last = lastAlerted[a.mac] ?: 0L
if (now - last <= window) return
lastAlerted[a.mac] = now
- NotificationHelper.sendAlert(this, a.mac, best, a.rssi)
- AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best))
+ NotificationHelper.sendAlert(this, a.mac, best, a.rssi, via = via)
+ AlertPlayer.play(this, best.tier, com.rfsentinel.app.util.Spoken.device(this, best, via = via))
}
private fun knownAlprActive() = (Prefs.knownAlprAlerts(this) || Prefs.speedCameraAlerts(this)) &&
@@ -1116,9 +1223,11 @@ class ScanForegroundService : Service() {
* an RTL-SDR ([com.rfsentinel.app.sdr.RadioWatch]): logged, and an alert when it clears
* the alert threshold. Only signal strength is known - nothing that was said.
*/
- private fun onRadio(e: com.rfsentinel.app.sdr.RadioWatch.Event) {
- if (!Prefs.categoryEnabled(this, Category.RADIO)) return
+ private fun onRadio(e: com.rfsentinel.app.sdr.RadioWatch.Event, via: String? = null) {
val now = System.currentTimeMillis()
+ if (via == null) linkOutbox?.addRadio(LinkCodec.Radio(e.freqHz, e.snrDb, e.band.label, e.band.startHz, e.band.endHz,
+ e.band.kind.name, e.confidence, e.target?.label, e.repeat, e.tdma, now))
+ if (!Prefs.categoryEnabled(this, Category.RADIO)) return
// Who uses this frequency: a watched frequency's own label, the imported list, or RadioReference.
val named = com.rfsentinel.app.sdr.FreqNames.lookup(e.freqHz, Prefs.radioMatchKhz(this) * 1000L)
val name = e.target?.label ?: named?.name
@@ -1128,13 +1237,14 @@ class ScanForegroundService : Service() {
val threshold = Prefs.alertThreshold(this)
val trend = com.rfsentinel.app.sdr.RadioLog.observe(e, name, Prefs.radioTrendDb(this), now)
val cell = e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.CELLULAR_UPLINK
- if (trend != null && e.confidence >= threshold) {
+ if (trend != null && e.confidence >= threshold && via == null) {
AlertPlayer.callout(this, (if (cell) "Cellular signal " else "Radio ${spokenMhz(e.freqHz)} ") +
if (trend == com.rfsentinel.app.sdr.RadioLog.Trend.CLOSER) "getting closer" else "moving away")
}
if (e.repeat) return // same channel within 2 minutes: list and trend only, no new log entry or alert
val near = when { e.snrDb >= 40 -> "very close"; e.snrDb >= 30 -> "close" else -> "nearby" }
- val detail = "A radio transmitted on ${e.mhz} MHz (${e.band.label}), ${e.snrDb} dB above the noise - $near. " +
+ val heardBy = via?.let { "Heard by $it (Sentinel Link): \"$near\" is from that phone. " } ?: ""
+ val detail = heardBy + "A radio transmitted on ${e.mhz} MHz (${e.band.label}), ${e.snrDb} dB above the noise - $near. " +
(named?.let { "Matches ${"%.4f".format(java.util.Locale.US, it.hz / 1e6)} MHz: ${it.name} (${it.source}). " } ?: "") +
when (e.band.kind) {
com.rfsentinel.app.sdr.RadioWatch.Kind.PUBLIC_SAFETY_MOBILE ->
@@ -1147,7 +1257,7 @@ class ScanForegroundService : Service() {
com.rfsentinel.app.sdr.RadioWatch.Kind.CUSTOM -> "A band you added in Settings > RTL-SDR radio."
else -> "Police use this band, but so do businesses, schools and transit; a weak sign on its own."
}
- val cellDetail = "A cellular transmitter is on the air nearby on ${e.mhz} MHz (${e.band.label}), " +
+ val cellDetail = heardBy + "A cellular transmitter is on the air nearby on ${e.mhz} MHz (${e.band.label}), " +
"${e.snrDb} dB above the quiet level - $near. Something is transmitting on the phone / modem side of an " +
"LTE band: a phone, but also a vehicle modem, a Cradlepoint-style router or a camera with a SIM. Signal " +
"strength only, nothing decoded - it can't tell devices or carriers apart. On its own it means little " +
@@ -1157,7 +1267,7 @@ class ScanForegroundService : Service() {
name != null -> "Radio transmitting: $name"
e.tdma -> "TETRA radio transmitting nearby"
else -> "Two-way radio transmitting nearby"
- }
+ } + (via?.let { " · via $it" } ?: "")
val hit = Hit(Category.RADIO, label, e.confidence, if (cell) cellDetail else detail,
if (e.tdma) "SDR signal strength and TETRA burst timing (no decoding)" else "SDR signal strength (no decoding)")
val loc = lastLocation
@@ -1180,7 +1290,7 @@ class ScanForegroundService : Service() {
Prefs.radioSpeakFreq(this) -> (if (e.tdma) "TETRA radio " else "Radio ") + spokenMhz(e.freqHz) + (name?.let { ", $it" } ?: "")
e.tdma -> "TETRA radio nearby"
else -> "Radio transmitting nearby"
- }
+ } + (via?.let { ", via $it" } ?: "")
AlertPlayer.play(this, hit.tier, spoken)
}
}
@@ -1456,6 +1566,7 @@ class ScanForegroundService : Service() {
if (gnssWatching) { GnssWatch.stop(this, gnssListener); gnssWatching = false }
if (onlineWatchLazy.isInitialized()) onlineWatch.stop() // not built just to be stopped
com.rfsentinel.app.esp.OuiSpyBle.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()
com.rfsentinel.app.esp.HeardBy.usb.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 e38a3f1..6bacb7c 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -311,6 +311,18 @@ class SettingsActivity : AppCompatActivity() {
}
private val pcapTicker = Runnable { updatePcap() }
+ private fun updateLinkStatus() {
+ val link = com.rfsentinel.app.link.LinkStore
+ val n = link.members(this).size
+ binding.linkStatusText.text = when {
+ !link.hasGroup(this) -> "Not linked to other phones"
+ !link.enabled(this) -> "Sharing off"
+ else -> com.rfsentinel.app.link.PhoneLink.status.ifBlank {
+ "$n Sentinel${if (n == 1) "" else "s"} in the group · links while scanning"
+ }
+ }
+ }
+
private fun updateEspStatus() {
val s = com.rfsentinel.app.esp.EspBoards.status
binding.espStatusText.text = s.ifBlank { "ESP32 board on USB: not connected" }
@@ -580,6 +592,15 @@ class SettingsActivity : AppCompatActivity() {
"position, with an alert when their light bar or siren is on, or when they warn that they're approaching. " +
"Ordinary cars are counted, not listed. North America uses a different V2X radio (C-V2X) that this board can't hear. " +
"Receiving V2X may fall under telecom or privacy law where you are."),
+ Section("link", binding.headerLink, binding.sectionLink,
+ "Link RF Sentinel phones near each other over Bluetooth: every linked phone shows the same devices on its list, " +
+ "radar and map, whichever phone heard them first - including what each phone's ESP32 board, USB WiFi adapter " +
+ "or RTL-SDR hears. Alerts sound on every phone and say which Sentinel heard the device.\n\n" +
+ "Linking: tap \"Link up a Sentinel\" on one phone and \"Join a Sentinel\" on the other, then check that both " +
+ "screens show the same 6 digits. Three or more phones: link each new one to any phone of the group.\n\n" +
+ "Works while scanning, up to about 50-100 m between phones (Bluetooth range); a phone in reach of two others " +
+ "passes on what it hears. Everything sent is encrypted for the phones of the group only. No internet, no account, " +
+ "and no Android Bluetooth pairing."),
Section("radio", binding.headerRadio, binding.sectionRadio,
"An RTL-SDR dongle or a HackRF on USB notices two-way radios transmitting nearby, from signal strength only - nothing is " +
"decoded or recorded. Needs the Police radio category on (What to detect).\n\n" +
@@ -2187,6 +2208,7 @@ class SettingsActivity : AppCompatActivity() {
com.rfsentinel.app.esp.EspBoards.onStatusChanged = { runOnUiThread { updateEspStatus() } }
com.rfsentinel.app.esp.OuiSpyBle.onStatusChanged = { runOnUiThread { updateEspStatus() } }
binding.ouiSpyButton.setOnClickListener { pairOuiSpy() }
+ binding.linkButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ui.SentinelLinkActivity::class.java)) }
binding.usbWifiLogButton.setOnClickListener { exportUsbWifiLog() }
// FOSS build: an adapter waiting for its chip firmware asks to download it.
binding.usbWifiText.setOnClickListener { com.rfsentinel.app.usb.FirmwarePrompt.show(this) { updateEspStatus() } }
@@ -2326,6 +2348,7 @@ class SettingsActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
+ updateLinkStatus()
// Back from the theme maker: its themes may have changed.
if (loaded) buildThemeList()
updatePcap()
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
index 2f516fd..6b96ae7 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
@@ -29,6 +29,8 @@ data class DeviceRow(
val heardByEsp: Boolean = false,
val heardByUsb: Boolean = false,
val heardByPhone: Boolean = false,
+ /** The linked Sentinel that heard it (Sentinel Link), or null. */
+ val heardByPeer: String? = null,
/** For the visual style: the signal for the bars (null = none), and the match's confidence (null = not a match). */
val rssi: Int? = null,
val confidence: Int? = null,
@@ -39,10 +41,11 @@ data class DeviceRow(
private const val ESP_BADGE = 0xFF1E88E5.toInt()
private const val PHONE_BADGE = 0xFF2E7D32.toInt()
private const val USB_BADGE = 0xFF6A1B9A.toInt()
+private const val PEER_BADGE = 0xFF00838F.toInt()
-/** The meta line, followed by small coloured "ESP32" / "INTERNAL" badges. */
+/** The meta line, followed by small coloured "ESP32" / "INTERNAL" / "VIA <Sentinel>" badges. */
private fun metaWithBadges(row: DeviceRow): CharSequence {
- if (!row.heardByEsp && !row.heardByUsb && !row.heardByPhone) return row.meta
+ if (!row.heardByEsp && !row.heardByUsb && !row.heardByPhone && row.heardByPeer == null) return row.meta
val sb = android.text.SpannableStringBuilder(row.meta)
fun badge(label: String, color: Int) {
sb.append(" ")
@@ -56,6 +59,7 @@ private fun metaWithBadges(row: DeviceRow): CharSequence {
if (row.heardByEsp) badge("ESP32", ESP_BADGE)
if (row.heardByUsb) badge("USB WIFI", USB_BADGE)
if (row.heardByPhone) badge("INTERNAL", PHONE_BADGE)
+ row.heardByPeer?.let { badge("VIA " + it.uppercase(), PEER_BADGE) }
return sb
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
index 530185b..a6d0712 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceFilter.kt
@@ -26,7 +26,9 @@ enum class DeviceFilter(val label: String) {
/** Aircraft from the RTL-SDR's ADS-B receiver and the online feeds: not devices (list and map). */
AIRCRAFT("Aircraft"),
/** Heard by external hardware: an ESP32 board (USB or OUI-SPY over Bluetooth) or a USB WiFi adapter. */
- EXTERNAL("External");
+ EXTERNAL("External"),
+ /** Heard by a linked Sentinel (Sentinel Link). */
+ SENTINELS("Sentinels");
fun matches(s: DeviceRegistry.Snapshot): Boolean = when (this) {
ALL -> true
@@ -37,6 +39,7 @@ enum class DeviceFilter(val label: String) {
NEW -> s.isNew
CELLS, WAZE, RADIO, AIRCRAFT -> false
EXTERNAL -> com.rfsentinel.app.esp.HeardBy.esp.recent(s.mac) || com.rfsentinel.app.esp.HeardBy.usb.recent(s.mac)
+ SENTINELS -> com.rfsentinel.app.esp.HeardBy.peer.recent(s.mac)
FAVORITES -> Favorites.contains(s.mac)
BLE -> Advert.Source.BLE in s.sources
WIFI -> Advert.Source.WIFI in s.sources
@@ -56,6 +59,6 @@ enum class DeviceFilter(val label: String) {
* The main screen's chip order: the counts worth a glance first (flagged, then what's heard on each
* radio), so they fit without scrolling; the narrower filters after them.
*/
- val MAIN_ORDER = listOf(ALL, FLAGGED, BLE, WIFI, CELLS, TRACKERS, DRONES, AIRCRAFT, RADIO, WAZE, EXTERNAL, FAVORITES, NEW)
+ val MAIN_ORDER = listOf(ALL, FLAGGED, BLE, WIFI, CELLS, TRACKERS, DRONES, AIRCRAFT, RADIO, WAZE, EXTERNAL, SENTINELS, FAVORITES, NEW)
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
index 0fa34ff..a3821c0 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/LiveWindow.kt
@@ -37,8 +37,9 @@ object LiveWindow {
// A flagged device never leaves the list while it still alerts (bubble, banner, beeps).
if (s.best != null && inRange(s, now)) return true
val phoneMs = if (wifi) wifiMs else bleMs
- // Heard by an ESP32 board or a USB adapter: its own time, or the longer one when the phone hears it too.
- val external = HeardBy.esp.recent(s.mac, now) || HeardBy.usb.recent(s.mac, now)
+ // Heard by an ESP32 board, a USB adapter or a linked Sentinel: its own time, or the longer one when the
+ // phone hears it too.
+ val external = HeardBy.esp.recent(s.mac, now) || HeardBy.usb.recent(s.mac, now) || HeardBy.peer.recent(s.mac, now)
val ms = when {
!external -> phoneMs
HeardBy.phone.recent(s.mac, now) -> maxOf(phoneMs, externalMs)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
new file mode 100644
index 0000000..0e0c559
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
@@ -0,0 +1,282 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.Typeface
+import android.os.Build
+import android.os.Bundle
+import android.text.format.DateUtils
+import android.view.Gravity
+import android.view.View
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.Lifecycle
+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.switchmaterial.SwitchMaterial
+import com.rfsentinel.app.link.LinkStore
+import com.rfsentinel.app.link.PhoneLink
+import com.rfsentinel.app.service.ScanForegroundService
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/**
+ * Sentinel Link: this phone's name, sharing on / off, linking a new phone ("Link up a Sentinel" on one,
+ * "Join a Sentinel" on the other, same 6 digits on both), the Sentinels of the group, and leaving it.
+ */
+class SentinelLinkActivity : AppCompatActivity() {
+
+ private lateinit var status: TextView
+ private lateinit var share: SwitchMaterial
+ private lateinit var list: LinearLayout
+ private lateinit var leave: MaterialButton
+ private var pairDialog: AlertDialog? = null
+ private var pendingHost: Boolean? = 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)
+ else Toast.makeText(this, "Sentinel Link needs \"Nearby devices\"", Toast.LENGTH_LONG).show()
+ }
+
+ private val dp get() = resources.displayMetrics.density
+ private fun pad(v: Int) = (v * dp).toInt()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ title = "Sentinel Link"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+
+ val intro = TextView(this).apply {
+ textSize = 14f
+ setLineSpacing(0f, 1.2f)
+ text = "Link RF Sentinel phones near each other over Bluetooth: each one shows the same devices on its list, " +
+ "radar and map - with what any phone's external hardware hears - whichever phone heard them first. " +
+ "Linked phones share while they scan."
+ }
+ status = TextView(this).apply { textSize = 14f; setTypeface(typeface, Typeface.BOLD); setPadding(0, pad(12), 0, 0) }
+
+ val nameLabel = TextView(this).apply { textSize = 13f; text = "This phone's name"; setPadding(0, pad(16), 0, 0) }
+ val name = EditText(this).apply {
+ setSingleLine(true)
+ setText(LinkStore.myName(this@SentinelLinkActivity))
+ setOnFocusChangeListener { _, focused -> if (!focused) saveName(text.toString()) }
+ setOnEditorActionListener { v, _, _ -> saveName(v.text.toString()); v.clearFocus(); false }
+ }
+ share = SwitchMaterial(this).apply {
+ text = "Share with linked Sentinels"
+ isChecked = LinkStore.enabled(this@SentinelLinkActivity)
+ setOnCheckedChangeListener { _, on ->
+ LinkStore.setEnabled(this@SentinelLinkActivity, on)
+ ScanForegroundService.refreshLink(this@SentinelLinkActivity)
+ refresh()
+ }
+ setPadding(0, pad(8), 0, pad(8))
+ }
+
+ fun button(label: String, onClick: () -> Unit) = MaterialButton(this).apply {
+ text = label
+ setOnClickListener { onClick() }
+ layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
+ .apply { topMargin = pad(8) }
+ }
+ val hostButton = button("Link up a Sentinel") { pair(host = true) }
+ val joinButton = button("Join a Sentinel") { pair(host = false) }
+ val listHeader = TextView(this).apply {
+ textSize = 16f; setTypeface(typeface, Typeface.BOLD); text = "Sentinels"; setPadding(0, pad(20), 0, pad(4))
+ }
+ list = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+ leave = MaterialButton(this, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ text = "Leave the group"
+ setOnClickListener { confirmLeave() }
+ }
+
+ 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)
+ }
+ val scroll = ScrollView(this).apply { addView(column) }
+ setContentView(scroll)
+ scroll.applySystemBarInsets()
+
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(5_000) }
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ PhoneLink.addListener(onLinkChanged)
+ }
+
+ override fun onStop() {
+ PhoneLink.removeListener(onLinkChanged)
+ super.onStop()
+ }
+
+ override fun onDestroy() {
+ if (pairDialog?.isShowing == true) PhoneLink.cancelPairing()
+ pairDialog = null
+ super.onDestroy()
+ }
+
+ override fun onSupportNavigateUp(): Boolean { finish(); return true }
+
+ private fun saveName(text: String) {
+ if (text.trim() == LinkStore.myName(this)) return
+ LinkStore.setMyName(this, text)
+ PhoneLink.meChanged()
+ }
+
+ private fun refresh() {
+ if (isFinishing) return
+ val grouped = LinkStore.hasGroup(this)
+ status.text = when {
+ !grouped -> "Not linked yet"
+ !LinkStore.enabled(this) -> "Sharing off"
+ !ScanForegroundService.isRunning -> "Links while scanning - start a scan to share"
+ else -> PhoneLink.status.ifBlank { "Starting…" }
+ }
+ share.visibility = if (grouped) View.VISIBLE else View.GONE
+ leave.visibility = if (grouped) View.VISIBLE else View.GONE
+
+ list.removeAllViews()
+ val members = LinkStore.members(this)
+ if (members.isEmpty()) {
+ list.addView(TextView(this).apply {
+ textSize = 14f
+ text = "None yet. On two phones near each other, tap \"Link up a Sentinel\" on one and \"Join a Sentinel\" on the other."
+ })
+ return
+ }
+ val linked = PhoneLink.linked.associateBy { it.id }
+ val now = System.currentTimeMillis()
+ for (m in members) {
+ val heard = PhoneLink.lastHeard[m.id]
+ val detail = when {
+ linked.containsKey(m.id) -> "Linked now"
+ heard != null -> "Last heard " + DateUtils.getRelativeTimeSpanString(heard, now, DateUtils.MINUTE_IN_MILLIS)
+ else -> "Not in reach"
+ }
+ list.addView(TextView(this).apply {
+ textSize = 15f
+ setPadding(0, pad(6), 0, pad(6))
+ text = "${m.name}\n$detail"
+ })
+ }
+ }
+
+ private fun confirmLeave() {
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Leave the group?")
+ .setMessage("This phone stops sharing with the other Sentinels and forgets the group. The others keep it on their " +
+ "list; to link again, join one of them.")
+ .setPositiveButton("Leave") { _, _ ->
+ LinkStore.leave(this)
+ PhoneLink.groupChanged()
+ ScanForegroundService.refreshLink(this)
+ refresh()
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ private fun pair(host: Boolean) {
+ val others = LinkStore.members(this).size
+ if (!host && others > 0) {
+ MaterialAlertDialogBuilder(this)
+ .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) }
+ .setNegativeButton("Cancel", null)
+ .show()
+ return
+ }
+ withPermission(host)
+ }
+
+ private fun withPermission(host: Boolean) {
+ if (PhoneLink.canUse(this)) { startPairing(host); return }
+ pendingHost = host
+ 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())
+ }
+
+ private fun startPairing(host: Boolean) {
+ val messageView = TextView(this).apply { textSize = 15f; gravity = Gravity.CENTER }
+ val codeView = TextView(this).apply {
+ textSize = 40f
+ typeface = Typeface.MONOSPACE
+ letterSpacing = 0.15f
+ gravity = Gravity.CENTER
+ setPadding(0, pad(16), 0, pad(8))
+ visibility = View.GONE
+ }
+ val body = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(pad(24), pad(16), pad(24), 0)
+ addView(codeView); addView(messageView)
+ }
+ val dialog = MaterialAlertDialogBuilder(this)
+ .setTitle(if (host) "Link up a Sentinel" else "Join a Sentinel")
+ .setView(body)
+ .setPositiveButton("Confirm", null)
+ .setNegativeButton("Cancel") { _, _ -> PhoneLink.cancelPairing() }
+ .setCancelable(false)
+ .create()
+ dialog.setOnShowListener {
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE).apply {
+ isEnabled = false
+ setOnClickListener {
+ isEnabled = false
+ PhoneLink.confirmCode()
+ }
+ }
+ }
+ dialog.show()
+ pairDialog = dialog
+
+ val listener = object : PhoneLink.PairListener {
+ override fun onStatus(text: String) { messageView.text = text }
+ override fun onCode(code: String) {
+ codeView.text = code.substring(0, 3) + " " + code.substring(3)
+ codeView.visibility = View.VISIBLE
+ messageView.text = "Check that the other phone shows the same code, then tap Confirm on both. Different code? Cancel."
+ dialog.getButton(AlertDialog.BUTTON_POSITIVE)?.isEnabled = true
+ }
+ override fun onLinked(name: String) {
+ if (pairDialog === dialog) pairDialog = null
+ dialog.dismiss()
+ ScanForegroundService.refreshLink(this@SentinelLinkActivity)
+ refresh()
+ MaterialAlertDialogBuilder(this@SentinelLinkActivity)
+ .setTitle("Linked")
+ .setMessage("Linked with $name. " + if (ScanForegroundService.isRunning) "Sharing starts now."
+ else "Sharing starts when both phones scan.")
+ .setPositiveButton("OK", null)
+ .show()
+ }
+ override fun onEnded(message: String) {
+ if (pairDialog === dialog) pairDialog = null
+ dialog.dismiss()
+ Toast.makeText(this@SentinelLinkActivity, message, Toast.LENGTH_LONG).show()
+ }
+ }
+ if (host) PhoneLink.host(this, listener) else PhoneLink.join(this, listener)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
index e0f33ce..dc70883 100644
--- a/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/NotificationHelper.kt
@@ -250,14 +250,15 @@ object NotificationHelper {
othersFlagged.takeIf { it > 0 }?.let { "+$it more flagged" }
).joinToString(" · ")
- fun sendAlert(context: Context, mac: String, hit: Hit, rssi: Int, following: Boolean = false) {
+ /** [via]: the linked Sentinel that heard it (Sentinel Link); [rssi] is then that phone's. */
+ fun sendAlert(context: Context, mac: String, hit: Hit, rssi: Int, following: Boolean = false, via: String? = null) {
// A drone with a Remote ID position is logged where it is; anything else where you were.
val rid = com.rfsentinel.app.service.DeviceRegistry.get(mac)?.remoteId?.takeIf { it.hasPosition }
recordAlert(context, mac, mac, hit, rssi, following, rid?.latitude, rid?.longitude)
val discreet = Prefs.discreetMode(context)
com.rfsentinel.app.ui.ThreatBubble.popup(context,
if (discreet) "New alert" else if (following) "Following you: ${hit.label}" else hit.label,
- if (discreet) null else listOfNotNull(hit.category.shortTag,
+ if (discreet) null else listOfNotNull(hit.category.shortTag, via?.let { "via $it" },
com.rfsentinel.app.service.DeviceRegistry.get(mac)?.distanceM?.takeIf { it > 0 }
?.let { "~" + com.rfsentinel.app.detect.DeviceIntel.formatDistance(it) },
ProximityUtil.band(rssi).lowercase()).joinToString(" · "),
@@ -271,6 +272,7 @@ object NotificationHelper {
)
val title = when {
following -> "May be following you: ${hit.label}"
+ via != null -> "Near $via: ${hit.label}"
else -> "Nearby: ${hit.label}"
}
val snap = com.rfsentinel.app.service.DeviceRegistry.get(mac)
@@ -278,7 +280,8 @@ object NotificationHelper {
val others = com.rfsentinel.app.service.DeviceRegistry.snapshot()
.count { it.mac != mac && com.rfsentinel.app.ui.DeviceColors.isFlagged(it) }
val text = "${hit.category.title} · ${hit.tier.label} (${hit.confidence}%) · $rssi dBm" +
- (snap?.let { " · " + com.rfsentinel.app.detect.DeviceIntel.formatDistance(it.distanceM) } ?: "")
+ (snap?.let { " · " + com.rfsentinel.app.detect.DeviceIntel.formatDistance(it.distanceM) } ?: "") +
+ (via?.let { " · via $it" } ?: "")
val publicVersion = NotificationCompat.Builder(context, CHANNEL_ALERTS)
.setContentTitle("RF Sentinel")
diff --git a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
index 1a93160..5b56af2 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Spoken.kt
@@ -15,10 +15,12 @@ object Spoken {
/** Short phrases; always in the radar-detector sound style, which speaks like a detector. */
fun short(context: Context) = Prefs.shortVoice(context) || Prefs.detectorSound(context) || Prefs.detectorSound(context)
- fun device(context: Context, hit: Hit, following: Boolean = false): String {
- if (!short(context)) return if (following) "Warning. ${hit.label} may be following you." else "${hit.label} nearby"
+ /** [via]: the linked Sentinel that heard it (Sentinel Link). */
+ fun device(context: Context, hit: Hit, following: Boolean = false, via: String? = null): String {
+ val v = via?.let { ", via $it" } ?: ""
+ if (!short(context)) return if (following) "Warning. ${hit.label} may be following you." else "${hit.label} nearby$v"
val word = shortWord(hit)
- return if (following) "$word following" else word
+ return if (following) "$word following" else word + v
}
fun camera(context: Context, cam: KnownCamera): String {
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 29cce52..f1067c4 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -761,6 +761,23 @@
android:text="AWUS036ACS: light blinks with traffic" />
</LinearLayout>
+ <!-- ================= Sentinel Link ================= -->
+ <TextView android:id="@+id/headerLink" style="@style/SettingsHeader" android:text="Sentinel Link" />
+ <LinearLayout android:id="@+id/sectionLink" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/linkStatusText"
+ style="@style/SettingsLabel"
+ android:paddingTop="6dp" />
+
+ <Button
+ android:id="@+id/linkButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Open Sentinel Link" />
+ </LinearLayout>
+
<!-- ================= RTL-SDR radio (filled in by SettingsActivity.setupRadioSection) ================= -->
<TextView android:id="@+id/headerRadio" style="@style/SettingsHeader" android:text="RTL-SDR radio" />
<LinearLayout android:id="@+id/sectionRadio" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />
diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml
index 9010b64..2a22b9a 100644
--- a/app/src/main/res/xml/backup_rules.xml
+++ b/app/src/main/res/xml/backup_rules.xml
@@ -7,4 +7,6 @@
<exclude domain="sharedpref" path="secure_store.xml" />
<!-- Home, Work, starred and recent destinations: addresses stay on this phone. -->
<exclude domain="sharedpref" path="nav_places.xml" />
+ <!-- Sentinel Link: this phone's own id and its group; a copy would make two phones the same Sentinel. -->
+ <exclude domain="sharedpref" path="sentinel_link.xml" />
</full-backup-content>
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
index 5655ee4..a0954e0 100644
--- a/app/src/main/res/xml/data_extraction_rules.xml
+++ b/app/src/main/res/xml/data_extraction_rules.xml
@@ -8,10 +8,13 @@
<exclude domain="sharedpref" path="secure_store.xml" />
<!-- Home, Work, starred and recent destinations: addresses stay on this phone. -->
<exclude domain="sharedpref" path="nav_places.xml" />
+ <!-- Sentinel Link: this phone's own id and its group; a copy would make two phones the same Sentinel. -->
+ <exclude domain="sharedpref" path="sentinel_link.xml" />
</cloud-backup>
<device-transfer>
<include domain="database" path="." />
<include domain="sharedpref" path="." />
<exclude domain="sharedpref" path="secure_store.xml" />
+ <exclude domain="sharedpref" path="sentinel_link.xml" />
</device-transfer>
</data-extraction-rules>
diff --git a/app/src/test/java/com/rfsentinel/app/link/SentinelLinkTest.kt b/app/src/test/java/com/rfsentinel/app/link/SentinelLinkTest.kt
new file mode 100644
index 0000000..00f38fa
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/link/SentinelLinkTest.kt
@@ -0,0 +1,182 @@
+package com.rfsentinel.app.link
+
+import android.app.Application
+import com.rfsentinel.app.detect.AddressType
+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.assertNotEquals
+import org.junit.Assert.assertNotNull
+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
+import java.util.UUID
+
+/**
+ * Sentinel Link's crypto, wire format, framing and send throttle. Conscrypt off: once another Robolectric test
+ * has installed it, the JVM's own Cipher can't start in the same test run.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+@ConscryptMode(ConscryptMode.Mode.OFF)
+class SentinelLinkTest {
+
+ @Test
+ fun bothPhonesShowTheSameCodeAndKeys() {
+ val joiner = LinkCrypto.ecKeyPair()
+ val host = LinkCrypto.ecKeyPair()
+ val jPub = LinkCrypto.publicBytes(joiner)
+ val hPub = LinkCrypto.publicBytes(host)
+ val jN = LinkCrypto.random(16)
+ val hN = LinkCrypto.random(16)
+ val sJ = LinkCrypto.ecdh(joiner, LinkCrypto.publicFrom(hPub))
+ val sH = LinkCrypto.ecdh(host, LinkCrypto.publicFrom(jPub))
+ assertArrayEquals(sJ, sH)
+ val code = LinkCrypto.code(sJ, jPub, hPub, jN, hN)
+ assertEquals(code, LinkCrypto.code(sH, jPub, hPub, jN, hN))
+ assertTrue(code.matches(Regex("\\d{6}")))
+ // A phone in the middle has its own key pair: its code differs.
+ val mitm = LinkCrypto.ecKeyPair()
+ val sM = LinkCrypto.ecdh(mitm, LinkCrypto.publicFrom(hPub))
+ assertNotEquals(code, LinkCrypto.code(sM, LinkCrypto.publicBytes(mitm), hPub, jN, hN))
+
+ val toHost = LinkCrypto.pairKey(sJ, jN, hN, toHost = true)
+ assertArrayEquals(toHost, LinkCrypto.pairKey(sH, jN, hN, toHost = true))
+ assertFalse(toHost.contentEquals(LinkCrypto.pairKey(sH, jN, hN, toHost = false)))
+ }
+
+ @Test
+ fun sealedDataOpensOnlyUnchangedWithItsKeyAndCounter() {
+ val key = LinkCrypto.random(32)
+ val sealed = LinkCrypto.seal(key, 7, "hello".toByteArray())
+ assertEquals("hello", String(LinkCrypto.open(key, 7, sealed)!!))
+ assertNull(LinkCrypto.open(key, 8, sealed))
+ assertNull(LinkCrypto.open(LinkCrypto.random(32), 7, sealed))
+ val tampered = sealed.copyOf().also { it[0] = (it[0].toInt() xor 1).toByte() }
+ assertNull(LinkCrypto.open(key, 7, tampered))
+ }
+
+ @Test
+ fun sessionKeysPairUpAndProofsNeedTheGroupKey() {
+ val gk = LinkCrypto.random(32)
+ val c = LinkCrypto.random(16)
+ val s = LinkCrypto.random(16)
+ val clientTx = LinkCrypto.sessionKey(gk, c, s, toServer = true)
+ val serverRx = LinkCrypto.sessionKey(gk, c, s, toServer = true)
+ assertArrayEquals(clientTx, serverRx)
+ assertFalse(clientTx.contentEquals(LinkCrypto.sessionKey(gk, c, s, toServer = false)))
+ assertFalse(LinkCrypto.proof(gk, "c", c).contentEquals(LinkCrypto.proof(LinkCrypto.random(32), "c", c)))
+ assertFalse(LinkCrypto.proof(gk, "c", c).contentEquals(LinkCrypto.proof(gk, "s", c)))
+ }
+
+ @Test
+ fun advertTagsChangeEverySlotAndNameThePhone() {
+ val gk = LinkCrypto.random(32)
+ assertFalse(LinkCrypto.groupTag(gk, 10).contentEquals(LinkCrypto.groupTag(gk, 11)))
+ assertFalse(LinkCrypto.nodeTag(gk, 10, 1L).contentEquals(LinkCrypto.nodeTag(gk, 10, 2L)))
+ assertArrayEquals(LinkCrypto.nodeTag(gk, 10, 1L), LinkCrypto.nodeTag(gk, 10, 1L))
+ assertEquals(4, LinkCrypto.groupTag(gk, 10).size)
+ }
+
+ @Test
+ fun batchRoundTripKeepsEverything() {
+ val uuid = UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb")
+ val ble = Advert(
+ mac = "AA:BB:CC:01:02:03", source = Advert.Source.BLE, rssi = -61, name = "Axon Body 3",
+ manufacturerData = mapOf(0x034D to byteArrayOf(1, 2, 3)), serviceUuids = listOf(uuid),
+ serviceData = mapOf(uuid to byteArrayOf(9, 8)), rawBytes = byteArrayOf(2, 1, 6), txPower = -4,
+ addressType = AddressType.RANDOM_STATIC, connectable = true, phy = "LE 1M", timestamp = 1_000_000L - 1_500L
+ )
+ val wifi = Advert(
+ mac = "11:22:33:44:55:66", source = Advert.Source.WIFI, rssi = -70, name = null,
+ wifi = Advert.WifiInfo(5180, "[WPA2-PSK-CCMP]", "802.11ac", listOf(221 to byteArrayOf(0x50, 0x6F)), client = true,
+ wildcardProbe = true, flockProbeIe = false, probeSkeleton = 0x1234L),
+ timestamp = 1_000_000L
+ )
+ val hit = Hit(Category.BODY_CAM, "Axon body camera", 88, "Axon company id", "ESP32")
+ val b = LinkCodec.Batch(42L, 7, 1, 1_000_000L, 10.5, 20.25,
+ listOf(LinkCodec.Sighting(LinkCodec.KIND_PHONE, ble),
+ LinkCodec.Sighting(LinkCodec.KIND_USB, wifi, listOf(hit), listOf("HomeNet"), "fp1", hidden = true)),
+ listOf(LinkCodec.Radio(154_430_000L, 33, "VHF high", 150_000_000L, 174_000_000L, "SHARED", 60, "Dispatch", false, true, 999_000L)))
+
+ val bytes = LinkCodec.batch(b)
+ assertEquals(LinkCodec.BATCH, bytes[0].toInt())
+ val r = LinkCodec.readBatch(bytes)!!
+ assertEquals(42L, r.origin); assertEquals(7, r.seq); assertEquals(1, r.hops); assertEquals(10.5, r.lat, 0.0)
+ val a = r.sightings[0].advert
+ assertEquals("AA:BB:CC:01:02:03", a.mac)
+ assertEquals(-61, a.rssi); assertEquals("Axon Body 3", a.name); assertEquals(998_500L, a.timestamp)
+ assertArrayEquals(byteArrayOf(1, 2, 3), a.manufacturerData[0x034D])
+ assertEquals(listOf(uuid), a.serviceUuids)
+ assertArrayEquals(byteArrayOf(9, 8), a.serviceData[uuid])
+ assertEquals(-4, a.txPower); assertEquals(AddressType.RANDOM_STATIC, a.addressType); assertEquals(true, a.connectable)
+ val s2 = r.sightings[1]
+ assertEquals(LinkCodec.KIND_USB, s2.kind)
+ assertEquals(listOf(hit), s2.hits)
+ assertEquals(listOf("HomeNet"), s2.probed)
+ assertEquals("fp1", s2.fingerprint); assertTrue(s2.hidden)
+ val w = s2.advert.wifi!!
+ assertEquals(5180, w.frequencyMhz); assertTrue(w.client); assertTrue(w.wildcardProbe); assertEquals(0x1234L, w.probeSkeleton)
+ assertEquals(221, w.infoElements[0].first)
+ assertEquals(LinkCodec.Radio(154_430_000L, 33, "VHF high", 150_000_000L, 174_000_000L, "SHARED", 60, "Dispatch", false, true, 999_000L),
+ r.radios[0])
+ assertNull(LinkCodec.readBatch(byteArrayOf(LinkCodec.BATCH.toByte(), 1, 2, 3)))
+ }
+
+ @Test
+ fun smallMessagesRoundTrip() {
+ val me = LinkCodec.Member(5L, "Pixel 7")
+ val (who, known) = LinkCodec.readInfo(LinkCodec.info(me, listOf(LinkCodec.Member(9L, "Tablet"))))
+ assertEquals(me, who); assertEquals(listOf(LinkCodec.Member(9L, "Tablet")), known)
+ val key = LinkCrypto.random(32)
+ val (k, members) = LinkCodec.readGroup(LinkCodec.group(key, listOf(me)))
+ assertArrayEquals(key, k); assertEquals(listOf(me), members)
+ val (counter, data) = LinkCodec.readSealed(LinkCodec.sealed(77L, byteArrayOf(4, 5)))
+ assertEquals(77L, counter); assertArrayEquals(byteArrayOf(4, 5), data)
+ }
+
+ @Test
+ fun framesReassembleFromAnyPieces() {
+ val a = ByteArray(1000) { it.toByte() }
+ val b = byteArrayOf(1, 2, 3)
+ val stream = LinkFrames.frame(a) + LinkFrames.frame(b)
+ val r = LinkFrames.Reassembler()
+ val out = LinkFrames.chunks(stream, 37).flatMap { r.feed(it) }
+ assertEquals(2, out.size)
+ assertArrayEquals(a, out[0]); assertArrayEquals(b, out[1])
+ val bad = LinkFrames.Reassembler()
+ assertTrue(runCatching { bad.feed(byteArrayOf(0x7F, 0, 0, 0)) }.isFailure)
+ }
+
+ @Test
+ fun outboxSendsEachDeviceOnceUntilItChanges() {
+ val box = LinkOutbox(1L)
+ fun adv(rssi: Int, t: Long) = Advert("AA:00:00:00:00:01", Advert.Source.BLE, rssi, timestamp = t)
+ box.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, adv(-60, 1_000)))
+ box.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, adv(-61, 1_500))) // same device, nothing new
+ val first = box.drain(2_000, Double.NaN, Double.NaN)
+ assertNotNull(first)
+ assertEquals(1, first!!.sightings.size)
+ assertNull(box.drain(2_100, Double.NaN, Double.NaN))
+ box.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, adv(-45, 2_200))) // much stronger
+ box.add(LinkCodec.Sighting(LinkCodec.KIND_ESP, adv(-80, 2_200))) // another radio heard it
+ val second = box.drain(2_300, Double.NaN, Double.NaN)!!
+ assertEquals(2, second.sightings.size)
+ assertTrue(second.seq > first.seq)
+ box.add(LinkCodec.Sighting(LinkCodec.KIND_PHONE, adv(-45, 2_200 + LinkOutbox.REPEAT_MS))) // time to repeat
+ assertEquals(1, box.drain(9_000, Double.NaN, Double.NaN)!!.sightings.size)
+ }
+
+ @Test
+ fun seenBatchesPassEachOnlyOnce() {
+ val seen = SeenBatches(capacity = 3)
+ assertTrue(seen.first(1L, 1)); assertFalse(seen.first(1L, 1)); assertTrue(seen.first(2L, 1))
+ }
+}