feat: negotiating MTU size
This commit is contained in:
@@ -36,6 +36,12 @@ private const val ENABLE_BLUETOOTH_REQUEST_CODE = 1
|
||||
|
||||
private const val RUNTIME_PERMISSION_REQUEST_CODE = 2
|
||||
|
||||
// Top level declaration
|
||||
private const val GATT_MAX_MTU_SIZE = 517
|
||||
|
||||
// Top level declaration
|
||||
private const val GATT_REQUESTED_MTU_SIZE = GATT_MAX_MTU_SIZE
|
||||
|
||||
fun Context.hasPermission(permissionType: String): Boolean {
|
||||
return ContextCompat.checkSelfPermission(this, permissionType) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
@@ -97,6 +103,8 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
private val kirbyScanResults = ArrayList<ScanResult>();
|
||||
|
||||
private var mtuSizeInBytes = 23
|
||||
|
||||
private val gattCallback = object : BluetoothGattCallback() {
|
||||
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
|
||||
val deviceAddress = gatt.device.address
|
||||
@@ -104,12 +112,21 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED) {
|
||||
|
||||
Log.i(
|
||||
"BluetoothGattCallback",
|
||||
"Successfully connected to $deviceAddress (${deviceName})"
|
||||
)
|
||||
val serviceDiscoveryStarted = gatt.discoverServices()
|
||||
if (!serviceDiscoveryStarted) {
|
||||
|
||||
if (!gatt.requestMtu(GATT_REQUESTED_MTU_SIZE)) {
|
||||
Log.e(
|
||||
"BluetoothGattCallback",
|
||||
"Requesting MTU size failed"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (!gatt.discoverServices()) {
|
||||
Log.e(
|
||||
"BluetoothGattCallback",
|
||||
"Service discovery did not start"
|
||||
@@ -141,6 +158,21 @@ class MainActivity : AppCompatActivity() {
|
||||
printGattTable()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
|
||||
if (status == BluetoothGatt.GATT_SUCCESS) {
|
||||
Log.i(
|
||||
"BluetoothGattCallback",
|
||||
"mtuSizeInBytes set to ${mtu}"
|
||||
)
|
||||
mtuSizeInBytes = mtu
|
||||
} else {
|
||||
Log.w(
|
||||
"BluetoothGattCallback",
|
||||
"Unsuccessful MTU change. Leaving mtuSizeInBytes unchanged ${mtuSizeInBytes}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val scanResultAdapter: ScanResultAdapter by lazy {
|
||||
|
||||
Reference in New Issue
Block a user