Recommended set-up
This page shows the whole flow of an app that uses the Corsano SDK, in the order the calls are made, with the minimum of code for each step. Each step links to the page that describes it in full. The sample app follows the same flow.
It assumes the usual integration: the ble, data and dfu modules, one bracelet per phone, a
phone that is online at least every two days, and the SDK downloading the data automatically.
The flow at a glance
| When | Step | SDK call |
|---|---|---|
| Every start of the app's process | 1. Initialize the SDK | CorsanoSdk.initialize, enableAutoInitialization |
| Once per bracelet | 2. Pair the bracelet | BleScanner.startScan, startScanForPusherEvent, BleDevice.connect(keepAlive = true) |
| Every connection | 3. Wait until the bracelet is initialized | Manager.ensureInitialized |
| Once per bracelet, and when it changes | 4. Set the wearer's profile | SetUserProfileRequest and the other profile commands |
| Once per bracelet, and after an update of your app | 5. Check the firmware | CorsanoDfu.needDfu, startDfu |
| Once per wearer, and when the SDK asks for it | 6. Run the wearing optimization | CorsanoWearingOptimizationFragment or WearingOptimizationManager |
| Once per bracelet | 7. Start the automatic download | DataDownloadManager.subscribeDeviceForDownload |
| While your app runs | 8. Receive and read the data | Manager.*Updated listeners, then the repositories |
| Regularly | 9. Upload and clean up | the repositories' deleteByTimestampRange |
| Every later start of the app | 10. Reconnect | BleSdk.getDevice(address).connect(keepAlive = true) |
| When the wearer stops | 11. Unpair | DataDownloadManager.stopAll, BleSdk.removeDevice |
Three rules cause most support questions. Keep them in mind:
- Initialize the SDK in
Application.onCreate(), never in an Activity. The SDK's background work can start your process without any screen. - A bracelet accepts commands only after it is initialized on the current connection. Before
that every command fails with
NotInitializedException. Enable the automatic initialization and wait for it withensureInitialized. - You do not download data yourself. You subscribe the bracelet once; the SDK downloads, stores and computes; you listen for updates and read from the repositories.
1. Initialize the SDK
In Application.onCreate(): the licence key, a licence listener, and the automatic bracelet
initialization with the plan and the sampling rates agreed for your project.
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
val dataConfig = DataSdk.Config(
licenceKey = "my_key",
licenceListener = myLicenceListener,
)
val config = CorsanoSdkConfig.Builder()
.addModuleConfig(dataConfig)
.addModuleConfig(CorsanoDfu.Config(notificationTarget = MainActivity::class.java))
.build()
CorsanoSdk.initialize(this, config)
DataSdk.getInstance().getManager().enableAutoInitialization(
InitializationConfig(
braceletPlan = DevicePlan.CONTINUOUS_GREEN_INTERMITTENT_MULTICOLOR,
samplingRate = SampleRate.ONE_MIN,
)
)
}
}
Full description: Getting Started. The plan and the rates: Bracelet plans. What your app must do when the licence locks the SDK: Licence Key.
2. Pair the bracelet
Do this once per bracelet, from a screen of your app.
- Check that Bluetooth is on (
BluetoothUtil.isBluetoothEnabled()). - Ask the user for the permissions
BleScanner.getMissingPermissions()returns. - Scan with
startScanand let the user choose a bracelet. - Scan for that bracelet with
startScanForPusherEvent(address)until the user confirms on the bracelet (287-2B: put it on the charger and take it off). - Ask for the permissions
BleDevice.getMissingConnectPermissions()returns, then connect:
val device = BleSdk.getInstance().getDevice(address)
device.connect(keepAlive = true)
connect returns at once. With keepAlive = true the SDK creates the bond during the first
connection and brings the connection back whenever it is lost. Store the bracelet's address in
your app: you need it at every start (step 10).
On Android 13 and later, also ask for the notification permission (POST_NOTIFICATIONS): the
download, the SDK's background reconnection and the firmware update show a notification while
they run.
Full description: Pairing.
3. Wait until the bracelet is initialized
After every connection the SDK initializes the bracelet by itself (step 1 enabled this): it authenticates, sets the time, the plan and the sampling rates. Before you send a command of your own, wait for it:
val manager = DataSdk.getInstance().getManager()
val connectionListener = object : BleDevice.DeviceConnectionStateListener {
override fun onWatchConnectionStateChanged(state: ConnectionState) {
if (state == ConnectionState.CONNECTED) {
scope.launch {
val initialized = manager.ensureInitialized(device)
if (initialized.isSuccess) {
// The bracelet accepts commands now.
val hardwareId = device.awaitCommandV2(GetHwIdRequest()).getOrNull()
val firmware = device.awaitCommandV2(GetFwVersionRequest()).getOrNull()
}
}
}
}
}
device.addConnectionStateListener(connectionListener)
ensureInitialized does not start a second initialization: it joins the one that is running, or
returns at once when the bracelet is already initialized. If it returns a failure (for example
because the user was slow to confirm the pairing), call it again. Keep the hardware id and the
firmware version; the next steps need them.
Full description: Bracelet Initialization. Sending commands: BLE SDK and Bracelet commands.
4. Set the wearer's profile
Send the wearer's profile (birthday, gender, wrist, skin type), height and weight, and the bedtime and rise time once after pairing, and again when one of them changes. The bracelet's algorithms use them.
Full description: Set up the bracelet.
5. Check the firmware
val dfu = CorsanoDfu.getInstance()
if (hardwareId != null && firmware != null && dfu.needDfu(hardwareId.value, firmware)) {
// Ask the user to keep the bracelet close and charged, then:
dfu.startDfu(device.address, hardwareId.value)
}
needDfu answers true when the bracelet's firmware is older than the default firmware of the
SDK version in your app. Add a DfuListener to follow the update. Do this check after pairing and
after each update of your app, since a new SDK version can bring a new default firmware.
Before you update bracelets in the field, read DFU SDK: it lists the firmware versions, says which updates cannot be undone, and how to keep a group of bracelets on a version you validated.
6. Run the wearing optimization
The wearing optimization checks that the bracelet sits well on the wrist and gives its signal
quality. Run it when a wearer starts, and again when the SDK reports that a redo is needed. Use
the ready-made screen of the ui module, or WearingOptimizationManager with a screen of your own.
Full description, including how to read the result and the quality: Wearing optimization.
7. Start the automatic download
Subscribe the bracelet once. The SDK keeps the subscription across restarts of your app. It holds one subscription at a time.
DataSdk.getInstance().getDownloadManager().subscribeDeviceForDownload(
address = device.address,
hardwareId = hardwareId,
plan = DevicePlan.CONTINUOUS_GREEN_INTERMITTENT_MULTICOLOR,
onSuccess = { /* the automatic download is on */ },
onError = { error -> /* show or log it */ },
)
From then on the SDK downloads the bracelet's files when the bracelet announces new data, stores them, erases them from the bracelet and computes the daily summaries, also while your app is in the background.
Full description: Setup auto file transfer.
8. Receive and read the data
The SDK tells you when new data is stored. Add a listener for each kind of data you use, then read from the repository:
val manager = DataSdk.getInstance().getManager()
val heartRateListener = object : ValueUpdated.Listener<HeartRateSummaryModel> {
override fun onValueUpdated(model: HeartRateSummaryModel) {
// The summary of one day was recalculated: model is that day.
}
}
manager.heartRateSummaryUpdated.addListener(heartRateListener)
// when you no longer need it
manager.heartRateSummaryUpdated.removeListener(heartRateListener)
// The stored data, at any time:
manager.metricActivityRepository.getByTimestampRange(startTimestamp, endTimestamp) { metrics ->
// raw records, oldest first
}
A listener only gets the changes that happen while it is registered, so read the repository once when your screen opens, then update from the listener.
- Which listener and which repository for which data: Data SDK.
- Every field with its unit and meaning: Data Models.
- Live values (heart rate, battery, wearing state) without waiting for a download: Instant data.
9. Upload and clean up
The SDK keeps the health data on the phone: uploading it to your backend is your app's job. (The SDK itself only sends Corsano a usage report without health measurements.) The SDK also never deletes stored data by itself, and raw metrics grow quickly. So, regularly:
- read the new data from the repositories and upload it;
- delete what you no longer need with
deleteByTimestampRange. Keep the raw metrics of the last two days, because the summaries of a day are calculated from them.
dataCleanUp() in SampleApp.kt of the sample app is a worked example. Full description:
Data SDK, Delete data.
10. Reconnect at the next start
When your app starts again and a bracelet is already paired, no scan is needed. After
CorsanoSdk.initialize (step 1), connect with the stored address:
val device = BleSdk.getInstance().getDevice(storedAddress)
if (device.getMissingConnectPermissions().isEmpty()) {
device.connect(keepAlive = true)
}
The automatic initialization and the automatic download start again by themselves.
11. Unpair
When the wearer stops using the bracelet, or before pairing another one:
DataSdk.getInstance().getDownloadManager().stopAll(
context,
address = address,
onSuccess = { },
onError = { },
)
BleSdk.getInstance().removeDevice(address, removeFromRecents = true)
Upload the data you still need first. Full description: Pairing, Unpair.
Things to handle in every app
| Situation | What to do | Page |
|---|---|---|
The licence locks the SDK (LicenceListener.onLicenceLocked) | Tell the user what to do for that reason, for example to go online after two days without a connection (NotConfirmed); calls fail with SdkLicenceException until a check unlocks it | Licence Key |
| Bluetooth is off, or a permission was revoked | Check before every scan and connect; the user can revoke a permission at any time | Pairing |
A command fails with NotInitializedException | Wait with ensureInitialized before you send commands | Bracelet Initialization |
| The bracelet's battery is low or it is on the charger | Show it to the wearer | Instant data |
| An upgrade from SDK 2.x imports the old data | Optional: show progress from Manager.databaseState | Migrating to 3.0 |
| A support case | Export the SDK logs and send them to Corsano | SDK logs |
| A bracelet behaves unexpectedly | Symptoms, causes and fixes | Troubleshooting |