Skip to main content

Retrieve the Data

To set up the bracelet and the Android SDK here are the main steps to implement:

Retrieving the data is handled by the Data SDK: the module that downloads the bracelet's files, stores the raw data and calculates the summaries.

What are raw metrics and summaries?

The end-to-end set-up of an app is described in Recommended set-up.

Entry points​

After CorsanoSdk.initialize():

import com.corsano.sdk.data.DataSdk

val dataSdk = DataSdk.getInstance()
val manager = dataSdk.getManager() // repositories, listeners, exports, feature managers
val downloadManager = dataSdk.getDownloadManager() // automatic download

DataSdk.getInstance() throws IllegalStateException when the SDK is not initialized. Both managers are singletons that live as long as your app's process.

note

getSummaryManager() is deprecated. Use getManager(); it returns the same object.

The manager also gives the feature managers, each documented on its own page: getEcgManager() (ECG), getNibpCalibrationManager() (NIBP), getWearingOptimizationManager() (Wearing Optimization) and getSpotMeasurementManager() (SpO2 spot measurement).

What you get and where it arrives​

Your app does not download anything itself. Once a bracelet is subscribed for the automatic download, the SDK stores each kind of data and tells you through a listener on the manager. You then read the stored data from the repository.

DataNew raw data: listener, then repositoryDaily summary: listener, then repositoryDownloaded when
Heart rate, steps, SpO2, respiration, blood pressure (NIBP), battery, wearingmetricActivityUpdated, then metricActivityRepositoryheartRateSummaryUpdated, stepsSummaryUpdated, spo2SummaryUpdated, respirationSummaryUpdated, bloodPressureSummaryUpdated, then the repository of the same name (heartRateSummaryRepository, …)Always
TemperaturemetricTemperatureUpdated, then metricTemperatureRepositorytemperatureSummaryUpdated, then temperatureSummaryRepositoryAlways (it is part of the activity file)
HRV (RR intervals)metricHrvUpdated, then metricHrvRepositoryNoneAlways
SleepmetricSleepUpdated, then metricSleepRepositorysleepSummaryUpdated, then sleepSummaryRepository. See Sleep processing287-2B only
EmoGraphy (stress)No listener call (see the note under Raw metric updaters). Query metricEmographyRepositoryemographySummaryUpdated, then emographySummaryRepository287-2B, licence with PPG2
PPGmetricPpgUpdated, then metricPpgRepositoryNoneLicence with PPG
Raw temperature (heat flux)metricTemperatureRawUpdated, then metricTemperatureRawRepositoryNone287-2B, licence with raw temperature
PPG2, accelerometer, BioZ fileswiffFileUpdated, then rawFileRepository. See Raw File Transfer & ExportNone287-2B, licence with that raw data
ECG measurementecgWiffFileUpdated, then ecgRepository. See ECGNone287-2B, licence with ECG

"Licence with …" means that your licence key must include that raw data type, otherwise the SDK does not download the file. See The licence and raw data. Some raw data must also be switched on on the bracelet: see Enable raw streams and, for raw temperature, SDK logs.

Data events​

Do not poll the database. Subscribe to the updaters of the manager. Each is a ValueUpdated<T> with addListener and removeListener.

Example​

import com.corsano.sdk.data.external.realm.models.StepsSummaryModel
import com.corsano.sdk.data.summary.ValueUpdated

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

private val stepsSummaryListener = object : ValueUpdated.Listener<StepsSummaryModel> {
override fun onValueUpdated(model: StepsSummaryModel) {
// One call per day that was recalculated. model.serverDate is the day ("yyyy-MM-dd").
view?.findViewById<TextView>(R.id.action_result)?.text = model.toString()
}
}

override fun onStart() {
super.onStart()
manager.stepsSummaryUpdated.addListener(stepsSummaryListener)
}

override fun onStop() {
manager.stepsSummaryUpdated.removeListener(stepsSummaryListener)
super.onStop()
}
warning

Always remove your listener. The manager is a singleton that outlives your fragments and activities, so a listener left registered keeps them alive.

A listener only gets the changes that happen while it is registered. It does not get the current value when you add it: read that from the repository.

Which thread. With the default configuration every listener is called on the main thread. In detail:

  • metricActivityUpdated, metricHrvUpdated, metricPpgUpdated, metricSleepUpdated, metricTemperatureUpdated and metricTemperatureRawUpdated are called on the main thread.
  • The summary updaters except sleep, wiffFileUpdated, ecgWiffFileUpdated and databaseState are called on the callback scheduler (callbackScheduler in the configuration, the main thread by default).
  • sleepSummaryUpdated is called on the main thread when the automatic download processes the sleep, and in your own coroutine when you call processSleepIfNeeded() yourself.

Sample app: DataActivityFragment.kt for summary updaters, DataMeasurementFragment.kt for wiffFileUpdated, DataSleepFragment.kt for sleep processing.

Summary updaters​

Each delivers one summary: a day that was recalculated because new raw data arrived. The model you get is the one that was saved.

UpdaterDelivers
stepsSummaryUpdatedStepsSummaryModel
heartRateSummaryUpdatedHeartRateSummaryModel
respirationSummaryUpdatedRespirationSummaryModel
spo2SummaryUpdatedSpO2SummaryModel
temperatureSummaryUpdatedTemperatureSummaryModel
sleepSummaryUpdatedSleepSummaryModel
bloodPressureSummaryUpdatedMetricBloodPressureSummary
emographySummaryUpdatedEmographySummaryModel

Raw metric updaters​

These deliver a list of the records that were just stored. Records that the SDK dropped are not in the list (see Data flow).

UpdaterDelivers
metricActivityUpdatedList<MetricActivity>
metricHrvUpdatedList<MetricHrv>
metricPpgUpdatedList<MetricPpg>
metricSleepUpdatedList<MetricSleep>
metricTemperatureUpdatedList<MetricTemperature>
metricTemperatureRawUpdatedList<MetricTemperatureRaw>
metricEdaUpdatedList<MetricEmography>
note

The EmoGraphy updater is metricEdaUpdated, not metricEmographyUpdated: it does not follow the naming of its repository. In SDK 3.0.0 the automatic download stores the EmoGraphy records but does not call metricEdaUpdated. To be told about new EmoGraphy data, listen to emographySummaryUpdated, or query metricEmographyRepository after a download.

File updaters​

UpdaterDeliversFires when
wiffFileUpdatedRawFileChunkA new PPG2, accelerometer or BioZ .wiff file is ready to export. See Raw File Transfer & Export
ecgWiffFileUpdatedEcgMeasurementModelThe .wiff file of an ECG measurement is written. See ECG

Database state​

manager.databaseState is a ValueUpdated<DatabaseState>. See Storage.

Sleep processing​

note

Changed in 2.2.0: sleep is computed on the bracelet and downloaded, so there is no on-app processing event. manager.sleepProcessUpdater and the SleepProcessResult type were removed. The automatic download brings the sleep state up to date by itself: it calls manager.processSleepIfNeeded() after every download of the sleep file, so your app normally does not have to. To read the state of a day, call the suspend function manager.getSleepState(dayDate).

See Sleep processing, including the migration steps from 2.1.x.

Reading the database​

Repositories​

Raw metrics:

RepositoryModel
metricActivityRepositoryMetricActivity
metricPpgRepositoryMetricPpg
metricHrvRepositoryMetricHrv
metricSleepRepositoryMetricSleep
metricTemperatureRepositoryMetricTemperature
metricTemperatureRawRepositoryMetricTemperatureRaw
metricEmographyRepositoryMetricEmography

Summaries:

RepositoryModel
stepsSummaryRepositoryStepsSummaryModel
heartRateSummaryRepositoryHeartRateSummaryModel
respirationSummaryRepositoryRespirationSummaryModel
spo2SummaryRepositorySpO2SummaryModel
temperatureSummaryRepositoryTemperatureSummaryModel
sleepSummaryRepositorySleepSummaryModel
bloodPressureSummaryRepositoryMetricBloodPressureSummary
emographySummaryRepositoryEmographySummaryModel

Measurements and device state:

RepositoryContents
ecgRepositoryECG measurements. See ECG
nibpCalibrationRepositoryNIBP calibration sessions. See NIBP
spotMeasurementRepositorySpO2 spot measurements. See SpO2 spot measurement
woRepositoryWearing Optimization measurements. See Wearing Optimization
rawFileRepository.wiff files. See Raw File Transfer & Export
braceletInfoRepositoryBracelet information the SDK keeps for itself. It has no public function
localSettingRepositoryLocal settings the SDK keeps for itself. It has no public function; to read one setting use LocalSetting.load(key) (see Storage)

Get the repositories from the manager. Since 3.0.0 ecgRepository, nibpCalibrationRepository, spotMeasurementRepository and woRepository cannot be constructed by your app.

The full method list for each is documented with the models: see Raw data models and Summaries.

What applies to every repository call:

  • The result arrives in a callback, on the callback scheduler (the main thread by default). The database work itself runs on the SDK's data thread, so you can call from the main thread.
  • Timestamps are UTC milliseconds. A range includes both its start and its end.
  • Every model you get is a copy (since 3.0.0). Changing it does not change the database, and it is not updated when new data arrives: query again.
  • A read of a metric or a summary has no error callback. When there is no data you get an empty array or null. When the read fails, for example because the database cannot be opened (DatabaseState.Unreadable, see Storage), the SDK logs the failure and calls the result callback once with null (an empty list for an ECG list). A read that takes an onError reports the failure there. Before 3.0.0 such a read never called back.
  • metricPpgRepository, metricHrvRepository, metricSleepRepository and metricEmographyRepository return at most 50 000 rows per call, oldest first. Ask for a shorter range to get the rest.

Get raw metrics​

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

manager.metricActivityRepository.getByTimestampRange(startTimestamp, endTimestamp) { metrics ->
// metrics: Array<MetricActivity>?, ordered by timestamp
metrics?.forEach { Log.d("Corsano-SDK", it.toString()) }
}

Pass groupedBySeconds to get fixed-size time buckets instead of every sample. Each bucket is one model. Its values are the average of the samples in the bucket: values of 0 are left out, and where a quality is available the average is weighted by it. In MetricActivity the steps, energy_exp and activityCount are summed, and the activity type, the wearing state and the charging state are the most frequent value. In MetricSleep the sleep state is the most frequent one. The rules per field are in Grouping rows; some values changed in 3.0.0. A bucket without samples is not returned. The timestamp of a bucket is its start.

manager.metricActivityRepository.getByTimestampRange(
startTimestamp,
endTimestamp,
groupedBySeconds = 5 * 60
) { metrics ->
// one entry per 5-minute bucket
}

Supported on MetricActivityRepository, MetricTemperatureRepository, MetricSleepRepository, MetricHrvRepository and MetricPpgRepository. MetricEmographyRepository and MetricTemperatureRawRepository have no groupedBySeconds overload: they return the stored rows as they are.

warning

Only MetricActivityRepository reads groupedBySeconds as seconds. The other four repositories group the millisecond timestamps by the number you pass, so they read it as milliseconds. For 5-minute buckets on MetricTemperatureRepository, MetricSleepRepository, MetricHrvRepository or MetricPpgRepository, pass 5 * 60 * 1000. This is a known quirk that is kept as it is, so that existing apps keep getting the same result.

Get a summary​

The date is the local day, as yyyy-MM-dd. The result is null when there is no summary for that day.

manager.stepsSummaryRepository.getByDate("2021-11-10") { summary ->
Log.d("Corsano-SDK", "Steps: ${summary?.stepCount}")
}

Delete data​

The SDK never deletes stored data by itself. Raw metrics grow quickly, so delete them regularly.

warning

For metrics that feed a summary the calculation reads the whole day: MetricActivity (steps, heart rate, respiration, SpO2, blood pressure), MetricTemperature, MetricSleep (sleep) and MetricEmography (EmoGraphy). Keep the last 2 days so summaries stay correct in every case. PPG produces no summary and can be deleted at any time.

manager.metricActivityRepository.deleteByTimestampRange(startTimestamp, endTimestamp)
manager.metricActivityRepository.deleteAll()

manager.stepsSummaryRepository.deleteByDate("2021-11-10")
manager.stepsSummaryRepository.deleteByTimestampRange(startTimestamp, endTimestamp)
manager.stepsSummaryRepository.deleteAll()

Every delete function takes an optional onSuccess and an optional onError, both called on the callback scheduler. Summaries are much smaller than raw metrics, but clearing old ones still frees space. A worked example is dataCleanUp() in SampleApp.kt of the sample app.

Full data model description: Data Models.

Exporting data​

exportData writes the stored raw metrics to CSV files, puts them in one zip file (sdk-export-<date>.zip) and saves that file in a folder the user has granted access to.

fun exportData(
fileTypes: List<ExportType>,
context: Context,
documentFile: DocumentFile,
from: Long,
to: Long,
onDone: () -> Unit,
onError: (Throwable) -> Unit
)
ParameterTypeDescription
fileTypesList<ExportType>What to export: ACTIVITY, SLEEP, HRV, TEMPERATURE, TEMPERATURE_RAW. PPG exists in the enum but is not exported: it is skipped
contextContextAndroid context
documentFileDocumentFileDestination folder, obtained from the user via the system folder picker
from, toLongTime range in UTC milliseconds, both included
onDone() -> UnitCalled when the zip file is in the folder
onError(Throwable) -> UnitCalled when the export fails. Nothing is delivered then

A second overload takes groupedBySeconds: Int before the callbacks. It averages the exported rows the same way the repositories do, with the same seconds / milliseconds quirk: seconds for ACTIVITY, milliseconds for SLEEP, HRV and TEMPERATURE. TEMPERATURE_RAW is always exported row by row.

manager.exportData(
fileTypes = listOf(ExportType.ACTIVITY, ExportType.HRV),
context = requireContext(),
documentFile = pickedFolder,
from = startTimestamp,
to = endTimestamp,
onDone = { Log.d("Corsano-SDK", "Export finished") },
onError = { Log.e("Corsano-SDK", "Export failed: $it") }
)

What to expect:

  • The zip holds one CSV file per type you asked for, each with a header row, also when the range holds no rows: export-activity-raw-data.csv, export-sleep-raw-data.csv, export-hrv-raw-data.csv, export-temperature-raw-data.csv, export-extended-temperature-raw-data.csv.
  • onError is called when no supported type is in fileTypes (for example only PPG), when a CSV file cannot be written, or when the zip file cannot be copied to the folder.
  • The callbacks run on the callback scheduler.
  • Since 3.0.0 a data export and a log export can run at the same time. Before, a log export started alongside could make the data export fail with FileNotFoundException.

For exporting the raw .wiff files rather than CSV, see Raw File Transfer & Export.

Data flow​

Once a bracelet is subscribed for the automatic file transfer, each cycle runs as follows:

BleDevice → File Transfer → Raw Metric → Erase → Summary + Slots

  • File Transfer: the SDK asks the bracelet for the size of each file and, if it is above zero, downloads the file in rounds. A round is a number of whole records (for example up to 2 000 activity records) or, for a raw file, 20 KB to 50 KB depending on the file and the Android version.
  • Raw Metric: each round is mapped to the matching metric objects and saved. Once saved, the records are given to the metric<Type>Updated listener and can be read through the metric<Type>Repository.
  • Erase: the round is deleted from the bracelet with EraseFileRequest, to free space for new measurements. Since 3.0.0 this happens only after the SDK has stored the round. A round that cannot be stored stays on the bracelet for the next download.
  • Summary + Slots: the SDK recalculates the summaries and slots affected by the new data, saves them, then calls the <type>SummaryUpdated listeners.

You do not drive this loop yourself. Your app subscribes the bracelet, then reacts to the events and reads the database.

Since 3.0.0 the SDK drops a record whose time is not plausible: before 2021-01-01, or more than 10 minutes after the phone's clock. Such a record is not stored, not given to a listener and not counted in a summary. This removes samples dated 2020-01-01 (a bracelet whose clock was never set) and samples dated years ahead.

note

Since 2.3.0: the Data SDK also sends a usage report for the connected bracelet to the Corsano cloud every 12 hours. See SDK usage report for what it contains.

Storage​

Since 3.0.0 the Data SDK stores its data in a Room database of its own (corsano-sdk-local.db). The database is internal to the SDK: read and delete through the repositories. RealmDatabase and Manager.realmDatabase of SDK 2.x are removed, with no replacement.

The database is plain SQLite unless you pass a databaseOpenHelperFactory in DataSdk.Config, for example SQLCipher's with a key of your own. The SDK holds no key. See Migrating to 3.0, Encrypting the database before you switch it on.

Manager.databaseState reports where the database stands, and Manager.currentDatabaseState gives the latest state:

DatabaseStateMeaningRepository calls
OpeningThe database is being openedWait, then answer
Importing(file, table, rowsDone, rowsTotal)The data of SDK 2.x is being importedWait, then answer with the imported data
ReadyThe database is open. Nothing to import, or importedAnswer
ImportFailed(file, attempt, reason, keptAs)The data of SDK 2.x could not be imported this time. The old file is kept and tried again at the next start. After the third failed attempt it is set aside under the name in keptAsAnswer
LegacyFileWithoutImporter(file)A file of SDK 2.x exists, but your app left out the importerAnswer
Unreadable(cause)The database file cannot be opened, for example with a wrong key. The file is kept, never deletedFail
import com.corsano.sdk.data.DatabaseState

val databaseListener = object : ValueUpdated.Listener<DatabaseState> {
override fun onValueUpdated(model: DatabaseState) {
if (model is DatabaseState.Importing) showUpdating() else hideUpdating()
}
}
manager.databaseState.addListener(databaseListener)
val now = manager.currentDatabaseState // the listener only gets the changes

On the first start after an upgrade from SDK 2.x the SDK imports the data of 2.x once, in the background. Your app calls nothing for it. What happens to the data, how to check the import (getLegacyImportReport(), exportLegacyRealmFile(directory)) and how to leave the importer out of a new app are described in Migrating to 3.0.

Two classes that read the database changed with it:

  • LocalSetting(realm, key) is replaced by LocalSetting.load(key, result = { setting -> }) or the suspend LocalSetting.load(key).
  • SleepSettings(realm) is replaced by SleepSettings.load(result = { settings -> }) or the suspend SleepSettings.load().

Pass the result callback by name, as shown: the last parameter of both functions is the optional onError, so a trailing lambda would be taken as onError.

Both answer on the callback scheduler, and throw IllegalStateException when the SDK is not initialized.

Configuration​

DataSdk.Config is the configuration of the Data SDK. You add it to CorsanoSdkConfig before CorsanoSdk.initialize(). All parameters have a default except licenceKey, which is mandatory. Use named arguments.

ParameterTypeDefaultUnitDescription
licenceKeyString?nullMandatory. When it is null, CorsanoSdk.initialize() throws IllegalArgumentException. See Licence Key
slotsIntervalSecsInt60secondsSlot interval of the summaries. Minimum 60
nibpSlotsIntervalSecsInt7 200 (2 h)secondsSlot interval of the blood pressure summaries. Minimum 1 800 (30 minutes)
ppg2ThresholdFileSizeInt500 * 1024bytesSize the downloaded PPG2 data must reach before a .wiff file is produced
bioZThresholdFileSizeInt30 * 1024bytesSame, for BioZ
accThresholdFileSizeInt30 * 1024bytesSame, for accelerometer
automaticReconnectIfNeededIntervalMinutesInt15minutesHow often the SDK tries a background reconnect. Minimum 15
loggerSdkLogger?nullLogger of the Data SDK. null: the one of CorsanoSdkConfig (by default SdkLogger.LogCat())
dataScheduler, callbackSchedulerScheduler?nullThread of the database work, and thread of the callbacks. null: the ones of CorsanoSdkConfig (by default a thread of the SDK's own, and the main thread, Scheduler.MAIN)
databaseOpenHelperFactorySupportSQLiteOpenHelper.Factory?nullSince 3.0.0. Opens the SDK's database. null: plain SQLite. See Storage
licenceListenerLicenceListener?nullSince 3.0.0. Told when a licence check locks or unlocks the SDK. See Licence Key

slotsIntervalSecs​

The interval of slots in the summary generation, in seconds. With a 60-second interval the summary slots run 00:00, 00:01, 00:02 and so on.

note

The minimum value is 60 seconds. A lower value is raised to 60, and the SDK logs a warning.

Summaries are meant to be daily aggregates, not a second copy of the raw metrics: a short interval makes the database larger to no benefit.

File size thresholds​

ppg2ThresholdFileSize, bioZThresholdFileSize and accThresholdFileSize each set the size, in bytes, that the downloaded data must reach before a .wiff file is produced. The data is downloaded from the bracelet continuously, but a file only appears, and wiffFileUpdated only fires, once the data waiting on the phone is at least as large as the threshold. This avoids a large number of tiny files, at the cost of waiting for data to build up.

Set a threshold to zero for continuous generation: a file is then produced after every download that brought data.

nibpSlotsIntervalSecs​

The slot interval for blood pressure summaries, in seconds. It is separate from slotsIntervalSecs and defaults to 2 hours (7 200). A value below 30 minutes (1 800) is not accepted: the SDK then uses the default of 2 hours and logs a warning.

automaticReconnectIfNeededIntervalMinutes​

How often, in minutes, a background worker looks at the bracelet that is subscribed for the automatic download and, when it is not connected, connects to it (with keepAlive = true). Values below 15 minutes are raised to 15, which is the Android WorkManager minimum for periodic work.

Set it to Int.MAX_VALUE to cancel the periodic reconnect worker entirely.

Code example​

import com.corsano.sdk.CorsanoSdk
import com.corsano.sdk.CorsanoSdkConfig
import com.corsano.sdk.data.DataSdk

val dataConfig = DataSdk.Config(
licenceKey = "my_key", // your licence key; if you need one, see https://corsano.com/contact-us/
slotsIntervalSecs = 10 * 60,
ppg2ThresholdFileSize = 500 * 1024,
bioZThresholdFileSize = 30 * 1024,
accThresholdFileSize = 30 * 1024
)

val config = CorsanoSdkConfig.Builder()
.addModuleConfig(dataConfig)
.build()

CorsanoSdk.initialize(this, config) // in Application.onCreate()

databaseOpenHelperFactory and licenceListener are passed the same way; see Migrating to 3.0, Encrypting the database and Licence Key for complete examples.

Other manager methods​

getBraceletCapacity​

fun getBraceletCapacity(
bleDevice: BleDevice,
hardwareId: HardwareId,
onDone: (Double) -> Unit,
onError: (Throwable) -> Unit
)

How full the bracelet's storage is, as a percentage from 0 to 100. Useful for warning a user before measurements are lost. The SDK asks the connected bracelet for the size of each of its files, so the bracelet must be connected and initialized; onError is called when one of these commands fails. The callbacks run on the main thread. A suspend variant, getBraceletCapacitySuspend(bleDevice, hardwareId), returns a Result<Double>.

getLogs​

fun getLogs(context: Context, documentFile: DocumentFile)

Writes the SDK logs as a zip file to the given folder, for support purposes. See SDK logs.

Controlling downloads​

DataSdk.getInstance().getDownloadManager() controls the automatic download. Day-to-day set-up is covered in Data transfer; the full surface is:

MethodPurpose
subscribeDeviceForDownload(address, hardwareId, plan, onSuccess, onError)Subscribe a bracelet for the automatic download. It replaces the bracelet that was subscribed before
unsubscribeDeviceForDownload(address, onSuccess, onError)Stop the automatic download for a bracelet
triggerDownload(address, hardwareId, plan, filteredFiles)Run one download now. filteredFiles is optional: the files to leave out
startContinuousDownload()Start listening to the bracelet's pings. subscribeDeviceForDownload and the start of the app call it for you
stopContinuousDownload()Stop listening to the bracelet's pings. The subscription is kept
stopAll(context, address, onSuccess, onError)Cancel a running download, stop listening and unsubscribe. Use it when you unpair
getDownloadClient(address, hardwareId, plan)The DeviceDownloadClient of a bracelet, for finer control
getProgressLiveData()LiveData<List<WorkInfo>> of the download job
parseProgressLiveData(listOfWorkInfo)Turns that into a DownloadProgress?
note

The three-argument stopAll(address, onSuccess, onError) is deprecated: it does not cancel a download that is running. Use the overload that takes a Context.

DeviceDownloadClient runs a download directly, without the background job: start(filteredFiles) and cancel(), the properties isInProgress and lastDownloadRequestTimestamp, and the listeners DownloadProgressListener (onDownloadProgress(address, percentage, currentStep)) and DownloadCompletionListener (onDownloadFinished(address, error), error is null on success). The bracelet must already be connected and initialized. Prefer triggerDownload, which connects and initializes the bracelet first.