Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
23 changes: 22 additions & 1 deletion app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
ovitrif marked this conversation as resolved.
Resolved

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 <K> closest(readings: Map<K, List<Int>>): 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 <K> needsMoreReadings(readings: Map<K, List<Int>>): 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? {
Expand Down
69 changes: 48 additions & 21 deletions app/src/main/java/to/bitkit/nearby/NearbyScanner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Pair<BluetoothDevice, Int>>()
private val skippedUntil = mutableMapOf<String, Long>()
private val devices = mutableMapOf<String, BluetoothDevice>()
private val readings = mutableMapOf<String, MutableList<Int>>()
private var isScanning = false
private var windowStartedAt = 0L
private var isStarted = false
private var session: ReadSession? = null

Expand Down Expand Up @@ -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.
Expand All @@ -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() }
}
Expand All @@ -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()
Expand Down Expand Up @@ -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<String, Long>()

fun skip(address: String, untilMillis: Long) {
skippedUntil[address] = untilMillis
}

fun isSkipped(address: String, nowMillis: Long): Boolean = (skippedUntil[address] ?: 0) > nowMillis
}
5 changes: 4 additions & 1 deletion app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -58,7 +59,9 @@ class NearbyAdvertiserTest {

reportServiceAdded(BluetoothGatt.GATT_SUCCESS)

verify(advertiser).startAdvertising(any(), any(), any())
val settings = argumentCaptor<AdvertiseSettings>()
verify(advertiser).startAdvertising(settings.capture(), any(), any())
assertEquals(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH, settings.lastValue.txPowerLevel)
assertEquals(0, failures)
}

Expand Down
27 changes: 27 additions & 0 deletions app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))))
}
}
16 changes: 16 additions & 0 deletions app/src/test/java/to/bitkit/nearby/NearbySkipsTest.kt
Original file line number Diff line number Diff line change
@@ -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))
}
}
1 change: 1 addition & 0 deletions changelog.d/next/2225.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Bluetooth nearby payments now connect with the phones held close, without pressing them together.
6 changes: 4 additions & 2 deletions docs/nearby-payments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down