BleConnection

class BleConnection(context: Context, device: BluetoothDevice, bondManager: BondManager? = null, autoReconnect: Boolean = true, reconnectDelayMs: Long = ConnectionStateMachine.DEFAULT_RECONNECT_DELAY_MS, maxReconnectDelayMs: Long = ConnectionStateMachine.DEFAULT_MAX_RECONNECT_DELAY_MS, maxReconnectAttempts: Int = ConnectionStateMachine.DEFAULT_MAX_RECONNECT_ATTEMPTS)

Manages a Bluetooth Low Energy (BLE) connection to a remote device.

This class provides a high-level API for establishing and managing BLE connections, including reading and writing characteristics, enabling/disabling notifications, and handling device bonding. It wraps a ConnectionStateMachine to manage the underlying connection state and provides coroutine-based suspend functions for asynchronous BLE operations.

Usage Example

val connection = BleConnection(context, bluetoothDevice)
connection.connect()

// Observe connection state
connection.connectionStateFlow.collect { state ->
when (state) {
ConnectionState.Connected -> println("Connected!")
ConnectionState.Disconnected -> println("Disconnected")
// Handle other states...
}
}

// Read a characteristic
val value = connection.readCharacteristic(serviceUuid, characteristicUuid)

// Don't forget to close when done
connection.close()

Parameters

context

The Android Context used for BLE operations. An application context is recommended to avoid memory leaks.

device

The BluetoothDevice to connect to.

bondManager

Optional BondManager for handling device bonding operations. If null, bond will return an empty flow.

autoReconnect

Whether to automatically attempt reconnection when the connection is lost unexpectedly. Defaults to true.

reconnectDelayMs

Base delay in milliseconds for exponential backoff reconnection. The actual delay increases exponentially with each attempt. Defaults to ConnectionStateMachine.DEFAULT_RECONNECT_DELAY_MS.

maxReconnectDelayMs

Maximum delay in milliseconds between reconnection attempts. The exponential backoff will be capped at this value. Defaults to ConnectionStateMachine.DEFAULT_MAX_RECONNECT_DELAY_MS.

maxReconnectAttempts

Maximum number of reconnection attempts before giving up. When this limit is reached, the state transitions to ConnectionState.Error. Defaults to ConnectionStateMachine.DEFAULT_MAX_RECONNECT_ATTEMPTS.

See also

Constructors

Link copied to clipboard
constructor(context: Context, device: BluetoothDevice, bondManager: BondManager? = null, autoReconnect: Boolean = true, reconnectDelayMs: Long = ConnectionStateMachine.DEFAULT_RECONNECT_DELAY_MS, maxReconnectDelayMs: Long = ConnectionStateMachine.DEFAULT_MAX_RECONNECT_DELAY_MS, maxReconnectAttempts: Int = ConnectionStateMachine.DEFAULT_MAX_RECONNECT_ATTEMPTS)

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard

A StateFlow that emits the current connection state of the BLE device.

Functions

Link copied to clipboard

Binds this BleConnection to a LifecycleOwner for automatic lifecycle management.

Link copied to clipboard
fun bond(): Flow<BondState>

Initiates the bonding (pairing) process with the BLE device.

Link copied to clipboard

Clears the service cache for this device.

Link copied to clipboard
fun close()

Closes the BLE connection and releases all associated resources.

Link copied to clipboard
fun connect()

Initiates a connection to the BLE device.

Link copied to clipboard
fun disableNotifications(serviceUuid: UUID, characteristicUuid: UUID)

Disables notifications for a characteristic.

Link copied to clipboard

Disconnects from the BLE device while keeping resources allocated.

Link copied to clipboard
fun enableNotifications(serviceUuid: UUID, characteristicUuid: UUID, callback: (ByteArray) -> Unit)

Enables notifications for a characteristic and registers a callback for received values.

Link copied to clipboard

Gets the list of discovered GATT services for this device.

Link copied to clipboard
suspend fun readCharacteristic(serviceUuid: UUID, characteristicUuid: UUID): ByteArray?

Reads the value of a characteristic from the connected BLE device.

Link copied to clipboard
suspend fun readCharacteristicResult(serviceUuid: UUID, characteristicUuid: UUID): BleResult<ByteArray>

Reads the value of a characteristic from the connected BLE device, returning a BleResult.

Link copied to clipboard

Resets the reconnect attempt counter to zero.

Link copied to clipboard
suspend fun writeCharacteristic(serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray): Boolean

Writes a value to a characteristic on the connected BLE device.

Link copied to clipboard
suspend fun writeCharacteristicResult(serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray): BleResult<Unit>

Writes a value to a characteristic on the connected BLE device, returning a BleResult.

Link copied to clipboard
suspend fun writeLongCharacteristic(serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray): Boolean

Writes a large value to a characteristic using sequential chunked writes.

Link copied to clipboard
suspend fun writeLongCharacteristicResult(serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray): BleResult<Unit>

Writes a large value to a characteristic using sequential chunked writes, returning a BleResult.