diff --git a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt index 262a125b8f..bb912e8f2a 100644 --- a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt +++ b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt @@ -145,7 +145,7 @@ class NearbyAdvertiser( val advertiser = bluetoothManager.adapter?.bluetoothLeAdvertiser ?: return onFailed() val settings = AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) - .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW) + .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) .setConnectable(true) .build() val data = AdvertiseData.Builder() diff --git a/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt b/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt index 745cdf95e8..f854f9c612 100644 --- a/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt +++ b/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt @@ -19,7 +19,28 @@ object NearbyProtocol { const val CHUNK_SIZE = 512 const val CHUNK_COUNT = 8 const val MAX_REQUEST_BYTES = CHUNK_SIZE * CHUNK_COUNT - const val MIN_RSSI = -60 + const val MIN_RSSI = -75 + + const val MIN_READINGS = 3 + + /** Whether a phone seen at [rssi] dBm is close enough to read. */ + fun isInRange(rssi: Int): Boolean = rssi >= MIN_RSSI + + /** + * The phone to read among [readings] (each phone's RSSI values over the selection window): the one with the + * strongest median, if that median is in range. A phone needs [MIN_READINGS] values, so one spike never wins. + */ + fun closest(readings: Map>): K? = readings + .mapNotNull { (key, values) -> + if (values.size < MIN_READINGS) return@mapNotNull null + val median = values.sorted()[(values.size - 1) / 2] + if (isInRange(median)) key to median else null + } + .maxByOrNull { it.second } + ?.first + + /** Whether a phone in [readings] has fewer than [MIN_READINGS] values; the window goes on while none qualifies. */ + fun needsMoreReadings(readings: Map>): Boolean = readings.values.any { it.size < MIN_READINGS } /** The request as served, or null when it is empty or too large to serve. */ fun encodeRequest(request: String): ByteArray? { diff --git a/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt index d7abee3008..7ce8b42a8f 100644 --- a/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt +++ b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt @@ -28,20 +28,24 @@ import kotlin.time.Duration.Companion.seconds /** * Finds the closest nearby Bitkit wallet that serves a payment request and reads that request. * - * While started it scans for the nearby service. Once an advertiser at or above - * [NearbyProtocol.MIN_RSSI] is seen, it waits [CANDIDATE_WINDOW] for others, connects to the - * strongest one and reads the request. Only payment requests ([nearbyPaymentRequest]) reach - * [onRequest], on the main thread. A device is then skipped for [RETRY_AFTER], so the scanner keeps listening for - * others, and reads the device again if the screen stayed open after rejecting its request. + * While started it scans for the nearby service. From the first advertiser seen it collects + * readings for [CANDIDATE_WINDOW], connects to the one with the strongest median signal at or above + * [NearbyProtocol.MIN_RSSI] ([NearbyProtocol.closest]) and reads the request. While no phone qualifies yet + * and some phone has fewer than [NearbyProtocol.MIN_READINGS], the window goes on in [CANDIDATE_WINDOW] + * steps, up to [MAX_CANDIDATE_WINDOW]. + * Only payment requests ([nearbyPaymentRequest]) reach [onRequest], on the main thread. A device is then + * skipped for [RETRY_AFTER], so the scanner keeps listening for others, and reads the device again if the + * screen stayed open after rejecting its request. */ class NearbyScanner( private val context: Context, private val onRequest: (String) -> Unit, ) { private val handler = Handler(Looper.getMainLooper()) - private val candidates = mutableMapOf>() - private val skippedUntil = mutableMapOf() + private val devices = mutableMapOf() + private val readings = mutableMapOf>() private var isScanning = false + private var windowStartedAt = 0L private var isStarted = false private var session: ReadSession? = null @@ -72,8 +76,8 @@ class NearbyScanner( handler.removeCallbacksAndMessages(null) session?.close() session = null - candidates.clear() - skippedUntil.clear() + devices.clear() + readings.clear() } @SuppressLint("MissingPermission") // Scheduled only by a started scanner. @@ -98,20 +102,28 @@ class NearbyScanner( } private fun onCandidate(device: BluetoothDevice, rssi: Int) { - if (!isStarted || session != null || rssi < NearbyProtocol.MIN_RSSI) return - val until = skippedUntil[device.address] - if (until != null && nowMillis() < until) return - val isFirst = candidates.isEmpty() - val previous = candidates[device.address]?.second - if (previous == null || rssi > previous) candidates[device.address] = device to rssi - if (isFirst) handler.postDelayed(::connectToClosest, CANDIDATE_WINDOW.inWholeMilliseconds) + if (!isStarted || session != null) return + if (NearbySkips.isSkipped(device.address, nowMillis())) return + val isFirst = readings.isEmpty() + devices[device.address] = device + readings.getOrPut(device.address) { mutableListOf() } += rssi + if (isFirst) { + windowStartedAt = nowMillis() + handler.postDelayed(::connectToClosest, CANDIDATE_WINDOW.inWholeMilliseconds) + } } @SuppressLint("MissingPermission") // Scheduled only by a started scanner. private fun connectToClosest() { - val closest = candidates.values.maxByOrNull { it.second }?.first ?: return - candidates.clear() - if (!isStarted) return + val closest = NearbyProtocol.closest(readings)?.let(devices::get) + val isWindowOpen = nowMillis() - windowStartedAt < MAX_CANDIDATE_WINDOW.inWholeMilliseconds + if (closest == null && isStarted && isWindowOpen && NearbyProtocol.needsMoreReadings(readings)) { + handler.postDelayed(::connectToClosest, CANDIDATE_WINDOW.inWholeMilliseconds) + return + } + devices.clear() + readings.clear() + if (closest == null || !isStarted) return stopScan() session = ReadSession(closest).also { it.open() } } @@ -125,7 +137,7 @@ class NearbyScanner( if (request != null && payment == null) { Logger.warn("Ignored nearby request that is not a payment", context = TAG) } - skippedUntil[device.address] = nowMillis() + RETRY_AFTER.inWholeMilliseconds + NearbySkips.skip(device.address, nowMillis() + RETRY_AFTER.inWholeMilliseconds) if (!isStarted) return if (payment != null) onRequest(payment) startScan() @@ -229,9 +241,24 @@ class NearbyScanner( private companion object { const val TAG = "NearbyScanner" const val MTU = 517 - val CANDIDATE_WINDOW: Duration = 400.milliseconds + val CANDIDATE_WINDOW: Duration = 500.milliseconds + val MAX_CANDIDATE_WINDOW: Duration = 2.seconds val READ_TIMEOUT: Duration = 8.seconds val RETRY_AFTER: Duration = 10.seconds val SCAN_RETRY_DELAY: Duration = 5.seconds } } + +/** + * When each device may be read again. It outlives a [NearbyScanner], since screens stop and recreate theirs when + * they come back (Back from the send review), and would otherwise read the same phone again at once. + */ +internal object NearbySkips { + private val skippedUntil = mutableMapOf() + + fun skip(address: String, untilMillis: Long) { + skippedUntil[address] = untilMillis + } + + fun isSkipped(address: String, nowMillis: Long): Boolean = (skippedUntil[address] ?: 0) > nowMillis +} diff --git a/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt index 087afb34fd..19f41a44d4 100644 --- a/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt +++ b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt @@ -5,6 +5,7 @@ import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattServer import android.bluetooth.BluetoothGattServerCallback import android.bluetooth.BluetoothManager +import android.bluetooth.le.AdvertiseSettings import android.bluetooth.le.BluetoothLeAdvertiser import android.content.Context import android.os.Looper @@ -58,7 +59,9 @@ class NearbyAdvertiserTest { reportServiceAdded(BluetoothGatt.GATT_SUCCESS) - verify(advertiser).startAdvertising(any(), any(), any()) + val settings = argumentCaptor() + verify(advertiser).startAdvertising(settings.capture(), any(), any()) + assertEquals(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH, settings.lastValue.txPowerLevel) assertEquals(0, failures) } diff --git a/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt index b2981746d8..e7274e66e2 100644 --- a/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt +++ b/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt @@ -2,6 +2,7 @@ package to.bitkit.nearby import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -68,4 +69,30 @@ class NearbyProtocolTest { fun `decode fails when chunks do not match the length`() { assertNull(NearbyProtocol.decode(listOf("abc".toByteArray()), 4)) } + + @Test + fun `reads phones down to -75 dBm`() { + assertTrue(NearbyProtocol.isInRange(-74)) + assertTrue(NearbyProtocol.isInRange(-75)) + assertFalse(NearbyProtocol.isInRange(-76)) + } + + @Test + fun `picks the phone with the strongest median in range`() { + val readings = mapOf( + "near" to listOf(-60, -62, -90), + "peak" to listOf(-50, -70, -72), + "spike" to listOf(-84, -75, -83, -82), + "few" to listOf(-40, -40), + ) + + assertEquals("near", NearbyProtocol.closest(readings)) + assertNull(NearbyProtocol.closest(readings - "near" - "peak")) + } + + @Test + fun `keeps collecting while a phone has too few readings`() { + assertTrue(NearbyProtocol.needsMoreReadings(mapOf("slow" to listOf(-40, -41), "far" to listOf(-90, -91, -92)))) + assertFalse(NearbyProtocol.needsMoreReadings(mapOf("far" to listOf(-90, -91, -92)))) + } } diff --git a/app/src/test/java/to/bitkit/nearby/NearbySkipsTest.kt b/app/src/test/java/to/bitkit/nearby/NearbySkipsTest.kt new file mode 100644 index 0000000000..2e6e93746e --- /dev/null +++ b/app/src/test/java/to/bitkit/nearby/NearbySkipsTest.kt @@ -0,0 +1,16 @@ +package to.bitkit.nearby + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NearbySkipsTest { + @Test + fun `skips a device until its deadline, across scanners`() { + NearbySkips.skip("AA:BB", untilMillis = 10_000) + + assertTrue(NearbySkips.isSkipped("AA:BB", nowMillis = 9_999)) + assertFalse(NearbySkips.isSkipped("AA:BB", nowMillis = 10_000)) + assertFalse(NearbySkips.isSkipped("CC:DD", nowMillis = 0)) + } +} diff --git a/changelog.d/next/2225.fixed.md b/changelog.d/next/2225.fixed.md new file mode 100644 index 0000000000..0ddf5c3921 --- /dev/null +++ b/changelog.d/next/2225.fixed.md @@ -0,0 +1 @@ +Bluetooth nearby payments now connect with the phones held close, without pressing them together. diff --git a/docs/nearby-payments.md b/docs/nearby-payments.md index f91d6f7f77..a72946ee3e 100644 --- a/docs/nearby-payments.md +++ b/docs/nearby-payments.md @@ -43,8 +43,10 @@ advertiser and reads the request. - Maximum request size: 4096 bytes. - The request is the same URI as the NFC tag. - Advertising runs only while the Receive screen is in the foreground and the nearby setting is on. -- Central: scans for the service UUID while a payment scanner is open, connects to the strongest - advertiser at or above -60 dBm, reads meta and the needed chunks, then disconnects. +- Central: scans for the service UUID while a payment scanner is open, collects each advertiser's + RSSI for 500 ms, connects to the one with the strongest median (at least 3 readings) at or above + -75 dBm, reads meta and the needed chunks, then disconnects. While none qualifies yet and some + advertiser has fewer than 3 readings, it keeps collecting in 500 ms steps, up to 2 s. - A request received over Bluetooth always opens the normal send review; QuickPay does not apply, because Bluetooth range lets a device that is not the merchant's answer. - Only `bitcoin:`, `lightning:` BOLT11 and USDT `ethereum:` requests are taken over Bluetooth. LNURL and