Jasonchenlijian / FastBle

Android Bluetooth Low Energy (BLE) Fast Development Framework. It uses simple ways to filter, scan, connect, read ,write, notify, readRssi, setMTU, and multiConnection.
Apache License 2.0
5.28k stars 1.22k forks source link

Is there a trick to set the MTU size? #581

Open mikedorin opened 11 months ago

mikedorin commented 11 months ago

Sometimes it works, and sometimes I get a timeout/error. Is there a trick to setting it? Is there a maximum value? Thank you, Mike

hcyAndroid commented 5 months ago
private suspend fun initBleMTU(bleDevice: BleDevice): Boolean {
    val MAX_MTU = 180
    return withContext(Dispatchers.IO) {
        suspendCoroutine { continuation ->
            BleManager.getInstance()
                .setMtu(bleDevice, MAX_MTU, object : BleMtuChangedCallback() {
                    override fun onSetMTUFailure(exception: BleException) {
                        // 设置 MTU 失败
                        Logger.e("$TAG 设置MTU失败==${exception.description}")
                        if (isActive) {
                            continuation.resume(false) // 返回 false 表示初始化失败
                        }

                    }

                    override fun onMtuChanged(mtu: Int) {
                        // 设置 MTU 成功
                        Logger.d("$TAG 设置MTU成功==${mtu}")
                        if (isActive) {
                            continuation.resume(true) // 返回 true 表示初始化成功
                        }
                    }
                })
        }
    }

},

mtu between 23 and 512