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: Internet relay - the mesh's sealed packets through an MQTT broker the user chooses (mqtts:// or mqtt://, optional login kept in the Keystore), topic made from the group key; off by default

CIS-C054643e4bb073
diff --git a/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
index 87274da..d69fdb3 100644
--- a/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/LinkStore.kt
@@ -120,6 +120,20 @@ object LinkStore {
const val MESH_HOPS_MIN = 1
const val MESH_HOPS_MAX = 7
+ // ---- Internet relay (MQTT)
+
+ /** Sentinel Link also goes through an MQTT broker (off until turned on). */
+ fun mqttOn(c: Context) = sp(c).getBoolean("mqtt_on", false)
+ fun setMqttOn(c: Context, on: Boolean) = sp(c).edit { putBoolean("mqtt_on", on) }
+ /** "mqtts://host:8883" as typed, "" until set. */
+ fun mqttBroker(c: Context): String = sp(c).getString("mqtt_broker", "") ?: ""
+ fun setMqttBroker(c: Context, url: String) = sp(c).edit { putString("mqtt_broker", url.trim()) }
+ fun mqttUser(c: Context): String = sp(c).getString("mqtt_user", "") ?: ""
+ fun setMqttUser(c: Context, user: String) = sp(c).edit { putString("mqtt_user", user.trim()) }
+ /** Kept encrypted ([SecureStore]), out of backups. */
+ fun mqttPassword(c: Context): String? = SecureStore.get(c, "mqtt_password")
+ fun setMqttPassword(c: Context, password: String) = SecureStore.put(c, "mqtt_password", password)
+
private var meshNext = -1L
private var meshReserved = 0L
diff --git a/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt b/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt
new file mode 100644
index 0000000..88c2c1a
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/link/MqttRelay.kt
@@ -0,0 +1,262 @@
+package com.rfsentinel.app.link
+
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import java.io.BufferedInputStream
+import java.io.ByteArrayOutputStream
+import java.io.DataInputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.net.URI
+import java.util.concurrent.CopyOnWriteArrayList
+import javax.net.ssl.HttpsURLConnection
+import javax.net.ssl.SSLSocket
+import javax.net.ssl.SSLSocketFactory
+
+/**
+ * Sentinel Link over the internet: the same sealed packets as the Meshtastic node ([MeshCodec], AES-GCM with a key
+ * from the group key), published to an MQTT broker the user chooses (their own Mosquitto, say) on a topic made from
+ * the group key. The broker sees encrypted bytes, the phone's IP and when it sends; nothing else. Reconnects on its own.
+ */
+object MqttRelay {
+ private const val TAG = "MqttRelay"
+ private const val KEEPALIVE_S = 60
+ /** A ping this long after the last packet out; the broker answers, so silence past [DEAD_MS] means the link is gone. */
+ private const val PING_MS = 30_000L
+ private const val DEAD_MS = 90_000L
+ private const val CONNECT_TIMEOUT_MS = 15_000
+ private const val RETRY_MIN_MS = 5_000L
+ private const val RETRY_MAX_MS = 120_000L
+
+ /** Where to connect: mqtts:// (TLS, port 8883 by default) or mqtt:// (port 1883). */
+ data class Broker(val tls: Boolean, val host: String, val port: Int)
+
+ /** "mqtts://host:8883", "mqtt://host" or a bare "host" (TLS); null when it isn't one. */
+ fun parse(text: String): Broker? = runCatching {
+ val t = text.trim()
+ if (t.isEmpty()) return null
+ val u = URI(if ("://" in t) t else "mqtts://$t")
+ val tls = when (u.scheme?.lowercase()) { "mqtts", "ssl", "tls" -> true; "mqtt", "tcp" -> false; else -> return null }
+ val host = u.host?.takeIf { it.isNotBlank() } ?: return null
+ Broker(tls, host, if (u.port > 0) u.port else if (tls) 8883 else 1883)
+ }.getOrNull()
+
+ /** The group's topic: from the group key, so it says nothing about the group and others can't guess it. */
+ fun topic(groupKey: ByteArray) =
+ "rfsentinel/" + LinkCrypto.hmac(groupKey, "mqtt topic".toByteArray()).copyOf(8).joinToString("") { "%02x".format(it) }
+
+ private val main by lazy { Handler(Looper.getMainLooper()) }
+
+ /** One line for the screens, "" while off. */
+ @Volatile var status = ""; private set
+ /** Connected and subscribed. */
+ @Volatile var ready = false; private set
+ @Volatile var lastSent = 0L; private set
+ private val listeners = CopyOnWriteArrayList<() -> Unit>()
+ fun addListener(l: () -> Unit) { listeners += l }
+ fun removeListener(l: () -> Unit) { listeners -= l }
+ private fun changed() = main.post { listeners.forEach { it() } }
+ private fun setStatus(s: String) { if (s != status) { status = s; changed() } }
+
+ private data class Config(val broker: Broker, val user: String?, val password: String?, val topic: String)
+
+ private var config: Config? = null
+ private var thread: Thread? = null
+ @Volatile private var socket: Socket? = null
+ @Volatile private var out: OutputStream? = null
+ private val writeLock = Any()
+ @Volatile private var lastWrite = 0L
+
+ /** Connects (again, when anything changed); [packets] gets the group's payloads, on the relay's thread. */
+ @Synchronized
+ fun start(broker: Broker, user: String?, password: String?, groupKey: ByteArray, packets: (ByteArray) -> Unit) {
+ val c = Config(broker, user?.takeIf { it.isNotBlank() }, password?.takeIf { it.isNotEmpty() }, topic(groupKey))
+ if (c == config && thread?.isAlive == true) return
+ stop()
+ config = c
+ thread = Thread({ run(c, packets) }, "rf-mqtt").apply { isDaemon = true; start() }
+ }
+
+ @Synchronized
+ fun stop() {
+ config = null
+ thread?.interrupt()
+ thread = null
+ closeSocket()
+ ready = false
+ setStatus("")
+ }
+
+ /** Publishes one packet; false while not connected (the packet is dropped: the outbox sends newer ones later). */
+ fun send(payload: ByteArray): Boolean {
+ val c = config ?: return false
+ if (!ready) return false
+ return write(MqttCodec.publish(c.topic, payload)).also { if (it) lastSent = System.currentTimeMillis() }
+ }
+
+ /** Called every few seconds: a ping when nothing went out for a while, so the broker keeps the session. */
+ fun keepAlive(now: Long) {
+ if (ready && now - lastWrite >= PING_MS) write(MqttCodec.PINGREQ)
+ }
+
+ private fun write(bytes: ByteArray): Boolean = synchronized(writeLock) {
+ val o = out ?: return false
+ try { o.write(bytes); o.flush(); lastWrite = System.currentTimeMillis(); true }
+ catch (e: IOException) { closeSocket(); false } // the reader sees it and reconnects
+ }
+
+ private fun closeSocket() {
+ ready = false
+ out = null
+ runCatching { socket?.close() }
+ socket = null
+ }
+
+ private fun current(c: Config) = synchronized(this) { config === c }
+
+ private fun run(c: Config, packets: (ByteArray) -> Unit) {
+ var retry = RETRY_MIN_MS
+ while (current(c) && !Thread.currentThread().isInterrupted) {
+ try {
+ setStatus("Connecting to ${c.broker.host}…")
+ val s = open(c.broker)
+ socket = s
+ s.soTimeout = DEAD_MS.toInt()
+ val input = DataInputStream(BufferedInputStream(s.getInputStream()))
+ val o = s.getOutputStream()
+ synchronized(writeLock) { out = o }
+ // A fresh client id each time: nothing ties two sessions (or the phone) together on the broker.
+ val id = "rfs-" + LinkCrypto.random(6).joinToString("") { "%02x".format(it) }
+ if (!write(MqttCodec.connect(id, c.user, c.password, KEEPALIVE_S))) throw IOException("closed")
+ val ack = MqttCodec.read(input)
+ if (ack.type != MqttCodec.CONNACK || ack.body.size < 2) throw IOException("not an MQTT broker")
+ when (val code = ack.body[1].toInt()) {
+ 0 -> Unit
+ 4, 5 -> throw Refused("The broker refused the username or password")
+ else -> throw Refused("The broker refused the connection (code $code)")
+ }
+ if (!write(MqttCodec.subscribe(1, c.topic))) throw IOException("closed")
+ ready = true
+ retry = RETRY_MIN_MS
+ setStatus("Connected to ${c.broker.host}")
+ while (current(c)) {
+ val p = MqttCodec.read(input)
+ if (p.type == MqttCodec.PUBLISH) MqttCodec.payload(p)?.let { (topic, data) -> if (topic == c.topic) packets(data) }
+ }
+ } catch (e: Refused) {
+ if (!current(c)) break
+ setStatus(e.message ?: "Refused")
+ retry = RETRY_MAX_MS
+ } catch (e: Exception) {
+ if (!current(c)) break
+ Log.d(TAG, "connection ended: ${e.javaClass.simpleName}")
+ setStatus("Can't reach ${c.broker.host} - ${e.message?.take(60) ?: e.javaClass.simpleName}, retrying")
+ } finally {
+ closeSocket()
+ }
+ try { Thread.sleep(retry) } catch (e: InterruptedException) { break }
+ retry = (retry * 2).coerceAtMost(RETRY_MAX_MS)
+ }
+ }
+
+ private class Refused(message: String) : IOException(message)
+
+ private fun open(b: Broker): Socket {
+ val plain = Socket().apply { connect(InetSocketAddress(b.host, b.port), CONNECT_TIMEOUT_MS) }
+ if (!b.tls) return plain
+ val s = (SSLSocketFactory.getDefault() as SSLSocketFactory).createSocket(plain, b.host, b.port, true) as SSLSocket
+ s.soTimeout = CONNECT_TIMEOUT_MS
+ s.startHandshake()
+ // An SSLSocket checks the certificate chain but not that it's for this host: done here.
+ if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(b.host, s.session)) {
+ s.close()
+ throw IOException("the certificate isn't for ${b.host}")
+ }
+ return s
+ }
+}
+
+/** The few MQTT 3.1.1 packets the relay uses (QoS 0 only). Plain JVM, so it's unit-tested. */
+object MqttCodec {
+ const val CONNACK = 2
+ const val PUBLISH = 3
+ private const val MAX_PACKET = 64 * 1024
+ val PINGREQ = byteArrayOf(0xC0.toByte(), 0)
+
+ class Packet(val type: Int, val flags: Int, val body: ByteArray)
+
+ fun connect(clientId: String, user: String?, password: String?, keepAliveS: Int): ByteArray {
+ val b = ByteArrayOutputStream()
+ str(b, "MQTT")
+ b.write(4) // protocol level: 3.1.1
+ b.write(0x02 or (if (user != null) 0x80 else 0) or (if (user != null && password != null) 0x40 else 0)) // clean session
+ b.write(keepAliveS shr 8); b.write(keepAliveS and 0xFF)
+ str(b, clientId)
+ if (user != null) { str(b, user); password?.let { str(b, it) } }
+ return packet(0x10, b.toByteArray())
+ }
+
+ fun subscribe(packetId: Int, topic: String): ByteArray {
+ val b = ByteArrayOutputStream()
+ b.write(packetId shr 8); b.write(packetId and 0xFF)
+ str(b, topic)
+ b.write(0) // QoS 0
+ return packet(0x82, b.toByteArray())
+ }
+
+ fun publish(topic: String, payload: ByteArray): ByteArray {
+ val b = ByteArrayOutputStream()
+ str(b, topic)
+ b.write(payload)
+ return packet(0x30, b.toByteArray())
+ }
+
+ /** A PUBLISH's topic and payload (its packet id skipped when the broker sent it above QoS 0). */
+ fun payload(p: Packet): Pair<String, ByteArray>? {
+ if (p.body.size < 2) return null
+ val n = ((p.body[0].toInt() and 0xFF) shl 8) or (p.body[1].toInt() and 0xFF)
+ var at = 2 + n
+ if ((p.flags shr 1) and 3 != 0) at += 2
+ if (at > p.body.size) return null
+ return String(p.body, 2, n, Charsets.UTF_8) to p.body.copyOfRange(at, p.body.size)
+ }
+
+ /** The next packet; throws when the stream ends or doesn't look like MQTT. */
+ fun read(input: DataInputStream): Packet {
+ val head = input.readUnsignedByte()
+ var len = 0
+ var shift = 0
+ while (true) {
+ val d = input.readUnsignedByte()
+ len = len or ((d and 0x7F) shl shift)
+ if (d and 0x80 == 0) break
+ shift += 7
+ if (shift > 21) throw IOException("bad length")
+ }
+ if (len > MAX_PACKET) throw IOException("packet too big")
+ return Packet(head shr 4, head and 0x0F, ByteArray(len).also { input.readFully(it) })
+ }
+
+ private fun packet(head: Int, body: ByteArray): ByteArray {
+ val b = ByteArrayOutputStream()
+ b.write(head)
+ var n = body.size
+ do {
+ var d = n and 0x7F
+ n = n shr 7
+ if (n > 0) d = d or 0x80
+ b.write(d)
+ } while (n > 0)
+ b.write(body)
+ return b.toByteArray()
+ }
+
+ private fun str(b: ByteArrayOutputStream, s: String) {
+ val bytes = s.toByteArray(Charsets.UTF_8)
+ b.write(bytes.size shr 8); b.write(bytes.size and 0xFF)
+ b.write(bytes)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
index 9d190cf..4fedfca 100644
--- a/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
+++ b/app/src/main/java/com/rfsentinel/app/link/PhoneLink.kt
@@ -125,8 +125,9 @@ object PhoneLink {
/** When each Sentinel was last heard from (directly or relayed), wall clock. */
val lastHeard = ConcurrentHashMap<Long, Long>()
- /** When each Sentinel was last heard over the mesh (Meshtastic node). */
+ /** When each Sentinel was last heard over the mesh (Meshtastic node), and through the internet relay (MQTT). */
val lastHeardMesh = ConcurrentHashMap<Long, Long>()
+ val lastHeardNet = ConcurrentHashMap<Long, Long>()
private val listeners = CopyOnWriteArraySet<() -> Unit>()
fun addListener(l: () -> Unit) { listeners += l }
@@ -776,7 +777,7 @@ object PhoneLink {
* A packet from the Meshtastic node: what a Sentinel far away heard. Shown like a Bluetooth one and passed on
* to the Sentinels linked here over Bluetooth (each one shows it once, whichever way it arrives first).
*/
- fun meshIn(payload: ByteArray) = h.post {
+ fun meshIn(payload: ByteArray, viaNet: Boolean = false) = h.post {
if (!sharing) return@post
val key = meshKey ?: return@post
val m = MeshCodec.open(key, payload) ?: return@post
@@ -787,7 +788,7 @@ object PhoneLink {
val c = ctx ?: return@post
m.name?.let { if (LinkStore.addMembers(c, listOf(LinkCodec.Member(m.origin, it)))) names = LinkStore.members(c).associate { x -> x.id to x.name } }
lastHeard[m.origin] = now
- lastHeardMesh[m.origin] = now
+ (if (viaNet) lastHeardNet else lastHeardMesh)[m.origin] = now
val b = MeshCodec.toBatch(m)
if (seen.first(b.origin, b.seq)) {
onBatch?.invoke(b, nameOf(b.origin))
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 9eaded4..1b42bba 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -139,6 +139,10 @@ class ScanForegroundService : Service() {
private const val MESH_MIN_GAP_MS = 15_000L
private const val MESH_PRESENCE_MS = 10 * 60_000L
private const val MESH_NAME_MS = 10 * 60_000L
+ private const val MQTT_TICK_MS = 5_000L
+ private const val MQTT_PRESENCE_MS = 60_000L
+ /** Packets per tick at most: a burst of new devices goes out over a few ticks. */
+ private const val MQTT_MAX_PACKETS = 8
/** 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
@@ -754,7 +758,7 @@ class ScanForegroundService : Service() {
val isFirst = DeviceRegistry.report(a, c.hits, c.identity, c.vendor, remoteId, geo, now, broadcast)
if (isFirst) serviceScope.launch { loadHistory(mac) }
// Over the mesh too (Meshtastic node): not the user's own whitelisted devices.
- if (toMesh && !WhitelistCache.contains(mac)) meshOutbox?.add(a, c.hits, now)
+ if (toMesh && !WhitelistCache.contains(mac)) { meshOutbox?.add(a, c.hits, now); mqttOutbox?.add(a, c.hits, now) }
if (TripRecorder.isRecording) {
TripRecorder.onDevice(
mac, a.rssi, a.source.name,
@@ -917,6 +921,68 @@ class ScanForegroundService : Service() {
}
com.rfsentinel.app.link.PhoneLink.start(this) { b, name -> pipeline.post { onPeerBatch(b, name) } }
updateMesh()
+ updateMqtt()
+ }
+
+ /** What goes out through the MQTT broker (null while it's off). */
+ @Volatile private var mqttOutbox: com.rfsentinel.app.link.MeshOutbox? = null
+ private var mqttLastSend = 0L
+ private var mqttLastName = 0L
+
+ /** The internet relay runs with Sentinel Link when it's turned on and a broker is set. */
+ private fun updateMqtt() {
+ val link = com.rfsentinel.app.link.LinkStore
+ val relay = com.rfsentinel.app.link.MqttRelay
+ val broker = relay.parse(link.mqttBroker(this))
+ val key = link.groupKey(this)
+ if (linkOutbox == null || !link.mqttOn(this) || broker == null || key == null) { stopMqtt(); return }
+ if (mqttOutbox == null) {
+ mqttOutbox = com.rfsentinel.app.link.MeshOutbox()
+ mqttLastSend = 0L
+ mqttLastName = 0L
+ pipeline.postDelayed(mqttFlush, MQTT_TICK_MS)
+ }
+ relay.start(broker, link.mqttUser(this), link.mqttPassword(this), key) { com.rfsentinel.app.link.PhoneLink.meshIn(it, viaNet = true) }
+ }
+
+ private fun stopMqtt() {
+ if (mqttOutbox == null) return
+ mqttOutbox = null
+ pipeline.removeCallbacks(mqttFlush)
+ com.rfsentinel.app.link.MqttRelay.stop()
+ }
+
+ /**
+ * Every few seconds, the devices due (the mesh's turns: watchlist matches first, repeats spaced out), as many
+ * packets as they fill; a packet with none every minute so the others know this Sentinel is there and where.
+ */
+ private val mqttFlush = object : Runnable {
+ override fun run() {
+ val box = mqttOutbox ?: return
+ pipeline.postDelayed(this, MQTT_TICK_MS)
+ val relay = com.rfsentinel.app.link.MqttRelay
+ val now = System.currentTimeMillis()
+ relay.keepAlive(now)
+ if (!relay.ready) return
+ val ctx = this@ScanForegroundService
+ val link = com.rfsentinel.app.link.LinkStore
+ val key = link.groupKey(ctx) ?: return
+ val loc = lastLocation?.takeIf { usableForPlacing(it) }
+ val lat = loc?.latitude ?: Double.NaN
+ val lon = loc?.longitude ?: Double.NaN
+ val codec = com.rfsentinel.app.link.MeshCodec
+ var presence = now - mqttLastSend >= MQTT_PRESENCE_MS
+ repeat(MQTT_MAX_PACKETS) {
+ val name = if (now - mqttLastName >= MESH_NAME_MS) link.myName(ctx) else null
+ val devices = box.take(now, codec.MAX_BODY - codec.baseSize(!lat.isNaN(), name))
+ if (devices.isEmpty() && !presence) return
+ val bytes = codec.seal(codec.messageKey(key), link.myId(ctx), link.nextMeshCounter(ctx), now, lat, lon, name, devices)
+ if (!relay.send(bytes)) return
+ mqttLastSend = now
+ presence = false
+ if (name != null) mqttLastName = now
+ }
+ }
}
/** What goes out over the Meshtastic node (null while it's off). */
@@ -981,6 +1047,7 @@ class ScanForegroundService : Service() {
private fun stopLink() {
stopMesh()
+ stopMqtt()
if (linkOutbox == null) return
linkOutbox = null
pipeline.removeCallbacks(linkFlush)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
index ee72a90..828f33d 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
@@ -4,6 +4,7 @@ import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
+import android.text.InputType
import android.text.format.DateUtils
import android.view.Gravity
import android.view.View
@@ -23,6 +24,7 @@ import com.google.android.material.slider.Slider
import com.google.android.material.switchmaterial.SwitchMaterial
import com.rfsentinel.app.link.LinkStore
import com.rfsentinel.app.link.MeshNode
+import com.rfsentinel.app.link.MqttRelay
import com.rfsentinel.app.link.PhoneLink
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.applySystemBarInsets
@@ -46,6 +48,8 @@ class SentinelLinkActivity : AppCompatActivity() {
private lateinit var meshSwitch: SwitchMaterial
private lateinit var meshNodeText: TextView
private lateinit var meshStatus: TextView
+ private lateinit var mqttSection: LinearLayout
+ private lateinit var mqttStatus: TextView
private var pairDialog: AlertDialog? = null
private var pending: (() -> Unit)? = null
private val onLinkChanged: () -> Unit = { refresh() }
@@ -110,12 +114,13 @@ class SentinelLinkActivity : AppCompatActivity() {
}
meshSection = meshSection(::button)
+ mqttSection = mqttSection()
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(meshSection); addView(leave)
+ addView(hostButton); addView(joinButton); addView(listHeader); addView(list); addView(meshSection); addView(mqttSection); addView(leave)
}
val scroll = ScrollView(this).apply { addView(column) }
setContentView(scroll)
@@ -128,11 +133,13 @@ class SentinelLinkActivity : AppCompatActivity() {
super.onStart()
PhoneLink.addListener(onLinkChanged)
MeshNode.addListener(onLinkChanged)
+ MqttRelay.addListener(onLinkChanged)
}
override fun onStop() {
PhoneLink.removeListener(onLinkChanged)
MeshNode.removeListener(onLinkChanged)
+ MqttRelay.removeListener(onLinkChanged)
super.onStop()
}
@@ -225,6 +232,66 @@ class SentinelLinkActivity : AppCompatActivity() {
}
}
+ /** Internet relay: on / off, the MQTT broker and its login, how it's doing. */
+ private fun mqttSection(): LinearLayout {
+ val header = TextView(this).apply {
+ textSize = 16f; setTypeface(typeface, Typeface.BOLD); text = "Internet relay"; setPadding(0, pad(20), 0, pad(4))
+ }
+ val about = TextView(this).apply {
+ textSize = 14f
+ setLineSpacing(0f, 1.2f)
+ text = "Reach Sentinels anywhere through an MQTT broker you choose, like your own Mosquitto server. Every phone " +
+ "of the group sets the same broker. Packets are encrypted with the group's key before they leave the phone, " +
+ "on a topic made from it: the broker only sees encrypted bytes, your IP address and when you send. " +
+ "mqtts:// connects with TLS (port 8883 unless you give one); mqtt:// doesn't, so the username and password " +
+ "go unencrypted - use it only on a network you trust. Uses mobile data: a few small packets a minute."
+ }
+ val switch = SwitchMaterial(this).apply {
+ text = "Use an MQTT broker"
+ isChecked = LinkStore.mqttOn(this@SentinelLinkActivity)
+ setOnCheckedChangeListener { _, on ->
+ LinkStore.setMqttOn(this@SentinelLinkActivity, on)
+ ScanForegroundService.refreshLink(this@SentinelLinkActivity)
+ refresh()
+ }
+ setPadding(0, pad(8), 0, pad(8))
+ }
+ fun field(label: String, hint: String, value: String, password: Boolean, save: (String) -> Unit): List<View> {
+ val l = TextView(this).apply { textSize = 13f; text = label; setPadding(0, pad(8), 0, 0) }
+ val e = EditText(this).apply {
+ setSingleLine(true)
+ this.hint = hint
+ setText(value)
+ inputType = if (password) InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
+ else InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
+ var saved = value
+ fun commit() {
+ val t = text.toString()
+ if (t == saved) return
+ saved = t
+ save(t)
+ ScanForegroundService.refreshLink(this@SentinelLinkActivity)
+ refresh()
+ }
+ setOnFocusChangeListener { _, focused -> if (!focused) commit() }
+ setOnEditorActionListener { v, _, _ -> commit(); v.clearFocus(); false }
+ }
+ return listOf(l, e)
+ }
+ val ctx = this
+ val views = field("Broker", "mqtts://broker.example.com:8883", LinkStore.mqttBroker(ctx), false) { LinkStore.setMqttBroker(ctx, it) } +
+ field("Username", "Optional", LinkStore.mqttUser(ctx), false) { LinkStore.setMqttUser(ctx, it) } +
+ field("Password", "Optional", LinkStore.mqttPassword(ctx).orEmpty(), true) { LinkStore.setMqttPassword(ctx, it) }
+ mqttStatus = TextView(this).apply { textSize = 14f; setPadding(0, pad(8), 0, 0) }
+ return LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(header); addView(about); addView(switch)
+ views.forEach { addView(it) }
+ addView(mqttStatus)
+ setPadding(0, 0, 0, pad(12))
+ }
+ }
+
/** Lists the Meshtastic nodes nearby; the one tapped is paired (Android asks for its PIN) and used. */
private fun chooseNode() = withPermission {
val names = ArrayList<String>()
@@ -312,6 +379,15 @@ class SentinelLinkActivity : AppCompatActivity() {
share.visibility = if (grouped) View.VISIBLE else View.GONE
leave.visibility = if (grouped) View.VISIBLE else View.GONE
meshSection.visibility = if (grouped) View.VISIBLE else View.GONE
+ mqttSection.visibility = if (grouped) View.VISIBLE else View.GONE
+ mqttStatus.text = when {
+ !LinkStore.mqttOn(this) -> "Off"
+ LinkStore.mqttBroker(this).isBlank() -> "Set the broker"
+ MqttRelay.parse(LinkStore.mqttBroker(this)) == null -> "Not a broker address: mqtts://host or mqtt://host:port"
+ !ScanForegroundService.isRunning || !LinkStore.enabled(this) -> "Starts with sharing, while scanning"
+ else -> MqttRelay.status.ifBlank { "Starting…" } +
+ (MqttRelay.lastSent.takeIf { it > 0 }?.let { " · sent " + DateUtils.getRelativeTimeSpanString(it, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS) } ?: "")
+ }
meshNodeText.text = LinkStore.meshNodeName(this)?.let { "Node: $it" } ?: "No node chosen yet"
meshStatus.text = when {
!LinkStore.meshOn(this) -> "Off"
@@ -335,10 +411,13 @@ class SentinelLinkActivity : AppCompatActivity() {
for (m in members) {
val heard = PhoneLink.lastHeard[m.id]
val overMesh = PhoneLink.lastHeardMesh[m.id]
+ val overNet = PhoneLink.lastHeardNet[m.id]
val detail = when {
linked.containsKey(m.id) -> "Linked now"
overMesh != null && overMesh == heard ->
"Over the mesh · last heard " + DateUtils.getRelativeTimeSpanString(overMesh, now, DateUtils.MINUTE_IN_MILLIS)
+ overNet != null && overNet == heard ->
+ "Over the internet relay · last heard " + DateUtils.getRelativeTimeSpanString(overNet, now, DateUtils.MINUTE_IN_MILLIS)
heard != null -> "Last heard " + DateUtils.getRelativeTimeSpanString(heard, now, DateUtils.MINUTE_IN_MILLIS)
else -> "Not in reach"
}
diff --git a/app/src/test/java/com/rfsentinel/app/link/MqttCodecTest.kt b/app/src/test/java/com/rfsentinel/app/link/MqttCodecTest.kt
new file mode 100644
index 0000000..1ba9999
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/link/MqttCodecTest.kt
@@ -0,0 +1,57 @@
+package com.rfsentinel.app.link
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.DataInputStream
+
+class MqttCodecTest {
+
+ private fun read(bytes: ByteArray) = MqttCodec.read(DataInputStream(ByteArrayInputStream(bytes)))
+
+ @Test
+ fun connectWithLogin() {
+ val p = MqttCodec.connect("rfs-1", "u", "pw", 60)
+ // 0x10, length, "MQTT", level 4, flags user+password+clean, keepalive 60, then the strings.
+ val expected = byteArrayOf(0x10, 24, 0, 4, 'M'.code.toByte(), 'Q'.code.toByte(), 'T'.code.toByte(), 'T'.code.toByte(), 4, 0xC2.toByte(), 0, 60,
+ 0, 5, 'r'.code.toByte(), 'f'.code.toByte(), 's'.code.toByte(), '-'.code.toByte(), '1'.code.toByte(),
+ 0, 1, 'u'.code.toByte(), 0, 2, 'p'.code.toByte(), 'w'.code.toByte())
+ assertArrayEquals(expected, p)
+ assertEquals(0x02, MqttCodec.connect("x", null, "ignored", 60)[9].toInt()) // no user: no password either
+ }
+
+ @Test
+ fun publishRoundTripsWithLongLength() {
+ val payload = ByteArray(300) { it.toByte() }
+ val p = read(MqttCodec.publish("rfsentinel/ab", payload))
+ assertEquals(MqttCodec.PUBLISH, p.type)
+ val (topic, data) = MqttCodec.payload(p)!!
+ assertEquals("rfsentinel/ab", topic)
+ assertArrayEquals(payload, data)
+ }
+
+ @Test
+ fun qos1PublishSkipsItsPacketId() {
+ // Topic "t", packet id 0x0001, payload 0xAA.
+ val p = read(byteArrayOf(0x32, 6, 0, 1, 't'.code.toByte(), 0, 1, 0xAA.toByte()))
+ assertArrayEquals(byteArrayOf(0xAA.toByte()), MqttCodec.payload(p)!!.second)
+ }
+
+ @Test
+ fun brokerAddresses() {
+ assertEquals(MqttRelay.Broker(true, "example.org", 8883), MqttRelay.parse("example.org"))
+ assertEquals(MqttRelay.Broker(false, "10.0.0.5", 1883), MqttRelay.parse(" mqtt://10.0.0.5 "))
+ assertEquals(MqttRelay.Broker(true, "h.net", 9000), MqttRelay.parse("mqtts://h.net:9000"))
+ assertEquals(null, MqttRelay.parse("http://h.net"))
+ assertEquals(null, MqttRelay.parse(""))
+ }
+
+ @Test
+ fun topicIsStableAndGroupSpecific() {
+ val a = MqttRelay.topic(ByteArray(32) { 1 })
+ assertEquals(a, MqttRelay.topic(ByteArray(32) { 1 }))
+ assertEquals(27, a.length)
+ assert(a != MqttRelay.topic(ByteArray(32) { 2 }))
+ }
+}