I am using theKable library for BLE scanning and connection in a Compose Multiplatform (KMP) app for Android and iOS. Scanning works perfectly in both the plateforms, but I am unable to establish a connection with the BLE device. What could be the possible reasons, and how can I fix this issue?
implementation("com.juul.kable:core:0.27.0")
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.juul.kable.Peripheral
import com.juul.kable.Scanner
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class ScanningViewModel : ViewModel(){
private val scanner = Scanner()
private var connectedPeripheral: Peripheral? = null
private val _devices = MutableStateFlow<List<BleDevice>>(emptyList()) // You can store the device names here
val devices: StateFlow<List<BleDevice>> = _devices
fun startScanning() {
viewModelScope.launch {
try {
// Start scanning and collect advertisements
scanner.advertisements.collect { advertisement ->
val deviceName = advertisement.name ?: "Unknown Device"
val txPower = advertisement.txPower ?: 0
val newDevice = BleDevice(
name = deviceName,
peripheralName = "", // Use peripheral name
txPower = txPower,
)
_devices.update { currentList ->
if (newDevice !in currentList) {
currentList + newDevice // Add the new device if not already present
} else {
currentList // Keep the list unchanged if device already exists
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
data class BleDevice(
val name: String,
val peripheralName: String,
val txPower: Int?,
)
Note : Connect methos is available in Peripheral object.
Expecting : Peripheral object because it has connect method
I tried with all possible version of kable lib