Skip to main content

BLE SDK

Core module that provides the low-level API for connecting to Corsano bracelets, performing commands on the bracelet, and getting raw data.

Most apps use this module for three things: pairing and connecting, sending a few commands (user profile, battery), and listening to notifications. The download of the measured data is done for you by the automatic data transfer of the Data SDK.

Main interfaces​

The main entry point of the BLE SDK is BleSdk. Get its instance with BleSdk.getInstance(). This method always returns the same (singleton) instance, so it is safe to keep a reference to it in the scope of your app.

note

Call CorsanoSdk.initialize() first, see Getting Started. Before that, BleSdk.getInstance() throws IllegalStateException.

BleSdk gives access to the other interfaces listed in the table below.

InterfaceDescriptionHow to obtain
BleScannerLooks for Corsano bracelets with the Android BLE scanner.BleSdk.getInstance().getScanner()
BleDeviceRepresents one physical bracelet and provides the methods to interact with it.BleSdk.getInstance().getDevice(address)
BleRequestDescribes what to ask the bracelet: a command ID and its parameters.Create using public constructor, e.g. GetBatteryLevelRequest()
BleCommandA request that can be sent to one bracelet, once.BleDevice.newCommand(request)
BleFileTransferSpecial type of BleCommand that reads a file from the bracelet.BleDevice.newFileTransfer(request)
NotificationSourceInterface for listening to notifications from the bracelet.BleDevice.notifications
BluetoothBluetooth state of the phone and bond state of a device.BleSdk.getInstance().getBluetooth()

BleSdk also exposes getBpCuffDevice(address) for an external blood pressure cuff (see NIBP), getRecentDevices() for the bracelets used before, and removeDevice(address) to unpair (see Pairing).

note

getWatch() and removeWatch() are deprecated in favour of getDevice() and removeDevice().

Executing commands​

Every interaction with the bracelet follows the same shape: you build a request, turn it into a command on a device, and enqueue it.

BleDevice
.newCommand(BleCommandRequest<T>) -> BleCommand<T>
.newFileTransfer(FileTransferRequest<T>) -> BleFileTransfer<T>

You rarely call newCommand directly. The extension functions below wrap it. The list of requests is on BLE commands.

Before a command can run, three things must be true. The queue checks them in this order:

ConditionIf it is not met
1. The bracelet is connected (connectionState == CONNECTED)The command waits in the queue.
2. The bracelet is bonded (bondState == BONDED)The command waits in the queue.
3. The bracelet is initialized (isInitialized == true)The command fails at once with NotInitializedException. See Bracelet Initialization.

A new connection is never initialized yet. So a command that waited for the connection fails with NotInitializedException as soon as the bracelet is connected, unless it is one of the few requests that do not need initialization. Send your commands after ensureInitialized has succeeded:

val manager = DataSdk.getInstance().getManager()

manager.ensureInitialized(bleDevice).onSuccess {
// connected, bonded and initialized: commands run now
}

Callback style​

enqueueCommand for a single value, enqueueFileTransfer for a file, which additionally reports progress:

import com.corsano.sdk.ble.command.enqueueCommand

val bleDevice = BleSdk.getInstance().getDevice(address)

bleDevice.enqueueCommand(
request = GetBatteryLevelRequest(),
onSuccess = { level -> Log.d("Corsano-SDK", "Battery: $level") },
onError = { error -> Log.e("Corsano-SDK", "Failed: $error") }
)
import com.corsano.sdk.ble.command.enqueueFileTransfer

bleDevice.enqueueFileTransfer(
request = ActivityFileTransferRequest(sizeInBytes),
onSuccess = { data -> Log.d("Corsano-SDK", "Got ${data.items.size} records") },
onError = { error -> Log.e("Corsano-SDK", "Failed: $error") },
onProgress = { progress -> Log.d("Corsano-SDK", "Progress: ${progress.percentage} %") }
)
  • onSuccess, onError and onProgress run on the SDK's callback scheduler. This is the main thread unless you set another one with CorsanoSdkConfig.Builder().callbackScheduler(...).
  • One of onSuccess and onError is called for every command, unless you cancel it.
  • Both functions return the BleCommand, which you need if you want to cancel.
  • enqueueCommand(request, delayMs, onSuccess, onError) puts the command in the queue after delayMs milliseconds.
  • onProgress receives a TransferProgress(downloaded, total) in bytes; percentage is 0 to 100.

If your app uses coroutines, prefer awaitCommandV2 and awaitFileTransferV2 from com.corsano.sdk.data.util. They return a Result<T> rather than throwing, and accept an optional timeout in milliseconds.

import com.corsano.sdk.data.util.awaitCommandV2

val result: Result<BatteryLevel> = bleDevice.awaitCommandV2(
request = GetBatteryLevelRequest(),
timeout = 10_000
)

result
.onSuccess { level -> Log.d("Corsano-SDK", "Battery: $level") }
.onFailure { error -> Log.e("Corsano-SDK", "Failed: $error") }

Always pass a timeout. The default is no timeout, and a command for a bracelet that is not connected waits in the queue, so without a timeout the call can suspend until the bracelet is back. When the timeout ends, the Result is a failure with a TimeoutCancellationException, and a command that was still waiting is not sent.

warning

The earlier awaitCommand and awaitFileTransfer are deprecated. They throw instead of returning a Result, so they can crash your app if the bracelet disconnects during a command. Use the V2 variants.

These helpers are in the data module (com.corsano.sdk:data). From SDK 3.0.0 every app needs that module, also an app that uses only ble: without it the SDK is locked with LicenceError.NoLicenceKey. See Licence Key.

The command queue​

From SDK 3.0.0 each bracelet has its own queue. A command for one bracelet does not wait for a command or a file transfer of another bracelet.

  • One bracelet runs one command or one file transfer at a time. The others wait in the order below.
  • enqueueCommand puts a command at the end of the queue.
  • awaitCommandV2, and BleCommand.enqueue(callback, isHighPriority = true), put a command before the commands of normal priority and after the high-priority commands that already wait. So two awaited commands keep their order.
  • A file transfer always has normal priority.
  • When the link to the bracelet is lost, the command that is running fails with "Watch disconnected". The commands that are still waiting stay in the queue until the bracelet is connected again. Then the three conditions above are checked again, so a waiting command that needs initialization fails with NotInitializedException.
  • When you call BleDevice.disconnect(), the running command and all waiting commands of that bracelet fail with "Watch disconnected".

Timeouts​

The SDK gives every step of an exchange a time limit:

ExchangeTime limit per stepSteps
Command15 secondsThe write, then the bracelet's reply
File transfer of records (activity, HRV, EmoGraphy, raw temperature, workout, sleep, logs, PPG)60 secondsThe file size, the start, then each block of data
File transfer of a raw file (Ppg2FileTransferRequest, AccFileTransferRequest, BiozFileTransferRequest, EcgFileTransferRequest)30 secondsThe same

The time limit starts when the step starts, not when you enqueue. The time a command waits in the queue is not limited by the SDK.

When a step takes too long:

  1. The command fails with java.util.concurrent.TimeoutException.
  2. The SDK takes it as a sign that the link no longer answers. It disconnects the bracelet and connects again (with keepAlive = true).
  3. The other commands that waited for this bracelet fail with "Watch disconnected".

GetNibpTrainingInfoRequest is the exception: when it gets no reply (a firmware without this command), it fails with its timeout and the connection is kept.

Cancelling a command​

BleCommand.cancel() withdraws a command. After cancel() none of its callbacks is called, and isCanceled() returns true. A command that was still waiting is not sent.

A BleCommand object can be enqueued once. enqueue throws IllegalStateException when the command was already enqueued or was cancelled. From SDK 3.0.0 this is also true for a BleFileTransfer: a cancelled transfer stays cancelled.

With the coroutine functions (await, awaitCommandV2, awaitFileTransferV2), from SDK 3.0.0:

  • When the coroutine is cancelled, the command is not withdrawn. The bracelet may already be acting on it, so the command is still sent. Only your coroutine stops waiting.
  • When the timeout of the function ends, the command is withdrawn.

File transfers​

A file transfer reads a file of the bracelet into memory and decodes it. In normal use you do not send file transfers yourself: the automatic data transfer reads, stores and erases the files for you. If you do send one:

  1. Read the size with GetFileSizeRequest(file).
  2. Pass the number of bytes you want to the transfer request. The SDK never asks for more than the file holds, and asks for whole records only.
  3. A transfer does not erase anything. Erase what you have stored with EraseFileRequest.

A file that holds less than one record gives an empty result (from SDK 3.0.0; before, the transfer never answered).

The requests and their result types are listed in BLE commands.

Listening to notifications​

The bracelet pushes notifications without being asked. Observe them all, or filter by type:

import com.corsano.sdk.ble.command.observeNotifications
import com.corsano.sdk.ble.command.observeNotificationsOfType

// everything
val listener = bleDevice.observeNotifications { notification ->
Log.d("Corsano-SDK", "Notification: $notification")
}

// just one type
bleDevice.observeNotificationsOfType<Notification.RealTimePing> { ping ->
Log.d("Corsano-SDK", "Live heart rate: ${ping.hrm}")
}

Both return the underlying NotificationSource.NotificationListener, which you pass to bleDevice.notifications.removeNotificationListener(listener) when you are done. The listener is called on the callback scheduler (the main thread by default).

With coroutines and the data module, bleDevice.notificationFlow() (com.corsano.sdk.data.util) gives the same notifications as a Flow.

Notification is a sealed class with four cases: RegularPing, RealTimePing, LiveHrm and ChargingEventPing. They are described in Instant data.

Errors​

Commands fail through onError (callback style) or a failed Result (coroutine style). A command never reports a failure as false or null.

ErrorMeaningWhat to do
NotInitializedExceptionThe bracelet is connected but not initialized on this connection.Initialize it, see Bracelet Initialization
PairingRequiredExceptionThe bracelet answered that it is not bonded with this phone.Pair it again, see Pairing
InvalidCommandResponseExceptionThe bracelet's reply is shorter than expected or holds a value the SDK does not know.The reply cannot be used. If it happens every time, send the SDK logs to Corsano
CommandResponseValidationExceptionThe reply failed its checksum, or a value is out of range (a battery level above 100).Send the command again
SdkLicenceExceptionThe SDK is locked by its licence check (from SDK 3.0.0). Sending again does not help.See Licence Key
java.util.concurrent.TimeoutExceptionThe bracelet did not answer in time. The SDK reconnects, see Timeouts.Send the command again when the bracelet is connected
RuntimeException with the message "Watch disconnected"The bracelet disconnected, or disconnect() was called, before the command got its answer.Send the command again when the bracelet is connected
RuntimeException with a message that starts with "BLE write failed"Android could not write the command to the bracelet.Send the command again
TimeoutCancellationExceptionThe timeout you passed to awaitCommandV2 or awaitFileTransferV2 ended.Check the connection state, then send again

The first four are in com.corsano.sdk.ble.exceptions. SdkLicenceException is in com.corsano.sdk.licence.

Enums that grow​

New SDK versions add values to CommandId and FileOnWatch, and may add cases to Notification. SDK 3.0.0 added values to CommandId and FileOnWatch.NIBP. A Kotlin when over one of them without an else branch stops compiling when a value is added, so add an else branch.