Hi everyone In my code kable cann't scan BLE, I a...
# juul-libraries
g
Hi everyone In my code kable cann't scan BLE, I always get timeout cause, my code refer example sensortag, below show my code:
Copy code
fun start() {
    if (_status.value == BluetoothStatus.Scanning) return
    _status.value = BluetoothStatus.Scanning
    scanScope.launch {
        withTimeoutOrNull(ScanDurationMillts) {
            bluetoothScanner
                .advertisements
                .catch { cause -> _status.value = BluetoothStatus.Failed(cause.message?:"Unknown error") }
                .onCompletion { cause ->
                    if(cause == null || cause is CancellationException) {
                        _status.value = BluetoothStatus.ScanStoped
                    }
                }
                .collect { advertisement ->
                    found = found.plus(advertisement)
                    _advertisements.value = found.toList()
                }
        }
    }
}
val bluetoothScanner = Scanner {
    logging {
        level = Logging.Level.Events
    }
    filters {
        match {
            services = listOf(SERVICE_UUID)
//            name = Filter.Name.Prefix("ED719M")
        }

    }
}
I also get same scan timeout exception when I run example sensortag which I only modify sensorTagUuid to my device uuid
t
You're using
collect
which will pull from the flow forever (or until timeout in this case). If you're only looking for a specific (single) advertisement then I'd recommend using
first
instead of
collect
. If you need to grab a few advertisements, then you can use your current
collect
approach but add a
takeWhile
above it that provides a
false
when you want to stop scanning (when you've hit a condition that satisfies what you were scanning for). If you need a specific number of advertisements,
take(#)
can be used with your
collect
.
g
Copy code
fun start() {
    if (_status.value == Scanning) return // Scan already in progress.
    _status.value = Scanning

    scanScope.launch {
        withTimeoutOrNull(SCAN_DURATION_MILLIS) {
            val advertisement = scanner
                .advertisements
                .catch { cause ->
                    _status.value = ScanStatus.Failed(cause.message ?: "Unknown error") }
                .onCompletion { cause ->
                    if (cause == null || cause is CancellationException) _status.value = Stopped }
                .first()
            found[advertisement.address] = advertisement
        }
    }
I change code to use first() but also cann't scan anything which in file ScanViewModel.kt of project sensortag .
Thanks, I have find the solution according history issues.
👍 1