Skip to content

README suggestion #229

@mobilekosmos

Description

@mobilekosmos

For a quick start something like this would be beneficial, I needed to use AI to check how to use the lib:

Android Quick start:
Add the library to your toml file:

[versions]
nordic-ble = "2.0.0-alpha08" # check latest: https://github.com/NordicSemiconductor/Kotlin-BLE-Library/releases

[libraries]
nordic-ble-client-android = { module = "no.nordicsemi.kotlin.ble:client-android", version.ref = "nordic-ble" }

Reference it in your module:

implementation(libs.nordic.ble.client.android)

In your ViewModel:

    private val central: CentralManager by lazy {
        CentralManager.Factory.native(applicationContext, viewModelScope)
    }

    data class UiDevice(
        val id: String,           // PeripheralId (string)
        val name: String?,        // Advertised name (may be null)
        val rssi: Int?,           // Last known RSSI if provided by scan result
    )

    private val _devices = MutableStateFlow<List<UiDevice>>(emptyList())
    val devices: StateFlow<List<UiDevice>> = _devices.asStateFlow()

    private val seenIds = linkedSetOf<String>() // preserves discovery order
    private var scanJob: Job? = null

    fun startScan(duration: Duration = 5.seconds) {
        stopNordicBleScan()
        Timber.d("BLE: starting scan for ${duration.inWholeMilliseconds} ms")

        scanJob = central
            .scan(duration) {
                // Add filters if needed, e.g.:
                // ServiceUUID(UUID.fromString("0000180F-0000-1000-8000-00805F9B34FB"))
                // Name("MyDevice")
                ManufacturerData(BleRepo.HAGLEITNER_MANUFACTURER_ID)
            }
            .onEach { scanResult ->
                val p = scanResult.peripheral
                val id = p.identifier
                if (seenIds.add(id)) {
                    Timber.i("BLE NEW: name='${p.name ?: "<unknown>"}' id='$id' rssi=${scanResult.rssi}")
                    _devices.value = _devices.value + UiDevice(id, p.name, scanResult.rssi)
                } else {
                    _devices.value = _devices.value.map {
                        if (it.id == id) it.copy(name = p.name ?: it.name, rssi = scanResult.rssi) else it
                    }
                }
            }
            .launchIn(viewModelScope)
    }

    fun stopNordicBleScan() {
        scanJob?.cancel()
        scanJob = null
        Timber.i("BLE: scan cancelled")
    }

    override fun onCleared() {
        super.onCleared()
        stopNordicBleScan()
    }

Just a quick example, not the best, but working one.

Btw., how do I set the scan priority SCAN_MODE_LOW_LATENCY?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions