weliem / blessed-android-coroutines

BLESSED Coroutines, a Bluetooth Low Energy (BLE) library for Android using Kotlin Coroutines

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Advertise Fails DATA_TOO_LARGE

cren90 opened this issue · comments

I'm following the guide at Server.MD to POC an android app as a heart rate monitor. I get a DATA_TOO_LARGE error on attempting to advertise. Here are the pertinent pieces of the POC:

private val hrmService = UUID.fromString("0000180D-0000-1000-8000-00805f9b34fb")
private val hrmCharacteristic = UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb")
private val service = BluetoothGattService(hrmService, BluetoothGattService.SERVICE_TYPE_PRIMARY)
private val characteristic = BluetoothGattCharacteristic(hrmCharacteristic, PROPERTY_READ or PROPERTY_INDICATE, PERMISSION_READ_ENCRYPTED_MITM)
private val peripheralManager by lazy { BluetoothPeripheralManager(this, getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager, callback) }

fun setupAdvertising() {
        CoroutineScope(Dispatchers.IO).launch {
            hrFlow.collect {
                it?.let {
                    val bytes = ByteBuffer.allocate(Int.SIZE_BYTES).apply {
                        putShort(it)
                    }.array()
                    peripheralManager.notifyCharacteristicChanged(bytes, characteristic)
                }
            }
        }

        service.addCharacteristic(characteristic)
        peripheralManager.add(service)

        val advertiseSettings = AdvertiseSettings.Builder()
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
            .setConnectable(true)
            .setTimeout(0)
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
            .build()

        val advertiseData = AdvertiseData.Builder()
            .setIncludeTxPowerLevel(true)
            .addServiceUuid(ParcelUuid(hrmService))
            .build()

        val scanResponse = AdvertiseData.Builder()
            .setIncludeDeviceName(true)
            .build()

        peripheralManager.startAdvertising(advertiseSettings, scanResponse, advertiseData)
    }

The total advertisement size cannot be larger than 31 bytes and 31 bytes for the scan reponse. So apparently one of them is too long. I can't see in your code snippet what you use as the local name but maybe it is that one....

Looks like it was the name of my phone that was the problem.