From 97d881e1c360ac9fb9d9a737aec97053a9e9fcf7 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:00 -0700 Subject: [PATCH 01/12] feat(rnode): save a chosen Bluetooth RNode by device id Derive an RNode's connection type from its saved value, tell a device id from a device name by format, and keep the chosen device's name and whether Starling paired it in two optional fields appended to the interface record. Older six-field records still load. A name saved by an older version is upgraded to the device id after a successful connection. A bare ble:// is never pinned to a device. --- .../Starling/ChatStatePersistence.kt | 3 + .../com/sidpatchy/Starling/RNodeConnection.kt | 395 ++++++++++++++++++ .../sidpatchy/Starling/ReticulumTransport.kt | 26 +- 3 files changed, 419 insertions(+), 5 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ChatStatePersistence.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ChatStatePersistence.kt index 24e7524..d77367b 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ChatStatePersistence.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ChatStatePersistence.kt @@ -76,6 +76,7 @@ object ChatStateCodec { appendRecord( "I", radio.port, radio.frequencyHz.toString(), radio.bandwidthHz.toString(), radio.txPowerDbm.toString(), radio.spreadingFactor.toString(), radio.codingRate.toString(), + radio.bleName.orEmpty(), radio.pairedByStarling.bit(), ) } } @@ -172,6 +173,8 @@ object ChatStateCodec { txPowerDbm = decoded[3].toIntOrNull() ?: 0, spreadingFactor = decoded[4].toIntOrNull() ?: 0, codingRate = decoded[5].toIntOrNull() ?: 0, + bleName = decoded.getOrNull(6)?.ifBlank { null }, + pairedByStarling = decoded.getOrNull(7) == "1", ) } "N" -> if (decoded.size >= 3 && decoded[0].isNotBlank() && decoded[2].isNotBlank()) { diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt new file mode 100644 index 0000000..95dcbd5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt @@ -0,0 +1,395 @@ +package com.sidpatchy.Starling + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow + +const val RNODE_BLE_PREFIX = "ble://" +const val RNODE_TCP_PREFIX = "tcp://" + +/** How an RNode is attached. It is derived from the saved connection, never stored. */ +enum class RNodeConnectionType { BLUETOOTH, WIFI, SERIAL } + +/** The connection type a saved value describes, by its prefix alone. */ +fun rnodeConnectionType(port: String): RNodeConnectionType { + val trimmed = port.trim() + return when { + trimmed.startsWith(RNODE_BLE_PREFIX, ignoreCase = true) -> RNodeConnectionType.BLUETOOTH + trimmed.startsWith(RNODE_TCP_PREFIX, ignoreCase = true) -> RNodeConnectionType.WIFI + else -> RNodeConnectionType.SERIAL + } +} + +/** + * The connection type the editor shows. Phones have no serial ports, so a + * value without a prefix is a Bluetooth RNode that has not been chosen yet; + * desktop never offers Bluetooth. + */ +fun rnodeEditorConnectionType(port: String, supportsBleRNodes: Boolean): RNodeConnectionType = + when (rnodeConnectionType(port)) { + RNodeConnectionType.WIFI -> RNodeConnectionType.WIFI + else -> if (supportsBleRNodes) RNodeConnectionType.BLUETOOTH else RNodeConnectionType.SERIAL + } + +/** The saved value for a connection type with nothing entered or chosen yet. */ +fun rnodeEmptyPort(type: RNodeConnectionType): String = + if (type == RNodeConnectionType.WIFI) RNODE_TCP_PREFIX else "" + +/** The host part of a Wi-Fi RNode value. */ +fun rnodeWifiHost(port: String): String { + val trimmed = port.trim() + return if (trimmed.startsWith(RNODE_TCP_PREFIX, ignoreCase = true)) trimmed.drop(RNODE_TCP_PREFIX.length) else "" +} + +/** What follows `ble://`: a device id, a device name, or nothing. */ +fun rnodeBleTarget(port: String): String { + val trimmed = port.trim() + return if (trimmed.startsWith(RNODE_BLE_PREFIX, ignoreCase = true)) trimmed.drop(RNODE_BLE_PREFIX.length).trim() else "" +} + +enum class RNodeBleTargetKind { + /** A bare `ble://`: the first RNode found. */ + ANY, + + /** A platform device id: a Bluetooth address on Android, a peripheral UUID on iOS. */ + ID, + + /** An advertised device name saved by an older version. */ + NAME, +} + +/** Tells a saved device id from a device name by its format. */ +fun rnodeBleTargetKind(target: String): RNodeBleTargetKind { + val trimmed = target.trim() + return when { + trimmed.isEmpty() -> RNodeBleTargetKind.ANY + isBleDeviceId(trimmed) -> RNodeBleTargetKind.ID + else -> RNodeBleTargetKind.NAME + } +} + +fun isBleDeviceId(value: String): Boolean = isBleMacAddress(value) || isBlePeripheralUuid(value) + +/** True for a colon-separated 48-bit Bluetooth address. */ +private fun isBleMacAddress(value: String): Boolean { + val octets = value.trim().split(":") + return octets.size == 6 && octets.all { it.length == 2 && it.toIntOrNull(16) != null } +} + +/** True for the 8-4-4-4-12 hexadecimal form CoreBluetooth uses for peripherals. */ +fun isBlePeripheralUuid(value: String): Boolean { + val groups = value.trim().split("-") + if (groups.map { it.length } != listOf(8, 4, 4, 4, 12)) return false + return groups.all { group -> group.all { it.digitToIntOrNull(16) != null } } +} + +/** The saved value for a chosen Bluetooth device. */ +fun rnodeBlePort(deviceId: String): String = RNODE_BLE_PREFIX + deviceId.trim() + +/** A name for an RNode that never exposes a peripheral UUID or a URL-style value. */ +fun rnodeDisplayName(radio: ReticulumRNodeInterface): String = when (rnodeConnectionType(radio.port)) { + RNodeConnectionType.BLUETOOTH -> { + val target = rnodeBleTarget(radio.port) + radio.bleName?.takeIf(String::isNotBlank) + ?: target.takeIf { rnodeBleTargetKind(it) == RNodeBleTargetKind.NAME } + ?: "Bluetooth RNode" + } + RNodeConnectionType.WIFI -> rnodeWifiHost(radio.port).ifBlank { "Wi-Fi RNode" } + RNodeConnectionType.SERIAL -> radio.port.trim() +} + +/** How node-start messages refer to a Bluetooth RNode. */ +fun rnodeBleLabel(port: String, bleName: String?): String { + val target = rnodeBleTarget(port) + return bleName?.trim()?.takeIf(String::isNotEmpty) + ?: target.takeIf { rnodeBleTargetKind(it) == RNodeBleTargetKind.NAME } + ?: RNodeBleText.FALLBACK_NAME +} + +/** The device a Bluetooth RNode bridge connected to at node start. */ +data class ResolvedBleRNode(val id: String, val name: String) + +/** The outcome of matching a connected device against a saved RNode. */ +data class RNodeBleUpgrade(val radio: ReticulumRNodeInterface, val note: String?) + +/** + * Brings a saved Bluetooth RNode up to date after a successful connection. + * + * A device name saved by an older version becomes the device id, with the + * name kept for display. A saved id only gains a missing name. A bare + * `ble://` is left alone: it means "the first RNode found" and is never + * pinned to a device without the user choosing it. Radio parameters are + * never changed. Returns null when there is nothing to change. + */ +fun upgradeRNodeBleInterface(radio: ReticulumRNodeInterface, resolved: ResolvedBleRNode): RNodeBleUpgrade? { + if (rnodeConnectionType(radio.port) != RNodeConnectionType.BLUETOOTH) return null + val id = resolved.id.trim() + if (!isBleDeviceId(id)) return null + val target = rnodeBleTarget(radio.port) + val name = resolved.name.trim() + return when (rnodeBleTargetKind(target)) { + RNodeBleTargetKind.ANY -> null + RNodeBleTargetKind.NAME -> { + val savedName = name.ifBlank { target } + RNodeBleUpgrade( + radio.copy(port = rnodeBlePort(id), bleName = savedName), + "Saved $savedName as your radio.", + ) + } + RNodeBleTargetKind.ID -> + if (!target.equals(id, ignoreCase = true) || name.isBlank() || !radio.bleName.isNullOrBlank()) null + else RNodeBleUpgrade(radio.copy(bleName = name), null) + } +} + +/** Applies [upgradeRNodeBleInterface] to the one Bluetooth RNode a node can have. */ +fun upgradeRNodeBleInterfaces( + radios: List, + resolved: ResolvedBleRNode, +): Pair, String?>? { + var note: String? = null + var changed = false + val upgraded = radios.map { radio -> + val upgrade = if (changed) null else upgradeRNodeBleInterface(radio, resolved) + if (upgrade == null) radio else { + changed = true + note = upgrade.note + upgrade.radio + } + } + return if (changed) upgraded to note else null +} + +/** Signal strength as one of four levels, weakest first. */ +enum class RNodeSignalLevel(val bars: Int, val label: String) { + WEAK(1, "Weak signal"), + FAIR(2, "Fair signal"), + GOOD(3, "Good signal"), + STRONG(4, "Strong signal"), +} + +fun rnodeSignalLevel(rssi: Int): RNodeSignalLevel = when { + rssi >= -60 -> RNodeSignalLevel.STRONG + rssi >= -70 -> RNodeSignalLevel.GOOD + rssi >= -80 -> RNodeSignalLevel.FAIR + else -> RNodeSignalLevel.WEAK +} + +/** One advertisement seen while searching for RNodes. */ +data class RNodeBleSighting(val id: String, val name: String, val rssi: Int) + +data class RNodeScanRow( + val id: String, + val name: String, + val rssi: Int, + /** The saved device, or one already paired with this phone. */ + val pinned: Boolean, + /** The last four characters of the id, set when another row has the same name. */ + val idSuffix: String?, +) + +/** + * The rows of the search dialog. + * + * Devices are told apart by platform id, never by name. Pinned devices come + * first, then stronger signals, then names. Once the search has run for + * [freezeAfterMillis] the order stops changing so a row cannot move under a + * finger: signal updates in place and later devices are added at the end. + * A new search keeps the previous rows for [staleAfterMillis] and then drops + * the ones that were not seen again. Not thread-safe. + */ +class RNodeScanList( + private val freezeAfterMillis: Long = 3_000, + private val staleAfterMillis: Long = 2_000, +) { + private class Entry(var name: String, var rssi: Int, var pinned: Boolean, var lastSeenAt: Long) + + private val entries = linkedMapOf() + private var firstSearchAt: Long? = null + private var searchAt: Long? = null + private var frozenOrder: MutableList? = null + + /** Marks the start of a search, the first or a repeated one. */ + fun beginSearch(nowMillis: Long) { + if (firstSearchAt == null) firstSearchAt = nowMillis + searchAt = nowMillis + } + + fun observe(sighting: RNodeBleSighting, pinned: Boolean, nowMillis: Long) { + val key = sighting.id.trim().uppercase() + if (key.isEmpty()) return + val entry = entries[key] + if (entry == null) { + entries[key] = Entry(sighting.name.trim(), sighting.rssi, pinned, nowMillis) + } else { + // Some advertisements omit the name; keep the one already seen. + if (sighting.name.isNotBlank()) entry.name = sighting.name.trim() + entry.rssi = sighting.rssi + entry.pinned = pinned + entry.lastSeenAt = nowMillis + } + } + + fun rows(nowMillis: Long): List { + val searchStart = searchAt + if (searchStart != null && nowMillis - searchStart >= staleAfterMillis) { + val stale = entries.filterValues { it.lastSeenAt < searchStart }.keys.toList() + stale.forEach(entries::remove) + frozenOrder?.removeAll(stale) + } + val first = firstSearchAt + val order = if (first == null || nowMillis - first < freezeAfterMillis) { + sortedIds(entries.keys) + } else { + val frozen = frozenOrder ?: sortedIds(entries.keys).toMutableList().also { frozenOrder = it } + frozen += sortedIds(entries.keys.filter { it !in frozen }) + frozen + } + val sharedNames = entries.values.groupingBy { it.name.lowercase() }.eachCount().filterValues { it > 1 }.keys + return order.mapNotNull { id -> + val entry = entries[id] ?: return@mapNotNull null + RNodeScanRow( + id = id, + name = entry.name, + rssi = entry.rssi, + pinned = entry.pinned, + idSuffix = if (entry.name.lowercase() in sharedNames) id.takeLast(4) else null, + ) + } + } + + private fun sortedIds(ids: Collection): List = ids.sortedWith( + compareByDescending { entries.getValue(it).pinned } + .thenByDescending { entries.getValue(it).rssi } + .thenBy { entries.getValue(it).name.lowercase() } + .thenBy { it }, + ) +} + +/** + * How long to wait before starting another search. Android silently returns + * nothing once an app starts more than [maxStarts] searches in [windowMillis], + * so the last allowed start is held back until the oldest one leaves the window. + */ +fun rnodeScanStartDelayMillis( + previousStartsMillis: List, + nowMillis: Long, + maxStarts: Int = 4, + windowMillis: Long = 30_000, +): Long { + val recent = previousStartsMillis.filter { nowMillis - it < windowMillis }.sorted() + if (recent.size < maxStarts) return 0 + return (recent[recent.size - maxStarts] + windowMillis - nowMillis).coerceAtLeast(0) +} + +enum class RNodeBlePlatform { ANDROID, IOS } + +sealed interface RNodeBleScanStatus { + data object Idle : RNodeBleScanStatus + data object Scanning : RNodeBleScanStatus + + /** The search ran its time or was stopped. */ + data object Finished : RNodeBleScanStatus + data object BluetoothOff : RNodeBleScanStatus + data object PermissionNotAsked : RNodeBleScanStatus + data object PermissionDenied : RNodeBleScanStatus + data object PermissionPermanentlyDenied : RNodeBleScanStatus + + /** Android 11 and older cannot search with Location turned off. */ + data object LocationOff : RNodeBleScanStatus + data class Failed(val code: Int) : RNodeBleScanStatus + data object Unsupported : RNodeBleScanStatus +} + +enum class RNodeBlePairingFailure { WRONG_PIN, TIMEOUT, STALE_BOND, OTHER } + +/** Progress of pairing on Android, or of the first trial connection on iOS. */ +sealed interface RNodeBlePairingState { + data object Idle : RNodeBlePairingState + data class Waiting(val name: String) : RNodeBlePairingState + data class AlreadyPaired(val name: String) : RNodeBlePairingState + data class Paired(val name: String) : RNodeBlePairingState + + /** The RNode accepted a connection without a new pairing. */ + data class Ready(val name: String) : RNodeBlePairingState + data class Failed(val name: String, val reason: RNodeBlePairingFailure, val code: Int = 0) : RNodeBlePairingState +} + +/** Platform Bluetooth access for choosing an RNode in Settings. */ +interface RNodeBlePicker { + val platform: RNodeBlePlatform + val scanStatus: StateFlow + val sightings: Flow + val pairing: StateFlow + + /** Asks for whatever access is missing, then searches for about 20 seconds. */ + fun startScan() + fun stopScan() + + /** Acts on the current blocking status: ask again, turn Bluetooth on, or open system settings. */ + fun resolveScanBlocker() + + fun pair(deviceId: String, name: String) + fun cancelPairing() + + /** Whether the system has a pairing for this device, or null when that cannot be known. */ + fun isPaired(deviceId: String): Boolean? + + /** The system's name for a device it already knows. */ + fun knownName(deviceId: String): String? = null + fun openBluetoothSettings() = Unit +} + +/** User-facing text for the Bluetooth RNode picker and node start. */ +object RNodeBleText { + const val CHOOSE_BEFORE_START = "Choose an RNode for this interface before starting the node." + const val FALLBACK_NAME = "the RNode" + + fun scanStatusMessage(status: RNodeBleScanStatus, platform: RNodeBlePlatform, hasRows: Boolean): String? = when (status) { + RNodeBleScanStatus.Idle -> null + RNodeBleScanStatus.Scanning -> if (hasRows) "Searching..." else "Searching for RNodes..." + RNodeBleScanStatus.Finished -> if (hasRows) null else + "No RNodes found. Make sure it is powered on with Bluetooth enabled, and keep it within a few metres. " + + "An RNode that is already connected to another phone will not appear." + RNodeBleScanStatus.BluetoothOff -> + if (platform == RNodeBlePlatform.IOS) "Bluetooth is turned off. Turn on Bluetooth in Control Center or Settings." + else "Bluetooth is turned off." + RNodeBleScanStatus.PermissionNotAsked -> "Starling needs permission to find nearby devices." + RNodeBleScanStatus.PermissionDenied -> "Starling can't search without Bluetooth permission." + RNodeBleScanStatus.PermissionPermanentlyDenied -> + "Bluetooth permission is turned off for Starling. Turn it on in system settings." + RNodeBleScanStatus.LocationOff -> + "Android needs Location turned on to search for Bluetooth devices. Starling does not use your location." + is RNodeBleScanStatus.Failed -> "Bluetooth search failed (code ${status.code}). Try again." + RNodeBleScanStatus.Unsupported -> "This device doesn't support Bluetooth LE." + } + + /** The label of the button that resolves a blocking status, if it has one. */ + fun scanBlockerAction(status: RNodeBleScanStatus, platform: RNodeBlePlatform): String? = when (status) { + RNodeBleScanStatus.BluetoothOff -> if (platform == RNodeBlePlatform.ANDROID) "Turn on Bluetooth" else null + RNodeBleScanStatus.PermissionNotAsked, RNodeBleScanStatus.PermissionDenied -> "Allow" + RNodeBleScanStatus.PermissionPermanentlyDenied -> "Open settings" + RNodeBleScanStatus.LocationOff -> "Open location settings" + else -> null + } + + fun pairingFailureMessage(failure: RNodeBlePairingState.Failed, platform: RNodeBlePlatform): String = when { + failure.reason == RNodeBlePairingFailure.STALE_BOND -> + "This RNode no longer recognises this iPhone. Remove it in Settings > Bluetooth (if listed) and clear " + + "paired devices on the RNode, then try again." + platform == RNodeBlePlatform.IOS -> + "iOS didn't finish pairing. Try again and, if asked, enter the PIN shown on the RNode." + failure.reason == RNodeBlePairingFailure.WRONG_PIN -> + "The PIN didn't match. Try again and enter the PIN currently shown on the RNode." + failure.reason == RNodeBlePairingFailure.TIMEOUT -> "Pairing timed out. Wake the RNode's screen, then try again." + else -> "Pairing didn't complete (reason ${failure.code}). Try again." + } + + fun notFound(name: String) = "Couldn't reach $name. Check that it's powered on and in range, then try again." + fun notPairedAndroid(name: String) = "$name isn't paired with this phone. Open Settings, choose Change, and pair it." + fun notPairedIos(name: String) = + "$name didn't accept the connection. Open Settings and reconnect it, entering the PIN shown on the RNode if asked." + fun pairingLost(name: String) = "Pairing with $name was removed. Open Settings, choose Change, and pair it again." + fun permission(name: String) = "Allow Starling Bluetooth access to connect to $name." + fun heldElsewhere(name: String) = "$name may be connected to another device. Disconnect it there and try again." + fun unknownToIos(name: String) = "iOS no longer knows $name. Choose it again in Settings." +} diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ReticulumTransport.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ReticulumTransport.kt index 4fd2ad7..f791fb4 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ReticulumTransport.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/ReticulumTransport.kt @@ -37,12 +37,19 @@ data class ReticulumRNodeInterface( val txPowerDbm: Int, val spreadingFactor: Int, val codingRate: Int, + /** The advertised name of a chosen Bluetooth RNode, kept for display. */ + val bleName: String? = null, + /** True when Starling created this phone's pairing with the Bluetooth RNode. */ + val pairedByStarling: Boolean = false, ) { val id: String get() = port.trim().lowercase() - fun validationError(): String? = when { - port.isBlank() -> "Enter a serial port, tcp://host, or ble://device name." + /** [supportsBleRNodes] is true on phones, where a blank connection is an unchosen Bluetooth RNode. */ + fun validationError(supportsBleRNodes: Boolean = false): String? = when { + port.isBlank() -> if (supportsBleRNodes) RNodeBleText.CHOOSE_BEFORE_START else "Enter the RNode's serial port." port.any { it.code < 32 || it.code == 127 } -> "The RNode connection cannot contain control characters." + rnodeConnectionType(port) == RNodeConnectionType.WIFI && rnodeWifiHost(port).isBlank() -> + "Enter the RNode's host name or IP address." frequencyHz !in 137_000_000L..3_000_000_000L -> "RNode frequency must be between 137 MHz and 3 GHz." bandwidthHz !in 7_800..1_625_000 -> "RNode bandwidth must be between 7.8 kHz and 1.625 MHz." txPowerDbm !in 0..37 -> "RNode transmit power must be between 0 and 37 dBm." @@ -58,7 +65,7 @@ data class ReticulumNodeConfig( val rnodeInterfaces: List = emptyList(), val existingInstanceRpcKeyHex: String? = null, ) { - fun validationError(): String? { + fun validationError(supportsBleRNodes: Boolean = false): String? { if (mode == ReticulumRuntimeMode.EXISTING_SHARED_INSTANCE && !isValidReticulumRpcKey(existingInstanceRpcKeyHex.orEmpty())) { return "Enter the existing local RNS instance's RPC key as at least 32 hexadecimal characters." } @@ -86,8 +93,8 @@ data class ReticulumNodeConfig( return "For each peer, enter both IFAC values or leave both blank." } } - val invalidRNode = rnodeInterfaces.firstOrNull { it.validationError() != null } - if (invalidRNode != null) return invalidRNode.validationError() + val invalidRNode = rnodeInterfaces.firstOrNull { it.validationError(supportsBleRNodes) != null } + if (invalidRNode != null) return invalidRNode.validationError(supportsBleRNodes) if (rnodeInterfaces.map { it.id }.distinct().size != rnodeInterfaces.size) { return "Each RNode interface must use a unique connection." } @@ -128,11 +135,20 @@ interface ReticulumNodeController { val supportsReticulumProtocol: Boolean get() = true /** Whether this platform exposes RNode connection settings. */ val supportsRNodeInterfaces: Boolean get() = false + /** Whether this platform reaches RNodes over Bluetooth LE rather than a serial port. */ + val supportsBleRNodes: Boolean get() = false + /** Finds and pairs Bluetooth RNodes for Settings; null where [supportsBleRNodes] is false. */ + val rnodeBlePicker: RNodeBlePicker? get() = null + /** The Bluetooth RNode the running node connected to, once known. */ + val resolvedBleRNode: StateFlow get() = NO_RESOLVED_BLE_RNODE suspend fun start(config: ReticulumNodeConfig) suspend fun disconnect() suspend fun refreshState() = Unit } +private val NO_RESOLVED_BLE_RNODE: StateFlow = + kotlinx.coroutines.flow.MutableStateFlow(null) + class UnsupportedReticulumNodeController(reason: String) : ReticulumNodeController { private val _state = kotlinx.coroutines.flow.MutableStateFlow(ReticulumNodeState.Unavailable(reason)) override val state: StateFlow = _state From a13ef1b261d894ffb5986b0d3bf6d0770187e588 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:00 -0700 Subject: [PATCH 02/12] test(rnode): cover connection types, migration and scan rows Covers prefix-derived connection types, id and name detection, the legacy-name upgrade, persistence with and without the appended fields, scan-row sorting, de-duplication and freezing, signal labels and the validation and picker messages. --- .../sidpatchy/Starling/RNodeConnectionTest.kt | 358 ++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt diff --git a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt new file mode 100644 index 0000000..cee34f8 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt @@ -0,0 +1,358 @@ +package com.sidpatchy.Starling + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class RNodeConnectionTest { + private val radio = ReticulumRNodeInterface("", 915_000_000L, 125_000, 17, 7, 5) + private val address = "AA:BB:CC:DD:EE:FF" + private val uuid = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" + + @Test + fun connectionTypeComesFromThePrefix() { + assertEquals(RNodeConnectionType.BLUETOOTH, rnodeConnectionType("ble://RNode A1B2")) + assertEquals(RNodeConnectionType.BLUETOOTH, rnodeConnectionType(" BLE://")) + assertEquals(RNodeConnectionType.WIFI, rnodeConnectionType("tcp://rnode.local")) + assertEquals(RNodeConnectionType.WIFI, rnodeConnectionType("TCP://")) + assertEquals(RNodeConnectionType.SERIAL, rnodeConnectionType("/dev/ttyUSB0")) + assertEquals(RNodeConnectionType.SERIAL, rnodeConnectionType("COM3")) + assertEquals(RNodeConnectionType.SERIAL, rnodeConnectionType("")) + } + + @Test + fun editorDefaultsToBluetoothOnPhonesAndSerialOnDesktop() { + assertEquals(RNodeConnectionType.BLUETOOTH, rnodeEditorConnectionType("", supportsBleRNodes = true)) + assertEquals(RNodeConnectionType.SERIAL, rnodeEditorConnectionType("", supportsBleRNodes = false)) + assertEquals(RNodeConnectionType.WIFI, rnodeEditorConnectionType("tcp://", supportsBleRNodes = true)) + assertEquals(RNodeConnectionType.WIFI, rnodeEditorConnectionType("tcp://10.0.0.5", supportsBleRNodes = false)) + assertEquals(RNodeConnectionType.BLUETOOTH, rnodeEditorConnectionType("ble://$address", supportsBleRNodes = true)) + // Desktop never offers Bluetooth. + assertEquals(RNodeConnectionType.SERIAL, rnodeEditorConnectionType("ble://$address", supportsBleRNodes = false)) + } + + @Test + fun switchingTypeClearsOnlyTheConnection() { + assertEquals("tcp://", rnodeEmptyPort(RNodeConnectionType.WIFI)) + assertEquals("", rnodeEmptyPort(RNodeConnectionType.BLUETOOTH)) + assertEquals("", rnodeEmptyPort(RNodeConnectionType.SERIAL)) + assertEquals("rnode.local", rnodeWifiHost("tcp://rnode.local")) + assertEquals("", rnodeWifiHost("/dev/ttyUSB0")) + } + + @Test + fun deviceIdsAreToldFromNamesByFormat() { + assertEquals(RNodeBleTargetKind.ANY, rnodeBleTargetKind(rnodeBleTarget("ble://"))) + assertEquals(RNodeBleTargetKind.ANY, rnodeBleTargetKind(rnodeBleTarget("ble:// "))) + assertEquals(RNodeBleTargetKind.ID, rnodeBleTargetKind(rnodeBleTarget("ble://$address"))) + assertEquals(RNodeBleTargetKind.ID, rnodeBleTargetKind(rnodeBleTarget("ble://aa:bb:cc:dd:ee:ff"))) + assertEquals(RNodeBleTargetKind.ID, rnodeBleTargetKind(rnodeBleTarget("ble://$uuid"))) + assertEquals(RNodeBleTargetKind.ID, rnodeBleTargetKind(rnodeBleTarget("ble://${uuid.lowercase()}"))) + assertEquals(RNodeBleTargetKind.NAME, rnodeBleTargetKind(rnodeBleTarget("ble://RNode A1B2"))) + assertEquals(RNodeBleTargetKind.NAME, rnodeBleTargetKind("AA:BB:CC:DD:EE")) + assertEquals(RNodeBleTargetKind.NAME, rnodeBleTargetKind("AA-BB-CC-DD-EE-FF")) + assertEquals(RNodeBleTargetKind.NAME, rnodeBleTargetKind("6E400001-B5A3-F393-E0A9-E50E24DCCA9")) + assertEquals(RNodeBleTargetKind.NAME, rnodeBleTargetKind("6E400001-B5A3-F393-E0A9-E50E24DCCAZZ")) + assertTrue(isBlePeripheralUuid(uuid)) + assertFalse(isBlePeripheralUuid(address)) + assertEquals("", rnodeBleTarget("tcp://host")) + } + + @Test + fun legacyNameIsUpgradedToTheDeviceIdAfterAConnection() { + val legacy = radio.copy(port = "ble://RNode A1B2") + + val upgrade = assertNotNull(upgradeRNodeBleInterface(legacy, ResolvedBleRNode(address, "RNode A1B2"))) + + assertEquals("ble://$address", upgrade.radio.port) + assertEquals("RNode A1B2", upgrade.radio.bleName) + assertEquals("Saved RNode A1B2 as your radio.", upgrade.note) + // Radio parameters and the pairing record are never touched. + assertEquals(legacy.copy(port = upgrade.radio.port, bleName = upgrade.radio.bleName), upgrade.radio) + assertFalse(upgrade.radio.pairedByStarling) + } + + @Test + fun legacyNameIsKeptWhenTheDeviceReportsNoName() { + val upgrade = assertNotNull( + upgradeRNodeBleInterface(radio.copy(port = "ble://RNode A1B2"), ResolvedBleRNode(uuid, "")), + ) + + assertEquals("ble://$uuid", upgrade.radio.port) + assertEquals("RNode A1B2", upgrade.radio.bleName) + } + + @Test + fun bareBleIsNeverPinnedAutomatically() { + assertNull(upgradeRNodeBleInterface(radio.copy(port = "ble://"), ResolvedBleRNode(address, "RNode A1B2"))) + } + + @Test + fun savedDeviceIdIsUnchangedAndOnlyGainsAMissingName() { + val saved = radio.copy(port = "ble://$address") + + val named = assertNotNull(upgradeRNodeBleInterface(saved, ResolvedBleRNode(address.lowercase(), "RNode A1B2"))) + assertEquals(saved.copy(bleName = "RNode A1B2"), named.radio) + assertNull(named.note) + + assertNull(upgradeRNodeBleInterface(named.radio, ResolvedBleRNode(address, "Renamed"))) + assertNull(upgradeRNodeBleInterface(saved, ResolvedBleRNode(address, ""))) + assertNull(upgradeRNodeBleInterface(saved, ResolvedBleRNode("11:22:33:44:55:66", "Other"))) + } + + @Test + fun otherConnectionsAndMalformedIdsAreNotUpgraded() { + val resolved = ResolvedBleRNode(address, "RNode A1B2") + + assertNull(upgradeRNodeBleInterface(radio.copy(port = "tcp://rnode.local"), resolved)) + assertNull(upgradeRNodeBleInterface(radio.copy(port = "/dev/ttyUSB0"), resolved)) + assertNull(upgradeRNodeBleInterface(radio.copy(port = "ble://RNode A1B2"), ResolvedBleRNode("not an id", "x"))) + } + + @Test + fun upgradeAppliesToTheBluetoothRNodeInAList() { + val wifi = radio.copy(port = "tcp://rnode.local") + val legacy = radio.copy(port = "ble://RNode A1B2", frequencyHz = 868_000_000L) + + val (radios, note) = assertNotNull( + upgradeRNodeBleInterfaces(listOf(wifi, legacy), ResolvedBleRNode(address, "RNode A1B2")), + ) + + assertEquals(listOf(wifi, legacy.copy(port = "ble://$address", bleName = "RNode A1B2")), radios) + assertEquals("Saved RNode A1B2 as your radio.", note) + assertNull(upgradeRNodeBleInterfaces(radios, ResolvedBleRNode(address, "RNode A1B2"))) + assertNull(upgradeRNodeBleInterfaces(listOf(wifi), ResolvedBleRNode(address, "RNode A1B2"))) + } + + @Test + fun bluetoothFieldsSurviveARoundTrip() { + val config = ReticulumNodeConfig( + rnodeInterfaces = listOf( + radio.copy(port = "ble://$address", bleName = "RNode A1B2", pairedByStarling = true), + radio.copy(port = "tcp://rnode.local"), + ), + ) + + val decoded = ChatStateCodec.decode(ChatStateCodec.encode(PersistedChatState(nodeConfig = config))) + + assertEquals(config, decoded?.nodeConfig) + } + + @Test + fun recordsWithoutBluetoothFieldsStillLoad() { + fun record(kind: String, vararg values: String) = + (listOf(kind) + values.map { Base64TextCodec.encode(it) }).joinToString("\t") + val saved = listOf( + "STARLING_CHAT_STATE_V13", + record("V", ReticulumRuntimeMode.EMBEDDED.name), + record("I", "ble://RNode A1B2", "915000000", "125000", "17", "7", "5"), + ).joinToString("\n") + + val loaded = ChatStateCodec.decode(saved)?.nodeConfig?.rnodeInterfaces + + assertEquals(listOf(radio.copy(port = "ble://RNode A1B2")), loaded) + assertNull(loaded?.single()?.bleName) + assertEquals(false, loaded?.single()?.pairedByStarling) + } + + @Test + fun scanRowsAreDedupedByIdAndSortedPinnedThenSignalThenName() { + val list = RNodeScanList() + list.beginSearch(0) + list.observe(RNodeBleSighting("11:11:11:11:11:11", "RNode B", -70), pinned = false, nowMillis = 100) + list.observe(RNodeBleSighting("22:22:22:22:22:22", "RNode A", -70), pinned = false, nowMillis = 100) + list.observe(RNodeBleSighting("33:33:33:33:33:33", "RNode C", -50), pinned = false, nowMillis = 100) + list.observe(RNodeBleSighting("44:44:44:44:44:44", "RNode D", -90), pinned = true, nowMillis = 100) + list.observe(RNodeBleSighting("11:11:11:11:11:11", "RNode B", -72), pinned = false, nowMillis = 200) + + val rows = list.rows(300) + + assertEquals(listOf("RNode D", "RNode C", "RNode A", "RNode B"), rows.map { it.name }) + assertEquals(-72, rows.last().rssi) + assertTrue(rows.first().pinned) + assertTrue(rows.all { it.idSuffix == null }) + } + + @Test + fun sameNameRowsStayApartAndShowTheEndOfTheirId() { + val list = RNodeScanList() + list.beginSearch(0) + list.observe(RNodeBleSighting("AA:BB:CC:DD:11:22", "RNode", -60), pinned = false, nowMillis = 10) + list.observe(RNodeBleSighting("AA:BB:CC:DD:33:44", "rnode", -65), pinned = false, nowMillis = 10) + list.observe(RNodeBleSighting("AA:BB:CC:DD:55:66", "Other", -80), pinned = false, nowMillis = 10) + + val rows = list.rows(20) + + assertEquals(3, rows.size) + assertEquals(listOf("1:22", "3:44", null), rows.map { it.idSuffix }) + } + + @Test + fun aBlankAdvertisedNameDoesNotReplaceAKnownOne() { + val list = RNodeScanList() + list.beginSearch(0) + list.observe(RNodeBleSighting("aa:bb:cc:dd:11:22", "RNode", -60), pinned = false, nowMillis = 10) + list.observe(RNodeBleSighting("AA:BB:CC:DD:11:22", "", -61), pinned = false, nowMillis = 20) + + assertEquals(listOf(RNodeScanRow("AA:BB:CC:DD:11:22", "RNode", -61, false, null)), list.rows(30)) + } + + @Test + fun orderFreezesAfterThreeSecondsAndSignalUpdatesInPlace() { + val list = RNodeScanList() + list.beginSearch(0) + list.observe(RNodeBleSighting("11:11:11:11:11:11", "Near", -50), pinned = false, nowMillis = 100) + list.observe(RNodeBleSighting("22:22:22:22:22:22", "Far", -85), pinned = false, nowMillis = 100) + assertEquals(listOf("Near", "Far"), list.rows(2_999).map { it.name }) + + // Before the freeze a stronger signal still moves a row. + list.observe(RNodeBleSighting("22:22:22:22:22:22", "Far", -40), pinned = false, nowMillis = 2_000) + assertEquals(listOf("Far", "Near"), list.rows(2_999).map { it.name }) + assertEquals(listOf("Far", "Near"), list.rows(3_000).map { it.name }) + + // After it, rows keep their place and later devices go to the end. + list.observe(RNodeBleSighting("11:11:11:11:11:11", "Near", -30), pinned = false, nowMillis = 4_000) + list.observe(RNodeBleSighting("33:33:33:33:33:33", "Late", -20), pinned = true, nowMillis = 4_000) + val rows = list.rows(4_100) + assertEquals(listOf("Far", "Near", "Late"), rows.map { it.name }) + assertEquals(listOf(-40, -30, -20), rows.map { it.rssi }) + } + + @Test + fun aNewSearchKeepsRowsForTwoSecondsThenDropsTheUnseen() { + val list = RNodeScanList() + list.beginSearch(0) + list.observe(RNodeBleSighting("11:11:11:11:11:11", "Stays", -50), pinned = false, nowMillis = 100) + list.observe(RNodeBleSighting("22:22:22:22:22:22", "Gone", -60), pinned = false, nowMillis = 100) + assertEquals(2, list.rows(20_000).size) + + list.beginSearch(30_000) + list.observe(RNodeBleSighting("11:11:11:11:11:11", "Stays", -55), pinned = false, nowMillis = 30_500) + assertEquals(listOf("Stays", "Gone"), list.rows(31_999).map { it.name }) + assertEquals(listOf("Stays"), list.rows(32_000).map { it.name }) + assertEquals(listOf("Stays"), list.rows(40_000).map { it.name }) + } + + @Test + fun signalLevelsHaveFourLabelledBuckets() { + assertEquals("Strong signal", rnodeSignalLevel(-45).label) + assertEquals("Strong signal", rnodeSignalLevel(-60).label) + assertEquals("Good signal", rnodeSignalLevel(-61).label) + assertEquals("Good signal", rnodeSignalLevel(-70).label) + assertEquals("Fair signal", rnodeSignalLevel(-71).label) + assertEquals("Fair signal", rnodeSignalLevel(-80).label) + assertEquals("Weak signal", rnodeSignalLevel(-81).label) + assertEquals("Weak signal", rnodeSignalLevel(-120).label) + assertEquals(listOf(1, 2, 3, 4), RNodeSignalLevel.entries.map { it.bars }) + } + + @Test + fun scanStartsAreHeldBackBeforeAndroidThrottlesThem() { + assertEquals(0, rnodeScanStartDelayMillis(emptyList(), 0)) + assertEquals(0, rnodeScanStartDelayMillis(listOf(0, 1_000, 2_000), 3_000)) + assertEquals(27_000, rnodeScanStartDelayMillis(listOf(0, 1_000, 2_000, 2_500), 3_000)) + assertEquals(28_000, rnodeScanStartDelayMillis(listOf(0, 1_000, 2_000, 2_500, 2_800), 3_000)) + // Starts that have left the 30 second window no longer count. + assertEquals(0, rnodeScanStartDelayMillis(listOf(0, 1_000, 2_000, 2_500), 31_500)) + assertEquals(0, rnodeScanStartDelayMillis(listOf(0, 1_000, 2_000, 2_500), 60_000)) + } + + @Test + fun validationNamesWhatIsMissingForEachConnection() { + assertEquals( + "Choose an RNode for this interface before starting the node.", + radio.validationError(supportsBleRNodes = true), + ) + assertEquals("Enter the RNode's serial port.", radio.validationError()) + assertEquals("Enter the RNode's host name or IP address.", radio.copy(port = "tcp://").validationError(true)) + assertNull(radio.copy(port = "tcp://rnode.local").validationError(true)) + assertNull(radio.copy(port = "ble://").validationError(true)) + assertNull(radio.copy(port = "ble://$address").validationError(true)) + assertNull(radio.copy(port = "/dev/ttyUSB0").validationError()) + assertEquals( + "RNode frequency must be between 137 MHz and 3 GHz.", + radio.copy(port = "ble://$address", frequencyHz = 0).validationError(true), + ) + assertEquals( + "Choose an RNode for this interface before starting the node.", + ReticulumNodeConfig(rnodeInterfaces = listOf(radio)).validationError(supportsBleRNodes = true), + ) + } + + @Test + fun scanStatesUseTheApprovedCopy() { + val android = RNodeBlePlatform.ANDROID + val ios = RNodeBlePlatform.IOS + + assertEquals("Searching for RNodes...", RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Scanning, android, false)) + assertEquals("Searching...", RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Scanning, android, true)) + assertNull(RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Finished, android, true)) + assertTrue(RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Finished, android, false)!!.startsWith("No RNodes found.")) + assertEquals("Bluetooth is turned off.", RNodeBleText.scanStatusMessage(RNodeBleScanStatus.BluetoothOff, android, false)) + assertEquals( + "Bluetooth is turned off. Turn on Bluetooth in Control Center or Settings.", + RNodeBleText.scanStatusMessage(RNodeBleScanStatus.BluetoothOff, ios, false), + ) + assertEquals( + "Bluetooth search failed (code 2). Try again.", + RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Failed(2), android, false), + ) + assertEquals("Turn on Bluetooth", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.BluetoothOff, android)) + assertNull(RNodeBleText.scanBlockerAction(RNodeBleScanStatus.BluetoothOff, ios)) + assertEquals("Allow", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.PermissionNotAsked, android)) + assertEquals("Allow", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.PermissionDenied, android)) + assertEquals("Open settings", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.PermissionPermanentlyDenied, ios)) + assertEquals("Open location settings", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.LocationOff, android)) + assertNull(RNodeBleText.scanBlockerAction(RNodeBleScanStatus.Scanning, android)) + } + + @Test + fun pairingFailuresAndNodeStartErrorsNameTheRNode() { + val android = RNodeBlePlatform.ANDROID + fun failed(reason: RNodeBlePairingFailure, code: Int = 0) = RNodeBlePairingState.Failed("RNode A1B2", reason, code) + + assertTrue(RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.WRONG_PIN, 1), android).startsWith("The PIN didn't match.")) + assertTrue(RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.TIMEOUT), android).startsWith("Pairing timed out.")) + assertEquals( + "Pairing didn't complete (reason 9). Try again.", + RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.OTHER, 9), android), + ) + assertTrue( + RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.OTHER), RNodeBlePlatform.IOS) + .startsWith("iOS didn't finish pairing."), + ) + assertTrue( + RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.STALE_BOND), RNodeBlePlatform.IOS) + .startsWith("This RNode no longer recognises this iPhone."), + ) + assertEquals( + "Couldn't reach RNode A1B2. Check that it's powered on and in range, then try again.", + RNodeBleText.notFound("RNode A1B2"), + ) + assertEquals("RNode A1B2", rnodeBleLabel("ble://$address", "RNode A1B2")) + assertEquals("RNode A1B2", rnodeBleLabel("ble://RNode A1B2", null)) + assertEquals("the RNode", rnodeBleLabel("ble://$address", null)) + assertEquals("the RNode", rnodeBleLabel("ble://", " ")) + } + + @Test + fun displayNameNeverShowsADeviceId() { + assertEquals("RNode A1B2", rnodeDisplayName(radio.copy(port = "ble://$uuid", bleName = "RNode A1B2"))) + assertEquals("Bluetooth RNode", rnodeDisplayName(radio.copy(port = "ble://$uuid"))) + assertEquals("RNode A1B2", rnodeDisplayName(radio.copy(port = "ble://RNode A1B2"))) + assertEquals("rnode.local", rnodeDisplayName(radio.copy(port = "tcp://rnode.local"))) + assertEquals("/dev/ttyUSB0", rnodeDisplayName(radio.copy(port = "/dev/ttyUSB0"))) + } + + @Test + fun onlyPhonesReachRNodesOverBluetooth() { + val controller = UnsupportedReticulumNodeController("unavailable") + + assertFalse(controller.supportsBleRNodes) + assertNull(controller.rnodeBlePicker) + assertNull(controller.resolvedBleRNode.value) + } +} From 2c8cac9b789975510a9e619b544867270360b192 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:01 -0700 Subject: [PATCH 03/12] feat(settings): pick an RNode's connection instead of typing it Replace the free-text connection field with Connect over choices: Bluetooth or Wi-Fi on phones, Serial port or Wi-Fi on desktop. A Bluetooth RNode is chosen from a search dialog that also walks through pairing; the card shows the chosen device with Change and Forget. The editor is read-only while the node is running or starting. A Bluetooth RNode is shown by name in status and diagnostics. --- .../sidpatchy/Starling/NetworkDiagnostics.kt | 10 +- .../Starling/RNodeBluetoothPicker.kt | 455 ++++++++++++++++++ .../com/sidpatchy/Starling/SettingsPage.kt | 48 +- .../com/sidpatchy/Starling/StarlingApp.kt | 27 +- 4 files changed, 523 insertions(+), 17 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/NetworkDiagnostics.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/NetworkDiagnostics.kt index 4521f60..48c573f 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/NetworkDiagnostics.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/NetworkDiagnostics.kt @@ -60,6 +60,8 @@ data class RNodeRadioDiagnostics( val spreadingFactor: Int, val codingRate: Int, val online: Boolean, + /** What the diagnostics screen calls this radio. */ + val label: String = port, ) /** @@ -166,6 +168,12 @@ fun buildNetworkDiagnostics( rnodeRadios = state.rnodeInterfaces.map { radio -> RNodeRadioDiagnostics( port = radio.port, + // A Bluetooth RNode is shown by name, not by its device id. + label = if (rnodeConnectionType(radio.port) == RNodeConnectionType.BLUETOOTH) { + rnodeDisplayName(radio) + } else { + radio.port + }, frequencyHz = radio.frequencyHz, bandwidthHz = radio.bandwidthHz, txPowerDbm = radio.txPowerDbm, @@ -301,7 +309,7 @@ internal fun NetworkDiagnosticsDialog( SectionTitle("RNode radios") diagnostics.rnodeRadios.forEach { radio -> RadioRow( - label = radio.port, + label = radio.label, detail = "${radio.frequencyHz / 1_000_000} MHz · ${radio.bandwidthHz / 1000} kHz BW · SF${radio.spreadingFactor} · CR${radio.codingRate} · ${radio.txPowerDbm} dBm", online = radio.online, color = palette, diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt new file mode 100644 index 0000000..cf857a8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt @@ -0,0 +1,455 @@ +package com.sidpatchy.Starling + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.delay +import kotlin.time.TimeSource + +private const val RESCAN_DEBOUNCE_MILLIS = 2_000L +private const val RESULT_ADVANCE_MILLIS = 1_000L + +/** The "Connect over" part of an RNode card: connection type and the device, host, or port. */ +@Composable +internal fun RNodeConnectionEditor( + radio: ReticulumRNodeInterface, + onRadioChange: (ReticulumRNodeInterface) -> Unit, + locked: Boolean, + supportsBleRNodes: Boolean, + picker: RNodeBlePicker?, + upgradeNote: String?, + onDismissKeyboard: () -> Unit, +) { + val type = rnodeEditorConnectionType(radio.port, supportsBleRNodes) + val options = if (supportsBleRNodes) { + listOf(RNodeConnectionType.BLUETOOTH to "Bluetooth", RNodeConnectionType.WIFI to "Wi-Fi") + } else { + listOf(RNodeConnectionType.SERIAL to "Serial port", RNodeConnectionType.WIFI to "Wi-Fi") + } + Text("Connect over", color = Ink, fontSize = 12.sp, fontWeight = FontWeight.Medium) + Row(Modifier.fillMaxWidth().selectableGroup()) { + options.forEach { (option, label) -> + Row( + modifier = Modifier.weight(1f).heightIn(min = 48.dp).clip(RoundedCornerShape(8.dp)) + .selectable(selected = type == option, enabled = !locked, role = Role.RadioButton) { + onDismissKeyboard() + if (type != option) { + // Only the connection is cleared; the radio parameters stay. + onRadioChange(radio.copy(port = rnodeEmptyPort(option), bleName = null, pairedByStarling = false)) + } + }, + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = type == option, onClick = null, enabled = !locked) + Text(label, color = Ink, fontSize = 12.sp, fontWeight = FontWeight.Medium) + } + } + } + when (type) { + RNodeConnectionType.WIFI -> OutlinedTextField( + value = rnodeWifiHost(radio.port), + onValueChange = { value -> onRadioChange(radio.copy(port = RNODE_TCP_PREFIX + value.trim())) }, + modifier = Modifier.fillMaxWidth(), + label = { Text("RNode address (host or IP)") }, + supportingText = { Text("Starling uses the RNode's default port, 7633.", color = Muted, fontSize = 10.sp) }, + singleLine = true, + enabled = !locked, + ) + RNodeConnectionType.SERIAL -> OutlinedTextField( + value = radio.port, + onValueChange = { value -> onRadioChange(radio.copy(port = value)) }, + modifier = Modifier.fillMaxWidth(), + label = { Text("Serial port") }, + supportingText = { + Text("For example /dev/ttyUSB0, COM3 or /dev/cu.usbserial-0001", color = Muted, fontSize = 10.sp) + }, + singleLine = true, + enabled = !locked, + ) + RNodeConnectionType.BLUETOOTH -> + if (picker != null) RNodeBluetoothDevice(radio, onRadioChange, locked, picker, upgradeNote, onDismissKeyboard) + } + if (locked) Text("Stop the node to change the RNode.", color = Muted, fontSize = 11.sp) +} + +private data class RNodePickerRequest(val pairDeviceId: String? = null, val pairDeviceName: String = "") + +@Composable +private fun RNodeBluetoothDevice( + radio: ReticulumRNodeInterface, + onRadioChange: (ReticulumRNodeInterface) -> Unit, + locked: Boolean, + picker: RNodeBlePicker, + upgradeNote: String?, + onDismissKeyboard: () -> Unit, +) { + var request by remember { mutableStateOf(null) } + var forgotten by remember { mutableStateOf(false) } + // Pairing can change in the dialog or in system settings; look again after either. + var pairingChecks by remember { mutableStateOf(0) } + val isBleValue = rnodeConnectionType(radio.port) == RNodeConnectionType.BLUETOOTH + val target = rnodeBleTarget(radio.port) + val kind = rnodeBleTargetKind(target) + val android = picker.platform == RNodeBlePlatform.ANDROID + val find = { onDismissKeyboard(); request = RNodePickerRequest() } + + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + when { + !isBleValue -> { + Text("No RNode chosen", color = Ink, fontSize = 13.sp, fontWeight = FontWeight.Medium) + Text("Turn on your RNode and tap Find RNode.", color = Muted, fontSize = 11.sp) + if (!locked) TextButton(onClick = find) { Text("Find RNode", color = Accent) } + } + kind == RNodeBleTargetKind.ANY -> { + Text( + "Starling connects to the first RNode it finds. Choose a specific RNode to avoid connecting to the wrong one.", + color = Muted, + fontSize = 11.sp, + lineHeight = 16.sp, + ) + if (!locked) TextButton(onClick = find) { Text("Find RNode", color = Accent) } + } + else -> { + val savedId = target.takeIf { kind == RNodeBleTargetKind.ID } + val name = radio.bleName?.takeIf(String::isNotBlank) + ?: savedId?.let { id -> remember(id, pairingChecks) { picker.knownName(id) } } + ?: target.takeIf { kind == RNodeBleTargetKind.NAME } + ?: "RNode" + val paired = if (android && savedId != null) { + remember(savedId, pairingChecks) { picker.isPaired(savedId) } + } else { + null + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text(name, modifier = Modifier.weight(1f), color = Ink, fontSize = 13.sp, fontWeight = FontWeight.Medium) + when { + paired == true -> Text("Paired", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Medium) + paired == false -> Text("Not paired", color = ErrorText, fontSize = 11.sp, fontWeight = FontWeight.Medium) + !android && savedId != null -> + Text("Saved", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Medium) + } + } + if (android && savedId != null) { + Text(savedId.uppercase(), color = Muted, fontSize = 10.sp) + } else if (!android && savedId != null) { + Text("Starling connects to this RNode only.", color = Muted, fontSize = 11.sp) + } + if (!locked) { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (paired == false && savedId != null) { + TextButton(onClick = { + onDismissKeyboard() + request = RNodePickerRequest(pairDeviceId = savedId, pairDeviceName = name) + }) { Text("Pair", color = Accent) } + } + TextButton(onClick = find) { Text("Change", color = Accent) } + TextButton(onClick = { + onDismissKeyboard() + forgotten = true + onRadioChange( + radio.copy( + port = rnodeEmptyPort(RNodeConnectionType.BLUETOOTH), + bleName = null, + pairedByStarling = false, + ), + ) + }) { Text("Forget", color = ErrorText) } + } + } + } + } + if (forgotten && !isBleValue) { + Text( + "This only removes the RNode from Starling. To unpair it, use Bluetooth settings.", + color = Muted, + fontSize = 11.sp, + lineHeight = 16.sp, + ) + if (android) { + TextButton(onClick = { picker.openBluetoothSettings() }) { Text("Open Bluetooth settings", color = Accent) } + } + } + if (upgradeNote != null && kind == RNodeBleTargetKind.ID) { + Text(upgradeNote, color = Muted, fontSize = 11.sp) + } + } + + request?.let { current -> + RNodeScanDialog( + picker = picker, + savedId = target.takeIf { isBleValue && kind == RNodeBleTargetKind.ID }, + pairDeviceId = current.pairDeviceId, + pairDeviceName = current.pairDeviceName, + onChosen = { id, name, pairedByStarling -> + forgotten = false + request = null + pairingChecks++ + onRadioChange( + radio.copy( + port = rnodeBlePort(id), + bleName = name.ifBlank { null }, + // Re-pairing the saved device keeps what Starling already knew about it. + pairedByStarling = pairedByStarling || + (radio.pairedByStarling && target.equals(id, ignoreCase = true) && picker.isPaired(id) == true), + ), + ) + }, + onDismiss = { + request = null + pairingChecks++ + }, + ) + } +} + +/** + * Finds nearby RNodes and pairs with the one that is picked. The current + * RNode stays saved until [onChosen] reports a new one. + */ +@Composable +private fun RNodeScanDialog( + picker: RNodeBlePicker, + savedId: String?, + pairDeviceId: String?, + pairDeviceName: String, + onChosen: (id: String, name: String, pairedByStarling: Boolean) -> Unit, + onDismiss: () -> Unit, +) { + val android = picker.platform == RNodeBlePlatform.ANDROID + val scanStatus by picker.scanStatus.collectAsState() + val pairing by picker.pairing.collectAsState() + val clock = remember { TimeSource.Monotonic.markNow() } + val list = remember { RNodeScanList() } + val pairedIds = remember { mutableMapOf() } + var rows by remember { mutableStateOf(emptyList()) } + var selected by remember { mutableStateOf(pairDeviceId?.let { it to pairDeviceName }) } + var lastSearchAt by remember { mutableStateOf(0L) } + var now by remember { mutableStateOf(0L) } + + fun search() { + lastSearchAt = clock.elapsedNow().inWholeMilliseconds + picker.startScan() + } + + DisposableEffect(picker) { + onDispose { + picker.stopScan() + picker.cancelPairing() + } + } + LaunchedEffect(picker) { + if (pairDeviceId != null) picker.pair(pairDeviceId, pairDeviceName) else search() + } + LaunchedEffect(scanStatus) { + if (scanStatus == RNodeBleScanStatus.Scanning) list.beginSearch(clock.elapsedNow().inWholeMilliseconds) + } + LaunchedEffect(picker) { + picker.sightings.collect { sighting -> + val key = sighting.id.uppercase() + val paired = android && pairedIds.getOrPut(key) { picker.isPaired(sighting.id) == true } + val pinned = paired || (savedId != null && savedId.equals(sighting.id, ignoreCase = true)) + val at = clock.elapsedNow().inWholeMilliseconds + list.observe(sighting, pinned, at) + rows = list.rows(at) + } + } + LaunchedEffect(Unit) { + while (true) { + delay(500) + now = clock.elapsedNow().inWholeMilliseconds + rows = list.rows(now) + } + } + LaunchedEffect(pairing) { + val device = selected ?: return@LaunchedEffect + when (pairing) { + is RNodeBlePairingState.AlreadyPaired, is RNodeBlePairingState.Ready -> { + delay(RESULT_ADVANCE_MILLIS) + onChosen(device.first, device.second, false) + } + is RNodeBlePairingState.Paired -> { + delay(RESULT_ADVANCE_MILLIS) + onChosen(device.first, device.second, true) + } + else -> Unit + } + } + + val device = selected + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Choose your RNode", color = Ink) }, + text = { + Column( + modifier = Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (device == null) { + Text("Turn the RNode on and keep it close.", color = Muted, fontSize = 12.sp) + if (!android && savedId == null) { + Text( + "iOS may ask to pair with the RNode the first time Starling connects to it. If iOS asks, " + + "enter the PIN shown on the RNode's screen. Starling can't start pairing itself or tell " + + "whether the RNode is already paired.", + color = Muted, + fontSize = 11.sp, + lineHeight = 16.sp, + ) + } + rows.forEach { row -> + RNodeScanRowItem( + row = row, + marker = when { + android && pairedIds[row.id] == true -> "Paired" + !android && savedId != null && savedId.equals(row.id, ignoreCase = true) -> "Saved" + else -> null + }, + onClick = { + picker.stopScan() + selected = row.id to row.name + picker.pair(row.id, row.name) + }, + ) + } + RNodeBleText.scanStatusMessage(scanStatus, picker.platform, rows.isNotEmpty())?.let { message -> + val blocked = scanStatus != RNodeBleScanStatus.Scanning && scanStatus != RNodeBleScanStatus.Finished + Text( + message, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + color = if (scanStatus is RNodeBleScanStatus.Failed) ErrorText else if (blocked) Ink else Muted, + fontSize = 12.sp, + lineHeight = 17.sp, + ) + } + RNodeBleText.scanBlockerAction(scanStatus, picker.platform)?.let { action -> + TextButton(onClick = { picker.resolveScanBlocker() }) { Text(action, color = Accent) } + } + } else { + RNodePairingStep(device.second.ifBlank { "RNode" }, pairing, picker.platform) + } + } + }, + confirmButton = { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (device == null) { + if (scanStatus == RNodeBleScanStatus.Scanning) { + TextButton(onClick = { picker.stopScan() }) { Text("Stop", color = Accent) } + } else if (scanStatus != RNodeBleScanStatus.Unsupported) { + TextButton( + enabled = now - lastSearchAt >= RESCAN_DEBOUNCE_MILLIS, + onClick = { search() }, + ) { Text("Rescan") } + } + } else if (pairing is RNodeBlePairingState.Failed) { + TextButton(onClick = { picker.pair(device.first, device.second) }) { Text("Try again", color = Accent) } + if (android) { + // Pairing is not required to save an RNode; it may accept connections without it. + TextButton(onClick = { onChosen(device.first, device.second, false) }) { Text("Skip pairing") } + } + } + TextButton(onClick = onDismiss) { Text("Cancel") } + } + }, + ) +} + +@Composable +private fun RNodePairingStep(name: String, pairing: RNodeBlePairingState, platform: RNodeBlePlatform) { + val android = platform == RNodeBlePlatform.ANDROID + Column( + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + when (pairing) { + RNodeBlePairingState.Idle, is RNodeBlePairingState.Waiting -> if (android) { + Text("Pair with $name", color = Ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold) + Text( + "If Android asks, enter the PIN shown on your RNode's screen, then tap Pair.", + color = Ink, + fontSize = 12.sp, + lineHeight = 17.sp, + ) + Text("Waiting for pairing...", color = Muted, fontSize = 12.sp) + } else { + Text( + "Connecting to $name. If iOS asks for a PIN, enter the one shown on your RNode's screen.", + color = Ink, + fontSize = 12.sp, + lineHeight = 17.sp, + ) + } + is RNodeBlePairingState.AlreadyPaired -> Text("Already paired", color = Ink, fontSize = 13.sp) + is RNodeBlePairingState.Paired -> Text("Paired with $name.", color = Ink, fontSize = 13.sp) + is RNodeBlePairingState.Ready -> Text("Connected to $name. This RNode is ready.", color = Ink, fontSize = 13.sp) + is RNodeBlePairingState.Failed -> + Text(RNodeBleText.pairingFailureMessage(pairing, platform), color = ErrorText, fontSize = 12.sp, lineHeight = 17.sp) + } + } +} + +@Composable +private fun RNodeScanRowItem(row: RNodeScanRow, marker: String?, onClick: () -> Unit) { + val level = rnodeSignalLevel(row.rssi) + Row( + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(RoundedCornerShape(8.dp)) + .clickable(role = Role.Button, onClick = onClick) + .semantics(mergeDescendants = true) {} + .padding(horizontal = 4.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(row.name.ifBlank { "Unnamed RNode" }, color = Ink, fontSize = 13.sp, fontWeight = FontWeight.Medium) + row.idSuffix?.let { Text(it, color = Muted, fontSize = 10.sp) } + marker?.let { Text(it, color = Accent, fontSize = 10.sp, fontWeight = FontWeight.Medium) } + } + Spacer(Modifier.width(8.dp)) + Column(horizontalAlignment = Alignment.End) { + Row(horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.Bottom) { + for (bar in 1..4) { + Box( + Modifier.width(4.dp).height((3 + bar * 3).dp).clip(RoundedCornerShape(1.dp)) + .background(if (bar <= level.bars) Accent else Line), + ) + } + } + Text(level.label, color = Muted, fontSize = 10.sp) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt index 66336ce..888fcaf 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt @@ -175,6 +175,10 @@ internal fun SettingsPage( onManageIdentity: () -> Unit, supportsReticulumProtocol: Boolean, supportsRNodeInterfaces: Boolean, + supportsBleRNodes: Boolean = false, + rnodeBlePicker: RNodeBlePicker? = null, + resolvedBleRNode: ResolvedBleRNode? = null, + rnodeUpgradeNote: String? = null, rrcState: ReticulumConnectionState, rrcError: String?, localDeliveryAddress: String?, @@ -221,18 +225,22 @@ internal fun SettingsPage( radio.txPowerDbm.toString(), radio.spreadingFactor.toString(), radio.codingRate.toString(), + radio.bleName.orEmpty(), + if (radio.pairedByStarling) "1" else "0", ) } }, restore = { saved: List -> - saved.chunked(6).mapNotNull { fields -> - if (fields.size != 6) null else ReticulumRNodeInterface( + saved.chunked(8).mapNotNull { fields -> + if (fields.size != 8) null else ReticulumRNodeInterface( port = fields[0], frequencyHz = fields[1].toLongOrNull() ?: 0L, bandwidthHz = fields[2].toIntOrNull() ?: 0, txPowerDbm = fields[3].toIntOrNull() ?: -1, spreadingFactor = fields[4].toIntOrNull() ?: 0, codingRate = fields[5].toIntOrNull() ?: 0, + bleName = fields[6].ifBlank { null }, + pairedByStarling = fields[7] == "1", ) } }, @@ -271,7 +279,7 @@ internal fun SettingsPage( existingInstanceRpcKeyHex = existingRpcKey, ) } - val nodeConfigValidationError = nodeConfigDraft.validationError() + val nodeConfigValidationError = nodeConfigDraft.validationError(supportsBleRNodes) val nodeActionEnabled = nodeSupported && !isStarting && !identityBusy && (isRunning || (identityAvailable && nodeConfigValidationError == null)) val nodeActionBlockedReason = when { @@ -298,6 +306,11 @@ internal fun SettingsPage( else -> Unit } } + LaunchedEffect(resolvedBleRNode) { + // The node connected to a Bluetooth RNode saved by name: keep its id from now on. + val resolved = resolvedBleRNode ?: return@LaunchedEffect + upgradeRNodeBleInterfaces(rnodeInterfaces, resolved)?.let { (upgraded, _) -> rnodeInterfaces = upgraded } + } LaunchedEffect(runtimeModeName, tcpPeers, rnodeInterfaces) { onNodeConfigChange( ReticulumNodeConfig( @@ -554,7 +567,11 @@ internal fun SettingsPage( if (!supportsReticulumProtocol) { "This opens a plain TCP socket only; it does not exchange Reticulum traffic." } else if (supportsRNodeInterfaces) { - "Configure TCP peers and/or an RNode radio. Use a serial port on desktop, tcp://host for a Wi-Fi RNode on port 7633, or ble://device name for BLE on iOS and Android. Bare ble:// selects the first nearby RNode. Android and iOS support one BLE RNode at a time. Starling stays a client; Reticulum transport routing remains disabled." + if (supportsBleRNodes) { + "Add TCP peers and/or an RNode. Choose Bluetooth or Wi-Fi for each RNode. Starling supports one Bluetooth RNode at a time and stays a client; Reticulum transport routing remains disabled." + } else { + "Add TCP peers and/or an RNode. Choose a serial port or Wi-Fi for each RNode. Starling stays a client; Reticulum transport routing remains disabled." + } } else { "Manage outbound TCP client interfaces. Starling stays a client; Reticulum transport routing remains disabled." }, @@ -655,18 +672,19 @@ internal fun SettingsPage( } } } - OutlinedTextField( - value = radio.port, - onValueChange = { value -> + RNodeConnectionEditor( + radio = radio, + onRadioChange = { changed -> rnodeInterfaces = rnodeInterfaces.mapIndexed { radioIndex, old -> - if (radioIndex == index) old.copy(port = value) else old + if (radioIndex == index) changed else old } connectionInputError = null }, - modifier = Modifier.fillMaxWidth(), - label = { Text("Serial port, tcp://host, or ble://device name") }, - singleLine = true, - enabled = !isRunning && !isStarting, + locked = isRunning || isStarting, + supportsBleRNodes = supportsBleRNodes, + picker = rnodeBlePicker, + upgradeNote = rnodeUpgradeNote, + onDismissKeyboard = onDismissKeyboard, ) OutlinedTextField( value = radio.frequencyHz.takeIf { it > 0 }?.toString().orEmpty(), @@ -747,7 +765,7 @@ internal fun SettingsPage( enabled = !isRunning && !isStarting, ) } - radio.validationError()?.let { validationError -> + radio.validationError(supportsBleRNodes)?.let { validationError -> Text(validationError, color = ErrorText, fontSize = 10.sp) } } @@ -807,7 +825,9 @@ internal fun SettingsPage( "${state.onlineTcpPeerIds.size} of ${state.tcpPeers.size} TCP connections online; " + "${state.onlineRNodePorts.size} of ${state.rnodeInterfaces.size} RNode radios online." state.rnodeInterfaces.isNotEmpty() -> "${state.onlineRNodePorts.size} of ${state.rnodeInterfaces.size} RNode radios online. " + - state.rnodeInterfaces.joinToString { radio -> "${radio.port} ${if (radio.id in state.onlineRNodePorts) "(online)" else "(retrying)"}" } + state.rnodeInterfaces.joinToString { radio -> + val saved = rnodeInterfaces.firstOrNull { it.id == radio.id } ?: radio + "${rnodeDisplayName(saved)} ${if (radio.id in state.onlineRNodePorts) "(online)" else "(retrying)"}" } state.tcpPeers.isNotEmpty() -> "${state.onlineTcpPeerIds.size} of ${state.tcpPeers.size} TCP connections online. " + (if (supportsReticulumProtocol) "" else "Socket check only; RNS traffic is not implemented on iOS. ") + state.tcpPeers.joinToString { diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/StarlingApp.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/StarlingApp.kt index d3d1386..8e4b13e 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/StarlingApp.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/StarlingApp.kt @@ -203,6 +203,17 @@ fun StarlingApp( val persistedNodeConfig by remember(liveChatRepository) { liveChatRepository?.nodeConfig ?: flowOf(null) }.collectAsState(initial = liveChatRepository?.nodeConfig?.value) + val resolvedBleRNode by nodeController.resolvedBleRNode.collectAsState() + var rnodeUpgradeNote by remember { mutableStateOf(null) } + LaunchedEffect(resolvedBleRNode, liveChatRepository) { + // A Bluetooth RNode saved by name is kept by device id once the node has connected to it. + val resolved = resolvedBleRNode ?: return@LaunchedEffect + val chat = liveChatRepository ?: return@LaunchedEffect + val config = chat.nodeConfig.value ?: return@LaunchedEffect + val (radios, note) = upgradeRNodeBleInterfaces(config.rnodeInterfaces, resolved) ?: return@LaunchedEffect + chat.saveNodeConfig(config.copy(rnodeInterfaces = radios)) + if (note != null) rnodeUpgradeNote = note + } val preferredHubNetworkId by remember(liveChatRepository) { liveChatRepository?.preferredHubNetworkId ?: flowOf(null) }.collectAsState(initial = liveChatRepository?.preferredHubNetworkId?.value) @@ -395,7 +406,11 @@ fun StarlingApp( if (identityManager != null && identityManager.state.value !is ReticulumIdentityState.Available) return@LaunchedEffect nodeController.refreshState() val savedConfig = liveChatRepository?.nodeConfig?.value ?: return@LaunchedEffect - if (savedConfig.mode != ReticulumRuntimeMode.EMBEDDED || savedConfig.validationError() != null) return@LaunchedEffect + if (savedConfig.mode != ReticulumRuntimeMode.EMBEDDED || + savedConfig.validationError(nodeController.supportsBleRNodes) != null + ) { + return@LaunchedEffect + } when (nodeController.state.value) { ReticulumNodeState.Stopped -> nodeController.start(savedConfig) @@ -458,7 +473,7 @@ fun StarlingApp( if (repository.previewMode.value) return@collect nodeController.refreshState() - val savedConfig = chat.nodeConfig.value?.takeIf { it.validationError() == null } + val savedConfig = chat.nodeConfig.value?.takeIf { it.validationError(nodeController.supportsBleRNodes) == null } val canStartNode = identityManager == null || identityManager.state.value is ReticulumIdentityState.Available when (val state = nodeController.state.value) { is ReticulumNodeState.Running -> { @@ -630,6 +645,10 @@ fun StarlingApp( }, supportsReticulumProtocol = nodeController.supportsReticulumProtocol, supportsRNodeInterfaces = nodeController.supportsRNodeInterfaces, + supportsBleRNodes = nodeController.supportsBleRNodes, + rnodeBlePicker = nodeController.rnodeBlePicker, + resolvedBleRNode = resolvedBleRNode, + rnodeUpgradeNote = rnodeUpgradeNote, rrcState = visibleConnectionState, rrcError = visibleRrcError, localDeliveryAddress = visibleDeliveryAddress, @@ -899,6 +918,10 @@ fun StarlingApp( }, supportsReticulumProtocol = nodeController.supportsReticulumProtocol, supportsRNodeInterfaces = nodeController.supportsRNodeInterfaces, + supportsBleRNodes = nodeController.supportsBleRNodes, + rnodeBlePicker = nodeController.rnodeBlePicker, + resolvedBleRNode = resolvedBleRNode, + rnodeUpgradeNote = rnodeUpgradeNote, rrcState = visibleConnectionState, rrcError = visibleRrcError, localDeliveryAddress = visibleDeliveryAddress, From 96db17c0595c79be34253c1e130cc4e7679faba8 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:12 -0700 Subject: [PATCH 04/12] feat(android): find and pair RNodes from Settings Search for devices advertising the Nordic UART service, report why a search cannot run (permission, Bluetooth off, Location off on Android 11 and older) and hold back search starts before Android throttles them. Pair with createBond and follow ACTION_BOND_STATE_CHANGED. A device that Android knows as dual-mode or classic is paired from an LE connection instead, since createBond cannot name a transport. Permission requests now report granted, denied or permanently denied. --- .../Starling/AndroidRNodeBlePicker.kt | 433 ++++++++++++++++++ .../AndroidReticulumNodeController.kt | 13 +- .../com/sidpatchy/Starling/MainActivity.kt | 67 ++- 3 files changed, 501 insertions(+), 12 deletions(-) create mode 100644 androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt new file mode 100644 index 0000000..b84d51d --- /dev/null +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt @@ -0,0 +1,433 @@ +package com.sidpatchy.Starling + +import android.Manifest +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile +import android.bluetooth.le.BluetoothLeScanner +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageManager +import android.location.LocationManager +import android.net.Uri +import android.os.Build +import android.os.ParcelUuid +import android.os.SystemClock +import android.provider.Settings +import androidx.core.content.ContextCompat +import androidx.core.location.LocationManagerCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import java.util.UUID + +/** What the user answered when Android asked for Bluetooth access. */ +enum class BluetoothPermissionResult { GRANTED, DENIED, PERMANENTLY_DENIED } + +/** + * Finds RNodes and pairs with them for Settings. It runs in the UI process + * and only while the node is stopped, so it never competes with the bridge + * that carries RNode traffic in the node's own process. + */ +internal class AndroidRNodeBlePicker( + context: Context, + private val requestPermissions: suspend (Array) -> BluetoothPermissionResult, + private val requestEnableBluetooth: suspend () -> Unit, + private val startActivity: (Intent) -> Unit, +) : RNodeBlePicker { + private val appContext = context.applicationContext + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val adapter: BluetoothAdapter? = + (appContext.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter + + override val platform = RNodeBlePlatform.ANDROID + private val _scanStatus = MutableStateFlow(RNodeBleScanStatus.Idle) + override val scanStatus: StateFlow = _scanStatus.asStateFlow() + private val _sightings = MutableSharedFlow( + extraBufferCapacity = 64, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + override val sightings: Flow = _sightings.asSharedFlow() + private val _pairing = MutableStateFlow(RNodeBlePairingState.Idle) + override val pairing: StateFlow = _pairing.asStateFlow() + + private var scanJob: Job? = null + private var activeScanner: BluetoothLeScanner? = null + private val scanStarts = mutableListOf() + + private var pairingDevice: BluetoothDevice? = null + private var pairingName = "" + private var pairingTimeout: Job? = null + private var pairingGatt: BluetoothGatt? = null + private var bondReceiver: BroadcastReceiver? = null + private var bondRequested = false + + private val scanCallback = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + val name = result.scanRecord?.deviceName + ?: runCatching { result.device.name }.getOrNull().orEmpty() + _sightings.tryEmit(RNodeBleSighting(result.device.address, name, result.rssi)) + } + + override fun onScanFailed(errorCode: Int) { + scope.launch { + scanJob?.cancel() + activeScanner = null + _scanStatus.value = RNodeBleScanStatus.Failed(errorCode) + } + } + } + + override fun startScan() { + stopScanner() + scanJob?.cancel() + scanJob = scope.launch { + val bluetooth = adapter + if (bluetooth == null || !appContext.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + _scanStatus.value = RNodeBleScanStatus.Unsupported + return@launch + } + val permissions = scanPermissions() + if (!hasPermissions(permissions)) { + if (_scanStatus.value != RNodeBleScanStatus.PermissionDenied) { + _scanStatus.value = RNodeBleScanStatus.PermissionNotAsked + } + when (requestPermissions(permissions)) { + BluetoothPermissionResult.GRANTED -> Unit + BluetoothPermissionResult.DENIED -> { + _scanStatus.value = RNodeBleScanStatus.PermissionDenied + return@launch + } + BluetoothPermissionResult.PERMANENTLY_DENIED -> { + _scanStatus.value = RNodeBleScanStatus.PermissionPermanentlyDenied + return@launch + } + } + } + if (!bluetooth.isEnabled) { + _scanStatus.value = RNodeBleScanStatus.BluetoothOff + return@launch + } + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R && !locationEnabled()) { + _scanStatus.value = RNodeBleScanStatus.LocationOff + return@launch + } + val scanner = bluetooth.bluetoothLeScanner + if (scanner == null) { + _scanStatus.value = RNodeBleScanStatus.BluetoothOff + return@launch + } + _scanStatus.value = RNodeBleScanStatus.Scanning + // Android stops returning results to an app that starts scans too often. + delay(rnodeScanStartDelayMillis(scanStarts, SystemClock.elapsedRealtime())) + try { + val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE_UUID)).build() + val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() + scanner.startScan(listOf(filter), settings, scanCallback) + } catch (_: SecurityException) { + _scanStatus.value = RNodeBleScanStatus.PermissionDenied + return@launch + } + activeScanner = scanner + val startedAt = SystemClock.elapsedRealtime() + scanStarts += startedAt + scanStarts.removeAll { startedAt - it > SCAN_START_HISTORY_MS } + delay(SCAN_DURATION_MS) + stopScanner() + _scanStatus.value = RNodeBleScanStatus.Finished + } + } + + override fun stopScan() { + scanJob?.cancel() + scanJob = null + stopScanner() + if (_scanStatus.value == RNodeBleScanStatus.Scanning) _scanStatus.value = RNodeBleScanStatus.Finished + } + + private fun stopScanner() { + val scanner = activeScanner ?: return + activeScanner = null + runCatching { scanner.stopScan(scanCallback) } + } + + override fun resolveScanBlocker() { + when (_scanStatus.value) { + RNodeBleScanStatus.PermissionNotAsked, RNodeBleScanStatus.PermissionDenied -> startScan() + RNodeBleScanStatus.PermissionPermanentlyDenied -> open( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", appContext.packageName, null)), + ) + RNodeBleScanStatus.BluetoothOff -> scope.launch { + runCatching { requestEnableBluetooth() } + startScan() + } + RNodeBleScanStatus.LocationOff -> open(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) + else -> Unit + } + } + + override fun openBluetoothSettings() = open(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) + + private fun open(intent: Intent) { + runCatching { startActivity(intent) } + } + + override fun isPaired(deviceId: String): Boolean? { + if (!hasPermissions(connectPermissions())) return null + return runCatching { remoteDevice(deviceId)?.bondState == BluetoothDevice.BOND_BONDED }.getOrNull() + } + + override fun knownName(deviceId: String): String? { + if (!hasPermissions(connectPermissions())) return null + return runCatching { remoteDevice(deviceId)?.name }.getOrNull()?.takeIf(String::isNotBlank) + } + + private fun remoteDevice(deviceId: String): BluetoothDevice? { + val address = deviceId.trim().uppercase() + if (!BluetoothAdapter.checkBluetoothAddress(address)) return null + return adapter?.getRemoteDevice(address) + } + + override fun pair(deviceId: String, name: String) { + endPairing() + val label = name.ifBlank { "RNode" } + val device = try { + remoteDevice(deviceId) + } catch (_: SecurityException) { + null + } + if (device == null) { + _pairing.value = RNodeBlePairingState.Failed(label, RNodeBlePairingFailure.OTHER) + return + } + try { + if (device.bondState == BluetoothDevice.BOND_BONDED) { + _pairing.value = RNodeBlePairingState.AlreadyPaired(label) + return + } + pairingDevice = device + pairingName = label + bondRequested = false + _pairing.value = RNodeBlePairingState.Waiting(label) + registerBondReceiver() + pairingTimeout = scope.launch { + delay(PAIRING_TIMEOUT_MS) + failPairing(RNodeBlePairingFailure.TIMEOUT, 0) + } + // createBond() cannot name a transport. For a device Android knows as + // dual-mode or classic it may pair over classic Bluetooth, which does + // not cover the LE UART service, so those devices are paired from an + // LE connection instead: reading the protected service makes Android + // start LE pairing itself. + val type = device.type + val pairOverGatt = type == BluetoothDevice.DEVICE_TYPE_DUAL || type == BluetoothDevice.DEVICE_TYPE_CLASSIC + if (pairOverGatt || !requestBond(device)) connectForPairing(device) + } catch (_: SecurityException) { + failPairing(RNodeBlePairingFailure.OTHER, 0) + } + } + + override fun cancelPairing() { + endPairing() + _pairing.value = RNodeBlePairingState.Idle + } + + private fun requestBond(device: BluetoothDevice): Boolean { + bondRequested = true + return device.createBond() + } + + private fun registerBondReceiver() { + val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action != BluetoothDevice.ACTION_BOND_STATE_CHANGED) return + val device = pairingDevice ?: return + val changed: BluetoothDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) + } + if (changed?.address != device.address) return + val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR) + val previous = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR) + when { + state == BluetoothDevice.BOND_BONDED -> finishPairing(RNodeBlePairingState.Paired(pairingName)) + state == BluetoothDevice.BOND_NONE && previous == BluetoothDevice.BOND_BONDING -> { + // Android does not document this extra; it is read on a best-effort basis. + val reason = intent.getIntExtra(EXTRA_UNBOND_REASON, 0) + failPairing( + when (reason) { + UNBOND_REASON_AUTH_FAILED -> RNodeBlePairingFailure.WRONG_PIN + UNBOND_REASON_AUTH_TIMEOUT -> RNodeBlePairingFailure.TIMEOUT + else -> RNodeBlePairingFailure.OTHER + }, + reason, + ) + } + } + } + } + bondReceiver = receiver + ContextCompat.registerReceiver( + appContext, + receiver, + IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), + ContextCompat.RECEIVER_EXPORTED, + ) + } + + /** Opens the LE UART service so Android pairs if the RNode protects it. */ + private fun connectForPairing(device: BluetoothDevice) { + val callback = object : BluetoothGattCallback() { + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) { + if (!runCatching { gatt.discoverServices() }.getOrDefault(false)) gattPairingFailed(gatt, 0) + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + gattPairingFailed(gatt, status) + } + } + + override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { + val tx = gatt.getService(SERVICE_UUID)?.getCharacteristic(TX_UUID) + val cccd = tx?.getDescriptor(CCCD_UUID) + if (status != BluetoothGatt.GATT_SUCCESS || tx == null || cccd == null) { + gattPairingFailed(gatt, status) + return + } + val value = if (tx.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) { + BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + } else { + BluetoothGattDescriptor.ENABLE_INDICATION_VALUE + } + val written = runCatching { + gatt.setCharacteristicNotification(tx, true) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + gatt.writeDescriptor(cccd, value) == BluetoothGatt.GATT_SUCCESS + } else { + @Suppress("DEPRECATION") + cccd.value = value + @Suppress("DEPRECATION") + gatt.writeDescriptor(cccd) + } + }.getOrDefault(false) + if (!written) gattPairingFailed(gatt, 0) + } + + override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { + if (descriptor.uuid != CCCD_UUID) return + scope.launch { + if (pairingGatt !== gatt) return@launch + val bondState = runCatching { gatt.device.bondState }.getOrDefault(BluetoothDevice.BOND_NONE) + when { + bondState == BluetoothDevice.BOND_BONDING -> Unit + status == BluetoothGatt.GATT_SUCCESS && bondState == BluetoothDevice.BOND_BONDED -> + finishPairing(RNodeBlePairingState.Paired(pairingName)) + // The RNode accepted the subscription without a pairing. + status == BluetoothGatt.GATT_SUCCESS -> finishPairing(RNodeBlePairingState.Ready(pairingName)) + // The service is protected and Android did not start pairing on its own. + !bondRequested && runCatching { requestBond(gatt.device) }.getOrDefault(false) -> Unit + else -> failPairing(RNodeBlePairingFailure.OTHER, status) + } + } + } + } + val gatt = device.connectGatt(appContext, false, callback, BluetoothDevice.TRANSPORT_LE) + if (gatt == null) failPairing(RNodeBlePairingFailure.OTHER, 0) else pairingGatt = gatt + } + + private fun gattPairingFailed(gatt: BluetoothGatt, status: Int) { + scope.launch { + if (pairingGatt !== gatt) return@launch + // The link can drop while Android is pairing; the pairing result decides the outcome. + val bonding = runCatching { gatt.device.bondState == BluetoothDevice.BOND_BONDING }.getOrDefault(false) + if (!bonding) failPairing(RNodeBlePairingFailure.OTHER, status) + } + } + + private fun finishPairing(result: RNodeBlePairingState) { + if (pairingDevice == null) return + endPairing() + _pairing.value = result + } + + private fun failPairing(reason: RNodeBlePairingFailure, code: Int) { + if (pairingDevice == null) return + val name = pairingName + endPairing() + _pairing.value = RNodeBlePairingState.Failed(name, reason, code) + } + + /** Releases everything a pairing attempt holds. A pairing Android has already started is left to finish. */ + private fun endPairing() { + pairingTimeout?.cancel() + pairingTimeout = null + bondReceiver?.let { receiver -> runCatching { appContext.unregisterReceiver(receiver) } } + bondReceiver = null + pairingGatt?.let { gatt -> + runCatching { gatt.disconnect() } + runCatching { gatt.close() } + } + pairingGatt = null + pairingDevice = null + } + + fun dispose() { + stopScan() + endPairing() + scope.cancel() + } + + private fun scanPermissions(): Array = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) + } else { + arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) + } + + private fun connectPermissions(): Array = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) arrayOf(Manifest.permission.BLUETOOTH_CONNECT) else emptyArray() + + private fun hasPermissions(permissions: Array): Boolean = permissions.all { + ContextCompat.checkSelfPermission(appContext, it) == PackageManager.PERMISSION_GRANTED + } + + private fun locationEnabled(): Boolean { + val manager = appContext.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return false + return LocationManagerCompat.isLocationEnabled(manager) + } + + private companion object { + const val SCAN_DURATION_MS = 20_000L + const val SCAN_START_HISTORY_MS = 60_000L + const val PAIRING_TIMEOUT_MS = 60_000L + const val EXTRA_UNBOND_REASON = "android.bluetooth.device.extra.REASON" + const val UNBOND_REASON_AUTH_FAILED = 1 + const val UNBOND_REASON_AUTH_TIMEOUT = 6 + val SERVICE_UUID: UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E") + val TX_UUID: UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E") + val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB") + } +} diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt index e88796d..2006c19 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt @@ -21,12 +21,14 @@ import kotlinx.coroutines.withTimeoutOrNull class AndroidReticulumNodeController( context: Context, private val requestBluetoothPermissions: suspend () -> Boolean = { false }, + override val rnodeBlePicker: RNodeBlePicker? = null, ) : ReticulumNodeController { private val appContext = context.applicationContext private val _state = MutableStateFlow(ReticulumNodeState.Stopped) override val state: StateFlow = _state.asStateFlow() override val isSupported: Boolean = true override val supportsRNodeInterfaces: Boolean = true + override val supportsBleRNodes: Boolean = true private var pendingStateQuery: CompletableDeferred? = null private var watchingServiceProcess = false @@ -90,6 +92,10 @@ class AndroidReticulumNodeController( } override suspend fun start(config: ReticulumNodeConfig) { + if (config.rnodeInterfaces.any { it.port.isBlank() }) { + _state.value = ReticulumNodeState.Failed(RNodeBleText.CHOOSE_BEFORE_START) + return + } val bleInterfaces = config.rnodeInterfaces.filter { it.port.startsWith(BLE_PREFIX, ignoreCase = true) } if (bleInterfaces.size > 1) { _state.value = ReticulumNodeState.Failed( @@ -124,7 +130,7 @@ class AndroidReticulumNodeController( return } - config.validationError()?.let { + config.validationError(supportsBleRNodes)?.let { _state.value = ReticulumNodeState.Failed(it) return } @@ -135,9 +141,8 @@ class AndroidReticulumNodeController( } if (bleInterfaces.isNotEmpty() && !requestBluetoothPermissions()) { - _state.value = ReticulumNodeState.Failed( - "Bluetooth permission is required to connect to a BLE RNode. Grant it and try again.", - ) + val radio = bleInterfaces.first() + _state.value = ReticulumNodeState.Failed(RNodeBleText.permission(rnodeBleLabel(radio.port, radio.bleName))) return } diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt index 89bc3cd..b86163c 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt @@ -1,6 +1,9 @@ package com.sidpatchy.Starling import android.Manifest +import android.bluetooth.BluetoothAdapter +import android.content.Intent +import androidx.core.app.ActivityCompat import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.compose.setContent @@ -20,7 +23,15 @@ class MainActivity : ComponentActivity() { private var nodeController: AndroidReticulumNodeController? = null private var transport: AndroidReticulumTransport? = null private var chatRepository: ReticulumChatRepository? = null + private var rnodeBlePicker: AndroidRNodeBlePicker? = null private var pendingBluetoothPermission: CompletableDeferred? = null + private var pendingBluetoothEnable: CompletableDeferred? = null + private val bluetoothEnableLauncher = registerForActivityResult( + ActivityResultContracts.StartActivityForResult(), + ) { + pendingBluetoothEnable?.complete(Unit) + pendingBluetoothEnable = null + } private val bluetoothPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions(), ) { @@ -32,9 +43,18 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) requestHighRefreshRate() - val controller = AndroidReticulumNodeController(applicationContext) { - requestRNodeBluetoothPermissions() - } + val picker = AndroidRNodeBlePicker( + applicationContext, + requestPermissions = { permissions -> requestBluetoothPermissionResult(permissions) }, + requestEnableBluetooth = { requestEnableBluetooth() }, + startActivity = { intent -> startActivity(intent) }, + ) + rnodeBlePicker = picker + val controller = AndroidReticulumNodeController( + applicationContext, + requestBluetoothPermissions = { requestBluetoothPermissions(rnodeBluetoothPermissions()) }, + rnodeBlePicker = picker, + ) val reticulumTransport = AndroidReticulumTransport(applicationContext) val chat = ReticulumChatRepository( LocalPreviewChatRepository(), @@ -67,6 +87,8 @@ class MainActivity : ComponentActivity() { override fun onDestroy() { nodeController?.dispose() + rnodeBlePicker?.dispose() + rnodeBlePicker = null transport?.dispose() chatRepository?.close() nodeController = null @@ -90,16 +112,28 @@ class MainActivity : ComponentActivity() { } } - private suspend fun requestRNodeBluetoothPermissions(): Boolean = withContext(Dispatchers.Main.immediate) { - val requiredPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + private fun rnodeBluetoothPermissions(): Array = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) } else { arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) } + + private suspend fun requestBluetoothPermissions(requiredPermissions: Array): Boolean = + requestBluetoothPermissionResult(requiredPermissions) == BluetoothPermissionResult.GRANTED + + /** + * Asks for the permissions that are missing and reports how the request ended. + * Android does not say when a permission is permanently denied; a refusal + * after which it would show no rationale is the documented way to tell. + */ + private suspend fun requestBluetoothPermissionResult( + requiredPermissions: Array, + ): BluetoothPermissionResult = withContext(Dispatchers.Main.immediate) { val missingPermissions = requiredPermissions.filter { ContextCompat.checkSelfPermission(this@MainActivity, it) != PackageManager.PERMISSION_GRANTED } - if (missingPermissions.isEmpty()) return@withContext true + if (missingPermissions.isEmpty()) return@withContext BluetoothPermissionResult.GRANTED val response = pendingBluetoothPermission ?: CompletableDeferred().also { pending -> pendingBluetoothPermission = pending @@ -107,9 +141,26 @@ class MainActivity : ComponentActivity() { } val completed = withTimeoutOrNull(BLUETOOTH_PERMISSION_TIMEOUT_MS) { response.await() } != null if (pendingBluetoothPermission === response) pendingBluetoothPermission = null - completed && requiredPermissions.all { - ContextCompat.checkSelfPermission(this@MainActivity, it) == PackageManager.PERMISSION_GRANTED + val stillMissing = requiredPermissions.filter { + ContextCompat.checkSelfPermission(this@MainActivity, it) != PackageManager.PERMISSION_GRANTED + } + when { + stillMissing.isEmpty() -> BluetoothPermissionResult.GRANTED + completed && stillMissing.any { + !ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity, it) + } -> BluetoothPermissionResult.PERMANENTLY_DENIED + else -> BluetoothPermissionResult.DENIED + } + } + + /** Shows the system request to turn Bluetooth on and waits for the answer. */ + private suspend fun requestEnableBluetooth() = withContext(Dispatchers.Main.immediate) { + val response = pendingBluetoothEnable ?: CompletableDeferred().also { pending -> + pendingBluetoothEnable = pending + bluetoothEnableLauncher.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)) } + withTimeoutOrNull(BLUETOOTH_PERMISSION_TIMEOUT_MS) { response.await() } + if (pendingBluetoothEnable === response) pendingBluetoothEnable = null } private companion object { From a8f8465354b8c19c32d2532c0750fb10290a1ec8 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:12 -0700 Subject: [PATCH 05/12] feat(android): connect to a saved RNode by address With a saved device address the bridge connects directly instead of scanning, and reconnects the same way. A pairing Starling created that has since been removed fails the start before connecting, and GATT authentication failures are reported as a missing pairing. Saved names and a bare ble:// keep the scan path. The service reports the connected device so a saved name can be upgraded to its address. --- .../Starling/AndroidRNodeBluetoothBridge.kt | 158 +++++++++++++++--- .../AndroidReticulumNodeController.kt | 13 +- .../Starling/ReticulumNodeService.kt | 30 +++- 3 files changed, 168 insertions(+), 33 deletions(-) diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt index 27cef70..1e283bc 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt @@ -48,6 +48,16 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { private var startupError: String? = null private var startupLatch: CountDownLatch? = null @Volatile private var targetName: String? = null + /** Set when the saved RNode is a device address: connect to it without scanning. */ + @Volatile private var targetAddress: String? = null + /** How messages refer to the RNode. */ + @Volatile private var label: String = RNodeBleText.FALLBACK_NAME + @Volatile private var adapter: BluetoothAdapter? = null + @Volatile private var scannedName: String? = null + + /** The address and name of the RNode this bridge connected to; null until startup succeeds. */ + @Volatile var resolvedDevice: ResolvedBleRNode? = null + private set @Volatile private var scanner: BluetoothLeScanner? = null private var serverSocket: ServerSocket? = null private var clientSocket: Socket? = null @@ -58,7 +68,7 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { private var writeInProgress = false private var writeChunkSize = DEFAULT_WRITE_CHUNK private var adapterStateReceiverRegistered = false - private val retryScan = Runnable { startScan() } + private val retryConnect = Runnable { if (targetAddress != null) connectToAddress() else startScan() } private val adapterStateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { @@ -82,6 +92,7 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { } if (!running || !matches) return + scannedName = deviceName.takeIf(String::isNotBlank) stopScan() runCatching { val connection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { @@ -106,7 +117,7 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { failStartup("Android Bluetooth scanning failed (code $errorCode).") } else if (running) { closeTcpClient() - scheduleScanRetry() + scheduleReconnect() } } } @@ -114,7 +125,16 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { private val gattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (status != BluetoothGatt.GATT_SUCCESS) { - handleGattDisconnect(gatt, "BLE connection failed (status $status).") + handleGattDisconnect( + gatt, + when { + isAuthenticationFailure(status) -> RNodeBleText.notPairedAndroid(label) + // The RNode ended the connection itself, as it does while another device holds it. + targetAddress != null && status == GATT_CONN_TERMINATE_PEER_USER -> RNodeBleText.heldElsewhere(label) + targetAddress != null -> RNodeBleText.notFound(label) + else -> "BLE connection failed (status $status)." + }, + ) return } when (newState) { @@ -140,7 +160,11 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status != BluetoothGatt.GATT_SUCCESS) { - handleGattDisconnect(gatt, "Could not inspect the BLE RNode services (status $status).") + handleGattDisconnect( + gatt, + if (isAuthenticationFailure(status)) RNodeBleText.notPairedAndroid(label) + else "Could not inspect the BLE RNode services (status $status).", + ) return } val service = gatt.getService(SERVICE_UUID) @@ -195,13 +219,21 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { if (descriptor.uuid != CCCD_UUID) return if (status != BluetoothGatt.GATT_SUCCESS) { - handleGattDisconnect(gatt, "The BLE RNode rejected UART notifications (status $status).") + handleGattDisconnect( + gatt, + if (isAuthenticationFailure(status)) RNodeBleText.notPairedAndroid(label) + else "The BLE RNode rejected UART notifications (status $status).", + ) return } if (!openTcpServer(gatt)) { handleGattDisconnect(gatt, "Could not open the local port for the BLE RNode bridge.") return } + if (resolvedDevice == null) { + val name = scannedName ?: runCatching { gatt.device.name }.getOrNull().orEmpty() + resolvedDevice = ResolvedBleRNode(gatt.device.address, name) + } synchronized(lock) { startupResolved = true startupError = null @@ -239,8 +271,18 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { } } - /** Returns null after BLE notifications and the loopback listener are ready. */ - fun start(targetName: String): String? { + /** + * Returns null after BLE notifications and the loopback listener are ready. + * + * A [target] that is a device address is connected to directly. A device + * name, or an empty target for the first RNode found, is located by + * scanning. [pairedByStarling] makes a missing system pairing an error + * before any connection is attempted. + */ + fun start(target: String, displayName: String? = null, pairedByStarling: Boolean = false): String? { + val trimmedTarget = target.trim() + val address = trimmedTarget.uppercase().takeIf { BluetoothAdapter.checkBluetoothAddress(it) } + val targetName = if (address == null) trimmedTarget else "" val latch = CountDownLatch(1) synchronized(lock) { if (running) return "An Android BLE RNode connection is already active." @@ -248,7 +290,11 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { startupResolved = false startupError = null startupLatch = latch - this.targetName = targetName.trim().takeIf(String::isNotEmpty) + this.targetName = targetName.takeIf(String::isNotEmpty) + targetAddress = address + label = rnodeBleLabel(RNODE_BLE_PREFIX + trimmedTarget, displayName) + scannedName = null + resolvedDevice = null } try { @@ -259,20 +305,42 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { val adapter: BluetoothAdapter = manager.adapter ?: return stopWithError("Bluetooth is not available on this device.") if (!adapter.isEnabled) return stopWithError("Turn on Bluetooth to connect to a BLE RNode.") - scanner = adapter.bluetoothLeScanner - ?: return stopWithError("Android could not start Bluetooth LE scanning.") - val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE_UUID)).build() - val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() - scanner?.startScan(listOf(filter), settings, scanCallback) + this.adapter = adapter + if (address != null) { + val device = adapter.getRemoteDevice(address) + if (displayName.isNullOrBlank()) { + runCatching { device.name }.getOrNull()?.takeIf(String::isNotBlank)?.let { label = it } + } + if (pairedByStarling && device.bondState != BluetoothDevice.BOND_BONDED) { + return stopWithError(RNodeBleText.pairingLost(label)) + } + val connection = device.connectGatt(appContext, false, gattCallback, BluetoothDevice.TRANSPORT_LE) + ?: return stopWithError(RNodeBleText.notFound(label)) + synchronized(lock) { gatt = connection } + } else { + scanner = adapter.bluetoothLeScanner + ?: return stopWithError("Android could not start Bluetooth LE scanning.") + val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(SERVICE_UUID)).build() + val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() + scanner?.startScan(listOf(filter), settings, scanCallback) + } } catch (error: SecurityException) { - return stopWithError("Allow Starling Bluetooth access to connect to the RNode.") + return stopWithError( + if (address != null) RNodeBleText.permission(label) + else "Allow Starling Bluetooth access to connect to the RNode.", + ) } catch (error: Exception) { return stopWithError("Could not start the BLE RNode bridge: ${error.message.orEmpty()}") } val ready = runCatching { latch.await(STARTUP_TIMEOUT_SECONDS, TimeUnit.SECONDS) } .getOrDefault(false) - if (!ready) return stopWithError("Timed out finding the BLE RNode. Keep Starling open and check that the radio is nearby.") + if (!ready) { + return stopWithError( + if (address != null) RNodeBleText.notFound(label) + else "Timed out finding the BLE RNode. Keep Starling open and check that the radio is nearby.", + ) + } val error = synchronized(lock) { startupError } if (error != null) stop() return error @@ -291,13 +359,14 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { startupLatch = null } running = false - mainHandler.removeCallbacks(retryScan) + mainHandler.removeCallbacks(retryConnect) if (adapterStateReceiverRegistered) { adapterStateReceiverRegistered = false runCatching { appContext.unregisterReceiver(adapterStateReceiver) } } runCatching { scanner?.stopScan(scanCallback) } scanner = null + adapter = null runCatching { gatt?.disconnect() } runCatching { gatt?.close() } gatt = null @@ -338,13 +407,39 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { failStartup(message) } else if (running) { closeTcpClient() - scheduleScanRetry() + scheduleReconnect() } } - private fun scheduleScanRetry() { - mainHandler.removeCallbacks(retryScan) - mainHandler.postDelayed(retryScan, RECONNECT_SCAN_DELAY_MS) + /** Opens a new connection to the saved address, at startup or after the link drops. */ + private fun connectToAddress() { + if (!running) return + val address = targetAddress ?: return + try { + val device = adapter?.getRemoteDevice(address) ?: throw IOException("Bluetooth is unavailable.") + val connection = device.connectGatt(appContext, false, gattCallback, BluetoothDevice.TRANSPORT_LE) + ?: throw IOException("Android did not create a BLE connection.") + synchronized(lock) { gatt = connection } + } catch (error: SecurityException) { + handleReconnectFailure(RNodeBleText.permission(label)) + } catch (error: Exception) { + handleReconnectFailure(RNodeBleText.notFound(label)) + } + } + + private fun handleReconnectFailure(message: String) { + val isStarting = synchronized(lock) { !startupResolved } + if (isStarting) { + failStartup(message) + } else if (running) { + closeTcpClient() + scheduleReconnect() + } + } + + private fun scheduleReconnect() { + mainHandler.removeCallbacks(retryConnect) + mainHandler.postDelayed(retryConnect, RECONNECT_SCAN_DELAY_MS) } private fun stopScan() { @@ -368,8 +463,8 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { /** * Android does not reliably report a GATT disconnect when Bluetooth is - * switched off. Drop the link the same way as a lost RNode; the scan retry - * then keeps failing until the adapter is back on and the RNode is found. + * switched off. Drop the link the same way as a lost RNode; the reconnect + * retry then keeps failing until the adapter is back on and the RNode is found. */ private fun handleAdapterOff() { if (!running) return @@ -379,7 +474,7 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { handleGattDisconnect(activeGatt, message) } else { stopScan() - handleScanRestartFailure(message) + handleReconnectFailure(message) } } @@ -400,7 +495,8 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { */ private fun handleGattDisconnect(disconnectedGatt: BluetoothGatt, message: String) { val wasCurrentGatt = synchronized(lock) { - if (gatt !== disconnectedGatt) { + // A direct connection can fail before start() has stored it. + if (gatt != null && gatt !== disconnectedGatt) { false } else { gatt = null @@ -417,9 +513,19 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { closeTcpClient() if (!running) return val isStillStarting = synchronized(lock) { !startupResolved } - if (isStillStarting) failStartup(message) else startScan() + when { + isStillStarting -> failStartup(message) + targetAddress != null -> scheduleReconnect() + else -> startScan() + } } + /** Insufficient authentication or encryption, or a failed authentication: the link needs a pairing. */ + private fun isAuthenticationFailure(status: Int): Boolean = + status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION || + status == BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION || + status == GATT_AUTH_FAIL + private fun onRNodeData(bytes: ByteArray?) { if (bytes == null || bytes.isEmpty()) return val destination = synchronized(lock) { @@ -621,6 +727,8 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { private const val TCP_READ_BUFFER_BYTES = 4096 private const val WRITE_RETRY_DELAY_MS = 30L private const val RECONNECT_SCAN_DELAY_MS = 2_000L + private const val GATT_CONN_TERMINATE_PEER_USER = 0x13 + private const val GATT_AUTH_FAIL = 0x89 private val SERVICE_UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E") private val RX_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E") private val TX_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E") diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt index 2006c19..1e8c259 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidReticulumNodeController.kt @@ -29,6 +29,8 @@ class AndroidReticulumNodeController( override val isSupported: Boolean = true override val supportsRNodeInterfaces: Boolean = true override val supportsBleRNodes: Boolean = true + private val _resolvedBleRNode = MutableStateFlow(null) + override val resolvedBleRNode: StateFlow = _resolvedBleRNode.asStateFlow() private var pendingStateQuery: CompletableDeferred? = null private var watchingServiceProcess = false @@ -36,6 +38,13 @@ class AndroidReticulumNodeController( override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action != ReticulumNodeService.ACTION_STATE) return val state = stateFromIntent(intent) + _resolvedBleRNode.value = if (state is ReticulumNodeState.Running) { + val id = intent.getStringExtra(ReticulumNodeService.EXTRA_RNODE_BLE_ID).orEmpty() + val name = intent.getStringExtra(ReticulumNodeService.EXTRA_RNODE_BLE_NAME).orEmpty() + if (id.isBlank()) null else ResolvedBleRNode(id, name) + } else { + null + } _state.value = state pendingStateQuery?.complete(state) if (state is ReticulumNodeState.Starting || state is ReticulumNodeState.Running) { @@ -166,7 +175,9 @@ class AndroidReticulumNodeController( .put("bandwidth_hz", radio.bandwidthHz) .put("tx_power_dbm", radio.txPowerDbm) .put("spreading_factor", radio.spreadingFactor) - .put("coding_rate", radio.codingRate), + .put("coding_rate", radio.codingRate) + .put(ReticulumNodeService.RNODE_BLE_NAME_KEY, radio.bleName.orEmpty()) + .put(ReticulumNodeService.RNODE_PAIRED_BY_STARLING_KEY, radio.pairedByStarling), ) } val intent = Intent(appContext, ReticulumNodeService::class.java).apply { diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/ReticulumNodeService.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/ReticulumNodeService.kt index d773147..84c582e 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/ReticulumNodeService.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/ReticulumNodeService.kt @@ -44,6 +44,8 @@ class ReticulumNodeService : Service() { private var lastNodeShared = false private var lastNodeTcpStatusJson = "[]" private var lastNodeRNodeStatusJson = "[]" + /** The Bluetooth RNode this run connected to, reported so a saved name can become a device id. */ + @Volatile private var resolvedBleRNode: ResolvedBleRNode? = null @Volatile private var stopping = false @Volatile private var lifecycleGeneration = 0L @@ -101,6 +103,7 @@ class ReticulumNodeService : Service() { val generation = lifecycleGeneration + 1 lifecycleGeneration = generation + resolvedBleRNode = null stopping = false startForegroundCompat() publish(STATE_STARTING) @@ -157,6 +160,7 @@ class ReticulumNodeService : Service() { private fun stopNode(startId: Int) { lifecycleGeneration += 1 + resolvedBleRNode = null stopping = true handler.removeCallbacks(pollStatus) handler.removeCallbacks(pollRrcEvents) @@ -361,6 +365,8 @@ class ReticulumNodeService : Service() { .putExtra(EXTRA_RNODE_STATUS, rnodeStatusJson) .putExtra(EXTRA_SHARED, shared) .putExtra(EXTRA_MESSAGE, message) + .putExtra(EXTRA_RNODE_BLE_ID, resolvedBleRNode?.id.orEmpty()) + .putExtra(EXTRA_RNODE_BLE_NAME, resolvedBleRNode?.name.orEmpty()) sendBroadcast(intent) } @@ -425,16 +431,21 @@ class ReticulumNodeService : Service() { private fun startBleRNodeBridgeIfNeeded() { val radios = JSONArray(rnodeInterfacesJson) - var selectedName: String? = null + var selected: JSONObject? = null for (index in 0 until radios.length()) { - val port = radios.optJSONObject(index)?.optString("port").orEmpty() - if (!port.startsWith("ble://", ignoreCase = true)) continue - if (selectedName != null) throw IllegalArgumentException("Only one BLE RNode can be connected on Android at a time.") - selectedName = port.drop("ble://".length).trim() + val radio = radios.optJSONObject(index) ?: continue + if (!radio.optString("port").startsWith(RNODE_BLE_PREFIX, ignoreCase = true)) continue + if (selected != null) throw IllegalArgumentException("Only one BLE RNode can be connected on Android at a time.") + selected = radio } - if (selectedName != null) { - val error = rnodeBluetoothBridge.start(selectedName) + if (selected != null) { + val error = rnodeBluetoothBridge.start( + target = rnodeBleTarget(selected.optString("port")), + displayName = selected.optString(RNODE_BLE_NAME_KEY).takeIf(String::isNotBlank), + pairedByStarling = selected.optBoolean(RNODE_PAIRED_BY_STARLING_KEY, false), + ) if (error != null) throw IllegalStateException(error) + resolvedBleRNode = rnodeBluetoothBridge.resolvedDevice } } @@ -461,6 +472,11 @@ class ReticulumNodeService : Service() { const val EXTRA_SHARED = "shared" const val EXTRA_RPC_KEY = "rpc_key" const val EXTRA_MESSAGE = "message" + const val EXTRA_RNODE_BLE_ID = "rnode_ble_id" + const val EXTRA_RNODE_BLE_NAME = "rnode_ble_name" + /** Keys Starling adds to an RNode entry for the BLE bridge; the Python runtime ignores them. */ + const val RNODE_BLE_NAME_KEY = "ble_name" + const val RNODE_PAIRED_BY_STARLING_KEY = "paired_by_starling" const val EXTRA_HUB_DESTINATION = "hub_destination" const val EXTRA_LXMF_ADDRESS = "lxmf_address" const val EXTRA_DISPLAY_NAME = "display_name" From f0cb772b8a5fc49ae9c7f2885b9dd2bad14efa07 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:12 -0700 Subject: [PATCH 06/12] feat(ios): find RNodes and connect by peripheral identifier Add a CoreBluetooth scanner that reports signal strength and makes a trial connection to the picked RNode: subscribing to the UART service is when iOS pairs if the RNode requires it. The peripheral identifier is saved and the bridge connects through retrievePeripherals, scanning only to find the same identifier again. The Swift sources have not been compiled; the Kotlin side builds for iosArm64. --- .../sidpatchy/Starling/IosRNodeBlePicker.kt | 168 ++++++++++++++ .../Starling/IosReticulumNodeController.kt | 30 ++- .../StarlingEmbeddedPythonRuntime.swift | 25 +- .../StarlingRNodeBluetoothBridge.swift | 111 ++++++++- .../StarlingRNodeBluetoothScanner.swift | 218 ++++++++++++++++++ 5 files changed, 538 insertions(+), 14 deletions(-) create mode 100644 composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosRNodeBlePicker.kt create mode 100644 iosApp/Sources/Starling/StarlingRNodeBluetoothScanner.swift diff --git a/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosRNodeBlePicker.kt b/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosRNodeBlePicker.kt new file mode 100644 index 0000000..31824b1 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosRNodeBlePicker.kt @@ -0,0 +1,168 @@ +package com.sidpatchy.Starling + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import platform.Foundation.NSURL +import platform.UIKit.UIApplication +import platform.UIKit.UIApplicationOpenSettingsURLString + +/** + * Receives CoreBluetooth results from Swift. It is a named interface so the + * Objective-C export has plain `void` methods for Swift to call. + */ +interface IosRNodeBleListener { + /** [status] is one of the `IOS_RNODE_SCAN_*` values; [code] is only set for a failure. */ + fun onScanStatus(status: String, code: Int) + fun onDevice(identifier: String, name: String, rssi: Int) + + /** [outcome] is one of the `IOS_RNODE_TRIAL_*` values. */ + fun onTrialResult(outcome: String) +} + +const val IOS_RNODE_SCAN_SCANNING = "scanning" +const val IOS_RNODE_SCAN_BLUETOOTH_OFF = "bluetooth_off" +const val IOS_RNODE_SCAN_UNAUTHORIZED = "unauthorized" +const val IOS_RNODE_SCAN_UNSUPPORTED = "unsupported" +const val IOS_RNODE_SCAN_FAILED = "failed" +const val IOS_RNODE_TRIAL_READY = "ready" +const val IOS_RNODE_TRIAL_STALE = "stale" +const val IOS_RNODE_TRIAL_FAILED = "failed" + +/** Maps a failure code from the Swift RNode bridge to the message shown for [name]. */ +internal fun iosRNodeBleProxyError(error: String, name: String): String = + if (!error.startsWith(IOS_RNODE_PROXY_ERROR_PREFIX)) error else when (error.removePrefix(IOS_RNODE_PROXY_ERROR_PREFIX)) { + "not_found" -> RNodeBleText.notFound(name) + "not_paired" -> RNodeBleText.notPairedIos(name) + "pairing_lost" -> RNodeBleText.pairingLost(name) + "permission" -> RNodeBleText.permission(name) + "held_elsewhere" -> RNodeBleText.heldElsewhere(name) + "unknown_id" -> RNodeBleText.unknownToIos(name) + else -> RNodeBleText.notFound(name) + } + +/** Swift prefixes a failure it reports by code, so the wording stays in shared code. */ +const val IOS_RNODE_PROXY_ERROR_PREFIX = "RNODE_BLE:" + +/** Finds RNodes and makes the first trial connection through the Swift CoreBluetooth scanner. */ +class IosRNodeBlePicker(private val runtime: IosPythonRuntime) : RNodeBlePicker, IosRNodeBleListener { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + override val platform = RNodeBlePlatform.IOS + private val _scanStatus = MutableStateFlow(RNodeBleScanStatus.Idle) + override val scanStatus: StateFlow = _scanStatus.asStateFlow() + private val _sightings = MutableSharedFlow( + extraBufferCapacity = 64, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + override val sightings: Flow = _sightings.asSharedFlow() + private val _pairing = MutableStateFlow(RNodeBlePairingState.Idle) + override val pairing: StateFlow = _pairing.asStateFlow() + + private var scanTimeout: Job? = null + private var trialTimeout: Job? = null + private var trialName: String? = null + + override fun startScan() { + scanTimeout?.cancel() + runtime.stopRNodeBleScan() + // iOS asks for Bluetooth access the first time the scanner is used. + runtime.startRNodeBleScan(this) + } + + override fun stopScan() { + scanTimeout?.cancel() + scanTimeout = null + runtime.stopRNodeBleScan() + if (_scanStatus.value == RNodeBleScanStatus.Scanning) _scanStatus.value = RNodeBleScanStatus.Finished + } + + override fun resolveScanBlocker() { + if (_scanStatus.value != RNodeBleScanStatus.PermissionPermanentlyDenied) return + val url = NSURL.URLWithString(UIApplicationOpenSettingsURLString) ?: return + UIApplication.sharedApplication.openURL(url, options = emptyMap(), completionHandler = null) + } + + override fun pair(deviceId: String, name: String) { + trialTimeout?.cancel() + runtime.cancelRNodeBleTrial() + val label = name.ifBlank { "RNode" } + trialName = label + _pairing.value = RNodeBlePairingState.Waiting(label) + runtime.startRNodeBleTrial(deviceId, this) + trialTimeout = scope.launch { + delay(TRIAL_TIMEOUT_MS) + runtime.cancelRNodeBleTrial() + finishTrial(RNodeBlePairingState.Failed(label, RNodeBlePairingFailure.TIMEOUT)) + } + } + + override fun cancelPairing() { + trialTimeout?.cancel() + trialTimeout = null + trialName = null + runtime.cancelRNodeBleTrial() + _pairing.value = RNodeBlePairingState.Idle + } + + /** iOS does not tell apps whether a peripheral is paired. */ + override fun isPaired(deviceId: String): Boolean? = null + + override fun onScanStatus(status: String, code: Int) { + scope.launch { + when (status) { + IOS_RNODE_SCAN_SCANNING -> { + _scanStatus.value = RNodeBleScanStatus.Scanning + scanTimeout?.cancel() + scanTimeout = scope.launch { + delay(SCAN_DURATION_MS) + stopScan() + } + } + IOS_RNODE_SCAN_BLUETOOTH_OFF -> _scanStatus.value = RNodeBleScanStatus.BluetoothOff + IOS_RNODE_SCAN_UNAUTHORIZED -> _scanStatus.value = RNodeBleScanStatus.PermissionPermanentlyDenied + IOS_RNODE_SCAN_UNSUPPORTED -> _scanStatus.value = RNodeBleScanStatus.Unsupported + else -> _scanStatus.value = RNodeBleScanStatus.Failed(code) + } + } + } + + override fun onDevice(identifier: String, name: String, rssi: Int) { + _sightings.tryEmit(RNodeBleSighting(identifier, name, rssi)) + } + + override fun onTrialResult(outcome: String) { + scope.launch { + val label = trialName ?: return@launch + finishTrial( + when (outcome) { + IOS_RNODE_TRIAL_READY -> RNodeBlePairingState.Ready(label) + IOS_RNODE_TRIAL_STALE -> RNodeBlePairingState.Failed(label, RNodeBlePairingFailure.STALE_BOND) + else -> RNodeBlePairingState.Failed(label, RNodeBlePairingFailure.OTHER) + }, + ) + } + } + + private fun finishTrial(result: RNodeBlePairingState) { + if (trialName == null) return + trialName = null + trialTimeout?.cancel() + trialTimeout = null + _pairing.value = result + } + + private companion object { + const val SCAN_DURATION_MS = 20_000L + const val TRIAL_TIMEOUT_MS = 60_000L + } +} diff --git a/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosReticulumNodeController.kt b/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosReticulumNodeController.kt index 72c760e..03810cd 100644 --- a/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosReticulumNodeController.kt +++ b/composeApp/src/iosMain/kotlin/com/sidpatchy/Starling/IosReticulumNodeController.kt @@ -23,9 +23,20 @@ import kotlin.time.TimeSource interface IosPythonRuntime { val dataDirectory: String fun invoke(command: String): String - /** Start a CoreBluetooth UART bridge; an empty name accepts the first RNode. */ - fun startRNodeBleProxy(deviceName: String): String? + /** + * Start a CoreBluetooth UART bridge. [target] is a peripheral identifier, a + * device name saved by an older version, or empty to accept the first RNode. + * Returns null on success, or a message or `RNODE_BLE:` failure code. + */ + fun startRNodeBleProxy(target: String): String? fun stopRNodeBleProxy() + /** The peripheral the bridge connected to, as "identifiername"; null before a successful start. */ + fun rnodeBleProxyDevice(): String? + fun startRNodeBleScan(listener: IosRNodeBleListener) + fun stopRNodeBleScan() + /** Connects once and subscribes to the UART service, which is when iOS pairs if the RNode requires it. */ + fun startRNodeBleTrial(identifier: String, listener: IosRNodeBleListener) + fun cancelRNodeBleTrial() } /** RNS/LXMF node lifecycle backed by the bundled reference Python modules. */ @@ -40,6 +51,10 @@ class IosReticulumNodeController( override val state: StateFlow = _state.asStateFlow() override val isSupported: Boolean = true override val supportsRNodeInterfaces: Boolean = true + override val supportsBleRNodes: Boolean = true + override val rnodeBlePicker: RNodeBlePicker = IosRNodeBlePicker(runtime) + private val _resolvedBleRNode = MutableStateFlow(null) + override val resolvedBleRNode: StateFlow = _resolvedBleRNode.asStateFlow() val bridgeEvents: SharedFlow = _bridgeEvents.asSharedFlow() private var activeConfig: ReticulumNodeConfig? = null @@ -48,7 +63,7 @@ class IosReticulumNodeController( private var bleProxyStarted = false override suspend fun start(config: ReticulumNodeConfig) = operations.withLock { - config.validationError()?.let { + config.validationError(supportsBleRNodes)?.let { _state.value = ReticulumNodeState.Failed(it) return@withLock } @@ -92,10 +107,16 @@ class IosReticulumNodeController( }.getOrElse { it.message ?: "Could not start the iOS BLE RNode bridge." } if (error != null) { runCatching { withContext(Dispatchers.Default) { runtime.stopRNodeBleProxy() } } - _state.value = ReticulumNodeState.Failed(error) + _state.value = ReticulumNodeState.Failed( + iosRNodeBleProxyError(error, rnodeBleLabel(bleInterface.port, bleInterface.bleName)), + ) return@withLock } bleProxyStarted = true + _resolvedBleRNode.value = runCatching { runtime.rnodeBleProxyDevice() }.getOrNull()?.let { device -> + val identifier = device.substringBefore('\t').trim() + if (identifier.isEmpty()) null else ResolvedBleRNode(identifier, device.substringAfter('\t', "").trim()) + } } runtimeUsed = true val response = try { @@ -236,6 +257,7 @@ class IosReticulumNodeController( } private suspend fun stopBleProxy() { + _resolvedBleRNode.value = null if (!bleProxyStarted) return bleProxyStarted = false runCatching { withContext(Dispatchers.Default) { runtime.stopRNodeBleProxy() } } diff --git a/iosApp/Sources/Starling/StarlingEmbeddedPythonRuntime.swift b/iosApp/Sources/Starling/StarlingEmbeddedPythonRuntime.swift index 9428859..e56c0dc 100644 --- a/iosApp/Sources/Starling/StarlingEmbeddedPythonRuntime.swift +++ b/iosApp/Sources/Starling/StarlingEmbeddedPythonRuntime.swift @@ -9,6 +9,7 @@ final class StarlingEmbeddedPythonRuntime: NSObject, IosPythonRuntime { private let executablePath: String private let runtimeLock = NSRecursiveLock() private let rnodeBluetoothBridge = StarlingRNodeBluetoothBridge() + private let rnodeBluetoothScanner = StarlingRNodeBluetoothScanner() private var didInitialize = false private var startupError: String? @@ -60,11 +61,31 @@ final class StarlingEmbeddedPythonRuntime: NSObject, IosPythonRuntime { return StarlingPythonInvoke(command) } - func startRNodeBleProxy(deviceName: String) -> String? { - rnodeBluetoothBridge.start(targetName: deviceName.isEmpty ? nil : deviceName) + func startRNodeBleProxy(target: String) -> String? { + rnodeBluetoothBridge.start(target: target.isEmpty ? nil : target) } func stopRNodeBleProxy() { rnodeBluetoothBridge.stop() } + + func rnodeBleProxyDevice() -> String? { + rnodeBluetoothBridge.connectedDevice + } + + func startRNodeBleScan(listener: IosRNodeBleListener) { + rnodeBluetoothScanner.startScan(listener: listener) + } + + func stopRNodeBleScan() { + rnodeBluetoothScanner.stopScan() + } + + func startRNodeBleTrial(identifier: String, listener: IosRNodeBleListener) { + rnodeBluetoothScanner.startTrial(identifier: identifier, listener: listener) + } + + func cancelRNodeBleTrial() { + rnodeBluetoothScanner.cancelTrial() + } } diff --git a/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift b/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift index 31ffa30..08c7ee3 100644 --- a/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift +++ b/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift @@ -21,6 +21,12 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB private var listener: NWListener? private var tcpConnection: NWConnection? private var targetName: String? + /// Set when the saved RNode is a peripheral identifier: connect to that peripheral only. + private var targetIdentifier: UUID? + /// False when iOS had no record of the saved identifier and a scan has to find it again. + private var identifierKnown = false + private var discoveredName: String? + private var resolvedDevice: String? private var startWaiter: DispatchSemaphore? private var startupError: String? private var startupResolved = false @@ -29,8 +35,24 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB private var pendingWrite = Data() private var pendingRead = Data() - /// Returns nil when the BLE link and loopback listener are ready, or a user-facing error. - func start(targetName: String?) -> String? { + /// Failure codes that shared code turns into messages naming the RNode. + private static let errorPrefix = "RNODE_BLE:" + private static let notFound = errorPrefix + "not_found" + private static let notPaired = errorPrefix + "not_paired" + private static let pairingLost = errorPrefix + "pairing_lost" + private static let permission = errorPrefix + "permission" + private static let heldElsewhere = errorPrefix + "held_elsewhere" + private static let unknownIdentifier = errorPrefix + "unknown_id" + + /// The connected peripheral as "identifiername", or nil before a successful start. + var connectedDevice: String? { queue.sync { resolvedDevice } } + + /// Returns nil when the BLE link and loopback listener are ready, or a user-facing error + /// or failure code. A target that is a peripheral identifier is connected to directly; + /// a device name, or no target for the first RNode found, is located by scanning. + func start(target: String?) -> String? { + let trimmedTarget = target?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let identifier = UUID(uuidString: trimmedTarget) let waiter = DispatchSemaphore(value: 0) queue.async { guard self.central == nil, self.listener == nil else { @@ -38,7 +60,11 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB waiter.signal() return } - self.targetName = targetName?.trimmingCharacters(in: .whitespacesAndNewlines) + self.targetName = identifier == nil ? trimmedTarget : nil + self.targetIdentifier = identifier + self.identifierKnown = false + self.discoveredName = nil + self.resolvedDevice = nil self.startWaiter = waiter self.startupError = nil self.startupResolved = false @@ -47,8 +73,12 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB } guard waiter.wait(timeout: .now() + 40) == .success else { + let known = queue.sync { identifierKnown } stop() - return "Timed out connecting to the BLE RNode. Check that it is powered on and nearby." + if identifier == nil { + return "Timed out connecting to the BLE RNode. Check that it is powered on and nearby." + } + return known ? Self.notFound : Self.unknownIdentifier } return queue.sync { startupError } } @@ -65,6 +95,7 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB self.tcpConnection?.cancel() self.listener?.cancel() self.central = nil + self.resolvedDevice = nil self.peripheral = nil self.rxCharacteristic = nil self.txCharacteristic = nil @@ -82,12 +113,21 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB switch central.state { case .poweredOn: guard !scanning, running else { return } + if let targetIdentifier, + let known = central.retrievePeripherals(withIdentifiers: [targetIdentifier]).first { + identifierKnown = true + peripheral = known + central.connect(known, options: nil) + return + } + // No saved identifier, or iOS no longer has it: scan, and for a saved + // identifier accept only that same peripheral. scanning = true central.scanForPeripherals(withServices: [Self.serviceUUID], options: nil) case .poweredOff: resolveStart(error: "Turn on Bluetooth to connect to a BLE RNode.") case .unauthorized: - resolveStart(error: "Allow Starling to use Bluetooth in iOS Settings.") + resolveStart(error: targetIdentifier == nil ? "Allow Starling to use Bluetooth in iOS Settings." : Self.permission) case .unsupported: resolveStart(error: "Bluetooth LE is not available on this device.") case .resetting, .unknown: @@ -105,13 +145,17 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB ) { let name = (advertisementData[CBAdvertisementDataLocalNameKey] as? String) ?? peripheral.name ?? "" let matchesTarget: Bool - if let targetName, !targetName.isEmpty { + if let targetIdentifier { + matchesTarget = peripheral.identifier == targetIdentifier + } else if let targetName, !targetName.isEmpty { matchesTarget = name.caseInsensitiveCompare(targetName) == .orderedSame } else { matchesTarget = name.hasPrefix("RNode") } guard matchesTarget else { return } + if targetIdentifier != nil { identifierKnown = true } + if !name.isEmpty { discoveredName = name } scanning = false central.stopScan() self.peripheral = peripheral @@ -124,7 +168,15 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { - if running { + if running, targetIdentifier != nil { + if Self.isPairingRemoved(error) { + resolveStart(error: Self.pairingLost) + } else if !startupResolved { + resolveStart(error: Self.notFound) + } else { + central.connect(peripheral, options: nil) + } + } else if running { scanning = false central.scanForPeripherals(withServices: [Self.serviceUUID], options: nil) scanning = true @@ -138,6 +190,20 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB guard running else { return } rxCharacteristic = nil txCharacteristic = nil + if !startupResolved, targetIdentifier != nil, let error { + // The link dropped before the UART service was usable. + if Self.isPairingRemoved(error) { + resolveStart(error: Self.pairingLost) + } else if Self.isAuthenticationFailure(error) { + resolveStart(error: Self.notPaired) + } else if Self.isCoreBluetoothError(error, code: CBError.Code.peripheralDisconnected.rawValue) { + // The RNode ended the connection itself, as it does while another device holds it. + resolveStart(error: Self.heldElsewhere) + } else { + resolveStart(error: Self.notFound) + } + return + } central.connect(peripheral, options: nil) } @@ -185,13 +251,21 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB ) { guard characteristic.uuid == Self.txUUID else { return } if let error { - resolveStart(error: "Could not subscribe to BLE RNode data: \(error.localizedDescription)") + if Self.isPairingRemoved(error) { + resolveStart(error: Self.pairingLost) + } else if Self.isAuthenticationFailure(error) { + resolveStart(error: Self.notPaired) + } else { + resolveStart(error: "Could not subscribe to BLE RNode data: \(error.localizedDescription)") + } return } guard characteristic.isNotifying else { resolveStart(error: "The BLE RNode did not enable UART notifications.") return } + let name = discoveredName ?? peripheral.name ?? "" + resolvedDevice = peripheral.identifier.uuidString + "\t" + name flushPendingWrites() startLoopbackListener() } @@ -302,6 +376,27 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB pendingRead.removeAll(keepingCapacity: true) } + /// CBError.peerRemovedPairingInformation: the RNode discarded its pairing with this iPhone. + static func isPairingRemoved(_ error: Error?) -> Bool { + isCoreBluetoothError(error, code: 14) + } + + /// The UART service needs an authenticated or encrypted link and iOS did not establish one. + static func isAuthenticationFailure(_ error: Error?) -> Bool { + guard let error = error as NSError? else { return false } + if error.domain == CBATTErrorDomain { + return error.code == CBATTError.Code.insufficientAuthentication.rawValue + || error.code == CBATTError.Code.insufficientEncryption.rawValue + } + // CBError.encryptionTimedOut + return error.domain == CBErrorDomain && error.code == 15 + } + + static func isCoreBluetoothError(_ error: Error?, code: Int) -> Bool { + guard let error = error as NSError? else { return false } + return error.domain == CBErrorDomain && error.code == code + } + private func resolveStart(error: String?) { guard !startupResolved else { return } startupResolved = true diff --git a/iosApp/Sources/Starling/StarlingRNodeBluetoothScanner.swift b/iosApp/Sources/Starling/StarlingRNodeBluetoothScanner.swift new file mode 100644 index 0000000..4f52626 --- /dev/null +++ b/iosApp/Sources/Starling/StarlingRNodeBluetoothScanner.swift @@ -0,0 +1,218 @@ +import ComposeApp +import CoreBluetooth +import Foundation + +/// Finds nearby RNodes for Settings and makes the first trial connection to the one +/// that is picked. It is separate from the bridge that carries RNode traffic and is +/// only used while the node is stopped. +final class StarlingRNodeBluetoothScanner: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, @unchecked Sendable { + private static var serviceUUID: CBUUID { CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E") } + private static var txUUID: CBUUID { CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") } + + /// Carries a Kotlin listener onto the Bluetooth queue; its methods are safe to call from any thread. + private struct Listener: @unchecked Sendable { + let value: IosRNodeBleListener + } + + private let queue = DispatchQueue(label: "com.sidpatchy.Starling.rnode-ble-scan") + private var central: CBCentralManager? + /// Peripherals must be retained to be connected to after the scan stops. + private var discovered: [UUID: CBPeripheral] = [:] + private var scanListener: IosRNodeBleListener? + private var scanning = false + private var trialListener: IosRNodeBleListener? + private var trialIdentifier: UUID? + private var trialPeripheral: CBPeripheral? + + /// Creating the central manager is what makes iOS ask for Bluetooth access. + func startScan(listener: IosRNodeBleListener) { + let listener = Listener(value: listener) + queue.async { + self.scanListener = listener.value + if let central = self.central { + self.apply(state: central.state) + } else { + self.central = CBCentralManager(delegate: self, queue: self.queue) + } + } + } + + func stopScan() { + queue.async { + self.scanListener = nil + self.endScan() + } + } + + /// Connects, finds the UART service, and subscribes to it. iOS shows its pairing + /// prompt during the subscription if the RNode requires pairing. + func startTrial(identifier: String, listener: IosRNodeBleListener) { + let listener = Listener(value: listener) + queue.async { + self.endTrial() + self.endScan() + guard let uuid = UUID(uuidString: identifier) else { + listener.value.onTrialResult(outcome: "failed") + return + } + self.trialListener = listener.value + self.trialIdentifier = uuid + if let central = self.central { + self.apply(state: central.state) + } else { + self.central = CBCentralManager(delegate: self, queue: self.queue) + } + } + } + + func cancelTrial() { + queue.async { self.endTrial() } + } + + func centralManagerDidUpdateState(_ central: CBCentralManager) { + apply(state: central.state) + } + + private func apply(state: CBManagerState) { + switch state { + case .poweredOn: + if trialIdentifier != nil { + beginTrial() + } else if scanListener != nil, !scanning, let central { + scanning = true + // Repeated advertisements keep the signal strength current. + central.scanForPeripherals( + withServices: [Self.serviceUUID], + options: [CBCentralManagerScanOptionAllowDuplicatesKey: true] + ) + scanListener?.onScanStatus(status: "scanning", code: 0) + } + case .poweredOff: + scanning = false + scanListener?.onScanStatus(status: "bluetooth_off", code: 0) + finishTrial(outcome: "failed") + case .unauthorized: + scanning = false + scanListener?.onScanStatus(status: "unauthorized", code: 0) + finishTrial(outcome: "failed") + case .unsupported: + scanning = false + scanListener?.onScanStatus(status: "unsupported", code: 0) + finishTrial(outcome: "failed") + case .resetting, .unknown: + break + @unknown default: + scanning = false + scanListener?.onScanStatus(status: "failed", code: Int32(state.rawValue)) + finishTrial(outcome: "failed") + } + } + + func centralManager( + _ central: CBCentralManager, + didDiscover peripheral: CBPeripheral, + advertisementData: [String: Any], + rssi RSSI: NSNumber + ) { + // 127 means the signal strength is not available for this advertisement. + guard scanning, RSSI.intValue != 127 else { return } + discovered[peripheral.identifier] = peripheral + let name = (advertisementData[CBAdvertisementDataLocalNameKey] as? String) ?? peripheral.name ?? "" + scanListener?.onDevice( + identifier: peripheral.identifier.uuidString, + name: name, + rssi: Int32(RSSI.intValue) + ) + } + + private func beginTrial() { + guard let central, let trialIdentifier, trialPeripheral == nil else { return } + guard let peripheral = discovered[trialIdentifier] + ?? central.retrievePeripherals(withIdentifiers: [trialIdentifier]).first else { + finishTrial(outcome: "failed") + return + } + trialPeripheral = peripheral + peripheral.delegate = self + central.connect(peripheral, options: nil) + } + + func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + guard peripheral === trialPeripheral else { return } + peripheral.discoverServices([Self.serviceUUID]) + } + + func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { + guard peripheral === trialPeripheral else { return } + finishTrial(outcome: Self.outcome(for: error)) + } + + func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { + guard peripheral === trialPeripheral else { return } + finishTrial(outcome: Self.outcome(for: error)) + } + + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + guard peripheral === trialPeripheral else { return } + guard error == nil, + let service = peripheral.services?.first(where: { $0.uuid == Self.serviceUUID }) else { + finishTrial(outcome: Self.outcome(for: error)) + return + } + peripheral.discoverCharacteristics([Self.txUUID], for: service) + } + + func peripheral( + _ peripheral: CBPeripheral, + didDiscoverCharacteristicsFor service: CBService, + error: Error? + ) { + guard peripheral === trialPeripheral else { return } + guard error == nil, + let tx = service.characteristics?.first(where: { $0.uuid == Self.txUUID }) else { + finishTrial(outcome: Self.outcome(for: error)) + return + } + peripheral.setNotifyValue(true, for: tx) + } + + func peripheral( + _ peripheral: CBPeripheral, + didUpdateNotificationStateFor characteristic: CBCharacteristic, + error: Error? + ) { + guard peripheral === trialPeripheral, characteristic.uuid == Self.txUUID else { return } + if error == nil, characteristic.isNotifying { + finishTrial(outcome: "ready") + } else { + finishTrial(outcome: Self.outcome(for: error)) + } + } + + private static func outcome(for error: Error?) -> String { + StarlingRNodeBluetoothBridge.isPairingRemoved(error) ? "stale" : "failed" + } + + private func finishTrial(outcome: String) { + guard let listener = trialListener else { return } + endTrial() + listener.onTrialResult(outcome: outcome) + } + + /// Drops the trial connection; the RNode is left free for the node to connect to. + private func endTrial() { + trialListener = nil + trialIdentifier = nil + if let peripheral = trialPeripheral { + trialPeripheral = nil + peripheral.delegate = nil + central?.cancelPeripheralConnection(peripheral) + } + } + + private func endScan() { + guard scanning else { return } + scanning = false + if central?.state == .poweredOn { central?.stopScan() } + } +} From 0b0ac42ae4e3854e4a8c0fc4a08cd5921f448a28 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:24:12 -0700 Subject: [PATCH 07/12] docs: describe choosing a Bluetooth RNode in Settings --- docs/RETICULUM_RUNTIME.md | 4 ++-- iosApp/README.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/RETICULUM_RUNTIME.md b/docs/RETICULUM_RUNTIME.md index 11cabd9..eb2c094 100644 --- a/docs/RETICULUM_RUNTIME.md +++ b/docs/RETICULUM_RUNTIME.md @@ -8,7 +8,7 @@ - Desktop runs the same Python bridge in a child process, installing those pinned packages into a Starling-private virtual environment on first explicit connection. Windows and macOS use this same host-Python flow; Flatpak ships the Python/RNS dependencies inside its app bundle. - Android starts the node on demand from Settings in a dedicated process and foreground service. Android shows an ongoing notification while it is running. - Embedded mode configures multiple outbound `TCPClientInterface` instances from the TCP peer list. Each connection can have its own optional IFAC network name and passphrase; both must match that peer's interface settings. RNS transport-node routing is explicitly disabled; Starling is a client, not a gateway. -- Desktop can configure one or more reference `RNodeInterface` instances over serial ports (for example `/dev/ttyUSB0`) or the RNS TCP RNode transport. iOS and Android support RNodes over TCP/Wi-Fi (`tcp://host`, RNode's default TCP port 7633) and one BLE RNode at a time (`ble://device name`, or bare `ble://` to select the first nearby RNode). iOS uses CoreBluetooth and Android uses `BluetoothGatt` to bridge the Nordic UART service to a loopback TCP socket consumed by RNS's TCP RNode transport. Direct USB serial is not available on either mobile platform. Enter the radio frequency, bandwidth, transmit power, spreading factor, and coding rate as required by the radio. The RNode must already have compatible RNode firmware installed. +- Desktop can configure one or more reference `RNodeInterface` instances over serial ports (for example `/dev/ttyUSB0`) or the RNS TCP RNode transport. iOS and Android support RNodes over Wi-Fi (the RNode's default TCP port 7633) and one Bluetooth RNode at a time, chosen from a list of nearby RNodes in Settings. iOS uses CoreBluetooth and Android uses `BluetoothGatt` to bridge the Nordic UART service to a loopback TCP socket consumed by RNS's TCP RNode transport. Direct USB serial is not available on either mobile platform. Enter the radio frequency, bandwidth, transmit power, spreading factor, and coding rate as required by the radio. The RNode must already have compatible RNode firmware installed. - Advanced mode attaches to a Reticulum shared instance already running on the same device. Since Starling has a private config directory, the existing instance must be configured with a shared RPC key and the default local ports (37428/37429). This is not a generic remote-daemon management protocol. - Android config and identity files live under `noBackupFilesDir/reticulum`, to avoid copying identity material through Android backup/restore. Desktop state is stored in the user's Starling application-data directory. iOS stores RNS identity/config under app-private Application Support and excludes that directory from device backup. - A host-side smoke test against reference RNS 1.5.5 has verified both an outbound Starling TCP client connecting to a local RNS TCP server and the advanced shared-instance/RPC-key handshake. This validates the generated RNS config and Python bridge, not the Android service on a physical device. @@ -33,7 +33,7 @@ The desktop adapter supports serial, while mobile adapters support TCP/Wi-Fi and ## Mobile RNode setup 1. Flash a supported radio with compatible RNode firmware and configure its Wi-Fi TCP service or Nordic UART BLE service. -2. In Starling's embedded-node settings, add an RNode and use `tcp://host` for Wi-Fi (TCP port 7633) or `ble://device name` for BLE. Bare `ble://` selects the first nearby RNode. Android also accepts a BLE device address. +2. In Starling's embedded-node settings, add an RNode and choose **Bluetooth** or **Wi-Fi** under **Connect over**. For Wi-Fi, enter the RNode's host name or IP address (TCP port 7633). For Bluetooth, tap **Find RNode** with the node stopped, pick the radio from the list, and enter the PIN shown on the RNode's screen if the phone asks for one. Starling saves the device itself (its Bluetooth address on Android, its peripheral identifier on iOS) and connects to that device only. A radio saved by name in an older version keeps working and is saved by device after its next successful connection; a saved bare `ble://` still connects to the first RNode found until a specific one is chosen. 3. Enter the radio frequency, bandwidth, transmit power, spreading factor, and coding rate to match the radio and local regulations. The current Android RNS adapter limits bandwidth to 500 kHz. Android requests Bluetooth scan/connect permission when a BLE interface is started. On mobile, Starling bridges BLE UART bytes to a local TCP socket and uses RNS's TCP RNode transport; Reticulum continues to perform radio detection/configuration and packet framing. TCP/Wi-Fi connects directly through the same RNS adapter. Only one BLE radio can be connected at a time per app instance. diff --git a/iosApp/README.md b/iosApp/README.md index 09865e2..1eb6a7e 100644 --- a/iosApp/README.md +++ b/iosApp/README.md @@ -22,11 +22,11 @@ uses PyCA `cryptography`, built as device and simulator iOS wheels and packaged frameworks. RNS identities and config live in app-private Application Support; chat preferences and history use the shared persisted-state codec. iOS does not provide an Android-style background service, so live networking is foreground-only. -For RNode radios, use `tcp://host` for a Wi-Fi RNode on port 7633, or `ble://device name` -for a BLE RNode advertising the Nordic UART service. A bare `ble://` selects the first -nearby device advertising as an RNode. BLE runs through CoreBluetooth and is proxied +For RNode radios, choose Wi-Fi and enter the RNode's host (port 7633), or choose Bluetooth +and pick the radio with Find RNode in Settings. Starling saves the peripheral's identifier +and connects to that RNode only. BLE runs through CoreBluetooth and is proxied over loopback to the bundled RNS TCP RNode transport; approve any iOS Bluetooth pairing -prompt. Direct USB serial is unavailable on iOS or Android. +prompt the first time Starling connects. Direct USB serial is unavailable on iOS or Android. The unsigned release IPA workflow prepares the pinned Python support framework, builds the release Compose framework, asks xtool to generate an Xcode project, From 73aacdaba5f7a4a51215876335a8b4f3fd8bcfb3 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:02:47 -0700 Subject: [PATCH 08/12] fix(settings): polish the RNode picker screens - Tell same-name RNodes apart by the last two bytes of their id, written like the end of a Bluetooth address (77:10). - Show "Choose an RNode..." in the card only after a start was tried without one, not as soon as the card is empty. - Title the pairing steps "Pair with {name}". - Show "Not paired" and "Forget" in the muted colour; pairing is optional, so neither is an error. - Stack the buttons of the failed-pairing step so they fit narrow screens and large fonts. - Keep each example serial port path on one line. --- .../Starling/RNodeBluetoothPicker.kt | 47 ++++++++++++------- .../com/sidpatchy/Starling/RNodeConnection.kt | 8 +++- .../com/sidpatchy/Starling/SettingsPage.kt | 7 ++- .../sidpatchy/Starling/RNodeConnectionTest.kt | 3 +- 4 files changed, 44 insertions(+), 21 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt index cf857a8..2b26a4e 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt @@ -98,7 +98,12 @@ internal fun RNodeConnectionEditor( modifier = Modifier.fillMaxWidth(), label = { Text("Serial port") }, supportingText = { - Text("For example /dev/ttyUSB0, COM3 or /dev/cu.usbserial-0001", color = Muted, fontSize = 10.sp) + // Word joiners keep each example path on one line. + Text( + "For example /\u2060dev/\u2060ttyUSB0, COM3 or /\u2060dev/\u2060cu.usbserial-0001", + color = Muted, + fontSize = 10.sp, + ) }, singleLine = true, enabled = !locked, @@ -161,7 +166,8 @@ private fun RNodeBluetoothDevice( Text(name, modifier = Modifier.weight(1f), color = Ink, fontSize = 13.sp, fontWeight = FontWeight.Medium) when { paired == true -> Text("Paired", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Medium) - paired == false -> Text("Not paired", color = ErrorText, fontSize = 11.sp, fontWeight = FontWeight.Medium) + // Pairing is optional, so a missing pairing is not shown as an error. + paired == false -> Text("Not paired", color = Muted, fontSize = 11.sp, fontWeight = FontWeight.Medium) !android && savedId != null -> Text("Saved", color = Accent, fontSize = 11.sp, fontWeight = FontWeight.Medium) } @@ -190,7 +196,7 @@ private fun RNodeBluetoothDevice( pairedByStarling = false, ), ) - }) { Text("Forget", color = ErrorText) } + }) { Text("Forget", color = Muted) } } } } @@ -315,7 +321,9 @@ private fun RNodeScanDialog( val device = selected AlertDialog( onDismissRequest = onDismiss, - title = { Text("Choose your RNode", color = Ink) }, + title = { + Text(if (device == null) "Choose your RNode" else "Pair with ${device.second.ifBlank { "RNode" }}", color = Ink) + }, text = { Column( modifier = Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState()), @@ -367,24 +375,30 @@ private fun RNodeScanDialog( } }, confirmButton = { - Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { - if (device == null) { - if (scanStatus == RNodeBleScanStatus.Scanning) { - TextButton(onClick = { picker.stopScan() }) { Text("Stop", color = Accent) } - } else if (scanStatus != RNodeBleScanStatus.Unsupported) { - TextButton( - enabled = now - lastSearchAt >= RESCAN_DEBOUNCE_MILLIS, - onClick = { search() }, - ) { Text("Rescan") } - } - } else if (pairing is RNodeBlePairingState.Failed) { + if (device != null && pairing is RNodeBlePairingState.Failed) { + // Stacked, so three buttons fit a narrow screen or a large font. + Column(horizontalAlignment = Alignment.End) { TextButton(onClick = { picker.pair(device.first, device.second) }) { Text("Try again", color = Accent) } if (android) { // Pairing is not required to save an RNode; it may accept connections without it. TextButton(onClick = { onChosen(device.first, device.second, false) }) { Text("Skip pairing") } } + TextButton(onClick = onDismiss) { Text("Cancel") } + } + } else { + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (device == null) { + if (scanStatus == RNodeBleScanStatus.Scanning) { + TextButton(onClick = { picker.stopScan() }) { Text("Stop", color = Accent) } + } else if (scanStatus != RNodeBleScanStatus.Unsupported) { + TextButton( + enabled = now - lastSearchAt >= RESCAN_DEBOUNCE_MILLIS, + onClick = { search() }, + ) { Text("Rescan") } + } + } + TextButton(onClick = onDismiss) { Text("Cancel") } } - TextButton(onClick = onDismiss) { Text("Cancel") } } }, ) @@ -399,7 +413,6 @@ private fun RNodePairingStep(name: String, pairing: RNodeBlePairingState, platfo ) { when (pairing) { RNodeBlePairingState.Idle, is RNodeBlePairingState.Waiting -> if (android) { - Text("Pair with $name", color = Ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold) Text( "If Android asks, enter the PIN shown on your RNode's screen, then tap Pair.", color = Ink, diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt index 95dcbd5..f658949 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt @@ -183,7 +183,7 @@ data class RNodeScanRow( val rssi: Int, /** The saved device, or one already paired with this phone. */ val pinned: Boolean, - /** The last four characters of the id, set when another row has the same name. */ + /** The last two bytes of the id, like 77:10, set when another row has the same name. */ val idSuffix: String?, ) @@ -252,7 +252,7 @@ class RNodeScanList( name = entry.name, rssi = entry.rssi, pinned = entry.pinned, - idSuffix = if (entry.name.lowercase() in sharedNames) id.takeLast(4) else null, + idSuffix = if (entry.name.lowercase() in sharedNames) rnodeIdSuffix(id) else null, ) } } @@ -265,6 +265,10 @@ class RNodeScanList( ) } +/** The last two bytes of a device id, written like the end of a Bluetooth address. */ +internal fun rnodeIdSuffix(id: String): String = + id.filter(Char::isLetterOrDigit).takeLast(4).chunked(2).joinToString(":") + /** * How long to wait before starting another search. Android silently returns * nothing once an app starts more than [maxStarts] searches in [windowMillis], diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt index 888fcaf..81ed06e 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/SettingsPage.kt @@ -765,7 +765,12 @@ internal fun SettingsPage( enabled = !isRunning && !isStarting, ) } - radio.validationError(supportsBleRNodes)?.let { validationError -> + // An RNode that is not chosen yet is not an error until a start is tried. + radio.validationError(supportsBleRNodes)?.takeIf { validationError -> + validationError != RNodeBleText.CHOOSE_BEFORE_START || + validationError == connectionInputError || + validationError == (nodeState as? ReticulumNodeState.Failed)?.message + }?.let { validationError -> Text(validationError, color = ErrorText, fontSize = 10.sp) } } diff --git a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt index cee34f8..d30d55e 100644 --- a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt +++ b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt @@ -187,7 +187,8 @@ class RNodeConnectionTest { val rows = list.rows(20) assertEquals(3, rows.size) - assertEquals(listOf("1:22", "3:44", null), rows.map { it.idSuffix }) + assertEquals(listOf("11:22", "33:44", null), rows.map { it.idSuffix }) + assertEquals("34:56", rnodeIdSuffix("6E400001-B5A3-F393-E0A9-E50E24DC3456")) } @Test From 2021bd844a041159fe6b0c59cf9fcbe0d595aaa4 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:21:16 -0700 Subject: [PATCH 09/12] fix(android): tighten RNode scan, pairing errors and bond state List only devices named like an RNode in the search dialog, on Android and iOS; other radios offer the same UART service. Replace the pairing failure message that showed a raw reason code. Check the saved RNode pairing again when the app returns to the front or Android reports a pairing change, so a pairing removed in Bluetooth settings shows as Not paired. --- .../Starling/AndroidRNodeBlePicker.kt | 38 +++++++++++++++++++ .../com/sidpatchy/Starling/MainActivity.kt | 1 + .../Starling/RNodeBluetoothPicker.kt | 5 +++ .../com/sidpatchy/Starling/RNodeConnection.kt | 23 ++++++++++- .../sidpatchy/Starling/RNodeConnectionTest.kt | 30 ++++++++++++++- 5 files changed, 95 insertions(+), 2 deletions(-) diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt index b84d51d..0fe4267 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt @@ -25,6 +25,7 @@ import android.os.Build import android.os.ParcelUuid import android.os.SystemClock import android.provider.Settings +import android.util.Log import androidx.core.content.ContextCompat import androidx.core.location.LocationManagerCompat import kotlinx.coroutines.CoroutineScope @@ -33,6 +34,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow @@ -40,6 +42,8 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.merge import kotlinx.coroutines.launch import java.util.UUID @@ -73,6 +77,33 @@ internal class AndroidRNodeBlePicker( private val _pairing = MutableStateFlow(RNodeBlePairingState.Idle) override val pairing: StateFlow = _pairing.asStateFlow() + private val resumes = MutableSharedFlow( + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** + * A pairing can be removed in Android's Bluetooth settings. Android reports + * that while the app is listening; coming back to the app covers the rest. + */ + override val pairingChanges: Flow = merge( + resumes, + callbackFlow { + val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) trySend(Unit) + } + } + ContextCompat.registerReceiver( + appContext, + receiver, + IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), + ContextCompat.RECEIVER_EXPORTED, + ) + awaitClose { runCatching { appContext.unregisterReceiver(receiver) } } + }, + ) + private var scanJob: Job? = null private var activeScanner: BluetoothLeScanner? = null private val scanStarts = mutableListOf() @@ -194,6 +225,11 @@ internal class AndroidRNodeBlePicker( runCatching { startActivity(intent) } } + /** The app is in front again; a pairing may have changed while it was not. */ + fun onResume() { + resumes.tryEmit(Unit) + } + override fun isPaired(deviceId: String): Boolean? { if (!hasPermissions(connectPermissions())) return null return runCatching { remoteDevice(deviceId)?.bondState == BluetoothDevice.BOND_BONDED }.getOrNull() @@ -376,6 +412,7 @@ internal class AndroidRNodeBlePicker( private fun failPairing(reason: RNodeBlePairingFailure, code: Int) { if (pairingDevice == null) return val name = pairingName + Log.d(TAG, "Pairing failed: $reason (code $code)") endPairing() _pairing.value = RNodeBlePairingState.Failed(name, reason, code) } @@ -420,6 +457,7 @@ internal class AndroidRNodeBlePicker( } private companion object { + const val TAG = "AndroidRNodeBlePicker" const val SCAN_DURATION_MS = 20_000L const val SCAN_START_HISTORY_MS = 60_000L const val PAIRING_TIMEOUT_MS = 60_000L diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt index b86163c..93a35e4 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/MainActivity.kt @@ -83,6 +83,7 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() requestHighRefreshRate() + rnodeBlePicker?.onResume() } override fun onDestroy() { diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt index 2b26a4e..442bae0 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeBluetoothPicker.kt @@ -134,6 +134,9 @@ private fun RNodeBluetoothDevice( val kind = rnodeBleTargetKind(target) val android = picker.platform == RNodeBlePlatform.ANDROID val find = { onDismissKeyboard(); request = RNodePickerRequest() } + LaunchedEffect(picker) { + picker.pairingChanges.collect { pairingChecks++ } + } Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { when { @@ -288,6 +291,8 @@ private fun RNodeScanDialog( } LaunchedEffect(picker) { picker.sightings.collect { sighting -> + // Other devices offer the same UART service; only RNodes are listed. + if (!list.accepts(sighting)) return@collect val key = sighting.id.uppercase() val paired = android && pairedIds.getOrPut(key) { picker.isPaired(sighting.id) == true } val pinned = paired || (savedId != null && savedId.equals(sighting.id, ignoreCase = true)) diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt index f658949..3ad518d 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt @@ -2,6 +2,7 @@ package com.sidpatchy.Starling import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.emptyFlow const val RNODE_BLE_PREFIX = "ble://" const val RNODE_TCP_PREFIX = "tcp://" @@ -174,6 +175,15 @@ fun rnodeSignalLevel(rssi: Int): RNodeSignalLevel = when { else -> RNodeSignalLevel.WEAK } +/** RNode firmware advertises itself as "RNode" followed by four characters of its address. */ +const val RNODE_BLE_NAME_PREFIX = "RNode " + +/** + * Whether a Bluetooth name belongs to an RNode. Other radios offer the same + * UART service, so the service alone does not identify one. + */ +fun isRNodeBleName(name: String): Boolean = name.startsWith(RNODE_BLE_NAME_PREFIX) + /** One advertisement seen while searching for RNodes. */ data class RNodeBleSighting(val id: String, val name: String, val rssi: Int) @@ -214,6 +224,14 @@ class RNodeScanList( searchAt = nowMillis } + /** + * Whether a sighting belongs in the list: it carries an RNode name, or it + * is a nameless advertisement from a device that is already listed. + */ + fun accepts(sighting: RNodeBleSighting): Boolean = + isRNodeBleName(sighting.name) || + (sighting.name.isBlank() && sighting.id.trim().uppercase() in entries) + fun observe(sighting: RNodeBleSighting, pinned: Boolean, nowMillis: Long) { val key = sighting.id.trim().uppercase() if (key.isEmpty()) return @@ -338,6 +356,9 @@ interface RNodeBlePicker { /** Whether the system has a pairing for this device, or null when that cannot be known. */ fun isPaired(deviceId: String): Boolean? + /** Emits when a pairing may have changed outside the picker, so [isPaired] is worth asking again. */ + val pairingChanges: Flow get() = emptyFlow() + /** The system's name for a device it already knows. */ fun knownName(deviceId: String): String? = null fun openBluetoothSettings() = Unit @@ -385,7 +406,7 @@ object RNodeBleText { failure.reason == RNodeBlePairingFailure.WRONG_PIN -> "The PIN didn't match. Try again and enter the PIN currently shown on the RNode." failure.reason == RNodeBlePairingFailure.TIMEOUT -> "Pairing timed out. Wake the RNode's screen, then try again." - else -> "Pairing didn't complete (reason ${failure.code}). Try again." + else -> "Pairing didn't finish. Make sure the RNode is on and in pairing mode, then try again." } fun notFound(name: String) = "Couldn't reach $name. Check that it's powered on and in range, then try again." diff --git a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt index d30d55e..d11e3bc 100644 --- a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt +++ b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt @@ -201,6 +201,30 @@ class RNodeConnectionTest { assertEquals(listOf(RNodeScanRow("AA:BB:CC:DD:11:22", "RNode", -61, false, null)), list.rows(30)) } + @Test + fun onlyDevicesNamedLikeAnRNodeAreListed() { + assertTrue(isRNodeBleName("RNode 5719")) + assertTrue(isRNodeBleName("RNode A1B2")) + assertFalse(isRNodeBleName("MeshCore-A1B2")) + assertFalse(isRNodeBleName("RNode")) + assertFalse(isRNodeBleName("RNodeX 5719")) + assertFalse(isRNodeBleName("rnode 5719")) + assertFalse(isRNodeBleName("My RNode 5719")) + assertFalse(isRNodeBleName("")) + + val list = RNodeScanList() + list.beginSearch(0) + val rnode = RNodeBleSighting("AA:BB:CC:DD:57:19", "RNode 5719", -60) + val meshCore = RNodeBleSighting("AA:BB:CC:DD:00:99", "MeshCore-A1B2", -50) + assertTrue(list.accepts(rnode)) + assertFalse(list.accepts(meshCore)) + // A nameless advertisement is only taken from a device already listed as an RNode. + assertFalse(list.accepts(rnode.copy(name = ""))) + list.observe(rnode, pinned = false, nowMillis = 10) + assertTrue(list.accepts(RNodeBleSighting("aa:bb:cc:dd:57:19", "", -62))) + assertFalse(list.accepts(meshCore.copy(name = ""))) + } + @Test fun orderFreezesAfterThreeSecondsAndSignalUpdatesInPlace() { val list = RNodeScanList() @@ -318,7 +342,11 @@ class RNodeConnectionTest { assertTrue(RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.WRONG_PIN, 1), android).startsWith("The PIN didn't match.")) assertTrue(RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.TIMEOUT), android).startsWith("Pairing timed out.")) assertEquals( - "Pairing didn't complete (reason 9). Try again.", + "Pairing didn't finish. Make sure the RNode is on and in pairing mode, then try again.", + RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.OTHER, 9), android), + ) + assertEquals( + RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.OTHER), android), RNodeBleText.pairingFailureMessage(failed(RNodeBlePairingFailure.OTHER, 9), android), ) assertTrue( From 2fa8e320d168ab75bcfd7f0604ed0a15d87f132a Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:22:35 -0700 Subject: [PATCH 10/12] fix(settings): plain scan errors; bare ble:// only picks an RNode The search-failed message no longer shows the Android error code; the code goes to the debug log. A saved ble:// port with no name now takes only a device named like an RNode, the rule the picker uses. A typed name or address is still matched exactly. --- .../Starling/AndroidRNodeBlePicker.kt | 1 + .../Starling/AndroidRNodeBluetoothBridge.kt | 9 +------ .../com/sidpatchy/Starling/RNodeConnection.kt | 14 ++++++++++- .../sidpatchy/Starling/RNodeConnectionTest.kt | 25 ++++++++++++++++++- 4 files changed, 39 insertions(+), 10 deletions(-) diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt index 0fe4267..f1eff26 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt @@ -123,6 +123,7 @@ internal class AndroidRNodeBlePicker( } override fun onScanFailed(errorCode: Int) { + Log.d(TAG, "Bluetooth search failed (code $errorCode)") scope.launch { scanJob?.cancel() activeScanner = null diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt index 1e283bc..3bb4d5c 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBluetoothBridge.kt @@ -83,14 +83,7 @@ internal class AndroidRNodeBluetoothBridge(context: Context) { override fun onScanResult(callbackType: Int, result: ScanResult) { val deviceName = result.scanRecord?.deviceName ?: runCatching { result.device.name }.getOrNull().orEmpty() - val selectedName = targetName - val matches = if (selectedName.isNullOrBlank()) { - deviceName.startsWith("RNode", ignoreCase = true) - } else { - deviceName.equals(selectedName, ignoreCase = true) || - result.device.address.equals(selectedName, ignoreCase = true) - } - if (!running || !matches) return + if (!running || !matchesTypedRNodeBleTarget(targetName, deviceName, result.device.address)) return scannedName = deviceName.takeIf(String::isNotBlank) stopScan() diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt index 3ad518d..bdcc89f 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt @@ -184,6 +184,18 @@ const val RNODE_BLE_NAME_PREFIX = "RNode " */ fun isRNodeBleName(name: String): Boolean = name.startsWith(RNODE_BLE_NAME_PREFIX) +/** + * Whether a scanned device is the one a typed ble:// port asks for. A port + * with a name or address takes exactly that device; an empty one takes the + * first RNode. + */ +fun matchesTypedRNodeBleTarget(target: String?, deviceName: String, deviceAddress: String): Boolean = + if (target.isNullOrBlank()) { + isRNodeBleName(deviceName) + } else { + deviceName.equals(target, ignoreCase = true) || deviceAddress.equals(target, ignoreCase = true) + } + /** One advertisement seen while searching for RNodes. */ data class RNodeBleSighting(val id: String, val name: String, val rssi: Int) @@ -384,7 +396,7 @@ object RNodeBleText { "Bluetooth permission is turned off for Starling. Turn it on in system settings." RNodeBleScanStatus.LocationOff -> "Android needs Location turned on to search for Bluetooth devices. Starling does not use your location." - is RNodeBleScanStatus.Failed -> "Bluetooth search failed (code ${status.code}). Try again." + is RNodeBleScanStatus.Failed -> "Bluetooth search failed. Turn Bluetooth off and on, then try again." RNodeBleScanStatus.Unsupported -> "This device doesn't support Bluetooth LE." } diff --git a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt index d11e3bc..2aa0540 100644 --- a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt +++ b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt @@ -201,6 +201,29 @@ class RNodeConnectionTest { assertEquals(listOf(RNodeScanRow("AA:BB:CC:DD:11:22", "RNode", -61, false, null)), list.rows(30)) } + @Test + fun anEmptyTypedBleTargetOnlyTakesAnRNode() { + val address = "AA:BB:CC:DD:77:10" + + assertTrue(matchesTypedRNodeBleTarget(null, "RNode 5719", address)) + assertTrue(matchesTypedRNodeBleTarget("", "RNode 5719", address)) + assertFalse(matchesTypedRNodeBleTarget(null, "MeshCore-A1B2", address)) + assertFalse(matchesTypedRNodeBleTarget(null, "RNodeX 5719", address)) + assertFalse(matchesTypedRNodeBleTarget(null, "rnode 5719", address)) + assertFalse(matchesTypedRNodeBleTarget(null, "", address)) + } + + @Test + fun aTypedBleNameIsHonouredExactly() { + val address = "AA:BB:CC:DD:77:10" + + assertTrue(matchesTypedRNodeBleTarget("RNode 5719", "rnode 5719", address)) + assertTrue(matchesTypedRNodeBleTarget("MeshCore-A1B2", "MeshCore-A1B2", address)) + assertTrue(matchesTypedRNodeBleTarget("aa:bb:cc:dd:77:10", "", address)) + assertFalse(matchesTypedRNodeBleTarget("RNode 5719", "RNode 5720", address)) + assertFalse(matchesTypedRNodeBleTarget("RNode", "RNode 5719", address)) + } + @Test fun onlyDevicesNamedLikeAnRNodeAreListed() { assertTrue(isRNodeBleName("RNode 5719")) @@ -322,7 +345,7 @@ class RNodeConnectionTest { RNodeBleText.scanStatusMessage(RNodeBleScanStatus.BluetoothOff, ios, false), ) assertEquals( - "Bluetooth search failed (code 2). Try again.", + "Bluetooth search failed. Turn Bluetooth off and on, then try again.", RNodeBleText.scanStatusMessage(RNodeBleScanStatus.Failed(2), android, false), ) assertEquals("Turn on Bluetooth", RNodeBleText.scanBlockerAction(RNodeBleScanStatus.BluetoothOff, android)) From 3396a31ed505fb995db7594df944b9641f60e627 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:32:42 -0700 Subject: [PATCH 11/12] fix(android): only call a pairing failure a wrong PIN when Android says so Android gives the same reason, authentication failed, for a PIN that did not match, a cancelled PIN prompt and a link that dropped during pairing, so that reason now shows the general pairing message. The timeout reason is unchanged. The reason is written to the info log. --- .../Starling/AndroidRNodeBlePicker.kt | 12 ++--------- .../com/sidpatchy/Starling/RNodeConnection.kt | 12 +++++++++++ .../sidpatchy/Starling/RNodeConnectionTest.kt | 21 +++++++++++++++++++ 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt index f1eff26..8e79ec9 100644 --- a/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt +++ b/androidApp/src/main/kotlin/com/sidpatchy/Starling/AndroidRNodeBlePicker.kt @@ -315,14 +315,8 @@ internal class AndroidRNodeBlePicker( state == BluetoothDevice.BOND_NONE && previous == BluetoothDevice.BOND_BONDING -> { // Android does not document this extra; it is read on a best-effort basis. val reason = intent.getIntExtra(EXTRA_UNBOND_REASON, 0) - failPairing( - when (reason) { - UNBOND_REASON_AUTH_FAILED -> RNodeBlePairingFailure.WRONG_PIN - UNBOND_REASON_AUTH_TIMEOUT -> RNodeBlePairingFailure.TIMEOUT - else -> RNodeBlePairingFailure.OTHER - }, - reason, - ) + Log.i(TAG, "Pairing ended without a bond (Android reason $reason)") + failPairing(rnodePairingFailureForAndroidUnbondReason(reason), reason) } } } @@ -463,8 +457,6 @@ internal class AndroidRNodeBlePicker( const val SCAN_START_HISTORY_MS = 60_000L const val PAIRING_TIMEOUT_MS = 60_000L const val EXTRA_UNBOND_REASON = "android.bluetooth.device.extra.REASON" - const val UNBOND_REASON_AUTH_FAILED = 1 - const val UNBOND_REASON_AUTH_TIMEOUT = 6 val SERVICE_UUID: UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E") val TX_UUID: UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E") val CCCD_UUID: UUID = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB") diff --git a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt index bdcc89f..c167acb 100644 --- a/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt +++ b/composeApp/src/commonMain/kotlin/com/sidpatchy/Starling/RNodeConnection.kt @@ -336,6 +336,18 @@ sealed interface RNodeBleScanStatus { enum class RNodeBlePairingFailure { WRONG_PIN, TIMEOUT, STALE_BOND, OTHER } +/** Android's reason for a pairing it gave up on waiting for. */ +const val ANDROID_UNBOND_REASON_AUTH_TIMEOUT = 6 + +/** + * The failure for the reason Android gives when a pairing ends without a + * bond. Over Bluetooth LE Android gives the same reason for a PIN that did + * not match, a PIN prompt that was cancelled and a link that dropped, so no + * reason is treated as a wrong PIN. + */ +fun rnodePairingFailureForAndroidUnbondReason(reason: Int): RNodeBlePairingFailure = + if (reason == ANDROID_UNBOND_REASON_AUTH_TIMEOUT) RNodeBlePairingFailure.TIMEOUT else RNodeBlePairingFailure.OTHER + /** Progress of pairing on Android, or of the first trial connection on iOS. */ sealed interface RNodeBlePairingState { data object Idle : RNodeBlePairingState diff --git a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt index 2aa0540..cd3ee43 100644 --- a/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt +++ b/composeApp/src/commonTest/kotlin/com/sidpatchy/Starling/RNodeConnectionTest.kt @@ -357,6 +357,27 @@ class RNodeConnectionTest { assertNull(RNodeBleText.scanBlockerAction(RNodeBleScanStatus.Scanning, android)) } + @Test + fun noAndroidUnbondReasonIsReportedAsAWrongPin() { + // 1 authentication failed, 2 rejected, 3 cancelled, 4 device down, 5 discovery in progress, + // 7 repeated attempts, 8 cancelled by the other device, 9 removed; 0 when Android gives none. + for (reason in listOf(0, 1, 2, 3, 4, 5, 7, 8, 9, 42)) { + assertEquals(RNodeBlePairingFailure.OTHER, rnodePairingFailureForAndroidUnbondReason(reason), "reason $reason") + } + assertEquals(RNodeBlePairingFailure.TIMEOUT, rnodePairingFailureForAndroidUnbondReason(6)) + + val cancelled = RNodeBlePairingState.Failed("RNode A1B2", rnodePairingFailureForAndroidUnbondReason(1), 1) + assertEquals( + "Pairing didn't finish. Make sure the RNode is on and in pairing mode, then try again.", + RNodeBleText.pairingFailureMessage(cancelled, RNodeBlePlatform.ANDROID), + ) + val timedOut = RNodeBlePairingState.Failed("RNode A1B2", rnodePairingFailureForAndroidUnbondReason(6), 6) + assertEquals( + "Pairing timed out. Wake the RNode's screen, then try again.", + RNodeBleText.pairingFailureMessage(timedOut, RNodeBlePlatform.ANDROID), + ) + } + @Test fun pairingFailuresAndNodeStartErrorsNameTheRNode() { val android = RNodeBlePlatform.ANDROID From 080712f110df2f5731e3cd16d4b2a6e887b3de17 Mon Sep 17 00:00:00 2001 From: zvx-echo6 <242306573+zvx-echo6@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:33:18 -0700 Subject: [PATCH 12/12] fix(ios): bare ble:// only picks an RNode A saved ble:// port with no name now takes only a device whose name starts with RNode and a space, the rule the picker and Android use. A typed name is still matched exactly. --- iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift b/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift index 08c7ee3..52b8fc5 100644 --- a/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift +++ b/iosApp/Sources/Starling/StarlingRNodeBluetoothBridge.swift @@ -150,7 +150,7 @@ final class StarlingRNodeBluetoothBridge: NSObject, CBCentralManagerDelegate, CB } else if let targetName, !targetName.isEmpty { matchesTarget = name.caseInsensitiveCompare(targetName) == .orderedSame } else { - matchesTarget = name.hasPrefix("RNode") + matchesTarget = name.hasPrefix("RNode ") } guard matchesTarget else { return }