announce peer ID in servicedata to prevent duplicate connections (#613)

This commit is contained in:
callebtc
2026-01-15 13:51:30 +07:00
committed by GitHub
parent e3310a34fd
commit c2f60d6ab2
4 changed files with 52 additions and 12 deletions
@@ -24,7 +24,8 @@ class BluetoothGattServerManager(
private val connectionTracker: BluetoothConnectionTracker,
private val permissionManager: BluetoothPermissionManager,
private val powerManager: PowerManager,
private val delegate: BluetoothConnectionManagerDelegate?
private val delegate: BluetoothConnectionManagerDelegate?,
private val myPeerID: String
) {
companion object {
@@ -372,13 +373,27 @@ class BluetoothGattServerManager(
.setIncludeTxPowerLevel(false)
.setIncludeDeviceName(false)
.build()
// Add stable identity (first 8 bytes of peerID) to Scan Response
// This allows scanners to deduplicate devices even if MAC address rotates
val peerIDBytes = try {
myPeerID.chunked(2).map { it.toInt(16).toByte() }.toByteArray().take(8).toByteArray()
} catch (e: Exception) {
ByteArray(0)
}
val scanResponse = AdvertiseData.Builder()
.addServiceData(ParcelUuid(AppConstants.Mesh.Gatt.SERVICE_UUID), peerIDBytes)
.setIncludeTxPowerLevel(false)
.setIncludeDeviceName(false)
.build()
advertiseCallback = object : AdvertiseCallback() {
override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
val mode = try {
powerManager.getPowerInfo().split("Current Mode: ")[1].split("\n")[0]
} catch (_: Exception) { "unknown" }
Log.i(TAG, "Advertising started (power mode: $mode)")
Log.i(TAG, "Advertising started (power mode: $mode) with stable ID: ${peerIDBytes.joinToString("") { "%02x".format(it) }}")
}
override fun onStartFailure(errorCode: Int) {
@@ -387,7 +402,7 @@ class BluetoothGattServerManager(
}
try {
bleAdvertiser.startAdvertising(settings, data, advertiseCallback)
bleAdvertiser.startAdvertising(settings, data, scanResponse, advertiseCallback)
} catch (se: SecurityException) {
Log.e(TAG, "SecurityException starting advertising (missing permission?): ${se.message}")
} catch (e: Exception) {